plugin-agent-orchestrator 1.1.2 → 1.1.4

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 (173) hide show
  1. package/dist/client/index.js +1 -1
  2. package/dist/client-v2/214.b063f33ba044a808.js +10 -0
  3. package/dist/client-v2/253.59577b40d9875be0.js +10 -0
  4. package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
  5. package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
  6. package/dist/client-v2/418.58fa350f5496efd3.js +10 -0
  7. package/dist/client-v2/{53.7c29c28043e9112d.js → 53.9a10455323390f14.js} +1 -1
  8. package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
  9. package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
  10. package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
  11. package/dist/client-v2/925.e5925bf21ed68e7a.js +10 -0
  12. package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
  13. package/dist/client-v2/index.js +1 -1
  14. package/dist/externalVersion.js +8 -6
  15. package/dist/locale/en-US.json +48 -28
  16. package/dist/locale/vi-VN.json +48 -28
  17. package/dist/locale/zh-CN.json +48 -28
  18. package/dist/server/collections/agent-execution-spans.js +47 -0
  19. package/dist/server/collections/agent-harness-profile-versions.js +56 -0
  20. package/dist/server/collections/agent-harness-profiles.js +12 -0
  21. package/dist/server/collections/agent-loop-action-approvals.js +68 -0
  22. package/dist/server/collections/agent-loop-artifacts.js +55 -0
  23. package/dist/server/collections/agent-loop-circuit-states.js +53 -0
  24. package/dist/server/collections/agent-loop-control-settings.js +51 -0
  25. package/dist/server/collections/agent-loop-events.js +27 -0
  26. package/dist/server/collections/agent-loop-path-locks.js +57 -0
  27. package/dist/server/collections/agent-loop-patterns.js +72 -0
  28. package/dist/server/collections/agent-loop-runs.js +163 -2
  29. package/dist/server/collections/agent-loop-steps.js +69 -0
  30. package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
  31. package/dist/server/collections/agent-loop-worktrees.js +55 -0
  32. package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
  33. package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
  34. package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
  35. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
  36. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
  37. package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
  38. package/dist/server/plugin.js +52 -150
  39. package/dist/server/resources/agent-loop-approval.js +83 -0
  40. package/dist/server/resources/agent-loop-artifact.js +86 -0
  41. package/dist/server/resources/agent-loop-events-stream.js +130 -0
  42. package/dist/server/resources/agent-loop.js +181 -139
  43. package/dist/server/resources/resource-helpers.js +63 -0
  44. package/dist/server/resources/tracing.js +121 -107
  45. package/dist/server/services/DurableCircuitBreakerService.js +229 -0
  46. package/dist/server/services/HarnessCompiler.js +142 -0
  47. package/dist/server/services/HarnessProfileService.js +168 -0
  48. package/dist/server/services/HarnessSchema.js +167 -0
  49. package/dist/server/services/LoopBudgetService.js +269 -0
  50. package/dist/server/services/LoopControlService.js +139 -0
  51. package/dist/server/services/LoopPatternSchema.js +180 -0
  52. package/dist/server/services/LoopPatternService.js +132 -0
  53. package/dist/server/services/LoopRunRepository.js +205 -0
  54. package/dist/server/services/LoopRunStateMachine.js +389 -0
  55. package/dist/server/services/LoopSchedulerService.js +193 -0
  56. package/dist/server/services/LoopTriggerService.js +128 -0
  57. package/dist/server/services/LoopWorkerService.js +461 -0
  58. package/dist/server/services/PathLockService.js +288 -0
  59. package/dist/server/services/PluginAiRuntimeAdapter.js +215 -0
  60. package/dist/server/services/VerificationSchema.js +59 -0
  61. package/dist/server/services/VerificationService.js +169 -0
  62. package/dist/server/skill-hub/actions/git-import.js +13 -7
  63. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
  64. package/dist/server/utils/ensure-indexes.js +111 -0
  65. package/dist/server/utils/loop-pattern-context.js +56 -0
  66. package/package.json +2 -2
  67. package/src/client/OrchestratorSettings.tsx +44 -0
  68. package/src/client-v2/components/AgentRunsTab.tsx +576 -494
  69. package/src/client-v2/components/HarnessProfilesTab.tsx +13 -8
  70. package/src/client-v2/components/MemoryInspectorTab.tsx +19 -3
  71. package/src/client-v2/components/TracingTab.tsx +515 -432
  72. package/src/client-v2/hooks/useApiRequest.ts +141 -121
  73. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +8 -6
  74. package/src/locale/en-US.json +52 -28
  75. package/src/locale/vi-VN.json +52 -28
  76. package/src/locale/zh-CN.json +52 -28
  77. package/src/server/__tests__/circuit-breaker.test.ts +225 -146
  78. package/src/server/__tests__/harness-compiler.test.ts +131 -0
  79. package/src/server/__tests__/harness-profile-service.test.ts +116 -0
  80. package/src/server/__tests__/harness-tool-plan.test.ts +148 -0
  81. package/src/server/__tests__/loop-budget-service.test.ts +255 -0
  82. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
  83. package/src/server/__tests__/loop-pattern-schema.test.ts +56 -0
  84. package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
  85. package/src/server/__tests__/loop-run-state-machine.test.ts +90 -0
  86. package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
  87. package/src/server/__tests__/loop-worker-execution.test.ts +236 -0
  88. package/src/server/__tests__/path-lock-service.test.ts +254 -0
  89. package/src/server/__tests__/smoke.test.ts +62 -21
  90. package/src/server/collections/agent-execution-spans.ts +47 -0
  91. package/src/server/collections/agent-harness-profile-versions.ts +26 -0
  92. package/src/server/collections/agent-harness-profiles.ts +12 -0
  93. package/src/server/collections/agent-loop-action-approvals.ts +38 -0
  94. package/src/server/collections/agent-loop-artifacts.ts +25 -0
  95. package/src/server/collections/agent-loop-circuit-states.ts +23 -0
  96. package/src/server/collections/agent-loop-control-settings.ts +21 -0
  97. package/src/server/collections/agent-loop-events.ts +27 -0
  98. package/src/server/collections/agent-loop-path-locks.ts +27 -0
  99. package/src/server/collections/agent-loop-patterns.ts +42 -0
  100. package/src/server/collections/agent-loop-runs.ts +163 -2
  101. package/src/server/collections/agent-loop-steps.ts +69 -0
  102. package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
  103. package/src/server/collections/agent-loop-worktrees.ts +25 -0
  104. package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +3 -0
  105. package/src/server/migrations/20260429000000-add-llm-fields.ts +3 -2
  106. package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +13 -6
  107. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +2 -1
  108. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +2 -1
  109. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
  110. package/src/server/plugin.ts +53 -167
  111. package/src/server/resources/agent-loop-approval.ts +52 -0
  112. package/src/server/resources/agent-loop-artifact.ts +56 -0
  113. package/src/server/resources/agent-loop-events-stream.ts +105 -0
  114. package/src/server/resources/agent-loop.ts +202 -143
  115. package/src/server/resources/agent-monitor.ts +482 -482
  116. package/src/server/resources/resource-helpers.ts +33 -0
  117. package/src/server/resources/tracing.ts +145 -137
  118. package/src/server/services/DurableCircuitBreakerService.ts +239 -0
  119. package/src/server/services/HarnessCompiler.ts +133 -0
  120. package/src/server/services/HarnessProfileService.ts +157 -0
  121. package/src/server/services/HarnessSchema.ts +163 -0
  122. package/src/server/services/LoopBudgetService.ts +275 -0
  123. package/src/server/services/LoopControlService.ts +124 -0
  124. package/src/server/services/LoopPatternSchema.ts +167 -0
  125. package/src/server/services/LoopPatternService.ts +143 -0
  126. package/src/server/services/LoopRunRepository.ts +237 -0
  127. package/src/server/services/LoopRunStateMachine.ts +432 -0
  128. package/src/server/services/LoopSchedulerService.ts +199 -0
  129. package/src/server/services/LoopTriggerService.ts +115 -0
  130. package/src/server/services/LoopWorkerService.ts +522 -0
  131. package/src/server/services/PathLockService.ts +321 -0
  132. package/src/server/services/PluginAiRuntimeAdapter.ts +315 -0
  133. package/src/server/services/VerificationSchema.ts +31 -0
  134. package/src/server/services/VerificationService.ts +185 -0
  135. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +62 -0
  136. package/src/server/skill-hub/actions/git-import.ts +9 -3
  137. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +1 -5
  138. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +1 -3
  139. package/src/server/utils/ensure-indexes.ts +96 -0
  140. package/src/server/utils/logging.ts +0 -1
  141. package/src/server/utils/loop-pattern-context.ts +20 -0
  142. package/dist/client-v2/214.79650a549273f163.js +0 -10
  143. package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
  144. package/dist/client-v2/264.718a107e43fc163c.js +0 -10
  145. package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
  146. package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
  147. package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
  148. package/dist/server/services/AgentHarness.js +0 -81
  149. package/dist/server/services/AgentLoopController.js +0 -1023
  150. package/dist/server/services/AgentLoopRepository.js +0 -192
  151. package/dist/server/services/AgentLoopService.js +0 -142
  152. package/dist/server/services/AgentPlanValidator.js +0 -99
  153. package/dist/server/services/AgentPlannerService.js +0 -99
  154. package/dist/server/services/CircuitBreaker.js +0 -125
  155. package/dist/server/services/ContextAggregator.js +0 -201
  156. package/dist/server/services/PlanningPromptService.js +0 -95
  157. package/dist/server/tools/agent-loop.js +0 -373
  158. package/dist/server/tools/orchestrator-plan.js +0 -254
  159. package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
  160. package/src/server/__tests__/context-aggregator.test.ts +0 -222
  161. package/src/server/__tests__/parallel-execution.test.ts +0 -318
  162. package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
  163. package/src/server/services/AgentHarness.ts +0 -67
  164. package/src/server/services/AgentLoopController.ts +0 -1263
  165. package/src/server/services/AgentLoopRepository.ts +0 -178
  166. package/src/server/services/AgentLoopService.ts +0 -177
  167. package/src/server/services/AgentPlanValidator.ts +0 -73
  168. package/src/server/services/AgentPlannerService.ts +0 -80
  169. package/src/server/services/CircuitBreaker.ts +0 -126
  170. package/src/server/services/ContextAggregator.ts +0 -239
  171. package/src/server/services/PlanningPromptService.ts +0 -72
  172. package/src/server/tools/agent-loop.ts +0 -360
  173. package/src/server/tools/orchestrator-plan.ts +0 -255
