plugin-agent-orchestrator 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/253.59577b40d9875be0.js +10 -0
  6. package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
  7. package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
  8. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  9. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  10. package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
  11. package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
  12. package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
  13. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  14. package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
  15. package/dist/client-v2/index.js +1 -1
  16. package/dist/externalVersion.js +8 -7
  17. package/dist/locale/en-US.json +199 -123
  18. package/dist/locale/vi-VN.json +199 -123
  19. package/dist/locale/zh-CN.json +199 -123
  20. package/dist/server/collections/agent-execution-spans.js +55 -0
  21. package/dist/server/collections/agent-harness-profile-versions.js +56 -0
  22. package/dist/server/collections/agent-harness-profiles.js +12 -0
  23. package/dist/server/collections/agent-loop-action-approvals.js +69 -0
  24. package/dist/server/collections/agent-loop-artifacts.js +55 -0
  25. package/dist/server/collections/agent-loop-circuit-states.js +53 -0
  26. package/dist/server/collections/agent-loop-control-settings.js +51 -0
  27. package/dist/server/collections/agent-loop-events.js +27 -0
  28. package/dist/server/collections/agent-loop-path-locks.js +57 -0
  29. package/dist/server/collections/agent-loop-patterns.js +72 -0
  30. package/dist/server/collections/agent-loop-runs.js +170 -3
  31. package/dist/server/collections/agent-loop-steps.js +76 -0
  32. package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
  33. package/dist/server/collections/agent-loop-worktrees.js +55 -0
  34. package/dist/server/collections/skill-executions.js +8 -0
  35. package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
  36. package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
  37. package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
  38. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
  39. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
  40. package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
  41. package/dist/server/plugin.js +54 -150
  42. package/dist/server/resources/agent-harness-profile.js +117 -0
  43. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  44. package/dist/server/resources/agent-loop-approval.js +108 -0
  45. package/dist/server/resources/agent-loop-artifact.js +86 -0
  46. package/dist/server/resources/agent-loop-events-stream.js +130 -0
  47. package/dist/server/resources/agent-loop.js +183 -139
  48. package/dist/server/resources/resource-helpers.js +63 -0
  49. package/dist/server/resources/tracing.js +121 -107
  50. package/dist/server/services/AgentMemoryContextService.js +34 -0
  51. package/dist/server/services/DurableCircuitBreakerService.js +229 -0
  52. package/dist/server/services/HarnessCompiler.js +175 -0
  53. package/dist/server/services/HarnessProfileService.js +233 -0
  54. package/dist/server/services/HarnessSchema.js +194 -0
  55. package/dist/server/services/LoopBudgetService.js +269 -0
  56. package/dist/server/services/LoopControlService.js +139 -0
  57. package/dist/server/services/LoopPatternSchema.js +195 -0
  58. package/dist/server/services/LoopPatternService.js +132 -0
  59. package/dist/server/services/LoopRunRepository.js +285 -0
  60. package/dist/server/services/LoopRunStateMachine.js +478 -0
  61. package/dist/server/services/LoopSchedulerService.js +193 -0
  62. package/dist/server/services/LoopTriggerService.js +165 -0
  63. package/dist/server/services/LoopWorkerService.js +699 -0
  64. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  65. package/dist/server/services/PathLockService.js +288 -0
  66. package/dist/server/services/PluginAiRuntimeAdapter.js +226 -0
  67. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  68. package/dist/server/services/VerificationSchema.js +59 -0
  69. package/dist/server/services/VerificationService.js +235 -0
  70. package/dist/server/services/harness-runtime-policy.js +139 -0
  71. package/dist/server/skill-hub/actions/git-import.js +13 -7
  72. package/dist/server/skill-hub/plugin.js +36 -3
  73. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
  74. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  75. package/dist/server/utils/ensure-indexes.js +111 -0
  76. package/dist/server/utils/loop-pattern-context.js +56 -0
  77. package/package.json +53 -53
  78. package/src/client/ApprovalsTab.tsx +2 -0
  79. package/src/client/OrchestratorSettings.tsx +55 -0
  80. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  81. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  82. package/src/client/skill-hub/index.tsx +0 -52
  83. package/src/client-v2/components/AgentRunsTab.tsx +100 -18
  84. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  85. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -100
  86. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -125
  87. package/src/client-v2/components/TracingTab.tsx +160 -77
  88. package/src/client-v2/hooks/useApiRequest.ts +28 -8
  89. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  90. package/src/client-v2/plugin.tsx +6 -6
  91. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +11 -6
  92. package/src/locale/en-US.json +199 -123
  93. package/src/locale/vi-VN.json +199 -123
  94. package/src/locale/zh-CN.json +199 -123
  95. package/src/server/__tests__/circuit-breaker.test.ts +248 -169
  96. package/src/server/__tests__/harness-compiler.test.ts +214 -0
  97. package/src/server/__tests__/harness-profile-service.test.ts +167 -0
  98. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  99. package/src/server/__tests__/harness-tool-plan.test.ts +172 -0
  100. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  101. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  102. package/src/server/__tests__/loop-budget-service.test.ts +255 -0
  103. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
  104. package/src/server/__tests__/loop-pattern-schema.test.ts +73 -0
  105. package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
  106. package/src/server/__tests__/loop-run-state-machine.test.ts +101 -0
  107. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  108. package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
  109. package/src/server/__tests__/loop-worker-execution.test.ts +317 -0
  110. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  111. package/src/server/__tests__/path-lock-service.test.ts +254 -0
  112. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  113. package/src/server/__tests__/smoke.test.ts +162 -121
  114. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  115. package/src/server/collections/agent-execution-spans.ts +55 -0
  116. package/src/server/collections/agent-harness-profile-versions.ts +26 -0
  117. package/src/server/collections/agent-harness-profiles.ts +71 -59
  118. package/src/server/collections/agent-loop-action-approvals.ts +39 -0
  119. package/src/server/collections/agent-loop-artifacts.ts +25 -0
  120. package/src/server/collections/agent-loop-circuit-states.ts +23 -0
  121. package/src/server/collections/agent-loop-control-settings.ts +21 -0
  122. package/src/server/collections/agent-loop-events.ts +98 -71
  123. package/src/server/collections/agent-loop-path-locks.ts +27 -0
  124. package/src/server/collections/agent-loop-patterns.ts +42 -0
  125. package/src/server/collections/agent-loop-runs.ts +170 -3
  126. package/src/server/collections/agent-loop-steps.ts +76 -0
  127. package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
  128. package/src/server/collections/agent-loop-worktrees.ts +25 -0
  129. package/src/server/collections/skill-executions.ts +8 -0
  130. package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +52 -49
  131. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -46
  132. package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +45 -38
  133. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -32
  134. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -30
  135. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
  136. package/src/server/plugin.ts +55 -167
  137. package/src/server/resources/agent-harness-profile.ts +94 -0
  138. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  139. package/src/server/resources/agent-loop-approval.ts +84 -0
  140. package/src/server/resources/agent-loop-artifact.ts +56 -0
  141. package/src/server/resources/agent-loop-events-stream.ts +105 -0
  142. package/src/server/resources/agent-loop.ts +204 -143
  143. package/src/server/resources/agent-monitor.ts +482 -482
  144. package/src/server/resources/resource-helpers.ts +33 -0
  145. package/src/server/resources/tracing.ts +266 -258
  146. package/src/server/services/AgentMemoryContextService.ts +44 -0
  147. package/src/server/services/DurableCircuitBreakerService.ts +239 -0
  148. package/src/server/services/ExecutionSpanService.ts +2 -0
  149. package/src/server/services/HarnessCompiler.ts +170 -0
  150. package/src/server/services/HarnessProfileService.ts +239 -0
  151. package/src/server/services/HarnessSchema.ts +194 -0
  152. package/src/server/services/LoopBudgetService.ts +275 -0
  153. package/src/server/services/LoopControlService.ts +124 -0
  154. package/src/server/services/LoopPatternSchema.ts +185 -0
  155. package/src/server/services/LoopPatternService.ts +143 -0
  156. package/src/server/services/LoopRunRepository.ts +336 -0
  157. package/src/server/services/LoopRunStateMachine.ts +529 -0
  158. package/src/server/services/LoopSchedulerService.ts +199 -0
  159. package/src/server/services/LoopTriggerService.ts +157 -0
  160. package/src/server/services/LoopWorkerService.ts +822 -0
  161. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  162. package/src/server/services/PathLockService.ts +321 -0
  163. package/src/server/services/PluginAiRuntimeAdapter.ts +332 -0
  164. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  165. package/src/server/services/VerificationSchema.ts +31 -0
  166. package/src/server/services/VerificationService.ts +264 -0
  167. package/src/server/services/harness-runtime-policy.ts +141 -0
  168. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +15 -1
  169. package/src/server/skill-hub/actions/git-import.ts +9 -3
  170. package/src/server/skill-hub/plugin.ts +41 -3
  171. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -239
  172. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -63
  173. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  174. package/src/server/utils/ensure-indexes.ts +96 -0
  175. package/src/server/utils/logging.ts +62 -63
  176. package/src/server/utils/loop-pattern-context.ts +20 -0
  177. package/dist/client-v2/214.79650a549273f163.js +0 -10
  178. package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
  179. package/dist/client-v2/264.718a107e43fc163c.js +0 -10
  180. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  181. package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
  182. package/dist/client-v2/53.7c29c28043e9112d.js +0 -10
  183. package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
  184. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  185. package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
  186. package/dist/server/services/AgentHarness.js +0 -81
  187. package/dist/server/services/AgentLoopController.js +0 -1023
  188. package/dist/server/services/AgentLoopRepository.js +0 -192
  189. package/dist/server/services/AgentLoopService.js +0 -142
  190. package/dist/server/services/AgentPlanValidator.js +0 -99
  191. package/dist/server/services/AgentPlannerService.js +0 -99
  192. package/dist/server/services/CircuitBreaker.js +0 -125
  193. package/dist/server/services/ContextAggregator.js +0 -201
  194. package/dist/server/services/PlanningPromptService.js +0 -95
  195. package/dist/server/tools/agent-loop.js +0 -373
  196. package/dist/server/tools/orchestrator-plan.js +0 -254
  197. package/src/client/AIEmployeeSelect.tsx +0 -47
  198. package/src/client/AIEmployeesContext.tsx +0 -102
  199. package/src/client/RulesTab.tsx +0 -2
  200. package/src/client/TracingTab.tsx +0 -436
  201. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  202. package/src/client-v2/components/RulesTab.tsx +0 -2
  203. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
  204. package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
  205. package/src/server/__tests__/context-aggregator.test.ts +0 -222
  206. package/src/server/__tests__/parallel-execution.test.ts +0 -318
  207. package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
  208. package/src/server/services/AgentHarness.ts +0 -67
  209. package/src/server/services/AgentLoopController.ts +0 -1263
  210. package/src/server/services/AgentLoopRepository.ts +0 -178
  211. package/src/server/services/AgentLoopService.ts +0 -177
  212. package/src/server/services/AgentPlanValidator.ts +0 -73
  213. package/src/server/services/AgentPlannerService.ts +0 -80
  214. package/src/server/services/CircuitBreaker.ts +0 -126
  215. package/src/server/services/ContextAggregator.ts +0 -239
  216. package/src/server/services/PlanningPromptService.ts +0 -72
  217. package/src/server/tools/agent-loop.ts +0 -360
  218. package/src/server/tools/orchestrator-plan.ts +0 -255
