plugin-agent-orchestrator 1.1.7 → 1.2.0

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 (413) hide show
  1. package/README.md +207 -204
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +2 -2
  5. package/client.js +1 -1
  6. package/dist/client/117.2e4cb0477da3db1f.js +10 -0
  7. package/dist/client/253.93deb9e0192e76a5.js +10 -0
  8. package/dist/client/325.8f7f509bdb35e142.js +10 -0
  9. package/dist/client/404.498d2d9516dd1dce.js +10 -0
  10. package/dist/client/418.6f01da17774a5a25.js +10 -0
  11. package/dist/client/53.774ff07505d521fa.js +10 -0
  12. package/dist/client/619.e342b0fa467d39ca.js +10 -0
  13. package/dist/client/627.fdd60bcc0f3a9cf6.js +10 -0
  14. package/dist/client/652.477e21bfff67bc1c.js +10 -0
  15. package/dist/client/981.e0546ffc34afedcd.js +10 -0
  16. package/dist/client/993.5d04b510835ab0d2.js +10 -0
  17. package/dist/client/index.js +1 -1
  18. package/dist/client-v2/117.ccf43ae8631f7d74.js +10 -0
  19. package/dist/client-v2/214.cdf76752053a8990.js +10 -0
  20. package/dist/client-v2/253.1198df22f5baf304.js +10 -0
  21. package/dist/client-v2/264.78887ff88f969467.js +10 -0
  22. package/dist/client-v2/325.fafe5a6e83ba9cb3.js +10 -0
  23. package/dist/client-v2/404.9ba964c28a151c81.js +10 -0
  24. package/dist/client-v2/{41.3deb9e57a0f64fc4.js → 41.b28cf7a675a603d1.js} +1 -1
  25. package/dist/client-v2/418.55b6b28cda8bb5f3.js +10 -0
  26. package/dist/client-v2/{53.349fff8db80b19d4.js → 53.282081f97e4308c6.js} +1 -1
  27. package/dist/client-v2/{619.0a2144aaffefe018.js → 619.8c03913873785fb6.js} +1 -1
  28. package/dist/client-v2/627.e16f4a0dd596c3e6.js +10 -0
  29. package/dist/client-v2/652.1a48364774d5383a.js +10 -0
  30. package/dist/client-v2/{70.ffff2997c10fd4b0.js → 70.9166ed70906d041f.js} +1 -1
  31. package/dist/client-v2/{981.e4a1f41cfc94a856.js → 981.a81521f0296c7db8.js} +1 -1
  32. package/dist/client-v2/993.ca5b28f1e2b4c1ef.js +10 -0
  33. package/dist/client-v2/index.js +1 -1
  34. package/dist/externalVersion.js +10 -7
  35. package/dist/locale/en-US.json +229 -1
  36. package/dist/locale/zh-CN.json +229 -1
  37. package/dist/node_modules/adm-zip/adm-zip.js +1 -1
  38. package/dist/node_modules/adm-zip/package.json +1 -1
  39. package/dist/node_modules/ajv/package.json +1 -1
  40. package/dist/node_modules/zod/index.cjs +1 -1
  41. package/dist/node_modules/zod/package.json +1 -1
  42. package/dist/server/collections/agent-execution-spans.js +145 -6
  43. package/dist/server/collections/agent-governance-audit-events.js +47 -0
  44. package/dist/server/collections/agent-governance-policies.js +47 -0
  45. package/dist/server/collections/agent-governance-policy-versions.js +48 -0
  46. package/dist/server/collections/agent-governance-prompt-bindings.js +50 -0
  47. package/dist/server/collections/agent-loop-runs.js +23 -5
  48. package/dist/server/migrations/20261110000000-add-usage-pricing-snapshots.js +117 -0
  49. package/dist/server/migrations/20261110010000-add-usage-department-attribution.js +54 -0
  50. package/dist/server/plugin.js +114 -33
  51. package/dist/server/resources/agent-governance.js +192 -0
  52. package/dist/server/resources/agent-harness-profile.js +11 -3
  53. package/dist/server/resources/agent-monitor.js +109 -339
  54. package/dist/server/resources/agent-usage.js +423 -0
  55. package/dist/server/resources/native-monitor-format.js +179 -0
  56. package/dist/server/resources/tracing.js +35 -12
  57. package/dist/server/services/AgentGovernanceService.js +500 -0
  58. package/dist/server/services/DepartmentAttribution.js +65 -0
  59. package/dist/server/services/ExecutionSpanService.js +96 -3
  60. package/dist/server/services/GovernanceAdmission.js +211 -0
  61. package/dist/server/services/HarnessCapabilities.js +118 -0
  62. package/dist/server/services/LoopBudgetService.js +29 -11
  63. package/dist/server/services/LoopRunRepository.js +15 -6
  64. package/dist/server/services/LoopRunStateMachine.js +18 -7
  65. package/dist/server/services/LoopTriggerService.js +1 -1
  66. package/dist/server/services/LoopWorkerService.js +66 -32
  67. package/dist/server/services/ManagedPromptProtection.js +99 -0
  68. package/dist/server/services/NativeAgentMonitorSyncService.js +584 -0
  69. package/dist/server/services/NativeSubAgentObserver.js +141 -508
  70. package/dist/server/services/NativeUsageAttribution.js +97 -0
  71. package/dist/server/services/TokenTracker.js +787 -104
  72. package/dist/server/services/TracingRetentionPolicy.js +66 -0
  73. package/dist/server/services/VerificationService.js +18 -8
  74. package/dist/server/skill-hub/sandbox-config.json +6 -6
  75. package/dist/server/utils/ensure-indexes.js +14 -5
  76. package/package.json +63 -53
  77. package/server.d.ts +2 -2
  78. package/server.js +1 -1
  79. package/src/client/AgentRunsTab.tsx +2 -2
  80. package/src/client/ApprovalsTab.tsx +2 -2
  81. package/src/client/HarnessProfilesTab.tsx +2 -2
  82. package/src/client/OrchestratorSettings.tsx +152 -152
  83. package/src/client/SkillPages.tsx +41 -0
  84. package/src/client/__tests__/embedded-settings.test.tsx +232 -0
  85. package/src/client/hooks/useRunEventStream.ts +76 -76
  86. package/src/client/index.tsx +2 -2
  87. package/src/client/plugin.tsx +76 -32
  88. package/src/client/skill-hub/components/ExecutionHistory.tsx +200 -200
  89. package/src/client/skill-hub/components/GitSkillImport.tsx +562 -562
  90. package/src/client/skill-hub/components/LoopSettings.tsx +331 -331
  91. package/src/client/skill-hub/components/SkillEditor.tsx +460 -460
  92. package/src/client/skill-hub/components/SkillManager.tsx +194 -194
  93. package/src/client/skill-hub/components/SkillMetrics.tsx +162 -162
  94. package/src/client/skill-hub/components/SkillTestPanel.tsx +141 -141
  95. package/src/client/skill-hub/index.tsx +6 -6
  96. package/src/client/skill-hub/locale.ts +16 -16
  97. package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +132 -132
  98. package/src/client/skill-hub/tools/SkillHubCard.tsx +104 -104
  99. package/src/client/skill-hub/tools/loopTemplates.ts +52 -52
  100. package/src/client/skill-hub/tools/registerSkillLoopCards.ts +71 -71
  101. package/src/client/skill-hub/utils/jsonFields.ts +41 -41
  102. package/src/client-v2/__tests__/embedded-settings.test.tsx +193 -0
  103. package/src/client-v2/components/AIEmployeeSelect.tsx +47 -47
  104. package/src/client-v2/components/AIEmployeesContext.tsx +97 -97
  105. package/src/client-v2/components/AgentBindingsTab.tsx +269 -269
  106. package/src/client-v2/components/AgentRunsTab.tsx +92 -83
  107. package/src/client-v2/components/ApprovalsTab.tsx +337 -337
  108. package/src/client-v2/components/EmployeeGovernanceTab.tsx +702 -0
  109. package/src/client-v2/components/HarnessProfilesTab.tsx +704 -541
  110. package/src/client-v2/components/KnowledgeAccessTab.tsx +116 -116
  111. package/src/client-v2/components/RetrievalTraceTab.tsx +162 -162
  112. package/src/client-v2/components/UsageGovernanceTab.tsx +386 -0
  113. package/src/client-v2/index.tsx +1 -1
  114. package/src/client-v2/pages/AgentBindingsPage.tsx +22 -13
  115. package/src/client-v2/pages/ApprovalsPage.tsx +19 -10
  116. package/src/client-v2/pages/EmployeeGovernancePage.tsx +22 -0
  117. package/src/client-v2/pages/ExecutionHistoryPage.tsx +19 -10
  118. package/src/client-v2/pages/HarnessProfilesPage.tsx +19 -10
  119. package/src/client-v2/pages/KnowledgeAccessPage.tsx +19 -10
  120. package/src/client-v2/pages/LoopSettingsPage.tsx +19 -10
  121. package/src/client-v2/pages/MemoryInspectorPage.tsx +22 -13
  122. package/src/client-v2/pages/RetrievalTracePage.tsx +19 -10
  123. package/src/client-v2/pages/RulesPage.tsx +22 -13
  124. package/src/client-v2/pages/SkillDefinitionsPage.tsx +19 -10
  125. package/src/client-v2/pages/SkillMetricsPage.tsx +19 -10
  126. package/src/client-v2/pages/TracingPage.tsx +22 -13
  127. package/src/client-v2/pages/UsageGovernancePage.tsx +22 -0
  128. package/src/client-v2/plugin.tsx +139 -99
  129. package/src/client-v2/skill-hub/components/ExecutionHistory.tsx +196 -196
  130. package/src/client-v2/skill-hub/components/FileLinkList.tsx +37 -37
  131. package/src/client-v2/skill-hub/components/GitSkillImport.tsx +539 -539
  132. package/src/client-v2/skill-hub/components/LoopSettings.tsx +331 -331
  133. package/src/client-v2/skill-hub/components/SkillEditor.tsx +453 -453
  134. package/src/client-v2/skill-hub/components/SkillManager.tsx +191 -174
  135. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +162 -162
  136. package/src/client-v2/skill-hub/components/SkillTestPanel.tsx +135 -135
  137. package/src/client-v2/skill-hub/locale.ts +13 -13
  138. package/src/client-v2/skill-hub/tools/InteractionSchemasProvider.tsx +62 -0
  139. package/src/client-v2/skill-hub/tools/SkillHubCard.tsx +104 -0
  140. package/src/client-v2/skill-hub/tools/__tests__/interactions.test.ts +110 -0
  141. package/src/client-v2/skill-hub/tools/interactions.ts +128 -0
  142. package/src/client-v2/skill-hub/tools/loopTemplates.ts +52 -52
  143. package/src/client-v2/skill-hub/utils/jsonFields.ts +41 -41
  144. package/src/client-v2/utils/jsonFields.ts +41 -41
  145. package/src/index.ts +2 -2
  146. package/src/locale/en-US.json +229 -1
  147. package/src/locale/zh-CN.json +229 -1
  148. package/src/server/__tests__/agent-execution-context.test.ts +18 -18
  149. package/src/server/__tests__/agent-governance.integration.test.ts +392 -0
  150. package/src/server/__tests__/agent-knowledge-insights.test.ts +123 -123
  151. package/src/server/__tests__/agent-monitor-acl.integration.test.ts +274 -0
  152. package/src/server/__tests__/agent-registry-service.test.ts +147 -147
  153. package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -46
  154. package/src/server/__tests__/agent-usage-report.integration.test.ts +342 -0
  155. package/src/server/__tests__/code-validator.test.ts +63 -63
  156. package/src/server/__tests__/external-rag-search.test.ts +107 -107
  157. package/src/server/__tests__/harness-capabilities.test.ts +95 -0
  158. package/src/server/__tests__/harness-compiler.test.ts +214 -214
  159. package/src/server/__tests__/harness-profile-service.test.ts +167 -167
  160. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -293
  161. package/src/server/__tests__/harness-tool-plan.test.ts +182 -172
  162. package/src/server/__tests__/input-schema-validator.test.ts +26 -26
  163. package/src/server/__tests__/loop-approval-decision.test.ts +577 -512
  164. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -258
  165. package/src/server/__tests__/loop-budget-service.test.ts +36 -0
  166. package/src/server/__tests__/loop-pattern-schema.test.ts +73 -73
  167. package/src/server/__tests__/loop-run-repository.test.ts +32 -0
  168. package/src/server/__tests__/loop-run-state-machine.test.ts +101 -101
  169. package/src/server/__tests__/loop-trigger-service.test.ts +192 -148
  170. package/src/server/__tests__/loop-worker-claim.test.ts +72 -9
  171. package/src/server/__tests__/loop-worker-execution.test.ts +382 -317
  172. package/src/server/__tests__/native-agent-monitor-sync.test.ts +350 -0
  173. package/src/server/__tests__/native-sub-agent-observer.test.ts +470 -662
  174. package/src/server/__tests__/native-usage-attribution.integration.test.ts +175 -0
  175. package/src/server/__tests__/skill-access-service.test.ts +64 -64
  176. package/src/server/__tests__/skill-execute.test.ts +70 -70
  177. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -140
  178. package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -15
  179. package/src/server/__tests__/skill-settings.test.ts +63 -63
  180. package/src/server/__tests__/skill-tool-name.test.ts +23 -23
  181. package/src/server/__tests__/token-tracker.test.ts +639 -0
  182. package/src/server/__tests__/tool-loop-detection.test.ts +276 -276
  183. package/src/server/__tests__/tracing-retention-policy.test.ts +37 -0
  184. package/src/server/__tests__/usage-ledger.integration.test.ts +194 -0
  185. package/src/server/collections/agent-execution-spans.ts +393 -245
  186. package/src/server/collections/agent-governance-audit-events.ts +26 -0
  187. package/src/server/collections/agent-governance-policies.ts +26 -0
  188. package/src/server/collections/agent-governance-policy-versions.ts +27 -0
  189. package/src/server/collections/agent-governance-prompt-bindings.ts +29 -0
  190. package/src/server/collections/agent-loop-action-approvals.ts +39 -39
  191. package/src/server/collections/agent-loop-runs.ts +396 -369
  192. package/src/server/collections/agent-loop-steps.ts +220 -220
  193. package/src/server/collections/agent-memory-contexts.ts +95 -95
  194. package/src/server/collections/orchestrator-config.ts +87 -87
  195. package/src/server/collections/orchestrator-logs.ts +116 -116
  196. package/src/server/collections/skill-definitions.ts +159 -159
  197. package/src/server/collections/skill-executions.ts +154 -154
  198. package/src/server/collections/skill-loop-configs.ts +65 -65
  199. package/src/server/collections/skill-metrics.ts +36 -36
  200. package/src/server/collections/skill-registry-installations.ts +41 -41
  201. package/src/server/collections/skill-worker-configs.ts +86 -86
  202. package/src/server/index.ts +1 -1
  203. package/src/server/migrations/20260423000000-add-progress-fields.ts +50 -50
  204. package/src/server/migrations/20260425000000-add-interaction-schema.ts +37 -37
  205. package/src/server/migrations/20260427000000-add-tracing-detail-fields.ts +41 -41
  206. package/src/server/migrations/20260427000001-change-other-json-to-text.ts +61 -61
  207. package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +145 -145
  208. package/src/server/migrations/20260601000000-add-token-fields.ts +89 -89
  209. package/src/server/migrations/20260615000000-normalize-ai-employee-tool-bindings.ts +39 -39
  210. package/src/server/migrations/20260621000000-native-policy-profile-defaults.ts +190 -190
  211. package/src/server/migrations/20260727000000-remove-unused-knowledge-scopes.ts +25 -25
  212. package/src/server/migrations/20260727010000-backfill-skill-tool-names.ts +45 -45
  213. package/src/server/migrations/20261110000000-add-usage-pricing-snapshots.ts +117 -0
  214. package/src/server/migrations/20261110010000-add-usage-department-attribution.ts +35 -0
  215. package/src/server/plugin.ts +674 -573
  216. package/src/server/resources/agent-governance.ts +168 -0
  217. package/src/server/resources/agent-harness-profile.ts +110 -94
  218. package/src/server/resources/agent-knowledge-insights.ts +306 -306
  219. package/src/server/resources/agent-loop-approval.ts +84 -84
  220. package/src/server/resources/agent-loop-events-stream.ts +108 -108
  221. package/src/server/resources/agent-loop.ts +252 -252
  222. package/src/server/resources/agent-monitor.ts +215 -482
  223. package/src/server/resources/agent-usage.ts +420 -0
  224. package/src/server/resources/native-monitor-format.ts +157 -0
  225. package/src/server/resources/tracing.ts +303 -267
  226. package/src/server/services/AgentExecutionContext.ts +23 -23
  227. package/src/server/services/AgentGovernanceService.ts +548 -0
  228. package/src/server/services/AgentMemoryContextService.ts +344 -344
  229. package/src/server/services/AgentRegistryService.ts +220 -220
  230. package/src/server/services/AgentRuntimeLifecycle.ts +64 -64
  231. package/src/server/services/CodeValidator.ts +238 -238
  232. package/src/server/services/DepartmentAttribution.ts +54 -0
  233. package/src/server/services/DurableCircuitBreakerService.ts +235 -235
  234. package/src/server/services/ExecutionSpanService.ts +278 -146
  235. package/src/server/services/FileManager.ts +159 -159
  236. package/src/server/services/GovernanceAdmission.ts +239 -0
  237. package/src/server/services/HarnessCapabilities.ts +119 -0
  238. package/src/server/services/HarnessCompiler.ts +170 -170
  239. package/src/server/services/HarnessProfileService.ts +235 -235
  240. package/src/server/services/HarnessSchema.ts +194 -194
  241. package/src/server/services/InputSchemaValidator.ts +44 -44
  242. package/src/server/services/LoopBudgetService.ts +332 -271
  243. package/src/server/services/LoopControlService.ts +120 -120
  244. package/src/server/services/LoopPatternSchema.ts +231 -231
  245. package/src/server/services/LoopPatternService.ts +171 -171
  246. package/src/server/services/LoopRunRepository.ts +350 -332
  247. package/src/server/services/LoopRunStateMachine.ts +545 -525
  248. package/src/server/services/LoopSchedulerService.ts +195 -195
  249. package/src/server/services/LoopTriggerService.ts +169 -159
  250. package/src/server/services/LoopWorkerService.ts +986 -912
  251. package/src/server/services/ManagedPromptProtection.ts +88 -0
  252. package/src/server/services/NativeAgentMonitorSyncService.ts +691 -0
  253. package/src/server/services/NativeSubAgentObserver.ts +331 -757
  254. package/src/server/services/NativeUsageAttribution.ts +98 -0
  255. package/src/server/services/PathLockService.ts +317 -317
  256. package/src/server/services/PluginAiRuntimeAdapter.ts +387 -387
  257. package/src/server/services/RunEventBus.ts +58 -58
  258. package/src/server/services/SandboxRunner.ts +492 -492
  259. package/src/server/services/SkillAccessService.ts +175 -175
  260. package/src/server/services/SkillManager.ts +585 -585
  261. package/src/server/services/SkillRepositoryService.ts +236 -236
  262. package/src/server/services/TokenTracker.ts +1158 -287
  263. package/src/server/services/ToolLoopDetectionService.ts +210 -210
  264. package/src/server/services/TracingRetentionPolicy.ts +56 -0
  265. package/src/server/services/VerificationSchema.ts +31 -31
  266. package/src/server/services/VerificationService.ts +332 -313
  267. package/src/server/services/WorkerEnvManager.ts +198 -198
  268. package/src/server/services/__tests__/SkillRepositoryService.test.ts +33 -33
  269. package/src/server/services/harness-runtime-policy.ts +134 -134
  270. package/src/server/services/pythonGuardTemplate.ts +87 -87
  271. package/src/server/services/sandboxCapabilities.ts +348 -348
  272. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +563 -563
  273. package/src/server/skill-hub/actions/git-import.ts +936 -936
  274. package/src/server/skill-hub/mcp/McpController.ts +107 -107
  275. package/src/server/skill-hub/middlewares/git-import-request-method-policy.ts +51 -51
  276. package/src/server/skill-hub/plugin.ts +1232 -1232
  277. package/src/server/skill-hub/sandbox-config.json +6 -6
  278. package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +281 -281
  279. package/src/server/skill-hub/services/__tests__/RegistrySkillInstallationService.test.ts +295 -295
  280. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +568 -568
  281. package/src/server/skill-hub/utils/json-fields.ts +57 -57
  282. package/src/server/tools/delegate-task.ts +30 -30
  283. package/src/server/tools/external-rag-search.ts +329 -329
  284. package/src/server/tools/skill-execute.ts +216 -216
  285. package/src/server/types.ts +21 -21
  286. package/src/server/utils/ai-manager.ts +24 -24
  287. package/src/server/utils/ctx-utils.ts +132 -132
  288. package/src/server/utils/ensure-indexes.ts +119 -96
  289. package/src/server/utils/ha-lock.ts +80 -80
  290. package/src/server/utils/loop-pattern-context.ts +84 -84
  291. package/src/server/utils/record-utils.ts +19 -19
  292. package/src/server/utils/skill-settings.ts +135 -135
  293. package/src/server/utils/skill-tool-name.ts +58 -58
  294. package/dist/client-v2/117.7565cff57c39318a.js +0 -10
  295. package/dist/client-v2/214.106635011859dede.js +0 -10
  296. package/dist/client-v2/253.59577b40d9875be0.js +0 -10
  297. package/dist/client-v2/264.7ed8bee71fa5935c.js +0 -10
  298. package/dist/client-v2/418.41ed200e7d6da332.js +0 -10
  299. package/dist/client-v2/794.a67a2614405ba627.js +0 -10
  300. package/dist/client-v2/993.b0688fdc5ccb000a.js +0 -10
  301. package/dist/node_modules/simple-git/dist/cjs/index.js +0 -7399
  302. package/dist/node_modules/simple-git/dist/esm/index.js +0 -4745
  303. package/dist/node_modules/simple-git/dist/esm/package.json +0 -3
  304. package/dist/node_modules/simple-git/dist/src/lib/api.d.ts +0 -13
  305. package/dist/node_modules/simple-git/dist/src/lib/args/log-format.d.ts +0 -9
  306. package/dist/node_modules/simple-git/dist/src/lib/errors/git-construct-error.d.ts +0 -15
  307. package/dist/node_modules/simple-git/dist/src/lib/errors/git-error.d.ts +0 -30
  308. package/dist/node_modules/simple-git/dist/src/lib/errors/git-plugin-error.d.ts +0 -7
  309. package/dist/node_modules/simple-git/dist/src/lib/errors/git-response-error.d.ts +0 -32
  310. package/dist/node_modules/simple-git/dist/src/lib/errors/task-configuration-error.d.ts +0 -12
  311. package/dist/node_modules/simple-git/dist/src/lib/git-factory.d.ts +0 -15
  312. package/dist/node_modules/simple-git/dist/src/lib/git-logger.d.ts +0 -21
  313. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-branch-delete.d.ts +0 -5
  314. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-branch.d.ts +0 -2
  315. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-commit.d.ts +0 -2
  316. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-diff-summary.d.ts +0 -3
  317. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-fetch.d.ts +0 -2
  318. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-list-log-summary.d.ts +0 -6
  319. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-merge.d.ts +0 -11
  320. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-move.d.ts +0 -2
  321. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-pull.d.ts +0 -6
  322. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-push.d.ts +0 -4
  323. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-remote-messages.d.ts +0 -5
  324. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-remote-objects.d.ts +0 -3
  325. package/dist/node_modules/simple-git/dist/src/lib/plugins/abort-plugin.d.ts +0 -3
  326. package/dist/node_modules/simple-git/dist/src/lib/plugins/block-unsafe-operations-plugin.d.ts +0 -3
  327. package/dist/node_modules/simple-git/dist/src/lib/plugins/command-config-prefixing-plugin.d.ts +0 -2
  328. package/dist/node_modules/simple-git/dist/src/lib/plugins/completion-detection.plugin.d.ts +0 -3
  329. package/dist/node_modules/simple-git/dist/src/lib/plugins/custom-binary.plugin.d.ts +0 -3
  330. package/dist/node_modules/simple-git/dist/src/lib/plugins/error-detection.plugin.d.ts +0 -7
  331. package/dist/node_modules/simple-git/dist/src/lib/plugins/index.d.ts +0 -11
  332. package/dist/node_modules/simple-git/dist/src/lib/plugins/plugin-store.d.ts +0 -11
  333. package/dist/node_modules/simple-git/dist/src/lib/plugins/progress-monitor-plugin.d.ts +0 -3
  334. package/dist/node_modules/simple-git/dist/src/lib/plugins/simple-git-plugin.d.ts +0 -48
  335. package/dist/node_modules/simple-git/dist/src/lib/plugins/spawn-options-plugin.d.ts +0 -3
  336. package/dist/node_modules/simple-git/dist/src/lib/plugins/suffix-paths.plugin.d.ts +0 -2
  337. package/dist/node_modules/simple-git/dist/src/lib/plugins/timout-plugin.d.ts +0 -3
  338. package/dist/node_modules/simple-git/dist/src/lib/responses/BranchDeleteSummary.d.ts +0 -12
  339. package/dist/node_modules/simple-git/dist/src/lib/responses/BranchSummary.d.ts +0 -14
  340. package/dist/node_modules/simple-git/dist/src/lib/responses/CheckIgnore.d.ts +0 -4
  341. package/dist/node_modules/simple-git/dist/src/lib/responses/CleanSummary.d.ts +0 -9
  342. package/dist/node_modules/simple-git/dist/src/lib/responses/ConfigList.d.ts +0 -13
  343. package/dist/node_modules/simple-git/dist/src/lib/responses/DiffSummary.d.ts +0 -10
  344. package/dist/node_modules/simple-git/dist/src/lib/responses/FileStatusSummary.d.ts +0 -9
  345. package/dist/node_modules/simple-git/dist/src/lib/responses/GetRemoteSummary.d.ts +0 -11
  346. package/dist/node_modules/simple-git/dist/src/lib/responses/InitSummary.d.ts +0 -9
  347. package/dist/node_modules/simple-git/dist/src/lib/responses/MergeSummary.d.ts +0 -16
  348. package/dist/node_modules/simple-git/dist/src/lib/responses/PullSummary.d.ts +0 -25
  349. package/dist/node_modules/simple-git/dist/src/lib/responses/StatusSummary.d.ts +0 -19
  350. package/dist/node_modules/simple-git/dist/src/lib/responses/TagList.d.ts +0 -7
  351. package/dist/node_modules/simple-git/dist/src/lib/runners/git-executor-chain.d.ts +0 -25
  352. package/dist/node_modules/simple-git/dist/src/lib/runners/git-executor.d.ts +0 -14
  353. package/dist/node_modules/simple-git/dist/src/lib/runners/promise-wrapped.d.ts +0 -2
  354. package/dist/node_modules/simple-git/dist/src/lib/runners/scheduler.d.ts +0 -11
  355. package/dist/node_modules/simple-git/dist/src/lib/runners/tasks-pending-queue.d.ts +0 -23
  356. package/dist/node_modules/simple-git/dist/src/lib/simple-git-api.d.ts +0 -20
  357. package/dist/node_modules/simple-git/dist/src/lib/task-callback.d.ts +0 -2
  358. package/dist/node_modules/simple-git/dist/src/lib/tasks/apply-patch.d.ts +0 -3
  359. package/dist/node_modules/simple-git/dist/src/lib/tasks/branch.d.ts +0 -7
  360. package/dist/node_modules/simple-git/dist/src/lib/tasks/change-working-directory.d.ts +0 -2
  361. package/dist/node_modules/simple-git/dist/src/lib/tasks/check-ignore.d.ts +0 -2
  362. package/dist/node_modules/simple-git/dist/src/lib/tasks/check-is-repo.d.ts +0 -9
  363. package/dist/node_modules/simple-git/dist/src/lib/tasks/checkout.d.ts +0 -2
  364. package/dist/node_modules/simple-git/dist/src/lib/tasks/clean.d.ts +0 -25
  365. package/dist/node_modules/simple-git/dist/src/lib/tasks/clone.d.ts +0 -9
  366. package/dist/node_modules/simple-git/dist/src/lib/tasks/commit.d.ts +0 -4
  367. package/dist/node_modules/simple-git/dist/src/lib/tasks/config.d.ts +0 -8
  368. package/dist/node_modules/simple-git/dist/src/lib/tasks/count-objects.d.ts +0 -12
  369. package/dist/node_modules/simple-git/dist/src/lib/tasks/diff-name-status.d.ts +0 -12
  370. package/dist/node_modules/simple-git/dist/src/lib/tasks/diff.d.ts +0 -5
  371. package/dist/node_modules/simple-git/dist/src/lib/tasks/fetch.d.ts +0 -4
  372. package/dist/node_modules/simple-git/dist/src/lib/tasks/first-commit.d.ts +0 -2
  373. package/dist/node_modules/simple-git/dist/src/lib/tasks/grep.d.ts +0 -12
  374. package/dist/node_modules/simple-git/dist/src/lib/tasks/hash-object.d.ts +0 -5
  375. package/dist/node_modules/simple-git/dist/src/lib/tasks/init.d.ts +0 -3
  376. package/dist/node_modules/simple-git/dist/src/lib/tasks/log.d.ts +0 -32
  377. package/dist/node_modules/simple-git/dist/src/lib/tasks/merge.d.ts +0 -4
  378. package/dist/node_modules/simple-git/dist/src/lib/tasks/move.d.ts +0 -3
  379. package/dist/node_modules/simple-git/dist/src/lib/tasks/pull.d.ts +0 -3
  380. package/dist/node_modules/simple-git/dist/src/lib/tasks/push.d.ts +0 -9
  381. package/dist/node_modules/simple-git/dist/src/lib/tasks/remote.d.ts +0 -8
  382. package/dist/node_modules/simple-git/dist/src/lib/tasks/reset.d.ts +0 -11
  383. package/dist/node_modules/simple-git/dist/src/lib/tasks/show.d.ts +0 -2
  384. package/dist/node_modules/simple-git/dist/src/lib/tasks/stash-list.d.ts +0 -4
  385. package/dist/node_modules/simple-git/dist/src/lib/tasks/status.d.ts +0 -3
  386. package/dist/node_modules/simple-git/dist/src/lib/tasks/sub-module.d.ts +0 -5
  387. package/dist/node_modules/simple-git/dist/src/lib/tasks/tag.d.ts +0 -18
  388. package/dist/node_modules/simple-git/dist/src/lib/tasks/task.d.ts +0 -14
  389. package/dist/node_modules/simple-git/dist/src/lib/tasks/version.d.ts +0 -9
  390. package/dist/node_modules/simple-git/dist/src/lib/types/handlers.d.ts +0 -21
  391. package/dist/node_modules/simple-git/dist/src/lib/types/index.d.ts +0 -136
  392. package/dist/node_modules/simple-git/dist/src/lib/types/tasks.d.ts +0 -19
  393. package/dist/node_modules/simple-git/dist/src/lib/utils/argument-filters.d.ts +0 -14
  394. package/dist/node_modules/simple-git/dist/src/lib/utils/exit-codes.d.ts +0 -10
  395. package/dist/node_modules/simple-git/dist/src/lib/utils/git-output-streams.d.ts +0 -7
  396. package/dist/node_modules/simple-git/dist/src/lib/utils/index.d.ts +0 -8
  397. package/dist/node_modules/simple-git/dist/src/lib/utils/line-parser.d.ts +0 -15
  398. package/dist/node_modules/simple-git/dist/src/lib/utils/simple-git-options.d.ts +0 -2
  399. package/dist/node_modules/simple-git/dist/src/lib/utils/task-options.d.ts +0 -13
  400. package/dist/node_modules/simple-git/dist/src/lib/utils/task-parser.d.ts +0 -5
  401. package/dist/node_modules/simple-git/dist/src/lib/utils/util.d.ts +0 -47
  402. package/dist/node_modules/simple-git/dist/typings/errors.d.ts +0 -5
  403. package/dist/node_modules/simple-git/dist/typings/index.d.ts +0 -14
  404. package/dist/node_modules/simple-git/dist/typings/response.d.ts +0 -556
  405. package/dist/node_modules/simple-git/dist/typings/simple-git.d.ts +0 -1033
  406. package/dist/node_modules/simple-git/dist/typings/types.d.ts +0 -22
  407. package/dist/node_modules/simple-git/node_modules/debug/package.json +0 -64
  408. package/dist/node_modules/simple-git/node_modules/debug/src/browser.js +0 -272
  409. package/dist/node_modules/simple-git/node_modules/debug/src/common.js +0 -292
  410. package/dist/node_modules/simple-git/node_modules/debug/src/index.js +0 -10
  411. package/dist/node_modules/simple-git/node_modules/debug/src/node.js +0 -263
  412. package/dist/node_modules/simple-git/package.json +0 -1
  413. package/dist/node_modules/simple-git/promise.js +0 -17