@@ -0,0 +1,86 @@
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_artifact_exports = {};
28
+ __export(agent_loop_artifact_exports, {
29
+ registerAgentLoopArtifactResource: () => registerAgentLoopArtifactResource
30
+ });
31
+ module.exports = __toCommonJS(agent_loop_artifact_exports);
32
+ var import_LoopRunRepository = require("../services/LoopRunRepository");
33
+ var import_resource_helpers = require("./resource-helpers");
34
+ function artifactMetadata(artifact) {
35
+ const { uri: _storageReference, ...metadata } = artifact;
36
+ return metadata;
37
+ }
38
+ function registerAgentLoopArtifactResource(plugin) {
39
+ const repository = new import_LoopRunRepository.LoopRunRepository(plugin.db);
40
+ plugin.app.resource({
41
+ name: "agentLoopArtifactsView",
42
+ actions: {
43
+ async list(ctx, next) {
44
+ try {
45
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
46
+ const result = await repository.listArtifacts({
47
+ userId: actor.userId,
48
+ isAdmin: actor.isAdmin,
49
+ filter: ctx.action.params.filter || {},
50
+ sort: ctx.action.params.sort,
51
+ page: Number(ctx.action.params.page),
52
+ pageSize: Number(ctx.action.params.pageSize)
53
+ });
54
+ ctx.body = {
55
+ data: result.rows.map(artifactMetadata),
56
+ meta: {
57
+ count: result.count,
58
+ page: result.page,
59
+ pageSize: result.pageSize,
60
+ totalPage: result.totalPage
61
+ }
62
+ };
63
+ } catch (error) {
64
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
65
+ }
66
+ await next();
67
+ },
68
+ async get(ctx, next) {
69
+ try {
70
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
71
+ const artifactId = ctx.action.params.filterByTk;
72
+ if (!artifactId) ctx.throw(400, "artifact id is required");
73
+ const artifact = await repository.requireOwnedArtifact(artifactId, actor.userId, actor.isAdmin);
74
+ ctx.body = { data: artifactMetadata(artifact) };
75
+ } catch (error) {
76
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
77
+ }
78
+ await next();
79
+ }
80
+ }
81
+ });
82
+ }
83
+ // Annotate the CommonJS export names for ESM import in node:
84
+ 0 && (module.exports = {
85
+ registerAgentLoopArtifactResource
86
+ });
@@ -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,220 @@ __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
+ values: { blockedReason: null, escalationReason: null },
201
+ eventType: "run_retried"
202
+ })
203
+ };
204
+ } catch (error) {
205
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
165
206
  }
