plugin-agent-orchestrator 1.2.0 → 1.2.2

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 (223) 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 +80 -12
  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/ParallelInterruptActionsPatch.js +132 -0
  78. package/dist/server/services/PluginAiRuntimeAdapter.js +107 -9
  79. package/dist/server/services/RoutingBindingRepository.js +156 -0
  80. package/dist/server/services/RoutingBindingValidation.js +161 -0
  81. package/dist/server/services/SandboxRunner.js +19 -0
  82. package/dist/server/services/SessionAutoApproval.js +173 -0
  83. package/dist/server/services/VerificationService.js +2 -2
  84. package/dist/server/skill-hub/plugin.js +17 -0
  85. package/dist/server/skill-hub/services/RegistrySkillInstallationService.js +2 -2
  86. package/dist/server/skill-hub/services/registry-node-package.js +191 -0
  87. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +21 -6
  88. package/dist/server/tools/skill-execute.js +1 -0
  89. package/dist/server/utils/ensure-indexes.js +1 -0
  90. package/package.json +5 -2
  91. package/src/client/SkillPages.tsx +1 -8
  92. package/src/client/__tests__/embedded-settings.test.tsx +1 -8
  93. package/src/client/plugin.tsx +3 -8
  94. package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +21 -6
  95. package/src/client/skill-hub/tools/SkillHubCard.tsx +22 -16
  96. package/src/client/skill-hub/tools/__tests__/skill-hub-card.test.tsx +255 -0
  97. package/src/client/skill-hub/tools/registerSkillLoopCards.ts +12 -3
  98. package/src/client-v2/__tests__/embedded-settings.test.tsx +20 -11
  99. package/src/client-v2/__tests__/hierarchical-routing-settings.test.tsx +350 -0
  100. package/src/client-v2/auto-approval/AutoApprovalBridge.tsx +513 -0
  101. package/src/client-v2/auto-approval/AutoApprovalProvider.tsx +399 -0
  102. package/src/client-v2/auto-approval/__tests__/session-auto-approval.test.tsx +1676 -0
  103. package/src/client-v2/components/AgentBindingsTab.tsx +275 -3
  104. package/src/client-v2/components/AgentRunsTab.tsx +1 -8
  105. package/src/client-v2/components/EmployeeGovernanceTab.tsx +1 -8
  106. package/src/client-v2/components/HarnessProfilesTab.tsx +4 -8
  107. package/src/client-v2/components/HarnessSettingsForm.tsx +221 -0
  108. package/src/client-v2/components/UsageGovernanceTab.tsx +1 -8
  109. package/src/client-v2/pages/AgentBindingsPage.tsx +1 -8
  110. package/src/client-v2/pages/ApprovalsPage.tsx +1 -8
  111. package/src/client-v2/pages/EmployeeGovernancePage.tsx +1 -8
  112. package/src/client-v2/pages/ExecutionHistoryPage.tsx +1 -8
  113. package/src/client-v2/pages/HarnessProfilesPage.tsx +1 -8
  114. package/src/client-v2/pages/KnowledgeAccessPage.tsx +1 -8
  115. package/src/client-v2/pages/LoopSettingsPage.tsx +1 -8
  116. package/src/client-v2/pages/MemoryInspectorPage.tsx +1 -8
  117. package/src/client-v2/pages/RetrievalTracePage.tsx +1 -8
  118. package/src/client-v2/pages/RulesPage.tsx +1 -8
  119. package/src/client-v2/pages/SkillDefinitionsPage.tsx +1 -8
  120. package/src/client-v2/pages/SkillMetricsPage.tsx +1 -8
  121. package/src/client-v2/pages/TracingPage.tsx +1 -8
  122. package/src/client-v2/pages/UsageGovernancePage.tsx +1 -8
  123. package/src/client-v2/plugin.tsx +3 -8
  124. package/src/client-v2/skill-hub/tools/__tests__/interactions.test.ts +17 -1
  125. package/src/client-v2/skill-hub/tools/interactions.ts +12 -3
  126. package/src/locale/en-US.json +80 -1
  127. package/src/locale/vi-VN.json +5 -1
  128. package/src/locale/zh-CN.json +80 -1
  129. package/src/server/__tests__/agent-governance.integration.test.ts +1 -8
  130. package/src/server/__tests__/agent-monitor-acl.integration.test.ts +1 -8
  131. package/src/server/__tests__/agent-usage-report.integration.test.ts +1 -8
  132. package/src/server/__tests__/auto-approval-checkpoint.integration.test.ts +295 -0
  133. package/src/server/__tests__/harness-capabilities.test.ts +1 -8
  134. package/src/server/__tests__/harness-compiler.test.ts +64 -0
  135. package/src/server/__tests__/harness-tool-plan.test.ts +1 -8
  136. package/src/server/__tests__/hierarchical-routing.integration.test.ts +2318 -0
  137. package/src/server/__tests__/hierarchy-invocation-journal.integration.test.ts +119 -0
  138. package/src/server/__tests__/loop-approval-decision.test.ts +59 -12
  139. package/src/server/__tests__/loop-budget-service.test.ts +1 -8
  140. package/src/server/__tests__/loop-run-repository.test.ts +1 -8
  141. package/src/server/__tests__/loop-trigger-service.test.ts +1 -8
  142. package/src/server/__tests__/loop-worker-claim.test.ts +46 -9
  143. package/src/server/__tests__/loop-worker-execution.test.ts +1 -8
  144. package/src/server/__tests__/native-agent-monitor-sync.test.ts +1 -8
  145. package/src/server/__tests__/native-hierarchy-probe.integration.test.ts +527 -0
  146. package/src/server/__tests__/native-sub-agent-observer.test.ts +1 -8
  147. package/src/server/__tests__/native-usage-attribution.integration.test.ts +1 -8
  148. package/src/server/__tests__/parallel-interrupt-actions.test.ts +342 -0
  149. package/src/server/__tests__/plugin-ai-runtime-adapter.test.ts +403 -0
  150. package/src/server/__tests__/registry-node-package.test.ts +299 -0
  151. package/src/server/__tests__/routing-binding-graph.integration.test.ts +217 -0
  152. package/src/server/__tests__/routing-binding-validation.test.ts +256 -0
  153. package/src/server/__tests__/session-auto-approval.integration.test.ts +329 -0
  154. package/src/server/__tests__/skill-execute.test.ts +11 -0
  155. package/src/server/__tests__/skill-review-guard.test.ts +171 -0
  156. package/src/server/__tests__/token-tracker.test.ts +1 -8
  157. package/src/server/__tests__/tracing-retention-policy.test.ts +1 -8
  158. package/src/server/__tests__/usage-ledger.integration.test.ts +1 -8
  159. package/src/server/collections/agent-auto-approval-checkpoints.ts +18 -0
  160. package/src/server/collections/agent-execution-spans.ts +4 -11
  161. package/src/server/collections/agent-governance-audit-events.ts +1 -8
  162. package/src/server/collections/agent-governance-policies.ts +1 -8
  163. package/src/server/collections/agent-governance-policy-versions.ts +1 -8
  164. package/src/server/collections/agent-governance-prompt-bindings.ts +1 -8
  165. package/src/server/collections/agent-hierarchy-invocations.ts +30 -0
  166. package/src/server/collections/agent-loop-runs.ts +1 -8
  167. package/src/server/collections/agent-routing-graph-locks.ts +11 -0
  168. package/src/server/collections/agent-session-auto-approvals.ts +16 -0
  169. package/src/server/collections/orchestrator-config.ts +26 -0
  170. package/src/server/migrations/20261110000000-add-usage-pricing-snapshots.ts +1 -8
  171. package/src/server/migrations/20261110010000-add-usage-department-attribution.ts +1 -8
  172. package/src/server/migrations/20261119000000-widen-native-employee-identifiers.ts +37 -0
  173. package/src/server/plugin.ts +72 -8
  174. package/src/server/resources/agent-auto-approval.ts +51 -0
  175. package/src/server/resources/agent-governance.ts +1 -8
  176. package/src/server/resources/agent-harness-profile.ts +1 -8
  177. package/src/server/resources/agent-monitor.ts +1 -8
  178. package/src/server/resources/agent-usage.ts +1 -8
  179. package/src/server/resources/hierarchical-routing.ts +39 -0
  180. package/src/server/resources/native-monitor-format.ts +1 -8
  181. package/src/server/resources/tracing.ts +1 -8
  182. package/src/server/services/AgentGovernanceService.ts +1 -8
  183. package/src/server/services/AutoApprovalCheckpoint.ts +140 -0
  184. package/src/server/services/CodeValidator.ts +23 -4
  185. package/src/server/services/DepartmentAttribution.ts +1 -8
  186. package/src/server/services/ExecutionSpanService.ts +1 -8
  187. package/src/server/services/GovernanceAdmission.ts +83 -8
  188. package/src/server/services/HarnessCapabilities.ts +1 -8
  189. package/src/server/services/HarnessCompiler.ts +12 -0
  190. package/src/server/services/HarnessSchema.ts +30 -0
  191. package/src/server/services/HierarchicalAgentRuntime.ts +1052 -0
  192. package/src/server/services/HierarchyEnrollmentGuard.ts +211 -0
  193. package/src/server/services/HierarchyInvocationJournal.ts +172 -0
  194. package/src/server/services/HierarchyRequestCancellation.ts +132 -0
  195. package/src/server/services/LoopBudgetService.ts +1 -8
  196. package/src/server/services/LoopRunRepository.ts +2 -9
  197. package/src/server/services/LoopRunStateMachine.ts +3 -10
  198. package/src/server/services/LoopTriggerService.ts +1 -8
  199. package/src/server/services/LoopWorkerService.ts +8 -19
  200. package/src/server/services/ManagedPromptProtection.ts +1 -8
  201. package/src/server/services/NativeAgentMonitorSyncService.ts +1 -8
  202. package/src/server/services/NativeSubAgentObserver.ts +1 -8
  203. package/src/server/services/NativeUsageAttribution.ts +1 -8
  204. package/src/server/services/ParallelInterruptActionsPatch.ts +164 -0
  205. package/src/server/services/PluginAiRuntimeAdapter.ts +140 -9
  206. package/src/server/services/RoutingBindingRepository.ts +146 -0
  207. package/src/server/services/RoutingBindingValidation.ts +161 -0
  208. package/src/server/services/SandboxRunner.ts +35 -1
  209. package/src/server/services/SessionAutoApproval.ts +167 -0
  210. package/src/server/services/TokenTracker.ts +1 -8
  211. package/src/server/services/TracingRetentionPolicy.ts +1 -8
  212. package/src/server/services/VerificationService.ts +3 -10
  213. package/src/server/skill-hub/plugin.ts +40 -0
  214. package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +11 -1
  215. package/src/server/skill-hub/services/registry-node-package.ts +191 -0
  216. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +34 -5
  217. package/src/server/tools/skill-execute.ts +10 -0
  218. package/src/server/utils/ensure-indexes.ts +2 -8
  219. package/dist/client/418.6f01da17774a5a25.js +0 -10
  220. package/dist/client/652.477e21bfff67bc1c.js +0 -10
  221. package/dist/client-v2/418.55b6b28cda8bb5f3.js +0 -10
  222. package/dist/client-v2/652.1a48364774d5383a.js +0 -10
  223. package/dist/client-v2/981.a81521f0296c7db8.js +0 -10
