plugin-agent-orchestrator 1.1.3 → 1.1.5

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 (218) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/253.59577b40d9875be0.js +10 -0
  6. package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
  7. package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
  8. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  9. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  10. package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
  11. package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
  12. package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
  13. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  14. package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
  15. package/dist/client-v2/index.js +1 -1
  16. package/dist/externalVersion.js +8 -7
  17. package/dist/locale/en-US.json +199 -123
  18. package/dist/locale/vi-VN.json +199 -123
  19. package/dist/locale/zh-CN.json +199 -123
  20. package/dist/server/collections/agent-execution-spans.js +55 -0
  21. package/dist/server/collections/agent-harness-profile-versions.js +56 -0
  22. package/dist/server/collections/agent-harness-profiles.js +12 -0
  23. package/dist/server/collections/agent-loop-action-approvals.js +69 -0
  24. package/dist/server/collections/agent-loop-artifacts.js +55 -0
  25. package/dist/server/collections/agent-loop-circuit-states.js +53 -0
  26. package/dist/server/collections/agent-loop-control-settings.js +51 -0
  27. package/dist/server/collections/agent-loop-events.js +27 -0
  28. package/dist/server/collections/agent-loop-path-locks.js +57 -0
  29. package/dist/server/collections/agent-loop-patterns.js +72 -0
  30. package/dist/server/collections/agent-loop-runs.js +170 -3
  31. package/dist/server/collections/agent-loop-steps.js +76 -0
  32. package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
  33. package/dist/server/collections/agent-loop-worktrees.js +55 -0
  34. package/dist/server/collections/skill-executions.js +8 -0
  35. package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
  36. package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
  37. package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
  38. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
  39. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
  40. package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
  41. package/dist/server/plugin.js +54 -150
  42. package/dist/server/resources/agent-harness-profile.js +117 -0
  43. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  44. package/dist/server/resources/agent-loop-approval.js +108 -0
  45. package/dist/server/resources/agent-loop-artifact.js +86 -0
  46. package/dist/server/resources/agent-loop-events-stream.js +130 -0
  47. package/dist/server/resources/agent-loop.js +183 -139
  48. package/dist/server/resources/resource-helpers.js +63 -0
  49. package/dist/server/resources/tracing.js +121 -107
  50. package/dist/server/services/AgentMemoryContextService.js +34 -0
  51. package/dist/server/services/DurableCircuitBreakerService.js +229 -0
  52. package/dist/server/services/HarnessCompiler.js +175 -0
  53. package/dist/server/services/HarnessProfileService.js +233 -0
  54. package/dist/server/services/HarnessSchema.js +194 -0
  55. package/dist/server/services/LoopBudgetService.js +269 -0
  56. package/dist/server/services/LoopControlService.js +139 -0
  57. package/dist/server/services/LoopPatternSchema.js +195 -0
  58. package/dist/server/services/LoopPatternService.js +132 -0
  59. package/dist/server/services/LoopRunRepository.js +285 -0
  60. package/dist/server/services/LoopRunStateMachine.js +478 -0
  61. package/dist/server/services/LoopSchedulerService.js +193 -0
  62. package/dist/server/services/LoopTriggerService.js +165 -0
  63. package/dist/server/services/LoopWorkerService.js +699 -0
  64. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  65. package/dist/server/services/PathLockService.js +288 -0
  66. package/dist/server/services/PluginAiRuntimeAdapter.js +226 -0
  67. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  68. package/dist/server/services/VerificationSchema.js +59 -0
  69. package/dist/server/services/VerificationService.js +235 -0
  70. package/dist/server/services/harness-runtime-policy.js +139 -0
  71. package/dist/server/skill-hub/actions/git-import.js +13 -7
  72. package/dist/server/skill-hub/plugin.js +36 -3
  73. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
  74. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  75. package/dist/server/utils/ensure-indexes.js +111 -0
  76. package/dist/server/utils/loop-pattern-context.js +56 -0
  77. package/package.json +53 -53
  78. package/src/client/ApprovalsTab.tsx +2 -0
  79. package/src/client/OrchestratorSettings.tsx +55 -0
  80. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  81. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  82. package/src/client/skill-hub/index.tsx +0 -52
  83. package/src/client-v2/components/AgentRunsTab.tsx +100 -18
  84. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  85. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -100
  86. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -125
  87. package/src/client-v2/components/TracingTab.tsx +160 -77
  88. package/src/client-v2/hooks/useApiRequest.ts +28 -8
  89. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  90. package/src/client-v2/plugin.tsx +6 -6
  91. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +11 -6
  92. package/src/locale/en-US.json +199 -123
  93. package/src/locale/vi-VN.json +199 -123
  94. package/src/locale/zh-CN.json +199 -123
  95. package/src/server/__tests__/circuit-breaker.test.ts +248 -169
  96. package/src/server/__tests__/harness-compiler.test.ts +214 -0
  97. package/src/server/__tests__/harness-profile-service.test.ts +167 -0
  98. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  99. package/src/server/__tests__/harness-tool-plan.test.ts +172 -0
  100. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  101. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  102. package/src/server/__tests__/loop-budget-service.test.ts +255 -0
  103. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
  104. package/src/server/__tests__/loop-pattern-schema.test.ts +73 -0
  105. package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
  106. package/src/server/__tests__/loop-run-state-machine.test.ts +101 -0
  107. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  108. package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
  109. package/src/server/__tests__/loop-worker-execution.test.ts +317 -0
  110. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  111. package/src/server/__tests__/path-lock-service.test.ts +254 -0
  112. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  113. package/src/server/__tests__/smoke.test.ts +162 -121
  114. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  115. package/src/server/collections/agent-execution-spans.ts +55 -0
  116. package/src/server/collections/agent-harness-profile-versions.ts +26 -0
  117. package/src/server/collections/agent-harness-profiles.ts +71 -59
  118. package/src/server/collections/agent-loop-action-approvals.ts +39 -0
  119. package/src/server/collections/agent-loop-artifacts.ts +25 -0
  120. package/src/server/collections/agent-loop-circuit-states.ts +23 -0
  121. package/src/server/collections/agent-loop-control-settings.ts +21 -0
  122. package/src/server/collections/agent-loop-events.ts +98 -71
  123. package/src/server/collections/agent-loop-path-locks.ts +27 -0
  124. package/src/server/collections/agent-loop-patterns.ts +42 -0
  125. package/src/server/collections/agent-loop-runs.ts +170 -3
  126. package/src/server/collections/agent-loop-steps.ts +76 -0
  127. package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
  128. package/src/server/collections/agent-loop-worktrees.ts +25 -0
  129. package/src/server/collections/skill-executions.ts +8 -0
  130. package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +52 -49
  131. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -46
  132. package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +45 -38
  133. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -32
  134. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -30
  135. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
  136. package/src/server/plugin.ts +55 -167
  137. package/src/server/resources/agent-harness-profile.ts +94 -0
  138. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  139. package/src/server/resources/agent-loop-approval.ts +84 -0
  140. package/src/server/resources/agent-loop-artifact.ts +56 -0
  141. package/src/server/resources/agent-loop-events-stream.ts +105 -0
  142. package/src/server/resources/agent-loop.ts +204 -143
  143. package/src/server/resources/agent-monitor.ts +482 -482
  144. package/src/server/resources/resource-helpers.ts +33 -0
  145. package/src/server/resources/tracing.ts +266 -258
  146. package/src/server/services/AgentMemoryContextService.ts +44 -0
  147. package/src/server/services/DurableCircuitBreakerService.ts +239 -0
  148. package/src/server/services/ExecutionSpanService.ts +2 -0
  149. package/src/server/services/HarnessCompiler.ts +170 -0
  150. package/src/server/services/HarnessProfileService.ts +239 -0
  151. package/src/server/services/HarnessSchema.ts +194 -0
  152. package/src/server/services/LoopBudgetService.ts +275 -0
  153. package/src/server/services/LoopControlService.ts +124 -0
  154. package/src/server/services/LoopPatternSchema.ts +185 -0
  155. package/src/server/services/LoopPatternService.ts +143 -0
  156. package/src/server/services/LoopRunRepository.ts +336 -0
  157. package/src/server/services/LoopRunStateMachine.ts +529 -0
  158. package/src/server/services/LoopSchedulerService.ts +199 -0
  159. package/src/server/services/LoopTriggerService.ts +157 -0
  160. package/src/server/services/LoopWorkerService.ts +822 -0
  161. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  162. package/src/server/services/PathLockService.ts +321 -0
  163. package/src/server/services/PluginAiRuntimeAdapter.ts +332 -0
  164. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  165. package/src/server/services/VerificationSchema.ts +31 -0
  166. package/src/server/services/VerificationService.ts +264 -0
  167. package/src/server/services/harness-runtime-policy.ts +141 -0
  168. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +15 -1
  169. package/src/server/skill-hub/actions/git-import.ts +9 -3
  170. package/src/server/skill-hub/plugin.ts +41 -3
  171. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -239
  172. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -63
  173. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  174. package/src/server/utils/ensure-indexes.ts +96 -0
  175. package/src/server/utils/logging.ts +62 -63
  176. package/src/server/utils/loop-pattern-context.ts +20 -0
  177. package/dist/client-v2/214.79650a549273f163.js +0 -10
  178. package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
  179. package/dist/client-v2/264.718a107e43fc163c.js +0 -10
  180. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  181. package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
  182. package/dist/client-v2/53.7c29c28043e9112d.js +0 -10
  183. package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
  184. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  185. package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
  186. package/dist/server/services/AgentHarness.js +0 -81
  187. package/dist/server/services/AgentLoopController.js +0 -1023
  188. package/dist/server/services/AgentLoopRepository.js +0 -192
  189. package/dist/server/services/AgentLoopService.js +0 -142
  190. package/dist/server/services/AgentPlanValidator.js +0 -99
  191. package/dist/server/services/AgentPlannerService.js +0 -99
  192. package/dist/server/services/CircuitBreaker.js +0 -125
  193. package/dist/server/services/ContextAggregator.js +0 -201
  194. package/dist/server/services/PlanningPromptService.js +0 -95
  195. package/dist/server/tools/agent-loop.js +0 -373
  196. package/dist/server/tools/orchestrator-plan.js +0 -254
  197. package/src/client/AIEmployeeSelect.tsx +0 -47
  198. package/src/client/AIEmployeesContext.tsx +0 -102
  199. package/src/client/RulesTab.tsx +0 -2
  200. package/src/client/TracingTab.tsx +0 -436
  201. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  202. package/src/client-v2/components/RulesTab.tsx +0 -2
  203. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
  204. package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
  205. package/src/server/__tests__/context-aggregator.test.ts +0 -222
  206. package/src/server/__tests__/parallel-execution.test.ts +0 -318
  207. package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
  208. package/src/server/services/AgentHarness.ts +0 -67
  209. package/src/server/services/AgentLoopController.ts +0 -1263
  210. package/src/server/services/AgentLoopRepository.ts +0 -178
  211. package/src/server/services/AgentLoopService.ts +0 -177
  212. package/src/server/services/AgentPlanValidator.ts +0 -73
  213. package/src/server/services/AgentPlannerService.ts +0 -80
  214. package/src/server/services/CircuitBreaker.ts +0 -126
  215. package/src/server/services/ContextAggregator.ts +0 -239
  216. package/src/server/services/PlanningPromptService.ts +0 -72
  217. package/src/server/tools/agent-loop.ts +0 -360
  218. package/src/server/tools/orchestrator-plan.ts +0 -255