166
- ctx.body = {
167
- data: await service.cancelRun(runId, {
168
- reason: body.reason,
169
- userId: (0, import_ctx_utils.currentUserId)(ctx)
170
- })
171
- };
172
207
  await next();
173
208
  },
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;
209
+ async escalate(ctx, next) {
210
+ try {
211
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
212
+ ctx.body = {
213
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "waiting_human", {
214
+ values: { escalationReason: stringValue(values.reason) || "Escalated by user." },
215
+ eventType: "run_escalated"
216
+ })
217
+ };
218
+ } catch (error) {
219
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
179
220
  }
180
- ctx.body = {
181
- data: await service.retryStep(body.stepId, {
182
- userId: (0, import_ctx_utils.currentUserId)(ctx)
183
- })
184
- };
185
221
  await next();
186
222
  },
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;
223
+ async acceptResult(ctx, next) {
224
+ try {
225
+ ctx.body = {
226
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "succeeded", {
227
+ humanAccepted: true,
228
+ eventType: "run_result_accepted"
229
+ })
230
+ };
231
+ } catch (error) {
232
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
192
233
  }
193
- if (!["positive", "negative"].includes(body.rating)) {
194
- ctx.throw(400, 'rating must be "positive" or "negative"');
195
- return;
234
+ await next();
235
+ },
236
+ async status(ctx, next) {
237
+ try {
238
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
239
+ const runId = runIdFromContext(ctx);
240
+ if (!runId) ctx.throw(400, "runId is required");
241
+ const run = await repository.requireOwnedRun(runId, actor.userId, actor.isAdmin);
242
+ ctx.body = { data: { id: run.id, status: statusValue(run.status), runtimeVersion: run.runtimeVersion } };
243
+ } catch (error) {
244
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
196
245
  }
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
246
  await next();
205
247
  }
206
248
  }
@@ -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
+ });