@@ -1,1023 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __defProp = Object.defineProperty;
11
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
- var __getOwnPropNames = Object.getOwnPropertyNames;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __export = (target, all) => {
15
- for (var name in all)
16
- __defProp(target, name, { get: all[name], enumerable: true });
17
- };
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
- var AgentLoopController_exports = {};
28
- __export(AgentLoopController_exports, {
29
- AgentLoopController: () => AgentLoopController
30
- });
31
- module.exports = __toCommonJS(AgentLoopController_exports);
32
- var import_CircuitBreaker = require("./CircuitBreaker");
33
- var import_crypto = require("crypto");
34
- var import_ctx_utils = require("../utils/ctx-utils");
35
- const DEFAULT_POLICY = {
36
- maxIterations: 20,
37
- maxStepAttempts: 2,
38
- allowReplan: true,
39
- requireVerification: true,
40
- stopOnApprovalRequired: true,
41
- maxContextTokens: 4e3,
42
- contextSummaryStrategy: "last_n",
43
- includeToolResults: false,
44
- includeStepOutputs: true,
45
- maxConcurrency: 5
46
- };
47
- const TERMINAL_RUN_STATUSES = /* @__PURE__ */ new Set(["succeeded", "failed", "rejected", "canceled"]);
48
- const TERMINAL_STEP_STATUSES = /* @__PURE__ */ new Set(["succeeded", "skipped"]);
49
- const ORCHESTRATOR_CONTROLLER_MAX_STEPS = 100;
50
- function now() {
51
- return /* @__PURE__ */ new Date();
52
- }
53
- function createRootRunId(seed = "") {
54
- const hash = (0, import_crypto.createHash)("sha1").update(`${Date.now()}::${Math.random()}::${seed}`).digest("hex").slice(0, 10);
55
- return `loop_${Date.now()}_${hash}`;
56
- }
57
- function normalizePolicy(policy) {
58
- const next = { ...DEFAULT_POLICY, ...policy || {} };
59
- next.maxIterations = Math.max(1, Number(next.maxIterations || DEFAULT_POLICY.maxIterations));
60
- next.maxStepAttempts = Math.max(1, Number(next.maxStepAttempts || DEFAULT_POLICY.maxStepAttempts));
61
- next.allowReplan = next.allowReplan !== false;
62
- next.requireVerification = next.requireVerification !== false;
63
- next.stopOnApprovalRequired = next.stopOnApprovalRequired !== false;
64
- next.maxContextTokens = next.maxContextTokens || DEFAULT_POLICY.maxContextTokens;
65
- next.contextSummaryStrategy = next.contextSummaryStrategy || DEFAULT_POLICY.contextSummaryStrategy;
66
- next.includeToolResults = next.includeToolResults !== false;
67
- next.includeStepOutputs = next.includeStepOutputs !== false;
68
- next.maxConcurrency = Math.max(1, Number(next.maxConcurrency || DEFAULT_POLICY.maxConcurrency));
69
- return next;
70
- }
71
- class AgentLoopController {
72
- constructor(registryService, plannerService, validator, repository, harness, tokenTracker = null) {
73
- this.registryService = registryService;
74
- this.plannerService = plannerService;
75
- this.validator = validator;
76
- this.repository = repository;
77
- this.harness = harness;
78
- this.tokenTracker = tokenTracker;
79
- }
80
- async createRun(options) {
81
- const goal = String(options.goal || "").trim();
82
- if (!goal) {
83
- throw new Error("Agent loop goal is required.");
84
- }
85
- const policy = normalizePolicy(options.policy);
86
- const rootRunId = createRootRunId(options.leaderUsername || goal);
87
- const run = await this.repository.createRun({
88
- rootRunId,
89
- sessionId: options.sessionId,
90
- messageId: options.messageId,
91
- leaderUsername: options.leaderUsername,
92
- goal,
93
- status: "planning",
94
- policy,
95
- iterationCount: 0,
96
- metadata: options.metadata || {},
97
- userId: options.userId,
98
- startedAt: now()
99
- });
100
- await this.repository.createEvent({
101
- runId: run.id,
102
- type: "created",
103
- title: "Agent loop created",
104
- content: goal,
105
- status: "planning",
106
- userId: options.userId,
107
- payload: { rootRunId }
108
- });
109
- if (Array.isArray(options.plan) && options.plan.length > 0) {
110
- this.validator.validate(options.plan);
111
- await this.replacePlan(run.id, options.plan, {
112
- userId: options.userId,
113
- mode: "append",
114
- markRunning: true
115
- });
116
- }
117
- return this.getRunSnapshot(run.id);
118
- }
119
- async planGoal(options) {
120
- var _a;
121
- const plan = this.plannerService.buildPlan(options.goal, options.plan, options);
122
- this.validator.validate(plan);
123
- const harnessTag = String(options.harnessTag || ((_a = options.metadata) == null ? void 0 : _a.harnessTag) || "default").trim() || "default";
124
- const harnessProfile = await this.registryService.getHarnessProfile(harnessTag);
125
- const harnessSettings = (0, import_ctx_utils.asObject)(harnessProfile == null ? void 0 : harnessProfile.settings);
126
- if (options.runId) {
127
- return this.revisePlanGoal(options.runId, plan, {
128
- goal: options.goal,
129
- userId: options.userId,
130
- metadata: options.metadata,
131
- planSource: options.planSource || (Array.isArray(options.plan) && options.plan.length ? "provided" : "template"),
132
- plannerModel: options.plannerModel,
133
- harnessTag,
134
- harnessProfileId: harnessProfile == null ? void 0 : harnessProfile.id,
135
- harnessSettings
136
- });
137
- }
138
- const snapshot = await this.createRun({
139
- goal: options.goal,
140
- leaderUsername: options.leaderUsername,
141
- sessionId: options.sessionId,
142
- messageId: options.messageId,
143
- userId: options.userId,
144
- policy: options.policy,
145
- metadata: {
146
- ...(0, import_ctx_utils.asObject)(options.metadata),
147
- harnessTag,
148
- harnessProfileId: harnessProfile == null ? void 0 : harnessProfile.id,
149
- harnessSettings,
150
- approvalMode: "plan_first"
151
- },
152
- plan: []
153
- });
154
- const runId = snapshot.run.id;
155
- await this.replacePlan(runId, plan, {
156
- userId: options.userId,
157
- mode: "append",
158
- markRunning: false
159
- });
160
- await this.repository.updateRun(runId, {
161
- status: "waiting_plan_approval",
162
- approvalStatus: "pending",
163
- planVersion: 1,
164
- planSource: options.planSource || (Array.isArray(options.plan) && options.plan.length ? "provided" : "template"),
165
- plannerModel: options.plannerModel || "",
166
- updatedAt: now()
167
- });
168
- await this.repository.createEvent({
169
- runId,
170
- type: "plan_approval_requested",
171
- title: "Plan approval requested",
172
- content: `Waiting for user approval before executing ${plan.length} step(s).`,
173
- status: "waiting_plan_approval",
174
- userId: options.userId,
175
- payload: {
176
- planVersion: 1,
177
- harnessTag,
178
- steps: plan.map((step, index) => ({
179
- planKey: (0, import_ctx_utils.normalizePlanKey)(step, index),
180
- title: step.title || `Step ${index + 1}`,
181
- type: (0, import_ctx_utils.normalizeStepType)(step.type),
182
- target: step.target || "",
183
- dependsOn: (0, import_ctx_utils.asArray)(step.dependsOn).map(String)
184
- }))
185
- }
186
- });
187
- return this.getRunDetail(runId);
188
- }
189
- async revisePlanGoal(runId, plan, options = {}) {
190
- this.validator.validate(plan);
191
- const run = await this.repository.requireRun(runId);
192
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
193
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
194
- }
195
- if (!["waiting_plan_approval", "needs_replan"].includes(run.status)) {
196
- throw new Error(`Run ${run.id} is not waiting for plan revision.`);
197
- }
198
- await this.replacePlan(run.id, plan, {
199
- userId: options.userId,
200
- mode: "replace_pending",
201
- reason: "Plan revised",
202
- markRunning: false
203
- });
204
- const nextPlanVersion = Number(run.planVersion || 1) + 1;
205
- await this.repository.updateRun(run.id, {
206
- goal: options.goal || run.goal,
207
- status: "waiting_plan_approval",
208
- approvalStatus: "pending",
209
- planVersion: nextPlanVersion,
210
- planSource: options.planSource || run.planSource || "provided",
211
- plannerModel: options.plannerModel || run.plannerModel || "",
212
- rejectionReason: "",
213
- changeRequest: "",
214
- metadata: {
215
- ...(0, import_ctx_utils.asObject)(run.metadata),
216
- ...(0, import_ctx_utils.asObject)(options.metadata),
217
- harnessTag: options.harnessTag || (0, import_ctx_utils.asObject)(run.metadata).harnessTag || "default",
218
- harnessProfileId: options.harnessProfileId || (0, import_ctx_utils.asObject)(run.metadata).harnessProfileId,
219
- harnessSettings: (0, import_ctx_utils.asObject)(options.harnessSettings || (0, import_ctx_utils.asObject)(run.metadata).harnessSettings),
220
- approvalMode: "plan_first"
221
- },
222
- updatedAt: now()
223
- });
224
- await this.repository.createEvent({
225
- runId: run.id,
226
- type: "plan_revision_requested",
227
- title: "Plan revised for approval",
228
- content: `Waiting for approval of plan version ${nextPlanVersion}.`,
229
- status: "waiting_plan_approval",
230
- userId: options.userId,
231
- payload: {
232
- planVersion: nextPlanVersion,
233
- steps: plan.map((step, index) => (0, import_ctx_utils.normalizePlanKey)(step, index))
234
- }
235
- });
236
- return this.getRunDetail(run.id);
237
- }
238
- async approvePlan(runId, options = {}) {
239
- const run = await this.repository.requireRun(runId);
240
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
241
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
242
- }
243
- if (!["waiting_plan_approval", "approved", "needs_replan"].includes(run.status)) {
244
- throw new Error(`Run ${run.id} is not waiting for plan approval.`);
245
- }
246
- await this.repository.updateRun(run.id, {
247
- status: "approved",
248
- approvalStatus: "approved",
249
- approvedById: options.userId,
250
- approvedAt: now(),
251
- rejectionReason: "",
252
- changeRequest: "",
253
- updatedAt: now()
254
- });
255
- await this.repository.createEvent({
256
- runId: run.id,
257
- type: "plan_approved",
258
- title: "Plan approved",
259
- content: options.reason || "",
260
- status: "approved",
261
- userId: options.userId,
262
- payload: { planVersion: run.planVersion || 1 }
263
- });
264
- return this.getRunDetail(run.id);
265
- }
266
- /**
267
- * @deprecated Use approvePlan() instead. Auto-execution via AgentHarness is retired;
268
- * step execution is now driven by the AI via agent_loop_update_step tools.
269
- */
270
- async approvePlanAndExecute(runId, options = {}) {
271
- const run = await this.repository.requireRun(runId);
272
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
273
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
274
- }
275
- if (!["waiting_plan_approval", "approved"].includes(run.status)) {
276
- throw new Error(`Run ${run.id} is not waiting for plan approval.`);
277
- }
278
- await this.repository.updateRun(run.id, {
279
- status: "approved",
280
- approvalStatus: "approved",
281
- approvedById: options.userId,
282
- approvedAt: now(),
283
- rejectionReason: "",
284
- changeRequest: "",
285
- updatedAt: now()
286
- });
287
- await this.repository.createEvent({
288
- runId: run.id,
289
- type: "plan_approved",
290
- title: "Plan approved",
291
- content: options.reason || "",
292
- status: "approved",
293
- userId: options.userId,
294
- payload: { planVersion: run.planVersion || 1 }
295
- });
296
- return this.executeApprovedPlan(run.id, options);
297
- }
298
- async rejectPlan(runId, options = {}) {
299
- const run = await this.repository.requireRun(runId);
300
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
301
- return this.getRunSnapshot(run.id);
302
- }
303
- if (!["waiting_plan_approval", "approved", "needs_replan"].includes(run.status)) {
304
- throw new Error(`Run ${run.id} is not waiting for plan approval.`);
305
- }
306
- const steps = await this.repository.getSteps(run.id);
307
- for (const step of steps) {
308
- if (!TERMINAL_STEP_STATUSES.has(step.status) && step.status !== "failed") {
309
- await this.repository.updateStep(step.id, {
310
- status: "skipped",
311
- error: options.reason || "Plan rejected by user.",
312
- endedAt: now(),
313
- updatedAt: now()
314
- });
315
- }
316
- }
317
- await this.repository.updateRun(run.id, {
318
- status: "rejected",
319
- approvalStatus: "rejected",
320
- rejectionReason: options.reason || "",
321
- currentStepId: null,
322
- endedAt: now(),
323
- updatedAt: now()
324
- });
325
- await this.repository.createEvent({
326
- runId: run.id,
327
- type: "plan_rejected",
328
- title: "Plan rejected",
329
- content: options.reason || "",
330
- status: "rejected",
331
- userId: options.userId
332
- });
333
- return this.getRunSnapshot(run.id);
334
- }
335
- async requestPlanChanges(runId, options = {}) {
336
- const run = await this.repository.requireRun(runId);
337
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
338
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
339
- }
340
- if (!["waiting_plan_approval", "needs_replan"].includes(run.status)) {
341
- throw new Error(`Run ${run.id} is not waiting for plan changes.`);
342
- }
343
- await this.repository.updateRun(run.id, {
344
- status: "needs_replan",
345
- approvalStatus: "changes_requested",
346
- changeRequest: options.feedback || "",
347
- updatedAt: now()
348
- });
349
- await this.repository.createEvent({
350
- runId: run.id,
351
- type: "plan_changes_requested",
352
- title: "Plan changes requested",
353
- content: options.feedback || "",
354
- status: "needs_replan",
355
- userId: options.userId
356
- });
357
- return this.getRunDetail(run.id);
358
- }
359
- async replacePlan(runId, plan, options = {}) {
360
- var _a;
361
- if (!Array.isArray(plan) || plan.length === 0) {
362
- throw new Error("Plan must include at least one step.");
363
- }
364
- this.validator.validate(plan);
365
- const run = await this.repository.requireRun(runId);
366
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
367
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
368
- }
369
- const policy = normalizePolicy(run.policy);
370
- if (options.mode === "replace_pending") {
371
- const existing = await this.repository.getSteps(run.id);
372
- for (const step of existing) {
373
- if (!TERMINAL_STEP_STATUSES.has(step.status) && step.status !== "running") {
374
- await this.repository.updateStep(step.id, {
375
- status: "skipped",
376
- error: options.reason || "Replanned",
377
- endedAt: now()
378
- });
379
- }
380
- }
381
- }
382
- const existingSteps = await this.repository.getSteps(run.id);
383
- const indexStart = existingSteps.reduce((max, step) => Math.max(max, Number(step.index || 0)), -1) + 1;
384
- const createdSteps = [];
385
- for (let i = 0; i < plan.length; i++) {
386
- const step = plan[i] || {};
387
- const created = await this.repository.createStep({
388
- runId: run.id,
389
- parentStepId: step.parentStepId,
390
- planKey: (0, import_ctx_utils.normalizePlanKey)(step, i),
391
- index: indexStart + i,
392
- title: step.title || `Step ${indexStart + i + 1}`,
393
- description: step.description || "",
394
- type: (0, import_ctx_utils.normalizeStepType)(step.type),
395
- target: step.target || "",
396
- input: step.input || {},
397
- output: {},
398
- status: "pending",
399
- attempt: 0,
400
- maxAttempts: step.maxAttempts || policy.maxStepAttempts,
401
- dependsOn: (0, import_ctx_utils.asArray)(step.dependsOn).map(String),
402
- dependencyPolicy: step.dependencyPolicy || ((_a = step.metadata) == null ? void 0 : _a.dependencyPolicy) || "require_success",
403
- metadata: (0, import_ctx_utils.asObject)(step.metadata)
404
- });
405
- createdSteps.push(created);
406
- }
407
- const nextStatus = options.markRunning === false ? run.status : "running";
408
- await this.repository.updateRun(run.id, {
409
- status: nextStatus,
410
- updatedAt: now()
411
- });
412
- await this.repository.createEvent({
413
- runId: run.id,
414
- type: options.reason ? "replanned" : "planned",
415
- title: options.reason ? "Plan updated" : "Plan created",
416
- content: options.reason || `Created ${createdSteps.length} step(s).`,
417
- status: nextStatus,
418
- userId: options.userId,
419
- payload: { mode: options.mode || "append", steps: createdSteps.map((step) => step.planKey) }
420
- });
421
- return createdSteps;
422
- }
423
- async replan(runId, plan, options = {}) {
424
- if (!Array.isArray(plan) || plan.length === 0) {
425
- throw new Error("Plan must include at least one step.");
426
- }
427
- const run = await this.repository.requireRun(runId);
428
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
429
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
430
- }
431
- const policy = normalizePolicy(run.policy);
432
- if (!policy.allowReplan) {
433
- throw new Error("Replanning is disabled for this run.");
434
- }
435
- if (Number(run.iterationCount || 0) >= policy.maxIterations) {
436
- throw new Error(`Agent loop reached maxIterations=${policy.maxIterations}.`);
437
- }
438
- await this.repository.updateRun(run.id, {
439
- iterationCount: Number(run.iterationCount || 0) + 1,
440
- status: "running",
441
- updatedAt: now()
442
- });
443
- return this.replacePlan(run.id, plan, {
444
- mode: options.mode || "replace_pending",
445
- reason: options.reason || "Replan requested",
446
- userId: options.userId
447
- });
448
- }
449
- async startStep(stepId, options = {}) {
450
- const step = await this.repository.requireStep(stepId);
451
- const run = await this.repository.requireRun(step.runId);
452
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
453
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
454
- }
455
- if (step.status !== "pending" && step.status !== "failed") {
456
- throw new Error(`Step ${step.id} cannot start from status "${step.status}".`);
457
- }
458
- const policy = normalizePolicy(run.policy);
459
- if (Number(step.attempt || 0) >= Number(step.maxAttempts || policy.maxStepAttempts)) {
460
- throw new Error(`Step ${step.id} reached maxAttempts=${step.maxAttempts}.`);
461
- }
462
- const nextAttempt = Number(step.attempt || 0) + 1;
463
- await this.repository.updateStep(step.id, {
464
- status: "running",
465
- attempt: nextAttempt,
466
- error: "",
467
- agentExecutionSpanId: options.agentExecutionSpanId || step.agentExecutionSpanId,
468
- startedAt: now(),
469
- updatedAt: now()
470
- });
471
- await this.repository.updateRun(run.id, {
472
- status: "running",
473
- updatedAt: now()
474
- });
475
- await this.repository.createEvent({
476
- runId: run.id,
477
- stepId: step.id,
478
- type: "step_started",
479
- title: `Started: ${step.title || step.planKey}`,
480
- status: "running",
481
- userId: options.userId,
482
- payload: { attempt: nextAttempt }
483
- });
484
- if (["skill", "tool", "sub_agent"].includes(step.type)) {
485
- await this.repository.createEvent({
486
- runId: run.id,
487
- stepId: step.id,
488
- type: "tool_called",
489
- title: `Calling ${step.type}: ${step.target || step.title || step.planKey}`,
490
- status: "running",
491
- userId: options.userId,
492
- payload: {
493
- type: step.type,
494
- target: step.target,
495
- attempt: nextAttempt
496
- }
497
- });
498
- }
499
- return this.getRunSnapshot(run.id);
500
- }
501
- async completeStep(stepId, output, options = {}) {
502
- const step = await this.repository.requireStep(stepId);
503
- const run = await this.repository.requireRun(step.runId);
504
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
505
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
506
- }
507
- if (step.status !== "running") {
508
- throw new Error(`Step ${step.id} cannot complete from status "${step.status}".`);
509
- }
510
- await this.repository.updateStep(step.id, {
511
- status: "succeeded",
512
- output: output === void 0 ? {} : output,
513
- error: "",
514
- skillExecutionId: options.skillExecutionId || step.skillExecutionId,
515
- agentExecutionSpanId: options.agentExecutionSpanId || step.agentExecutionSpanId,
516
- metadata: { ...(0, import_ctx_utils.asObject)(step.metadata), ...(0, import_ctx_utils.asObject)(options.metadata) },
517
- endedAt: now(),
518
- updatedAt: now()
519
- });
520
- await this.repository.updateRun(run.id, {
521
- status: "running",
522
- updatedAt: now()
523
- });
524
- await this.repository.createEvent({
525
- runId: run.id,
526
- stepId: step.id,
527
- type: "step_succeeded",
528
- title: `Completed: ${step.title || step.planKey}`,
529
- content: (0, import_ctx_utils.trimText)(output, 2e3),
530
- status: "succeeded",
531
- userId: options.userId
532
- });
533
- if (step.type === "sub_agent" && step.target && run.leaderUsername) {
534
- (0, import_CircuitBreaker.getCircuitBreaker)().recordSuccess((0, import_CircuitBreaker.subAgentCircuitKey)(run.leaderUsername, step.target));
535
- }
536
- return this.getRunSnapshot(run.id);
537
- }
538
- async failStep(stepId, error, options = {}) {
539
- const step = await this.repository.requireStep(stepId);
540
- const run = await this.repository.requireRun(step.runId);
541
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
542
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
543
- }
544
- if (step.status !== "running") {
545
- throw new Error(`Step ${step.id} cannot fail from status "${step.status}".`);
546
- }
547
- const policy = normalizePolicy(run.policy);
548
- await this.repository.updateStep(step.id, {
549
- status: "failed",
550
- error: (0, import_ctx_utils.trimText)(error, 1e4),
551
- metadata: { ...(0, import_ctx_utils.asObject)(step.metadata), ...(0, import_ctx_utils.asObject)(options.metadata) },
552
- endedAt: now(),
553
- updatedAt: now()
554
- });
555
- await this.repository.updateRun(run.id, {
556
- status: "running",
557
- updatedAt: now()
558
- });
559
- await this.repository.createEvent({
560
- runId: run.id,
561
- stepId: step.id,
562
- type: "step_failed",
563
- title: `Failed: ${step.title || step.planKey}`,
564
- content: error,
565
- status: "failed",
566
- userId: options.userId,
567
- payload: {
568
- retryable: Number(step.attempt || 0) < Number(step.maxAttempts || policy.maxStepAttempts)
569
- }
570
- });
571
- if (step.type === "sub_agent" && step.target && run.leaderUsername) {
572
- (0, import_CircuitBreaker.getCircuitBreaker)().recordFailure((0, import_CircuitBreaker.subAgentCircuitKey)(run.leaderUsername, step.target));
573
- }
574
- return this.getRunSnapshot(run.id);
575
- }
576
- async skipStep(stepId, reason = "Skipped", options = {}) {
577
- const step = await this.repository.requireStep(stepId);
578
- const run = await this.repository.requireRun(step.runId);
579
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
580
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
581
- }
582
- if (!["pending", "running", "failed"].includes(step.status)) {
583
- throw new Error(`Step ${step.id} cannot skip from status "${step.status}".`);
584
- }
585
- await this.repository.updateStep(step.id, {
586
- status: "skipped",
587
- error: reason,
588
- endedAt: now(),
589
- updatedAt: now()
590
- });
591
- await this.repository.createEvent({
592
- runId: run.id,
593
- stepId: step.id,
594
- type: "step_skipped",
595
- title: `Skipped: ${step.title || step.planKey}`,
596
- content: reason,
597
- status: "skipped",
598
- userId: options.userId
599
- });
600
- return this.getRunSnapshot(run.id);
601
- }
602
- async requestApproval(stepId, approval, options = {}) {
603
- const step = await this.repository.requireStep(stepId);
604
- const run = await this.repository.requireRun(step.runId);
605
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
606
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
607
- }
608
- if (!["pending", "running"].includes(step.status)) {
609
- throw new Error(`Step ${step.id} cannot request approval for status "${step.status}".`);
610
- }
611
- await this.repository.updateStep(step.id, {
612
- status: "waiting_user",
613
- approval: approval || {},
614
- updatedAt: now()
615
- });
616
- await this.repository.updateRun(run.id, {
617
- status: "waiting_user",
618
- currentStepId: step.id,
619
- updatedAt: now()
620
- });
621
- await this.repository.createEvent({
622
- runId: run.id,
623
- stepId: step.id,
624
- type: "approval_requested",
625
- title: `Approval requested: ${step.title || step.planKey}`,
626
- content: options.reason || (approval == null ? void 0 : approval.prompt) || "",
627
- status: "waiting_user",
628
- userId: options.userId,
629
- payload: approval || {}
630
- });
631
- return this.getRunSnapshot(run.id);
632
- }
633
- async resumeRun(runId, options) {
634
- const run = await this.repository.requireRun(runId);
635
- const stepId = options.stepId || run.currentStepId;
636
- if (!stepId) {
637
- throw new Error("No waiting step found for this run.");
638
- }
639
- const step = await this.repository.requireStep(stepId);
640
- if (String(step.runId) !== String(run.id)) {
641
- throw new Error("Step does not belong to the run.");
642
- }
643
- if (run.status !== "waiting_user" || step.status !== "waiting_user") {
644
- throw new Error("Run is not waiting for user approval.");
645
- }
646
- if (options.approved) {
647
- const nextValues = {
648
- status: "pending",
649
- approval: { ...step.approval || {}, approved: true, resolvedAt: now().toISOString() },
650
- updatedAt: now()
651
- };
652
- if (options.editedInput !== void 0) {
653
- nextValues.input = options.editedInput;
654
- }
655
- await this.repository.updateStep(step.id, nextValues);
656
- await this.repository.updateRun(run.id, {
657
- status: "running",
658
- currentStepId: null,
659
- updatedAt: now()
660
- });
661
- } else {
662
- await this.repository.updateStep(step.id, {
663
- status: "failed",
664
- approval: { ...step.approval || {}, approved: false, resolvedAt: now().toISOString() },
665
- error: "User rejected this step.",
666
- endedAt: now(),
667
- updatedAt: now()
668
- });
669
- await this.repository.updateRun(run.id, {
670
- status: "running",
671
- currentStepId: null,
672
- updatedAt: now()
673
- });
674
- }
675
- await this.repository.createEvent({
676
- runId: run.id,
677
- stepId: step.id,
678
- type: "approval_resolved",
679
- title: options.approved ? "Approval granted" : "Approval rejected",
680
- status: options.approved ? "running" : "failed",
681
- userId: options.userId,
682
- payload: {
683
- approved: options.approved,
684
- editedInput: options.editedInput
685
- }
686
- });
687
- if (options.approved) {
688
- return this.getRunSnapshot(run.id);
689
- }
690
- return this.getRunSnapshot(run.id);
691
- }
692
- async retryStep(stepId, options = {}) {
693
- const step = await this.repository.requireStep(stepId);
694
- const run = await this.repository.requireRun(step.runId);
695
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
696
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
697
- }
698
- if (step.status !== "failed") {
699
- throw new Error("Only failed steps can be retried.");
700
- }
701
- const policy = normalizePolicy(run.policy);
702
- if (Number(step.attempt || 0) >= Number(step.maxAttempts || policy.maxStepAttempts)) {
703
- throw new Error(`Step ${step.id} reached maxAttempts=${step.maxAttempts}.`);
704
- }
705
- let routedTarget;
706
- let routeReason;
707
- if (step.type === "sub_agent" && run.leaderUsername) {
708
- const target = step.target || "";
709
- if (target) {
710
- const circuitBreaker = (0, import_CircuitBreaker.getCircuitBreaker)();
711
- const state = circuitBreaker.getState((0, import_CircuitBreaker.subAgentCircuitKey)(run.leaderUsername, target));
712
- const attempt = Number(step.attempt || 0);
713
- const shouldRoute = (state == null ? void 0 : state.state) === "open" || state && state.failures >= 2 && attempt >= 1;
714
- if (shouldRoute) {
715
- const alternatives = await this.registryService.findAlternativeSubAgents(run.leaderUsername, target);
716
- if (alternatives.length > 0) {
717
- const chosen = alternatives[0];
718
- routedTarget = chosen.username;
719
- routeReason = `Sub-agent "${target}" has ${(state == null ? void 0 : state.failures) || 0} failure(s) (circuit: ${(state == null ? void 0 : state.state) || "closed"}). Routing retry to alternative "${routedTarget}".`;
720
- }
721
- }
722
- }
723
- }
724
- const updateValues = {
725
- status: "pending",
726
- error: "",
727
- endedAt: null,
728
- updatedAt: now()
729
- };
730
- if (routedTarget) {
731
- updateValues.target = routedTarget;
732
- }
733
- await this.repository.updateStep(step.id, updateValues);
734
- await this.repository.updateRun(run.id, {
735
- status: "running",
736
- updatedAt: now()
737
- });
738
- await this.repository.createEvent({
739
- runId: run.id,
740
- stepId: step.id,
741
- type: "step_retry",
742
- title: routedTarget ? `Retry routed: ${step.title || step.planKey} \u2192 ${routedTarget}` : `Retry queued: ${step.title || step.planKey}`,
743
- content: routeReason || "",
744
- status: "pending",
745
- userId: options.userId,
746
- payload: routedTarget ? { originalTarget: step.target, routedTarget, reason: routeReason } : void 0
747
- });
748
- return this.getRunSnapshot(run.id);
749
- }
750
- async finishRun(runId, finalAnswer, options = {}) {
751
- const run = await this.repository.requireRun(runId);
752
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
753
- throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
754
- }
755
- const status = options.status || "succeeded";
756
- if (status === "succeeded") {
757
- const steps = await this.repository.getSteps(run.id);
758
- const unfinished = steps.filter((step) => !TERMINAL_STEP_STATUSES.has(step.status));
759
- if (unfinished.length) {
760
- throw new Error(`Cannot finish run ${run.id}: ${unfinished.length} step(s) are not complete.`);
761
- }
762
- const policy = normalizePolicy(run.policy);
763
- const verificationPassed = steps.some((step) => step.type === "verification" && step.status === "succeeded");
764
- if (policy.requireVerification && !verificationPassed) {
765
- throw new Error("Cannot finish run: policy requires a succeeded verification step.");
766
- }
767
- }
768
- await this.repository.updateRun(run.id, {
769
- status,
770
- finalAnswer: finalAnswer || "",
771
- summary: options.summary || run.summary,
772
- currentStepId: null,
773
- metadata: { ...(0, import_ctx_utils.asObject)(run.metadata), evidence: options.evidence },
774
- endedAt: now(),
775
- updatedAt: now()
776
- });
777
- await this.repository.createEvent({
778
- runId: run.id,
779
- type: "finished",
780
- title: status === "succeeded" ? "Agent loop finished" : "Agent loop failed",
781
- content: finalAnswer,
782
- status,
783
- userId: options.userId,
784
- payload: { evidence: options.evidence }
785
- });
786
- return this.getRunSnapshot(run.id);
787
- }
788
- async stepFeedback(stepId, feedback, options = {}) {
789
- const step = await this.repository.requireStep(stepId);
790
- const run = await this.repository.requireRun(step.runId);
791
- if (step.status !== "succeeded" && step.status !== "failed") {
792
- throw new Error(`Cannot provide feedback for step ${step.id} in status "${step.status}".`);
793
- }
794
- await this.repository.createEvent({
795
- runId: run.id,
796
- stepId: step.id,
797
- type: "step_feedback",
798
- title: `Feedback: ${feedback.rating === "positive" ? "\u{1F44D}" : "\u{1F44E}"} ${step.title || step.planKey}`,
799
- content: feedback.comment || "",
800
- status: step.status,
801
- userId: options.userId,
802
- payload: {
803
- rating: feedback.rating,
804
- comment: feedback.comment || "",
805
- category: feedback.category || "",
806
- stepType: step.type,
807
- stepPlanKey: step.planKey,
808
- stepTarget: step.target || "",
809
- attempt: step.attempt || 0
810
- }
811
- });
812
- return this.getRunSnapshot(run.id);
813
- }
814
- async cancelRun(runId, options = {}) {
815
- const run = await this.repository.requireRun(runId);
816
- if (TERMINAL_RUN_STATUSES.has(run.status)) {
817
- return this.getRunSnapshot(run.id);
818
- }
819
- const steps = await this.repository.getSteps(run.id);
820
- for (const step of steps) {
821
- if (!TERMINAL_STEP_STATUSES.has(step.status) && step.status !== "failed") {
822
- await this.repository.updateStep(step.id, {
823
- status: "skipped",
824
- error: options.reason || "Run canceled.",
825
- endedAt: now(),
826
- updatedAt: now()
827
- });
828
- }
829
- }
830
- await this.repository.updateRun(run.id, {
831
- status: "canceled",
832
- currentStepId: null,
833
- endedAt: now(),
834
- updatedAt: now()
835
- });
836
- await this.repository.createEvent({
837
- runId: run.id,
838
- type: "canceled",
839
- title: "Agent loop canceled",
840
- content: options.reason || "",
841
- status: "canceled",
842
- userId: options.userId
843
- });
844
- return this.getRunSnapshot(run.id);
845
- }
846
- async executeApprovedPlan(runId, options = {}) {
847
- var _a, _b, _c, _d;
848
- const lockToken = `exec-${runId}-${Math.random().toString(36).slice(2, 10)}`;
849
- const acquired = await this.repository.lockRun(runId, lockToken, 3e5);
850
- if (!acquired) {
851
- throw new Error(`Run ${runId} is currently locked and executing in another process.`);
852
- }
853
- try {
854
- let iterations = 0;
855
- let snapshot = await this.getRunSnapshot(runId);
856
- const harnessSettings = (0, import_ctx_utils.asObject)((_b = (_a = snapshot.run) == null ? void 0 : _a.metadata) == null ? void 0 : _b.harnessSettings);
857
- const maxControllerSteps = Math.max(
858
- 1,
859
- Math.min(
860
- ORCHESTRATOR_CONTROLLER_MAX_STEPS,
861
- Number(harnessSettings.maxControllerSteps || ORCHESTRATOR_CONTROLLER_MAX_STEPS)
862
- )
863
- );
864
- const policy = normalizePolicy(snapshot.run.policy);
865
- const maxConcurrency = policy.maxConcurrency;
866
- while (snapshot.nextSteps && snapshot.nextSteps.length > 0 && iterations < maxControllerSteps) {
867
- const batch = snapshot.nextSteps.slice(0, maxConcurrency);
868
- iterations += batch.length;
869
- if (this.tokenTracker) {
870
- const budgetCheck = await this.tokenTracker.checkBudget(runId);
871
- if (!budgetCheck.allowed) {
872
- return this.finishRun(runId, budgetCheck.reason, {
873
- status: "failed",
874
- summary: budgetCheck.reason,
875
- userId: options.userId
876
- });
877
- }
878
- }
879
- await Promise.all(batch.map((step) => this.startStep(step.id, { userId: options.userId })));
880
- snapshot = await this.getRunSnapshot(runId);
881
- const runningSteps = batch.map(
882
- (step) => snapshot.steps.find((s) => String(s.id) === String(step.id)) || step
883
- );
884
- const results = await Promise.allSettled(
885
- runningSteps.map((step) => this.harness.executeStep(snapshot.run, step, options))
886
- );
887
- let batchBackoffMs = 0;
888
- let approvalBreak = false;
889
- for (let i = 0; i < results.length; i++) {
890
- const runningStep = runningSteps[i];
891
- const result = results[i];
892
- if (result.status === "fulfilled") {
893
- snapshot = await this.completeStep(runningStep.id, result.value, {
894
- userId: options.userId,
895
- metadata: { controller: "agent-loop-service" }
896
- });
897
- } else {
898
- const error = result.reason;
899
- if ((error == null ? void 0 : error.message) === "requires_approval") {
900
- snapshot = await this.requestApproval(
901
- runningStep.id,
902
- { prompt: `Execution of step "${runningStep.title}" requires permission.` },
903
- { userId: options.userId, reason: "Dynamic tool approval required by policy." }
904
- );
905
- approvalBreak = true;
906
- break;
907
- }
908
- snapshot = await this.failStep(runningStep.id, (error == null ? void 0 : error.message) || String(error), {
909
- userId: options.userId,
910
- metadata: { controller: "agent-loop-service" }
911
- });
912
- const failedStep = snapshot.steps.find((s) => String(s.id) === String(runningStep.id));
913
- if (failedStep && Number(failedStep.attempt || 0) < Number(failedStep.maxAttempts || policy.maxStepAttempts)) {
914
- const attempt = Number(failedStep.attempt || 1);
915
- const baseDelay = 1e3;
916
- const maxDelay = 6e4;
917
- const delay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxDelay);
918
- batchBackoffMs = Math.max(batchBackoffMs, delay);
919
- }
920
- }
921
- }
922
- if (!approvalBreak && batchBackoffMs > 0) {
923
- await new Promise((resolve) => setTimeout(resolve, batchBackoffMs));
924
- }
925
- snapshot = await this.getRunSnapshot(runId);
926
- if (snapshot.run.status === "waiting_user") {
927
- break;
928
- }
929
- }
930
- snapshot = await this.getRunSnapshot(runId);
931
- if (iterations >= maxControllerSteps && snapshot.nextSteps && snapshot.nextSteps.length > 0) {
932
- return this.finishRun(runId, `Agent loop stopped after ${maxControllerSteps} controller steps.`, {
933
- status: "failed",
934
- summary: "Controller iteration limit reached.",
935
- userId: options.userId
936
- });
937
- }
938
- if (snapshot.run.status === "waiting_user") {
939
- return snapshot;
940
- }
941
- const steps = snapshot.steps || [];
942
- const failed = steps.filter((step) => step.status === "failed");
943
- const unfinished = steps.filter(
944
- (step) => !TERMINAL_STEP_STATUSES.has(step.status) && step.status !== "failed"
945
- );
946
- if (failed.length || unfinished.length) {
947
- return this.finishRun(
948
- runId,
949
- failed.length ? `Agent loop failed at ${failed.length} step(s).` : `Agent loop stopped with ${unfinished.length} unfinished step(s).`,
950
- {
951
- status: "failed",
952
- summary: ((_c = failed[0]) == null ? void 0 : _c.error) || "No executable step is available.",
953
- evidence: {
954
- failedStepIds: failed.map((step) => step.id),
955
- unfinishedStepIds: unfinished.map((step) => step.id)
956
- },
957
- userId: options.userId
958
- }
959
- );
960
- }
961
- const verification = steps.find((step) => step.type === "verification" && step.status === "succeeded");
962
- return this.finishRun(runId, "Agent loop completed after plan execution.", {
963
- status: "succeeded",
964
- summary: ((_d = verification == null ? void 0 : verification.output) == null ? void 0 : _d.summary) || "All approved plan steps completed.",
965
- evidence: { stepCount: steps.length, controllerIterations: iterations },
966
- userId: options.userId
967
- });
968
- } finally {
969
- const current = await this.repository.getRun(runId);
970
- if (current && current.lockedBy === lockToken) {
971
- await this.repository.unlockRun(runId);
972
- }
973
- }
974
- }
975
- async getRunSnapshot(runId) {
976
- const run = await this.repository.requireRun(runId);
977
- const steps = await this.repository.getSteps(run.id);
978
- const nextSteps = this.pickNextSteps(steps, run.policy);
979
- const runningStepIds = steps.filter((s) => s.status === "running").map((s) => s.id);
980
- return {
981
- run: { ...run, runningStepIds },
982
- steps,
983
- nextSteps
984
- };
985
- }
986
- async getRunDetail(runId) {
987
- const snapshot = await this.getRunSnapshot(runId);
988
- const events = await this.repository.getEvents(snapshot.run.id);
989
- const spans = await this.repository.getLinkedSpans(snapshot.run.id, snapshot.run.rootRunId);
990
- const skillExecutions = await this.repository.getLinkedSkillExecutions(snapshot.run.id, snapshot.steps);
991
- return {
992
- ...snapshot,
993
- events,
994
- spans,
995
- skillExecutions
996
- };
997
- }
998
- pickNextSteps(steps, runPolicy) {
999
- var _a;
1000
- const byPlanKey = new Map(steps.map((step) => [String(step.planKey), step]));
1001
- const policy = normalizePolicy(runPolicy);
1002
- const candidates = steps.filter(
1003
- (step) => step.status === "pending" || step.status === "failed" && Number(step.attempt || 0) < Number(step.maxAttempts || policy.maxStepAttempts)
1004
- ).sort((a, b) => Number(a.index || 0) - Number(b.index || 0));
1005
- const ready = [];
1006
- for (const step of candidates) {
1007
- const dependencies = (0, import_ctx_utils.asArray)(step.dependsOn).map(String);
1008
- const allowSkipped = step.dependencyPolicy === "allow_skipped" || ((_a = step.metadata) == null ? void 0 : _a.dependencyPolicy) === "allow_skipped";
1009
- const allDepsReady = dependencies.every((key) => {
1010
- const dependency = byPlanKey.get(key);
1011
- return (dependency == null ? void 0 : dependency.status) === "succeeded" || allowSkipped && (dependency == null ? void 0 : dependency.status) === "skipped";
1012
- });
1013
- if (allDepsReady) {
1014
- ready.push(step);
1015
- }
1016
- }
1017
- return ready;
1018
- }
1019
- }
1020
- // Annotate the CommonJS export names for ESM import in node:
1021
- 0 && (module.exports = {
1022
- AgentLoopController
1023
- });