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
@@ -53,6 +53,9 @@ var import_agent_loop_events_stream = require("./resources/agent-loop-events-str
53
53
  var import_agent_knowledge_insights = require("./resources/agent-knowledge-insights");
54
54
  var import_agent_governance = require("./resources/agent-governance");
55
55
  var import_agent_usage = require("./resources/agent-usage");
56
+ var import_hierarchical_routing = require("./resources/hierarchical-routing");
57
+ var import_agent_auto_approval = require("./resources/agent-auto-approval");
58
+ var import_SessionAutoApproval = require("./services/SessionAutoApproval");
56
59
  var import_plugin = __toESM(require("./skill-hub/plugin"));
57
60
  var import_NativeSubAgentObserver = require("./services/NativeSubAgentObserver");
58
61
  var import_NativeAgentMonitorSyncService = require("./services/NativeAgentMonitorSyncService");
@@ -74,6 +77,12 @@ var import_TracingRetentionPolicy = require("./services/TracingRetentionPolicy")
74
77
  var import_GovernanceAdmission = require("./services/GovernanceAdmission");
75
78
  var import_ManagedPromptProtection = require("./services/ManagedPromptProtection");
76
79
  var import_NativeUsageAttribution = require("./services/NativeUsageAttribution");
80
+ var import_HierarchicalAgentRuntime = require("./services/HierarchicalAgentRuntime");
81
+ var import_RoutingBindingValidation = require("./services/RoutingBindingValidation");
82
+ var import_RoutingBindingRepository = require("./services/RoutingBindingRepository");
83
+ var import_HierarchyEnrollmentGuard = require("./services/HierarchyEnrollmentGuard");
84
+ var import_HierarchyRequestCancellation = require("./services/HierarchyRequestCancellation");
85
+ var import_ParallelInterruptActionsPatch = require("./services/ParallelInterruptActionsPatch");
77
86
  function normalizeOptionalString(value) {
78
87
  return typeof value === "string" ? value.trim() : "";
79
88
  }
@@ -174,6 +183,7 @@ async function validateAgentMemoryContextValues(ctx) {
174
183
  ctx.action.params.values = normalizedValues;
175
184
  }
176
185
  class PluginAgentOrchestratorServer extends import_server.Plugin {
186
+ hierarchyCancellation = new import_HierarchyRequestCancellation.HierarchyRequestCancellation(this);
177
187
  skillHub;
178
188
  registrySkillSnapshotService;
179
189
  registrySkillInstallationService;
@@ -183,6 +193,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
183
193
  removeNativeMonitorHook;
184
194
  removeManagedPromptProtection;
185
195
  removeNativeUsageAttribution;
196
+ removeParallelInterruptActionsPatch;
186
197
  governanceEnabled = true;
187
198
  loopScheduler;
188
199
  loopWorker;
@@ -208,6 +219,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
208
219
  this.app.agentRuntimeLifecycle = this.agentRuntimeLifecycle;
209
220
  }
210
221
  async beforeLoad() {
222
+ this.db.registerRepositories({ RoutingBindingRepository: import_RoutingBindingRepository.RoutingBindingRepository });
211
223
  this.db.import({ directory: import_path.default.resolve(__dirname, "collections") });
212
224
  this.db.addMigrations({
213
225
  namespace: this.name,
@@ -226,6 +238,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
226
238
  "agentMonitor:*",
227
239
  "agentUsage:*",
228
240
  "agentGovernance:*",
241
+ "agentHierarchy:*",
229
242
  "agentKnowledgeInsights:*",
230
243
  "agentMemoryContexts:*",
231
244
  "agentLoopRuns:*",
@@ -257,7 +270,24 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
257
270
  this.app.acl.allow("agentLoopApprovals", ["list", "get", "decide"], "loggedIn");
258
271
  this.app.acl.allow("agentLoopArtifactsView", ["list", "get"], "loggedIn");
259
272
  this.app.acl.allow("agentLoopEventsStream", ["stream"], "loggedIn");
273
+ this.app.acl.allow("agentAutoApproval", ["get", "set", "eligible"], "loggedIn");
260
274
  this.installGovernanceHooks();
275
+ this.installParallelInterruptActionsFix();
276
+ this.app.resourceManager.use(
277
+ async (ctx, next) => {
278
+ var _a2;
279
+ if ([
280
+ "agentHierarchyInvocations",
281
+ "agentSessionAutoApprovals",
282
+ "agentAutoApprovalCheckpoints",
283
+ "agentRoutingGraphLocks"
284
+ ].includes(((_a2 = ctx.action) == null ? void 0 : _a2.resourceName) ?? "")) {
285
+ return ctx.throw(403, ctx.t("Hierarchy invocation records are not directly accessible."));
286
+ }
287
+ return next();
288
+ },
289
+ { tag: "orchestrator-hierarchy-record-protection", after: "acl" }
290
+ );
261
291
  this.app.resourceManager.use(
262
292
  async (ctx, next) => {
263
293
  const { resourceName, actionName } = ctx.action || {};
@@ -283,6 +313,26 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
283
313
  tag: "orchestrator-governance-admission",
284
314
  after: "acl"
285
315
  });
316
+ this.app.resourceManager.use(async (ctx, next) => (0, import_RoutingBindingValidation.validateRoutingBindingAction)(ctx, next), {
317
+ tag: "orchestrator-routing-binding-validation",
318
+ after: "acl"
319
+ });
320
+ this.app.resourceManager.use(async (ctx, next) => (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(ctx, next), {
321
+ tag: "orchestrator-hierarchy-enrollment",
322
+ after: "acl"
323
+ });
324
+ this.app.resourceManager.use(async (ctx, next) => (0, import_HierarchyEnrollmentGuard.guardManagedChildActions)(ctx, next), {
325
+ tag: "orchestrator-hierarchy-child-protection",
326
+ after: "orchestrator-hierarchy-enrollment"
327
+ });
328
+ this.app.resourceManager.use(async (ctx, next) => (0, import_SessionAutoApproval.guardAutoApprovalDecision)(ctx, next), {
329
+ tag: "orchestrator-auto-approval-decision",
330
+ after: "orchestrator-hierarchy-child-protection"
331
+ });
332
+ this.app.resourceManager.use(async (ctx, next) => this.hierarchyCancellation.middleware(ctx, next), {
333
+ tag: "orchestrator-hierarchy-cancellation",
334
+ after: "orchestrator-hierarchy-child-protection"
335
+ });
286
336
  this.app.resourceManager.use(
287
337
  async (ctx, next) => {
288
338
  const { resourceName, actionName } = ctx.action || {};
@@ -382,6 +432,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
382
432
  );
383
433
  const toolsManager = (0, import_ai_manager.getAIToolsManager)(this.app);
384
434
  toolsManager.registerTools((0, import_external_rag_search.createExternalRagSearchTool)(this));
435
+ toolsManager.registerTools((0, import_HierarchicalAgentRuntime.createHierarchicalAgentTools)(this));
385
436
  const patterns = new import_LoopPatternService.LoopPatternService(
386
437
  this.db,
387
438
  (0, import_loop_pattern_context.employeeHarnessResolver)(this),
@@ -398,6 +449,8 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
398
449
  (0, import_agent_loop_events_stream.registerAgentLoopEventsStreamResource)(this);
399
450
  (0, import_agent_harness_profile.registerAgentHarnessProfileResource)(this);
400
451
  (0, import_agent_governance.registerAgentGovernanceResource)(this);
452
+ (0, import_hierarchical_routing.registerHierarchicalRoutingResource)(this);
453
+ (0, import_agent_auto_approval.registerAgentAutoApprovalResource)(this);
401
454
  (0, import_agent_usage.registerAgentUsageResource)(this);
402
455
  (0, import_agent_monitor.registerAgentMonitorResource)(this);
403
456
  (0, import_agent_knowledge_insights.registerAgentKnowledgeInsightsResource)(this);
@@ -528,50 +581,60 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
528
581
  }
529
582
  async install() {
530
583
  await this.skillHub.install();
584
+ await (0, import_RoutingBindingRepository.initializeRoutingGraphLock)(this.db);
531
585
  await (0, import_ensure_indexes.ensureAgentOrchestratorIndexes)(this.db);
532
586
  }
533
587
  async upgrade() {
588
+ await (0, import_RoutingBindingRepository.initializeRoutingGraphLock)(this.db);
534
589
  await (0, import_ensure_indexes.ensureAgentOrchestratorIndexes)(this.db);
535
590
  }
536
591
  async afterEnable() {
537
592
  this.governanceEnabled = true;
538
593
  this.installGovernanceHooks();
594
+ this.installParallelInterruptActionsFix();
539
595
  this.installNativeMonitorHook();
540
596
  }
541
597
  async afterDisable() {
542
- var _a, _b, _c, _d;
598
+ var _a, _b, _c, _d, _e;
543
599
  this.governanceEnabled = false;
600
+ this.hierarchyCancellation.abortAll();
544
601
  (_a = this.removeManagedPromptProtection) == null ? void 0 : _a.call(this);
545
602
  this.removeManagedPromptProtection = void 0;
546
603
  (_b = this.removeNativeUsageAttribution) == null ? void 0 : _b.call(this);
547
604
  this.removeNativeUsageAttribution = void 0;
548
- (_c = this.nativeObserver) == null ? void 0 : _c.uninstall();
549
- (_d = this.removeNativeMonitorHook) == null ? void 0 : _d.call(this);
605
+ (_c = this.removeParallelInterruptActionsPatch) == null ? void 0 : _c.call(this);
606
+ this.removeParallelInterruptActionsPatch = void 0;
607
+ (_d = this.nativeObserver) == null ? void 0 : _d.uninstall();
608
+ (_e = this.removeNativeMonitorHook) == null ? void 0 : _e.call(this);
550
609
  this.removeNativeMonitorHook = void 0;
551
610
  }
552
611
  async remove() {
553
612
  }
554
613
  async beforeStop() {
555
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
614
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
556
615
  this.governanceEnabled = false;
616
+ this.hierarchyCancellation.abortAll();
557
617
  (_a = this.removeManagedPromptProtection) == null ? void 0 : _a.call(this);
558
618
  this.removeManagedPromptProtection = void 0;
559
619
  (_b = this.removeNativeUsageAttribution) == null ? void 0 : _b.call(this);
560
620
  this.removeNativeUsageAttribution = void 0;
561
- (_d = (_c = this.app).off) == null ? void 0 : _d.call(_c, "afterStart", this.installNativeObserver);
562
- (_f = (_e = this.app).removeListener) == null ? void 0 : _f.call(_e, "afterStart", this.installNativeObserver);
563
- (_h = (_g = this.app).off) == null ? void 0 : _h.call(_g, "afterStart", this.startLoopWorker);
564
- (_j = (_i = this.app).removeListener) == null ? void 0 : _j.call(_i, "afterStart", this.startLoopWorker);
565
- await ((_k = this.loopWorker) == null ? void 0 : _k.stop());
566
- await ((_l = this.loopScheduler) == null ? void 0 : _l.dispose());
567
- (_m = this.nativeObserver) == null ? void 0 : _m.uninstall();
568
- (_n = this.removeNativeMonitorHook) == null ? void 0 : _n.call(this);
621
+ (_c = this.removeParallelInterruptActionsPatch) == null ? void 0 : _c.call(this);
622
+ this.removeParallelInterruptActionsPatch = void 0;
623
+ (_e = (_d = this.app).off) == null ? void 0 : _e.call(_d, "afterStart", this.installNativeObserver);
624
+ (_g = (_f = this.app).removeListener) == null ? void 0 : _g.call(_f, "afterStart", this.installNativeObserver);
625
+ (_i = (_h = this.app).off) == null ? void 0 : _i.call(_h, "afterStart", this.startLoopWorker);
626
+ (_k = (_j = this.app).removeListener) == null ? void 0 : _k.call(_j, "afterStart", this.startLoopWorker);
627
+ await ((_l = this.loopWorker) == null ? void 0 : _l.stop());
628
+ await ((_m = this.loopScheduler) == null ? void 0 : _m.dispose());
629
+ (_n = this.nativeObserver) == null ? void 0 : _n.uninstall();
630
+ (_o = this.removeNativeMonitorHook) == null ? void 0 : _o.call(this);
569
631
  this.removeNativeMonitorHook = void 0;
570
632
  await this.skillHub.beforeStop();
571
633
  (0, import_RunEventBus.resetRunEventBus)();
572
634
  }
573
635
  async handleSyncMessage(message) {
574
636
  var _a, _b;
637
+ this.hierarchyCancellation.handleSyncMessage(message);
575
638
  await ((_a = this.loopScheduler) == null ? void 0 : _a.handleSyncMessage(message));
576
639
  await ((_b = this.loopWorker) == null ? void 0 : _b.handleSyncMessage(message));
577
640
  }
@@ -584,6 +647,11 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
584
647
  this.removeManagedPromptProtection = (0, import_ManagedPromptProtection.installManagedPromptProtection)(this.db);
585
648
  if (!this.removeNativeUsageAttribution) this.removeNativeUsageAttribution = (0, import_NativeUsageAttribution.installNativeUsageAttribution)(this);
586
649
  }
650
+ installParallelInterruptActionsFix() {
651
+ if (!this.removeParallelInterruptActionsPatch) {
652
+ this.removeParallelInterruptActionsPatch = (0, import_ParallelInterruptActionsPatch.installParallelInterruptActionsPatch)();
653
+ }
654
+ }
587
655
  installNativeMonitorHook() {
588
656
  if (this.removeNativeMonitorHook || !this.agentRuntimeLifecycle || !this.nativeMonitorSyncService) return;
589
657
  this.removeNativeMonitorHook = this.agentRuntimeLifecycle.registerAfterRunHook("native-monitor", (context) => {
@@ -0,0 +1,80 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var agent_auto_approval_exports = {};
28
+ __export(agent_auto_approval_exports, {
29
+ registerAgentAutoApprovalResource: () => registerAgentAutoApprovalResource
30
+ });
31
+ module.exports = __toCommonJS(agent_auto_approval_exports);
32
+ var import_SessionAutoApproval = require("../services/SessionAutoApproval");
33
+ var import_ctx_utils = require("../utils/ctx-utils");
34
+ var import_record_utils = require("../utils/record-utils");
35
+ async function ownedSession(ctx) {
36
+ var _a, _b;
37
+ const ownerId = Number((_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id);
38
+ if (!Number.isSafeInteger(ownerId) || ownerId <= 0) ctx.throw(401, ctx.t("Authentication is required."));
39
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
40
+ const sessionId = values.sessionId;
41
+ if (typeof sessionId !== "string" || !sessionId.trim() || sessionId.length > 100) {
42
+ ctx.throw(400, ctx.t("A conversation is required."));
43
+ }
44
+ const conversation = await ctx.db.getRepository("aiConversations").findOne({ filter: { sessionId, userId: ownerId } });
45
+ if (!conversation || (0, import_record_utils.read)(conversation, "from") === "sub-agent") {
46
+ ctx.throw(404, ctx.t("The current conversation is unavailable."));
47
+ }
48
+ return { ownerId, sessionId };
49
+ }
50
+ function registerAgentAutoApprovalResource(plugin) {
51
+ plugin.app.resource({
52
+ name: "agentAutoApproval",
53
+ actions: {
54
+ async get(ctx, next) {
55
+ const { sessionId } = await ownedSession(ctx);
56
+ ctx.body = { enabled: await (0, import_SessionAutoApproval.sessionAutoApprovalEnabled)(ctx, sessionId) };
57
+ await next();
58
+ },
59
+ async set(ctx, next) {
60
+ const { ownerId, sessionId } = await ownedSession(ctx);
61
+ const { enabled } = (0, import_ctx_utils.valuesFromCtx)(ctx);
62
+ if (typeof enabled !== "boolean") ctx.throw(400, ctx.t("An auto-approval setting is required."));
63
+ await ctx.db.getModel("agentSessionAutoApprovals").upsert({ ownerId, sessionId, enabled });
64
+ ctx.body = { enabled };
65
+ await next();
66
+ },
67
+ async eligible(ctx, next) {
68
+ await ownedSession(ctx);
69
+ const call = (0, import_SessionAutoApproval.autoApprovalCall)((0, import_ctx_utils.valuesFromCtx)(ctx));
70
+ if (!call) return ctx.throw(400, ctx.t("A tool call is required."));
71
+ ctx.body = { eligible: await (0, import_SessionAutoApproval.isAutoApprovalEligible)(ctx, call) };
72
+ await next();
73
+ }
74
+ }
75
+ });
76
+ }
77
+ // Annotate the CommonJS export names for ESM import in node:
78
+ 0 && (module.exports = {
79
+ registerAgentAutoApprovalResource
80
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var hierarchical_routing_exports = {};
28
+ __export(hierarchical_routing_exports, {
29
+ registerHierarchicalRoutingResource: () => registerHierarchicalRoutingResource
30
+ });
31
+ module.exports = __toCommonJS(hierarchical_routing_exports);
32
+ var import_HierarchicalAgentRuntime = require("../services/HierarchicalAgentRuntime");
33
+ var import_ctx_utils = require("../utils/ctx-utils");
34
+ var import_resource_helpers = require("./resource-helpers");
35
+ function registerHierarchicalRoutingResource(plugin) {
36
+ const runtime = new import_HierarchicalAgentRuntime.HierarchicalAgentRuntime(plugin);
37
+ plugin.app.resource({
38
+ name: "agentHierarchy",
39
+ actions: {
40
+ async preview(ctx, next) {
41
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
42
+ const username = typeof values.username === "string" ? values.username.trim() : "";
43
+ const sessionId = typeof values.sessionId === "string" ? values.sessionId.trim() : "";
44
+ const specialistUsername = typeof values.specialistUsername === "string" ? values.specialistUsername.trim() : "";
45
+ if (!username || !sessionId) ctx.throw(400, ctx.t("A conversation and target employee are required."));
46
+ try {
47
+ (0, import_resource_helpers.requireAdminActor)(ctx);
48
+ ctx.body = { data: await runtime.preview(ctx, username, specialistUsername || void 0) };
49
+ } catch (error) {
50
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
51
+ }
52
+ await next();
53
+ }
54
+ }
55
+ });
56
+ }
57
+ // Annotate the CommonJS export names for ESM import in node:
58
+ 0 && (module.exports = {
59
+ registerHierarchicalRoutingResource
60
+ });
@@ -0,0 +1,133 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var AutoApprovalCheckpoint_exports = {};
28
+ __export(AutoApprovalCheckpoint_exports, {
29
+ autoApprovalCheckpoint: () => autoApprovalCheckpoint,
30
+ coordinateAutoApprovalDecision: () => coordinateAutoApprovalDecision,
31
+ enrollAutoApprovalCheckpoint: () => enrollAutoApprovalCheckpoint
32
+ });
33
+ module.exports = __toCommonJS(AutoApprovalCheckpoint_exports);
34
+ var import_node_crypto = require("node:crypto");
35
+ var import_record_utils = require("../utils/record-utils");
36
+ async function autoApprovalCheckpoint(ctx, call) {
37
+ var _a, _b;
38
+ const ownerId = Number((_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id);
39
+ if (!Number.isSafeInteger(ownerId) || ownerId <= 0) return void 0;
40
+ const conversation = await ctx.db.getRepository("aiConversations").findOne({
41
+ filter: { sessionId: call.sessionId, userId: ownerId }
42
+ });
43
+ if (!conversation || (0, import_record_utils.read)(conversation, "from") === "sub-agent") return void 0;
44
+ const username = (0, import_record_utils.read)(conversation, "aiEmployeeUsername");
45
+ if (typeof username !== "string" || !username) return void 0;
46
+ const message = await ctx.db.getRepository("aiMessages").findOne({
47
+ filter: { sessionId: call.sessionId, messageId: call.messageId, role: username }
48
+ });
49
+ const calls = (0, import_record_utils.read)(message, "toolCalls");
50
+ if (!Array.isArray(calls) || !calls.length) return void 0;
51
+ const callIds = calls.map((item) => (0, import_record_utils.asRecord)(item).id);
52
+ if (call.messageId.length > 100 || callIds.some((id) => typeof id !== "string" || !id) || new Set(callIds).size !== callIds.length || !callIds.includes(call.toolCallId))
53
+ return void 0;
54
+ const interruptId = (0, import_record_utils.asRecord)((0, import_record_utils.read)(message, "metadata")).interruptId;
55
+ if (typeof interruptId !== "string" || !interruptId) return void 0;
56
+ if (callIds.length === 1) return null;
57
+ const checkpointKey = (0, import_node_crypto.createHash)("sha256").update(JSON.stringify([ownerId, call.sessionId, call.messageId, interruptId])).digest("hex");
58
+ return {
59
+ checkpointKey,
60
+ ownerId,
61
+ sessionId: call.sessionId,
62
+ messageId: call.messageId,
63
+ interruptId,
64
+ callIds
65
+ };
66
+ }
67
+ async function enrollAutoApprovalCheckpoint(ctx, checkpoint) {
68
+ const model = ctx.db.getModel("agentAutoApprovalCheckpoints");
69
+ const where = { checkpointKey: checkpoint.checkpointKey };
70
+ if (await model.findOne({ where })) return;
71
+ try {
72
+ await model.create({
73
+ ...where,
74
+ ownerId: checkpoint.ownerId,
75
+ sessionId: checkpoint.sessionId,
76
+ messageId: checkpoint.messageId,
77
+ interruptId: checkpoint.interruptId,
78
+ status: "pending"
79
+ });
80
+ } catch (error) {
81
+ if (!(error instanceof Error) || error.name !== "SequelizeUniqueConstraintError") throw error;
82
+ if (!await model.findOne({ where })) throw error;
83
+ }
84
+ }
85
+ async function coordinateAutoApprovalDecision(ctx, checkpoint, call) {
86
+ const model = ctx.db.getModel("agentAutoApprovalCheckpoints");
87
+ const where = { checkpointKey: checkpoint.checkpointKey, ownerId: checkpoint.ownerId };
88
+ if (!await model.findOne({ where })) return;
89
+ const body = (0, import_record_utils.asRecord)(ctx.body);
90
+ const originalUpdated = body.updated;
91
+ const calls = Array.isArray(body.toolCalls) ? body.toolCalls.map(import_record_utils.asRecord) : [];
92
+ const ids = calls.map((item) => item.id);
93
+ const validSnapshot = calls.length === checkpoint.callIds.length && ids.every((id) => typeof id === "string" && checkpoint.callIds.includes(id)) && new Set(ids).size === ids.length && calls.every((item) => typeof item.willInterrupt === "boolean");
94
+ const current = await autoApprovalCheckpoint(ctx, call);
95
+ let sameCheckpoint = (current == null ? void 0 : current.checkpointKey) === checkpoint.checkpointKey && current.callIds.length === checkpoint.callIds.length && current.callIds.every((id) => checkpoint.callIds.includes(id));
96
+ const interruptedCalls = calls.filter((item) => item.willInterrupt === true);
97
+ const ready = validSnapshot && sameCheckpoint && interruptedCalls.some((item) => item.id === call.toolCallId) && interruptedCalls.every((item) => item.invokeStatus === "waiting");
98
+ let canFinalize = false;
99
+ if (originalUpdated === 1 && ready) {
100
+ canFinalize = await ctx.db.sequelize.transaction(async (transaction) => {
101
+ const message = await ctx.db.getModel("aiMessages").findOne({
102
+ where: { sessionId: checkpoint.sessionId, messageId: checkpoint.messageId },
103
+ transaction,
104
+ lock: transaction.LOCK.UPDATE
105
+ });
106
+ const messageCalls = (0, import_record_utils.read)(message, "toolCalls");
107
+ const messageIds = Array.isArray(messageCalls) ? messageCalls.map((item) => (0, import_record_utils.asRecord)(item).id) : [];
108
+ sameCheckpoint = (0, import_record_utils.asRecord)((0, import_record_utils.read)(message, "metadata")).interruptId === checkpoint.interruptId && messageIds.length === checkpoint.callIds.length && messageIds.every((id) => typeof id === "string" && checkpoint.callIds.includes(id)) && new Set(messageIds).size === messageIds.length;
109
+ if (!sameCheckpoint) return false;
110
+ const [updated] = await model.update(
111
+ { status: "issued" },
112
+ { where: { ...where, status: "pending" }, transaction }
113
+ );
114
+ return updated === 1;
115
+ });
116
+ }
117
+ ctx.body = {
118
+ ...body,
119
+ updated: canFinalize ? originalUpdated : 0,
120
+ agentAutoApprovalCheckpoint: {
121
+ interruptId: checkpoint.interruptId,
122
+ decisionRecorded: originalUpdated === 1,
123
+ canFinalize,
124
+ validSnapshot: validSnapshot && sameCheckpoint
125
+ }
126
+ };
127
+ }
128
+ // Annotate the CommonJS export names for ESM import in node:
129
+ 0 && (module.exports = {
130
+ autoApprovalCheckpoint,
131
+ coordinateAutoApprovalDecision,
132
+ enrollAutoApprovalCheckpoint
133
+ });
@@ -30,6 +30,8 @@ __export(CodeValidator_exports, {
30
30
  CodeValidator: () => CodeValidator
31
31
  });
32
32
  module.exports = __toCommonJS(CodeValidator_exports);
33
+ const NODE_ENV_PATTERN = /process\.env(?!\s*\.OUTPUT_DIR)/;
34
+ const REGISTRY_NODE_ENV_PATTERN = /process\.env(?!\s*\.OUTPUT_DIR)(?!\s*\.SKILL_INPUT_FILE(?![$\u200C\u200D\p{ID_Continue}\\]))/u;
33
35
  const DANGEROUS_NODE_PATTERNS = [
34
36
  { pattern: /require\s*\(\s*['"]child_process['"]\s*\)/, reason: "child_process module not allowed" },
35
37
  { pattern: /require\s*\(\s*['"]cluster['"]\s*\)/, reason: "cluster module not allowed" },
@@ -42,7 +44,7 @@ const DANGEROUS_NODE_PATTERNS = [
42
44
  { pattern: /require\s*\(\s*['"]inspector['"]\s*\)/, reason: "inspector module not allowed" },
43
45
  { pattern: /require\s*\(\s*['"]v8['"]\s*\)/, reason: "v8 module not allowed" },
44
46
  { pattern: /process\.exit/, reason: "process.exit not allowed" },
45
- { pattern: /process\.env(?!\s*\.OUTPUT_DIR)/, reason: "process.env access not allowed (use OUTPUT_DIR only)" },
47
+ { pattern: NODE_ENV_PATTERN, reason: "process.env access not allowed (use OUTPUT_DIR only)" },
46
48
  { pattern: /process\.kill/, reason: "process.kill not allowed" },
47
49
  { pattern: /process\.binding\s*\(/, reason: "process.binding not allowed" },
48
50
  { pattern: /\bglobalThis\b/, reason: "globalThis access not allowed" },
@@ -158,11 +160,13 @@ class CodeValidator {
158
160
  * Check code against forbidden patterns (dangerous modules/functions).
159
161
  * @throws CodeValidationError if a forbidden pattern is found.
160
162
  */
161
- validate(code, language) {
163
+ validate(code, language, options) {
162
164
  const patterns = language === "node" ? DANGEROUS_NODE_PATTERNS : DANGEROUS_PYTHON_PATTERNS;
163
165
  for (const { pattern, reason } of patterns) {
164
- if (pattern.test(code)) {
165
- throw new CodeValidationError(reason, pattern.source);
166
+ const checkedPattern = (options == null ? void 0 : options.allowSkillInputFile) && pattern === NODE_ENV_PATTERN ? REGISTRY_NODE_ENV_PATTERN : pattern;
167
+ if (checkedPattern.test(code)) {
168
+ const message = checkedPattern === REGISTRY_NODE_ENV_PATTERN ? "process.env access not allowed (use OUTPUT_DIR or SKILL_INPUT_FILE only)" : reason;
169
+ throw new CodeValidationError(message, checkedPattern.source);
166
170
  }
167
171
  }
168
172
  }
@@ -26,6 +26,7 @@ var __copyProps = (to, from, except, desc) => {
26
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
27
  var GovernanceAdmission_exports = {};
28
28
  __export(GovernanceAdmission_exports, {
29
+ authorizeDelegatedEmployee: () => authorizeDelegatedEmployee,
29
30
  createGovernanceAdmission: () => createGovernanceAdmission
30
31
  });
31
32
  module.exports = __toCommonJS(GovernanceAdmission_exports);
@@ -99,6 +100,64 @@ async function checkObservedQuota(ctx, policy, userId, departmentId) {
99
100
  if (checksTokens && tokens >= Number(settings.maxMonthlyTokens)) quotaError(ctx, "AI token quota reached.");
100
101
  if (checksCost && cost >= Number(settings.maxMonthlyCost)) quotaError(ctx, "AI cost quota reached.");
101
102
  }
103
+ async function authorizeDelegatedEmployee(context, employee, model) {
104
+ var _a, _b;
105
+ const userId = Number((_b = (_a = context.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id);
106
+ if (!Number.isSafeInteger(userId) || userId <= 0) quotaError(context, "Authentication is required.");
107
+ const employeeUsername = valueString((0, import_record_utils.read)(employee, "username"));
108
+ if (!employeeUsername || !model.llmService || !model.model) {
109
+ quotaError(context, "AI governance could not resolve the model.");
110
+ }
111
+ const service = new import_AgentGovernanceService.AgentGovernanceService(context.db);
112
+ let department;
113
+ try {
114
+ department = await (0, import_DepartmentAttribution.resolveUserDepartment)(context.db, userId);
115
+ } catch (error) {
116
+ const departmentPolicies = await context.db.getRepository("agentGovernancePolicies").count({
117
+ filter: { scope: "department", currentVersionId: { $ne: null } }
118
+ });
119
+ if (departmentPolicies) throw error;
120
+ department = { departmentId: null, status: "departments_unavailable" };
121
+ }
122
+ const policyRepo = context.db.getRepository("agentGovernancePolicies");
123
+ const configured = await policyRepo.count({ filter: { currentVersionId: { $ne: null } } });
124
+ const binding = await context.db.getRepository("agentGovernancePromptBindings").findOne({ filter: { userId, employeeUsername } });
125
+ if (!configured && !binding) return { userId, departmentId: department.departmentId };
126
+ if (department.status === "departments_unavailable") {
127
+ const departmentPolicies = await policyRepo.count({
128
+ filter: { scope: "department", currentVersionId: { $ne: null } }
129
+ });
130
+ if (departmentPolicies) quotaError(context, "AI governance cannot check department policies.");
131
+ }
132
+ const modelKey = `${model.llmService}:${model.model}`;
133
+ const policies = configured ? await service.activePolicies(userId, employeeUsername, department.departmentId, void 0, modelKey) : [];
134
+ for (const policy of policies) {
135
+ if (policy.scope === "employee" && policy.settings.systemPrompt !== void 0 && ((0, import_record_utils.read)(employee, "about") ?? null) !== policy.settings.systemPrompt) {
136
+ quotaError(context, "The managed AI employee prompt changed and needs administrator review.");
137
+ }
138
+ if (policy.settings.allow === false || policy.settings.allowedModels && !policy.settings.allowedModels.includes(modelKey)) {
139
+ quotaError(context, "Your AI employee or model is not allowed by governance policy.");
140
+ }
141
+ await checkObservedQuota(context, policy, userId, department.departmentId);
142
+ }
143
+ const prompt = await service.preview({ userId, employeeUsername });
144
+ if (prompt.instruction || binding) {
145
+ if (!prompt.instruction || prompt.promptMode !== "default" || !binding) {
146
+ quotaError(context, "Managed AI instructions need to be applied by an administrator.");
147
+ }
148
+ const expected = (0, import_node_crypto.createHash)("sha256").update(prompt.projectedPrompt).digest("hex");
149
+ const native = await context.db.getRepository("usersAiEmployees").findOne({ filter: { userId, aiEmployee: employeeUsername } });
150
+ const actual = (0, import_node_crypto.createHash)("sha256").update(valueString((0, import_record_utils.read)(native, "prompt"))).digest("hex");
151
+ const versions = prompt.policies.filter((policy) => {
152
+ var _a2;
153
+ return (_a2 = policy.settings.instruction) == null ? void 0 : _a2.trim();
154
+ }).map((policy) => ({ id: policy.id, versionId: policy.versionId }));
155
+ if (expected !== (0, import_record_utils.read)(binding, "contentHash") || expected !== actual || String(prompt.departmentId ?? "") !== String((0, import_record_utils.read)(binding, "departmentId") ?? "") || JSON.stringify(versions) !== JSON.stringify((0, import_record_utils.read)(binding, "policyVersions"))) {
156
+ quotaError(context, "Managed AI instructions need to be applied by an administrator.");
157
+ }
158
+ }
159
+ return { userId, departmentId: department.departmentId };
160
+ }
102
161
  function createGovernanceAdmission(plugin, enabled) {
103
162
  const service = new import_AgentGovernanceService.AgentGovernanceService(plugin.db);
104
163
  return async (context, next) => {
@@ -207,5 +266,6 @@ function createGovernanceAdmission(plugin, enabled) {
207
266
  }
208
267
  // Annotate the CommonJS export names for ESM import in node:
209
268
  0 && (module.exports = {
269
+ authorizeDelegatedEmployee,
210
270
  createGovernanceAdmission
211
271
  });
@@ -88,11 +88,13 @@ function mergeTimeouts(settings) {
88
88
  return timeouts;
89
89
  }
90
90
  function compileHarness(layers) {
91
+ var _a;
91
92
  if (!layers.length) {
92
93
  throw new Error("At least one harness layer is required.");
93
94
  }
94
95
  const parsed = layers.map((layer) => ({ source: layer.source, settings: (0, import_HarnessSchema.parseHarnessSettings)(layer.settings) }));
95
96
  const settings = parsed.map((layer) => layer.settings);
97
+ const routing = (_a = [...settings].reverse().find((layer) => layer.routing !== void 0)) == null ? void 0 : _a.routing;
96
98
  const effectNames = union(settings.map((layer) => Object.keys(layer.tools.effects)));
97
99
  const effects = Object.fromEntries(
98
100
  effectNames.map((name) => [
@@ -104,6 +106,7 @@ function compileHarness(layers) {
104
106
  );
105
107
  return {
106
108
  sources: parsed.map((layer) => layer.source),
109
+ ...routing === void 0 ? {} : { routing },
107
110
  tools: {
108
111
  allow: intersectRestrictions(settings.map((layer) => layer.tools.allow)),
109
112
  ask: union(settings.map((layer) => layer.tools.ask)),
@@ -39,6 +39,10 @@ const toolDecisionSchema = import_zod.z.enum(["allow", "ask", "deny"]);
39
39
  const toolEffectSchema = import_zod.z.enum(["read", "write", "external"]);
40
40
  const nullableLimit = import_zod.z.number().finite().nonnegative().nullable().default(null);
41
41
  const nullablePositiveLimit = import_zod.z.number().finite().positive().nullable().default(null);
42
+ const routingModelSchema = import_zod.z.object({
43
+ llmService: import_zod.z.string().trim().min(1),
44
+ model: import_zod.z.string().trim().min(1)
45
+ }).strict();
42
46
  const harnessSettingsSchema = import_zod.z.object({
43
47
  tools: import_zod.z.object({
44
48
  allow: import_zod.z.array(import_zod.z.string().min(1)).default([]),
@@ -98,7 +102,13 @@ const harnessSettingsSchema = import_zod.z.object({
98
102
  // Who span content may be shared with: full = inputs+outputs, feedback-only = outputs
99
103
  // only, disabled = no span content persisted at all.
100
104
  sharing: import_zod.z.enum(["full", "feedback-only", "disabled"]).default("full")
101
- }).default({})
105
+ }).default({}),
106
+ routing: import_zod.z.object({
107
+ models: import_zod.z.object({
108
+ primary: routingModelSchema.nullable().optional(),
109
+ fallback: import_zod.z.array(routingModelSchema).max(20).optional()
110
+ }).strict().optional()
111
+ }).strict().optional()
102
112
  }).strict();
103
113
  function isRecord(value) {
104
114
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -126,6 +136,7 @@ function normalizeHarnessSettings(value) {
126
136
  "limits",
127
137
  "isolation",
128
138
  "observability",
139
+ "routing",
129
140
  "nativeObserverEnabled",
130
141
  "memoryInjectionEnabled",
131
142
  "memoryScopes",
@@ -144,6 +155,7 @@ function normalizeHarnessSettings(value) {
144
155
  const unknownSettings = Object.fromEntries(Object.entries(source).filter(([key]) => !knownKeys.has(key)));
145
156
  return {
146
157
  ...unknownSettings,
158
+ ...source.routing === void 0 ? {} : { routing: source.routing },
147
159
  tools: {
148
160
  ...tools,
149
161
  allow: stringArray(tools.allow),