plugin-agent-orchestrator 1.1.7 → 1.2.0

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 (413) hide show
  1. package/README.md +207 -204
  2. package/client-v2.d.ts +2 -2
  3. package/client-v2.js +1 -1
  4. package/client.d.ts +2 -2
  5. package/client.js +1 -1
  6. package/dist/client/117.2e4cb0477da3db1f.js +10 -0
  7. package/dist/client/253.93deb9e0192e76a5.js +10 -0
  8. package/dist/client/325.8f7f509bdb35e142.js +10 -0
  9. package/dist/client/404.498d2d9516dd1dce.js +10 -0
  10. package/dist/client/418.6f01da17774a5a25.js +10 -0
  11. package/dist/client/53.774ff07505d521fa.js +10 -0
  12. package/dist/client/619.e342b0fa467d39ca.js +10 -0
  13. package/dist/client/627.fdd60bcc0f3a9cf6.js +10 -0
  14. package/dist/client/652.477e21bfff67bc1c.js +10 -0
  15. package/dist/client/981.e0546ffc34afedcd.js +10 -0
  16. package/dist/client/993.5d04b510835ab0d2.js +10 -0
  17. package/dist/client/index.js +1 -1
  18. package/dist/client-v2/117.ccf43ae8631f7d74.js +10 -0
  19. package/dist/client-v2/214.cdf76752053a8990.js +10 -0
  20. package/dist/client-v2/253.1198df22f5baf304.js +10 -0
  21. package/dist/client-v2/264.78887ff88f969467.js +10 -0
  22. package/dist/client-v2/325.fafe5a6e83ba9cb3.js +10 -0
  23. package/dist/client-v2/404.9ba964c28a151c81.js +10 -0
  24. package/dist/client-v2/{41.3deb9e57a0f64fc4.js → 41.b28cf7a675a603d1.js} +1 -1
  25. package/dist/client-v2/418.55b6b28cda8bb5f3.js +10 -0
  26. package/dist/client-v2/{53.349fff8db80b19d4.js → 53.282081f97e4308c6.js} +1 -1
  27. package/dist/client-v2/{619.0a2144aaffefe018.js → 619.8c03913873785fb6.js} +1 -1
  28. package/dist/client-v2/627.e16f4a0dd596c3e6.js +10 -0
  29. package/dist/client-v2/652.1a48364774d5383a.js +10 -0
  30. package/dist/client-v2/{70.ffff2997c10fd4b0.js → 70.9166ed70906d041f.js} +1 -1
  31. package/dist/client-v2/{981.e4a1f41cfc94a856.js → 981.a81521f0296c7db8.js} +1 -1
  32. package/dist/client-v2/993.ca5b28f1e2b4c1ef.js +10 -0
  33. package/dist/client-v2/index.js +1 -1
  34. package/dist/externalVersion.js +10 -7
  35. package/dist/locale/en-US.json +229 -1
  36. package/dist/locale/zh-CN.json +229 -1
  37. package/dist/node_modules/adm-zip/adm-zip.js +1 -1
  38. package/dist/node_modules/adm-zip/package.json +1 -1
  39. package/dist/node_modules/ajv/package.json +1 -1
  40. package/dist/node_modules/zod/index.cjs +1 -1
  41. package/dist/node_modules/zod/package.json +1 -1
  42. package/dist/server/collections/agent-execution-spans.js +145 -6
  43. package/dist/server/collections/agent-governance-audit-events.js +47 -0
  44. package/dist/server/collections/agent-governance-policies.js +47 -0
  45. package/dist/server/collections/agent-governance-policy-versions.js +48 -0
  46. package/dist/server/collections/agent-governance-prompt-bindings.js +50 -0
  47. package/dist/server/collections/agent-loop-runs.js +23 -5
  48. package/dist/server/migrations/20261110000000-add-usage-pricing-snapshots.js +117 -0
  49. package/dist/server/migrations/20261110010000-add-usage-department-attribution.js +54 -0
  50. package/dist/server/plugin.js +114 -33
  51. package/dist/server/resources/agent-governance.js +192 -0
  52. package/dist/server/resources/agent-harness-profile.js +11 -3
  53. package/dist/server/resources/agent-monitor.js +109 -339
  54. package/dist/server/resources/agent-usage.js +423 -0
  55. package/dist/server/resources/native-monitor-format.js +179 -0
  56. package/dist/server/resources/tracing.js +35 -12
  57. package/dist/server/services/AgentGovernanceService.js +500 -0
  58. package/dist/server/services/DepartmentAttribution.js +65 -0
  59. package/dist/server/services/ExecutionSpanService.js +96 -3
  60. package/dist/server/services/GovernanceAdmission.js +211 -0
  61. package/dist/server/services/HarnessCapabilities.js +118 -0
  62. package/dist/server/services/LoopBudgetService.js +29 -11
  63. package/dist/server/services/LoopRunRepository.js +15 -6
  64. package/dist/server/services/LoopRunStateMachine.js +18 -7
  65. package/dist/server/services/LoopTriggerService.js +1 -1
  66. package/dist/server/services/LoopWorkerService.js +66 -32
  67. package/dist/server/services/ManagedPromptProtection.js +99 -0
  68. package/dist/server/services/NativeAgentMonitorSyncService.js +584 -0
  69. package/dist/server/services/NativeSubAgentObserver.js +141 -508
  70. package/dist/server/services/NativeUsageAttribution.js +97 -0
  71. package/dist/server/services/TokenTracker.js +787 -104
  72. package/dist/server/services/TracingRetentionPolicy.js +66 -0
  73. package/dist/server/services/VerificationService.js +18 -8
  74. package/dist/server/skill-hub/sandbox-config.json +6 -6
  75. package/dist/server/utils/ensure-indexes.js +14 -5
  76. package/package.json +63 -53
  77. package/server.d.ts +2 -2
  78. package/server.js +1 -1
  79. package/src/client/AgentRunsTab.tsx +2 -2
  80. package/src/client/ApprovalsTab.tsx +2 -2
  81. package/src/client/HarnessProfilesTab.tsx +2 -2
  82. package/src/client/OrchestratorSettings.tsx +152 -152
  83. package/src/client/SkillPages.tsx +41 -0
  84. package/src/client/__tests__/embedded-settings.test.tsx +232 -0
  85. package/src/client/hooks/useRunEventStream.ts +76 -76
  86. package/src/client/index.tsx +2 -2
  87. package/src/client/plugin.tsx +76 -32
  88. package/src/client/skill-hub/components/ExecutionHistory.tsx +200 -200
  89. package/src/client/skill-hub/components/GitSkillImport.tsx +562 -562
  90. package/src/client/skill-hub/components/LoopSettings.tsx +331 -331
  91. package/src/client/skill-hub/components/SkillEditor.tsx +460 -460
  92. package/src/client/skill-hub/components/SkillManager.tsx +194 -194
  93. package/src/client/skill-hub/components/SkillMetrics.tsx +162 -162
  94. package/src/client/skill-hub/components/SkillTestPanel.tsx +141 -141
  95. package/src/client/skill-hub/index.tsx +6 -6
  96. package/src/client/skill-hub/locale.ts +16 -16
  97. package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +132 -132
  98. package/src/client/skill-hub/tools/SkillHubCard.tsx +104 -104
  99. package/src/client/skill-hub/tools/loopTemplates.ts +52 -52
  100. package/src/client/skill-hub/tools/registerSkillLoopCards.ts +71 -71
  101. package/src/client/skill-hub/utils/jsonFields.ts +41 -41
  102. package/src/client-v2/__tests__/embedded-settings.test.tsx +193 -0
  103. package/src/client-v2/components/AIEmployeeSelect.tsx +47 -47
  104. package/src/client-v2/components/AIEmployeesContext.tsx +97 -97
  105. package/src/client-v2/components/AgentBindingsTab.tsx +269 -269
  106. package/src/client-v2/components/AgentRunsTab.tsx +92 -83
  107. package/src/client-v2/components/ApprovalsTab.tsx +337 -337
  108. package/src/client-v2/components/EmployeeGovernanceTab.tsx +702 -0
  109. package/src/client-v2/components/HarnessProfilesTab.tsx +704 -541
  110. package/src/client-v2/components/KnowledgeAccessTab.tsx +116 -116
  111. package/src/client-v2/components/RetrievalTraceTab.tsx +162 -162
  112. package/src/client-v2/components/UsageGovernanceTab.tsx +386 -0
  113. package/src/client-v2/index.tsx +1 -1
  114. package/src/client-v2/pages/AgentBindingsPage.tsx +22 -13
  115. package/src/client-v2/pages/ApprovalsPage.tsx +19 -10
  116. package/src/client-v2/pages/EmployeeGovernancePage.tsx +22 -0
  117. package/src/client-v2/pages/ExecutionHistoryPage.tsx +19 -10
  118. package/src/client-v2/pages/HarnessProfilesPage.tsx +19 -10
  119. package/src/client-v2/pages/KnowledgeAccessPage.tsx +19 -10
  120. package/src/client-v2/pages/LoopSettingsPage.tsx +19 -10
  121. package/src/client-v2/pages/MemoryInspectorPage.tsx +22 -13
  122. package/src/client-v2/pages/RetrievalTracePage.tsx +19 -10
  123. package/src/client-v2/pages/RulesPage.tsx +22 -13
  124. package/src/client-v2/pages/SkillDefinitionsPage.tsx +19 -10
  125. package/src/client-v2/pages/SkillMetricsPage.tsx +19 -10
  126. package/src/client-v2/pages/TracingPage.tsx +22 -13
  127. package/src/client-v2/pages/UsageGovernancePage.tsx +22 -0
  128. package/src/client-v2/plugin.tsx +139 -99
  129. package/src/client-v2/skill-hub/components/ExecutionHistory.tsx +196 -196
  130. package/src/client-v2/skill-hub/components/FileLinkList.tsx +37 -37
  131. package/src/client-v2/skill-hub/components/GitSkillImport.tsx +539 -539
  132. package/src/client-v2/skill-hub/components/LoopSettings.tsx +331 -331
  133. package/src/client-v2/skill-hub/components/SkillEditor.tsx +453 -453
  134. package/src/client-v2/skill-hub/components/SkillManager.tsx +191 -174
  135. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +162 -162
  136. package/src/client-v2/skill-hub/components/SkillTestPanel.tsx +135 -135
  137. package/src/client-v2/skill-hub/locale.ts +13 -13
  138. package/src/client-v2/skill-hub/tools/InteractionSchemasProvider.tsx +62 -0
  139. package/src/client-v2/skill-hub/tools/SkillHubCard.tsx +104 -0
  140. package/src/client-v2/skill-hub/tools/__tests__/interactions.test.ts +110 -0
  141. package/src/client-v2/skill-hub/tools/interactions.ts +128 -0
  142. package/src/client-v2/skill-hub/tools/loopTemplates.ts +52 -52
  143. package/src/client-v2/skill-hub/utils/jsonFields.ts +41 -41
  144. package/src/client-v2/utils/jsonFields.ts +41 -41
  145. package/src/index.ts +2 -2
  146. package/src/locale/en-US.json +229 -1
  147. package/src/locale/zh-CN.json +229 -1
  148. package/src/server/__tests__/agent-execution-context.test.ts +18 -18
  149. package/src/server/__tests__/agent-governance.integration.test.ts +392 -0
  150. package/src/server/__tests__/agent-knowledge-insights.test.ts +123 -123
  151. package/src/server/__tests__/agent-monitor-acl.integration.test.ts +274 -0
  152. package/src/server/__tests__/agent-registry-service.test.ts +147 -147
  153. package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -46
  154. package/src/server/__tests__/agent-usage-report.integration.test.ts +342 -0
  155. package/src/server/__tests__/code-validator.test.ts +63 -63
  156. package/src/server/__tests__/external-rag-search.test.ts +107 -107
  157. package/src/server/__tests__/harness-capabilities.test.ts +95 -0
  158. package/src/server/__tests__/harness-compiler.test.ts +214 -214
  159. package/src/server/__tests__/harness-profile-service.test.ts +167 -167
  160. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -293
  161. package/src/server/__tests__/harness-tool-plan.test.ts +182 -172
  162. package/src/server/__tests__/input-schema-validator.test.ts +26 -26
  163. package/src/server/__tests__/loop-approval-decision.test.ts +577 -512
  164. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -258
  165. package/src/server/__tests__/loop-budget-service.test.ts +36 -0
  166. package/src/server/__tests__/loop-pattern-schema.test.ts +73 -73
  167. package/src/server/__tests__/loop-run-repository.test.ts +32 -0
  168. package/src/server/__tests__/loop-run-state-machine.test.ts +101 -101
  169. package/src/server/__tests__/loop-trigger-service.test.ts +192 -148
  170. package/src/server/__tests__/loop-worker-claim.test.ts +72 -9
  171. package/src/server/__tests__/loop-worker-execution.test.ts +382 -317
  172. package/src/server/__tests__/native-agent-monitor-sync.test.ts +350 -0
  173. package/src/server/__tests__/native-sub-agent-observer.test.ts +470 -662
  174. package/src/server/__tests__/native-usage-attribution.integration.test.ts +175 -0
  175. package/src/server/__tests__/skill-access-service.test.ts +64 -64
  176. package/src/server/__tests__/skill-execute.test.ts +70 -70
  177. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -140
  178. package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -15
  179. package/src/server/__tests__/skill-settings.test.ts +63 -63
  180. package/src/server/__tests__/skill-tool-name.test.ts +23 -23
  181. package/src/server/__tests__/token-tracker.test.ts +639 -0
  182. package/src/server/__tests__/tool-loop-detection.test.ts +276 -276
  183. package/src/server/__tests__/tracing-retention-policy.test.ts +37 -0
  184. package/src/server/__tests__/usage-ledger.integration.test.ts +194 -0
  185. package/src/server/collections/agent-execution-spans.ts +393 -245
  186. package/src/server/collections/agent-governance-audit-events.ts +26 -0
  187. package/src/server/collections/agent-governance-policies.ts +26 -0
  188. package/src/server/collections/agent-governance-policy-versions.ts +27 -0
  189. package/src/server/collections/agent-governance-prompt-bindings.ts +29 -0
  190. package/src/server/collections/agent-loop-action-approvals.ts +39 -39
  191. package/src/server/collections/agent-loop-runs.ts +396 -369
  192. package/src/server/collections/agent-loop-steps.ts +220 -220
  193. package/src/server/collections/agent-memory-contexts.ts +95 -95
  194. package/src/server/collections/orchestrator-config.ts +87 -87
  195. package/src/server/collections/orchestrator-logs.ts +116 -116
  196. package/src/server/collections/skill-definitions.ts +159 -159
  197. package/src/server/collections/skill-executions.ts +154 -154
  198. package/src/server/collections/skill-loop-configs.ts +65 -65
  199. package/src/server/collections/skill-metrics.ts +36 -36
  200. package/src/server/collections/skill-registry-installations.ts +41 -41
  201. package/src/server/collections/skill-worker-configs.ts +86 -86
  202. package/src/server/index.ts +1 -1
  203. package/src/server/migrations/20260423000000-add-progress-fields.ts +50 -50
  204. package/src/server/migrations/20260425000000-add-interaction-schema.ts +37 -37
  205. package/src/server/migrations/20260427000000-add-tracing-detail-fields.ts +41 -41
  206. package/src/server/migrations/20260427000001-change-other-json-to-text.ts +61 -61
  207. package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +145 -145
  208. package/src/server/migrations/20260601000000-add-token-fields.ts +89 -89
  209. package/src/server/migrations/20260615000000-normalize-ai-employee-tool-bindings.ts +39 -39
  210. package/src/server/migrations/20260621000000-native-policy-profile-defaults.ts +190 -190
  211. package/src/server/migrations/20260727000000-remove-unused-knowledge-scopes.ts +25 -25
  212. package/src/server/migrations/20260727010000-backfill-skill-tool-names.ts +45 -45
  213. package/src/server/migrations/20261110000000-add-usage-pricing-snapshots.ts +117 -0
  214. package/src/server/migrations/20261110010000-add-usage-department-attribution.ts +35 -0
  215. package/src/server/plugin.ts +674 -573
  216. package/src/server/resources/agent-governance.ts +168 -0
  217. package/src/server/resources/agent-harness-profile.ts +110 -94
  218. package/src/server/resources/agent-knowledge-insights.ts +306 -306
  219. package/src/server/resources/agent-loop-approval.ts +84 -84
  220. package/src/server/resources/agent-loop-events-stream.ts +108 -108
  221. package/src/server/resources/agent-loop.ts +252 -252
  222. package/src/server/resources/agent-monitor.ts +215 -482
  223. package/src/server/resources/agent-usage.ts +420 -0
  224. package/src/server/resources/native-monitor-format.ts +157 -0
  225. package/src/server/resources/tracing.ts +303 -267
  226. package/src/server/services/AgentExecutionContext.ts +23 -23
  227. package/src/server/services/AgentGovernanceService.ts +548 -0
  228. package/src/server/services/AgentMemoryContextService.ts +344 -344
  229. package/src/server/services/AgentRegistryService.ts +220 -220
  230. package/src/server/services/AgentRuntimeLifecycle.ts +64 -64
  231. package/src/server/services/CodeValidator.ts +238 -238
  232. package/src/server/services/DepartmentAttribution.ts +54 -0
  233. package/src/server/services/DurableCircuitBreakerService.ts +235 -235
  234. package/src/server/services/ExecutionSpanService.ts +278 -146
  235. package/src/server/services/FileManager.ts +159 -159
  236. package/src/server/services/GovernanceAdmission.ts +239 -0
  237. package/src/server/services/HarnessCapabilities.ts +119 -0
  238. package/src/server/services/HarnessCompiler.ts +170 -170
  239. package/src/server/services/HarnessProfileService.ts +235 -235
  240. package/src/server/services/HarnessSchema.ts +194 -194
  241. package/src/server/services/InputSchemaValidator.ts +44 -44
  242. package/src/server/services/LoopBudgetService.ts +332 -271
  243. package/src/server/services/LoopControlService.ts +120 -120
  244. package/src/server/services/LoopPatternSchema.ts +231 -231
  245. package/src/server/services/LoopPatternService.ts +171 -171
  246. package/src/server/services/LoopRunRepository.ts +350 -332
  247. package/src/server/services/LoopRunStateMachine.ts +545 -525
  248. package/src/server/services/LoopSchedulerService.ts +195 -195
  249. package/src/server/services/LoopTriggerService.ts +169 -159
  250. package/src/server/services/LoopWorkerService.ts +986 -912
  251. package/src/server/services/ManagedPromptProtection.ts +88 -0
  252. package/src/server/services/NativeAgentMonitorSyncService.ts +691 -0
  253. package/src/server/services/NativeSubAgentObserver.ts +331 -757
  254. package/src/server/services/NativeUsageAttribution.ts +98 -0
  255. package/src/server/services/PathLockService.ts +317 -317
  256. package/src/server/services/PluginAiRuntimeAdapter.ts +387 -387
  257. package/src/server/services/RunEventBus.ts +58 -58
  258. package/src/server/services/SandboxRunner.ts +492 -492
  259. package/src/server/services/SkillAccessService.ts +175 -175
  260. package/src/server/services/SkillManager.ts +585 -585
  261. package/src/server/services/SkillRepositoryService.ts +236 -236
  262. package/src/server/services/TokenTracker.ts +1158 -287
  263. package/src/server/services/ToolLoopDetectionService.ts +210 -210
  264. package/src/server/services/TracingRetentionPolicy.ts +56 -0
  265. package/src/server/services/VerificationSchema.ts +31 -31
  266. package/src/server/services/VerificationService.ts +332 -313
  267. package/src/server/services/WorkerEnvManager.ts +198 -198
  268. package/src/server/services/__tests__/SkillRepositoryService.test.ts +33 -33
  269. package/src/server/services/harness-runtime-policy.ts +134 -134
  270. package/src/server/services/pythonGuardTemplate.ts +87 -87
  271. package/src/server/services/sandboxCapabilities.ts +348 -348
  272. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +563 -563
  273. package/src/server/skill-hub/actions/git-import.ts +936 -936
  274. package/src/server/skill-hub/mcp/McpController.ts +107 -107
  275. package/src/server/skill-hub/middlewares/git-import-request-method-policy.ts +51 -51
  276. package/src/server/skill-hub/plugin.ts +1232 -1232
  277. package/src/server/skill-hub/sandbox-config.json +6 -6
  278. package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +281 -281
  279. package/src/server/skill-hub/services/__tests__/RegistrySkillInstallationService.test.ts +295 -295
  280. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +568 -568
  281. package/src/server/skill-hub/utils/json-fields.ts +57 -57
  282. package/src/server/tools/delegate-task.ts +30 -30
  283. package/src/server/tools/external-rag-search.ts +329 -329
  284. package/src/server/tools/skill-execute.ts +216 -216
  285. package/src/server/types.ts +21 -21
  286. package/src/server/utils/ai-manager.ts +24 -24
  287. package/src/server/utils/ctx-utils.ts +132 -132
  288. package/src/server/utils/ensure-indexes.ts +119 -96
  289. package/src/server/utils/ha-lock.ts +80 -80
  290. package/src/server/utils/loop-pattern-context.ts +84 -84
  291. package/src/server/utils/record-utils.ts +19 -19
  292. package/src/server/utils/skill-settings.ts +135 -135
  293. package/src/server/utils/skill-tool-name.ts +58 -58
  294. package/dist/client-v2/117.7565cff57c39318a.js +0 -10
  295. package/dist/client-v2/214.106635011859dede.js +0 -10
  296. package/dist/client-v2/253.59577b40d9875be0.js +0 -10
  297. package/dist/client-v2/264.7ed8bee71fa5935c.js +0 -10
  298. package/dist/client-v2/418.41ed200e7d6da332.js +0 -10
  299. package/dist/client-v2/794.a67a2614405ba627.js +0 -10
  300. package/dist/client-v2/993.b0688fdc5ccb000a.js +0 -10
  301. package/dist/node_modules/simple-git/dist/cjs/index.js +0 -7399
  302. package/dist/node_modules/simple-git/dist/esm/index.js +0 -4745
  303. package/dist/node_modules/simple-git/dist/esm/package.json +0 -3
  304. package/dist/node_modules/simple-git/dist/src/lib/api.d.ts +0 -13
  305. package/dist/node_modules/simple-git/dist/src/lib/args/log-format.d.ts +0 -9
  306. package/dist/node_modules/simple-git/dist/src/lib/errors/git-construct-error.d.ts +0 -15
  307. package/dist/node_modules/simple-git/dist/src/lib/errors/git-error.d.ts +0 -30
  308. package/dist/node_modules/simple-git/dist/src/lib/errors/git-plugin-error.d.ts +0 -7
  309. package/dist/node_modules/simple-git/dist/src/lib/errors/git-response-error.d.ts +0 -32
  310. package/dist/node_modules/simple-git/dist/src/lib/errors/task-configuration-error.d.ts +0 -12
  311. package/dist/node_modules/simple-git/dist/src/lib/git-factory.d.ts +0 -15
  312. package/dist/node_modules/simple-git/dist/src/lib/git-logger.d.ts +0 -21
  313. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-branch-delete.d.ts +0 -5
  314. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-branch.d.ts +0 -2
  315. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-commit.d.ts +0 -2
  316. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-diff-summary.d.ts +0 -3
  317. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-fetch.d.ts +0 -2
  318. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-list-log-summary.d.ts +0 -6
  319. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-merge.d.ts +0 -11
  320. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-move.d.ts +0 -2
  321. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-pull.d.ts +0 -6
  322. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-push.d.ts +0 -4
  323. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-remote-messages.d.ts +0 -5
  324. package/dist/node_modules/simple-git/dist/src/lib/parsers/parse-remote-objects.d.ts +0 -3
  325. package/dist/node_modules/simple-git/dist/src/lib/plugins/abort-plugin.d.ts +0 -3
  326. package/dist/node_modules/simple-git/dist/src/lib/plugins/block-unsafe-operations-plugin.d.ts +0 -3
  327. package/dist/node_modules/simple-git/dist/src/lib/plugins/command-config-prefixing-plugin.d.ts +0 -2
  328. package/dist/node_modules/simple-git/dist/src/lib/plugins/completion-detection.plugin.d.ts +0 -3
  329. package/dist/node_modules/simple-git/dist/src/lib/plugins/custom-binary.plugin.d.ts +0 -3
  330. package/dist/node_modules/simple-git/dist/src/lib/plugins/error-detection.plugin.d.ts +0 -7
  331. package/dist/node_modules/simple-git/dist/src/lib/plugins/index.d.ts +0 -11
  332. package/dist/node_modules/simple-git/dist/src/lib/plugins/plugin-store.d.ts +0 -11
  333. package/dist/node_modules/simple-git/dist/src/lib/plugins/progress-monitor-plugin.d.ts +0 -3
  334. package/dist/node_modules/simple-git/dist/src/lib/plugins/simple-git-plugin.d.ts +0 -48
  335. package/dist/node_modules/simple-git/dist/src/lib/plugins/spawn-options-plugin.d.ts +0 -3
  336. package/dist/node_modules/simple-git/dist/src/lib/plugins/suffix-paths.plugin.d.ts +0 -2
  337. package/dist/node_modules/simple-git/dist/src/lib/plugins/timout-plugin.d.ts +0 -3
  338. package/dist/node_modules/simple-git/dist/src/lib/responses/BranchDeleteSummary.d.ts +0 -12
  339. package/dist/node_modules/simple-git/dist/src/lib/responses/BranchSummary.d.ts +0 -14
  340. package/dist/node_modules/simple-git/dist/src/lib/responses/CheckIgnore.d.ts +0 -4
  341. package/dist/node_modules/simple-git/dist/src/lib/responses/CleanSummary.d.ts +0 -9
  342. package/dist/node_modules/simple-git/dist/src/lib/responses/ConfigList.d.ts +0 -13
  343. package/dist/node_modules/simple-git/dist/src/lib/responses/DiffSummary.d.ts +0 -10
  344. package/dist/node_modules/simple-git/dist/src/lib/responses/FileStatusSummary.d.ts +0 -9
  345. package/dist/node_modules/simple-git/dist/src/lib/responses/GetRemoteSummary.d.ts +0 -11
  346. package/dist/node_modules/simple-git/dist/src/lib/responses/InitSummary.d.ts +0 -9
  347. package/dist/node_modules/simple-git/dist/src/lib/responses/MergeSummary.d.ts +0 -16
  348. package/dist/node_modules/simple-git/dist/src/lib/responses/PullSummary.d.ts +0 -25
  349. package/dist/node_modules/simple-git/dist/src/lib/responses/StatusSummary.d.ts +0 -19
  350. package/dist/node_modules/simple-git/dist/src/lib/responses/TagList.d.ts +0 -7
  351. package/dist/node_modules/simple-git/dist/src/lib/runners/git-executor-chain.d.ts +0 -25
  352. package/dist/node_modules/simple-git/dist/src/lib/runners/git-executor.d.ts +0 -14
  353. package/dist/node_modules/simple-git/dist/src/lib/runners/promise-wrapped.d.ts +0 -2
  354. package/dist/node_modules/simple-git/dist/src/lib/runners/scheduler.d.ts +0 -11
  355. package/dist/node_modules/simple-git/dist/src/lib/runners/tasks-pending-queue.d.ts +0 -23
  356. package/dist/node_modules/simple-git/dist/src/lib/simple-git-api.d.ts +0 -20
  357. package/dist/node_modules/simple-git/dist/src/lib/task-callback.d.ts +0 -2
  358. package/dist/node_modules/simple-git/dist/src/lib/tasks/apply-patch.d.ts +0 -3
  359. package/dist/node_modules/simple-git/dist/src/lib/tasks/branch.d.ts +0 -7
  360. package/dist/node_modules/simple-git/dist/src/lib/tasks/change-working-directory.d.ts +0 -2
  361. package/dist/node_modules/simple-git/dist/src/lib/tasks/check-ignore.d.ts +0 -2
  362. package/dist/node_modules/simple-git/dist/src/lib/tasks/check-is-repo.d.ts +0 -9
  363. package/dist/node_modules/simple-git/dist/src/lib/tasks/checkout.d.ts +0 -2
  364. package/dist/node_modules/simple-git/dist/src/lib/tasks/clean.d.ts +0 -25
  365. package/dist/node_modules/simple-git/dist/src/lib/tasks/clone.d.ts +0 -9
  366. package/dist/node_modules/simple-git/dist/src/lib/tasks/commit.d.ts +0 -4
  367. package/dist/node_modules/simple-git/dist/src/lib/tasks/config.d.ts +0 -8
  368. package/dist/node_modules/simple-git/dist/src/lib/tasks/count-objects.d.ts +0 -12
  369. package/dist/node_modules/simple-git/dist/src/lib/tasks/diff-name-status.d.ts +0 -12
  370. package/dist/node_modules/simple-git/dist/src/lib/tasks/diff.d.ts +0 -5
  371. package/dist/node_modules/simple-git/dist/src/lib/tasks/fetch.d.ts +0 -4
  372. package/dist/node_modules/simple-git/dist/src/lib/tasks/first-commit.d.ts +0 -2
  373. package/dist/node_modules/simple-git/dist/src/lib/tasks/grep.d.ts +0 -12
  374. package/dist/node_modules/simple-git/dist/src/lib/tasks/hash-object.d.ts +0 -5
  375. package/dist/node_modules/simple-git/dist/src/lib/tasks/init.d.ts +0 -3
  376. package/dist/node_modules/simple-git/dist/src/lib/tasks/log.d.ts +0 -32
  377. package/dist/node_modules/simple-git/dist/src/lib/tasks/merge.d.ts +0 -4
  378. package/dist/node_modules/simple-git/dist/src/lib/tasks/move.d.ts +0 -3
  379. package/dist/node_modules/simple-git/dist/src/lib/tasks/pull.d.ts +0 -3
  380. package/dist/node_modules/simple-git/dist/src/lib/tasks/push.d.ts +0 -9
  381. package/dist/node_modules/simple-git/dist/src/lib/tasks/remote.d.ts +0 -8
  382. package/dist/node_modules/simple-git/dist/src/lib/tasks/reset.d.ts +0 -11
  383. package/dist/node_modules/simple-git/dist/src/lib/tasks/show.d.ts +0 -2
  384. package/dist/node_modules/simple-git/dist/src/lib/tasks/stash-list.d.ts +0 -4
  385. package/dist/node_modules/simple-git/dist/src/lib/tasks/status.d.ts +0 -3
  386. package/dist/node_modules/simple-git/dist/src/lib/tasks/sub-module.d.ts +0 -5
  387. package/dist/node_modules/simple-git/dist/src/lib/tasks/tag.d.ts +0 -18
  388. package/dist/node_modules/simple-git/dist/src/lib/tasks/task.d.ts +0 -14
  389. package/dist/node_modules/simple-git/dist/src/lib/tasks/version.d.ts +0 -9
  390. package/dist/node_modules/simple-git/dist/src/lib/types/handlers.d.ts +0 -21
  391. package/dist/node_modules/simple-git/dist/src/lib/types/index.d.ts +0 -136
  392. package/dist/node_modules/simple-git/dist/src/lib/types/tasks.d.ts +0 -19
  393. package/dist/node_modules/simple-git/dist/src/lib/utils/argument-filters.d.ts +0 -14
  394. package/dist/node_modules/simple-git/dist/src/lib/utils/exit-codes.d.ts +0 -10
  395. package/dist/node_modules/simple-git/dist/src/lib/utils/git-output-streams.d.ts +0 -7
  396. package/dist/node_modules/simple-git/dist/src/lib/utils/index.d.ts +0 -8
  397. package/dist/node_modules/simple-git/dist/src/lib/utils/line-parser.d.ts +0 -15
  398. package/dist/node_modules/simple-git/dist/src/lib/utils/simple-git-options.d.ts +0 -2
  399. package/dist/node_modules/simple-git/dist/src/lib/utils/task-options.d.ts +0 -13
  400. package/dist/node_modules/simple-git/dist/src/lib/utils/task-parser.d.ts +0 -5
  401. package/dist/node_modules/simple-git/dist/src/lib/utils/util.d.ts +0 -47
  402. package/dist/node_modules/simple-git/dist/typings/errors.d.ts +0 -5
  403. package/dist/node_modules/simple-git/dist/typings/index.d.ts +0 -14
  404. package/dist/node_modules/simple-git/dist/typings/response.d.ts +0 -556
  405. package/dist/node_modules/simple-git/dist/typings/simple-git.d.ts +0 -1033
  406. package/dist/node_modules/simple-git/dist/typings/types.d.ts +0 -22
  407. package/dist/node_modules/simple-git/node_modules/debug/package.json +0 -64
  408. package/dist/node_modules/simple-git/node_modules/debug/src/browser.js +0 -272
  409. package/dist/node_modules/simple-git/node_modules/debug/src/common.js +0 -292
  410. package/dist/node_modules/simple-git/node_modules/debug/src/index.js +0 -10
  411. package/dist/node_modules/simple-git/node_modules/debug/src/node.js +0 -263
  412. package/dist/node_modules/simple-git/package.json +0 -1
  413. package/dist/node_modules/simple-git/promise.js +0 -17
