plugin-agent-orchestrator 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/253.59577b40d9875be0.js +10 -0
  6. package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
  7. package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
  8. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  9. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  10. package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
  11. package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
  12. package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
  13. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  14. package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
  15. package/dist/client-v2/index.js +1 -1
  16. package/dist/externalVersion.js +8 -7
  17. package/dist/locale/en-US.json +199 -123
  18. package/dist/locale/vi-VN.json +199 -123
  19. package/dist/locale/zh-CN.json +199 -123
  20. package/dist/server/collections/agent-execution-spans.js +55 -0
  21. package/dist/server/collections/agent-harness-profile-versions.js +56 -0
  22. package/dist/server/collections/agent-harness-profiles.js +12 -0
  23. package/dist/server/collections/agent-loop-action-approvals.js +69 -0
  24. package/dist/server/collections/agent-loop-artifacts.js +55 -0
  25. package/dist/server/collections/agent-loop-circuit-states.js +53 -0
  26. package/dist/server/collections/agent-loop-control-settings.js +51 -0
  27. package/dist/server/collections/agent-loop-events.js +27 -0
  28. package/dist/server/collections/agent-loop-path-locks.js +57 -0
  29. package/dist/server/collections/agent-loop-patterns.js +72 -0
  30. package/dist/server/collections/agent-loop-runs.js +170 -3
  31. package/dist/server/collections/agent-loop-steps.js +76 -0
  32. package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
  33. package/dist/server/collections/agent-loop-worktrees.js +55 -0
  34. package/dist/server/collections/skill-executions.js +8 -0
  35. package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
  36. package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
  37. package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
  38. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
  39. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
  40. package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
  41. package/dist/server/plugin.js +54 -150
  42. package/dist/server/resources/agent-harness-profile.js +117 -0
  43. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  44. package/dist/server/resources/agent-loop-approval.js +108 -0
  45. package/dist/server/resources/agent-loop-artifact.js +86 -0
  46. package/dist/server/resources/agent-loop-events-stream.js +130 -0
  47. package/dist/server/resources/agent-loop.js +183 -139
  48. package/dist/server/resources/resource-helpers.js +63 -0
  49. package/dist/server/resources/tracing.js +121 -107
  50. package/dist/server/services/AgentMemoryContextService.js +34 -0
  51. package/dist/server/services/DurableCircuitBreakerService.js +229 -0
  52. package/dist/server/services/HarnessCompiler.js +175 -0
  53. package/dist/server/services/HarnessProfileService.js +233 -0
  54. package/dist/server/services/HarnessSchema.js +194 -0
  55. package/dist/server/services/LoopBudgetService.js +269 -0
  56. package/dist/server/services/LoopControlService.js +139 -0
  57. package/dist/server/services/LoopPatternSchema.js +195 -0
  58. package/dist/server/services/LoopPatternService.js +132 -0
  59. package/dist/server/services/LoopRunRepository.js +285 -0
  60. package/dist/server/services/LoopRunStateMachine.js +478 -0
  61. package/dist/server/services/LoopSchedulerService.js +193 -0
  62. package/dist/server/services/LoopTriggerService.js +165 -0
  63. package/dist/server/services/LoopWorkerService.js +699 -0
  64. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  65. package/dist/server/services/PathLockService.js +288 -0
  66. package/dist/server/services/PluginAiRuntimeAdapter.js +226 -0
  67. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  68. package/dist/server/services/VerificationSchema.js +59 -0
  69. package/dist/server/services/VerificationService.js +235 -0
  70. package/dist/server/services/harness-runtime-policy.js +139 -0
  71. package/dist/server/skill-hub/actions/git-import.js +13 -7
  72. package/dist/server/skill-hub/plugin.js +36 -3
  73. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
  74. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  75. package/dist/server/utils/ensure-indexes.js +111 -0
  76. package/dist/server/utils/loop-pattern-context.js +56 -0
  77. package/package.json +53 -53
  78. package/src/client/ApprovalsTab.tsx +2 -0
  79. package/src/client/OrchestratorSettings.tsx +55 -0
  80. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  81. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  82. package/src/client/skill-hub/index.tsx +0 -52
  83. package/src/client-v2/components/AgentRunsTab.tsx +100 -18
  84. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  85. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -100
  86. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -125
  87. package/src/client-v2/components/TracingTab.tsx +160 -77
  88. package/src/client-v2/hooks/useApiRequest.ts +28 -8
  89. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  90. package/src/client-v2/plugin.tsx +6 -6
  91. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +11 -6
  92. package/src/locale/en-US.json +199 -123
  93. package/src/locale/vi-VN.json +199 -123
  94. package/src/locale/zh-CN.json +199 -123
  95. package/src/server/__tests__/circuit-breaker.test.ts +248 -169
  96. package/src/server/__tests__/harness-compiler.test.ts +214 -0
  97. package/src/server/__tests__/harness-profile-service.test.ts +167 -0
  98. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  99. package/src/server/__tests__/harness-tool-plan.test.ts +172 -0
  100. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  101. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  102. package/src/server/__tests__/loop-budget-service.test.ts +255 -0
  103. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
  104. package/src/server/__tests__/loop-pattern-schema.test.ts +73 -0
  105. package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
  106. package/src/server/__tests__/loop-run-state-machine.test.ts +101 -0
  107. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  108. package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
  109. package/src/server/__tests__/loop-worker-execution.test.ts +317 -0
  110. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  111. package/src/server/__tests__/path-lock-service.test.ts +254 -0
  112. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  113. package/src/server/__tests__/smoke.test.ts +162 -121
  114. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  115. package/src/server/collections/agent-execution-spans.ts +55 -0
  116. package/src/server/collections/agent-harness-profile-versions.ts +26 -0
  117. package/src/server/collections/agent-harness-profiles.ts +71 -59
  118. package/src/server/collections/agent-loop-action-approvals.ts +39 -0
  119. package/src/server/collections/agent-loop-artifacts.ts +25 -0
  120. package/src/server/collections/agent-loop-circuit-states.ts +23 -0
  121. package/src/server/collections/agent-loop-control-settings.ts +21 -0
  122. package/src/server/collections/agent-loop-events.ts +98 -71
  123. package/src/server/collections/agent-loop-path-locks.ts +27 -0
  124. package/src/server/collections/agent-loop-patterns.ts +42 -0
  125. package/src/server/collections/agent-loop-runs.ts +170 -3
  126. package/src/server/collections/agent-loop-steps.ts +76 -0
  127. package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
  128. package/src/server/collections/agent-loop-worktrees.ts +25 -0
  129. package/src/server/collections/skill-executions.ts +8 -0
  130. package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +52 -49
  131. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -46
  132. package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +45 -38
  133. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -32
  134. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -30
  135. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
  136. package/src/server/plugin.ts +55 -167
  137. package/src/server/resources/agent-harness-profile.ts +94 -0
  138. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  139. package/src/server/resources/agent-loop-approval.ts +84 -0
  140. package/src/server/resources/agent-loop-artifact.ts +56 -0
  141. package/src/server/resources/agent-loop-events-stream.ts +105 -0
  142. package/src/server/resources/agent-loop.ts +204 -143
  143. package/src/server/resources/agent-monitor.ts +482 -482
  144. package/src/server/resources/resource-helpers.ts +33 -0
  145. package/src/server/resources/tracing.ts +266 -258
  146. package/src/server/services/AgentMemoryContextService.ts +44 -0
  147. package/src/server/services/DurableCircuitBreakerService.ts +239 -0
  148. package/src/server/services/ExecutionSpanService.ts +2 -0
  149. package/src/server/services/HarnessCompiler.ts +170 -0
  150. package/src/server/services/HarnessProfileService.ts +239 -0
  151. package/src/server/services/HarnessSchema.ts +194 -0
  152. package/src/server/services/LoopBudgetService.ts +275 -0
  153. package/src/server/services/LoopControlService.ts +124 -0
  154. package/src/server/services/LoopPatternSchema.ts +185 -0
  155. package/src/server/services/LoopPatternService.ts +143 -0
  156. package/src/server/services/LoopRunRepository.ts +336 -0
  157. package/src/server/services/LoopRunStateMachine.ts +529 -0
  158. package/src/server/services/LoopSchedulerService.ts +199 -0
  159. package/src/server/services/LoopTriggerService.ts +157 -0
  160. package/src/server/services/LoopWorkerService.ts +822 -0
  161. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  162. package/src/server/services/PathLockService.ts +321 -0
  163. package/src/server/services/PluginAiRuntimeAdapter.ts +332 -0
  164. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  165. package/src/server/services/VerificationSchema.ts +31 -0
  166. package/src/server/services/VerificationService.ts +264 -0
  167. package/src/server/services/harness-runtime-policy.ts +141 -0
  168. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +15 -1
  169. package/src/server/skill-hub/actions/git-import.ts +9 -3
  170. package/src/server/skill-hub/plugin.ts +41 -3
  171. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -239
  172. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -63
  173. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  174. package/src/server/utils/ensure-indexes.ts +96 -0
  175. package/src/server/utils/logging.ts +62 -63
  176. package/src/server/utils/loop-pattern-context.ts +20 -0
  177. package/dist/client-v2/214.79650a549273f163.js +0 -10
  178. package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
  179. package/dist/client-v2/264.718a107e43fc163c.js +0 -10
  180. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  181. package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
  182. package/dist/client-v2/53.7c29c28043e9112d.js +0 -10
  183. package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
  184. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  185. package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
  186. package/dist/server/services/AgentHarness.js +0 -81
  187. package/dist/server/services/AgentLoopController.js +0 -1023
  188. package/dist/server/services/AgentLoopRepository.js +0 -192
  189. package/dist/server/services/AgentLoopService.js +0 -142
  190. package/dist/server/services/AgentPlanValidator.js +0 -99
  191. package/dist/server/services/AgentPlannerService.js +0 -99
  192. package/dist/server/services/CircuitBreaker.js +0 -125
  193. package/dist/server/services/ContextAggregator.js +0 -201
  194. package/dist/server/services/PlanningPromptService.js +0 -95
  195. package/dist/server/tools/agent-loop.js +0 -373
  196. package/dist/server/tools/orchestrator-plan.js +0 -254
  197. package/src/client/AIEmployeeSelect.tsx +0 -47
  198. package/src/client/AIEmployeesContext.tsx +0 -102
  199. package/src/client/RulesTab.tsx +0 -2
  200. package/src/client/TracingTab.tsx +0 -436
  201. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  202. package/src/client-v2/components/RulesTab.tsx +0 -2
  203. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
  204. package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
  205. package/src/server/__tests__/context-aggregator.test.ts +0 -222
  206. package/src/server/__tests__/parallel-execution.test.ts +0 -318
  207. package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
  208. package/src/server/services/AgentHarness.ts +0 -67
  209. package/src/server/services/AgentLoopController.ts +0 -1263
  210. package/src/server/services/AgentLoopRepository.ts +0 -178
  211. package/src/server/services/AgentLoopService.ts +0 -177
  212. package/src/server/services/AgentPlanValidator.ts +0 -73
  213. package/src/server/services/AgentPlannerService.ts +0 -80
  214. package/src/server/services/CircuitBreaker.ts +0 -126
  215. package/src/server/services/ContextAggregator.ts +0 -239
  216. package/src/server/services/PlanningPromptService.ts +0 -72
  217. package/src/server/tools/agent-loop.ts +0 -360
  218. package/src/server/tools/orchestrator-plan.ts +0 -255
