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
@@ -220,9 +220,11 @@ export function registerAgentKnowledgeInsightsResource(plugin: Plugin) {
220
220
  sort: ['username'],
221
221
  appends: ['roles'],
222
222
  });
223
- const knowledgeBases = await ctx.db.getRepository('aiKnowledgeBases').find({
224
- sort: ['name'],
225
- });
223
+ // plugin-knowledge-base is an optional integration: when it is disabled the collection
224
+ // is not registered, and the matrix degrades to employees without knowledge bases.
225
+ const knowledgeBases = ctx.db.hasCollection('aiKnowledgeBases')
226
+ ? await ctx.db.getRepository('aiKnowledgeBases').find({ sort: ['name'] })
227
+ : [];
226
228
  ctx.body = { data: buildKnowledgeAccessMatrix(employees, knowledgeBases) };
227
229
  await next();
228
230
  },
@@ -0,0 +1,84 @@
1
+ import type { Plugin } from '@nocobase/server';
2
+ import { LoopRunRepository } from '../services/LoopRunRepository';
3
+ import { asObject, valuesFromCtx } from '../utils/ctx-utils';
4
+ import { requestActor, throwResourceError } from './resource-helpers';
5
+
6
+ export function registerAgentLoopApprovalResource(plugin: Plugin) {
7
+ const repository = new LoopRunRepository(plugin.db);
8
+
9
+ plugin.app.resource({
10
+ name: 'agentLoopApprovals',
11
+ actions: {
12
+ async list(ctx, next) {
13
+ try {
14
+ const actor = requestActor(ctx);
15
+ const result = await repository.listApprovals({
16
+ userId: actor.userId,
17
+ isAdmin: actor.isAdmin,
18
+ filter: ctx.action.params.filter || {},
19
+ sort: ctx.action.params.sort,
20
+ page: Number(ctx.action.params.page),
21
+ pageSize: Number(ctx.action.params.pageSize),
22
+ });
23
+ ctx.body = {
24
+ data: result.rows,
25
+ meta: {
26
+ count: result.count,
27
+ page: result.page,
28
+ pageSize: result.pageSize,
29
+ totalPage: result.totalPage,
30
+ },
31
+ };
32
+ } catch (error) {
33
+ throwResourceError(ctx, error);
34
+ }
35
+ await next();
36
+ },
37
+
38
+ async get(ctx, next) {
39
+ try {
40
+ const actor = requestActor(ctx);
41
+ const approvalId = ctx.action.params.filterByTk;
42
+ if (!approvalId) ctx.throw(400, 'approval id is required');
43
+ ctx.body = {
44
+ data: await repository.requireAccessibleApproval(approvalId, actor.userId, actor.isAdmin),
45
+ };
46
+ } catch (error) {
47
+ throwResourceError(ctx, error);
48
+ }
49
+ await next();
50
+ },
51
+
52
+ async decide(ctx, next) {
53
+ try {
54
+ const actor = requestActor(ctx);
55
+ const approvalId = ctx.action.params.filterByTk;
56
+ if (!approvalId) ctx.throw(400, 'approval id is required');
57
+ const values = valuesFromCtx(ctx);
58
+ const decision =
59
+ values.decision === 'approve' ? 'approved' : values.decision === 'reject' ? 'rejected' : null;
60
+ if (!decision) ctx.throw(400, 'decision must be "approve" or "reject"');
61
+ const editedInput = values.editedInput;
62
+ ctx.body = {
63
+ data: await repository.decideApproval({
64
+ approvalId,
65
+ userId: actor.userId,
66
+ isAdmin: actor.isAdmin,
67
+ decision,
68
+ note: typeof values.note === 'string' ? values.note.trim() : '',
69
+ editedInput:
70
+ decision === 'approved' && editedInput !== undefined
71
+ ? Array.isArray(editedInput)
72
+ ? editedInput
73
+ : asObject(editedInput)
74
+ : undefined,
75
+ }),
76
+ };
77
+ } catch (error) {
78
+ throwResourceError(ctx, error);
79
+ }
80
+ await next();
81
+ },
82
+ },
83
+ });
84
+ }
@@ -0,0 +1,56 @@
1
+ import type { Plugin } from '@nocobase/server';
2
+ import { LoopRunRepository, type LoopRunRecord } from '../services/LoopRunRepository';
3
+ import { requestActor, throwResourceError } from './resource-helpers';
4
+
5
+ function artifactMetadata(artifact: LoopRunRecord) {
6
+ const { uri: _storageReference, ...metadata } = artifact;
7
+ return metadata;
8
+ }
9
+
10
+ export function registerAgentLoopArtifactResource(plugin: Plugin) {
11
+ const repository = new LoopRunRepository(plugin.db);
12
+
13
+ plugin.app.resource({
14
+ name: 'agentLoopArtifactsView',
15
+ actions: {
16
+ async list(ctx, next) {
17
+ try {
18
+ const actor = requestActor(ctx);
19
+ const result = await repository.listArtifacts({
20
+ userId: actor.userId,
21
+ isAdmin: actor.isAdmin,
22
+ filter: ctx.action.params.filter || {},
23
+ sort: ctx.action.params.sort,
24
+ page: Number(ctx.action.params.page),
25
+ pageSize: Number(ctx.action.params.pageSize),
26
+ });
27
+ ctx.body = {
28
+ data: result.rows.map(artifactMetadata),
29
+ meta: {
30
+ count: result.count,
31
+ page: result.page,
32
+ pageSize: result.pageSize,
33
+ totalPage: result.totalPage,
34
+ },
35
+ };
36
+ } catch (error) {
37
+ throwResourceError(ctx, error);
38
+ }
39
+ await next();
40
+ },
41
+
42
+ async get(ctx, next) {
43
+ try {
44
+ const actor = requestActor(ctx);
45
+ const artifactId = ctx.action.params.filterByTk;
46
+ if (!artifactId) ctx.throw(400, 'artifact id is required');
47
+ const artifact = await repository.requireOwnedArtifact(artifactId, actor.userId, actor.isAdmin);
48
+ ctx.body = { data: artifactMetadata(artifact) };
49
+ } catch (error) {
50
+ throwResourceError(ctx, error);
51
+ }
52
+ await next();
53
+ },
54
+ },
55
+ });
56
+ }
@@ -0,0 +1,105 @@
1
+ import type { Context } from '@nocobase/actions';
2
+ import type { Plugin } from '@nocobase/server';
3
+ import { LoopRunRepository } from '../services/LoopRunRepository';
4
+ import { getRunEventBus } from '../services/RunEventBus';
5
+ import { requestActor, throwResourceError } from './resource-helpers';
6
+
7
+ const POLL_INTERVAL_MS = 1500;
8
+
9
+ function eventId(event: unknown) {
10
+ if (!event || typeof event !== 'object') return 0;
11
+ const id = Number((event as Record<string, unknown>).id);
12
+ return Number.isSafeInteger(id) && id > 0 ? id : 0;
13
+ }
14
+
15
+ function plainEvent(event: unknown) {
16
+ if (!event || typeof event !== 'object') return event;
17
+ const record = event as { toJSON?: () => unknown };
18
+ return typeof record.toJSON === 'function' ? record.toJSON() : event;
19
+ }
20
+
21
+ function writeEvent(ctx: Context, event: unknown) {
22
+ const id = eventId(event);
23
+ if (id > 0) ctx.res.write(`id: ${id}\n`);
24
+ ctx.res.write(`data: ${JSON.stringify(plainEvent(event))}\n\n`);
25
+ }
26
+
27
+ export function registerAgentLoopEventsStreamResource(plugin: Plugin) {
28
+ const repository = new LoopRunRepository(plugin.db);
29
+
30
+ plugin.app.resource({
31
+ name: 'agentLoopEventsStream',
32
+ actions: {
33
+ async stream(ctx, next) {
34
+ try {
35
+ const actor = requestActor(ctx);
36
+ const runId = Number(ctx.action.params.runId || ctx.action.params.filterByTk);
37
+ if (!Number.isSafeInteger(runId) || runId <= 0) ctx.throw(400, 'runId is required');
38
+ await repository.requireOwnedRun(runId, actor.userId, actor.isAdmin);
39
+
40
+ ctx.set({
41
+ 'Content-Type': 'text/event-stream',
42
+ 'Cache-Control': 'no-cache',
43
+ Connection: 'keep-alive',
44
+ });
45
+ ctx.status = 200;
46
+
47
+ let closed = false;
48
+ let lastEventId = Number(ctx.get('Last-Event-ID')) || 0;
49
+ const close = () => {
50
+ closed = true;
51
+ };
52
+ const send = (event: unknown) => {
53
+ const id = eventId(event);
54
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded || (id > 0 && id <= lastEventId)) return;
55
+ writeEvent(ctx, event);
56
+ if (id > 0) lastEventId = id;
57
+ };
58
+
59
+ ctx.req.once('aborted', close);
60
+ ctx.res.once('close', close);
61
+ const unsubscribe = getRunEventBus().subscribe(runId, send);
62
+
63
+ try {
64
+ const initial = await ctx.db.getRepository('agentLoopEvents').find({
65
+ filter: lastEventId > 0 ? { runId, id: { $gt: lastEventId } } : { runId },
66
+ sort: ['id'],
67
+ pageSize: 1000,
68
+ });
69
+ for (const event of initial) send(event);
70
+
71
+ await new Promise<void>((resolve) => {
72
+ const poll = async () => {
73
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded) {
74
+ resolve();
75
+ return;
76
+ }
77
+ try {
78
+ const events = await ctx.db.getRepository('agentLoopEvents').find({
79
+ filter: { runId, id: { $gt: lastEventId } },
80
+ sort: ['id'],
81
+ pageSize: 1000,
82
+ });
83
+ for (const event of events) send(event);
84
+ } catch (error) {
85
+ ctx.log.error('[AgentOrchestrator] Failed to poll loop events', error);
86
+ }
87
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded) resolve();
88
+ else setTimeout(poll, POLL_INTERVAL_MS);
89
+ };
90
+ setTimeout(poll, POLL_INTERVAL_MS);
91
+ });
92
+ } finally {
93
+ unsubscribe();
94
+ ctx.req.off('aborted', close);
95
+ ctx.res.off('close', close);
96
+ if (!ctx.res.destroyed && !ctx.res.writableEnded) ctx.res.end();
97
+ }
98
+ } catch (error) {
99
+ throwResourceError(ctx, error);
100
+ }
101
+ await next();
102
+ },
103
+ },
104
+ });
105
+ }
@@ -1,189 +1,250 @@
1
- import { Plugin } from '@nocobase/server';
2
- import { AgentLoopService } from '../services/AgentLoopService';
3
- import { toPlain, currentUserId, valuesFromCtx as values } from '../utils/ctx-utils';
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { Plugin } from '@nocobase/server';
3
+ import { LoopPatternService } from '../services/LoopPatternService';
4
+ import { LoopRunRepository } from '../services/LoopRunRepository';
5
+ import { LoopRunStateMachine, type LoopRunStatus, loopRunStatuses } from '../services/LoopRunStateMachine';
6
+ import { LoopTriggerService } from '../services/LoopTriggerService';
7
+ import { loopWorkerAbortMessage } from '../services/LoopWorkerService';
8
+ import { asObject, valuesFromCtx } from '../utils/ctx-utils';
9
+ import { employeeHarnessResolver, worktreeCapability } from '../utils/loop-pattern-context';
10
+ import { requestActor, throwResourceError } from './resource-helpers';
4
11
 