@@ -1,912 +1,986 @@
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 { TokenTracker } from './TokenTracker';
17
- import { VerificationService } from './VerificationService';
18
- import { read } from '../utils/record-utils';
19
- import { asObject } from '../utils/ctx-utils';
20
-
21
- const POLL_INTERVAL_MS = 3_000;
22
- const LEASE_MS = 120_000;
23
- const HEARTBEAT_MS = 30_000;
24
- const PATH_LOCK_TTL_MS = 900_000;
25
-
26
- const LEADER_SYSTEM_MESSAGE =
27
- '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.';
28
- const MAKER_SYSTEM_MESSAGE =
29
- '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.';
30
-
31
- export type LoopWorkerSyncMessage = {
32
- type: 'loop-run-abort-requested';
33
- runId: number;
34
- };
35
-
36
- export function loopWorkerAbortMessage(runId: number): LoopWorkerSyncMessage {
37
- return { type: 'loop-run-abort-requested', runId };
38
- }
39
-
40
- type ResumeContext = {
41
- role: 'leader' | 'maker';
42
- username: string;
43
- sessionId: string;
44
- messageId: string;
45
- makerReports: string[];
46
- makerQueue: string[];
47
- };
48
-
49
- export type RunProgress = {
50
- currentPhase: 'leader' | 'maker' | 'verifying' | 'complete';
51
- totalPhases: number;
52
- completedPhases: number;
53
- currentStepTitle: string;
54
- currentRole: string;
55
- estimatedMsRemaining: number | null;
56
- startedAt: string;
57
- updatedAt: string;
58
- };
59
-
60
- function buildProgress(
61
- phase: RunProgress['currentPhase'],
62
- totalPhases: number,
63
- completedPhases: number,
64
- stepTitle: string,
65
- role: string,
66
- startedAt: Date,
67
- ): RunProgress {
68
- return {
69
- currentPhase: phase,
70
- totalPhases,
71
- completedPhases,
72
- currentStepTitle: stepTitle,
73
- currentRole: role,
74
- estimatedMsRemaining: null,
75
- startedAt: startedAt.toISOString(),
76
- updatedAt: new Date().toISOString(),
77
- };
78
- }
79
-
80
- type RunSnapshot = {
81
- id: number;
82
- patternId: number;
83
- goal: string;
84
- autonomyLevel: 'L1' | 'L2' | 'L3';
85
- policy: LoopPatternPolicy;
86
- leaderUsername: string;
87
- makerUsernames: string[];
88
- verifierUsername: string;
89
- leaderHarness: CompiledHarness;
90
- makerHarnesses: Record<string, { effective: CompiledHarness }>;
91
- verifierHarness: CompiledHarness;
92
- repositoryKey: string;
93
- actingOn: string[];
94
- userId?: number;
95
- approvalStatus: string;
96
- resumeContext: ResumeContext | null;
97
- };
98
-
99
- function asStringArray(value: unknown): string[] {
100
- return Array.isArray(value) ? value.map((item) => String(item)).filter(Boolean) : [];
101
- }
102
-
103
- function autonomyLevel(value: unknown): 'L1' | 'L2' | 'L3' {
104
- return value === 'L2' || value === 'L3' ? value : 'L1';
105
- }
106
-
107
- function harnessFrom(value: unknown): CompiledHarness {
108
- const snapshot = asObject(value);
109
- const effective = asObject(snapshot.effective);
110
- if (!effective.tools) throw new Error('The run harness snapshot is missing its compiled settings.');
111
- return effective as unknown as CompiledHarness;
112
- }
113
-
114
- function resumeContextFrom(value: unknown): ResumeContext | null {
115
- const context = asObject(value);
116
- if (!context) return null;
117
- const role = context.role === 'leader' || context.role === 'maker' ? context.role : null;
118
- const username = typeof context.username === 'string' ? context.username : '';
119
- const sessionId = typeof context.sessionId === 'string' ? context.sessionId : '';
120
- const messageId = typeof context.messageId === 'string' ? context.messageId : '';
121
- if (!role || !username || !sessionId || !messageId) return null;
122
- return {
123
- role,
124
- username,
125
- sessionId,
126
- messageId,
127
- makerReports: asStringArray(context.makerReports),
128
- makerQueue: asStringArray(context.makerQueue),
129
- };
130
- }
131
-
132
- function inputHash(value: unknown) {
133
- return createHash('sha256')
134
- .update(JSON.stringify(value ?? null))
135
- .digest('hex');
136
- }
137
-
138
- export class LoopWorkerService {
139
- private readonly control: LoopControlService;
140
- private readonly stateMachine: LoopRunStateMachine;
141
- private readonly budgets: LoopBudgetService;
142
- private readonly circuits: DurableCircuitBreakerService;
143
- private readonly pathLocks: PathLockService;
144
- private readonly runtime: PluginAiRuntimeAdapter;
145
- private readonly verification: VerificationService;
146
- private readonly loopGuard: ToolLoopDetectionService;
147
- private readonly tokenTracker: TokenTracker;
148
- private readonly workerId: string;
149
- private readonly active = new Map<number, AbortController>();
150
- private readonly heldPathLocks = new Map<number, string>();
151
- private timer: ReturnType<typeof setTimeout> | null = null;
152
- private running = false;
153
- private draining: Promise<void> | null = null;
154
-
155
- constructor(
156
- private readonly app: Application,
157
- private readonly database: Database,
158
- ) {
159
- const distributedLock = {
160
- runExclusive: <T>(key: string, operation: () => Promise<T>, ttl?: number) =>
161
- this.app.lockManager.runExclusive(key, operation, ttl),
162
- };
163
- this.control = new LoopControlService(database);
164
- this.stateMachine = new LoopRunStateMachine(database);
165
- this.budgets = new LoopBudgetService(database, distributedLock);
166
- this.circuits = new DurableCircuitBreakerService(database, distributedLock);
167
- this.pathLocks = new PathLockService(database, distributedLock);
168
- this.runtime = new PluginAiRuntimeAdapter(app);
169
- this.tokenTracker = new TokenTracker({ app, db: database });
170
- this.verification = new VerificationService(database, this.runtime, this.stateMachine, this.tokenTracker);
171
- this.loopGuard = new ToolLoopDetectionService(database);
172
- this.workerId = `${app.name}:${process.pid}:${randomUUID()}`;
173
- }
174
-
175
- readonly start = () => {
176
- // Multi-instance deployments dedicate a process to background work; only that process
177
- // should claim runs, otherwise every web node competes for the same leases.
178
- if (this.running || !this.app.serving('agent-loop:worker')) return;
179
- this.running = true;
180
- this.scheduleNextPoll();
181
- };
182
-
183
- async stop() {
184
- this.running = false;
185
- if (this.timer) clearTimeout(this.timer);
186
- this.timer = null;
187
- for (const controller of this.active.values()) controller.abort();
188
- if (this.draining) await this.draining.catch(() => undefined);
189
- }
190
-
191
- abortRun(runId: number) {
192
- this.active.get(runId)?.abort();
193
- }
194
-
195
- // A run is only active on the node that claimed it, and `sendSyncMessage` publishes with
196
- // `skipSelf`, so pause/cancel aborts locally and broadcasts for whichever other node holds it.
197
- async handleSyncMessage(message: unknown) {
198
- if (!message || typeof message !== 'object') return;
199
- const value = message as Partial<LoopWorkerSyncMessage>;
200
- if (value.type !== 'loop-run-abort-requested') return;
201
- const runId = Number(value.runId);
202
- if (!Number.isSafeInteger(runId) || runId <= 0) return;
203
- this.abortRun(runId);
204
- }
205
-
206
- private scheduleNextPoll() {
207
- if (!this.running) return;
208
- this.timer = setTimeout(() => {
209
- this.draining = this.poll()
210
- .catch((error) => {
211
- this.app.logger.error('[AgentOrchestrator] Loop worker poll failed.', { error });
212
- })
213
- .finally(() => this.scheduleNextPoll());
214
- }, POLL_INTERVAL_MS);
215
- }
216
-
217
- private async poll() {
218
- if (!this.running) return;
219
- await this.stateMachine.expireOverdueApprovals(new Date()).catch((error) => {
220
- this.app.logger.error('[AgentOrchestrator] Approval expiry sweep failed.', { error });
221
- });
222
- const claimed = await this.stateMachine.claimNext(this.workerId, LEASE_MS);
223
- if (!claimed) return;
224
- await this.execute(claimed);
225
- }
226
-
227
- private async updateProgress(runId: number, progress: RunProgress) {
228
- await this.database
229
- .getRepository('agentLoopRuns')
230
- .update({
231
- filterByTk: runId,
232
- values: { progress },
233
- })
234
- .catch((error: unknown) => {
235
- this.app.logger?.warn?.(`[AgentOrchestrator] Failed to update progress for run ${runId}`, { error });
236
- });
237
- }
238
-
239
- private async execute(claimed: ClaimedLoopRun) {
240
- const runId = Number(claimed.run.id);
241
- const controller = new AbortController();
242
- this.active.set(runId, controller);
243
-
244
- // The path lock TTL is much longer than the run lease, but a run can outlive it. Renewing both
245
- // on the same beat keeps them expiring together, so a run can never keep executing on paths
246
- // whose lock another run is already free to take.
247
- const heartbeat = setInterval(() => {
248
- this.heartbeat(runId, claimed.leaseToken).catch((error) => {
249
- this.app.logger.warn(`[AgentOrchestrator] Loop run ${runId} lost its worker lease.`, { error });
250
- controller.abort();
251
- });
252
- }, HEARTBEAT_MS);
253
-
254
- let snapshot: RunSnapshot | null = null;
255
- try {
256
- snapshot = this.snapshotFrom(claimed.run);
257
- await this.runToCompletion(snapshot, claimed.leaseToken, controller.signal);
258
- } catch (error) {
259
- await this.failRun(runId, claimed.leaseToken, snapshot, error);
260
- } finally {
261
- clearInterval(heartbeat);
262
- this.active.delete(runId);
263
- const repositoryKey = this.heldPathLocks.get(runId);
264
- this.heldPathLocks.delete(runId);
265
- if (repositoryKey) {
266
- // The lease token is the lock owner. Passing it stops a worker whose lease was already
267
- // reclaimed from releasing a lock the new owner of the same run now holds.
268
- await this.pathLocks
269
- .release(runId, repositoryKey, claimed.leaseToken)
270
- .catch((error) => this.app.logger.warn(`[AgentOrchestrator] Path lock release failed.`, { error }));
271
- }
272
- await this.stateMachine.releaseLease(runId, claimed.leaseToken).catch(() => undefined);
273
- }
274
- }
275
-
276
- private async heartbeat(runId: number, leaseToken: string) {
277
- await this.stateMachine.renewLease(runId, leaseToken, LEASE_MS);
278
- const repositoryKey = this.heldPathLocks.get(runId);
279
- if (repositoryKey) await this.pathLocks.renew(runId, repositoryKey, PATH_LOCK_TTL_MS, leaseToken);
280
- }
281
-
282
- private async runToCompletion(snapshot: RunSnapshot, leaseToken: string, signal: AbortSignal) {
283
- await this.control.assertCanExecute();
284
- const scopeKey = `pattern:${snapshot.patternId}`;
285
- await this.circuits.authorizeAttempt({
286
- patternId: snapshot.patternId,
287
- scopeKey,
288
- policy: snapshot.policy.circuit,
289
- });
290
-
291
- if (!(await this.acquirePaths(snapshot, leaseToken))) return;
292
-
293
- // A run requeued from a pause while its approvals are still pending has nothing to execute:
294
- // the decisions never arrived, so it parks again instead of restarting from the leader.
295
- if (snapshot.resumeContext && snapshot.approvalStatus === 'pending') {
296
- await this.stateMachine.transition({
297
- runId: snapshot.id,
298
- to: 'waiting_approval',
299
- actorType: 'worker',
300
- actorIdentity: this.workerId,
301
- leaseToken,
302
- eventType: 'run_waiting_approval',
303
- title: 'Waiting for action approval',
304
- content: 'Run requeued while its approval decisions are still pending.',
305
- correlationKey: `approval-repark:${snapshot.id}`,
306
- values: { approvalStatus: 'pending' },
307
- });
308
- return;
309
- }
310
-
311
- await this.stateMachine.transition({
312
- runId: snapshot.id,
313
- to: 'running',
314
- actorType: 'worker',
315
- actorIdentity: this.workerId,
316
- leaseToken,
317
- eventType: 'run_started',
318
- title: snapshot.resumeContext ? 'Run resumed' : 'Run started',
319
- content: snapshot.resumeContext
320
- ? `${snapshot.resumeContext.username} resumed after approval decisions.`
321
- : `Leader ${snapshot.leaderUsername} began working on the goal.`,
322
- correlationKey: `started:${snapshot.id}`,
323
- values: { currentRole: snapshot.resumeContext ? snapshot.resumeContext.role : 'leader' },
324
- });
325
-
326
- // Loops recorded before this claim (for example before a park for approval) keep warning the
327
- // prompts composed later in the run.
328
- const loopNotices = await this.loopGuard.existingNotices(snapshot.id);
329
- const totalPhases = 1 + snapshot.makerUsernames.length + 1;
330
- const runStartedAt = new Date();
331
-
332
- let makerReports: string[];
333
- let makerQueue: string[];
334
-
335
- if (snapshot.resumeContext) {
336
- const resume = snapshot.resumeContext;
337
- const decisions = await this.consumeDecisions(snapshot.id);
338
- const resumed = await this.resumeRole(snapshot, resume, decisions, signal);
339
-
340
- const resumeGuard = await this.enforceToolLoopGuard(
341
- snapshot,
342
- leaseToken,
343
- { role: resume.role, username: resume.username },
344
- loopNotices,
345
- );
346
- if (resumeGuard === 'halt') return;
347
-
348
- // A resumed conversation can hit another approval gate; park with the same role context so
349
- // the next resume continues exactly where this one stopped.
350
- if (resumed.interrupted.length) {
351
- await this.parkForApproval(snapshot, resumed, leaseToken, {
352
- role: resume.role,
353
- username: resume.username,
354
- makerReports: resume.makerReports,
355
- makerQueue: resume.makerQueue,
356
- });
357
- return;
358
- }
359
- if (resume.role === 'leader') {
360
- makerReports = [resumed.content];
361
- makerQueue = [...snapshot.makerUsernames];
362
- } else {
363
- makerReports = [...resume.makerReports, `# ${resume.username}\n${resumed.content}`];
364
- makerQueue = [...resume.makerQueue];
365
- }
366
- } else {
367
- const leader = await this.invokeRole(snapshot, {
368
- role: 'leader',
369
- username: snapshot.leaderUsername,
370
- harness: snapshot.leaderHarness,
371
- systemMessage: LEADER_SYSTEM_MESSAGE,
372
- prompt: snapshot.goal,
373
- leaseToken,
374
- signal,
375
- });
376
-
377
- const leaderGuard = await this.enforceToolLoopGuard(
378
- snapshot,
379
- leaseToken,
380
- { role: 'leader', username: snapshot.leaderUsername },
381
- loopNotices,
382
- );
383
- if (leaderGuard === 'halt') return;
384
- await this.updateProgress(
385
- snapshot.id,
386
- buildProgress('leader', totalPhases, 1, 'Leader plan complete', 'leader', runStartedAt),
387
- );
388
-
389
- // plugin-ai stops the graph on an approval-gated tool. Approval is a human decision, so the
390
- // run parks here instead of the worker deciding on the operator's behalf.
391
- if (leader.interrupted.length) {
392
- await this.parkForApproval(snapshot, leader, leaseToken, {
393
- role: 'leader',
394
- username: snapshot.leaderUsername,
395
- makerReports: [],
396
- makerQueue: snapshot.makerUsernames,
397
- });
398
- return;
399
- }
400
- makerReports = [leader.content];
401
- makerQueue = [...snapshot.makerUsernames];
402
- }
403
-
404
- // Each maker executes with its own compiled harness snapshot. Reusing one harness would apply
405
- // the wrong per-employee tool grants, so the snapshot is looked up by username and a maker with
406
- // no snapshot is a compile error, not a silent skip.
407
- while (makerQueue.length) {
408
- const username = makerQueue[0];
409
- const harness = snapshot.makerHarnesses[username]?.effective;
410
- if (!harness) {
411
- throw new Error(`The claimed run has no harness snapshot for maker "${username}".`);
412
- }
413
- const maker = await this.invokeRole(snapshot, {
414
- role: 'maker',
415
- username,
416
- harness,
417
- systemMessage: MAKER_SYSTEM_MESSAGE,
418
- prompt: [
419
- `Goal: ${snapshot.goal}`,
420
- '',
421
- "Leader's plan:",
422
- makerReports[0] || '(the leader produced no textual plan)',
423
- ...loopNotices,
424
- ].join('\n'),
425
- leaseToken,
426
- signal,
427
- });
428
- const makerGuard = await this.enforceToolLoopGuard(
429
- snapshot,
430
- leaseToken,
431
- { role: 'maker', username },
432
- loopNotices,
433
- );
434
- if (makerGuard === 'halt') return;
435
- if (maker.interrupted.length) {
436
- await this.parkForApproval(snapshot, maker, leaseToken, {
437
- role: 'maker',
438
- username,
439
- makerReports,
440
- makerQueue: makerQueue.slice(1),
441
- });
442
- return;
443
- }
444
- makerReports.push(`# ${username}\n${maker.content}`);
445
- const completedMakers = snapshot.makerUsernames.length - makerQueue.length + 1;
446
- await this.updateProgress(
447
- snapshot.id,
448
- buildProgress('maker', totalPhases, 1 + completedMakers, `Maker "${username}" complete`, 'maker', runStartedAt),
449
- );
450
- makerQueue = makerQueue.slice(1);
451
- }
452
- const makerSummary = makerReports.join('\n\n');
453
-
454
- await this.stateMachine.transition({
455
- runId: snapshot.id,
456
- to: 'verifying',
457
- actorType: 'worker',
458
- actorIdentity: this.workerId,
459
- leaseToken,
460
- eventType: 'run_verifying',
461
- title: 'Verification started',
462
- content: `Verifier ${snapshot.verifierUsername} is reviewing the reported result.`,
463
- correlationKey: `verifying:${snapshot.id}`,
464
- values: { currentRole: 'verifier', finalAnswer: makerSummary },
465
- });
466
- await this.updateProgress(
467
- snapshot.id,
468
- buildProgress(
469
- 'verifying',
470
- totalPhases,
471
- totalPhases - 1,
472
- `Verifier "${snapshot.verifierUsername}" reviewing`,
473
- 'verifier',
474
- runStartedAt,
475
- ),
476
- );
477
-
478
- await this.budgets.reserve({
479
- runId: snapshot.id,
480
- patternId: snapshot.patternId,
481
- policy: snapshot.policy,
482
- delta: { verifications: 1 },
483
- });
484
- const outcome = await this.verification.verifyAndFinalize({
485
- runId: snapshot.id,
486
- goal: snapshot.goal,
487
- autonomyLevel: snapshot.autonomyLevel,
488
- verifierUsername: snapshot.verifierUsername,
489
- leaderUsername: snapshot.leaderUsername,
490
- makerUsernames: snapshot.makerUsernames,
491
- verifierHarness: snapshot.verifierHarness,
492
- policy: snapshot.policy,
493
- makerSummary,
494
- actingOn: snapshot.actingOn,
495
- userId: snapshot.userId,
496
- workerId: this.workerId,
497
- leaseToken,
498
- loopNotices,
499
- signal,
500
- });
501
-
502
- // The tool loop guard already moved the run to blocked or waiting_human; the circuit breaker
503
- // tracks failed attempts, not behavioral stops, so it must not see this as a failure.
504
- if (outcome.finalStatus === 'halted') return;
505
-
506
- if (outcome.finalStatus === 'failed') {
507
- await this.circuits.recordFailure({
508
- patternId: snapshot.patternId,
509
- scopeKey: `pattern:${snapshot.patternId}`,
510
- policy: snapshot.policy.circuit,
511
- error: new Error(`Verifier rejected run ${snapshot.id}.`),
512
- lastRunId: snapshot.id,
513
- });
514
- return;
515
- }
516
- await this.circuits.recordSuccess(snapshot.patternId, `pattern:${snapshot.patternId}`, snapshot.id);
517
- await this.updateProgress(
518
- snapshot.id,
519
- buildProgress(
520
- 'complete',
521
- totalPhases,
522
- totalPhases,
523
- 'Run completed successfully',
524
- snapshot.currentRole || 'verifier',
525
- runStartedAt,
526
- ),
527
- );
528
- }
529
-
530
- private async acquirePaths(snapshot: RunSnapshot, leaseToken: string) {
531
- if (!snapshot.repositoryKey || !snapshot.actingOn.length) return true;
532
- const lock = await this.pathLocks.acquire({
533
- runId: snapshot.id,
534
- repositoryKey: snapshot.repositoryKey,
535
- owner: leaseToken,
536
- paths: snapshot.actingOn,
537
- ttlMs: PATH_LOCK_TTL_MS,
538
- });
539
- if (lock.acquired) {
540
- // Recorded before any work starts so the heartbeat renews this lock for as long as the run
541
- // executes, and the release in `execute` frees exactly the lock this worker took.
542
- this.heldPathLocks.set(snapshot.id, snapshot.repositoryKey);
543
- return true;
544
- }
545
-
546
- const deadlocked = lock.deadlocked;
547
- await this.stateMachine.transition({
548
- runId: snapshot.id,
549
- to: deadlocked ? 'blocked' : 'waiting_lock',
550
- actorType: 'worker',
551
- actorIdentity: this.workerId,
552
- leaseToken,
553
- eventType: deadlocked ? 'run_blocked' : 'run_waiting_lock',
554
- title: deadlocked ? 'Run blocked by a lock cycle' : 'Waiting for repository paths',
555
- content: `Blocked by run(s): ${lock.blockers.join(', ')}.`,
556
- correlationKey: `lock:${snapshot.id}:${lock.blockers.join('-')}`,
557
- values: deadlocked ? { blockedReason: 'Path lock wait graph contains a cycle.' } : {},
558
- });
559
- return false;
560
- }
561
-
562
- private async invokeRole(
563
- snapshot: RunSnapshot,
564
- input: {
565
- role: 'leader' | 'maker';
566
- username: string;
567
- harness: CompiledHarness;
568
- systemMessage: string;
569
- prompt: string;
570
- leaseToken: string;
571
- signal: AbortSignal;
572
- },
573
- ) {
574
- await this.budgets.reserve({
575
- runId: snapshot.id,
576
- patternId: snapshot.patternId,
577
- policy: snapshot.policy,
578
- delta: { invocations: 1 },
579
- });
580
- const sessionId = await this.runtime.createConversation({
581
- username: input.username,
582
- userId: snapshot.userId,
583
- runId: snapshot.id,
584
- title: snapshot.goal.slice(0, 200),
585
- });
586
- const step = await this.database.getRepository('agentLoopSteps').create({
587
- values: {
588
- runId: snapshot.id,
589
- runtimeVersion: 'control-plane-v2',
590
- sequence: await this.nextSequence(snapshot.id),
591
- role: input.role,
592
- kind: 'invocation',
593
- type: 'reasoning',
594
- employeeUsername: input.username,
595
- sessionId,
596
- title: `${input.role} invocation`,
597
- inputHash: inputHash(input.prompt),
598
- status: 'running',
599
- startedAt: new Date(),
600
- createdAt: new Date(),
601
- },
602
- });
603
-
604
- const outcome = await this.runtime.invoke({
605
- username: input.username,
606
- sessionId,
607
- userId: snapshot.userId,
608
- systemMessage: input.systemMessage,
609
- harness: input.harness,
610
- prompt: input.prompt,
611
- signal: input.signal,
612
- });
613
-
614
- // Track actual token usage from the LLM response; fall back to text-length estimation
615
- await this.tokenTracker.trackActualUsage(
616
- read(step, 'id'),
617
- outcome.tokenUsage ?? null,
618
- input.prompt,
619
- outcome.content,
620
- snapshot.id,
621
- );
622
-
623
- await this.database.getRepository('agentLoopSteps').update({
624
- filterByTk: read(step, 'id'),
625
- values: {
626
- status: outcome.interrupted.length ? 'waiting_user' : 'succeeded',
627
- output: { content: outcome.content },
628
- endedAt: new Date(),
629
- },
630
- });
631
- await this.database.getRepository('agentLoopRuns').update({
632
- filterByTk: snapshot.id,
633
- values: { sessionId: outcome.sessionId, messageId: outcome.messageId },
634
- });
635
- return outcome;
636
- }
637
-
638
- private async resumeRole(
639
- snapshot: RunSnapshot,
640
- resume: ResumeContext,
641
- decisions: Array<{ toolCallId: string; decision: ToolCallDecision }>,
642
- signal: AbortSignal,
643
- ) {
644
- await this.budgets.reserve({
645
- runId: snapshot.id,
646
- patternId: snapshot.patternId,
647
- policy: snapshot.policy,
648
- delta: { invocations: 1 },
649
- });
650
- const harness =
651
- resume.role === 'leader' ? snapshot.leaderHarness : snapshot.makerHarnesses[resume.username]?.effective;
652
- if (!harness) {
653
- throw new Error(`The claimed run has no harness snapshot for ${resume.role} "${resume.username}".`);
654
- }
655
- const step = await this.database.getRepository('agentLoopSteps').create({
656
- values: {
657
- runId: snapshot.id,
658
- runtimeVersion: 'control-plane-v2',
659
- sequence: await this.nextSequence(snapshot.id),
660
- role: resume.role,
661
- kind: 'invocation',
662
- type: 'resume',
663
- employeeUsername: resume.username,
664
- sessionId: resume.sessionId,
665
- title: `${resume.role} resume after approval`,
666
- inputHash: inputHash(decisions),
667
- status: 'running',
668
- startedAt: new Date(),
669
- createdAt: new Date(),
670
- },
671
- });
672
-
673
- const outcome = await this.runtime.resume({
674
- username: resume.username,
675
- sessionId: resume.sessionId,
676
- messageId: resume.messageId,
677
- userId: snapshot.userId,
678
- systemMessage: resume.role === 'leader' ? LEADER_SYSTEM_MESSAGE : MAKER_SYSTEM_MESSAGE,
679
- harness,
680
- decisions,
681
- signal,
682
- });
683
-
684
- // Track actual token usage from the LLM response; fall back to text-length estimation
685
- await this.tokenTracker.trackActualUsage(
686
- read(step, 'id'),
687
- outcome.tokenUsage ?? null,
688
- resume.role === 'leader' ? LEADER_SYSTEM_MESSAGE : MAKER_SYSTEM_MESSAGE,
689
- outcome.content,
690
- snapshot.id,
691
- );
692
-
693
- await this.database.getRepository('agentLoopSteps').update({
694
- filterByTk: read(step, 'id'),
695
- values: {
696
- status: outcome.interrupted.length ? 'waiting_user' : 'succeeded',
697
- output: { content: outcome.content },
698
- endedAt: new Date(),
699
- },
700
- });
701
- await this.database.getRepository('agentLoopRuns').update({
702
- filterByTk: snapshot.id,
703
- values: { sessionId: outcome.sessionId, messageId: outcome.messageId },
704
- });
705
- return outcome;
706
- }
707
-
708
- // Run-level scan over every tool call issued so far, evaluated at each pass boundary. A warning
709
- // is injected into the prompts composed later in the run; block and escalate halt it at once.
710
- private async enforceToolLoopGuard(
711
- snapshot: RunSnapshot,
712
- leaseToken: string,
713
- pass: { role: 'leader' | 'maker'; username: string },
714
- loopNotices: string[],
715
- ): Promise<'continue' | 'halt'> {
716
- const finding = await this.loopGuard.scanRun(snapshot.id, snapshot.policy);
717
- if (!finding) return 'continue';
718
-
719
- await this.loopGuard.recordFinding(
720
- {
721
- runId: snapshot.id,
722
- role: pass.role,
723
- username: pass.username,
724
- runStatus: 'running',
725
- actorType: 'worker',
726
- actorIdentity: this.workerId,
727
- },
728
- finding,
729
- );
730
-
731
- if (finding.level === 'warn') {
732
- const notice = toolLoopNotice(finding.toolName, finding.count);
733
- if (!loopNotices.includes(notice)) loopNotices.push(notice);
734
- return 'continue';
735
- }
736
-
737
- const reason = toolLoopReason(finding);
738
- await this.stateMachine.transition({
739
- runId: snapshot.id,
740
- to: finding.level === 'block' ? 'blocked' : 'waiting_human',
741
- actorType: 'worker',
742
- actorIdentity: this.workerId,
743
- leaseToken,
744
- eventType: finding.level === 'block' ? 'run_blocked' : 'run_escalated',
745
- title: finding.level === 'block' ? 'Run blocked by tool loop detection' : 'Run escalated by tool loop detection',
746
- content: reason,
747
- correlationKey: `tool-loop-${finding.level}:${snapshot.id}:${finding.signature}`,
748
- values: finding.level === 'block' ? { blockedReason: reason } : { escalationReason: reason },
749
- });
750
- return 'halt';
751
- }
752
-
753
- // Decisions are consumed exactly once: rows are marked consumed so a retry or a second resume
754
- // can never replay a human decision against a fresh conversation.
755
- private async consumeDecisions(runId: number) {
756
- const repository = this.database.getRepository('agentLoopActionApprovals');
757
- const approvals = await repository.find({ filter: { runId } });
758
- const decisions: Array<{ toolCallId: string; decision: ToolCallDecision }> = [];
759
- const now = new Date();
760
- for (const approval of approvals) {
761
- const status = String(read(approval, 'status'));
762
- if (status !== 'approved' && status !== 'rejected') continue;
763
- if (read(approval, 'consumedAt')) continue;
764
- const editedInput = read(approval, 'editedInput');
765
- const decision: ToolCallDecision =
766
- status === 'approved'
767
- ? editedInput
768
- ? { type: 'edit', editedAction: { name: String(read(approval, 'toolName')), args: editedInput } }
769
- : { type: 'approve' }
770
- : { type: 'reject', message: String(read(approval, 'decisionNote') || '') || undefined };
771
- decisions.push({ toolCallId: String(read(approval, 'toolCallId')), decision });
772
- await repository.update({ filterByTk: Number(read(approval, 'id')), values: { consumedAt: now } });
773
- }
774
- if (!decisions.length) throw new Error('The resumed run has no recorded approval decisions.');
775
- return decisions;
776
- }
777
-
778
- private async parkForApproval(
779
- snapshot: RunSnapshot,
780
- outcome: InvocationOutcome,
781
- leaseToken: string,
782
- context: { role: 'leader' | 'maker'; username: string; makerReports: string[]; makerQueue: string[] },
783
- ) {
784
- const now = new Date();
785
- const expiresAt = new Date(now.getTime() + snapshot.policy.actions.approvalTimeoutMs);
786
- const assignedToId = snapshot.policy.actions.approvalAssigneeIds[0] || snapshot.userId || null;
787
- const harness =
788
- context.role === 'leader' ? snapshot.leaderHarness : snapshot.makerHarnesses[context.username]?.effective;
789
- const escalatable = new Set(harness?.tools.escalate ?? []);
790
- for (const call of outcome.interrupted) {
791
- // An escalation is a request for authority the harness never granted, widened for exactly
792
- // one call; a plain tool_call approval gates a tool the harness allows but asks about.
793
- const escalation = escalatable.has(call.toolName);
794
- await this.database.getRepository('agentLoopActionApprovals').create({
795
- values: {
796
- runId: snapshot.id,
797
- toolCallId: call.toolCallId,
798
- toolName: call.toolName,
799
- actionType: escalation ? 'escalation' : 'tool_call',
800
- proposedInput: call.args,
801
- inputHash: inputHash(call.args),
802
- paths: snapshot.actingOn,
803
- policyDecision: { decision: 'ask', interruptId: call.interruptId },
804
- reason: escalation
805
- ? `Tool "${call.toolName}" is not granted by this run's harness. Approving widens authority for this single call only.`
806
- : `Tool "${call.toolName}" requires human approval under this pattern's policy.`,
807
- status: 'pending',
808
- assignedToId,
809
- requestedById: snapshot.userId || null,
810
- requestedAt: now,
811
- expiresAt,
812
- createdAt: now,
813
- },
814
- });
815
- }
816
- await this.database.getRepository('agentLoopRuns').update({
817
- filterByTk: snapshot.id,
818
- values: {
819
- // The resume point is durable: which role stopped, in which conversation, with which
820
- // reports already collected and which makers still queued. Without it a resumed run
821
- // would restart from the leader and redo every completed invocation.
822
- resumeContext: {
823
- role: context.role,
824
- username: context.username,
825
- sessionId: outcome.sessionId,
826
- messageId: outcome.messageId,
827
- makerReports: context.makerReports,
828
- makerQueue: context.makerQueue,
829
- },
830
- },
831
- });
832
- await this.stateMachine.transition({
833
- runId: snapshot.id,
834
- to: 'waiting_approval',
835
- actorType: 'worker',
836
- actorIdentity: this.workerId,
837
- leaseToken,
838
- eventType: 'run_waiting_approval',
839
- title: 'Waiting for action approval',
840
- content: `${outcome.interrupted.length} tool call(s) require approval.`,
841
- correlationKey: `approval:${snapshot.id}:${outcome.messageId}`,
842
- values: { approvalStatus: 'pending', messageId: outcome.messageId },
843
- });
844
- }
845
-
846
- private async failRun(runId: number, leaseToken: string, snapshot: RunSnapshot | null, error: unknown) {
847
- const message = error instanceof Error ? error.message : String(error);
848
- try {
849
- if (snapshot) {
850
- await this.circuits.recordFailure({
851
- patternId: snapshot.patternId,
852
- scopeKey: `pattern:${snapshot.patternId}`,
853
- policy: snapshot.policy.circuit,
854
- error,
855
- lastRunId: runId,
856
- });
857
- }
858
- await this.stateMachine.transition({
859
- runId,
860
- to: 'failed',
861
- actorType: 'worker',
862
- actorIdentity: this.workerId,
863
- leaseToken,
864
- eventType: 'run_failed',
865
- title: 'Run failed',
866
- content: message,
867
- correlationKey: `failed:${runId}`,
868
- values: { summary: message },
869
- });
870
- } catch (transitionError) {
871
- this.app.logger.error(`[AgentOrchestrator] Loop run ${runId} could not be marked failed.`, {
872
- error: transitionError,
873
- cause: message,
874
- });
875
- }
876
- }
877
-
878
- private async nextSequence(runId: number) {
879
- return this.database.getRepository('agentLoopSteps').count({ filter: { runId } });
880
- }
881
-
882
- private snapshotFrom(run: Record<string, unknown>): RunSnapshot {
883
- const patternId = Number(run.patternId);
884
- if (!Number.isSafeInteger(patternId) || patternId <= 0) {
885
- throw new Error('The claimed run has no pattern snapshot.');
886
- }
887
- const roleBindings = asObject(run.roleBindingsSnapshot);
888
- const makerSnapshots = asObject(run.makerHarnessSnapshot);
889
- const approvalStatus = String(run.approvalStatus || 'none');
890
- return {
891
- id: Number(run.id),
892
- patternId,
893
- goal: String(run.goal || ''),
894
- autonomyLevel: autonomyLevel(run.autonomyLevel),
895
- policy: loopPatternPolicySchema.parse(run.policySnapshot),
896
- leaderUsername: String(roleBindings.leader || run.leaderUsername || ''),
897
- makerUsernames: asStringArray(roleBindings.makers),
898
- verifierUsername: String(roleBindings.verifier || run.verifierUsername || ''),
899
- leaderHarness: harnessFrom(run.leaderHarnessSnapshot),
900
- makerHarnesses: makerSnapshots as Record<string, { effective: CompiledHarness }>,
901
- verifierHarness: harnessFrom(run.verifierHarnessSnapshot),
902
- repositoryKey: String(run.repositoryKey || ''),
903
- actingOn: asStringArray(run.actingOn),
904
- userId: Number(run.userId) || undefined,
905
- approvalStatus,
906
- // Only a live approval state may resume. Stale context left over from an expired window or a
907
- // cleared retry would otherwise replay an old conversation against fresh approvals.
908
- resumeContext:
909
- approvalStatus === 'decided' || approvalStatus === 'pending' ? resumeContextFrom(run.resumeContext) : null,
910
- };
911
- }
912
- }
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { createHash, randomUUID } from 'node:crypto';
11
+ import type { Database, Model } from '@nocobase/database';
12
+ import type { Application } from '@nocobase/server';
13
+ import { DurableCircuitBreakerService } from './DurableCircuitBreakerService';
14
+ import type { CompiledHarness } from './HarnessCompiler';
15
+ import { LoopBudgetService } from './LoopBudgetService';
16
+ import { LoopControlService } from './LoopControlService';
17
+ import { loopPatternPolicySchema } from './LoopPatternSchema';
18
+ import type { LoopPatternPolicy } from './LoopPatternSchema';
19
+ import { LoopRunStateMachine } from './LoopRunStateMachine';
20
+ import type { ClaimedLoopRun } from './LoopRunStateMachine';
21
+ import { PathLockService } from './PathLockService';
22
+ import { PluginAiRuntimeAdapter } from './PluginAiRuntimeAdapter';
23
+ import type { InvocationOutcome, ToolCallDecision } from './PluginAiRuntimeAdapter';
24
+ import { ToolLoopDetectionService, toolLoopNotice, toolLoopReason } from './ToolLoopDetectionService';
25
+ import { TokenTracker } from './TokenTracker';
26
+ import { VerificationService } from './VerificationService';
27
+ import { read } from '../utils/record-utils';
28
+ import { asObject } from '../utils/ctx-utils';
29
+
30
+ const POLL_INTERVAL_MS = 3_000;
31
+ const LEASE_MS = 120_000;
32
+ const HEARTBEAT_MS = 30_000;
33
+ const PATH_LOCK_TTL_MS = 900_000;
34
+
35
+ const LEADER_SYSTEM_MESSAGE =
36
+ '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.';
37
+ const MAKER_SYSTEM_MESSAGE =
38
+ '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.';
39
+
40
+ export type LoopWorkerSyncMessage = {
41
+ type: 'loop-run-abort-requested';
42
+ runId: number;
43
+ };
44
+
45
+ export function loopWorkerAbortMessage(runId: number): LoopWorkerSyncMessage {
46
+ return { type: 'loop-run-abort-requested', runId };
47
+ }
48
+
49
+ type ResumeContext = {
50
+ role: 'leader' | 'maker';
51
+ username: string;
52
+ sessionId: string;
53
+ messageId: string;
54
+ makerReports: string[];
55
+ makerQueue: string[];
56
+ };
57
+
58
+ export type RunProgress = {
59
+ currentPhase: 'leader' | 'maker' | 'verifying' | 'complete';
60
+ totalPhases: number;
61
+ completedPhases: number;
62
+ currentStepTitle: string;
63
+ currentRole: string;
64
+ estimatedMsRemaining: number | null;
65
+ startedAt: string;
66
+ updatedAt: string;
67
+ };
68
+
69
+ function buildProgress(
70
+ phase: RunProgress['currentPhase'],
71
+ totalPhases: number,
72
+ completedPhases: number,
73
+ stepTitle: string,
74
+ role: string,
75
+ startedAt: Date,
76
+ ): RunProgress {
77
+ return {
78
+ currentPhase: phase,
79
+ totalPhases,
80
+ completedPhases,
81
+ currentStepTitle: stepTitle,
82
+ currentRole: role,
83
+ estimatedMsRemaining: null,
84
+ startedAt: startedAt.toISOString(),
85
+ updatedAt: new Date().toISOString(),
86
+ };
87
+ }
88
+
89
+ type RunSnapshot = {
90
+ id: number;
91
+ rootRunId: string;
92
+ patternId: number;
93
+ goal: string;
94
+ autonomyLevel: 'L1' | 'L2' | 'L3';
95
+ policy: LoopPatternPolicy;
96
+ leaderUsername: string;
97
+ makerUsernames: string[];
98
+ verifierUsername: string;
99
+ leaderHarness: CompiledHarness;
100
+ makerHarnesses: Record<string, { effective: CompiledHarness }>;
101
+ verifierHarness: CompiledHarness;
102
+ repositoryKey: string;
103
+ actingOn: string[];
104
+ userId?: number;
105
+ approvalStatus: string;
106
+ resumeContext: ResumeContext | null;
107
+ verificationRecoverySummary: string | null;
108
+ };
109
+
110
+ function asStringArray(value: unknown): string[] {
111
+ return Array.isArray(value) ? value.map((item) => String(item)).filter(Boolean) : [];
112
+ }
113
+
114
+ function autonomyLevel(value: unknown): 'L1' | 'L2' | 'L3' {
115
+ return value === 'L2' || value === 'L3' ? value : 'L1';
116
+ }
117
+
118
+ function harnessFrom(value: unknown): CompiledHarness {
119
+ const snapshot = asObject(value);
120
+ const effective = asObject(snapshot.effective);
121
+ if (!effective.tools) throw new Error('The run harness snapshot is missing its compiled settings.');
122
+ return effective as unknown as CompiledHarness;
123
+ }
124
+
125
+ function resumeContextFrom(value: unknown): ResumeContext | null {
126
+ const context = asObject(value);
127
+ if (!context) return null;
128
+ const role = context.role === 'leader' || context.role === 'maker' ? context.role : null;
129
+ const username = typeof context.username === 'string' ? context.username : '';
130
+ const sessionId = typeof context.sessionId === 'string' ? context.sessionId : '';
131
+ const messageId = typeof context.messageId === 'string' ? context.messageId : '';
132
+ if (!role || !username || !sessionId || !messageId) return null;
133
+ return {
134
+ role,
135
+ username,
136
+ sessionId,
137
+ messageId,
138
+ makerReports: asStringArray(context.makerReports),
139
+ makerQueue: asStringArray(context.makerQueue),
140
+ };
141
+ }
142
+
143
+ function inputHash(value: unknown) {
144
+ return createHash('sha256')
145
+ .update(JSON.stringify(value ?? null))
146
+ .digest('hex');
147
+ }
148
+
149
+ export class LoopWorkerService {
150
+ private readonly control: LoopControlService;
151
+ private readonly stateMachine: LoopRunStateMachine;
152
+ private readonly budgets: LoopBudgetService;
153
+ private readonly circuits: DurableCircuitBreakerService;
154
+ private readonly pathLocks: PathLockService;
155
+ private readonly runtime: PluginAiRuntimeAdapter;
156
+ private readonly verification: VerificationService;
157
+ private readonly loopGuard: ToolLoopDetectionService;
158
+ private readonly tokenTracker: TokenTracker;
159
+ private readonly workerId: string;
160
+ private readonly active = new Map<number, AbortController>();
161
+ private readonly heldPathLocks = new Map<number, string>();
162
+ private timer: ReturnType<typeof setTimeout> | null = null;
163
+ private running = false;
164
+ private draining: Promise<void> | null = null;
165
+
166
+ constructor(
167
+ private readonly app: Application,
168
+ private readonly database: Database,
169
+ ) {
170
+ const distributedLock = {
171
+ runExclusive: <T>(key: string, operation: () => Promise<T>, ttl?: number) =>
172
+ this.app.lockManager.runExclusive(key, operation, ttl),
173
+ };
174
+ this.control = new LoopControlService(database);
175
+ this.stateMachine = new LoopRunStateMachine(database);
176
+ this.budgets = new LoopBudgetService(database, distributedLock);
177
+ this.circuits = new DurableCircuitBreakerService(database, distributedLock);
178
+ this.pathLocks = new PathLockService(database, distributedLock);
179
+ this.runtime = new PluginAiRuntimeAdapter(app);
180
+ this.tokenTracker = new TokenTracker({ app, db: database });
181
+ this.verification = new VerificationService(database, this.runtime, this.stateMachine, this.tokenTracker);
182
+ this.loopGuard = new ToolLoopDetectionService(database);
183
+ this.workerId = `${app.name}:${process.pid}:${randomUUID()}`;
184
+ }
185
+
186
+ readonly start = () => {
187
+ // Multi-instance deployments dedicate a process to background work; only that process
188
+ // should claim runs, otherwise every web node competes for the same leases.
189
+ if (this.running || !this.app.serving('agent-loop:worker')) return;
190
+ this.running = true;
191
+ this.scheduleNextPoll();
192
+ };
193
+
194
+ async stop() {
195
+ this.running = false;
196
+ if (this.timer) clearTimeout(this.timer);
197
+ this.timer = null;
198
+ for (const controller of this.active.values()) controller.abort();
199
+ if (this.draining) await this.draining.catch(() => undefined);
200
+ }
201
+
202
+ abortRun(runId: number) {
203
+ this.active.get(runId)?.abort();
204
+ }
205
+
206
+ // A run is only active on the node that claimed it, and `sendSyncMessage` publishes with
207
+ // `skipSelf`, so pause/cancel aborts locally and broadcasts for whichever other node holds it.
208
+ async handleSyncMessage(message: unknown) {
209
+ if (!message || typeof message !== 'object') return;
210
+ const value = message as Partial<LoopWorkerSyncMessage>;
211
+ if (value.type !== 'loop-run-abort-requested') return;
212
+ const runId = Number(value.runId);
213
+ if (!Number.isSafeInteger(runId) || runId <= 0) return;
214
+ this.abortRun(runId);
215
+ }
216
+
217
+ private scheduleNextPoll() {
218
+ if (!this.running) return;
219
+ this.timer = setTimeout(() => {
220
+ this.draining = this.poll()
221
+ .catch((error) => {
222
+ this.app.logger.error('[AgentOrchestrator] Loop worker poll failed.', { error });
223
+ })
224
+ .finally(() => this.scheduleNextPoll());
225
+ }, POLL_INTERVAL_MS);
226
+ }
227
+
228
+ private async poll() {
229
+ if (!this.running) return;
230
+ await this.stateMachine.expireOverdueApprovals(new Date()).catch((error) => {
231
+ this.app.logger.error('[AgentOrchestrator] Approval expiry sweep failed.', { error });
232
+ });
233
+ const claimed = await this.stateMachine.claimNext(this.workerId, LEASE_MS);
234
+ if (!claimed) return;
235
+ await this.execute(claimed);
236
+ }
237
+
238
+ private async updateProgress(runId: number, progress: RunProgress) {
239
+ await this.database
240
+ .getRepository('agentLoopRuns')
241
+ .update({
242
+ filterByTk: runId,
243
+ values: { progress },
244
+ })
245
+ .catch((error: unknown) => {
246
+ this.app.logger?.warn?.(`[AgentOrchestrator] Failed to update progress for run ${runId}`, { error });
247
+ });
248
+ }
249
+
250
+ private async execute(claimed: ClaimedLoopRun) {
251
+ const runId = Number(claimed.run.id);
252
+ const controller = new AbortController();
253
+ this.active.set(runId, controller);
254
+
255
+ // The path lock TTL is much longer than the run lease, but a run can outlive it. Renewing both
256
+ // on the same beat keeps them expiring together, so a run can never keep executing on paths
257
+ // whose lock another run is already free to take.
258
+ const heartbeat = setInterval(() => {
259
+ this.heartbeat(runId, claimed.leaseToken).catch((error) => {
260
+ this.app.logger.warn(`[AgentOrchestrator] Loop run ${runId} lost its worker lease.`, { error });
261
+ controller.abort();
262
+ });
263
+ }, HEARTBEAT_MS);
264
+
265
+ let snapshot: RunSnapshot | null = null;
266
+ try {
267
+ snapshot = this.snapshotFrom(claimed.run);
268
+ await this.runToCompletion(snapshot, claimed.leaseToken, controller.signal);
269
+ } catch (error) {
270
+ await this.failRun(runId, claimed.leaseToken, snapshot, error);
271
+ } finally {
272
+ clearInterval(heartbeat);
273
+ this.active.delete(runId);
274
+ const repositoryKey = this.heldPathLocks.get(runId);
275
+ this.heldPathLocks.delete(runId);
276
+ if (repositoryKey) {
277
+ // The lease token is the lock owner. Passing it stops a worker whose lease was already
278
+ // reclaimed from releasing a lock the new owner of the same run now holds.
279
+ await this.pathLocks
280
+ .release(runId, repositoryKey, claimed.leaseToken)
281
+ .catch((error) => this.app.logger.warn(`[AgentOrchestrator] Path lock release failed.`, { error }));
282
+ }
283
+ await this.stateMachine.releaseLease(runId, claimed.leaseToken).catch(() => undefined);
284
+ }
285
+ }
286
+
287
+ private async heartbeat(runId: number, leaseToken: string) {
288
+ await this.stateMachine.renewLease(runId, leaseToken, LEASE_MS);
289
+ const repositoryKey = this.heldPathLocks.get(runId);
290
+ if (repositoryKey) await this.pathLocks.renew(runId, repositoryKey, PATH_LOCK_TTL_MS, leaseToken);
291
+ }
292
+
293
+ private async runToCompletion(snapshot: RunSnapshot, leaseToken: string, signal: AbortSignal) {
294
+ await this.control.assertCanExecute();
295
+ const scopeKey = `pattern:${snapshot.patternId}`;
296
+ await this.circuits.authorizeAttempt({
297
+ patternId: snapshot.patternId,
298
+ scopeKey,
299
+ policy: snapshot.policy.circuit,
300
+ });
301
+
302
+ if (!(await this.acquirePaths(snapshot, leaseToken))) return;
303
+
304
+ // A run requeued from a pause while its approvals are still pending has nothing to execute:
305
+ // the decisions never arrived, so it parks again instead of restarting from the leader.
306
+ if (snapshot.resumeContext && snapshot.approvalStatus === 'pending') {
307
+ await this.stateMachine.transition({
308
+ runId: snapshot.id,
309
+ to: 'waiting_approval',
310
+ actorType: 'worker',
311
+ actorIdentity: this.workerId,
312
+ leaseToken,
313
+ eventType: 'run_waiting_approval',
314
+ title: 'Waiting for action approval',
315
+ content: 'Run requeued while its approval decisions are still pending.',
316
+ correlationKey: `approval-repark:${snapshot.id}`,
317
+ values: { approvalStatus: 'pending' },
318
+ });
319
+ return;
320
+ }
321
+
322
+ await this.stateMachine.transition({
323
+ runId: snapshot.id,
324
+ to: 'running',
325
+ actorType: 'worker',
326
+ actorIdentity: this.workerId,
327
+ leaseToken,
328
+ eventType: 'run_started',
329
+ title: snapshot.verificationRecoverySummary
330
+ ? 'Verification recovery started'
331
+ : snapshot.resumeContext
332
+ ? 'Run resumed'
333
+ : 'Run started',
334
+ content: snapshot.verificationRecoverySummary
335
+ ? 'Recovering verification using the saved maker summary.'
336
+ : snapshot.resumeContext
337
+ ? `${snapshot.resumeContext.username} resumed after approval decisions.`
338
+ : `Leader ${snapshot.leaderUsername} began working on the goal.`,
339
+ correlationKey: snapshot.verificationRecoverySummary
340
+ ? `verification-recovery-started:${leaseToken}`
341
+ : `started:${snapshot.id}`,
342
+ values: {
343
+ currentRole: snapshot.verificationRecoverySummary
344
+ ? 'verifier'
345
+ : snapshot.resumeContext
346
+ ? snapshot.resumeContext.role
347
+ : 'leader',
348
+ },
349
+ });
350
+
351
+ // Loops recorded before this claim (for example before a park for approval) keep warning the
352
+ // prompts composed later in the run.
353
+ const loopNotices = await this.loopGuard.existingNotices(snapshot.id);
354
+ const totalPhases = 1 + snapshot.makerUsernames.length + 1;
355
+ const runStartedAt = new Date();
356
+
357
+ if (snapshot.verificationRecoverySummary) {
358
+ return this.finishVerification(
359
+ snapshot,
360
+ leaseToken,
361
+ signal,
362
+ loopNotices,
363
+ totalPhases,
364
+ runStartedAt,
365
+ snapshot.verificationRecoverySummary,
366
+ );
367
+ }
368
+
369
+ let makerReports: string[];
370
+ let makerQueue: string[];
371
+
372
+ if (snapshot.resumeContext) {
373
+ const resume = snapshot.resumeContext;
374
+ const decisions = await this.consumeDecisions(snapshot.id);
375
+ const resumed = await this.resumeRole(snapshot, resume, decisions, signal);
376
+
377
+ const resumeGuard = await this.enforceToolLoopGuard(
378
+ snapshot,
379
+ leaseToken,
380
+ { role: resume.role, username: resume.username },
381
+ loopNotices,
382
+ );
383
+ if (resumeGuard === 'halt') return;
384
+
385
+ // A resumed conversation can hit another approval gate; park with the same role context so
386
+ // the next resume continues exactly where this one stopped.
387
+ if (resumed.interrupted.length) {
388
+ await this.parkForApproval(snapshot, resumed, leaseToken, {
389
+ role: resume.role,
390
+ username: resume.username,
391
+ makerReports: resume.makerReports,
392
+ makerQueue: resume.makerQueue,
393
+ });
394
+ return;
395
+ }
396
+ if (resume.role === 'leader') {
397
+ makerReports = [resumed.content];
398
+ makerQueue = [...snapshot.makerUsernames];
399
+ } else {
400
+ makerReports = [...resume.makerReports, `# ${resume.username}\n${resumed.content}`];
401
+ makerQueue = [...resume.makerQueue];
402
+ }
403
+ } else {
404
+ const leader = await this.invokeRole(snapshot, {
405
+ role: 'leader',
406
+ username: snapshot.leaderUsername,
407
+ harness: snapshot.leaderHarness,
408
+ systemMessage: LEADER_SYSTEM_MESSAGE,
409
+ prompt: snapshot.goal,
410
+ leaseToken,
411
+ signal,
412
+ });
413
+
414
+ const leaderGuard = await this.enforceToolLoopGuard(
415
+ snapshot,
416
+ leaseToken,
417
+ { role: 'leader', username: snapshot.leaderUsername },
418
+ loopNotices,
419
+ );
420
+ if (leaderGuard === 'halt') return;
421
+ await this.updateProgress(
422
+ snapshot.id,
423
+ buildProgress('leader', totalPhases, 1, 'Leader plan complete', 'leader', runStartedAt),
424
+ );
425
+
426
+ // plugin-ai stops the graph on an approval-gated tool. Approval is a human decision, so the
427
+ // run parks here instead of the worker deciding on the operator's behalf.
428
+ if (leader.interrupted.length) {
429
+ await this.parkForApproval(snapshot, leader, leaseToken, {
430
+ role: 'leader',
431
+ username: snapshot.leaderUsername,
432
+ makerReports: [],
433
+ makerQueue: snapshot.makerUsernames,
434
+ });
435
+ return;
436
+ }
437
+ makerReports = [leader.content];
438
+ makerQueue = [...snapshot.makerUsernames];
439
+ }
440
+
441
+ // Each maker executes with its own compiled harness snapshot. Reusing one harness would apply
442
+ // the wrong per-employee tool grants, so the snapshot is looked up by username and a maker with
443
+ // no snapshot is a compile error, not a silent skip.
444
+ while (makerQueue.length) {
445
+ const username = makerQueue[0];
446
+ const harness = snapshot.makerHarnesses[username]?.effective;
447
+ if (!harness) {
448
+ throw new Error(`The claimed run has no harness snapshot for maker "${username}".`);
449
+ }
450
+ const maker = await this.invokeRole(snapshot, {
451
+ role: 'maker',
452
+ username,
453
+ harness,
454
+ systemMessage: MAKER_SYSTEM_MESSAGE,
455
+ prompt: [
456
+ `Goal: ${snapshot.goal}`,
457
+ '',
458
+ "Leader's plan:",
459
+ makerReports[0] || '(the leader produced no textual plan)',
460
+ ...loopNotices,
461
+ ].join('\n'),
462
+ leaseToken,
463
+ signal,
464
+ });
465
+ const makerGuard = await this.enforceToolLoopGuard(
466
+ snapshot,
467
+ leaseToken,
468
+ { role: 'maker', username },
469
+ loopNotices,
470
+ );
471
+ if (makerGuard === 'halt') return;
472
+ if (maker.interrupted.length) {
473
+ await this.parkForApproval(snapshot, maker, leaseToken, {
474
+ role: 'maker',
475
+ username,
476
+ makerReports,
477
+ makerQueue: makerQueue.slice(1),
478
+ });
479
+ return;
480
+ }
481
+ makerReports.push(`# ${username}\n${maker.content}`);
482
+ const completedMakers = snapshot.makerUsernames.length - makerQueue.length + 1;
483
+ await this.updateProgress(
484
+ snapshot.id,
485
+ buildProgress('maker', totalPhases, 1 + completedMakers, `Maker "${username}" complete`, 'maker', runStartedAt),
486
+ );
487
+ makerQueue = makerQueue.slice(1);
488
+ }
489
+ const makerSummary = makerReports.join('\n\n');
490
+
491
+ await this.finishVerification(snapshot, leaseToken, signal, loopNotices, totalPhases, runStartedAt, makerSummary);
492
+ }
493
+
494
+ private async finishVerification(
495
+ snapshot: RunSnapshot,
496
+ leaseToken: string,
497
+ signal: AbortSignal,
498
+ loopNotices: string[],
499
+ totalPhases: number,
500
+ runStartedAt: Date,
501
+ makerSummary: string,
502
+ ) {
503
+ await this.stateMachine.transition({
504
+ runId: snapshot.id,
505
+ to: 'verifying',
506
+ actorType: 'worker',
507
+ actorIdentity: this.workerId,
508
+ leaseToken,
509
+ eventType: 'run_verifying',
510
+ title: 'Verification started',
511
+ content: `Verifier ${snapshot.verifierUsername} is reviewing the reported result.`,
512
+ correlationKey: snapshot.verificationRecoverySummary
513
+ ? `verification-recovery:${leaseToken}`
514
+ : `verifying:${snapshot.id}`,
515
+ values: {
516
+ currentRole: 'verifier',
517
+ finalAnswer: makerSummary,
518
+ ...(snapshot.verificationRecoverySummary ? { resumeContext: null } : {}),
519
+ },
520
+ });
521
+ await this.updateProgress(
522
+ snapshot.id,
523
+ buildProgress(
524
+ 'verifying',
525
+ totalPhases,
526
+ totalPhases - 1,
527
+ `Verifier "${snapshot.verifierUsername}" reviewing`,
528
+ 'verifier',
529
+ runStartedAt,
530
+ ),
531
+ );
532
+
533
+ await this.budgets.reserve({
534
+ runId: snapshot.id,
535
+ patternId: snapshot.patternId,
536
+ policy: snapshot.policy,
537
+ delta: { verifications: 1 },
538
+ });
539
+ const outcome = await this.verification.verifyAndFinalize({
540
+ runId: snapshot.id,
541
+ rootRunId: snapshot.rootRunId,
542
+ goal: snapshot.goal,
543
+ autonomyLevel: snapshot.autonomyLevel,
544
+ verifierUsername: snapshot.verifierUsername,
545
+ leaderUsername: snapshot.leaderUsername,
546
+ makerUsernames: snapshot.makerUsernames,
547
+ verifierHarness: snapshot.verifierHarness,
548
+ policy: snapshot.policy,
549
+ makerSummary,
550
+ actingOn: snapshot.actingOn,
551
+ userId: snapshot.userId,
552
+ workerId: this.workerId,
553
+ leaseToken,
554
+ loopNotices,
555
+ signal,
556
+ });
557
+
558
+ // The tool loop guard already moved the run to blocked or waiting_human; the circuit breaker
559
+ // tracks failed attempts, not behavioral stops, so it must not see this as a failure.
560
+ if (outcome.finalStatus === 'halted') return;
561
+
562
+ if (outcome.finalStatus === 'failed') {
563
+ await this.circuits.recordFailure({
564
+ patternId: snapshot.patternId,
565
+ scopeKey: `pattern:${snapshot.patternId}`,
566
+ policy: snapshot.policy.circuit,
567
+ error: new Error(`Verifier rejected run ${snapshot.id}.`),
568
+ lastRunId: snapshot.id,
569
+ });
570
+ return;
571
+ }
572
+ await this.circuits.recordSuccess(snapshot.patternId, `pattern:${snapshot.patternId}`, snapshot.id);
573
+ await this.updateProgress(
574
+ snapshot.id,
575
+ buildProgress('complete', totalPhases, totalPhases, 'Run completed successfully', 'verifier', runStartedAt),
576
+ );
577
+ }
578
+
579
+ private async acquirePaths(snapshot: RunSnapshot, leaseToken: string) {
580
+ if (!snapshot.repositoryKey || !snapshot.actingOn.length) return true;
581
+ const lock = await this.pathLocks.acquire({
582
+ runId: snapshot.id,
583
+ repositoryKey: snapshot.repositoryKey,
584
+ owner: leaseToken,
585
+ paths: snapshot.actingOn,
586
+ ttlMs: PATH_LOCK_TTL_MS,
587
+ });
588
+ if (lock.acquired === true) {
589
+ // Recorded before any work starts so the heartbeat renews this lock for as long as the run
590
+ // executes, and the release in `execute` frees exactly the lock this worker took.
591
+ this.heldPathLocks.set(snapshot.id, snapshot.repositoryKey);
592
+ return true;
593
+ }
594
+
595
+ const deadlocked = lock.deadlocked;
596
+ await this.stateMachine.transition({
597
+ runId: snapshot.id,
598
+ to: deadlocked ? 'blocked' : 'waiting_lock',
599
+ actorType: 'worker',
600
+ actorIdentity: this.workerId,
601
+ leaseToken,
602
+ eventType: deadlocked ? 'run_blocked' : 'run_waiting_lock',
603
+ title: deadlocked ? 'Run blocked by a lock cycle' : 'Waiting for repository paths',
604
+ content: `Blocked by run(s): ${lock.blockers.join(', ')}.`,
605
+ correlationKey: `lock:${snapshot.id}:${lock.blockers.join('-')}`,
606
+ values: deadlocked ? { blockedReason: 'Path lock wait graph contains a cycle.' } : {},
607
+ });
608
+ return false;
609
+ }
610
+
611
+ private async invokeRole(
612
+ snapshot: RunSnapshot,
613
+ input: {
614
+ role: 'leader' | 'maker';
615
+ username: string;
616
+ harness: CompiledHarness;
617
+ systemMessage: string;
618
+ prompt: string;
619
+ leaseToken: string;
620
+ signal: AbortSignal;
621
+ },
622
+ ) {
623
+ await this.budgets.reserve({
624
+ runId: snapshot.id,
625
+ patternId: snapshot.patternId,
626
+ policy: snapshot.policy,
627
+ delta: { invocations: 1 },
628
+ });
629
+ const sessionId = await this.runtime.createConversation({
630
+ username: input.username,
631
+ userId: snapshot.userId,
632
+ runId: snapshot.id,
633
+ title: snapshot.goal.slice(0, 200),
634
+ });
635
+ const step = await this.database.getRepository('agentLoopSteps').create({
636
+ values: {
637
+ runId: snapshot.id,
638
+ runtimeVersion: 'control-plane-v2',
639
+ sequence: await this.nextSequence(snapshot.id),
640
+ role: input.role,
641
+ kind: 'invocation',
642
+ type: 'reasoning',
643
+ employeeUsername: input.username,
644
+ sessionId,
645
+ title: `${input.role} invocation`,
646
+ inputHash: inputHash(input.prompt),
647
+ status: 'running',
648
+ startedAt: new Date(),
649
+ createdAt: new Date(),
650
+ },
651
+ });
652
+
653
+ const outcome = await this.runtime.invoke({
654
+ username: input.username,
655
+ sessionId,
656
+ userId: snapshot.userId,
657
+ systemMessage: input.systemMessage,
658
+ harness: input.harness,
659
+ prompt: input.prompt,
660
+ signal: input.signal,
661
+ });
662
+
663
+ const stepId = read(step, 'id');
664
+ if (typeof stepId !== 'string' && typeof stepId !== 'number') throw new Error('Invocation step has no identifier.');
665
+ await this.tokenTracker.trackLoopInvocationUsage({
666
+ runId: snapshot.id,
667
+ rootRunId: snapshot.rootRunId,
668
+ stepId,
669
+ sessionId: outcome.sessionId,
670
+ messageId: outcome.messageId,
671
+ usage: outcome.tokenUsage,
672
+ input: input.prompt,
673
+ output: outcome.content,
674
+ role: input.role,
675
+ employeeUsername: input.username,
676
+ userId: snapshot.userId,
677
+ });
678
+
679
+ await this.database.getRepository('agentLoopSteps').update({
680
+ filterByTk: stepId,
681
+ values: {
682
+ status: outcome.interrupted.length ? 'waiting_user' : 'succeeded',
683
+ output: { content: outcome.content },
684
+ endedAt: new Date(),
685
+ },
686
+ });
687
+ await this.database.getRepository('agentLoopRuns').update({
688
+ filterByTk: snapshot.id,
689
+ values: { sessionId: outcome.sessionId, messageId: outcome.messageId },
690
+ });
691
+ return outcome;
692
+ }
693
+
694
+ private async resumeRole(
695
+ snapshot: RunSnapshot,
696
+ resume: ResumeContext,
697
+ decisions: Array<{ toolCallId: string; decision: ToolCallDecision }>,
698
+ signal: AbortSignal,
699
+ ) {
700
+ await this.budgets.reserve({
701
+ runId: snapshot.id,
702
+ patternId: snapshot.patternId,
703
+ policy: snapshot.policy,
704
+ delta: { invocations: 1 },
705
+ });
706
+ const harness =
707
+ resume.role === 'leader' ? snapshot.leaderHarness : snapshot.makerHarnesses[resume.username]?.effective;
708
+ if (!harness) {
709
+ throw new Error(`The claimed run has no harness snapshot for ${resume.role} "${resume.username}".`);
710
+ }
711
+ const step = await this.database.getRepository('agentLoopSteps').create({
712
+ values: {
713
+ runId: snapshot.id,
714
+ runtimeVersion: 'control-plane-v2',
715
+ sequence: await this.nextSequence(snapshot.id),
716
+ role: resume.role,
717
+ kind: 'invocation',
718
+ type: 'resume',
719
+ employeeUsername: resume.username,
720
+ sessionId: resume.sessionId,
721
+ title: `${resume.role} resume after approval`,
722
+ inputHash: inputHash(decisions),
723
+ status: 'running',
724
+ startedAt: new Date(),
725
+ createdAt: new Date(),
726
+ },
727
+ });
728
+
729
+ const outcome = await this.runtime.resume({
730
+ username: resume.username,
731
+ sessionId: resume.sessionId,
732
+ messageId: resume.messageId,
733
+ userId: snapshot.userId,
734
+ systemMessage: resume.role === 'leader' ? LEADER_SYSTEM_MESSAGE : MAKER_SYSTEM_MESSAGE,
735
+ harness,
736
+ decisions,
737
+ signal,
738
+ });
739
+
740
+ const stepId = read(step, 'id');
741
+ if (typeof stepId !== 'string' && typeof stepId !== 'number') throw new Error('Resume step has no identifier.');
742
+ await this.tokenTracker.trackLoopInvocationUsage({
743
+ runId: snapshot.id,
744
+ rootRunId: snapshot.rootRunId,
745
+ stepId,
746
+ sessionId: outcome.sessionId,
747
+ messageId: outcome.messageId,
748
+ usage: outcome.tokenUsage,
749
+ input: resume.role === 'leader' ? LEADER_SYSTEM_MESSAGE : MAKER_SYSTEM_MESSAGE,
750
+ output: outcome.content,
751
+ role: resume.role,
752
+ employeeUsername: resume.username,
753
+ userId: snapshot.userId,
754
+ });
755
+
756
+ await this.database.getRepository('agentLoopSteps').update({
757
+ filterByTk: stepId,
758
+ values: {
759
+ status: outcome.interrupted.length ? 'waiting_user' : 'succeeded',
760
+ output: { content: outcome.content },
761
+ endedAt: new Date(),
762
+ },
763
+ });
764
+ await this.database.getRepository('agentLoopRuns').update({
765
+ filterByTk: snapshot.id,
766
+ values: { sessionId: outcome.sessionId, messageId: outcome.messageId },
767
+ });
768
+ return outcome;
769
+ }
770
+
771
+ // Run-level scan over every tool call issued so far, evaluated at each pass boundary. A warning
772
+ // is injected into the prompts composed later in the run; block and escalate halt it at once.
773
+ private async enforceToolLoopGuard(
774
+ snapshot: RunSnapshot,
775
+ leaseToken: string,
776
+ pass: { role: 'leader' | 'maker'; username: string },
777
+ loopNotices: string[],
778
+ ): Promise<'continue' | 'halt'> {
779
+ const finding = await this.loopGuard.scanRun(snapshot.id, snapshot.policy);
780
+ if (!finding) return 'continue';
781
+
782
+ await this.loopGuard.recordFinding(
783
+ {
784
+ runId: snapshot.id,
785
+ role: pass.role,
786
+ username: pass.username,
787
+ runStatus: 'running',
788
+ actorType: 'worker',
789
+ actorIdentity: this.workerId,
790
+ },
791
+ finding,
792
+ );
793
+
794
+ if (finding.level === 'warn') {
795
+ const notice = toolLoopNotice(finding.toolName, finding.count);
796
+ if (!loopNotices.includes(notice)) loopNotices.push(notice);
797
+ return 'continue';
798
+ }
799
+
800
+ const reason = toolLoopReason(finding);
801
+ await this.stateMachine.transition({
802
+ runId: snapshot.id,
803
+ to: finding.level === 'block' ? 'blocked' : 'waiting_human',
804
+ actorType: 'worker',
805
+ actorIdentity: this.workerId,
806
+ leaseToken,
807
+ eventType: finding.level === 'block' ? 'run_blocked' : 'run_escalated',
808
+ title: finding.level === 'block' ? 'Run blocked by tool loop detection' : 'Run escalated by tool loop detection',
809
+ content: reason,
810
+ correlationKey: `tool-loop-${finding.level}:${snapshot.id}:${finding.signature}`,
811
+ values: finding.level === 'block' ? { blockedReason: reason } : { escalationReason: reason },
812
+ });
813
+ return 'halt';
814
+ }
815
+
816
+ // Decisions are consumed exactly once: rows are marked consumed so a retry or a second resume
817
+ // can never replay a human decision against a fresh conversation.
818
+ private async consumeDecisions(runId: number) {
819
+ const repository = this.database.getRepository('agentLoopActionApprovals');
820
+ const approvals = await repository.find({ filter: { runId } });
821
+ const decisions: Array<{ toolCallId: string; decision: ToolCallDecision }> = [];
822
+ const now = new Date();
823
+ for (const approval of approvals) {
824
+ const status = String(read(approval, 'status'));
825
+ if (status !== 'approved' && status !== 'rejected') continue;
826
+ if (read(approval, 'consumedAt')) continue;
827
+ const editedInput = read(approval, 'editedInput');
828
+ const decision: ToolCallDecision =
829
+ status === 'approved'
830
+ ? editedInput
831
+ ? { type: 'edit', editedAction: { name: String(read(approval, 'toolName')), args: editedInput } }
832
+ : { type: 'approve' }
833
+ : { type: 'reject', message: String(read(approval, 'decisionNote') || '') || undefined };
834
+ decisions.push({ toolCallId: String(read(approval, 'toolCallId')), decision });
835
+ await repository.update({ filterByTk: Number(read(approval, 'id')), values: { consumedAt: now } });
836
+ }
837
+ if (!decisions.length) throw new Error('The resumed run has no recorded approval decisions.');
838
+ return decisions;
839
+ }
840
+
841
+ private async parkForApproval(
842
+ snapshot: RunSnapshot,
843
+ outcome: InvocationOutcome,
844
+ leaseToken: string,
845
+ context: { role: 'leader' | 'maker'; username: string; makerReports: string[]; makerQueue: string[] },
846
+ ) {
847
+ const now = new Date();
848
+ const expiresAt = new Date(now.getTime() + snapshot.policy.actions.approvalTimeoutMs);
849
+ const assignedToId = snapshot.policy.actions.approvalAssigneeIds[0] || snapshot.userId || null;
850
+ const harness =
851
+ context.role === 'leader' ? snapshot.leaderHarness : snapshot.makerHarnesses[context.username]?.effective;
852
+ const escalatable = new Set(harness?.tools.escalate ?? []);
853
+ for (const call of outcome.interrupted) {
854
+ // An escalation is a request for authority the harness never granted, widened for exactly
855
+ // one call; a plain tool_call approval gates a tool the harness allows but asks about.
856
+ const escalation = escalatable.has(call.toolName);
857
+ await this.database.getRepository('agentLoopActionApprovals').create({
858
+ values: {
859
+ runId: snapshot.id,
860
+ toolCallId: call.toolCallId,
861
+ toolName: call.toolName,
862
+ actionType: escalation ? 'escalation' : 'tool_call',
863
+ proposedInput: call.args,
864
+ inputHash: inputHash(call.args),
865
+ paths: snapshot.actingOn,
866
+ policyDecision: { decision: 'ask', interruptId: call.interruptId },
867
+ reason: escalation
868
+ ? `Tool "${call.toolName}" is not granted by this run's harness. Approving widens authority for this single call only.`
869
+ : `Tool "${call.toolName}" requires human approval under this pattern's policy.`,
870
+ status: 'pending',
871
+ assignedToId,
872
+ requestedById: snapshot.userId || null,
873
+ requestedAt: now,
874
+ expiresAt,
875
+ createdAt: now,
876
+ },
877
+ });
878
+ }
879
+ await this.database.getRepository('agentLoopRuns').update({
880
+ filterByTk: snapshot.id,
881
+ values: {
882
+ // The resume point is durable: which role stopped, in which conversation, with which
883
+ // reports already collected and which makers still queued. Without it a resumed run
884
+ // would restart from the leader and redo every completed invocation.
885
+ resumeContext: {
886
+ role: context.role,
887
+ username: context.username,
888
+ sessionId: outcome.sessionId,
889
+ messageId: outcome.messageId,
890
+ makerReports: context.makerReports,
891
+ makerQueue: context.makerQueue,
892
+ },
893
+ },
894
+ });
895
+ await this.stateMachine.transition({
896
+ runId: snapshot.id,
897
+ to: 'waiting_approval',
898
+ actorType: 'worker',
899
+ actorIdentity: this.workerId,
900
+ leaseToken,
901
+ eventType: 'run_waiting_approval',
902
+ title: 'Waiting for action approval',
903
+ content: `${outcome.interrupted.length} tool call(s) require approval.`,
904
+ correlationKey: `approval:${snapshot.id}:${outcome.messageId}`,
905
+ values: { approvalStatus: 'pending', messageId: outcome.messageId },
906
+ });
907
+ }
908
+
909
+ private async failRun(runId: number, leaseToken: string, snapshot: RunSnapshot | null, error: unknown) {
910
+ const message = error instanceof Error ? error.message : String(error);
911
+ try {
912
+ if (snapshot) {
913
+ await this.circuits.recordFailure({
914
+ patternId: snapshot.patternId,
915
+ scopeKey: `pattern:${snapshot.patternId}`,
916
+ policy: snapshot.policy.circuit,
917
+ error,
918
+ lastRunId: runId,
919
+ });
920
+ }
921
+ await this.stateMachine.transition({
922
+ runId,
923
+ to: 'failed',
924
+ actorType: 'worker',
925
+ actorIdentity: this.workerId,
926
+ leaseToken,
927
+ eventType: 'run_failed',
928
+ title: 'Run failed',
929
+ content: message,
930
+ correlationKey: `failed:${runId}`,
931
+ values: { summary: message },
932
+ });
933
+ } catch (transitionError) {
934
+ this.app.logger.error(`[AgentOrchestrator] Loop run ${runId} could not be marked failed.`, {
935
+ error: transitionError,
936
+ cause: message,
937
+ });
938
+ }
939
+ }
940
+
941
+ private async nextSequence(runId: number) {
942
+ return this.database.getRepository('agentLoopSteps').count({ filter: { runId } });
943
+ }
944
+
945
+ private snapshotFrom(run: Record<string, unknown>): RunSnapshot {
946
+ const patternId = Number(run.patternId);
947
+ if (!Number.isSafeInteger(patternId) || patternId <= 0) {
948
+ throw new Error('The claimed run has no pattern snapshot.');
949
+ }
950
+ const roleBindings = asObject(run.roleBindingsSnapshot);
951
+ const makerSnapshots = asObject(run.makerHarnessSnapshot);
952
+ const approvalStatus = String(run.approvalStatus || 'none');
953
+ const recoveryContext = asObject(run.resumeContext);
954
+ const verificationRecoverySummary =
955
+ recoveryContext.kind === 'verification_lease_recovery' &&
956
+ typeof recoveryContext.makerSummary === 'string' &&
957
+ recoveryContext.makerSummary.trim()
958
+ ? recoveryContext.makerSummary
959
+ : null;
960
+ return {
961
+ id: Number(run.id),
962
+ rootRunId: String(run.rootRunId || ''),
963
+ patternId,
964
+ goal: String(run.goal || ''),
965
+ autonomyLevel: autonomyLevel(run.autonomyLevel),
966
+ policy: loopPatternPolicySchema.parse(run.policySnapshot),
967
+ leaderUsername: String(roleBindings.leader || run.leaderUsername || ''),
968
+ makerUsernames: asStringArray(roleBindings.makers),
969
+ verifierUsername: String(roleBindings.verifier || run.verifierUsername || ''),
970
+ leaderHarness: harnessFrom(run.leaderHarnessSnapshot),
971
+ makerHarnesses: makerSnapshots as Record<string, { effective: CompiledHarness }>,
972
+ verifierHarness: harnessFrom(run.verifierHarnessSnapshot),
973
+ repositoryKey: String(run.repositoryKey || ''),
974
+ actingOn: asStringArray(run.actingOn),
975
+ userId: Number(run.userId) || undefined,
976
+ approvalStatus,
977
+ verificationRecoverySummary,
978
+ // Only a live approval state may resume. Stale context left over from an expired window or a
979
+ // cleared retry would otherwise replay an old conversation against fresh approvals.
980
+ resumeContext:
981
+ !verificationRecoverySummary && (approvalStatus === 'decided' || approvalStatus === 'pending')
982
+ ? resumeContextFrom(run.resumeContext)
983
+ : null,
984
+ };
985
+ }
986
+ }