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
@@ -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';
@@ -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
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type { Context } from '@nocobase/actions';
11
+ import { read } from '../utils/record-utils';
12
+
13
+ const routingFields = ['routingEnabled', 'routingRole', 'routingPrompt', 'llmService', 'model'] as const;
14
+ const identityFields = ['leaderUsername', 'subAgentUsername', 'enabled', 'harnessTag'] as const;
15
+ const bindingFields = [...identityFields, ...routingFields] as const;
16
+
17
+ type RoutingBinding = Partial<Record<(typeof bindingFields)[number], unknown>>;
18
+
19
+ export class RoutingCycleError extends Error {
20
+ readonly status = 400;
21
+ readonly statusCode = 400;
22
+ readonly expose = true;
23
+
24
+ constructor() {
25
+ super('This binding would create a delegation cycle.');
26
+ }
27
+ }
28
+
29
+ function nonBlank(value: unknown): value is string {
30
+ return typeof value === 'string' && value.trim().length > 0;
31
+ }
32
+
33
+ function scalarBindingId(value: unknown) {
34
+ return (
35
+ (typeof value === 'string' && Boolean(value.trim())) ||
36
+ (typeof value === 'number' && Number.isSafeInteger(value) && value > 0)
37
+ );
38
+ }
39
+
40
+ /** Validate an opted-in binding after partial update values are merged with the stored record. */
41
+ export function routingBindingError(binding: RoutingBinding): string | null {
42
+ if (binding.routingEnabled !== true) return null;
43
+ if (!nonBlank(binding.leaderUsername) || !nonBlank(binding.subAgentUsername)) {
44
+ return 'Routing requires a parent and a target employee.';
45
+ }
46
+ if (binding.leaderUsername.trim() === binding.subAgentUsername.trim()) {
47
+ return 'An employee cannot delegate to itself.';
48
+ }
49
+ if (binding.routingRole !== 'specialist' && binding.routingRole !== 'worker') {
50
+ return 'Choose a routing role for the target employee.';
51
+ }
52
+ if (
53
+ (binding.llmService != null && typeof binding.llmService !== 'string') ||
54
+ (binding.model != null && typeof binding.model !== 'string') ||
55
+ Boolean(nonBlank(binding.llmService)) !== Boolean(nonBlank(binding.model))
56
+ ) {
57
+ return 'Select both an LLM service and a model, or leave both empty.';
58
+ }
59
+ if (
60
+ binding.routingPrompt != null &&
61
+ (typeof binding.routingPrompt !== 'string' || binding.routingPrompt.length > 4000)
62
+ ) {
63
+ return 'The routing description must be 4000 characters or fewer.';
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /** Check the enabled routing graph without trusting labels or names generated by a model. */
69
+ export function routingWouldCycle(binding: RoutingBinding, rows: unknown[], excludeId?: unknown): boolean {
70
+ if (binding.routingEnabled !== true || binding.enabled === false) return false;
71
+ if (!nonBlank(binding.leaderUsername) || !nonBlank(binding.subAgentUsername)) return false;
72
+ const parent = binding.leaderUsername.trim();
73
+ const queue = [binding.subAgentUsername.trim()];
74
+ const visited = new Set<string>();
75
+ const edges = rows
76
+ .filter((row) => excludeId == null || String(read(row, 'id')) !== String(excludeId))
77
+ .filter((row) => read(row, 'enabled') !== false && read(row, 'routingEnabled') === true)
78
+ .map((row) => ({ parent: read(row, 'leaderUsername'), target: read(row, 'subAgentUsername') }))
79
+ .filter((edge): edge is { parent: string; target: string } => nonBlank(edge.parent) && nonBlank(edge.target));
80
+ while (queue.length) {
81
+ const current = queue.shift();
82
+ if (!current) continue;
83
+ if (current === parent) return true;
84
+ if (visited.has(current)) continue;
85
+ visited.add(current);
86
+ for (const edge of edges) {
87
+ if (edge.parent.trim() === current) queue.push(edge.target.trim());
88
+ }
89
+ }
90
+ return false;
91
+ }
92
+
93
+ /** Run after ACL so this validation cannot replace collection or association authorization. */
94
+ async function validateRoutingBinding(ctx: Context, next: () => Promise<unknown>) {
95
+ const { resourceName, actionName, params } = ctx.action || {};
96
+ if (resourceName !== 'orchestratorConfig' || !['create', 'update'].includes(actionName)) return next();
97
+ const values = params?.values;
98
+ if (!values || typeof values !== 'object') return next();
99
+ if (Array.isArray(values)) {
100
+ if (
101
+ values.some(
102
+ (item) =>
103
+ item && typeof item === 'object' && [...routingFields, ...identityFields].some((field) => field in item),
104
+ )
105
+ ) {
106
+ return ctx.throw(400, ctx.t('Update routing settings for one binding at a time.'));
107
+ }
108
+ return next();
109
+ }
110
+ const patch = values as RoutingBinding;
111
+ if ('routingEnabled' in patch && typeof patch.routingEnabled !== 'boolean') {
112
+ return ctx.throw(400, ctx.t('Routing enabled must be a boolean.'));
113
+ }
114
+ let current: unknown;
115
+ if (actionName === 'update') {
116
+ const key = params.filterByTk;
117
+ if (!scalarBindingId(key)) {
118
+ if (routingFields.some((field) => field in patch)) {
119
+ return ctx.throw(400, ctx.t('Update routing settings for one binding at a time.'));
120
+ }
121
+ if (identityFields.some((field) => field in patch)) {
122
+ if (key != null && (!Array.isArray(key) || !key.length || !key.every(scalarBindingId))) {
123
+ return ctx.throw(400, ctx.t('Update routing settings for one binding at a time.'));
124
+ }
125
+ const filter = params.filter && typeof params.filter === 'object' ? params.filter : {};
126
+ const targets = Array.isArray(key) ? { id: key } : {};
127
+ const affected = await ctx.db.getRepository('orchestratorConfig').findOne({
128
+ filter: { $and: [filter, targets, { routingEnabled: true }] },
129
+ });
130
+ if (affected) return ctx.throw(400, ctx.t('Update routing settings for one binding at a time.'));
131
+ }
132
+ return next();
133
+ }
134
+ current = await ctx.db.getRepository('orchestratorConfig').findOne({ filterByTk: key });
135
+ if (!current) return next();
136
+ }
137
+ const merged: RoutingBinding = {};
138
+ for (const field of bindingFields) {
139
+ merged[field] = field in patch ? patch[field] : read(current, field);
140
+ }
141
+ const error = routingBindingError(merged);
142
+ if (error) return ctx.throw(400, ctx.t(error));
143
+ if (merged.routingEnabled === true && merged.enabled !== false) {
144
+ const rows = await ctx.db.getRepository('orchestratorConfig').find({
145
+ filter: { routingEnabled: true, enabled: true },
146
+ });
147
+ if (routingWouldCycle(merged, rows, actionName === 'update' ? params.filterByTk : undefined)) {
148
+ return ctx.throw(400, ctx.t('This binding would create a delegation cycle.'));
149
+ }
150
+ }
151
+ return next();
152
+ }
153
+
154
+ export async function validateRoutingBindingAction(ctx: Context, next: () => Promise<unknown>) {
155
+ try {
156
+ return await validateRoutingBinding(ctx, next);
157
+ } catch (error) {
158
+ if (error instanceof RoutingCycleError) return ctx.throw(400, ctx.t(error.message));
159
+ throw error;
160
+ }
161
+ }
@@ -1,5 +1,14 @@
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 { spawn } from 'child_process';
2
- import { existsSync, writeFileSync } from 'fs';
11
+ import { chownSync, existsSync, lstatSync, readdirSync, realpathSync, writeFileSync } from 'fs';
3
12
  import { resolve, delimiter } from 'path';
4
13
  import { tmpdir } from 'os';
5
14
  import { FileManager, OutputFileInfo } from './FileManager';
@@ -39,6 +48,8 @@ export interface ExecuteOptions {
39
48
  packageWhitelist?: string[];
40
49
  /** Optional installed/copied skill package root exposed to the runtime as SKILL_DIR. */
41
50
  skillDir?: string;
51
+ /** Private package snapshot inside the execution directory, if it needs a privilege-drop owner. */
52
+ packageSnapshotDir?: string;
42
53
  /** Validated input exposed as a JSON file to avoid source-code interpolation. */
43
54
  inputArgs?: Record<string, unknown>;
44
55
  }
@@ -198,6 +209,7 @@ export class SandboxRunner {
198
209
  signal,
199
210
  packageWhitelist,
200
211
  skillDir,
212
+ packageSnapshotDir,
201
213
  inputArgs,
202
214
  } = options;
203
215
 
@@ -230,8 +242,30 @@ export class SandboxRunner {
230
242
  : null;
231
243
  if (identity) {
232
244
  try {
245
+ const snapshotPaths: string[] = [];
246
+ if (packageSnapshotDir) {
247
+ const expected = resolve(workDir, 'skill');
248
+ if (
249
+ resolve(packageSnapshotDir) !== expected ||
250
+ lstatSync(packageSnapshotDir).isSymbolicLink() ||
251
+ realpathSync(packageSnapshotDir) !== resolve(realpathSync(workDir), 'skill')
252
+ ) {
253
+ throw new Error('Invalid skill package snapshot path.');
254
+ }
255
+ const collect = (path: string) => {
256
+ const stat = lstatSync(path);
257
+ if (stat.isSymbolicLink()) throw new Error('Invalid skill package snapshot path.');
258
+ snapshotPaths.push(path);
259
+ if (stat.isDirectory()) {
260
+ for (const entry of readdirSync(path)) collect(resolve(path, entry));
261
+ }
262
+ };
263
+ collect(packageSnapshotDir);
264
+ }
233
265
  this.fileManager.chownExecDir(execId, identity.uid, identity.gid);
266
+ for (const path of snapshotPaths) chownSync(path, identity.uid, identity.gid);
234
267
  } catch (error) {
268
+ if (packageSnapshotDir) throw error;
235
269
  this.logger.warn(
236
270
  `[skill-hub] chown of exec dir failed for ${execId}; running without privilege drop: ${
237
271
  (error as Error).message