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
@@ -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,11 @@ 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");
77
85
  function normalizeOptionalString(value) {
78
86
  return typeof value === "string" ? value.trim() : "";
79
87
  }
@@ -174,6 +182,7 @@ async function validateAgentMemoryContextValues(ctx) {
174
182
  ctx.action.params.values = normalizedValues;
175
183
  }
176
184
  class PluginAgentOrchestratorServer extends import_server.Plugin {
185
+ hierarchyCancellation = new import_HierarchyRequestCancellation.HierarchyRequestCancellation(this);
177
186
  skillHub;
178
187
  registrySkillSnapshotService;
179
188
  registrySkillInstallationService;
@@ -208,6 +217,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
208
217
  this.app.agentRuntimeLifecycle = this.agentRuntimeLifecycle;
209
218
  }
210
219
  async beforeLoad() {
220
+ this.db.registerRepositories({ RoutingBindingRepository: import_RoutingBindingRepository.RoutingBindingRepository });
211
221
  this.db.import({ directory: import_path.default.resolve(__dirname, "collections") });
212
222
  this.db.addMigrations({
213
223
  namespace: this.name,
@@ -226,6 +236,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
226
236
  "agentMonitor:*",
227
237
  "agentUsage:*",
228
238
  "agentGovernance:*",
239
+ "agentHierarchy:*",
229
240
  "agentKnowledgeInsights:*",
230
241
  "agentMemoryContexts:*",
231
242
  "agentLoopRuns:*",
@@ -257,7 +268,23 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
257
268
  this.app.acl.allow("agentLoopApprovals", ["list", "get", "decide"], "loggedIn");
258
269
  this.app.acl.allow("agentLoopArtifactsView", ["list", "get"], "loggedIn");
259
270
  this.app.acl.allow("agentLoopEventsStream", ["stream"], "loggedIn");
271
+ this.app.acl.allow("agentAutoApproval", ["get", "set", "eligible"], "loggedIn");
260
272
  this.installGovernanceHooks();
273
+ this.app.resourceManager.use(
274
+ async (ctx, next) => {
275
+ var _a2;
276
+ if ([
277
+ "agentHierarchyInvocations",
278
+ "agentSessionAutoApprovals",
279
+ "agentAutoApprovalCheckpoints",
280
+ "agentRoutingGraphLocks"
281
+ ].includes(((_a2 = ctx.action) == null ? void 0 : _a2.resourceName) ?? "")) {
282
+ return ctx.throw(403, ctx.t("Hierarchy invocation records are not directly accessible."));
283
+ }
284
+ return next();
285
+ },
286
+ { tag: "orchestrator-hierarchy-record-protection", after: "acl" }
287
+ );
261
288
  this.app.resourceManager.use(
262
289
  async (ctx, next) => {
263
290
  const { resourceName, actionName } = ctx.action || {};
@@ -283,6 +310,26 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
283
310
  tag: "orchestrator-governance-admission",
284
311
  after: "acl"
285
312
  });
313
+ this.app.resourceManager.use(async (ctx, next) => (0, import_RoutingBindingValidation.validateRoutingBindingAction)(ctx, next), {
314
+ tag: "orchestrator-routing-binding-validation",
315
+ after: "acl"
316
+ });
317
+ this.app.resourceManager.use(async (ctx, next) => (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(ctx, next), {
318
+ tag: "orchestrator-hierarchy-enrollment",
319
+ after: "acl"
320
+ });
321
+ this.app.resourceManager.use(async (ctx, next) => (0, import_HierarchyEnrollmentGuard.guardManagedChildActions)(ctx, next), {
322
+ tag: "orchestrator-hierarchy-child-protection",
323
+ after: "orchestrator-hierarchy-enrollment"
324
+ });
325
+ this.app.resourceManager.use(async (ctx, next) => (0, import_SessionAutoApproval.guardAutoApprovalDecision)(ctx, next), {
326
+ tag: "orchestrator-auto-approval-decision",
327
+ after: "orchestrator-hierarchy-child-protection"
328
+ });
329
+ this.app.resourceManager.use(async (ctx, next) => this.hierarchyCancellation.middleware(ctx, next), {
330
+ tag: "orchestrator-hierarchy-cancellation",
331
+ after: "orchestrator-hierarchy-child-protection"
332
+ });
286
333
  this.app.resourceManager.use(
287
334
  async (ctx, next) => {
288
335
  const { resourceName, actionName } = ctx.action || {};
@@ -382,6 +429,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
382
429
  );
383
430
  const toolsManager = (0, import_ai_manager.getAIToolsManager)(this.app);
384
431
  toolsManager.registerTools((0, import_external_rag_search.createExternalRagSearchTool)(this));
432
+ toolsManager.registerTools((0, import_HierarchicalAgentRuntime.createHierarchicalAgentTools)(this));
385
433
  const patterns = new import_LoopPatternService.LoopPatternService(
386
434
  this.db,
387
435
  (0, import_loop_pattern_context.employeeHarnessResolver)(this),
@@ -398,6 +446,8 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
398
446
  (0, import_agent_loop_events_stream.registerAgentLoopEventsStreamResource)(this);
399
447
  (0, import_agent_harness_profile.registerAgentHarnessProfileResource)(this);
400
448
  (0, import_agent_governance.registerAgentGovernanceResource)(this);
449
+ (0, import_hierarchical_routing.registerHierarchicalRoutingResource)(this);
450
+ (0, import_agent_auto_approval.registerAgentAutoApprovalResource)(this);
401
451
  (0, import_agent_usage.registerAgentUsageResource)(this);
402
452
  (0, import_agent_monitor.registerAgentMonitorResource)(this);
403
453
  (0, import_agent_knowledge_insights.registerAgentKnowledgeInsightsResource)(this);
@@ -528,9 +578,11 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
528
578
  }
529
579
  async install() {
530
580
  await this.skillHub.install();
581
+ await (0, import_RoutingBindingRepository.initializeRoutingGraphLock)(this.db);
531
582
  await (0, import_ensure_indexes.ensureAgentOrchestratorIndexes)(this.db);
532
583
  }
533
584
  async upgrade() {
585
+ await (0, import_RoutingBindingRepository.initializeRoutingGraphLock)(this.db);
534
586
  await (0, import_ensure_indexes.ensureAgentOrchestratorIndexes)(this.db);
535
587
  }
536
588
  async afterEnable() {
@@ -541,6 +593,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
541
593
  async afterDisable() {
542
594
  var _a, _b, _c, _d;
543
595
  this.governanceEnabled = false;
596
+ this.hierarchyCancellation.abortAll();
544
597
  (_a = this.removeManagedPromptProtection) == null ? void 0 : _a.call(this);
545
598
  this.removeManagedPromptProtection = void 0;
546
599
  (_b = this.removeNativeUsageAttribution) == null ? void 0 : _b.call(this);
@@ -554,6 +607,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
554
607
  async beforeStop() {
555
608
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
556
609
  this.governanceEnabled = false;
610
+ this.hierarchyCancellation.abortAll();
557
611
  (_a = this.removeManagedPromptProtection) == null ? void 0 : _a.call(this);
558
612
  this.removeManagedPromptProtection = void 0;
559
613
  (_b = this.removeNativeUsageAttribution) == null ? void 0 : _b.call(this);
@@ -572,6 +626,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
572
626
  }
573
627
  async handleSyncMessage(message) {
574
628
  var _a, _b;
629
+ this.hierarchyCancellation.handleSyncMessage(message);
575
630
  await ((_a = this.loopScheduler) == null ? void 0 : _a.handleSyncMessage(message));
576
631
  await ((_b = this.loopWorker) == null ? void 0 : _b.handleSyncMessage(message));
577
632
  }
@@ -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),