package/README.md CHANGED
@@ -1,204 +1,207 @@
1
- # plugin-agent-orchestrator
2
-
3
- ## Overview
4
-
5
- Agent orchestration layer for NocoBase AI Employees (plugin-ai). The plugin provides three main subsystems:
6
-
7
- 1. **Agent Loop Control Plane** — durable, policy-governed multi-step runs with a leader/maker/verifier role model, cron/event/manual triggers, budgets, approvals, and independent verification.
8
- 2. **Harness (Policy Profiles)** — versioned, tag-addressed policy bundles that constrain what each role may do (tools, memory, delegation, limits, isolation, observability), compiled layer-by-layer with most-restrictive-wins semantics.
9
- 3. **Skill Hub** — sandboxed Python/Node.js skills that AI employees can execute as tools, with async execution, human-in-the-loop review, an MCP-style surface, and Git/registry import.
10
-
11
- On top of these, the plugin observes native sub-agent dispatching from plugin-ai, records a unified execution-span tree, injects agent memory context, and exposes an external RAG search tool.
12
-
13
- ## Agent Loop Control Plane
14
-
15
- ### Patterns
16
-
17
- A loop pattern (`agentLoopPatterns`) defines a repeatable unit of autonomous work:
18
-
19
- - `key`, `goalTemplate` — identity and the goal rendered for each run.
20
- - `autonomyLevel` — `L1` (supervised), `L2`, `L3` (autonomous). L2/L3 require repository identity (`repositoryKey`, `repositoryRoot`, `baseRef`, `actingOn[]`) and worktree isolation (`policy.harness.isolation.requireWorktree`).
21
- - `triggerType` — `manual`, `cron` (`cronExpression` + `timezone`), or `event` (`eventKey`).
22
- - Role bindings — `leaderUsername`, `makerUsernames[]`, `verifierUsername` (verifier must differ from leader and makers).
23
- - Per-role harness tags — `leaderHarnessTag` / `makerHarnessTag` (default `default`), `verifierHarnessTag` (default `safe`).
24
- - `policy` — concurrency, per-run/daily budgets (invocations, tool calls, delegations, verifications, tokens, cost), circuit-breaker limits, path restrictions (`maxFiles`, deny list), action approval settings (`autoAllowlist`, approvers, timeout), tool-loop detection thresholds (`warnAt`/`blockAt`/`escalateAt`), and required verification checks.
25
-
26
- ### Run lifecycle
27
-
28
- `LoopTriggerService` compiles the pattern (including layered harness compilation), snapshots role bindings and harness settings onto the run row, and enqueues it. `LoopWorkerService` claims queued runs with a lease + heartbeat, acquires path locks on `actingOn`, then drives the run:
29
-
30
- `queued → preparing → waiting_lock → running → waiting_approval → verifying → waiting_human → succeeded | failed | canceled` (plus `paused`, `blocked`).
31
-
32
- - **Leader** invocation plans the work but changes nothing.
33
- - **Maker** invocations execute the plan, each under its own compiled harness.
34
- - Tool calls gated as `ask` park the run in `waiting_approval` until the approval row is resolved via `agentLoopApprovals:decide` (approve — optionally substituting an edited input — or reject).
35
- - **Tool-loop detection** (`ToolLoopDetectionService`, active in both worker and verifier) guards against repeated identical tool calls: `warnAt` injects a notice into the run, `blockAt` refuses the call, `escalateAt` escalates the run for human review.
36
- - **Verifier** (via `VerificationService`) runs an independent pass and returns a JSON verdict: `pass` → `succeeded` (L1) or `waiting_human` (L2/L3); `reject` → `failed`; `escalate` → `waiting_human`. Required checks and artifact evidence ownership are enforced.
37
-
38
- Human actions on runs: pause, resume, cancel, retry, escalate, accept result. Budgets, circuit-breaker state, usage buckets, events, steps, artifacts, and worktrees are persisted in dedicated collections.
39
-
40
- ### Sub-agent observation and memory
41
-
42
- - `NativeSubAgentObserver` wraps plugin-ai's native `dispatch-sub-agent-task` flow: it resolves harness policy, injects memory context into the delegated question, records root/tool spans in `agentExecutionSpans`, tracks tokens/cost, and links skill executions. Legacy `delegate_*` / `dispatch_subagents_*` tools are retired.
43
- - `AgentMemoryContextService` builds an `<agent_memory_context>` block from `agentMemoryContexts` records (scopes `public`, `user`, `agent_user`, plus plugin-user-memory content), trimmed to the harness-configured character limit.
44
- - `AgentRegistryService` resolves leader↔sub-agent bindings from `orchestratorConfig`, model overrides, and alternative sub-agents for retry.
45
-
46
- ## Harness (Policy Profiles)
47
-
48
- A harness profile is a versioned policy bundle addressed by a unique `tag`. Settings (validated by a strict zod schema in `HarnessSchema.ts`) have six sections:
49
-
50
- | Section | Controls |
51
- | --- | --- |
52
- | `tools` | `allow` / `ask` / `deny` lists, per-tool `effects` (`read` / `write` / `external`), `trustedPreHandlerTools` |
53
- | `memory` | `enabled`, `scopes` (`public` / `user` / `agent_user`), `maxChars` |
54
- | `delegation` | `allowedEmployees`, `maxDepth`, `maxCount` |
55
- | `limits` | `timeoutMs`, `recursionLimit`, max invocations/tool calls/tokens/cost |
56
- | `isolation` | `mode` (`none` / `worktree`), `requireWorktree`, `allowedConnectors`, `networkAccess` (`deny` / `restricted` / `allow`) |
57
- | `observability` | `enabled`, `tracingRetentionDays`, `captureInputs`, `captureOutputs` |
58
-
59
- ### Layered compilation
60
-
61
- `HarnessCompiler.compileHarness()` merges an ordered list of layers with most-restrictive-wins semantics: allow-lists and scopes are intersected, `ask`/`deny` are unioned, numeric limits take the minimum, booleans AND, network access takes the strictest value. For each run role, `LoopPatternService` stacks:
62
-
63
- `platform` (hard ceilings) → `profile:<tag>@<version>` (published profile) → `pattern` → `employee:<username>` → per-run overrides.
64
-
65
- The compiled result is persisted on the run as an immutable snapshot (`leaderHarnessSnapshot`, per-maker `makerHarnessSnapshot`, `verifierHarnessSnapshot`), so runs always execute against the policy that was in force at enqueue time.
66
-
67
- ### Tool planning
68
-
69
- At invocation time, `PluginAiRuntimeAdapter` converts the compiled harness into a tool plan: `deny` > `ask` > `allow`. Tools not explicitly allowed become `ask`; allowed tools with `write`/`external` effects stay `ask` unless listed in `trustedPreHandlerTools`. `ask` tools are attached without auto-call so they interrupt for approval; unenforceable system tools (e.g. web search) are blocked at the source.
70
-
71
- ### Versioning
72
-
73
- `HarnessProfileService` manages draft/publish lifecycle over `agentHarnessProfileVersions`: create draft → update draft → publish (points the profile's `currentVersionId` at the published version). One open draft per profile — `saveDraft` writes into the latest unpublished draft and only starts a new version once the previous one shipped, keeping the version history a clean publish trail. `createProfile` bootstraps a profile together with its first published version atomically, and version numbering is row-locked so concurrent saves/publishes cannot collide. Published versions are immutable. Profiles are resolved by tag via `getPublishedByTag(tag)`. Seeded profiles: `default`, `safe`, `file-heavy`.
74
-
75
- ## Skill Hub
76
-
77
- ### Skills
78
-
79
- A skill (`skillDefinitions`) is a sandboxed Python or Node.js code unit with:
80
-
81
- - immutable `toolName`, `title`, `description`, `instructions`;
82
- - `codeTemplate` with `{{placeholder}}` rendering and a JSON Schema `inputSchema`;
83
- - optional `interactionSchema` for human-in-the-loop review UI;
84
- - `packages`, `timeoutSeconds`, `maxOutputSizeMb`, `enabled`, `autoCall`;
85
- - `toolScope` (`CUSTOM` / `GENERAL` / `SPECIFIED`) controlling visibility across AI employees;
86
- - storage source: database (zip upload), local, s3, plugin template, or Git.
87
-
88
- ### Execution
89
-
90
- `skill_hub_execute` and per-skill `skill_hub_<toolName>` tools validate input, check per-agent access (`SkillAccessService`), apply a per-user rate limit, create a `skillExecutions` row, and publish `skill-hub.task`. Sandbox workers claim executions, render and validate the code, run it in a sandbox, stream progress, and store stdout/stderr/output files (downloadable via `skillHub:download`). A poller recovers stale executions. Executions link into the tracing graph via `agentExecutionSpans` (span type `skill`).
91
-
92
- ### MCP surface
93
-
94
- The Skill Hub exposes an MCP-style server surface: `skillHub:mcpListTools` lists enabled skills as `{name, description, inputSchema}` tools; `skillHub:mcpCallTool` executes one and returns MCP content (including a file manifest).
95
-
96
- ### Import and registry
97
-
98
- - **Git import**: `gitListSkills` / `gitSyncSkills` read a `skills.json` manifest and `SKILL.md` frontmatter through plugin-git-manager (optional peer dependency).
99
- - **Registry**: `RegistrySkillInstallationService` installs registry package versions into local `skillDefinitions` (disabled by default, with rollback chain), and `RegistrySkillSnapshotService` exports opt-in snapshots of local skills for an external registry plugin.
100
-
101
- ### Human-in-the-loop review
102
-
103
- `skillLoopConfigs` stores review templates (prompt + schema) per skill; the chat UI renders approval cards for skill executions that require review.
104
-
105
- ## External RAG Search
106
-
107
- The plugin registers the `external_rag_search` tool so leaders and sub-agents can retrieve context from NocoBase knowledge bases, including external RAG services. Source ownership stays in NocoBase; chunking, embedding, vector storage, and retrieval live in an external lightweight RAG service. The tool calls `plugin-knowledge-base.searchKnowledgeBases()`, so access control and mixed local/external search stay centralized.
108
-
109
- Knowledge bases of type `EXTERNAL_RAG` carry options such as `ragProvider` (`external-http` or `e5-http`), `ragApiUrl`, `ragApiKey`, `ragNamespace`, `ragTopK`, `ragScoreThreshold`.
110
-
111
- ### External search contract
112
-
113
- The built-in `external-http` strategy expects:
114
-
115
- ```http
116
- POST /search
117
- Authorization: Bearer <ragApiKey>
118
- Content-Type: application/json
119
- ```
120
-
121
- ```json
122
- {
123
- "query": "search text",
124
- "topK": 5,
125
- "scoreThreshold": 0.3,
126
- "namespace": "optional-kb-namespace",
127
- "filter": {}
128
- }
129
- ```
130
-
131
- Response:
132
-
133
- ```json
134
- {
135
- "results": [
136
- {
137
- "id": "chunk-or-source-id",
138
- "content": "matched text",
139
- "score": 0.82,
140
- "metadata": {
141
- "fileId": "123",
142
- "filename": "contract.pdf",
143
- "collection": "orders",
144
- "recordId": "456",
145
- "sourceUrl": "/api/attachments/123:download"
146
- }
147
- }
148
- ]
149
- }
150
- ```
151
-
152
- Every result must return enough metadata for NocoBase to resolve the original source: `fileId`/`filename` for files, or `collection`/`recordId` for datasource records.
153
-
154
- For E5-family models behind an OpenAI-compatible `/v1/embeddings` API, use `ragProvider: "e5-http"`: queries are embedded as `query: <question>`, chunks as `passage: <chunk>`, and the vector collection must be recreated when the model or vector dimensions change.
155
-
156
- ## UI
157
-
158
- Settings pages under **AI Employee → Agent Orchestrator** (both v1 client and client-v2):
159
-
160
- | Tab | Purpose |
161
- | --- | --- |
162
- | Native Monitor | Loop run list with status, budgets, approvals |
163
- | Execution Tracing | Span tree of sub-agent and tool executions |
164
- | Policy Profiles | Harness profile CRUD with draft/publish versioning and version history |
165
- | Approvals | Pending tool-call/escalation approvals; approve or reject with optional edited input |
166
- | Agent Bindings | Leader↔sub-agent binding configuration |
167
- | Knowledge Access | Per-agent knowledge base access matrix |
168
- | Retrieval Trace | Retrieval tracing for knowledge lookups |
169
- | Memory Inspector | Inspect agent memory context records |
170
- | Skill Hub Definitions | Skill CRUD, editor, test panel, Git import |
171
- | Execution History | Skill execution logs and output files |
172
- | Skill Review Settings | Human-in-the-loop review templates |
173
- | Metrics | Skill usage metrics |
174
-
175
- ## API Resources
176
-
177
- - `agentLoops` — list, get, runNow, pause, resume, cancel, retry, escalate, acceptResult, status
178
- - `agentLoopApprovals` — list, get, decide
179
- - `agentLoopArtifactsView` — list, get
180
- - `agentLoopEventsStream` — stream
181
- - `agentMonitor` — list, get, sync
182
- - `agentKnowledgeInsights` — accessMatrix, retrievalTrace, memoryPreview
183
- - `orchestratorTracing` — list, get
184
- - `skillHub` — download, test, initEnv, clearStorage, mcpListTools, mcpCallTool, listTemplates, gitListSkills, gitSyncSkills
185
- - `agentHarnessProfiles` — standard CRUD plus listVersions, saveDraft, publish, createProfile, validate
186
- - Standard CRUD on `skillDefinitions`, `skillExecutions`, `agentMemoryContexts`, and related collections
187
-
188
- ## Collections
189
-
190
- Agent loops: `agentLoopPatterns`, `agentLoopRuns`, `agentLoopSteps`, `agentLoopEvents`, `agentLoopActionApprovals`, `agentLoopArtifacts`, `agentLoopCircuitStates`, `agentLoopControlSettings`, `agentLoopPathLocks`, `agentLoopUsageBuckets`, `agentLoopWorktrees`.
191
-
192
- Harness: `agentHarnessProfiles`, `agentHarnessProfileVersions`.
193
-
194
- Observation/memory: `agentExecutionSpans`, `orchestratorConfig`, `orchestratorLogs`, `agentMemoryContexts`.
195
-
196
- Skill Hub: `skillDefinitions`, `skillExecutions`, `skillLoopConfigs`, `skillWorkerConfigs`, `skillRegistryInstallations`.
197
-
198
- ## Usage
199
-
200
- 1. Enable the plugin in the NocoBase Plugin Manager (requires plugin-ai; plugin-git-manager is optional for Git skill import).
201
- 2. Configure **Policy Profiles** (harness tags) for your risk levels — the seeded `default`, `safe`, and `file-heavy` profiles are a starting point.
202
- 3. For sub-agent delegation: configure leader↔sub-agent bindings in **Agent Bindings**, add the built-in **AI employee task dispatching** (`dispatch-sub-agent-task`) tool to the leader, and ensure the user role can access both employees.
203
- 4. For autonomous loops: create a pattern (goal, autonomy level, trigger, roles, harness tags, policy), then trigger runs manually, by cron, or by event; monitor runs in **Native Monitor** and resolve approvals/verification escalations there.
204
- 5. For skills: define skills in **Skill Hub Definitions** (or import from Git/registry), test them with the test panel, then bind the generated `skill_hub_*` tools to AI employees.
1
+ # plugin-agent-orchestrator
2
+
3
+ ## Overview
4
+
5
+ Agent orchestration layer for NocoBase AI Employees (plugin-ai). The plugin provides three main subsystems:
6
+
7
+ 1. **Agent Loop Control Plane** — durable, policy-governed multi-step runs with a leader/maker/verifier role model, cron/event/manual triggers, budgets, approvals, and independent verification.
8
+ 2. **Harness (Policy Profiles)** — versioned, tag-addressed policy bundles that constrain what each role may do (tools, memory, delegation, limits, isolation, observability), compiled layer-by-layer with most-restrictive-wins semantics.
9
+ 3. **Skill Hub** — sandboxed Python/Node.js skills that AI employees can execute as tools, with async execution, human-in-the-loop review, an MCP-style surface, and Git/registry import.
10
+
11
+ The legacy loop engine remains available for compatibility. Native agent execution is owned by plugin-ai. The native observer does not change a task, prompt, memory, tool binding, result, or error; persisted native records can be reconciled into a session-level execution tree with model usage and configured cost snapshots. The plugin also exposes an external RAG search tool.
12
+
13
+ Native harness settings are not global enforcement gates. The capability view describes which settings apply to plugin-owned components and which native policies are unsupported or observation-only. Cost is calculated from configured pricing, not provider billing, and missing usage or price remains unknown. Daily/global legacy cost buckets are not reconciled against every native provider call and must not be treated as confirmed actual-spend caps.
14
+
15
+ ## Agent Loop Control Plane
16
+
17
+ ### Patterns
18
+
19
+ A loop pattern (`agentLoopPatterns`) defines a repeatable unit of autonomous work:
20
+
21
+ - `key`, `goalTemplate` — identity and the goal rendered for each run.
22
+ - `autonomyLevel` — `L1` (supervised), `L2`, `L3` (autonomous). L2/L3 require repository identity (`repositoryKey`, `repositoryRoot`, `baseRef`, `actingOn[]`) and worktree isolation (`policy.harness.isolation.requireWorktree`).
23
+ - `triggerType` — `manual`, `cron` (`cronExpression` + `timezone`), or `event` (`eventKey`).
24
+ - Role bindings — `leaderUsername`, `makerUsernames[]`, `verifierUsername` (verifier must differ from leader and makers).
25
+ - Per-role harness tags — `leaderHarnessTag` / `makerHarnessTag` (default `default`), `verifierHarnessTag` (default `safe`).
26
+ - `policy` — concurrency, per-run/daily budgets (invocations, tool calls, delegations, verifications, tokens, cost), circuit-breaker limits, path restrictions (`maxFiles`, deny list), action approval settings (`autoAllowlist`, approvers, timeout), tool-loop detection thresholds (`warnAt`/`blockAt`/`escalateAt`), and required verification checks.
27
+
28
+ ### Run lifecycle
29
+
30
+ `LoopTriggerService` compiles the pattern (including layered harness compilation), snapshots role bindings and harness settings onto the run row, and enqueues it. `LoopWorkerService` claims queued runs with a lease + heartbeat, acquires path locks on `actingOn`, then drives the run:
31
+
32
+ `queued → preparing → waiting_lock → running → waiting_approval → verifying → waiting_human → succeeded | failed | canceled` (plus `paused`, `blocked`).
33
+
34
+ - **Leader** invocation plans the work but changes nothing.
35
+ - **Maker** invocations execute the plan, each under its own compiled harness.
36
+ - Tool calls gated as `ask` park the run in `waiting_approval` until the approval row is resolved via `agentLoopApprovals:decide` (approve — optionally substituting an edited input — or reject).
37
+ - **Tool-loop detection** (`ToolLoopDetectionService`, active in both worker and verifier) guards against repeated identical tool calls: `warnAt` injects a notice into the run, `blockAt` refuses the call, `escalateAt` escalates the run for human review.
38
+ - **Verifier** (via `VerificationService`) runs an independent pass and returns a JSON verdict: `pass` → `succeeded` (L1) or `waiting_human` (L2/L3); `reject` → `failed`; `escalate` → `waiting_human`. Required checks and artifact evidence ownership are enforced.
39
+
40
+ Human actions on runs: pause, resume, cancel, retry, escalate, accept result. Budgets, circuit-breaker state, usage buckets, events, steps, artifacts, and worktrees are persisted in dedicated collections.
41
+
42
+ ### Sub-agent observation and memory
43
+
44
+ - `NativeSubAgentObserver` observes the native `dispatch-sub-agent-task` flow without changing the task, result, or error. `agentMonitor:sync` reconciles persisted native sessions and calls in bounded pages; repeat complete passes to include late records and updates to older rows. A session root is not an individual request or complete real-time trace. Native message and tool content is omitted when no invocation-time capture-policy snapshot is available.
45
+ - Trace reconciliation and cleanup use the same global retention window, based on native source activity rather than reconciliation time. The cleanup falls back to source start/creation timestamps for older rows without an activity field. Model-call usage and pricing snapshots are retained separately as accounting data; trace retention is not a deletion policy for that ledger or for native core records.
46
+ - `AgentMemoryContextService` still provides context-building utilities for compatible plugin-owned consumers. The native observer no longer injects memory into delegated questions.
47
+ - `AgentRegistryService` resolves leader↔sub-agent bindings from `orchestratorConfig`, model overrides, and alternative sub-agents for retry.
48
+
49
+ ## Harness (Policy Profiles)
50
+
51
+ A harness profile is a versioned policy bundle addressed by a unique `tag`. Settings (validated by a strict zod schema in `HarnessSchema.ts`) have six sections:
52
+
53
+ | Section | Controls |
54
+ | --- | --- |
55
+ | `tools` | `allow` / `ask` / `deny` lists, per-tool `effects` (`read` / `write` / `external`), `trustedPreHandlerTools` |
56
+ | `memory` | `enabled`, `scopes` (`public` / `user` / `agent_user`), `maxChars` |
57
+ | `delegation` | `allowedEmployees`, `maxDepth`, `maxCount` |
58
+ | `limits` | `timeoutMs`, `recursionLimit`, max invocations/tool calls/tokens/cost |
59
+ | `isolation` | `mode` (`none` / `worktree`), `requireWorktree`, `allowedConnectors`, `networkAccess` (`deny` / `restricted` / `allow`) |
60
+ | `observability` | `enabled`, `tracingRetentionDays`, `captureInputs`, `captureOutputs` |
61
+
62
+ ### Layered compilation
63
+
64
+ `HarnessCompiler.compileHarness()` merges an ordered list of layers with most-restrictive-wins semantics: allow-lists and scopes are intersected, `ask`/`deny` are unioned, numeric limits take the minimum, booleans AND, network access takes the strictest value. For each run role, `LoopPatternService` stacks:
65
+
66
+ `platform` (hard ceilings) → `profile:<tag>@<version>` (published profile) → `pattern` → `employee:<username>` → per-run overrides.
67
+
68
+ The compiled result is persisted on the run as an immutable snapshot (`leaderHarnessSnapshot`, per-maker `makerHarnessSnapshot`, `verifierHarnessSnapshot`), so runs always execute against the policy that was in force at enqueue time.
69
+
70
+ ### Tool planning
71
+
72
+ For legacy plugin-owned loop invocations, `PluginAiRuntimeAdapter` converts the compiled harness into a tool plan: `deny` > `ask` > `allow`. Tools not explicitly allowed become `ask`; allowed tools with `write`/`external` effects stay `ask` unless listed in `trustedPreHandlerTools`. `ask` tools are attached without auto-call so they interrupt for approval; unenforceable system tools (e.g. web search) are blocked at the source. This adapter does not establish a global gate for native chat, API, workflow, or sub-agent execution.
73
+
74
+ ### Versioning
75
+
76
+ `HarnessProfileService` manages draft/publish lifecycle over `agentHarnessProfileVersions`: create draft → update draft → publish (points the profile's `currentVersionId` at the published version). One open draft per profile — `saveDraft` writes into the latest unpublished draft and only starts a new version once the previous one shipped, keeping the version history a clean publish trail. `createProfile` bootstraps a profile together with its first published version atomically, and version numbering is row-locked so concurrent saves/publishes cannot collide. Published versions are immutable. Profiles are resolved by tag via `getPublishedByTag(tag)`. Seeded profiles: `default`, `safe`, `file-heavy`.
77
+
78
+ ## Skill Hub
79
+
80
+ ### Skills
81
+
82
+ A skill (`skillDefinitions`) is a sandboxed Python or Node.js code unit with:
83
+
84
+ - immutable `toolName`, `title`, `description`, `instructions`;
85
+ - `codeTemplate` with `{{placeholder}}` rendering and a JSON Schema `inputSchema`;
86
+ - optional `interactionSchema` for human-in-the-loop review UI;
87
+ - `packages`, `timeoutSeconds`, `maxOutputSizeMb`, `enabled`, `autoCall`;
88
+ - `toolScope` (`CUSTOM` / `GENERAL` / `SPECIFIED`) controlling visibility across AI employees;
89
+ - storage source: database (zip upload), local, s3, plugin template, or Git.
90
+
91
+ ### Execution
92
+
93
+ `skill_hub_execute` and per-skill `skill_hub_<toolName>` tools validate input, check per-agent access (`SkillAccessService`), apply a per-user rate limit, create a `skillExecutions` row, and publish `skill-hub.task`. Sandbox workers claim executions, render and validate the code, run it in a sandbox, stream progress, and store stdout/stderr/output files (downloadable via `skillHub:download`). A poller recovers stale executions. Executions link into the tracing graph via `agentExecutionSpans` (span type `skill`).
94
+
95
+ ### MCP surface
96
+
97
+ The Skill Hub exposes an MCP-style server surface: `skillHub:mcpListTools` lists enabled skills as `{name, description, inputSchema}` tools; `skillHub:mcpCallTool` executes one and returns MCP content (including a file manifest).
98
+
99
+ ### Import and registry
100
+
101
+ - **Git import**: `gitListSkills` / `gitSyncSkills` read a `skills.json` manifest and `SKILL.md` frontmatter through plugin-git-manager (optional peer dependency).
102
+ - **Registry**: `RegistrySkillInstallationService` installs registry package versions into local `skillDefinitions` (disabled by default, with rollback chain), and `RegistrySkillSnapshotService` exports opt-in snapshots of local skills for an external registry plugin.
103
+
104
+ ### Human-in-the-loop review
105
+
106
+ `skillLoopConfigs` stores review templates (prompt + schema) per skill; the chat UI renders approval cards for skill executions that require review.
107
+
108
+ ## External RAG Search
109
+
110
+ The plugin registers the `external_rag_search` tool so leaders and sub-agents can retrieve context from NocoBase knowledge bases, including external RAG services. Source ownership stays in NocoBase; chunking, embedding, vector storage, and retrieval live in an external lightweight RAG service. The tool calls `plugin-knowledge-base.searchKnowledgeBases()`, so access control and mixed local/external search stay centralized.
111
+
112
+ Knowledge bases of type `EXTERNAL_RAG` carry options such as `ragProvider` (`external-http` or `e5-http`), `ragApiUrl`, `ragApiKey`, `ragNamespace`, `ragTopK`, `ragScoreThreshold`.
113
+
114
+ ### External search contract
115
+
116
+ The built-in `external-http` strategy expects:
117
+
118
+ ```http
119
+ POST /search
120
+ Authorization: Bearer <ragApiKey>
121
+ Content-Type: application/json
122
+ ```
123
+
124
+ ```json
125
+ {
126
+ "query": "search text",
127
+ "topK": 5,
128
+ "scoreThreshold": 0.3,
129
+ "namespace": "optional-kb-namespace",
130
+ "filter": {}
131
+ }
132
+ ```
133
+
134
+ Response:
135
+
136
+ ```json
137
+ {
138
+ "results": [
139
+ {
140
+ "id": "chunk-or-source-id",
141
+ "content": "matched text",
142
+ "score": 0.82,
143
+ "metadata": {
144
+ "fileId": "123",
145
+ "filename": "contract.pdf",
146
+ "collection": "orders",
147
+ "recordId": "456",
148
+ "sourceUrl": "/api/attachments/123:download"
149
+ }
150
+ }
151
+ ]
152
+ }
153
+ ```
154
+
155
+ Every result must return enough metadata for NocoBase to resolve the original source: `fileId`/`filename` for files, or `collection`/`recordId` for datasource records.
156
+
157
+ For E5-family models behind an OpenAI-compatible `/v1/embeddings` API, use `ragProvider: "e5-http"`: queries are embedded as `query: <question>`, chunks as `passage: <chunk>`, and the vector collection must be recreated when the model or vector dimensions change.
158
+
159
+ ## UI
160
+
161
+ Settings pages under **AI Employee → Agent Orchestrator** (both v1 client and client-v2):
162
+
163
+ | Tab | Purpose |
164
+ | --- | --- |
165
+ | Native Monitor | Loop run list with status, budgets, approvals |
166
+ | Execution Tracing | Span tree of sub-agent and tool executions |
167
+ | Policy Profiles | Harness profile CRUD with draft/publish versioning and version history |
168
+ | Approvals | Pending tool-call/escalation approvals; approve or reject with optional edited input |
169
+ | Agent Bindings | Leader↔sub-agent binding configuration |
170
+ | Knowledge Access | Per-agent knowledge base access matrix |
171
+ | Retrieval Trace | Retrieval tracing for knowledge lookups |
172
+ | Memory Inspector | Inspect agent memory context records |
173
+ | Skill Hub Definitions | Skill CRUD, editor, test panel, Git import |
174
+ | Execution History | Skill execution logs and output files |
175
+ | Skill Review Settings | Human-in-the-loop review templates |
176
+ | Metrics | Skill usage metrics |
177
+
178
+ ## API Resources
179
+
180
+ - `agentLoops` — list, get, runNow, pause, resume, cancel, retry, escalate, acceptResult, status
181
+ - `agentLoopApprovals` — list, get, decide
182
+ - `agentLoopArtifactsView` — list, get
183
+ - `agentLoopEventsStream` — stream
184
+ - `agentMonitor` — list, get, sync
185
+ - `agentKnowledgeInsights` — accessMatrix, retrievalTrace, memoryPreview
186
+ - `orchestratorTracing` — list, get
187
+ - `skillHub` — download, test, initEnv, clearStorage, mcpListTools, mcpCallTool, listTemplates, gitListSkills, gitSyncSkills
188
+ - `agentHarnessProfiles` — standard CRUD plus listVersions, saveDraft, publish, createProfile, validate
189
+ - Standard CRUD on `skillDefinitions`, `skillExecutions`, `agentMemoryContexts`, and related collections
190
+
191
+ ## Collections
192
+
193
+ Agent loops: `agentLoopPatterns`, `agentLoopRuns`, `agentLoopSteps`, `agentLoopEvents`, `agentLoopActionApprovals`, `agentLoopArtifacts`, `agentLoopCircuitStates`, `agentLoopControlSettings`, `agentLoopPathLocks`, `agentLoopUsageBuckets`, `agentLoopWorktrees`.
194
+
195
+ Harness: `agentHarnessProfiles`, `agentHarnessProfileVersions`.
196
+
197
+ Observation/memory: `agentExecutionSpans`, `orchestratorConfig`, `orchestratorLogs`, `agentMemoryContexts`.
198
+
199
+ Skill Hub: `skillDefinitions`, `skillExecutions`, `skillLoopConfigs`, `skillWorkerConfigs`, `skillRegistryInstallations`.
200
+
201
+ ## Usage
202
+
203
+ 1. Enable the plugin in the NocoBase Plugin Manager (requires plugin-ai; plugin-git-manager is optional for Git skill import).
204
+ 2. Configure **Policy Profiles** (harness tags) for your risk levels — the seeded `default`, `safe`, and `file-heavy` profiles are a starting point.
205
+ 3. For sub-agent delegation: configure leader↔sub-agent bindings in **Agent Bindings**, add the built-in **AI employee task dispatching** (`dispatch-sub-agent-task`) tool to the leader, and ensure the user role can access both employees.
206
+ 4. For autonomous loops: create a pattern (goal, autonomy level, trigger, roles, harness tags, policy), then trigger runs manually, by cron, or by event; monitor runs in **Native Monitor** and resolve approvals/verification escalations there.
207
+ 5. For skills: define skills in **Skill Hub Definitions** (or import from Git/registry), test them with the test panel, then bind the generated `skill_hub_*` tools to AI employees.
package/client-v2.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './dist/client-v2';
2
- export { default } from './dist/client-v2';
1
+ export * from './dist/client-v2';
2
+ export { default } from './dist/client-v2';
package/client-v2.js CHANGED
@@ -1 +1 @@
1
- module.exports = require('./dist/client-v2/index.js');
1
+ module.exports = require('./dist/client-v2/index.js');
package/client.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './dist/client';
2
- export { default } from './dist/client';
1
+ export * from './dist/client';
2
+ export { default } from './dist/client';
package/client.js CHANGED
@@ -1 +1 @@
1
- module.exports = require('./dist/client');
1
+ module.exports = require('./dist/client');
@@ -0,0 +1,10 @@
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
+ "use strict";(self.webpackChunkplugin_agent_orchestrator=self.webpackChunkplugin_agent_orchestrator||[]).push([["117"],{532:function(e,t,r){r.d(t,{j:function(){return d},l:function(){return s}});var n=r(155),a=r.n(n),l=r(608);function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function u(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("u">typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e){if(e){if("string"==typeof e)return o(e,void 0);var t=Object.prototype.toString.call(e).slice(8,-1);if("Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t)return Array.from(t);if("Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return o(e,void 0)}}(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var i=(0,n.createContext)({employees:[],employeeMap:new Map,toolNamesMap:new Map,loading:!1,refresh:function(){}}),c=new Set(["dispatch-sub-agent-task","external_rag_search","skill_hub_execute"]),s=function(e){var t=e.children,r=(0,l.b)({url:"aiEmployees:list",params:{pageSize:200}}),n=r.data,o=r.loading,s=r.refresh,d=a().useMemo(function(){var e=((null==n?void 0:n.data)||[]).map(function(e){var t,r,n,a,l=(r=Array.isArray(null==(t=e.skillSettings)?void 0:t.tools)?t.tools.map(function(e){return"string"==typeof e?e:null==e?void 0:e.name}).filter(function(e){return"string"==typeof e&&e.length>0}):[],n=Array.isArray(null==t?void 0:t.skills)?t.skills.map(function(e){if("string"==typeof e)return c.has(e)||e.startsWith("skill_hub_")||e.startsWith("browser_")||e.startsWith("drawio-")?e:null;return null==e?void 0:e.name}).filter(function(e){return"string"==typeof e&&e.length>0}):[],Array.from(new Set(u(r).concat(u(n)))));return{username:e.username,nickname:e.nickname||e.username,about:null==(a=e.about)?void 0:a.substring(0,80),tools:l}}),t=new Map,r=new Map,a=!0,l=!1,i=void 0;try{for(var d,m=e[Symbol.iterator]();!(a=(d=m.next()).done);a=!0){var f=d.value;t.set(f.username,f.nickname),r.set(f.username,new Set(f.tools))}}catch(e){l=!0,i=e}finally{try{a||null==m.return||m.return()}finally{if(l)throw i}}return{employees:e,employeeMap:t,toolNamesMap:r,loading:o,refresh:s}},[n,o,s]);return a().createElement(i.Provider,{value:d},t)},d=function(){return(0,n.useContext)(i)}},524:function(e,t,r){r.r(t),r.d(t,{default:function(){return S}});var n=r(155),a=r.n(n),l=r(532),o=r(59),u=r(375),i=r(608),c=r(603);function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function d(e,t,r,n,a,l,o){try{var u=e[l](o),i=u.value}catch(e){r(e);return}u.done?t(i):Promise.resolve(i).then(n,a)}function m(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var l=e.apply(t,r);function o(e){d(l,n,a,o,u,"next",e)}function u(e){d(l,n,a,o,u,"throw",e)}o(void 0)})}}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r,n,a=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var l=[],o=!0,u=!1;try{for(a=a.call(e);!(o=(r=a.next()).done)&&(l.push(r.value),!t||l.length!==t);o=!0);}catch(e){u=!0,n=e}finally{try{o||null==a.return||a.return()}finally{if(u)throw n}}return l}}(e,t)||function(e,t){if(e){if("string"==typeof e)return s(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return s(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){var r,n,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),u=Object.defineProperty;return u(o,"next",{value:i(0)}),u(o,"throw",{value:i(1)}),u(o,"return",{value:i(2)}),"function"==typeof Symbol&&u(o,Symbol.iterator,{value:function(){return this}}),o;function i(u){return function(i){var c=[u,i];if(r)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(l=0)),l;)try{if(r=1,n&&(a=2&c[0]?n.return:c[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,c[1])).done)return a;switch(n=0,a&&(c=[2&c[0],a.value]),c[0]){case 0:case 1:a=c;break;case 4:return l.label++,{value:c[1],done:!1};case 5:l.label++,n=c[1],c=[0];continue;case 7:c=l.ops.pop(),l.trys.pop();continue;default:if(!(a=(a=l.trys).length>0&&a[a.length-1])&&(6===c[0]||2===c[0])){l=0;continue}if(3===c[0]&&(!a||c[1]>a[0]&&c[1]<a[3])){l.label=c[1];break}if(6===c[0]&&l.label<a[1]){l.label=a[1],a=c;break}if(a&&l.label<a[2]){l.label=a[2],l.ops.push(c);break}a[2]&&l.ops.pop(),l.trys.pop();continue}c=t.call(e,l)}catch(e){c=[6,e],n=0}finally{r=a=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}var y=o.Typography.Paragraph,b=o.Typography.Text;function v(e){var t=e.status;return a().createElement(o.Tag,{color:function(e){switch(e){case"success":return"success";case"error":return"error";case"running":return"processing";default:return"default"}}(t),icon:"success"===t?a().createElement(u.CheckCircleOutlined,null):"error"===t?a().createElement(u.CloseCircleOutlined,null):void 0},t||"-")}function g(e){return e?new Date(e).toLocaleString():"-"}function h(e){return e?e>=6e4?"".concat(Math.round(e/6e4),"m"):e>=1e3?"".concat((e/1e3).toFixed(1),"s"):"".concat(e,"ms"):"-"}function E(e){var t=e.value,r=e.rows,n=function(e){if(null==e||""===e)return"";if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch(t){return String(e)}}(t);return n?a().createElement(y,{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",margin:0,fontSize:12},ellipsis:{rows:void 0===r?8:r,expandable:!0}},n):a().createElement(b,{type:"secondary"},"-")}var w=function(){var e,t,r,s,d,y,w,S,k,A,I,C,O,x,j,D=(0,i.R)(),M=(0,c.k)(),T=(0,l.j)(),P=T.employees,U=T.employeeMap,z=f((0,n.useState)({}),2),R=z[0],N=z[1],_=f((0,n.useState)(1),2),F=_[0],B=_[1],W=f((0,n.useState)(20),2),q=W[0],L=W[1],G=f((0,n.useState)(null),2),$=G[0],H=G[1],J=f((0,n.useState)(!1),2),K=J[0],Q=J[1],V=f((0,n.useState)(!1),2),X=V[0],Y=V[1],Z=f((0,n.useState)(null),2),ee=Z[0],et=Z[1],er=(0,n.useRef)(0),en=(0,n.useMemo)(function(){var e={};return R.leader&&(e.leaderUsername=R.leader),R.subAgent&&(e.subAgentUsername=R.subAgent),R.status&&(e.status=R.status),{sort:["-startedAt"],page:F,pageSize:q,filter:e}},[R,F,q]),ea=(0,i.b)({url:"agentMonitor:list",params:en},{refreshDeps:[en]}),el=ea.data,eo=ea.loading,eu=ea.refresh,ei=(0,n.useMemo)(function(){var e=null==el?void 0:el.data;return Array.isArray(e)?e:[]},[el]),ec=(0,n.useMemo)(function(){var e,t=null==el||null==(e=el.meta)?void 0:e.count;return"number"==typeof t?t:0},[el]),es=(0,n.useMemo)(function(){return P.map(function(e){return{label:e.nickname||e.username,value:e.username}})},[P]),ed=function(e){N(function(t){return function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){var n;n=r[t],t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n})}return e}({},t,e)}),B(1)},em=!!(R.leader||R.subAgent||R.status),ef=Array.isArray(null==$?void 0:$.trace)?$.trace:[],ep=[{title:M("Time"),dataIndex:"createdAt",key:"createdAt",width:170,render:g},{title:M("Leader"),dataIndex:"leaderUsername",key:"leaderUsername",width:160,render:function(e){return a().createElement(o.Tag,{color:"blue"},U.get(e)||e||"-")}},{title:M("Sub-Agent"),dataIndex:"subAgentUsername",key:"subAgentUsername",width:160,render:function(e){return a().createElement(o.Tag,{color:"green"},U.get(e)||e||"-")}},{title:M("Task"),dataIndex:"task",key:"task",render:function(e){return a().createElement(b,{ellipsis:!0,style:{maxWidth:360}},e||"-")}},{title:M("Status"),dataIndex:"status",key:"status",width:110,render:function(e){return a().createElement(v,{status:e})}},{title:M("Duration"),dataIndex:"durationMs",key:"durationMs",width:100,render:h},{title:M("Context"),dataIndex:"memoryContextApplied",key:"memoryContextApplied",width:100,render:function(e){return e?a().createElement(o.Tag,{color:"purple"},"memory"):a().createElement(b,{type:"secondary"},"-")}},{title:"",key:"actions",width:90,render:function(e,t){return a().createElement(o.Button,{type:"link",size:"small",icon:a().createElement(u.EyeOutlined,null),onClick:function(){return m(function(){var e,r,n,a,l,u,i,c,s,d,m,f;return p(this,function(p){switch(p.label){case 0:e=++er.current,H(t),Q(!0),p.label=1;case 1:return p.trys.push([1,3,4,5]),[4,D.request({url:"agentMonitor:get",params:{filterByTk:t.id}})];case 2:if(l=p.sent(),e!==er.current)return[2];return H((null==(u=l)||null==(n=u.data)||null==(r=n.data)?void 0:r.data)||(null==u||null==(a=u.data)?void 0:a.data)||t),[3,5];case 3:if(i=p.sent(),e!==er.current)return[2];return f=(null==i||null==(m=i.response)||null==(d=m.data)||null==(s=d.errors)||null==(c=s[0])?void 0:c.message)||(null==i?void 0:i.message)||M("Failed to load run detail"),o.message.error(f),[3,5];case 4:return e===er.current&&Q(!1),[7];case 5:return[2]}})})()}},M("Detail"))}}];return a().createElement("div",null,a().createElement(o.Alert,{type:"info",showIcon:!0,style:{marginBottom:16},message:M("Native Agent Runs"),description:a().createElement(b,{type:"secondary"},M("Native monitor coverage description")," ",M("Monitor descendant filters follow up to 32 levels"))}),a().createElement(o.Card,{bordered:!1},a().createElement(o.Form,{layout:"inline",style:{marginBottom:16,rowGap:8,flexWrap:"wrap"}},a().createElement(o.Form.Item,{label:M("Leader")},a().createElement(o.Select,{allowClear:!0,showSearch:!0,optionFilterProp:"label",placeholder:M("Any leader"),style:{minWidth:180},options:es,value:R.leader,onChange:function(e){return ed({leader:e})}})),a().createElement(o.Form.Item,{label:M("Sub-Agent")},a().createElement(o.Select,{allowClear:!0,showSearch:!0,optionFilterProp:"label",placeholder:M("Any sub-agent"),style:{minWidth:180},options:es,value:R.subAgent,onChange:function(e){return ed({subAgent:e})}})),a().createElement(o.Form.Item,{label:M("Status")},a().createElement(o.Select,{allowClear:!0,placeholder:M("Any status"),style:{minWidth:140},value:R.status,onChange:function(e){return ed({status:e})},options:[{label:M("Running"),value:"running"},{label:M("Success"),value:"success"},{label:M("Error"),value:"error"}]})),a().createElement(o.Form.Item,null,a().createElement(o.Space,null,a().createElement(o.Button,{onClick:function(){N({}),B(1)},disabled:!em},M("Reset")),a().createElement(o.Button,{icon:a().createElement(u.ReloadOutlined,null),onClick:eu},M("Refresh")),a().createElement(o.Button,{icon:a().createElement(u.SyncOutlined,null),onClick:function(){return m(function(){var e,t,r,n,a,l,u,i,c,s,d,m,f,y,b;return p(this,function(p){switch(p.label){case 0:Y(!0),p.label=1;case 1:return p.trys.push([1,3,4,5]),[4,D.request({url:"agentMonitor:sync",method:"post",data:{limit:500,cursor:ee}})];case 2:return et((i=(null==(u=null==(l=p.sent())||null==(e=l.data)?void 0:e.data)?void 0:u.data)||u||{}).cursor||null),c=((null==(t=i.counts)?void 0:t.conversations)||0)+((null==(r=i.counts)?void 0:r.linkedSubAgents)||0)+((null==(n=i.counts)?void 0:n.toolMessages)||0)+((null==(a=i.counts)?void 0:a.modelCalls)||0),o.message.success(i.complete?M("Native sync pass completed ({{count}} records in this page)",{count:c}):M("Synced {{count}} records; continue to finish this pass",{count:c})),eu(),[3,5];case 3:return b=(null==(s=p.sent())||null==(y=s.response)||null==(f=y.data)||null==(m=f.errors)||null==(d=m[0])?void 0:d.message)||(null==s?void 0:s.message)||M("Sync failed"),o.message.error(b),[3,5];case 4:return Y(!1),[7];case 5:return[2]}})})()},loading:X},ee?M("Continue sync"):M("Sync"))))),a().createElement(o.Table,{rowKey:"id",loading:eo,dataSource:ei,columns:ep,scroll:{x:"max-content"},pagination:{current:F,pageSize:q,total:ec,showSizeChanger:!0,pageSizeOptions:[10,20,50,100],showTotal:function(e){return M("{{count}} runs",{count:e})},onChange:function(e,t){B(e),t&&t!==q&&L(t)}},locale:{emptyText:a().createElement(o.Empty,{description:em?M("No runs match the current filters"):M("No native runs yet")})}})),a().createElement(o.Drawer,{title:M("Native Run Detail"),width:960,onClose:function(){return H(null)},open:!!$},$&&a().createElement(o.Spin,{spinning:K},a().createElement(o.Space,{direction:"vertical",size:16,style:{width:"100%"}},a().createElement(o.Descriptions,{bordered:!0,size:"small",column:2},a().createElement(o.Descriptions.Item,{label:M("Status")},a().createElement(v,{status:$.status})),a().createElement(o.Descriptions.Item,{label:M("Harness")},$.harnessTag||"default"),a().createElement(o.Descriptions.Item,{label:M("Leader")},a().createElement(o.Tag,{color:"blue"},U.get($.leaderUsername||"")||$.leaderUsername||"-")),a().createElement(o.Descriptions.Item,{label:M("Sub-Agent")},a().createElement(o.Tag,{color:"green"},U.get($.subAgentUsername||"")||$.subAgentUsername||"-")),a().createElement(o.Descriptions.Item,{label:M("Parent session")},a().createElement(b,{code:!0},$.parentSessionId||"-")),a().createElement(o.Descriptions.Item,{label:M("Sub session")},a().createElement(b,{code:!0},$.subSessionId||"-")),a().createElement(o.Descriptions.Item,{label:M("Tool call")},a().createElement(b,{code:!0},$.toolCallId||"-")),a().createElement(o.Descriptions.Item,{label:M("Duration")},h($.durationMs)),a().createElement(o.Descriptions.Item,{label:M("Started")},g($.startedAt||$.createdAt)),a().createElement(o.Descriptions.Item,{label:M("Ended")},g($.endedAt))),a().createElement(o.Card,{title:M("Task"),size:"small"},a().createElement(E,{value:$.task||(null==(w=$.input)?void 0:w.question),rows:6})),a().createElement(o.Card,{title:M("Execution Flow"),size:"small"},ef.length?a().createElement(o.Timeline,{items:ef.map(function(e){var t,r;return{key:e.id,color:"error"===e.status?"red":"running"===e.status?"blue":"green",children:a().createElement(o.Space,{direction:"vertical",size:2,style:{width:"100%"}},a().createElement(o.Space,{wrap:!0},a().createElement(b,{strong:!0},e.title||e.type),a().createElement(o.Tag,null,e.type),a().createElement(v,{status:e.status}),e.toolName&&a().createElement(b,{code:!0},e.toolName),e.durationMs?a().createElement(b,{type:"secondary"},h(e.durationMs)):null),a().createElement(b,{type:"secondary"},g(e.at)),"model_call"===e.type&&a().createElement(b,{type:"secondary"},[e.provider,e.model].filter(Boolean).join(" / ")||"-"," \xb7 ",M("Input tokens"),":"," ",null!=(t=e.inputTokens)?t:"?"," \xb7 ",M("Output tokens"),": ",null!=(r=e.outputTokens)?r:"?"," \xb7"," ",M(e.usageSource||"missing")," \xb7 ",M("Calculated cost"),":"," ",null==e.cost?M("Unpriced or incomplete"):"".concat(e.cost," USD")),e.content?a().createElement(E,{value:e.content,rows:4}):null)}})}):a().createElement(o.Empty,{description:M("No execution flow captured")})),a().createElement(o.Card,{title:M("Model usage"),size:"small"},a().createElement(o.Descriptions,{size:"small",column:2},a().createElement(o.Descriptions.Item,{label:M("Model calls")},null!=(e=null==(S=$.usage)?void 0:S.modelCalls)?e:"-"),a().createElement(o.Descriptions.Item,{label:M("Input tokens")},null!=(t=null==(k=$.usage)?void 0:k.inputTokens)?t:M("Incomplete")),a().createElement(o.Descriptions.Item,{label:M("Output tokens")},null!=(r=null==(A=$.usage)?void 0:A.outputTokens)?r:M("Incomplete")),a().createElement(o.Descriptions.Item,{label:M("Calculated cost")},(null==(I=$.usage)?void 0:I.cost)==null?M("Unpriced or incomplete"):"".concat($.usage.cost," ").concat($.usage.currency||"USD")),a().createElement(o.Descriptions.Item,{label:M("Estimated calls")},null!=(s=null==(C=$.usage)?void 0:C.estimatedCalls)?s:0),a().createElement(o.Descriptions.Item,{label:M("Missing usage calls")},null!=(d=null==(O=$.usage)?void 0:O.missingUsageCalls)?d:0),a().createElement(o.Descriptions.Item,{label:M("Unpriced calls")},null!=(y=null==(x=$.usage)?void 0:x.unpricedCalls)?y:0)),(null==(j=$.coverage)?void 0:j.truncated)&&a().createElement(o.Alert,{type:"warning",showIcon:!0,message:M("Trace detail truncated; usage totals are incomplete")})),a().createElement(o.Alert,{type:"info",showIcon:!0,message:M("Native content omitted without capture snapshot")}),a().createElement(o.Collapse,{items:[{key:"metadata",label:M("Monitor metadata"),children:a().createElement(E,{value:$.metadata,rows:10})}]}),!!($.output||$.error)&&a().createElement(o.Card,{title:$.error?M("Error"):M("Result"),size:"small"},a().createElement(E,{value:$.error||$.output,rows:12}))))))},S=function(e){var t=e.embedded;return a().createElement(l.l,null,a().createElement("div",{style:t?void 0:{padding:"0 24px 24px"}},a().createElement(w,null)))}},608:function(e,t,r){r.d(t,{R:function(){return c},b:function(){return s}});var n=r(485),a=r(155);function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function o(e,t,r,n,a,l,o){try{var u=e[l](o),i=u.value}catch(e){r(e);return}u.done?t(i):Promise.resolve(i).then(n,a)}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r,n,a=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var l=[],o=!0,u=!1;try{for(a=a.call(e);!(o=(r=a.next()).done)&&(l.push(r.value),!t||l.length!==t);o=!0);}catch(e){u=!0,n=e}finally{try{o||null==a.return||a.return()}finally{if(u)throw n}}return l}}(e,t)||function(e,t){if(e){if("string"==typeof e)return l(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return l(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function i(e){return e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function c(){return(0,n.useApp)().apiClient}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=c(),n=t.manual,l=void 0!==n&&n,s=t.refreshDeps,d=t.onSuccess,m=t.onError,f=u((0,a.useState)(void 0),2),p=f[0],y=f[1],b=u((0,a.useState)(!l),2),v=b[0],g=b[1],h=u((0,a.useState)(void 0),2),E=h[0],w=h[1],S=(0,a.useRef)(e);S.current=e;var k=(0,a.useRef)(d);k.current=d;var A=(0,a.useRef)(m);A.current=m;var I=(0,a.useRef)(!0),C=(0,a.useRef)(0);(0,a.useEffect)(function(){return I.current=!0,function(){I.current=!1}},[]);var O=(0,a.useCallback)(function(e){var t;return(t=function(){var t,n,a,l,o,u,c,s,d;return function(e,t){var r,n,a,l={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),u=Object.defineProperty;return u(o,"next",{value:i(0)}),u(o,"throw",{value:i(1)}),u(o,"return",{value:i(2)}),"function"==typeof Symbol&&u(o,Symbol.iterator,{value:function(){return this}}),o;function i(u){return function(i){var c=[u,i];if(r)throw TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(l=0)),l;)try{if(r=1,n&&(a=2&c[0]?n.return:c[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,c[1])).done)return a;switch(n=0,a&&(c=[2&c[0],a.value]),c[0]){case 0:case 1:a=c;break;case 4:return l.label++,{value:c[1],done:!1};case 5:l.label++,n=c[1],c=[0];continue;case 7:c=l.ops.pop(),l.trys.pop();continue;default:if(!(a=(a=l.trys).length>0&&a[a.length-1])&&(6===c[0]||2===c[0])){l=0;continue}if(3===c[0]&&(!a||c[1]>a[0]&&c[1]<a[3])){l.label=c[1];break}if(6===c[0]&&l.label<a[1]){l.label=a[1],a=c;break}if(a&&l.label<a[2]){l.label=a[2],l.ops.push(c);break}a[2]&&l.ops.pop(),l.trys.pop();continue}c=t.call(e,l)}catch(e){c=[6,e],n=0}finally{r=a=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}}(this,function(m){switch(m.label){case 0:t=S.current,n=++C.current,a=function(){return I.current&&n===C.current},g(!0),w(void 0),m.label=1;case 1:if(m.trys.push([1,6,7,8]),"function"!=typeof t)return[3,3];return[4,t()];case 2:return o=m.sent(),[3,5];case 3:return[4,r.request({url:t.url,method:t.method||"get",params:function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){var n;n=r[t],t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n})}return e}({},t.params||{},e||{}),data:t.data})];case 4:o=(c=null==(u=m.sent())?void 0:u.data)&&(void 0===c?"undefined":i(c))==="object"&&c.data&&"object"===i(c.data)&&"data"in c.data?c.data:c,m.label=5;case 5:if(!a())return[2,void 0];return y(o),null==(l=k.current)||l.call(k,o),[2,o];case 6:if(s=m.sent(),!a())return[2,void 0];return w(s),null==(d=A.current)||d.call(A,s),[2,void 0];case 7:return a()&&g(!1),[7];case 8:return[2]}})},function(){var e=this,r=arguments;return new Promise(function(n,a){var l=t.apply(e,r);function u(e){o(l,n,a,u,i,"next",e)}function i(e){o(l,n,a,u,i,"throw",e)}u(void 0)})})()},[r]),x=(0,a.useCallback)(function(){O()},[O]);return(0,a.useEffect)(function(){l||O()},void 0===s?[]:s),{data:p,loading:v,error:E,refresh:x,run:O}}},603:function(e,t,r){r.d(t,{k:function(){return l}});var n=r(485),a=r(155);function l(){var e=(0,n.useApp)();return(0,a.useCallback)(function(t,r){return e.i18n.t(t,function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){var n;n=r[t],t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n})}return e}({ns:["plugin-agent-orchestrator","client"]},r))},[e.i18n])}}}]);
@@ -0,0 +1,10 @@
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
+ "use strict";(self.webpackChunkplugin_agent_orchestrator=self.webpackChunkplugin_agent_orchestrator||[]).push([["253"],{740:function(e,t,r){r.r(t),r.d(t,{default:function(){return f}});var n=r(155),a=r.n(n),o=r(59),u=r(375),l=r(608),c=r(603);function i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}var s=function(){var e,t=(0,c.k)(),r=function(e){if(Array.isArray(e))return e}(e=(0,n.useState)(!1))||function(e){var t,r,n=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var a=[],o=!0,u=!1;try{for(n=n.call(e);!(o=(t=n.next()).done)&&(a.push(t.value),2!==a.length);o=!0);}catch(e){u=!0,r=e}finally{try{o||null==n.return||n.return()}finally{if(u)throw r}}return a}}(e)||function(e){if(e){if("string"==typeof e)return i(e,2);var t=Object.prototype.toString.call(e).slice(8,-1);if("Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t)return Array.from(t);if("Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return i(e,2)}}(e)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(),s=r[0],f=r[1],d=(0,l.b)({url:"agentKnowledgeInsights:accessMatrix"}),y=(0,n.useMemo)(function(){var e;return Array.isArray(null==(e=d.data)?void 0:e.data)?e.data:[]},[d.data]),p=(0,n.useMemo)(function(){return s?y.filter(function(e){return"denied"===e.access}):y},[y,s]),m=[{title:t("AI Employee"),dataIndex:"employeeUsername",key:"employeeUsername"},{title:t("Knowledge Base"),dataIndex:"knowledgeBaseName",key:"knowledgeBaseName",render:function(e,t){return a().createElement(o.Space,{size:4,wrap:!0},a().createElement("span",null,e),a().createElement(o.Tag,null,t.knowledgeBaseType))}},{title:t("Assignment"),dataIndex:"assigned",key:"assigned",width:120,render:function(e){return a().createElement(o.Tag,{color:e?"blue":"default"},e?t("Assigned"):t("Not assigned"))}},{title:t("Agent access"),dataIndex:"access",key:"access",width:130,render:function(e){return a().createElement(o.Tag,{color:"allowed"===e?"success":"error"},"allowed"===e?t("Allowed"):t("Denied"))}},{title:t("Reason"),dataIndex:"reason",key:"reason",render:function(e){return a().createElement(o.Typography.Text,null,e)}},{title:t("Runtime user gate"),dataIndex:"userGate",key:"userGate",render:function(e){return a().createElement(o.Tooltip,{title:e},a().createElement(o.Typography.Text,{ellipsis:!0,style:{maxWidth:260}},e))}}];return a().createElement(o.Card,{bordered:!1},a().createElement(o.Space,{direction:"vertical",size:16,style:{width:"100%"}},a().createElement(o.Typography.Text,{type:"secondary"},t("This matrix checks employee assignment and static agent policy. BASIC and SHARED user access is still evaluated when a run starts.")),a().createElement(o.Space,{wrap:!0},a().createElement(o.Button,{type:s?"primary":"default",onClick:function(){return f(function(e){return!e})}},s?t("Show all"):t("Show denied only")),a().createElement(o.Button,{icon:a().createElement(u.ReloadOutlined,null),onClick:d.refresh},t("Refresh"))),a().createElement(o.Table,{rowKey:"key",loading:d.loading,dataSource:p,columns:m,scroll:{x:"max-content"},pagination:{pageSize:50,showSizeChanger:!0}})))},f=function(e){var t=e.embedded;return a().createElement("div",{style:t?void 0:{padding:"0 24px 24px"}},a().createElement(s,null))}},608:function(e,t,r){r.d(t,{R:function(){return i},b:function(){return s}});var n=r(485),a=r(155);function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r<t;r++)n[r]=e[r];return n}function u(e,t,r,n,a,o,u){try{var l=e[o](u),c=l.value}catch(e){r(e);return}l.done?t(c):Promise.resolve(c).then(n,a)}function l(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r,n,a=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=a){var o=[],u=!0,l=!1;try{for(a=a.call(e);!(u=(r=a.next()).done)&&(o.push(r.value),!t||o.length!==t);u=!0);}catch(e){l=!0,n=e}finally{try{u||null==a.return||a.return()}finally{if(l)throw n}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if("Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r)return Array.from(r);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e){return e&&"u">typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function i(){return(0,n.useApp)().apiClient}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=i(),n=t.manual,o=void 0!==n&&n,s=t.refreshDeps,f=t.onSuccess,d=t.onError,y=l((0,a.useState)(void 0),2),p=y[0],m=y[1],b=l((0,a.useState)(!o),2),v=b[0],h=b[1],g=l((0,a.useState)(void 0),2),w=g[0],S=g[1],k=(0,a.useRef)(e);k.current=e;var E=(0,a.useRef)(f);E.current=f;var O=(0,a.useRef)(d);O.current=d;var A=(0,a.useRef)(!0),x=(0,a.useRef)(0);(0,a.useEffect)(function(){return A.current=!0,function(){A.current=!1}},[]);var j=(0,a.useCallback)(function(e){var t;return(t=function(){var t,n,a,o,u,l,i,s,f;return function(e,t){var r,n,a,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},u=Object.create(("function"==typeof Iterator?Iterator:Object).prototype),l=Object.defineProperty;return l(u,"next",{value:c(0)}),l(u,"throw",{value:c(1)}),l(u,"return",{value:c(2)}),"function"==typeof Symbol&&l(u,Symbol.iterator,{value:function(){return this}}),u;function c(l){return function(c){var i=[l,c];if(r)throw TypeError("Generator is already executing.");for(;u&&(u=0,i[0]&&(o=0)),o;)try{if(r=1,n&&(a=2&i[0]?n.return:i[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,i[1])).done)return a;switch(n=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,n=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],n=0}finally{r=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}}}(this,function(d){switch(d.label){case 0:t=k.current,n=++x.current,a=function(){return A.current&&n===x.current},h(!0),S(void 0),d.label=1;case 1:if(d.trys.push([1,6,7,8]),"function"!=typeof t)return[3,3];return[4,t()];case 2:return u=d.sent(),[3,5];case 3:return[4,r.request({url:t.url,method:t.method||"get",params:function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){var n;n=r[t],t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n})}return e}({},t.params||{},e||{}),data:t.data})];case 4:u=(i=null==(l=d.sent())?void 0:l.data)&&(void 0===i?"undefined":c(i))==="object"&&i.data&&"object"===c(i.data)&&"data"in i.data?i.data:i,d.label=5;case 5:if(!a())return[2,void 0];return m(u),null==(o=E.current)||o.call(E,u),[2,u];case 6:if(s=d.sent(),!a())return[2,void 0];return S(s),null==(f=O.current)||f.call(O,s),[2,void 0];case 7:return a()&&h(!1),[7];case 8:return[2]}})},function(){var e=this,r=arguments;return new Promise(function(n,a){var o=t.apply(e,r);function l(e){u(o,n,a,l,c,"next",e)}function c(e){u(o,n,a,l,c,"throw",e)}l(void 0)})})()},[r]),I=(0,a.useCallback)(function(){j()},[j]);return(0,a.useEffect)(function(){o||j()},void 0===s?[]:s),{data:p,loading:v,error:w,refresh:I,run:j}}},603:function(e,t,r){r.d(t,{k:function(){return o}});var n=r(485),a=r(155);function o(){var e=(0,n.useApp)();return(0,a.useCallback)(function(t,r){return e.i18n.t(t,function(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter(function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable}))),n.forEach(function(t){var n;n=r[t],t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n})}return e}({ns:["plugin-agent-orchestrator","client"]},r))},[e.i18n])}}}]);
@@ -0,0 +1,10 @@
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
+ "use strict";(self.webpackChunkplugin_agent_orchestrator=self.webpackChunkplugin_agent_orchestrator||[]).push([["325"],{660:function(e,t,n){n.r(t),n.d(t,{default:function(){return I}});var r=n(155),l=n.n(r),a=n(532),o=n(59),c=n(185),i=n.n(c),u=n(608),d=n(603),s=n(956);function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function p(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}function g(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t.push.apply(t,n)}return t})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"u">typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,c=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){c=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(c)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return m(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var y=o.Typography.Text;function v(e){if(null==e||""===e)return"—";var t=Number(e);return Number.isFinite(t)?t.toLocaleString(void 0,{maximumFractionDigits:8}):"—"}var b=[i()().subtract(29,"day").startOf("day"),i()().endOf("day")],E=function(){var e,t,n,a,c,i,m,E,I,h,S,k,w,C,O=(0,d.k)(),T=f(o.Form.useForm(),1)[0],D=f((0,r.useState)({from:b[0].toISOString(),to:b[1].add(1,"millisecond").toISOString()}),2),x=D[0],U=D[1],P=f((0,r.useState)("model"),2),j=P[0],A=P[1],M=f((0,r.useState)(1),2),F=M[0],L=M[1],z=f((0,r.useState)(1),2),B=z[0],N=z[1],_=f((0,r.useState)(null),2),R=_[0],G=_[1],K=(0,r.useMemo)(function(){return g(p({},x),{groupBy:j,page:F,pageSize:20})},[x,j,F]),V=(0,r.useMemo)(function(){return g(p({},x),{page:B,pageSize:20})},[x,B]),q=(0,u.b)({url:"agentUsage:summary",params:x},{refreshDeps:[x]}),$=(0,u.b)({url:"agentUsage:breakdown",params:K},{refreshDeps:[K]}),H=(0,u.b)({url:"agentUsage:calls",params:V},{refreshDeps:[V]}),J=null==(e=q.data)?void 0:e.data,Q=[{title:O("Group"),dataIndex:"key",render:function(e){return null!=e?e:O("Unknown")}},{title:O("Department attribution"),dataIndex:"departmentAttribution",render:function(e){return e?O("Usage attribution: ".concat(e)):"—"}},{title:O("Model calls"),dataIndex:"calls",render:v},{title:O("Input tokens"),dataIndex:"inputTokens",render:v},{title:O("Output tokens"),dataIndex:"outputTokens",render:v},{title:O("Priced subtotal"),key:"cost",render:function(e,t){return"".concat(v(t.knownCost)," ").concat(t.currency||"")}},{title:O("Missing usage calls"),dataIndex:"missingCalls",render:v},{title:O("Unpriced calls"),dataIndex:"unpricedCalls",render:v}],W=[{title:O("Time"),key:"time",render:function(e,t){var n=t.usageOccurredAt||t.startedAt||t.createdAt;if(!n)return"—";var r=new Date(n);return Number.isNaN(r.getTime())?"—":r.toLocaleString()}},{title:O("Model"),dataIndex:"model",render:function(e){return e||"—"}},{title:O("Employee"),dataIndex:"employeeUsername",render:function(e){return e||"—"}},{title:O("User ID"),dataIndex:"userId",render:function(e){return null!=e?e:"—"}},{title:O("Department ID"),dataIndex:"departmentId",render:function(e){return null!=e?e:"—"}},{title:O("Input tokens"),dataIndex:"inputTokens",render:v},{title:O("Output tokens"),dataIndex:"outputTokens",render:v},{title:O("Cost"),key:"cost",render:function(e,t){return"".concat(v(t.cost)," ").concat(t.priceCurrency||"")}},{title:O("Usage source"),dataIndex:"usageSource",render:function(e){return e?O(e):O("Unknown")}},{title:O("Actions"),key:"actions",render:function(e,t){return l().createElement(o.Button,{onClick:function(){return G(t)}},O("Details"))}}];return l().createElement(o.Space,{direction:"vertical",size:"large",style:{width:"100%"}},l().createElement(o.Alert,{type:"info",showIcon:!0,message:O("Usage ledger coverage"),description:O("Usage ledger coverage description")}),l().createElement(o.Card,{title:O("Usage filters")},l().createElement(o.Form,{form:T,layout:"vertical",initialValues:{dates:b},onFinish:function(e){for(var t=f(e.dates||b,2),n=t[0],r=t[1],l={from:n.startOf("day").toISOString(),to:r.add(1,"day").startOf("day").toISOString()},a=0,o=["provider","llmService","model","employeeUsername","userId","departmentId"];a<o.length;a++){var c,i=o[a],u=null==(c=e[i])?void 0:c.trim();u&&(l[i]=u)}e.includeInferredDepartment&&(l.includeInferredDepartment=!0),L(1),N(1),G(null),U(l)}},l().createElement(o.Space,{wrap:!0,align:"start"},l().createElement(o.Form.Item,{name:"dates",label:O("Date range"),rules:[{required:!0,message:O("Select a date range")}]},l().createElement(o.DatePicker.RangePicker,{allowClear:!1})),l().createElement(o.Form.Item,{name:"employeeUsername",label:O("Employee")},l().createElement(s.j,{placeholder:O("All employees")})),l().createElement(o.Form.Item,{name:"provider",label:O("Provider")},l().createElement(o.Input,{allowClear:!0})),l().createElement(o.Form.Item,{name:"llmService",label:O("LLM service")},l().createElement(o.Input,{allowClear:!0})),l().createElement(o.Form.Item,{name:"model",label:O("Model")},l().createElement(o.Input,{allowClear:!0})),l().createElement(o.Form.Item,{name:"userId",label:O("User ID")},l().createElement(o.Input,{allowClear:!0,inputMode:"numeric"})),l().createElement(o.Form.Item,{name:"departmentId",label:O("Department ID")},l().createElement(o.Input,{allowClear:!0,inputMode:"numeric"}))),l().createElement(o.Form.Item,{name:"includeInferredDepartment",valuePropName:"checked",label:O("Include inferred departments")},l().createElement(o.Switch,{"aria-label":O("Include inferred departments")})),l().createElement(o.Button,{type:"primary",htmlType:"submit"},O("Apply filters")))),!!(q.error||$.error||H.error)&&l().createElement(o.Alert,{type:"error",showIcon:!0,message:O("Unable to load usage data")}),l().createElement(o.Card,{title:O("Usage summary"),loading:q.loading},l().createElement(o.Space,{direction:"vertical",style:{width:"100%"}},l().createElement(o.Space,{wrap:!0},l().createElement(o.Tag,null,O("Model calls"),": ",v(null==J?void 0:J.calls)),l().createElement(o.Tag,null,O("Input tokens"),": ",v(null==J?void 0:J.inputTokens)),l().createElement(o.Tag,null,O("Output tokens"),": ",v(null==J?void 0:J.outputTokens)),l().createElement(o.Tag,null,O("Cached input tokens"),": ",v(null==J?void 0:J.cachedTokens)),l().createElement(o.Tag,null,O("Reasoning tokens"),": ",v(null==J?void 0:J.reasoningTokens)),l().createElement(o.Tag,null,O("Actual usage calls"),": ",v(null==J?void 0:J.actualCalls)),l().createElement(o.Tag,{color:"gold"},O("Estimated calls"),": ",v(null==J?void 0:J.estimatedCalls)),l().createElement(o.Tag,{color:"gold"},O("Missing usage calls"),": ",v(null==J?void 0:J.missingCalls)),l().createElement(o.Tag,{color:"gold"},O("Unpriced calls"),": ",v(null==J?void 0:J.unpricedCalls))),l().createElement(o.Space,{wrap:!0},l().createElement(o.Tag,null,O("Department snapshot calls"),": ",v(null==J||null==(t=J.coverage)?void 0:t.snapshotCalls)),l().createElement(o.Tag,null,O("Department inferred calls"),": ",v(null==J||null==(n=J.coverage)?void 0:n.inferredCalls)),l().createElement(o.Tag,{color:"gold"},O("Department unattributed calls"),": ",v(null==J||null==(a=J.coverage)?void 0:a.unattributedCalls)),l().createElement(o.Tag,{color:"gold"},O("Calls without usage identity"),": ",v(null==J||null==(c=J.coverage)?void 0:c.unidentifiedCalls))),l().createElement(y,null,O("Priced subtotal"),":"," ",(null==J||null==(i=J.costByCurrency)?void 0:i.length)?J.costByCurrency.map(function(e){return"".concat(v(e.knownCost)," ").concat(e.currency)}).join(", "):"—"),l().createElement(y,{type:"secondary"},O("Inferred departments are current membership only")))),l().createElement(o.Card,{title:O("Usage breakdown"),extra:l().createElement(o.Select,{"aria-label":O("Group by"),value:j,style:{width:180},onChange:function(e){L(1),A(e)},options:[{value:"model",label:O("Model")},{value:"provider",label:O("Provider")},{value:"llmService",label:O("LLM service")},{value:"employeeUsername",label:O("Employee")},{value:"userId",label:O("User")},{value:"departmentId",label:O("Department")}]})},l().createElement(o.Table,{rowKey:function(e){var t,n,r;return"".concat(null!=(t=e.key)?t:"unknown",":").concat(null!=(n=e.currency)?n:"",":").concat(null!=(r=e.departmentAttribution)?r:"")},columns:Q,dataSource:(null==(m=$.data)?void 0:m.data)||[],loading:$.loading,scroll:{x:"max-content"},pagination:{current:F,pageSize:20,total:(F-1)*20+((null==(I=$.data)||null==(E=I.data)?void 0:E.length)||0)+ +(null!=(S=$.data)&&null!=(h=S.meta)&&!!h.hasMore),showSizeChanger:!1,onChange:L}})),l().createElement(o.Card,{title:O("Model calls")},l().createElement(o.Table,{rowKey:"id",columns:W,dataSource:(null==(k=H.data)?void 0:k.data)||[],loading:H.loading,scroll:{x:"max-content"},pagination:{current:B,pageSize:20,total:(null==(C=H.data)||null==(w=C.meta)?void 0:w.count)||0,onChange:N}})),R&&l().createElement(o.Card,{title:O("Model call details"),extra:l().createElement(o.Button,{onClick:function(){return G(null)}},O("Close"))},l().createElement(o.Space,{direction:"vertical"},l().createElement(y,null,O("Provider"),": ",R.provider||"—"),l().createElement(y,null,O("LLM service"),": ",R.llmService||"—"),l().createElement(y,null,O("Cached input tokens"),": ",v(R.cachedTokens)),l().createElement(y,null,O("Reasoning tokens"),": ",v(R.reasoningTokens)),l().createElement(y,null,O("Department attribution"),":"," ",R.departmentAttribution?O("Usage attribution: ".concat(R.departmentAttribution)):O("Unknown")),l().createElement(y,null,O("Pricing status"),": ",R.pricingStatus||"—"),l().createElement(y,null,O("Price version"),": ",R.priceVersion||"—"),l().createElement(y,null,O("Session"),": ",R.usageSessionId||"—"))))},I=function(e){var t=e.embedded;return l().createElement(a.l,null,l().createElement("div",{style:t?void 0:{padding:"0 24px 24px"}},l().createElement(E,null)))}}}]);