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,201 +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 ContextAggregator_exports = {};
28
- __export(ContextAggregator_exports, {
29
- ContextAggregator: () => ContextAggregator
30
- });
31
- module.exports = __toCommonJS(ContextAggregator_exports);
32
- function trimText(text, maxLen) {
33
- if (text.length <= maxLen) return text;
34
- return text.slice(0, maxLen) + "\n...[truncated]";
35
- }
36
- function estimateTokens(text) {
37
- return Math.ceil(text.length / 4);
38
- }
39
- class ContextAggregator {
40
- constructor(plugin) {
41
- this.plugin = plugin;
42
- }
43
- get db() {
44
- return this.plugin.db;
45
- }
46
- get app() {
47
- return this.plugin.app;
48
- }
49
- /**
50
- * Build a structured context string from completed steps of a run.
51
- *
52
- * @param runId - agentLoopRuns.id
53
- * @param maxTokens - Maximum tokens for the context output (default 4000)
54
- * @param options - Strategy options
55
- */
56
- async buildStepContext(runId, maxTokens, options) {
57
- var _a;
58
- const effectiveMaxTokens = maxTokens || 4e3;
59
- let steps;
60
- try {
61
- const repo = this.db.getRepository("agentLoopSteps");
62
- if (!repo) return "";
63
- steps = await repo.find({
64
- filter: { runId },
65
- sort: ["index", "createdAt"],
66
- pageSize: 500
67
- });
68
- } catch {
69
- return "";
70
- }
71
- if (!steps || steps.length === 0) return "";
72
- const completedSteps = steps.filter((s) => s.status === "succeeded" || s.status === "failed");
73
- if (completedSteps.length === 0) return "";
74
- const config = {
75
- strategy: (options == null ? void 0 : options.strategy) || "all",
76
- includeToolResults: (options == null ? void 0 : options.includeToolResults) ?? false,
77
- includeStepOutputs: (options == null ? void 0 : options.includeStepOutputs) ?? true
78
- };
79
- let candidates = completedSteps;
80
- if (config.strategy === "last_n") {
81
- const n = Math.min(10, completedSteps.length);
82
- candidates = completedSteps.slice(-n);
83
- }
84
- const parts = [];
85
- for (const step of candidates) {
86
- const key = step.planKey || `step_${step.index || 0}`;
87
- const type = step.type || "unknown";
88
- const target = step.target || "";
89
- const title = step.title || key;
90
- const status = step.status || "unknown";
91
- const lines = [];
92
- lines.push(`<step key="${key}" type="${type}" target="${target}" status="${status}">`);
93
- lines.push(` <title>${this.escapeXml(title)}</title>`);
94
- if (step.description) {
95
- lines.push(` <description>${this.escapeXml(trimText(step.description, 500))}</description>`);
96
- }
97
- if (config.includeStepOutputs && step.output) {
98
- const outputStr = typeof step.output === "string" ? step.output : this.safeStringify(step.output);
99
- lines.push(` <output>${this.escapeXml(trimText(outputStr, 2e3))}</output>`);
100
- }
101
- if (config.includeToolResults && ((_a = step.metadata) == null ? void 0 : _a.toolResults)) {
102
- const toolStr = this.safeStringify(step.metadata.toolResults);
103
- lines.push(` <tool_results>${this.escapeXml(trimText(toolStr, 1500))}</tool_results>`);
104
- }
105
- if (step.error) {
106
- lines.push(` <error>${this.escapeXml(trimText(step.error, 1e3))}</error>`);
107
- }
108
- lines.push("</step>");
109
- parts.push(lines.join("\n"));
110
- }
111
- let context = `<previous_steps>
112
- ${parts.join("\n\n")}
113
- </previous_steps>`;
114
- if (estimateTokens(context) > effectiveMaxTokens) {
115
- context = this.truncateToTokenLimit(context, effectiveMaxTokens);
116
- }
117
- return context;
118
- }
119
- /**
120
- * Enrich a base system prompt with step context from the run.
121
- * Fetches the run from DB to access policy settings (maxContextTokens, etc.).
122
- *
123
- * @param basePrompt - The original system prompt to enrich
124
- * @param runId - agentLoopRuns.id
125
- * @param _stepId - agentLoopSteps.id (reserved for future per-step context)
126
- */
127
- async enrichSystemPrompt(basePrompt, runId, _stepId, options) {
128
- let run;
129
- try {
130
- const repo = this.db.getRepository("agentLoopRuns");
131
- if (!repo) return basePrompt;
132
- run = await repo.findOne({ filter: { id: runId } });
133
- if (!run) return basePrompt;
134
- } catch {
135
- return basePrompt;
136
- }
137
- const policy = run.policy || {};
138
- const maxCtxTokens = (options == null ? void 0 : options.maxContextTokens) ?? policy.maxContextTokens ?? 4e3;
139
- const strategy = (options == null ? void 0 : options.contextSummaryStrategy) ?? policy.contextSummaryStrategy ?? "all";
140
- const includeToolResults = (options == null ? void 0 : options.includeToolResults) ?? policy.includeToolResults ?? false;
141
- const includeStepOutputs = (options == null ? void 0 : options.includeStepOutputs) ?? policy.includeStepOutputs ?? true;
142
- const stepContext = await this.buildStepContext(runId, maxCtxTokens, {
143
- strategy,
144
- includeToolResults,
145
- includeStepOutputs
146
- });
147
- if (!stepContext) return basePrompt;
148
- return `${basePrompt}
149
-
150
- <previous_steps_context>
151
- ${stepContext}
152
- </previous_steps_context>`;
153
- }
154
- truncateToTokenLimit(text, maxTokens) {
155
- const outerMatch = text.match(/<previous_steps>\n([\s\S]*)\n<\/previous_steps>/);
156
- if (!outerMatch) return text;
157
- const inner = outerMatch[1];
158
- const stepBlocks = this.splitStepBlocks(inner);
159
- if (stepBlocks.length <= 2) {
160
- const maxChars2 = maxTokens * 4;
161
- if (text.length <= maxChars2) return text;
162
- return text.slice(0, maxChars2) + "\n...[truncated]\n</previous_steps>";
163
- }
164
- const keepFirst = stepBlocks.slice(0, 2);
165
- const keepLast = stepBlocks.slice(-2);
166
- const removed = stepBlocks.length - keepFirst.length - keepLast.length;
167
- const rebuilt = [
168
- "<previous_steps>",
169
- ...keepFirst,
170
- ` <!-- ... ${removed} intermediate step(s) omitted due to context limit ... -->`,
171
- ...keepLast,
172
- "</previous_steps>"
173
- ].join("\n");
174
- const maxChars = maxTokens * 4;
175
- if (rebuilt.length <= maxChars) return rebuilt;
176
- return rebuilt.slice(0, maxChars) + "\n...[truncated]\n</previous_steps>";
177
- }
178
- splitStepBlocks(text) {
179
- const blocks = [];
180
- const regex = /<step[\s\S]*?<\/step>/g;
181
- let match;
182
- while ((match = regex.exec(text)) !== null) {
183
- blocks.push(match[0]);
184
- }
185
- return blocks;
186
- }
187
- escapeXml(value) {
188
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
189
- }
190
- safeStringify(value) {
191
- try {
192
- return JSON.stringify(value, null, 2);
193
- } catch {
194
- return String(value);
195
- }
196
- }
197
- }
198
- // Annotate the CommonJS export names for ESM import in node:
199
- 0 && (module.exports = {
200
- ContextAggregator
201
- });
@@ -1,95 +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 PlanningPromptService_exports = {};
28
- __export(PlanningPromptService_exports, {
29
- PlanningPromptService: () => PlanningPromptService
30
- });
31
- module.exports = __toCommonJS(PlanningPromptService_exports);
32
- const PLAN_KEYWORDS = [
33
- "k\u1EBF ho\u1EA1ch",
34
- "l\u1EADp k\u1EBF ho\u1EA1ch",
35
- "l\xEAn k\u1EBF ho\u1EA1ch",
36
- "k\u1EBF ho\u1EA1ch h\xF3a",
37
- "l\u1EADp plan",
38
- "t\u1EA1o k\u1EBF ho\u1EA1ch",
39
- "x\xE2y d\u1EF1ng k\u1EBF ho\u1EA1ch",
40
- "planning",
41
- "make a plan",
42
- "create a plan"
43
- ];
44
- const PLAN_WORD_PATTERN = /\bplan\b/i;
45
- const PLANNING_PREFIX = `[PLAN MODE] The user's request may need a structured plan. First, analyze the request:
46
-
47
- STEP 0 \u2014 Evaluate: Does this request truly require 3+ distinct steps (building, creating, deploying, researching, etc.)?
48
- - NO \u2192 The user mentioned "plan" but this is a simple question or single action. Respond directly WITHOUT calling any agent_loop tools.
49
- - YES \u2192 Proceed with the plan workflow below.
50
-
51
- PLAN WORKFLOW (only if truly multi-step):
52
- 1. Call \`agent_loop_start\` with a concrete step-by-step plan. Use small, executable steps with clear planKey values and proper dependsOn chains. Structure the user's goal clearly in the "goal" field.
53
- 2. After the plan is approved, execute each step by calling \`agent_loop_update_step\` with status="running" before the action, then status="succeeded" or "failed" after.
54
- 3. If execution diverges, call \`agent_loop_replan\` to update remaining steps.
55
- 4. When all steps complete, call \`agent_loop_finish\`.
56
-
57
- User request:
58
- `;
59
- class PlanningPromptService {
60
- static getMessageText(content) {
61
- if (typeof content === "string") return content;
62
- if (content && typeof content === "object" && "content" in content) {
63
- const nested = content.content;
64
- return typeof nested === "string" ? nested : "";
65
- }
66
- return "";
67
- }
68
- shouldInjectPlanningPrompt(text) {
69
- if (!text) return false;
70
- const normalized = text.toLowerCase();
71
- if (PLAN_WORD_PATTERN.test(normalized)) return true;
72
- return PLAN_KEYWORDS.some((keyword) => normalized.includes(keyword));
73
- }
74
- getPlanningPrefix() {
75
- return PLANNING_PREFIX;
76
- }
77
- getPlanningInstructions() {
78
- return PLANNING_PREFIX.replace(/User request:\s*$/, "").trim();
79
- }
80
- applyPlanningContext(messages) {
81
- const shouldInject = messages.some(
82
- (message) => message.role === "user" && this.shouldInjectPlanningPrompt(PlanningPromptService.getMessageText(message.content))
83
- );
84
- if (!shouldInject) return false;
85
- messages.unshift({
86
- role: "system",
87
- content: { type: "text", content: this.getPlanningInstructions() }
88
- });
89
- return true;
90
- }
91
- }
92
- // Annotate the CommonJS export names for ESM import in node:
93
- 0 && (module.exports = {
94
- PlanningPromptService
95
- });
@@ -1,373 +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 agent_loop_exports = {};
28
- __export(agent_loop_exports, {
29
- createAgentLoopTools: () => createAgentLoopTools
30
- });
31
- module.exports = __toCommonJS(agent_loop_exports);
32
- var import_zod = require("zod");
33
- var import_ExecutionSpanService = require("../services/ExecutionSpanService");
34
- var import_ctx_utils = require("../utils/ctx-utils");
35
- const stepSchema = import_zod.z.object({
36
- id: import_zod.z.string().optional(),
37
- key: import_zod.z.string().optional(),
38
- planKey: import_zod.z.string().optional(),
39
- parentStepId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional(),
40
- title: import_zod.z.string().optional(),
41
- description: import_zod.z.string().optional(),
42
- type: import_zod.z.enum(["reasoning", "skill", "tool", "sub_agent", "verification"]).optional(),
43
- target: import_zod.z.string().optional(),
44
- input: import_zod.z.any().optional(),
45
- dependsOn: import_zod.z.array(import_zod.z.string()).optional(),
46
- maxAttempts: import_zod.z.number().int().min(1).max(10).optional(),
47
- metadata: import_zod.z.any().optional()
48
- });
49
- const policySchema = import_zod.z.object({
50
- maxIterations: import_zod.z.number().int().min(1).max(100).optional(),
51
- maxStepAttempts: import_zod.z.number().int().min(1).max(10).optional(),
52
- allowReplan: import_zod.z.boolean().optional(),
53
- requireVerification: import_zod.z.boolean().optional(),
54
- stopOnApprovalRequired: import_zod.z.boolean().optional()
55
- }).optional();
56
- function toolResult(status, payload) {
57
- return {
58
- status,
59
- content: typeof payload === "string" ? payload : JSON.stringify(payload)
60
- };
61
- }
62
- function setLoopTraceContext(ctx, snapshot, step) {
63
- if (!ctx || !(snapshot == null ? void 0 : snapshot.run)) return;
64
- const existing = (0, import_ExecutionSpanService.getOrchestratorTraceContext)(ctx) || {};
65
- (0, import_ExecutionSpanService.setOrchestratorTraceContext)(ctx, {
66
- ...existing,
67
- rootRunId: snapshot.run.rootRunId || existing.rootRunId,
68
- leaderUsername: snapshot.run.leaderUsername || existing.leaderUsername,
69
- agentLoopRunId: String(snapshot.run.id),
70
- agentLoopStepId: (step == null ? void 0 : step.id) ? String(step.id) : void 0
71
- });
72
- }
73
- function planFromArgs(plan) {
74
- return Array.isArray(plan) ? plan : [];
75
- }
76
- function createAgentLoopTools(plugin, service) {
77
- return [
78
- {
79
- scope: "CUSTOM",
80
- execution: "backend",
81
- defaultPermission: "ALLOW",
82
- introduction: {
83
- title: "Agent Loop - Start",
84
- about: "Create a persistent agent loop run and initial plan for a user goal."
85
- },
86
- definition: {
87
- name: "agent_loop_start",
88
- description: "Start a persistent agent loop run. Use this first when the user asks for a multi-step task. Provide a concrete plan with small executable steps before calling other tools.",
89
- schema: import_zod.z.object({
90
- goal: import_zod.z.string().min(1).describe("The user goal to complete."),
91
- leaderUsername: import_zod.z.string().optional().describe("Leader AI employee username. Usually omit; inferred from chat."),
92
- sessionId: import_zod.z.string().optional(),
93
- messageId: import_zod.z.string().optional(),
94
- policy: policySchema,
95
- metadata: import_zod.z.any().optional(),
96
- plan: import_zod.z.array(stepSchema).optional().describe("Initial plan steps. Use stable planKey values for dependencies.")
97
- })
98
- },
99
- invoke: async (ctx, args) => {
100
- var _a;
101
- try {
102
- const leaderUsername = await (0, import_ctx_utils.resolveLeaderUsername)(ctx, plugin, args);
103
- const snapshot = await service.createRun({
104
- goal: args.goal,
105
- leaderUsername,
106
- sessionId: (0, import_ctx_utils.resolveSessionId)(ctx, args),
107
- messageId: (0, import_ctx_utils.resolveMessageId)(ctx, args),
108
- userId: (0, import_ctx_utils.currentUserId)(ctx),
109
- policy: args.policy,
110
- metadata: args.metadata,
111
- plan: planFromArgs(args.plan)
112
- });
113
- setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
114
- return toolResult("success", snapshot);
115
- } catch (error) {
116
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
117
- }
118
- }
119
- },
120
- {
121
- scope: "CUSTOM",
122
- execution: "backend",
123
- defaultPermission: "ALLOW",
124
- introduction: {
125
- title: "Agent Loop - Status",
126
- about: "Read the current run, steps, and next executable steps."
127
- },
128
- definition: {
129
- name: "agent_loop_status",
130
- description: "Fetch an agent loop run. Call this to check which steps are ready for execution.",
131
- schema: import_zod.z.object({
132
- runId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()])
133
- })
134
- },
135
- invoke: async (ctx, args) => {
136
- var _a;
137
- try {
138
- const snapshot = await service.getRunSnapshot(args.runId);
139
- setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
140
- return toolResult("success", snapshot);
141
- } catch (error) {
142
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
143
- }
144
- }
145
- },
146
- {
147
- scope: "CUSTOM",
148
- execution: "backend",
149
- defaultPermission: "ALLOW",
150
- introduction: {
151
- title: "Agent Loop - Update Step",
152
- about: "Move a plan step through running, succeeded, failed, or skipped states."
153
- },
154
- definition: {
155
- name: "agent_loop_update_step",
156
- description: 'Update one plan step after executing the corresponding skill/tool/sub-agent action. Use status="running" before the action and status="succeeded" or "failed" after it.',
157
- schema: import_zod.z.object({
158
- stepId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
159
- status: import_zod.z.enum(["running", "succeeded", "failed", "skipped"]),
160
- output: import_zod.z.any().optional(),
161
- error: import_zod.z.string().optional(),
162
- reason: import_zod.z.string().optional(),
163
- skillExecutionId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional(),
164
- agentExecutionSpanId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional(),
165
- metadata: import_zod.z.any().optional()
166
- })
167
- },
168
- invoke: async (ctx, args) => {
169
- var _a, _b, _c;
170
- try {
171
- let snapshot;
172
- if (args.status === "running") {
173
- snapshot = await service.startStep(args.stepId, {
174
- userId: (0, import_ctx_utils.currentUserId)(ctx),
175
- agentExecutionSpanId: args.agentExecutionSpanId
176
- });
177
- const currentStep = snapshot.steps.find((step) => String(step.id) === String(args.stepId));
178
- setLoopTraceContext(ctx, snapshot, currentStep);
179
- } else if (args.status === "succeeded") {
180
- snapshot = await service.completeStep(args.stepId, args.output === void 0 ? {} : args.output, {
181
- userId: (0, import_ctx_utils.currentUserId)(ctx),
182
- skillExecutionId: args.skillExecutionId,
183
- agentExecutionSpanId: args.agentExecutionSpanId,
184
- metadata: args.metadata
185
- });
186
- setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
187
- } else if (args.status === "failed") {
188
- snapshot = await service.failStep(args.stepId, args.error || "Step failed.", {
189
- userId: (0, import_ctx_utils.currentUserId)(ctx),
190
- metadata: args.metadata
191
- });
192
- setLoopTraceContext(ctx, snapshot, (_b = snapshot.nextSteps) == null ? void 0 : _b[0]);
193
- } else {
194
- snapshot = await service.skipStep(args.stepId, args.reason || "Skipped.", {
195
- userId: (0, import_ctx_utils.currentUserId)(ctx)
196
- });
197
- setLoopTraceContext(ctx, snapshot, (_c = snapshot.nextSteps) == null ? void 0 : _c[0]);
198
- }
199
- return toolResult("success", snapshot);
200
- } catch (error) {
201
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
202
- }
203
- }
204
- },
205
- {
206
- scope: "CUSTOM",
207
- execution: "backend",
208
- defaultPermission: "ALLOW",
209
- introduction: {
210
- title: "Agent Loop - Replan",
211
- about: "Replace pending work or append new plan steps when execution needs a new path."
212
- },
213
- definition: {
214
- name: "agent_loop_replan",
215
- description: "Update the plan when a step fails, required context is missing, or a better execution path is discovered.",
216
- schema: import_zod.z.object({
217
- runId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
218
- reason: import_zod.z.string().optional(),
219
- mode: import_zod.z.enum(["replace_pending", "append"]).optional(),
220
- plan: import_zod.z.array(stepSchema).min(1)
221
- })
222
- },
223
- invoke: async (ctx, args) => {
224
- var _a;
225
- try {
226
- await service.replan(args.runId, args.plan, {
227
- reason: args.reason,
228
- mode: args.mode || "replace_pending",
229
- userId: (0, import_ctx_utils.currentUserId)(ctx)
230
- });
231
- const snapshot = await service.getRunSnapshot(args.runId);
232
- setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
233
- return toolResult("success", snapshot);
234
- } catch (error) {
235
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
236
- }
237
- }
238
- },
239
- {
240
- scope: "CUSTOM",
241
- execution: "backend",
242
- defaultPermission: "ALLOW",
243
- introduction: {
244
- title: "Agent Loop - Request Approval",
245
- about: "Pause a run and request user approval or edited input for a step."
246
- },
247
- definition: {
248
- name: "agent_loop_request_approval",
249
- description: "Pause the loop when a step needs user approval, user-edited input, or an ASK/human-review tool cannot run headlessly.",
250
- schema: import_zod.z.object({
251
- stepId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
252
- reason: import_zod.z.string().optional(),
253
- approval: import_zod.z.any().optional()
254
- })
255
- },
256
- invoke: async (ctx, args) => {
257
- var _a;
258
- try {
259
- const snapshot = await service.requestApproval(args.stepId, args.approval || {}, {
260
- reason: args.reason,
261
- userId: (0, import_ctx_utils.currentUserId)(ctx)
262
- });
263
- setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
264
- return toolResult("success", snapshot);
265
- } catch (error) {
266
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
267
- }
268
- }
269
- },
270
- {
271
- scope: "CUSTOM",
272
- execution: "backend",
273
- defaultPermission: "ALLOW",
274
- introduction: {
275
- title: "Agent Loop - Resume",
276
- about: "Resume a waiting run after user approval or rejection."
277
- },
278
- definition: {
279
- name: "agent_loop_resume",
280
- description: "Resume a run that is waiting for user approval. Pass editedInput when the user changed step input.",
281
- schema: import_zod.z.object({
282
- runId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
283
- stepId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional(),
284
- approved: import_zod.z.boolean(),
285
- editedInput: import_zod.z.any().optional()
286
- })
287
- },
288
- invoke: async (ctx, args) => {
289
- var _a;
290
- try {
291
- const snapshot = await service.resumeRun(args.runId, {
292
- stepId: args.stepId,
293
- approved: args.approved,
294
- editedInput: args.editedInput,
295
- userId: (0, import_ctx_utils.currentUserId)(ctx),
296
- ctx
297
- });
298
- setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
299
- return toolResult("success", snapshot);
300
- } catch (error) {
301
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
302
- }
303
- }
304
- },
305
- {
306
- scope: "CUSTOM",
307
- execution: "backend",
308
- defaultPermission: "ALLOW",
309
- introduction: {
310
- title: "Agent Loop - Finish",
311
- about: "Finish a run with final answer and optional evidence."
312
- },
313
- definition: {
314
- name: "agent_loop_finish",
315
- description: 'Finish the agent loop after all required steps and verification are complete. Use status="failed" if the goal cannot be completed.',
316
- schema: import_zod.z.object({
317
- runId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
318
- finalAnswer: import_zod.z.string().optional(),
319
- status: import_zod.z.enum(["succeeded", "failed"]).optional(),
320
- summary: import_zod.z.string().optional(),
321
- evidence: import_zod.z.any().optional()
322
- })
323
- },
324
- invoke: async (ctx, args) => {
325
- try {
326
- const snapshot = await service.finishRun(args.runId, args.finalAnswer || "", {
327
- status: args.status || "succeeded",
328
- summary: args.summary,
329
- evidence: args.evidence,
330
- userId: (0, import_ctx_utils.currentUserId)(ctx)
331
- });
332
- setLoopTraceContext(ctx, snapshot);
333
- return toolResult("success", snapshot);
334
- } catch (error) {
335
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
336
- }
337
- }
338
- },
339
- {
340
- scope: "CUSTOM",
341
- execution: "backend",
342
- defaultPermission: "ALLOW",
343
- introduction: {
344
- title: "Agent Loop - Cancel",
345
- about: "Cancel a run and skip unfinished steps."
346
- },
347
- definition: {
348
- name: "agent_loop_cancel",
349
- description: "Cancel an agent loop run. Use this when the user stops the task or the goal is no longer valid.",
350
- schema: import_zod.z.object({
351
- runId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]),
352
- reason: import_zod.z.string().optional()
353
- })
354
- },
355
- invoke: async (ctx, args) => {
356
- try {
357
- const snapshot = await service.cancelRun(args.runId, {
358
- reason: args.reason,
359
- userId: (0, import_ctx_utils.currentUserId)(ctx)
360
- });
361
- setLoopTraceContext(ctx, snapshot);
362
- return toolResult("success", snapshot);
363
- } catch (error) {
364
- return toolResult("error", (error == null ? void 0 : error.message) || String(error));
365
- }
366
- }
367
- }
368
- ];
369
- }
370
- // Annotate the CommonJS export names for ESM import in node:
371
- 0 && (module.exports = {
372
- createAgentLoopTools
373
- });