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,52 @@
1
+ import type { Plugin } from '@nocobase/server';
2
+ import { LoopRunRepository } from '../services/LoopRunRepository';
3
+ import { requestActor, throwResourceError } from './resource-helpers';
4
+
5
+ export function registerAgentLoopApprovalResource(plugin: Plugin) {
6
+ const repository = new LoopRunRepository(plugin.db);
7
+
8
+ plugin.app.resource({
9
+ name: 'agentLoopApprovals',
10
+ actions: {
11
+ async list(ctx, next) {
12
+ try {
13
+ const actor = requestActor(ctx);
14
+ const result = await repository.listApprovals({
15
+ userId: actor.userId,
16
+ isAdmin: actor.isAdmin,
17
+ filter: ctx.action.params.filter || {},
18
+ sort: ctx.action.params.sort,
19
+ page: Number(ctx.action.params.page),
20
+ pageSize: Number(ctx.action.params.pageSize),
21
+ });
22
+ ctx.body = {
23
+ data: result.rows,
24
+ meta: {
25
+ count: result.count,
26
+ page: result.page,
27
+ pageSize: result.pageSize,
28
+ totalPage: result.totalPage,
29
+ },
30
+ };
31
+ } catch (error) {
32
+ throwResourceError(ctx, error);
33
+ }
34
+ await next();
35
+ },
36
+
37
+ async get(ctx, next) {
38
+ try {
39
+ const actor = requestActor(ctx);
40
+ const approvalId = ctx.action.params.filterByTk;
41
+ if (!approvalId) ctx.throw(400, 'approval id is required');
42
+ ctx.body = {
43
+ data: await repository.requireAccessibleApproval(approvalId, actor.userId, actor.isAdmin),
44
+ };
45
+ } catch (error) {
46
+ throwResourceError(ctx, error);
47
+ }
48
+ await next();
49
+ },
50
+ },
51
+ });
52
+ }
@@ -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,248 @@
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
+ values: { blockedReason: null, escalationReason: null },
198
+ eventType: 'run_retried',
199
+ }),
200
+ };
201
+ } catch (error) {
202
+ throwResourceError(ctx, error);
146
203
  }
147
- ctx.body = {
148
- data: await service.cancelRun(runId, {
149
- reason: body.reason,
150
- userId: currentUserId(ctx),
151
- }),
152
- };
153
204
  await next();
154
205
  },
155
206
 
156
- async retryStep(ctx, next) {
157
- const body = values(ctx);
158
- if (!body.stepId) {
159
- ctx.throw(400, 'stepId is required');
160
- return;
207
+ async escalate(ctx, next) {
208
+ try {
209
+ const values = valuesFromCtx(ctx);
210
+ ctx.body = {
211
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'waiting_human', {
212
+ values: { escalationReason: stringValue(values.reason) || 'Escalated by user.' },
213
+ eventType: 'run_escalated',
214
+ }),
215
+ };
216
+ } catch (error) {
217
+ throwResourceError(ctx, error);
161
218
  }
162
- ctx.body = {
163
- data: await service.retryStep(body.stepId, {
164
- userId: currentUserId(ctx),
165
- }),
166
- };
167
219
  await next();
168
220
  },
169
221
 
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;
222
+ async acceptResult(ctx, next) {
223
+ try {
224
+ ctx.body = {
225
+ data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'succeeded', {
226
+ humanAccepted: true,
227
+ eventType: 'run_result_accepted',
228
+ }),
229
+ };
230
+ } catch (error) {
231
+ throwResourceError(ctx, error);
175
232
  }
176
- if (!['positive', 'negative'].includes(body.rating)) {
177
- ctx.throw(400, 'rating must be "positive" or "negative"');
178
- return;
233
+ await next();
234
+ },
235
+
236
+ async status(ctx, next) {
237
+ try {
238
+ const actor = 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
+ throwResourceError(ctx, error);
179
245
  }
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
246
  await next();
188
247
  },
189
248
  },