@@ -0,0 +1,822 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import type { Database, Model } from '@nocobase/database';
3
+ import type { Application } from '@nocobase/server';
4
+ import { DurableCircuitBreakerService } from './DurableCircuitBreakerService';
5
+ import type { CompiledHarness } from './HarnessCompiler';
6
+ import { LoopBudgetService } from './LoopBudgetService';
7
+ import { LoopControlService } from './LoopControlService';
8
+ import { loopPatternPolicySchema } from './LoopPatternSchema';
9
+ import type { LoopPatternPolicy } from './LoopPatternSchema';
10
+ import { LoopRunStateMachine } from './LoopRunStateMachine';
11
+ import type { ClaimedLoopRun } from './LoopRunStateMachine';
12
+ import { PathLockService } from './PathLockService';
13
+ import { PluginAiRuntimeAdapter } from './PluginAiRuntimeAdapter';
14
+ import type { InvocationOutcome, ToolCallDecision } from './PluginAiRuntimeAdapter';
15
+ import { ToolLoopDetectionService, toolLoopNotice, toolLoopReason } from './ToolLoopDetectionService';
16
+ import { VerificationService } from './VerificationService';
17
+
18
+ const POLL_INTERVAL_MS = 3_000;
19
+ const LEASE_MS = 120_000;
20
+ const HEARTBEAT_MS = 30_000;
21
+ const PATH_LOCK_TTL_MS = 900_000;
22
+
23
+ const LEADER_SYSTEM_MESSAGE =
24
+ 'You lead an autonomous run. Break the goal into concrete work for your makers, then finish with a concise plan of what must be built and which evidence will prove it. You do not modify anything yourself.';
25
+ const MAKER_SYSTEM_MESSAGE =
26
+ 'You are a maker on an autonomous run. Do the work assigned by the leader using only the tools you were granted, and report exactly what you changed and the evidence for it.';
27
+
28
+ export type LoopWorkerSyncMessage = {
29
+ type: 'loop-run-abort-requested';
30
+ runId: number;
31
+ };
32
+
33
+ export function loopWorkerAbortMessage(runId: number): LoopWorkerSyncMessage {
34
+ return { type: 'loop-run-abort-requested', runId };
35
+ }
36
+
37
+ type ResumeContext = {
38
+ role: 'leader' | 'maker';
39
+ username: string;
40
+ sessionId: string;
41
+ messageId: string;
42
+ makerReports: string[];
43
+ makerQueue: string[];
44
+ };
45
+
46
+ type RunSnapshot = {
47
+ id: number;
48
+ patternId: number;
49
+ goal: string;
50
+ autonomyLevel: 'L1' | 'L2' | 'L3';
51
+ policy: LoopPatternPolicy;
52
+ leaderUsername: string;
53
+ makerUsernames: string[];
54
+ verifierUsername: string;
55
+ leaderHarness: CompiledHarness;
56
+ makerHarnesses: Record<string, { effective: CompiledHarness }>;
57
+ verifierHarness: CompiledHarness;
58
+ repositoryKey: string;
59
+ actingOn: string[];
60
+ userId?: number;
61
+ approvalStatus: string;
62
+ resumeContext: ResumeContext | null;
63
+ };
64
+
65
+ function read(record: Model | Record<string, unknown>, key: string) {
66
+ const model = record as Model & { get?: (name: string) => unknown };
67
+ return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
68
+ }
69
+
70
+ function asObject(value: unknown): Record<string, unknown> {
71
+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
72
+ }
73
+
74
+ function asStringArray(value: unknown): string[] {
75
+ return Array.isArray(value) ? value.map((item) => String(item)).filter(Boolean) : [];
76
+ }
77
+
78
+ function autonomyLevel(value: unknown): 'L1' | 'L2' | 'L3' {
79
+ return value === 'L2' || value === 'L3' ? value : 'L1';
80
+ }
81
+
82
+ function harnessFrom(value: unknown): CompiledHarness {
83
+ const snapshot = asObject(value);
84
+ const effective = asObject(snapshot.effective);
85
+ if (!effective.tools) throw new Error('The run harness snapshot is missing its compiled settings.');
86
+ return effective as unknown as CompiledHarness;
87
+ }
88
+
89
+ function resumeContextFrom(value: unknown): ResumeContext | null {
90
+ const context = asObject(value);
91
+ if (!context) return null;
92
+ const role = context.role === 'leader' || context.role === 'maker' ? context.role : null;
93
+ const username = typeof context.username === 'string' ? context.username : '';
94
+ const sessionId = typeof context.sessionId === 'string' ? context.sessionId : '';
95
+ const messageId = typeof context.messageId === 'string' ? context.messageId : '';
96
+ if (!role || !username || !sessionId || !messageId) return null;
97
+ return {
98
+ role,
99
+ username,
100
+ sessionId,
101
+ messageId,
102
+ makerReports: asStringArray(context.makerReports),
103
+ makerQueue: asStringArray(context.makerQueue),
104
+ };
105
+ }
106
+
107
+ function inputHash(value: unknown) {
108
+ return createHash('sha256')
109
+ .update(JSON.stringify(value ?? null))
110
+ .digest('hex');
111
+ }
112
+
113
+ export class LoopWorkerService {
114
+ private readonly control: LoopControlService;
115
+ private readonly stateMachine: LoopRunStateMachine;
116
+ private readonly budgets: LoopBudgetService;
117
+ private readonly circuits: DurableCircuitBreakerService;
118
+ private readonly pathLocks: PathLockService;
119
+ private readonly runtime: PluginAiRuntimeAdapter;
120
+ private readonly verification: VerificationService;
121
+ private readonly loopGuard: ToolLoopDetectionService;
122
+ private readonly workerId: string;
123
+ private readonly active = new Map<number, AbortController>();
124
+ private readonly heldPathLocks = new Map<number, string>();
125
+ private timer: ReturnType<typeof setTimeout> | null = null;
126
+ private running = false;
127
+ private draining: Promise<void> | null = null;
128
+
129
+ constructor(
130
+ private readonly app: Application,
131
+ private readonly database: Database,
132
+ ) {
133
+ const distributedLock = {
134
+ runExclusive: <T>(key: string, operation: () => Promise<T>, ttl?: number) =>
135
+ this.app.lockManager.runExclusive(key, operation, ttl),
136
+ };
137
+ this.control = new LoopControlService(database);
138
+ this.stateMachine = new LoopRunStateMachine(database);
139
+ this.budgets = new LoopBudgetService(database, distributedLock);
140
+ this.circuits = new DurableCircuitBreakerService(database, distributedLock);
141
+ this.pathLocks = new PathLockService(database, distributedLock);
142
+ this.runtime = new PluginAiRuntimeAdapter(app);
143
+ this.verification = new VerificationService(database, this.runtime, this.stateMachine);
144
+ this.loopGuard = new ToolLoopDetectionService(database);
145
+ this.workerId = `${app.name}:${process.pid}:${randomUUID()}`;
146
+ }
147
+
148
+ readonly start = () => {
149
+ // Multi-instance deployments dedicate a process to background work; only that process
150
+ // should claim runs, otherwise every web node competes for the same leases.
151
+ if (this.running || !this.app.serving('agent-loop:worker')) return;
152
+ this.running = true;
153
+ this.scheduleNextPoll();
154
+ };
155
+
156
+ async stop() {
157
+ this.running = false;
158
+ if (this.timer) clearTimeout(this.timer);
159
+ this.timer = null;
160
+ for (const controller of this.active.values()) controller.abort();
161
+ if (this.draining) await this.draining.catch(() => undefined);
162
+ }
163
+
164
+ abortRun(runId: number) {
165
+ this.active.get(runId)?.abort();
166
+ }
167
+
168
+ // A run is only active on the node that claimed it, and `sendSyncMessage` publishes with
169
+ // `skipSelf`, so pause/cancel aborts locally and broadcasts for whichever other node holds it.
170
+ async handleSyncMessage(message: unknown) {
171
+ if (!message || typeof message !== 'object') return;
172
+ const value = message as Partial<LoopWorkerSyncMessage>;
173
+ if (value.type !== 'loop-run-abort-requested') return;
174
+ const runId = Number(value.runId);
175
+ if (!Number.isSafeInteger(runId) || runId <= 0) return;
176
+ this.abortRun(runId);
177
+ }
178
+
179
+ private scheduleNextPoll() {
180
+ if (!this.running) return;
181
+ this.timer = setTimeout(() => {
182
+ this.draining = this.poll()
183
+ .catch((error) => {
184
+ this.app.logger.error('[AgentOrchestrator] Loop worker poll failed.', { error });
185
+ })
186
+ .finally(() => this.scheduleNextPoll());
187
+ }, POLL_INTERVAL_MS);
188
+ }
189
+
190
+ private async poll() {
191
+ if (!this.running) return;
192
+ await this.stateMachine.expireOverdueApprovals(new Date()).catch((error) => {
193
+ this.app.logger.error('[AgentOrchestrator] Approval expiry sweep failed.', { error });
194
+ });
195
+ const claimed = await this.stateMachine.claimNext(this.workerId, LEASE_MS);
196
+ if (!claimed) return;
197
+ await this.execute(claimed);
198
+ }
199
+
200
+ private async execute(claimed: ClaimedLoopRun) {
201
+ const runId = Number(claimed.run.id);
202
+ const controller = new AbortController();
203
+ this.active.set(runId, controller);
204
+
205
+ // The path lock TTL is much longer than the run lease, but a run can outlive it. Renewing both
206
+ // on the same beat keeps them expiring together, so a run can never keep executing on paths
207
+ // whose lock another run is already free to take.
208
+ const heartbeat = setInterval(() => {
209
+ this.heartbeat(runId, claimed.leaseToken).catch((error) => {
210
+ this.app.logger.warn(`[AgentOrchestrator] Loop run ${runId} lost its worker lease.`, { error });
211
+ controller.abort();
212
+ });
213
+ }, HEARTBEAT_MS);
214
+
215
+ let snapshot: RunSnapshot | null = null;
216
+ try {
217
+ snapshot = this.snapshotFrom(claimed.run);
218
+ await this.runToCompletion(snapshot, claimed.leaseToken, controller.signal);
219
+ } catch (error) {
220
+ await this.failRun(runId, claimed.leaseToken, snapshot, error);
221
+ } finally {
222
+ clearInterval(heartbeat);
223
+ this.active.delete(runId);
224
+ const repositoryKey = this.heldPathLocks.get(runId);
225
+ this.heldPathLocks.delete(runId);
226
+ if (repositoryKey) {
227
+ // The lease token is the lock owner. Passing it stops a worker whose lease was already
228
+ // reclaimed from releasing a lock the new owner of the same run now holds.
229
+ await this.pathLocks
230
+ .release(runId, repositoryKey, claimed.leaseToken)
231
+ .catch((error) => this.app.logger.warn(`[AgentOrchestrator] Path lock release failed.`, { error }));
232
+ }
233
+ await this.stateMachine.releaseLease(runId, claimed.leaseToken).catch(() => undefined);
234
+ }
235
+ }
236
+
237
+ private async heartbeat(runId: number, leaseToken: string) {
238
+ await this.stateMachine.renewLease(runId, leaseToken, LEASE_MS);
239
+ const repositoryKey = this.heldPathLocks.get(runId);
240
+ if (repositoryKey) await this.pathLocks.renew(runId, repositoryKey, PATH_LOCK_TTL_MS, leaseToken);
241
+ }
242
+
243
+ private async runToCompletion(snapshot: RunSnapshot, leaseToken: string, signal: AbortSignal) {
244
+ await this.control.assertCanExecute();
245
+ const scopeKey = `pattern:${snapshot.patternId}`;
246
+ await this.circuits.authorizeAttempt({
247
+ patternId: snapshot.patternId,
248
+ scopeKey,
249
+ policy: snapshot.policy.circuit,
250
+ });
251
+
252
+ if (!(await this.acquirePaths(snapshot, leaseToken))) return;
253
+
254
+ // A run requeued from a pause while its approvals are still pending has nothing to execute:
255
+ // the decisions never arrived, so it parks again instead of restarting from the leader.
256
+ if (snapshot.resumeContext && snapshot.approvalStatus === 'pending') {
257
+ await this.stateMachine.transition({
258
+ runId: snapshot.id,
259
+ to: 'waiting_approval',
260
+ actorType: 'worker',
261
+ actorIdentity: this.workerId,
262
+ leaseToken,
263
+ eventType: 'run_waiting_approval',
264
+ title: 'Waiting for action approval',
265
+ content: 'Run requeued while its approval decisions are still pending.',
266
+ correlationKey: `approval-repark:${snapshot.id}`,
267
+ values: { approvalStatus: 'pending' },
268
+ });
269
+ return;
270
+ }
271
+
272
+ await this.stateMachine.transition({
273
+ runId: snapshot.id,
274
+ to: 'running',
275
+ actorType: 'worker',
276
+ actorIdentity: this.workerId,
277
+ leaseToken,
278
+ eventType: 'run_started',
279
+ title: snapshot.resumeContext ? 'Run resumed' : 'Run started',
280
+ content: snapshot.resumeContext
281
+ ? `${snapshot.resumeContext.username} resumed after approval decisions.`
282
+ : `Leader ${snapshot.leaderUsername} began working on the goal.`,
283
+ correlationKey: `started:${snapshot.id}`,
284
+ values: { currentRole: snapshot.resumeContext ? snapshot.resumeContext.role : 'leader' },
285
+ });
286
+
287
+ // Loops recorded before this claim (for example before a park for approval) keep warning the
288
+ // prompts composed later in the run.
289
+ const loopNotices = await this.loopGuard.existingNotices(snapshot.id);
290
+
291
+ let makerReports: string[];
292
+ let makerQueue: string[];
293
+
294
+ if (snapshot.resumeContext) {
295
+ const resume = snapshot.resumeContext;
296
+ const decisions = await this.consumeDecisions(snapshot.id);
297
+ const resumed = await this.resumeRole(snapshot, resume, decisions, signal);
298
+
299
+ const resumeGuard = await this.enforceToolLoopGuard(
300
+ snapshot,
301
+ leaseToken,
302
+ { role: resume.role, username: resume.username },
303
+ loopNotices,
304
+ );
305
+ if (resumeGuard === 'halt') return;
306
+
307
+ // A resumed conversation can hit another approval gate; park with the same role context so
308
+ // the next resume continues exactly where this one stopped.
309
+ if (resumed.interrupted.length) {
310
+ await this.parkForApproval(snapshot, resumed, leaseToken, {
311
+ role: resume.role,
312
+ username: resume.username,
313
+ makerReports: resume.makerReports,
314
+ makerQueue: resume.makerQueue,
315
+ });
316
+ return;
317
+ }
318
+ if (resume.role === 'leader') {
319
+ makerReports = [resumed.content];
320
+ makerQueue = [...snapshot.makerUsernames];
321
+ } else {
322
+ makerReports = [...resume.makerReports, `# ${resume.username}\n${resumed.content}`];
323
+ makerQueue = [...resume.makerQueue];
324
+ }
325
+ } else {
326
+ const leader = await this.invokeRole(snapshot, {
327
+ role: 'leader',
328
+ username: snapshot.leaderUsername,
329
+ harness: snapshot.leaderHarness,
330
+ systemMessage: LEADER_SYSTEM_MESSAGE,
331
+ prompt: snapshot.goal,
332
+ leaseToken,
333
+ signal,
334
+ });
335
+
336
+ const leaderGuard = await this.enforceToolLoopGuard(
337
+ snapshot,
338
+ leaseToken,
339
+ { role: 'leader', username: snapshot.leaderUsername },
340
+ loopNotices,
341
+ );
342
+ if (leaderGuard === 'halt') return;
343
+
344
+ // plugin-ai stops the graph on an approval-gated tool. Approval is a human decision, so the
345
+ // run parks here instead of the worker deciding on the operator's behalf.
346
+ if (leader.interrupted.length) {
347
+ await this.parkForApproval(snapshot, leader, leaseToken, {
348
+ role: 'leader',
349
+ username: snapshot.leaderUsername,
350
+ makerReports: [],
351
+ makerQueue: snapshot.makerUsernames,
352
+ });
353
+ return;
354
+ }
355
+ makerReports = [leader.content];
356
+ makerQueue = [...snapshot.makerUsernames];
357
+ }
358
+
359
+ // Each maker executes with its own compiled harness snapshot. Reusing one harness would apply
360
+ // the wrong per-employee tool grants, so the snapshot is looked up by username and a maker with
361
+ // no snapshot is a compile error, not a silent skip.
362
+ while (makerQueue.length) {
363
+ const username = makerQueue[0];
364
+ const harness = snapshot.makerHarnesses[username]?.effective;
365
+ if (!harness) {
366
+ throw new Error(`The claimed run has no harness snapshot for maker "${username}".`);
367
+ }
368
+ const maker = await this.invokeRole(snapshot, {
369
+ role: 'maker',
370
+ username,
371
+ harness,
372
+ systemMessage: MAKER_SYSTEM_MESSAGE,
373
+ prompt: [
374
+ `Goal: ${snapshot.goal}`,
375
+ '',
376
+ "Leader's plan:",
377
+ makerReports[0] || '(the leader produced no textual plan)',
378
+ ...loopNotices,
379
+ ].join('\n'),
380
+ leaseToken,
381
+ signal,
382
+ });
383
+ const makerGuard = await this.enforceToolLoopGuard(
384
+ snapshot,
385
+ leaseToken,
386
+ { role: 'maker', username },
387
+ loopNotices,
388
+ );
389
+ if (makerGuard === 'halt') return;
390
+ if (maker.interrupted.length) {
391
+ await this.parkForApproval(snapshot, maker, leaseToken, {
392
+ role: 'maker',
393
+ username,
394
+ makerReports,
395
+ makerQueue: makerQueue.slice(1),
396
+ });
397
+ return;
398
+ }
399
+ makerReports.push(`# ${username}\n${maker.content}`);
400
+ makerQueue = makerQueue.slice(1);
401
+ }
402
+ const makerSummary = makerReports.join('\n\n');
403
+
404
+ await this.stateMachine.transition({
405
+ runId: snapshot.id,
406
+ to: 'verifying',
407
+ actorType: 'worker',
408
+ actorIdentity: this.workerId,
409
+ leaseToken,
410
+ eventType: 'run_verifying',
411
+ title: 'Verification started',
412
+ content: `Verifier ${snapshot.verifierUsername} is reviewing the reported result.`,
413
+ correlationKey: `verifying:${snapshot.id}`,
414
+ values: { currentRole: 'verifier', finalAnswer: makerSummary },
415
+ });
416
+
417
+ await this.budgets.reserve({
418
+ runId: snapshot.id,
419
+ patternId: snapshot.patternId,
420
+ policy: snapshot.policy,
421
+ delta: { verifications: 1 },
422
+ });
423
+ const outcome = await this.verification.verifyAndFinalize({
424
+ runId: snapshot.id,
425
+ goal: snapshot.goal,
426
+ autonomyLevel: snapshot.autonomyLevel,
427
+ verifierUsername: snapshot.verifierUsername,
428
+ leaderUsername: snapshot.leaderUsername,
429
+ makerUsernames: snapshot.makerUsernames,
430
+ verifierHarness: snapshot.verifierHarness,
431
+ policy: snapshot.policy,
432
+ makerSummary,
433
+ userId: snapshot.userId,
434
+ workerId: this.workerId,
435
+ leaseToken,
436
+ loopNotices,
437
+ signal,
438
+ });
439
+
440
+ // The tool loop guard already moved the run to blocked or waiting_human; the circuit breaker
441
+ // tracks failed attempts, not behavioral stops, so it must not see this as a failure.
442
+ if (outcome.finalStatus === 'halted') return;
443
+
444
+ if (outcome.finalStatus === 'failed') {
445
+ await this.circuits.recordFailure({
446
+ patternId: snapshot.patternId,
447
+ scopeKey: `pattern:${snapshot.patternId}`,
448
+ policy: snapshot.policy.circuit,
449
+ error: new Error(`Verifier rejected run ${snapshot.id}.`),
450
+ lastRunId: snapshot.id,
451
+ });
452
+ return;
453
+ }
454
+ await this.circuits.recordSuccess(snapshot.patternId, `pattern:${snapshot.patternId}`, snapshot.id);
455
+ }
456
+
457
+ private async acquirePaths(snapshot: RunSnapshot, leaseToken: string) {
458
+ if (!snapshot.repositoryKey || !snapshot.actingOn.length) return true;
459
+ const lock = await this.pathLocks.acquire({
460
+ runId: snapshot.id,
461
+ repositoryKey: snapshot.repositoryKey,
462
+ owner: leaseToken,
463
+ paths: snapshot.actingOn,
464
+ ttlMs: PATH_LOCK_TTL_MS,
465
+ });
466
+ if (lock.acquired) {
467
+ // Recorded before any work starts so the heartbeat renews this lock for as long as the run
468
+ // executes, and the release in `execute` frees exactly the lock this worker took.
469
+ this.heldPathLocks.set(snapshot.id, snapshot.repositoryKey);
470
+ return true;
471
+ }
472
+
473
+ const deadlocked = lock.deadlocked;
474
+ await this.stateMachine.transition({
475
+ runId: snapshot.id,
476
+ to: deadlocked ? 'blocked' : 'waiting_lock',
477
+ actorType: 'worker',
478
+ actorIdentity: this.workerId,
479
+ leaseToken,
480
+ eventType: deadlocked ? 'run_blocked' : 'run_waiting_lock',
481
+ title: deadlocked ? 'Run blocked by a lock cycle' : 'Waiting for repository paths',
482
+ content: `Blocked by run(s): ${lock.blockers.join(', ')}.`,
483
+ correlationKey: `lock:${snapshot.id}:${lock.blockers.join('-')}`,
484
+ values: deadlocked ? { blockedReason: 'Path lock wait graph contains a cycle.' } : {},
485
+ });
486
+ return false;
487
+ }
488
+
489
+ private async invokeRole(
490
+ snapshot: RunSnapshot,
491
+ input: {
492
+ role: 'leader' | 'maker';
493
+ username: string;
494
+ harness: CompiledHarness;
495
+ systemMessage: string;
496
+ prompt: string;
497
+ leaseToken: string;
498
+ signal: AbortSignal;
499
+ },
500
+ ) {
501
+ await this.budgets.reserve({
502
+ runId: snapshot.id,
503
+ patternId: snapshot.patternId,
504
+ policy: snapshot.policy,
505
+ delta: { invocations: 1 },
506
+ });
507
+ const sessionId = await this.runtime.createConversation({
508
+ username: input.username,
509
+ userId: snapshot.userId,
510
+ runId: snapshot.id,
511
+ title: snapshot.goal.slice(0, 200),
512
+ });
513
+ const step = await this.database.getRepository('agentLoopSteps').create({
514
+ values: {
515
+ runId: snapshot.id,
516
+ runtimeVersion: 'control-plane-v2',
517
+ sequence: await this.nextSequence(snapshot.id),
518
+ role: input.role,
519
+ kind: 'invocation',
520
+ type: 'reasoning',
521
+ employeeUsername: input.username,
522
+ sessionId,
523
+ title: `${input.role} invocation`,
524
+ inputHash: inputHash(input.prompt),
525
+ status: 'running',
526
+ startedAt: new Date(),
527
+ createdAt: new Date(),
528
+ },
529
+ });
530
+
531
+ const outcome = await this.runtime.invoke({
532
+ username: input.username,
533
+ sessionId,
534
+ userId: snapshot.userId,
535
+ systemMessage: input.systemMessage,
536
+ harness: input.harness,
537
+ prompt: input.prompt,
538
+ signal: input.signal,
539
+ });
540
+
541
+ await this.database.getRepository('agentLoopSteps').update({
542
+ filterByTk: read(step, 'id'),
543
+ values: {
544
+ status: outcome.interrupted.length ? 'waiting_user' : 'succeeded',
545
+ output: { content: outcome.content },
546
+ endedAt: new Date(),
547
+ },
548
+ });
549
+ await this.database.getRepository('agentLoopRuns').update({
550
+ filterByTk: snapshot.id,
551
+ values: { sessionId: outcome.sessionId, messageId: outcome.messageId },
552
+ });
553
+ return outcome;
554
+ }
555
+
556
+ private async resumeRole(
557
+ snapshot: RunSnapshot,
558
+ resume: ResumeContext,
559
+ decisions: Array<{ toolCallId: string; decision: ToolCallDecision }>,
560
+ signal: AbortSignal,
561
+ ) {
562
+ await this.budgets.reserve({
563
+ runId: snapshot.id,
564
+ patternId: snapshot.patternId,
565
+ policy: snapshot.policy,
566
+ delta: { invocations: 1 },
567
+ });
568
+ const harness =
569
+ resume.role === 'leader' ? snapshot.leaderHarness : snapshot.makerHarnesses[resume.username]?.effective;
570
+ if (!harness) {
571
+ throw new Error(`The claimed run has no harness snapshot for ${resume.role} "${resume.username}".`);
572
+ }
573
+ const step = await this.database.getRepository('agentLoopSteps').create({
574
+ values: {
575
+ runId: snapshot.id,
576
+ runtimeVersion: 'control-plane-v2',
577
+ sequence: await this.nextSequence(snapshot.id),
578
+ role: resume.role,
579
+ kind: 'invocation',
580
+ type: 'resume',
581
+ employeeUsername: resume.username,
582
+ sessionId: resume.sessionId,
583
+ title: `${resume.role} resume after approval`,
584
+ inputHash: inputHash(decisions),
585
+ status: 'running',
586
+ startedAt: new Date(),
587
+ createdAt: new Date(),
588
+ },
589
+ });
590
+
591
+ const outcome = await this.runtime.resume({
592
+ username: resume.username,
593
+ sessionId: resume.sessionId,
594
+ messageId: resume.messageId,
595
+ userId: snapshot.userId,
596
+ systemMessage: resume.role === 'leader' ? LEADER_SYSTEM_MESSAGE : MAKER_SYSTEM_MESSAGE,
597
+ harness,
598
+ decisions,
599
+ signal,
600
+ });
601
+
602
+ await this.database.getRepository('agentLoopSteps').update({
603
+ filterByTk: read(step, 'id'),
604
+ values: {
605
+ status: outcome.interrupted.length ? 'waiting_user' : 'succeeded',
606
+ output: { content: outcome.content },
607
+ endedAt: new Date(),
608
+ },
609
+ });
610
+ await this.database.getRepository('agentLoopRuns').update({
611
+ filterByTk: snapshot.id,
612
+ values: { sessionId: outcome.sessionId, messageId: outcome.messageId },
613
+ });
614
+ return outcome;
615
+ }
616
+
617
+ // Run-level scan over every tool call issued so far, evaluated at each pass boundary. A warning
618
+ // is injected into the prompts composed later in the run; block and escalate halt it at once.
619
+ private async enforceToolLoopGuard(
620
+ snapshot: RunSnapshot,
621
+ leaseToken: string,
622
+ pass: { role: 'leader' | 'maker'; username: string },
623
+ loopNotices: string[],
624
+ ): Promise<'continue' | 'halt'> {
625
+ const finding = await this.loopGuard.scanRun(snapshot.id, snapshot.policy);
626
+ if (!finding) return 'continue';
627
+
628
+ await this.loopGuard.recordFinding(
629
+ {
630
+ runId: snapshot.id,
631
+ role: pass.role,
632
+ username: pass.username,
633
+ runStatus: 'running',
634
+ actorType: 'worker',
635
+ actorIdentity: this.workerId,
636
+ },
637
+ finding,
638
+ );
639
+
640
+ if (finding.level === 'warn') {
641
+ const notice = toolLoopNotice(finding.toolName, finding.count);
642
+ if (!loopNotices.includes(notice)) loopNotices.push(notice);
643
+ return 'continue';
644
+ }
645
+
646
+ const reason = toolLoopReason(finding);
647
+ await this.stateMachine.transition({
648
+ runId: snapshot.id,
649
+ to: finding.level === 'block' ? 'blocked' : 'waiting_human',
650
+ actorType: 'worker',
651
+ actorIdentity: this.workerId,
652
+ leaseToken,
653
+ eventType: finding.level === 'block' ? 'run_blocked' : 'run_escalated',
654
+ title: finding.level === 'block' ? 'Run blocked by tool loop detection' : 'Run escalated by tool loop detection',
655
+ content: reason,
656
+ correlationKey: `tool-loop-${finding.level}:${snapshot.id}:${finding.signature}`,
657
+ values: finding.level === 'block' ? { blockedReason: reason } : { escalationReason: reason },
658
+ });
659
+ return 'halt';
660
+ }
661
+
662
+ // Decisions are consumed exactly once: rows are marked consumed so a retry or a second resume
663
+ // can never replay a human decision against a fresh conversation.
664
+ private async consumeDecisions(runId: number) {
665
+ const repository = this.database.getRepository('agentLoopActionApprovals');
666
+ const approvals = await repository.find({ filter: { runId } });
667
+ const decisions: Array<{ toolCallId: string; decision: ToolCallDecision }> = [];
668
+ const now = new Date();
669
+ for (const approval of approvals) {
670
+ const status = String(read(approval, 'status'));
671
+ if (status !== 'approved' && status !== 'rejected') continue;
672
+ if (read(approval, 'consumedAt')) continue;
673
+ const editedInput = read(approval, 'editedInput');
674
+ const decision: ToolCallDecision =
675
+ status === 'approved'
676
+ ? editedInput
677
+ ? { type: 'edit', editedAction: { name: String(read(approval, 'toolName')), args: editedInput } }
678
+ : { type: 'approve' }
679
+ : { type: 'reject', message: String(read(approval, 'decisionNote') || '') || undefined };
680
+ decisions.push({ toolCallId: String(read(approval, 'toolCallId')), decision });
681
+ await repository.update({ filterByTk: Number(read(approval, 'id')), values: { consumedAt: now } });
682
+ }
683
+ if (!decisions.length) throw new Error('The resumed run has no recorded approval decisions.');
684
+ return decisions;
685
+ }
686
+
687
+ private async parkForApproval(
688
+ snapshot: RunSnapshot,
689
+ outcome: InvocationOutcome,
690
+ leaseToken: string,
691
+ context: { role: 'leader' | 'maker'; username: string; makerReports: string[]; makerQueue: string[] },
692
+ ) {
693
+ const now = new Date();
694
+ const expiresAt = new Date(now.getTime() + snapshot.policy.actions.approvalTimeoutMs);
695
+ const assignedToId = snapshot.policy.actions.approvalAssigneeIds[0] || snapshot.userId || null;
696
+ const harness =
697
+ context.role === 'leader' ? snapshot.leaderHarness : snapshot.makerHarnesses[context.username]?.effective;
698
+ const escalatable = new Set(harness?.tools.escalate ?? []);
699
+ for (const call of outcome.interrupted) {
700
+ // An escalation is a request for authority the harness never granted, widened for exactly
701
+ // one call; a plain tool_call approval gates a tool the harness allows but asks about.
702
+ const escalation = escalatable.has(call.toolName);
703
+ await this.database.getRepository('agentLoopActionApprovals').create({
704
+ values: {
705
+ runId: snapshot.id,
706
+ toolCallId: call.toolCallId,
707
+ toolName: call.toolName,
708
+ actionType: escalation ? 'escalation' : 'tool_call',
709
+ proposedInput: call.args,
710
+ inputHash: inputHash(call.args),
711
+ paths: snapshot.actingOn,
712
+ policyDecision: { decision: 'ask', interruptId: call.interruptId },
713
+ reason: escalation
714
+ ? `Tool "${call.toolName}" is not granted by this run's harness. Approving widens authority for this single call only.`
715
+ : `Tool "${call.toolName}" requires human approval under this pattern's policy.`,
716
+ status: 'pending',
717
+ assignedToId,
718
+ requestedById: snapshot.userId || null,
719
+ requestedAt: now,
720
+ expiresAt,
721
+ createdAt: now,
722
+ },
723
+ });
724
+ }
725
+ await this.database.getRepository('agentLoopRuns').update({
726
+ filterByTk: snapshot.id,
727
+ values: {
728
+ // The resume point is durable: which role stopped, in which conversation, with which
729
+ // reports already collected and which makers still queued. Without it a resumed run
730
+ // would restart from the leader and redo every completed invocation.
731
+ resumeContext: {
732
+ role: context.role,
733
+ username: context.username,
734
+ sessionId: outcome.sessionId,
735
+ messageId: outcome.messageId,
736
+ makerReports: context.makerReports,
737
+ makerQueue: context.makerQueue,
738
+ },
739
+ },
740
+ });
741
+ await this.stateMachine.transition({
742
+ runId: snapshot.id,
743
+ to: 'waiting_approval',
744
+ actorType: 'worker',
745
+ actorIdentity: this.workerId,
746
+ leaseToken,
747
+ eventType: 'run_waiting_approval',
748
+ title: 'Waiting for action approval',
749
+ content: `${outcome.interrupted.length} tool call(s) require approval.`,
750
+ correlationKey: `approval:${snapshot.id}:${outcome.messageId}`,
751
+ values: { approvalStatus: 'pending', messageId: outcome.messageId },
752
+ });
753
+ }
754
+
755
+ private async failRun(runId: number, leaseToken: string, snapshot: RunSnapshot | null, error: unknown) {
756
+ const message = error instanceof Error ? error.message : String(error);
757
+ try {
758
+ if (snapshot) {
759
+ await this.circuits.recordFailure({
760
+ patternId: snapshot.patternId,
761
+ scopeKey: `pattern:${snapshot.patternId}`,
762
+ policy: snapshot.policy.circuit,
763
+ error,
764
+ lastRunId: runId,
765
+ });
766
+ }
767
+ await this.stateMachine.transition({
768
+ runId,
769
+ to: 'failed',
770
+ actorType: 'worker',
771
+ actorIdentity: this.workerId,
772
+ leaseToken,
773
+ eventType: 'run_failed',
774
+ title: 'Run failed',
775
+ content: message,
776
+ correlationKey: `failed:${runId}`,
777
+ values: { summary: message },
778
+ });
779
+ } catch (transitionError) {
780
+ this.app.logger.error(`[AgentOrchestrator] Loop run ${runId} could not be marked failed.`, {
781
+ error: transitionError,
782
+ cause: message,
783
+ });
784
+ }
785
+ }
786
+
787
+ private async nextSequence(runId: number) {
788
+ const steps = await this.database.getRepository('agentLoopSteps').find({ filter: { runId } });
789
+ return steps.length;
790
+ }
791
+
792
+ private snapshotFrom(run: Record<string, unknown>): RunSnapshot {
793
+ const patternId = Number(run.patternId);
794
+ if (!Number.isSafeInteger(patternId) || patternId <= 0) {
795
+ throw new Error('The claimed run has no pattern snapshot.');
796
+ }
797
+ const roleBindings = asObject(run.roleBindingsSnapshot);
798
+ const makerSnapshots = asObject(run.makerHarnessSnapshot);
799
+ const approvalStatus = String(run.approvalStatus || 'none');
800
+ return {
801
+ id: Number(run.id),
802
+ patternId,
803
+ goal: String(run.goal || ''),
804
+ autonomyLevel: autonomyLevel(run.autonomyLevel),
805
+ policy: loopPatternPolicySchema.parse(run.policySnapshot),
806
+ leaderUsername: String(roleBindings.leader || run.leaderUsername || ''),
807
+ makerUsernames: asStringArray(roleBindings.makers),
808
+ verifierUsername: String(roleBindings.verifier || run.verifierUsername || ''),
809
+ leaderHarness: harnessFrom(run.leaderHarnessSnapshot),
810
+ makerHarnesses: makerSnapshots as Record<string, { effective: CompiledHarness }>,
811
+ verifierHarness: harnessFrom(run.verifierHarnessSnapshot),
812
+ repositoryKey: String(run.repositoryKey || ''),
813
+ actingOn: asStringArray(run.actingOn),
814
+ userId: Number(run.userId) || undefined,
815
+ approvalStatus,
816
+ // Only a live approval state may resume. Stale context left over from an expired window or a
817
+ // cleared retry would otherwise replay an old conversation against fresh approvals.
818
+ resumeContext:
819
+ approvalStatus === 'decided' || approvalStatus === 'pending' ? resumeContextFrom(run.resumeContext) : null,
820
+ };
821
+ }
822
+ }