@@ -1,11 +1,4 @@
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
- */
1
+ // SPDX-License-Identifier: Apache-2.0
9
2
 
10
3
  import type { Database, Model } from '@nocobase/database';
11
4
  import type { Transaction, WhereOptions } from 'sequelize';
@@ -1,11 +1,4 @@
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
- */
1
+ // SPDX-License-Identifier: Apache-2.0
9
2
 
10
3
  import { ExecutionSpanService } from './ExecutionSpanService';
11
4
  import { makeNativeRunId, NATIVE_SOURCE } from './NativeSubAgentObserver';
@@ -1,11 +1,4 @@
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
- */
1
+ // SPDX-License-Identifier: Apache-2.0
9
2
 
10
3
  import { createHash } from 'crypto';
11
4
  import { ExecutionSpanService } from './ExecutionSpanService';
@@ -1,11 +1,4 @@
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
- */
1
+ // SPDX-License-Identifier: Apache-2.0
9
2
 
10
3
  import { AsyncLocalStorage } from 'node:async_hooks';
11
4
  import type { Database } from '@nocobase/database';
@@ -0,0 +1,164 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { AIEmployee } from '@nocobase/plugin-ai/server';
4
+
5
+ export type InterruptActionRequest = {
6
+ name: string;
7
+ args?: unknown;
8
+ description?: string;
9
+ };
10
+
11
+ export type InterruptReviewConfig = {
12
+ actionName: string;
13
+ allowedDecisions?: string[];
14
+ };
15
+
16
+ export type InterruptPayload = {
17
+ actionRequests?: InterruptActionRequest[];
18
+ reviewConfigs?: InterruptReviewConfig[];
19
+ };
20
+
21
+ export type InterruptAction = {
22
+ order: number;
23
+ description?: string;
24
+ allowedDecisions?: string[];
25
+ toolCall?: { id: string; name: string };
26
+ currentConversation?: {
27
+ sessionId: string;
28
+ from: string;
29
+ username: string;
30
+ };
31
+ };
32
+
33
+ type ToInterruptActionsFn = (interrupt?: InterruptPayload) => Map<string, InterruptAction>;
34
+
35
+ const PATCH_STATE_KEY = Symbol.for('plugin-agent-orchestrator.parallelInterruptActionsPatch');
36
+
37
+ type PatchState = {
38
+ original: ToInterruptActionsFn;
39
+ wrapped: ToInterruptActionsFn;
40
+ owners: Set<symbol>;
41
+ };
42
+
43
+ export type PatchableAIEmployeePrototype = {
44
+ toInterruptActions?: ToInterruptActionsFn;
45
+ [PATCH_STATE_KEY]?: PatchState;
46
+ };
47
+
48
+ function parseInterruptDescription(description?: string): Record<string, unknown> | null {
49
+ if (typeof description !== 'string' || !description) return null;
50
+ try {
51
+ const parsed: unknown = JSON.parse(description);
52
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ function readOptionalString(record: Record<string, unknown>, key: string): string | undefined {
59
+ const value = record[key];
60
+ return typeof value === 'string' ? value : undefined;
61
+ }
62
+
63
+ /**
64
+ * Upstream @nocobase/plugin-ai indexes interrupt actionRequests by tool name, which overwrites earlier parallel calls
65
+ * to the same tool and leaves them stuck in invokeStatus="init". Iterate actionRequests directly and key by toolCallId.
66
+ */
67
+ export function toInterruptActionsFixed(interrupt?: InterruptPayload): Map<string, InterruptAction> {
68
+ const result = new Map<string, InterruptAction>();
69
+ const actionRequests = interrupt?.actionRequests ?? [];
70
+ const reviewConfigs = interrupt?.reviewConfigs ?? [];
71
+ if (!actionRequests.length) {
72
+ return result;
73
+ }
74
+
75
+ const reviewConfigsMap = new Map<string, InterruptReviewConfig>();
76
+ for (const config of reviewConfigs) {
77
+ reviewConfigsMap.set(config.actionName, config);
78
+ }
79
+
80
+ for (let order = 0; order < actionRequests.length; order++) {
81
+ const actionRequest = actionRequests[order];
82
+ const payload = parseInterruptDescription(actionRequest.description);
83
+ const matchingConfig =
84
+ reviewConfigs[order]?.actionName === actionRequest.name
85
+ ? reviewConfigs[order]
86
+ : reviewConfigsMap.get(actionRequest.name);
87
+
88
+ const toolCallId = payload ? readOptionalString(payload, 'toolCallId') : undefined;
89
+ const toolCallName = payload ? readOptionalString(payload, 'toolCallName') : undefined;
90
+ const sessionId = payload ? readOptionalString(payload, 'sessionId') : undefined;
91
+ const from = payload ? readOptionalString(payload, 'from') : undefined;
92
+ const username = payload ? readOptionalString(payload, 'username') : undefined;
93
+
94
+ const toolCall =
95
+ payload && toolCallId
96
+ ? {
97
+ id: toolCallId,
98
+ name: toolCallName ?? actionRequest.name,
99
+ }
100
+ : undefined;
101
+
102
+ const currentConversation =
103
+ payload && sessionId
104
+ ? {
105
+ sessionId,
106
+ from: from ?? '',
107
+ username: username ?? '',
108
+ }
109
+ : undefined;
110
+
111
+ const baseKey = toolCall?.id || `${actionRequest.name}:${order}`;
112
+ const key = result.has(baseKey) ? `${baseKey}:${order}` : baseKey;
113
+
114
+ result.set(key, {
115
+ order,
116
+ description: actionRequest.description,
117
+ allowedDecisions: matchingConfig?.allowedDecisions,
118
+ toolCall,
119
+ currentConversation,
120
+ });
121
+ }
122
+
123
+ return result;
124
+ }
125
+
126
+ export function installParallelInterruptActionsPatch(targetPrototype?: PatchableAIEmployeePrototype): () => void {
127
+ const target = targetPrototype ?? (AIEmployee?.prototype as PatchableAIEmployeePrototype | undefined);
128
+ if (!target || typeof target.toInterruptActions !== 'function') {
129
+ return () => undefined;
130
+ }
131
+
132
+ const owner = Symbol('parallel-interrupt-actions-owner');
133
+ let state = target[PATCH_STATE_KEY];
134
+ if (state && target.toInterruptActions === state.wrapped) {
135
+ state.owners.add(owner);
136
+ } else {
137
+ const original = target.toInterruptActions;
138
+ const wrapped: ToInterruptActionsFn = function toInterruptActionsPatched(interrupt?: InterruptPayload) {
139
+ return toInterruptActionsFixed(interrupt);
140
+ };
141
+ state = {
142
+ original,
143
+ wrapped,
144
+ owners: new Set([owner]),
145
+ };
146
+ target[PATCH_STATE_KEY] = state;
147
+ target.toInterruptActions = wrapped;
148
+ }
149
+
150
+ let disposed = false;
151
+ return () => {
152
+ if (disposed) return;
153
+ disposed = true;
154
+ const currentState = target[PATCH_STATE_KEY];
155
+ if (!currentState) return;
156
+ currentState.owners.delete(owner);
157
+ if (currentState.owners.size === 0) {
158
+ if (target.toInterruptActions === currentState.wrapped) {
159
+ target.toInterruptActions = currentState.original;
160
+ }
161
+ delete target[PATCH_STATE_KEY];
162
+ }
163
+ };
164
+ }
@@ -1,3 +1,12 @@
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
+
1
10
  import type { Model } from '@nocobase/database';
2
11
  import type { Application } from '@nocobase/server';
3
12
  import { AIEmployee } from '@nocobase/plugin-ai/server';
@@ -126,20 +135,57 @@ function textContent(messages: unknown): string {
126
135
  return '';
127
136
  }
128
137
 
129
- function interruptedFrom(result: Record<string, unknown>): InterruptedToolCall[] {
138
+ function invalidInterrupt(app: Application) {
139
+ const message = 'Invalid AI tool interruption payload.';
140
+ return new Error(app.i18n?.t?.(message, { ns: 'plugin-agent-orchestrator' }) || message);
141
+ }
142
+
143
+ function interruptedFrom(result: Record<string, unknown>, app: Application): InterruptedToolCall[] {
144
+ const invalidPayload = () => invalidInterrupt(app);
130
145
  const interrupts = result.__interrupt__;
131
- if (!Array.isArray(interrupts)) return [];
146
+ if (interrupts == null) return [];
147
+ if (!Array.isArray(interrupts) || interrupts.length > 1) throw invalidPayload();
132
148
  const calls: InterruptedToolCall[] = [];
133
149
  for (const interrupt of interrupts) {
150
+ if (!interrupt || typeof interrupt !== 'object') throw invalidPayload();
134
151
  const value = (interrupt as { value?: unknown }).value ?? interrupt;
152
+ if (!value || typeof value !== 'object') throw invalidPayload();
135
153
  const record = value as Record<string, unknown>;
154
+ const interruptId = String((interrupt as { id?: unknown }).id || record.interruptId || '');
155
+ if (Array.isArray(record.actionRequests)) {
156
+ if (!record.actionRequests.length || !interruptId) throw invalidPayload();
157
+ for (const action of record.actionRequests) {
158
+ if (!action || typeof action !== 'object') throw invalidPayload();
159
+ const request = action as Record<string, unknown>;
160
+ let details: Record<string, unknown>;
161
+ try {
162
+ details = JSON.parse(String(request.description));
163
+ } catch {
164
+ throw invalidPayload();
165
+ }
166
+ if (
167
+ !details ||
168
+ typeof details !== 'object' ||
169
+ typeof details.toolCallId !== 'string' ||
170
+ !details.toolCallId ||
171
+ typeof details.toolCallName !== 'string' ||
172
+ !details.toolCallName ||
173
+ !('args' in request)
174
+ ) {
175
+ throw invalidPayload();
176
+ }
177
+ calls.push({ toolCallId: details.toolCallId, toolName: details.toolCallName, args: request.args, interruptId });
178
+ }
179
+ continue;
180
+ }
136
181
  const toolCallId = String(record.toolCallId || record.tool_call_id || '');
137
- if (!toolCallId) continue;
182
+ const toolName = String(record.name || record.toolName || '');
183
+ if (!toolCallId || !toolName || !interruptId) throw invalidPayload();
138
184
  calls.push({
139
185
  toolCallId,
140
- toolName: String(record.name || record.toolName || ''),
186
+ toolName,
141
187
  args: record.args ?? record.input ?? {},
142
- interruptId: String((interrupt as { id?: unknown }).id || record.interruptId || ''),
188
+ interruptId,
143
189
  });
144
190
  }
145
191
  return calls;
@@ -251,14 +297,16 @@ export class PluginAiRuntimeAdapter {
251
297
  const { aiEmployee } = await this.buildEmployee(input);
252
298
 
253
299
  const result = (await aiEmployee.invoke({
254
- userMessages: [{ role: 'user', content: input.prompt }],
300
+ userMessages: [{ role: 'user', content: { type: 'text', content: input.prompt } }],
255
301
  signal: input.signal,
256
302
  })) as Record<string, unknown>;
257
303
 
304
+ const interrupted = interruptedFrom(result, this.app);
305
+ await this.repairInterruptedCalls(input, result, interrupted);
258
306
  return {
259
307
  sessionId: input.sessionId,
260
308
  messageId: String(result.messageId || ''),
261
- interrupted: interruptedFrom(result),
309
+ interrupted,
262
310
  content: textContent(result.messages),
263
311
  tokenUsage: extractTokenUsageFromResult(result),
264
312
  };
@@ -299,20 +347,103 @@ export class PluginAiRuntimeAdapter {
299
347
  const { aiEmployee } = await this.buildEmployee(input);
300
348
 
301
349
  const result = (await aiEmployee.invoke({
302
- messageId: input.messageId,
303
350
  userDecisions: userDecisions as { interruptId?: string; decisions: never[] },
304
351
  signal: input.signal,
305
352
  })) as Record<string, unknown>;
306
353
 
354
+ const interrupted = interruptedFrom(result, this.app);
355
+ await this.repairInterruptedCalls(input, result, interrupted);
307
356
  return {
308
357
  sessionId: input.sessionId,
309
358
  messageId: String(result.messageId || input.messageId),
310
- interrupted: interruptedFrom(result),
359
+ interrupted,
311
360
  content: textContent(result.messages),
312
361
  tokenUsage: extractTokenUsageFromResult(result),
313
362
  };
314
363
  }
315
364
 
365
+ private async repairInterruptedCalls(
366
+ input: { sessionId: string; username: string },
367
+ result: Record<string, unknown>,
368
+ calls: InterruptedToolCall[],
369
+ ) {
370
+ if (new Set(calls.map((call) => call.toolName)).size === calls.length) return;
371
+
372
+ const invalidPayload = () => invalidInterrupt(this.app);
373
+ const interrupt = (result.__interrupt__ as Array<{ value?: Record<string, unknown> }>)[0];
374
+ const requests = interrupt.value?.actionRequests;
375
+ const reviews = interrupt.value?.reviewConfigs;
376
+ const messageId = String(result.messageId || '');
377
+ if (!Array.isArray(requests) || requests.length !== calls.length || !messageId) throw invalidPayload();
378
+ if (new Set(calls.map((call) => call.toolCallId)).size !== calls.length) throw invalidPayload();
379
+
380
+ await this.app.db.sequelize.transaction(async (transaction) => {
381
+ const messages = this.app.db.getModel('aiMessages');
382
+ const toolMessages = this.app.db.getModel('aiToolMessages');
383
+ const message = await messages.findOne({
384
+ where: { sessionId: input.sessionId, messageId, role: input.username },
385
+ transaction,
386
+ lock: transaction.LOCK.UPDATE,
387
+ });
388
+ const messageCalls = read(message, 'toolCalls');
389
+ if (!message || !Array.isArray(messageCalls)) throw invalidPayload();
390
+
391
+ for (const [order, call] of calls.entries()) {
392
+ const request = requests[order] as Record<string, unknown>;
393
+ const description = request.description;
394
+ const details = JSON.parse(String(description)) as Record<string, unknown>;
395
+ if (
396
+ request.name !== call.toolName ||
397
+ details.sessionId !== input.sessionId ||
398
+ details.username !== input.username ||
399
+ details.from !== 'main-agent' ||
400
+ !messageCalls.some((item) => read(item, 'id') === call.toolCallId && read(item, 'name') === call.toolName)
401
+ ) {
402
+ throw invalidPayload();
403
+ }
404
+ const where = {
405
+ sessionId: input.sessionId,
406
+ messageId,
407
+ toolCallId: call.toolCallId,
408
+ toolName: call.toolName,
409
+ };
410
+ const toolMessage = await toolMessages.findOne({ where, transaction, lock: transaction.LOCK.UPDATE });
411
+ const status = read(toolMessage, 'invokeStatus');
412
+ if (!toolMessage || (status !== 'init' && status !== 'interrupted') || read(toolMessage, 'userDecision')) {
413
+ throw invalidPayload();
414
+ }
415
+ const review = Array.isArray(reviews)
416
+ ? reviews.find((item) => read(item, 'actionName') === call.toolName)
417
+ : null;
418
+ const [updated] = await toolMessages.update(
419
+ {
420
+ invokeStatus: 'interrupted',
421
+ interruptActionOrder: order,
422
+ interruptAction: {
423
+ order,
424
+ description,
425
+ allowedDecisions: read(review, 'allowedDecisions'),
426
+ toolCall: { id: call.toolCallId, name: call.toolName },
427
+ currentConversation: { sessionId: input.sessionId, from: details.from, username: input.username },
428
+ },
429
+ },
430
+ { where: { ...where, invokeStatus: status }, transaction },
431
+ );
432
+ if (updated !== 1) throw invalidPayload();
433
+ }
434
+
435
+ const metadata = read(message, 'metadata');
436
+ const existingMetadata = metadata && typeof metadata === 'object' && !Array.isArray(metadata) ? metadata : {};
437
+ if (read(existingMetadata, 'interruptId') !== calls[0].interruptId) {
438
+ const [updated] = await messages.update(
439
+ { metadata: { ...existingMetadata, interruptId: calls[0].interruptId } },
440
+ { where: { sessionId: input.sessionId, messageId }, transaction },
441
+ );
442
+ if (updated !== 1) throw invalidPayload();
443
+ }
444
+ });
445
+ }
446
+
316
447
  // The employee model is re-read per invocation and mutated only in memory. `isAutoCall` reads
317
448
  // `employee.skillSettings` off the Sequelize dataValues, so `set()` without `save()` gates this
318
449
  // run's tool calls without touching the shared employee configuration.
@@ -0,0 +1,146 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { literal, Repository, type Database, type Transaction } from '@nocobase/database';
3
+ import { read } from '../utils/record-utils';
4
+ import { RoutingCycleError, routingWouldCycle } from './RoutingBindingValidation';
5
+
6
+ const graphLockKey = 'routing';
7
+ const graphFields = ['leaderUsername', 'subAgentUsername', 'routingEnabled', 'enabled'] as const;
8
+
9
+ type CreateOptions = Parameters<Repository['create']>[0];
10
+ type UpdateOptions = Parameters<Repository['update']>[0];
11
+ type CreateManyOptions = Parameters<Repository['createMany']>[0];
12
+ type UpdateManyOptions = Parameters<Repository['updateMany']>[0];
13
+
14
+ function couldAddEdge(values: unknown): boolean {
15
+ if (Array.isArray(values)) return values.some(couldAddEdge);
16
+ if (!values || typeof values !== 'object') return false;
17
+ const patch = values as Record<string, unknown>;
18
+ const fields = graphFields.filter((field) => Object.prototype.hasOwnProperty.call(patch, field));
19
+ return fields.some((field) => (field !== 'enabled' && field !== 'routingEnabled') || patch[field] !== false);
20
+ }
21
+
22
+ function couldCreateEdge(values: unknown): boolean {
23
+ if (Array.isArray(values)) return values.some(couldCreateEdge);
24
+ if (!values || typeof values !== 'object') return false;
25
+ const value = (values as Record<string, unknown>).routingEnabled;
26
+ return value != null && value !== false;
27
+ }
28
+
29
+ function sqliteIsBusy(error: unknown): boolean {
30
+ if (!error || typeof error !== 'object') return false;
31
+ const value = error as { code?: unknown; parent?: { code?: unknown }; original?: { code?: unknown } };
32
+ return [value.code, value.parent?.code, value.original?.code].some(
33
+ (code) => typeof code === 'string' && /^(SQLITE_BUSY|SQLITE_LOCKED)/.test(code),
34
+ );
35
+ }
36
+
37
+ function edgeChanged(before: unknown, after: unknown): boolean {
38
+ return (
39
+ !before ||
40
+ read(before, 'leaderUsername') !== read(after, 'leaderUsername') ||
41
+ read(before, 'subAgentUsername') !== read(after, 'subAgentUsername')
42
+ );
43
+ }
44
+
45
+ export async function initializeRoutingGraphLock(database: Database) {
46
+ const model = database.getModel('agentRoutingGraphLocks');
47
+ await model.findOrCreate({ where: { key: graphLockKey }, defaults: { key: graphLockKey, marker: 0 } });
48
+ }
49
+
50
+ /** Serializes graph changes across processes until the binding transaction commits. */
51
+ export class RoutingBindingRepository extends Repository {
52
+ private readonly graphTransactions = new WeakSet<Transaction>();
53
+
54
+ private async withGraphLock<T>(
55
+ suppliedTransaction: Transaction | null | undefined,
56
+ operation: (transaction: Transaction) => Promise<T>,
57
+ ): Promise<T> {
58
+ for (let attempt = 0; ; attempt += 1) {
59
+ let writeStarted = false;
60
+ const afterCommit: Array<(transaction: Transaction) => void | Promise<void>> = [];
61
+ try {
62
+ const result = await this.database.sequelize.transaction(
63
+ { transaction: suppliedTransaction ?? undefined },
64
+ async (transaction) => {
65
+ if (suppliedTransaction) {
66
+ // Sequelize fires savepoint afterCommit callbacks before the enclosing transaction commits.
67
+ transaction.afterCommit = (callback) => {
68
+ if (typeof callback !== 'function') throw new Error('afterCommit callback must be a function.');
69
+ afterCommit.push(callback);
70
+ };
71
+ }
72
+ const lockModel = this.database.getModel('agentRoutingGraphLocks');
73
+ const [affected] = await lockModel.update(
74
+ { marker: literal('1 - marker') },
75
+ { where: { key: graphLockKey }, transaction },
76
+ );
77
+ if (affected !== 1) throw new Error('The routing graph lock has not been initialized.');
78
+
79
+ const query = {
80
+ filter: { routingEnabled: true, enabled: true },
81
+ transaction,
82
+ lock: transaction.LOCK.UPDATE,
83
+ };
84
+ const before = await this.find(query);
85
+ writeStarted = true;
86
+ this.graphTransactions.add(transaction);
87
+ let result: T;
88
+ try {
89
+ result = await operation(transaction);
90
+ } finally {
91
+ this.graphTransactions.delete(transaction);
92
+ }
93
+ const after = await this.find(query);
94
+ const previous = new Map(before.map((row) => [String(read(row, 'id')), row]));
95
+ for (const binding of after) {
96
+ const id = read(binding, 'id');
97
+ const candidate = {
98
+ leaderUsername: read(binding, 'leaderUsername'),
99
+ subAgentUsername: read(binding, 'subAgentUsername'),
100
+ routingEnabled: read(binding, 'routingEnabled'),
101
+ enabled: read(binding, 'enabled'),
102
+ };
103
+ if (edgeChanged(previous.get(String(id)), binding) && routingWouldCycle(candidate, after, id)) {
104
+ throw new RoutingCycleError();
105
+ }
106
+ }
107
+ return result;
108
+ },
109
+ );
110
+ for (const callback of afterCommit) suppliedTransaction?.afterCommit(callback);
111
+ return result;
112
+ } catch (error) {
113
+ if (suppliedTransaction || writeStarted || attempt >= 3 || !sqliteIsBusy(error)) throw error;
114
+ await new Promise((resolve) => setTimeout(resolve, 25 * 2 ** attempt));
115
+ }
116
+ }
117
+ }
118
+
119
+ async create(options: CreateOptions) {
120
+ if (!couldCreateEdge(options.values) || (options.transaction && this.graphTransactions.has(options.transaction))) {
121
+ return super.create(options);
122
+ }
123
+ return this.withGraphLock(options.transaction, (transaction) => super.create({ ...options, transaction }));
124
+ }
125
+
126
+ async createMany(options: CreateManyOptions) {
127
+ if (!couldCreateEdge(options.records) || (options.transaction && this.graphTransactions.has(options.transaction))) {
128
+ return super.createMany(options);
129
+ }
130
+ return this.withGraphLock(options.transaction, (transaction) => super.createMany({ ...options, transaction }));
131
+ }
132
+
133
+ async update(options: UpdateOptions) {
134
+ if (!couldAddEdge(options.values) || (options.transaction && this.graphTransactions.has(options.transaction))) {
135
+ return super.update(options);
136
+ }
137
+ return this.withGraphLock(options.transaction, (transaction) => super.update({ ...options, transaction }));
138
+ }
139
+
140
+ async updateMany(options: UpdateManyOptions) {
141
+ if (!couldAddEdge(options.records) || (options.transaction && this.graphTransactions.has(options.transaction))) {
142
+ return super.updateMany(options);
143
+ }
144
+ return this.withGraphLock(options.transaction, (transaction) => super.updateMany({ ...options, transaction }));
145
+ }
146
+ }