@@ -0,0 +1,130 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var agent_loop_events_stream_exports = {};
28
+ __export(agent_loop_events_stream_exports, {
29
+ registerAgentLoopEventsStreamResource: () => registerAgentLoopEventsStreamResource
30
+ });
31
+ module.exports = __toCommonJS(agent_loop_events_stream_exports);
32
+ var import_LoopRunRepository = require("../services/LoopRunRepository");
33
+ var import_RunEventBus = require("../services/RunEventBus");
34
+ var import_resource_helpers = require("./resource-helpers");
35
+ const POLL_INTERVAL_MS = 1500;
36
+ function eventId(event) {
37
+ if (!event || typeof event !== "object") return 0;
38
+ const id = Number(event.id);
39
+ return Number.isSafeInteger(id) && id > 0 ? id : 0;
40
+ }
41
+ function plainEvent(event) {
42
+ if (!event || typeof event !== "object") return event;
43
+ const record = event;
44
+ return typeof record.toJSON === "function" ? record.toJSON() : event;
45
+ }
46
+ function writeEvent(ctx, event) {
47
+ const id = eventId(event);
48
+ if (id > 0) ctx.res.write(`id: ${id}
49
+ `);
50
+ ctx.res.write(`data: ${JSON.stringify(plainEvent(event))}
51
+
52
+ `);
53
+ }
54
+ function registerAgentLoopEventsStreamResource(plugin) {
55
+ const repository = new import_LoopRunRepository.LoopRunRepository(plugin.db);
56
+ plugin.app.resource({
57
+ name: "agentLoopEventsStream",
58
+ actions: {
59
+ async stream(ctx, next) {
60
+ try {
61
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
62
+ const runId = Number(ctx.action.params.runId || ctx.action.params.filterByTk);
63
+ if (!Number.isSafeInteger(runId) || runId <= 0) ctx.throw(400, "runId is required");
64
+ await repository.requireOwnedRun(runId, actor.userId, actor.isAdmin);
65
+ ctx.set({
66
+ "Content-Type": "text/event-stream",
67
+ "Cache-Control": "no-cache",
68
+ Connection: "keep-alive"
69
+ });
70
+ ctx.status = 200;
71
+ let closed = false;
72
+ let lastEventId = Number(ctx.get("Last-Event-ID")) || 0;
73
+ const close = () => {
74
+ closed = true;
75
+ };
76
+ const send = (event) => {
77
+ const id = eventId(event);
78
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded || id > 0 && id <= lastEventId) return;
79
+ writeEvent(ctx, event);
80
+ if (id > 0) lastEventId = id;
81
+ };
82
+ ctx.req.once("aborted", close);
83
+ ctx.res.once("close", close);
84
+ const unsubscribe = (0, import_RunEventBus.getRunEventBus)().subscribe(runId, send);
85
+ try {
86
+ const initial = await ctx.db.getRepository("agentLoopEvents").find({
87
+ filter: lastEventId > 0 ? { runId, id: { $gt: lastEventId } } : { runId },
88
+ sort: ["id"],
89
+ pageSize: 1e3
90
+ });
91
+ for (const event of initial) send(event);
92
+ await new Promise((resolve) => {
93
+ const poll = async () => {
94
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded) {
95
+ resolve();
96
+ return;
97
+ }
98
+ try {
99
+ const events = await ctx.db.getRepository("agentLoopEvents").find({
100
+ filter: { runId, id: { $gt: lastEventId } },
101
+ sort: ["id"],
102
+ pageSize: 1e3
103
+ });
104
+ for (const event of events) send(event);
105
+ } catch (error) {
106
+ ctx.log.error("[AgentOrchestrator] Failed to poll loop events", error);
107
+ }
108
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded) resolve();
109
+ else setTimeout(poll, POLL_INTERVAL_MS);
110
+ };
111
+ setTimeout(poll, POLL_INTERVAL_MS);
112
+ });
113
+ } finally {
114
+ unsubscribe();
115
+ ctx.req.off("aborted", close);
116
+ ctx.res.off("close", close);
117
+ if (!ctx.res.destroyed && !ctx.res.writableEnded) ctx.res.end();
118
+ }
119
+ } catch (error) {
120
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
121
+ }
122
+ await next();
123
+ }
124
+ }
125
+ });
126
+ }
127
+ // Annotate the CommonJS export names for ESM import in node:
128
+ 0 && (module.exports = {
129
+ registerAgentLoopEventsStreamResource
130
+ });
@@ -29,178 +29,222 @@ __export(agent_loop_exports, {
29
29
  registerAgentLoopResource: () => registerAgentLoopResource
30
30
  });
