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