5
- function formatRunRow(raw: any) {
6
- const row = toPlain(raw);
12
+ type LoopResourcePlugin = Plugin & { loopWorker?: { abortRun(runId: number): void } };
13
+
14
+ function formatRunRow(row: Record<string, unknown>) {
7
15
  return {
8
- id: row.id,
9
- rootRunId: row.rootRunId,
10
- sessionId: row.sessionId,
11
- messageId: row.messageId,
12
- leaderUsername: row.leaderUsername,
13
- goal: row.goal,
14
- status: row.status,
15
- approvalStatus: row.approvalStatus,
16
- planVersion: row.planVersion,
17
- planSource: row.planSource,
18
- plannerModel: row.plannerModel,
19
- approvedById: row.approvedById,
20
- approvedAt: row.approvedAt,
21
- rejectionReason: row.rejectionReason,
22
- changeRequest: row.changeRequest,
23
- currentStepId: row.currentStepId,
24
- iterationCount: row.iterationCount || 0,
25
- finalAnswer: row.finalAnswer,
26
- summary: row.summary,
27
- userId: row.userId,
28
- startedAt: row.startedAt,
29
- endedAt: row.endedAt,
30
- createdAt: row.createdAt,
31
- updatedAt: row.updatedAt,
16
+ ...row,
17
+ historical: row.runtimeVersion !== 'control-plane-v2',
18
+ readOnly: row.runtimeVersion !== 'control-plane-v2',
32
19
  };
33
20
  }
34
21
 
35
- export function registerAgentLoopResource(plugin: Plugin, service: AgentLoopService) {
36
- const app = plugin.app;
22
+ function runIdFromContext(ctx: Parameters<typeof requestActor>[0]) {
23
+ const values = valuesFromCtx(ctx);
24
+ return values.runId || ctx.action.params.filterByTk;
25
+ }
26
+
27
+ function stringValue(value: unknown) {
28
+ return typeof value === 'string' ? value.trim() : '';
29
+ }
30
+
31
+ function statusValue(value: unknown): LoopRunStatus {
32
+ if (typeof value === 'string' && (loopRunStatuses as readonly string[]).includes(value)) {
33
+ return value as LoopRunStatus;
34
+ }
35
+ throw new Error(`Unknown Loop Control Plane run status: ${String(value)}.`);
36
+ }
37
+
38
+ function manualAllowedUserIds(pattern: Record<string, unknown>) {
39
+ const triggerConfig = asObject(pattern.triggerConfig);
40
+ const configured = triggerConfig.allowedUserIds;
41
+ if (!Array.isArray(configured)) return [];
42
+ return configured.map(Number).filter((id) => Number.isSafeInteger(id) && id > 0);
43
+ }
44
+
45
+ // Transitioning the row does not stop work that is already in flight: the invocation lives in the
46
+ // worker's `AbortController` on whichever node claimed the run. `sendSyncMessage` publishes with
47
+ // `skipSelf`, so the local worker is aborted directly and the message covers the other nodes.
48
+ async function abortRunEverywhere(plugin: LoopResourcePlugin, runId: number) {
49
+ plugin.loopWorker?.abortRun(runId);
50
+ await plugin.sendSyncMessage(loopWorkerAbortMessage(runId));
51
+ }
52
+
53
+ async function transitionOwnedRun(
54
+ plugin: LoopResourcePlugin,
55
+ stateMachine: LoopRunStateMachine,
56
+ repository: LoopRunRepository,
57
+ ctx: Parameters<typeof requestActor>[0],
58
+ to: LoopRunStatus,
59
+ input?: { values?: Record<string, unknown>; humanAccepted?: boolean; eventType?: string; abort?: boolean },
60
+ ) {
61
+ const actor = requestActor(ctx);
62
+ const runId = runIdFromContext(ctx);
63
+ if (!runId) ctx.throw(400, 'runId is required');
64
+ await repository.requireMutableV2Run(runId, actor.userId, actor.isAdmin);
65
+ const transitioned = await stateMachine.transition({
66
+ runId: Number(runId),
67
+ to,
68
+ actorType: 'human',
69
+ actorIdentity: String(actor.userId),
70
+ eventType: input?.eventType,
71
+ values: input?.values,
72
+ humanAccepted: input?.humanAccepted,
73
+ });
74
+ if (input?.abort) await abortRunEverywhere(plugin, Number(runId));
75
+ return transitioned;
76
+ }
77
+
78
+ export function registerAgentLoopResource(plugin: LoopResourcePlugin) {
79
+ const repository = new LoopRunRepository(plugin.db);
80
+ const stateMachine = new LoopRunStateMachine(plugin.db);
81
+ const patterns = new LoopPatternService(plugin.db, employeeHarnessResolver(plugin), async () =>
82
+ worktreeCapability(plugin),
83
+ );
84
+ const triggers = new LoopTriggerService(plugin.db, patterns);
37
85
 
38
- app.resource({
86
+ plugin.app.resource({
39
87
  name: 'agentLoops',
40
88
  actions: {
41
89
  async list(ctx, next) {
42
- const { page = 1, pageSize = 20, sort = ['-createdAt'], filter = {} } = ctx.action.params;
43
- const repo = ctx.db.getRepository('agentLoopRuns');
44
- const [rows, count] = await repo.findAndCount({
45
- filter,
46
- sort,
47
- offset: (Number(page) - 1) * Number(pageSize),
48
- limit: Number(pageSize),
49
- });
50
-
51
- ctx.body = {
52
- data: rows.map(formatRunRow),
53
- meta: {
54
- count,
55
- page: Number(page),
56
- pageSize: Number(pageSize),
57
- totalPage: Math.ceil(count / Number(pageSize)),
58
- },
59
- };
90
+ try {
91
+ const actor = requestActor(ctx);
92
+ const result = await repository.listOwnedRuns({
93
+ userId: actor.userId,
94
+ isAdmin: actor.isAdmin,
95
+ filter: ctx.action.params.filter || {},
96
+ sort: ctx.action.params.sort,
97
+ page: Number(ctx.action.params.page),
98
+ pageSize: Number(ctx.action.params.pageSize),
99
+ });
100
+ ctx.body = {
101
+ data: result.rows.map(formatRunRow),
102
+ meta: {
103
+ count: result.count,
104
+ page: result.page,
105
+ pageSize: result.pageSize,
106
+ totalPage: result.totalPage,
107
+ },
108
+ };
109
+ } catch (error) {
110
+ throwResourceError(ctx, error);
111
+ }
60
112
  await next();
61
113
  },
62
114
 
63
115
  async get(ctx, next) {
64
- const { filterByTk } = ctx.action.params;
65
- if (!filterByTk) {
66
- ctx.throw(400, 'run id is required');
67
- return;
116
+ try {
117
+ const actor = requestActor(ctx);
118
+ const runId = runIdFromContext(ctx);
119
+ if (!runId) ctx.throw(400, 'run id is required');
120
+ ctx.body = { data: await repository.getOwnedRunDetail(runId, actor.userId, actor.isAdmin) };
121
+ } catch (error) {
122
+ throwResourceError(ctx, error);
68
123
  }
69
- ctx.body = { data: await service.getRunDetail(filterByTk) };
70
124
  await next();
71
125
  },
72
126
 
73
- async resume(ctx, next) {
74
- const body = values(ctx);
75
- const runId = body.runId || ctx.action.params.filterByTk;
76
- if (!runId) {
77
- ctx.throw(400, 'runId is required');
78
- return;
127
+ async runNow(ctx, next) {
128
+ try {
129
+ const actor = requestActor(ctx);
130
+ const values = valuesFromCtx(ctx);
131
+ const patternId = Number(values.patternId || ctx.action.params.filterByTk);
132
+ if (!Number.isSafeInteger(patternId) || patternId <= 0) ctx.throw(400, 'patternId is required');
133
+ const { pattern } = await patterns.get(patternId);
134
+ if (
135
+ !actor.isAdmin &&
136
+ !manualAllowedUserIds(pattern as unknown as Record<string, unknown>).includes(actor.userId)
137
+ ) {
138
+ ctx.throw(403, 'This loop pattern does not allow manual runs for the current user.');
139
+ }
140
+ const requestedTriggerKey = stringValue(values.triggerKey);
141
+ const result = await triggers.enqueue({
142
+ patternId,
143
+ triggerType: 'manual',
144
+ triggerKey: requestedTriggerKey || `manual:${actor.userId}:${randomUUID()}`,
145
+ triggerPayload: asObject(values.triggerPayload),
146
+ userId: actor.userId,
147
+ goal: stringValue(values.goal) || undefined,
148
+ perRunHarness: values.perRunHarness,
149
+ });
150
+ ctx.body = { data: result };
151
+ } catch (error) {
152
+ throwResourceError(ctx, error);
79
153
  }
80
- ctx.body = {
81
- data: await service.resumeRun(runId, {
82
- stepId: body.stepId,
83
- approved: body.approved !== false,
84
- editedInput: body.editedInput,
85
- userId: currentUserId(ctx),
86
- ctx,
87
- }),
88
- };
89
154
  await next();
90
155
  },
91
156
 
92
- async approvePlan(ctx, next) {
93
- const body = values(ctx);
94
- const runId = body.runId || ctx.action.params.filterByTk;
95
- if (!runId) {
96
- ctx.throw(400, 'runId is required');
97
- return;
157
+ async pause(ctx, next) {
158
+ try {
159
+ ctx.body = {
160
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'paused', { abort: true }),
161
+ };
162
+ } catch (error) {
163
+ throwResourceError(ctx, error);
98
164
  }
99
- ctx.body = {
100
- data: await service.approvePlan(runId, {
101
- userId: currentUserId(ctx),
102
- reason: body.reason,
103
- }),
104
- };
105
165
  await next();
106
166
  },
107
167
 
108
- async rejectPlan(ctx, next) {
109
- const body = values(ctx);
110
- const runId = body.runId || ctx.action.params.filterByTk;
111
- if (!runId) {
112
- ctx.throw(400, 'runId is required');
113
- return;
168
+ async resume(ctx, next) {
169
+ try {
170
+ ctx.body = { data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'queued') };
171
+ } catch (error) {
172
+ throwResourceError(ctx, error);
114
173
  }
115
- ctx.body = {
116
- data: await service.rejectPlan(runId, {
117
- reason: body.reason,
118
- userId: currentUserId(ctx),
119
- }),
120
- };
121
174
  await next();
122
175
  },
123
176
 
124
- async requestPlanChanges(ctx, next) {
125
- const body = values(ctx);
126
- const runId = body.runId || ctx.action.params.filterByTk;
127
- if (!runId) {
128
- ctx.throw(400, 'runId is required');
129
- return;
177
+ async cancel(ctx, next) {
178
+ try {
179
+ const values = valuesFromCtx(ctx);
180
+ ctx.body = {
181
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'canceled', {
182
+ values: { summary: stringValue(values.reason) || 'Canceled by user.' },
183
+ eventType: 'run_canceled',
184
+ abort: true,
185
+ }),
186
+ };
187
+ } catch (error) {
188
+ throwResourceError(ctx, error);
130
189
  }
131
- ctx.body = {
132
- data: await service.requestPlanChanges(runId, {
133
- feedback: body.feedback,
134
- userId: currentUserId(ctx),
135
- }),
136
- };
137
190
  await next();
138
191
  },
139
192
 
140
- async cancel(ctx, next) {
141
- const body = values(ctx);
142
- const runId = body.runId || ctx.action.params.filterByTk;
143
- if (!runId) {
144
- ctx.throw(400, 'runId is required');
145
- return;
193
+ async retry(ctx, next) {
194
+ try {
195
+ ctx.body = {
196
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'queued', {
197
+ // Retry is a fresh attempt from the leader: any interrupted-session resume point
198
+ // and prior approval outcome must not leak into the new attempt.
199
+ values: { blockedReason: null, escalationReason: null, resumeContext: null, approvalStatus: null },
200
+ eventType: 'run_retried',
201
+ }),
202
+ };
203
+ } catch (error) {
204
+ throwResourceError(ctx, error);
146
205
  }
147
- ctx.body = {
148
- data: await service.cancelRun(runId, {
149
- reason: body.reason,
150
- userId: currentUserId(ctx),
151
- }),
152
- };
153
206
  await next();
154
207
  },
155
208
 
156
- async retryStep(ctx, next) {
157
- const body = values(ctx);
158
- if (!body.stepId) {
159
- ctx.throw(400, 'stepId is required');
160
- return;
209
+ async escalate(ctx, next) {
210
+ try {
211
+ const values = 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
+ throwResourceError(ctx, error);
161
220
  }
162
- ctx.body = {
163
- data: await service.retryStep(body.stepId, {
164
- userId: currentUserId(ctx),
165
- }),
166
- };
167
221
  await next();
168
222
  },
169
223
 
170
- async stepFeedback(ctx, next) {
171
- const body = values(ctx);
172
- if (!body.stepId || !body.rating) {
173
- ctx.throw(400, 'stepId and rating are required');
174
- return;
224
+ async acceptResult(ctx, next) {
225
+ try {
226
+ ctx.body = {
227
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'succeeded', {
228
+ humanAccepted: true,
229
+ eventType: 'run_result_accepted',
230
+ }),
231
+ };
232
+ } catch (error) {
233
+ throwResourceError(ctx, error);
175
234
  }
176
- if (!['positive', 'negative'].includes(body.rating)) {
177
- ctx.throw(400, 'rating must be "positive" or "negative"');
178
- return;
235
+ await next();
236
+ },
237
+
238
+ async status(ctx, next) {
239
+ try {
240
+ const actor = 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
+ throwResourceError(ctx, error);
179
247
  }
180
- ctx.body = {
181
- data: await service.stepFeedback(
182
- body.stepId,
183
- { rating: body.rating, comment: body.comment, category: body.category },
184
- { userId: currentUserId(ctx) },
185
- ),
186
- };
187
248
  await next();
188
249
  },
189
250
  },