31
31
  module.exports = __toCommonJS(agent_loop_exports);
32
+ var import_node_crypto = require("node:crypto");
33
+ var import_LoopPatternService = require("../services/LoopPatternService");
34
+ var import_LoopRunRepository = require("../services/LoopRunRepository");
35
+ var import_LoopRunStateMachine = require("../services/LoopRunStateMachine");
36
+ var import_LoopTriggerService = require("../services/LoopTriggerService");
37
+ var import_LoopWorkerService = require("../services/LoopWorkerService");
32
38
  var import_ctx_utils = require("../utils/ctx-utils");
33
- function formatRunRow(raw) {
34
- const row = (0, import_ctx_utils.toPlain)(raw);
39
+ var import_loop_pattern_context = require("../utils/loop-pattern-context");
40
+ var import_resource_helpers = require("./resource-helpers");
41
+ function formatRunRow(row) {
35
42
  return {
36
- id: row.id,
37
- rootRunId: row.rootRunId,
38
- sessionId: row.sessionId,
39
- messageId: row.messageId,
40
- leaderUsername: row.leaderUsername,
41
- goal: row.goal,
42
- status: row.status,
43
- approvalStatus: row.approvalStatus,
44
- planVersion: row.planVersion,
45
- planSource: row.planSource,
46
- plannerModel: row.plannerModel,
47
- approvedById: row.approvedById,
48
- approvedAt: row.approvedAt,
49
- rejectionReason: row.rejectionReason,
50
- changeRequest: row.changeRequest,
51
- currentStepId: row.currentStepId,
52
- iterationCount: row.iterationCount || 0,
53
- finalAnswer: row.finalAnswer,
54
- summary: row.summary,
55
- userId: row.userId,
56
- startedAt: row.startedAt,
57
- endedAt: row.endedAt,
58
- createdAt: row.createdAt,
59
- updatedAt: row.updatedAt
43
+ ...row,
44
+ historical: row.runtimeVersion !== "control-plane-v2",
45
+ readOnly: row.runtimeVersion !== "control-plane-v2"
60
46
  };
61
47
  }
62
- function registerAgentLoopResource(plugin, service) {
63
- const app = plugin.app;
64
- app.resource({
48
+ function runIdFromContext(ctx) {
49
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
50
+ return values.runId || ctx.action.params.filterByTk;
51
+ }
52
+ function stringValue(value) {
53
+ return typeof value === "string" ? value.trim() : "";
54
+ }
55
+ function statusValue(value) {
56
+ if (typeof value === "string" && import_LoopRunStateMachine.loopRunStatuses.includes(value)) {
57
+ return value;
58
+ }
59
+ throw new Error(`Unknown Loop Control Plane run status: ${String(value)}.`);
60
+ }
61
+ function manualAllowedUserIds(pattern) {
62
+ const triggerConfig = (0, import_ctx_utils.asObject)(pattern.triggerConfig);
63
+ const configured = triggerConfig.allowedUserIds;
64
+ if (!Array.isArray(configured)) return [];
65
+ return configured.map(Number).filter((id) => Number.isSafeInteger(id) && id > 0);
66
+ }
67
+ async function abortRunEverywhere(plugin, runId) {
68
+ var _a;
69
+ (_a = plugin.loopWorker) == null ? void 0 : _a.abortRun(runId);
70
+ await plugin.sendSyncMessage((0, import_LoopWorkerService.loopWorkerAbortMessage)(runId));
71
+ }
72
+ async function transitionOwnedRun(plugin, stateMachine, repository, ctx, to, input) {
73
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
74
+ const runId = runIdFromContext(ctx);
75
+ if (!runId) ctx.throw(400, "runId is required");
76
+ await repository.requireMutableV2Run(runId, actor.userId, actor.isAdmin);
77
+ const transitioned = await stateMachine.transition({
78
+ runId: Number(runId),
79
+ to,
80
+ actorType: "human",
81
+ actorIdentity: String(actor.userId),
82
+ eventType: input == null ? void 0 : input.eventType,
83
+ values: input == null ? void 0 : input.values,
84
+ humanAccepted: input == null ? void 0 : input.humanAccepted
85
+ });
86
+ if (input == null ? void 0 : input.abort) await abortRunEverywhere(plugin, Number(runId));
87
+ return transitioned;
88
+ }
89
+ function registerAgentLoopResource(plugin) {
90
+ const repository = new import_LoopRunRepository.LoopRunRepository(plugin.db);
91
+ const stateMachine = new import_LoopRunStateMachine.LoopRunStateMachine(plugin.db);
92
+ const patterns = new import_LoopPatternService.LoopPatternService(
93
+ plugin.db,
94
+ (0, import_loop_pattern_context.employeeHarnessResolver)(plugin),
95
+ async () => (0, import_loop_pattern_context.worktreeCapability)(plugin)
96
+ );
97
+ const triggers = new import_LoopTriggerService.LoopTriggerService(plugin.db, patterns);
98
+ plugin.app.resource({
65
99
  name: "agentLoops",
66
100
  actions: {
67
101
  async list(ctx, next) {
68
- const { page = 1, pageSize = 20, sort = ["-createdAt"], filter = {} } = ctx.action.params;
69
- const repo = ctx.db.getRepository("agentLoopRuns");
70
- const [rows, count] = await repo.findAndCount({
71
- filter,
72
- sort,
73
- offset: (Number(page) - 1) * Number(pageSize),
74
- limit: Number(pageSize)
75
- });
76
- ctx.body = {
77
- data: rows.map(formatRunRow),
78
- meta: {
79
- count,
80
- page: Number(page),
81
- pageSize: Number(pageSize),
82
- totalPage: Math.ceil(count / Number(pageSize))
83
- }
84
- };
102
+ try {
103
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
104
+ const result = await repository.listOwnedRuns({
105
+ userId: actor.userId,
106
+ isAdmin: actor.isAdmin,
107
+ filter: ctx.action.params.filter || {},
108
+ sort: ctx.action.params.sort,
109
+ page: Number(ctx.action.params.page),
110
+ pageSize: Number(ctx.action.params.pageSize)
111
+ });
112
+ ctx.body = {
113
+ data: result.rows.map(formatRunRow),
114
+ meta: {
115
+ count: result.count,
116
+ page: result.page,
117
+ pageSize: result.pageSize,
118
+ totalPage: result.totalPage
119
+ }
120
+ };
121
+ } catch (error) {
122
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
123
+ }
85
124
  await next();
86
125
  },
87
126
  async get(ctx, next) {
88
- const { filterByTk } = ctx.action.params;
89
- if (!filterByTk) {
90
- ctx.throw(400, "run id is required");
91
- return;
127
+ try {
128
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
129
+ const runId = runIdFromContext(ctx);
130
+ if (!runId) ctx.throw(400, "run id is required");
131
+ ctx.body = { data: await repository.getOwnedRunDetail(runId, actor.userId, actor.isAdmin) };
132
+ } catch (error) {
133
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
92
134
  }
93
- ctx.body = { data: await service.getRunDetail(filterByTk) };
94
135
  await next();
95
136
  },
96
- async resume(ctx, next) {
97
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
98
- const runId = body.runId || ctx.action.params.filterByTk;
99
- if (!runId) {
100
- ctx.throw(400, "runId is required");
101
- return;
137
+ async runNow(ctx, next) {
138
+ try {
139
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
140
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
141
+ const patternId = Number(values.patternId || ctx.action.params.filterByTk);
142
+ if (!Number.isSafeInteger(patternId) || patternId <= 0) ctx.throw(400, "patternId is required");
143
+ const { pattern } = await patterns.get(patternId);
144
+ if (!actor.isAdmin && !manualAllowedUserIds(pattern).includes(actor.userId)) {
145
+ ctx.throw(403, "This loop pattern does not allow manual runs for the current user.");
146
+ }
147
+ const requestedTriggerKey = stringValue(values.triggerKey);
148
+ const result = await triggers.enqueue({
149
+ patternId,
150
+ triggerType: "manual",
151
+ triggerKey: requestedTriggerKey || `manual:${actor.userId}:${(0, import_node_crypto.randomUUID)()}`,
152
+ triggerPayload: (0, import_ctx_utils.asObject)(values.triggerPayload),
153
+ userId: actor.userId,
154
+ goal: stringValue(values.goal) || void 0,
155
+ perRunHarness: values.perRunHarness
156
+ });
157
+ ctx.body = { data: result };
158
+ } catch (error) {
159
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
102
160
  }
103
- ctx.body = {
104
- data: await service.resumeRun(runId, {
105
- stepId: body.stepId,
106
- approved: body.approved !== false,
107
- editedInput: body.editedInput,
108
- userId: (0, import_ctx_utils.currentUserId)(ctx),
109
- ctx
110
- })
111
- };
112
161
  await next();
113
162
  },
114
- async approvePlan(ctx, next) {
115
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
116
- const runId = body.runId || ctx.action.params.filterByTk;
117
- if (!runId) {
118
- ctx.throw(400, "runId is required");
119
- return;
163
+ async pause(ctx, next) {
164
+ try {
165
+ ctx.body = {
166
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "paused", { abort: true })
167
+ };
168
+ } catch (error) {
169
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
120
170
  }
121
- ctx.body = {
122
- data: await service.approvePlan(runId, {
123
- userId: (0, import_ctx_utils.currentUserId)(ctx),
124
- reason: body.reason
125
- })
126
- };
127
171
  await next();
128
172
  },
129
- async rejectPlan(ctx, next) {
130
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
131
- const runId = body.runId || ctx.action.params.filterByTk;
132
- if (!runId) {
133
- ctx.throw(400, "runId is required");
134
- return;
173
+ async resume(ctx, next) {
174
+ try {
175
+ ctx.body = { data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "queued") };
176
+ } catch (error) {
177
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
135
178
  }
136
- ctx.body = {
137
- data: await service.rejectPlan(runId, {
138
- reason: body.reason,
139
- userId: (0, import_ctx_utils.currentUserId)(ctx)
140
- })
141
- };
142
179
  await next();
143
180
  },
144
- async requestPlanChanges(ctx, next) {
145
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
146
- const runId = body.runId || ctx.action.params.filterByTk;
147
- if (!runId) {
148
- ctx.throw(400, "runId is required");
149
- return;
181
+ async cancel(ctx, next) {
182
+ try {
183
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
184
+ ctx.body = {
185
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "canceled", {
186
+ values: { summary: stringValue(values.reason) || "Canceled by user." },
187
+ eventType: "run_canceled",
188
+ abort: true
189
+ })
190
+ };
191
+ } catch (error) {
192
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
150
193
  }
151
- ctx.body = {
152
- data: await service.requestPlanChanges(runId, {
153
- feedback: body.feedback,
154
- userId: (0, import_ctx_utils.currentUserId)(ctx)
155
- })
156
- };
157
194
  await next();
158
195
  },
159
- async cancel(ctx, next) {
160
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
161
- const runId = body.runId || ctx.action.params.filterByTk;
162
- if (!runId) {
163
- ctx.throw(400, "runId is required");
164
- return;
196
+ async retry(ctx, next) {
197
+ try {
198
+ ctx.body = {
199
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "queued", {
200
+ // Retry is a fresh attempt from the leader: any interrupted-session resume point
201
+ // and prior approval outcome must not leak into the new attempt.
202
+ values: { blockedReason: null, escalationReason: null, resumeContext: null, approvalStatus: null },
203
+ eventType: "run_retried"
204
+ })
205
+ };
206
+ } catch (error) {
207
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
165
208
  }
166
- ctx.body = {
167
- data: await service.cancelRun(runId, {
168
- reason: body.reason,
169
- userId: (0, import_ctx_utils.currentUserId)(ctx)
170
- })
171
- };
172
209
  await next();
173
210
  },
174
- async retryStep(ctx, next) {
175
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
176
- if (!body.stepId) {
177
- ctx.throw(400, "stepId is required");
178
- return;
211
+ async escalate(ctx, next) {
212
+ try {
213
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
214
+ ctx.body = {
215
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "waiting_human", {
216
+ values: { escalationReason: stringValue(values.reason) || "Escalated by user." },
217
+ eventType: "run_escalated"
218
+ })
219
+ };
220
+ } catch (error) {
221
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
179
222
  }
180
- ctx.body = {
181
- data: await service.retryStep(body.stepId, {
182
- userId: (0, import_ctx_utils.currentUserId)(ctx)
183
- })
184
- };
185
223
  await next();
186
224
  },
187
- async stepFeedback(ctx, next) {
188
- const body = (0, import_ctx_utils.valuesFromCtx)(ctx);
189
- if (!body.stepId || !body.rating) {
190
- ctx.throw(400, "stepId and rating are required");
191
- return;
225
+ async acceptResult(ctx, next) {
226
+ try {
227
+ ctx.body = {
228
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "succeeded", {
229
+ humanAccepted: true,
230
+ eventType: "run_result_accepted"
231
+ })
232
+ };
233
+ } catch (error) {
234
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
192
235
  }
193
- if (!["positive", "negative"].includes(body.rating)) {
194
- ctx.throw(400, 'rating must be "positive" or "negative"');
195
- return;
236
+ await next();
237
+ },
238
+ async status(ctx, next) {
239
+ try {
240
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
241
+ const runId = runIdFromContext(ctx);
242
+ if (!runId) ctx.throw(400, "runId is required");
243
+ const run = await repository.requireOwnedRun(runId, actor.userId, actor.isAdmin);
244
+ ctx.body = { data: { id: run.id, status: statusValue(run.status), runtimeVersion: run.runtimeVersion } };
245
+ } catch (error) {
246
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
196
247
  }
197
- ctx.body = {
198
- data: await service.stepFeedback(
199
- body.stepId,
200
- { rating: body.rating, comment: body.comment, category: body.category },
201
- { userId: (0, import_ctx_utils.currentUserId)(ctx) }
202
- )
203
- };
204
248
  await next();
205
249
  }
206
250
  }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var resource_helpers_exports = {};
28
+ __export(resource_helpers_exports, {
29
+ requestActor: () => requestActor,
30
+ requireAdminActor: () => requireAdminActor,
31
+ throwResourceError: () => throwResourceError
32
+ });
33
+ module.exports = __toCommonJS(resource_helpers_exports);
34
+ var import_zod = require("zod");
35
+ var import_ctx_utils = require("../utils/ctx-utils");
36
+ var import_LoopRunRepository = require("../services/LoopRunRepository");
37
+ function requestActor(ctx) {
38
+ const userId = Number((0, import_ctx_utils.currentUserId)(ctx));
39
+ if (!Number.isSafeInteger(userId) || userId <= 0) {
40
+ throw new import_LoopRunRepository.LoopRunAccessError(401, "Authentication is required.");
41
+ }
42
+ return { userId, isAdmin: (0, import_ctx_utils.isAdminUser)(ctx) };
43
+ }
44
+ function requireAdminActor(ctx) {
45
+ const actor = requestActor(ctx);
46
+ if (!actor.isAdmin) throw new import_LoopRunRepository.LoopRunAccessError(403, "Administrator access is required.");
47
+ return actor;
48
+ }
49
+ function throwResourceError(ctx, error) {
50
+ if (error instanceof import_LoopRunRepository.LoopRunAccessError) {
51
+ ctx.throw(error.status, error.message);
52
+ }
53
+ if (error instanceof import_zod.ZodError) {
54
+ ctx.throw(400, error.issues.map((issue) => issue.message).join(" "));
55
+ }
56
+ ctx.throw(409, error instanceof Error ? error.message : "The requested operation could not be completed.");
57
+ }
58
+ // Annotate the CommonJS export names for ESM import in node:
59
+ 0 && (module.exports = {
60
+ requestActor,
61
+ requireAdminActor,
62
+ throwResourceError
63
+ });