micro-models-agent 0.28.9 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/cli/commands.js +220 -0
  2. package/dist/cli/completer.js +168 -0
  3. package/dist/cli/index.js +2 -0
  4. package/dist/cli/main.js +113 -0
  5. package/dist/cli/repl.js +987 -0
  6. package/dist/cli/security-commands.js +166 -0
  7. package/dist/cli/setup.js +229 -0
  8. package/dist/config/config.js +186 -0
  9. package/dist/config/defaults.js +91 -0
  10. package/dist/config/experts.js +15 -0
  11. package/dist/config/index.js +3 -0
  12. package/dist/config/security.js +193 -0
  13. package/dist/config/types.js +1 -0
  14. package/dist/core/agent-moe.js +98 -0
  15. package/dist/core/agent.js +461 -0
  16. package/dist/core/bootstrap.js +321 -0
  17. package/dist/core/index.js +2 -0
  18. package/dist/core/prompt-builder.js +55 -0
  19. package/dist/core/session-logger.js +122 -0
  20. package/dist/core/types.js +1 -0
  21. package/dist/i18n/en.json +461 -0
  22. package/dist/i18n/index.js +43 -0
  23. package/dist/i18n/ru.json +461 -0
  24. package/dist/index.js +22 -0
  25. package/dist/llm/image-utils.js +144 -0
  26. package/dist/llm/index.js +4 -0
  27. package/dist/llm/model-loader.js +78 -0
  28. package/dist/llm/openai-compat.js +324 -0
  29. package/dist/llm/orchestrator.js +194 -0
  30. package/dist/llm/provider.js +10 -0
  31. package/dist/llm/response.js +39 -0
  32. package/dist/llm/token-counter.js +39 -0
  33. package/dist/llm/types.js +1 -0
  34. package/dist/logger/app-logger.js +76 -0
  35. package/dist/logger/index.js +1 -0
  36. package/dist/main.js +2251 -724
  37. package/dist/migration/backup.js +45 -0
  38. package/dist/migration/detect.js +50 -0
  39. package/dist/migration/index.js +2 -0
  40. package/dist/modules/browser/actions.js +46 -0
  41. package/dist/modules/browser/cookie-store.js +24 -0
  42. package/dist/modules/browser/index.js +5 -0
  43. package/dist/modules/browser/module.js +28 -0
  44. package/dist/modules/browser/session.js +287 -0
  45. package/dist/modules/browser/snapshot.js +114 -0
  46. package/dist/modules/browser/types.js +9 -0
  47. package/dist/modules/context/history.js +15 -0
  48. package/dist/modules/context/index.js +1 -0
  49. package/dist/modules/context/manager.js +240 -0
  50. package/dist/modules/execution/auditor.js +72 -0
  51. package/dist/modules/execution/index.js +6 -0
  52. package/dist/modules/execution/module.js +337 -0
  53. package/dist/modules/execution/moe-executor.js +209 -0
  54. package/dist/modules/execution/plan-validator.js +153 -0
  55. package/dist/modules/execution/planner.js +35 -0
  56. package/dist/modules/execution/stuck-detector.js +134 -0
  57. package/dist/modules/execution/tracker.js +53 -0
  58. package/dist/modules/execution/types.js +1 -0
  59. package/dist/modules/execution/verifier.js +149 -0
  60. package/dist/modules/hallucination/confidence.js +54 -0
  61. package/dist/modules/hallucination/consistency.js +60 -0
  62. package/dist/modules/hallucination/detector.js +41 -0
  63. package/dist/modules/hallucination/factual.js +170 -0
  64. package/dist/modules/hallucination/index.js +4 -0
  65. package/dist/modules/index.js +5 -0
  66. package/dist/modules/indexer/cache.js +38 -0
  67. package/dist/modules/indexer/index.js +3 -0
  68. package/dist/modules/indexer/module.js +192 -0
  69. package/dist/modules/indexer/walker.js +101 -0
  70. package/dist/modules/mcp/client.js +393 -0
  71. package/dist/modules/mcp/index.js +3 -0
  72. package/dist/modules/mcp/module.js +146 -0
  73. package/dist/modules/mcp/registry.js +15 -0
  74. package/dist/modules/memory/index.js +1 -0
  75. package/dist/modules/memory/module.js +48 -0
  76. package/dist/modules/memory/search.js +40 -0
  77. package/dist/modules/memory/store.js +65 -0
  78. package/dist/modules/pipelines/engine.js +60 -0
  79. package/dist/modules/pipelines/index.js +3 -0
  80. package/dist/modules/pipelines/parser.js +53 -0
  81. package/dist/modules/pipelines/template.js +14 -0
  82. package/dist/modules/plugins/builtin/lint-on-write.js +121 -0
  83. package/dist/modules/plugins/builtin/notify.js +8 -0
  84. package/dist/modules/plugins/index.js +1 -0
  85. package/dist/modules/plugins/loader.js +28 -0
  86. package/dist/modules/plugins/manager.js +161 -0
  87. package/dist/modules/plugins/types.js +1 -0
  88. package/dist/modules/processes/detect.js +34 -0
  89. package/dist/modules/processes/index.js +3 -0
  90. package/dist/modules/processes/registry.js +148 -0
  91. package/dist/modules/processes/runner.js +124 -0
  92. package/dist/modules/registry.js +45 -0
  93. package/dist/modules/security/audit-log.js +116 -0
  94. package/dist/modules/security/audit-notifier.js +292 -0
  95. package/dist/modules/security/command-validator.js +185 -0
  96. package/dist/modules/security/content-scanner.js +52 -0
  97. package/dist/modules/security/data-sanitizer.js +97 -0
  98. package/dist/modules/security/encryption.js +240 -0
  99. package/dist/modules/security/index.js +14 -0
  100. package/dist/modules/security/network-validator.js +79 -0
  101. package/dist/modules/security/path-validator.js +155 -0
  102. package/dist/modules/security/rate-limiter.js +119 -0
  103. package/dist/modules/security/security-policies.js +393 -0
  104. package/dist/modules/security/session-encryption.js +193 -0
  105. package/dist/modules/security/session-isolation.js +95 -0
  106. package/dist/modules/session/index.js +3 -0
  107. package/dist/modules/session/manager.js +167 -0
  108. package/dist/modules/session/module.js +24 -0
  109. package/dist/modules/session/store.js +174 -0
  110. package/dist/modules/session/types.js +1 -0
  111. package/dist/modules/skills/index.js +3 -0
  112. package/dist/modules/skills/loader.js +72 -0
  113. package/dist/modules/skills/matcher.js +27 -0
  114. package/dist/modules/skills/module.js +143 -0
  115. package/dist/modules/types.js +1 -0
  116. package/dist/modules/updater/checker.js +32 -0
  117. package/dist/modules/updater/index.js +1 -0
  118. package/dist/modules/user-profile/compressor.js +16 -0
  119. package/dist/modules/user-profile/index.js +1 -0
  120. package/dist/modules/user-profile/profile.js +68 -0
  121. package/dist/tools/approve.js +32 -0
  122. package/dist/tools/attach-image.js +89 -0
  123. package/dist/tools/bash.js +140 -0
  124. package/dist/tools/browser.js +97 -0
  125. package/dist/tools/create-dir.js +56 -0
  126. package/dist/tools/delete-file.js +63 -0
  127. package/dist/tools/edit-file.js +77 -0
  128. package/dist/tools/executor.js +95 -0
  129. package/dist/tools/file-info.js +45 -0
  130. package/dist/tools/filter-tools.js +10 -0
  131. package/dist/tools/glob-tool.js +26 -0
  132. package/dist/tools/grep-tool.js +64 -0
  133. package/dist/tools/index.js +52 -0
  134. package/dist/tools/list-dir.js +47 -0
  135. package/dist/tools/load-skill.js +48 -0
  136. package/dist/tools/mcp-call.js +68 -0
  137. package/dist/tools/move-file.js +84 -0
  138. package/dist/tools/path-utils.js +51 -0
  139. package/dist/tools/pipeline-run.js +144 -0
  140. package/dist/tools/preview.js +2 -0
  141. package/dist/tools/process-kill.js +29 -0
  142. package/dist/tools/process-list.js +38 -0
  143. package/dist/tools/process-log.js +41 -0
  144. package/dist/tools/question.js +142 -0
  145. package/dist/tools/read-file.js +73 -0
  146. package/dist/tools/recall.js +110 -0
  147. package/dist/tools/registry.js +36 -0
  148. package/dist/tools/remember.js +67 -0
  149. package/dist/tools/scope-check.js +30 -0
  150. package/dist/tools/search-history.js +64 -0
  151. package/dist/tools/subagent.js +142 -0
  152. package/dist/tools/types.js +1 -0
  153. package/dist/tools/user-input.js +123 -0
  154. package/dist/tools/web-browse.js +57 -0
  155. package/dist/tools/web-fetch.js +72 -0
  156. package/dist/tools/web-search.js +59 -0
  157. package/dist/tools/write-file.js +80 -0
  158. package/dist/ui/box.js +81 -0
  159. package/dist/ui/colors.js +4 -0
  160. package/dist/ui/diff.js +185 -0
  161. package/dist/ui/index.js +6 -0
  162. package/dist/ui/md-formatter.js +212 -0
  163. package/dist/ui/output.js +13 -0
  164. package/dist/ui/renderer.js +141 -0
  165. package/dist/ui/spinner.js +70 -0
  166. package/dist/ui/table.js +144 -0
  167. package/package.json +4 -4
@@ -0,0 +1,209 @@
1
+ import { getExpertConfig } from '../../config/experts';
2
+ import { filterToolsByTags } from '../../tools/filter-tools';
3
+ const TRANSIENT_ERROR_PATTERNS = [
4
+ 'timeout', 'Timeout', 'TIMEOUT',
5
+ '5xx', '500', '502', '503',
6
+ 'network', 'Network',
7
+ 'ECONNREFUSED', 'ECONNRESET',
8
+ 'fetch failed',
9
+ 'abort', 'Abort',
10
+ ];
11
+ function isTransientError(error) {
12
+ return TRANSIENT_ERROR_PATTERNS.some(p => error.includes(p));
13
+ }
14
+ function sleep(ms) {
15
+ return new Promise(r => setTimeout(r, ms));
16
+ }
17
+ export function topologicalSort(subtasks) {
18
+ const sorted = [];
19
+ const remaining = new Set(subtasks.map(s => s.id));
20
+ const subtaskMap = new Map(subtasks.map(s => [s.id, s]));
21
+ while (remaining.size > 0) {
22
+ const ready = [];
23
+ for (const id of remaining) {
24
+ const sub = subtaskMap.get(id);
25
+ const depsSatisfied = (sub.depends_on || []).every(d => !remaining.has(d));
26
+ if (depsSatisfied) {
27
+ ready.push(sub);
28
+ }
29
+ }
30
+ if (ready.length === 0) {
31
+ break;
32
+ }
33
+ sorted.push(ready);
34
+ for (const r of ready) {
35
+ remaining.delete(r.id);
36
+ }
37
+ }
38
+ return sorted;
39
+ }
40
+ async function executeSubtask(subtask, deps, _sharedContext) {
41
+ const startTime = Date.now();
42
+ const expertConfig = getExpertConfig(deps.config, subtask.expert_tag);
43
+ if (!expertConfig) {
44
+ return {
45
+ subtaskId: subtask.id,
46
+ success: false,
47
+ summary: `Unknown expert_tag: ${subtask.expert_tag}`,
48
+ result: '',
49
+ error: `No expert config found for tag "${subtask.expert_tag}"`,
50
+ durationMs: Date.now() - startTime,
51
+ };
52
+ }
53
+ const subagentTool = deps.toolRegistry.get('subagent');
54
+ if (!subagentTool) {
55
+ return {
56
+ subtaskId: subtask.id,
57
+ success: false,
58
+ summary: 'Subagent tool not registered',
59
+ result: '',
60
+ error: 'Subagent tool not found in registry',
61
+ durationMs: Date.now() - startTime,
62
+ };
63
+ }
64
+ const allTools = deps.toolRegistry.getAll();
65
+ const filteredTools = filterToolsByTags(allTools, expertConfig.tool_tags);
66
+ if (filteredTools.length === 0) {
67
+ return {
68
+ subtaskId: subtask.id,
69
+ success: false,
70
+ summary: `No tools available for expert "${subtask.expert_tag}" (tags: ${expertConfig.tool_tags.join(', ')})`,
71
+ result: '',
72
+ error: 'No matching tools',
73
+ durationMs: Date.now() - startTime,
74
+ };
75
+ }
76
+ const maxAttempts = expertConfig.max_attempts || 3;
77
+ let lastError = '';
78
+ let lastResult = null;
79
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
80
+ try {
81
+ const allowedFiles = subtask.allowed_files || [];
82
+ const readOnlyFiles = subtask.read_only_files || [];
83
+ const scopePrompt = allowedFiles.length > 0 || readOnlyFiles.length > 0
84
+ ? `\n\nAllowed files to write: ${allowedFiles.join(', ') || '(none)'}\nRead-only files: ${readOnlyFiles.join(', ') || '(none)'}`
85
+ : '';
86
+ const taskPrompt = `${subtask.description}\n\nExpected output: ${subtask.expected_output}\nSuccess criteria:\n${(subtask.success_criteria || []).map((c) => `- ${c}`).join('\n')}${scopePrompt}`;
87
+ const subagentArgs = {
88
+ task: taskPrompt,
89
+ allowed_files: allowedFiles,
90
+ read_only_files: readOnlyFiles,
91
+ tool_tags: expertConfig.tool_tags,
92
+ };
93
+ const result = await subagentTool.handler({
94
+ config: deps.config,
95
+ baseDir: deps.baseDir,
96
+ logger: deps.logger,
97
+ llmProvider: deps.llmProvider,
98
+ toolExecutor: deps.toolExecutor,
99
+ }, subagentArgs);
100
+ if (result.success) {
101
+ return {
102
+ subtaskId: subtask.id,
103
+ success: true,
104
+ summary: `Completed: ${subtask.id}`,
105
+ result: result.output,
106
+ durationMs: Date.now() - startTime,
107
+ };
108
+ }
109
+ lastError = result.output;
110
+ lastResult = result;
111
+ if (isTransientError(lastError) && attempt < maxAttempts) {
112
+ const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
113
+ deps.logger.debug(`Retrying subtask "${subtask.id}" (attempt ${attempt}/${maxAttempts}) after ${delay}ms: transient error`);
114
+ await sleep(delay);
115
+ continue;
116
+ }
117
+ return {
118
+ subtaskId: subtask.id,
119
+ success: false,
120
+ summary: `Failed: ${subtask.id}`,
121
+ result: result.output,
122
+ error: result.output,
123
+ durationMs: Date.now() - startTime,
124
+ };
125
+ }
126
+ catch (e) {
127
+ lastError = e.message;
128
+ if (isTransientError(lastError) && attempt < maxAttempts) {
129
+ const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
130
+ deps.logger.debug(`Retrying subtask "${subtask.id}" (attempt ${attempt}/${maxAttempts}) after ${delay}ms: ${lastError}`);
131
+ await sleep(delay);
132
+ continue;
133
+ }
134
+ return {
135
+ subtaskId: subtask.id,
136
+ success: false,
137
+ summary: `Error: ${subtask.id}`,
138
+ result: '',
139
+ error: e.message,
140
+ durationMs: Date.now() - startTime,
141
+ };
142
+ }
143
+ }
144
+ return {
145
+ subtaskId: subtask.id,
146
+ success: false,
147
+ summary: `Failed after ${maxAttempts} attempts: ${subtask.id}`,
148
+ result: '',
149
+ error: lastError,
150
+ durationMs: Date.now() - startTime,
151
+ };
152
+ }
153
+ export class MoEExecutor {
154
+ deps;
155
+ constructor(deps) {
156
+ this.deps = deps;
157
+ }
158
+ async executePlan(plan) {
159
+ const results = [];
160
+ const errors = [];
161
+ const warnings = [];
162
+ const waves = topologicalSort(plan.subtasks);
163
+ if (waves.length === 0) {
164
+ return { success: false, results: [], errors: ['Failed to topologically sort subtasks (possible cycle)'], warnings: [] };
165
+ }
166
+ // Verify all subtasks are included — catch silent drops from unresolved dependencies
167
+ const sortedCount = waves.flat().length;
168
+ if (sortedCount < plan.subtasks.length) {
169
+ const missing = plan.subtasks
170
+ .filter(s => !waves.flat().some(w => w.id === s.id))
171
+ .map(s => s.id);
172
+ return {
173
+ success: false,
174
+ results: [],
175
+ errors: [`Missing subtasks after topological sort: ${missing.join(', ')} (dangling or invalid depends_on)`],
176
+ warnings: [],
177
+ };
178
+ }
179
+ for (let waveIdx = 0; waveIdx < waves.length; waveIdx++) {
180
+ const wave = waves[waveIdx];
181
+ const wavePromises = wave.map(subtask => executeSubtask(subtask, this.deps, plan.shared_context)
182
+ .then(result => {
183
+ results.push(result);
184
+ return result;
185
+ })
186
+ .catch(e => {
187
+ const errResult = {
188
+ subtaskId: subtask.id,
189
+ success: false,
190
+ summary: `Unhandled error: ${subtask.id}`,
191
+ result: '',
192
+ error: e.message,
193
+ durationMs: 0,
194
+ };
195
+ results.push(errResult);
196
+ return errResult;
197
+ }));
198
+ await Promise.all(wavePromises);
199
+ }
200
+ const failed = results.filter(r => !r.success);
201
+ if (failed.length > 0) {
202
+ errors.push(...failed.map(f => `[${f.subtaskId}] ${f.error || f.summary}`));
203
+ }
204
+ return { success: failed.length === 0, results, errors, warnings };
205
+ }
206
+ getChainMaxAttempts() {
207
+ return 3;
208
+ }
209
+ }
@@ -0,0 +1,153 @@
1
+ export function validatePlan(plan, config) {
2
+ const errors = [];
3
+ const warnings = [];
4
+ const autoFixes = [];
5
+ if (!plan.subtasks || plan.subtasks.length === 0) {
6
+ return { valid: false, errors: ['Plan has no subtasks'], warnings: [], autoFixes: [] };
7
+ }
8
+ errors.push(...expertTagsExist(plan.subtasks, config));
9
+ errors.push(...hasCycle(plan.subtasks));
10
+ const overlapErrors = hasAllowedFilesOverlap(plan.subtasks);
11
+ errors.push(...overlapErrors);
12
+ const readOverlaps = deleteReadOverlap(plan.subtasks);
13
+ for (const overlap of readOverlaps) {
14
+ if (overlap.canAutoFix) {
15
+ autoFixes.push({ subtaskId: overlap.subtaskId, fix: `Add depends_on: ${overlap.dependsOn}` });
16
+ }
17
+ else if (overlap.error) {
18
+ errors.push(overlap.error);
19
+ }
20
+ }
21
+ return {
22
+ valid: errors.length === 0,
23
+ errors,
24
+ warnings,
25
+ autoFixes,
26
+ };
27
+ }
28
+ export function expertTagsExist(subtasks, config) {
29
+ const errors = [];
30
+ const knownExperts = new Set(Object.keys(config.experts || {}));
31
+ for (const subtask of subtasks) {
32
+ if (!knownExperts.has(subtask.expert_tag)) {
33
+ errors.push(`Subtask "${subtask.id}" references unknown expert_tag "${subtask.expert_tag}". Known experts: ${Array.from(knownExperts).join(', ')}`);
34
+ }
35
+ }
36
+ return errors;
37
+ }
38
+ export function hasCycle(subtasks) {
39
+ const edges = new Map();
40
+ for (const s of subtasks) {
41
+ edges.set(s.id, s.depends_on || []);
42
+ }
43
+ const visited = new Set();
44
+ const inStack = new Set();
45
+ function dfs(node) {
46
+ if (inStack.has(node))
47
+ return true;
48
+ if (visited.has(node))
49
+ return false;
50
+ visited.add(node);
51
+ inStack.add(node);
52
+ const deps = edges.get(node) || [];
53
+ for (const dep of deps) {
54
+ if (edges.has(dep) && dfs(dep))
55
+ return true;
56
+ }
57
+ inStack.delete(node);
58
+ return false;
59
+ }
60
+ const errors = [];
61
+ for (const s of subtasks) {
62
+ visited.clear();
63
+ inStack.clear();
64
+ if (dfs(s.id)) {
65
+ errors.push(`Cycle detected involving subtask "${s.id}"`);
66
+ break;
67
+ }
68
+ }
69
+ return errors;
70
+ }
71
+ export function hasAllowedFilesOverlap(subtasks) {
72
+ const errors = [];
73
+ const writeFiles = new Map();
74
+ for (const s of subtasks) {
75
+ for (const f of s.allowed_files || []) {
76
+ if (!writeFiles.has(f)) {
77
+ writeFiles.set(f, []);
78
+ }
79
+ writeFiles.get(f).push(s.id);
80
+ }
81
+ }
82
+ for (const [file, writers] of writeFiles) {
83
+ if (writers.length > 1) {
84
+ const noDep = writers.filter(w => {
85
+ const sub = subtasks.find(s => s.id === w);
86
+ return sub && !sub.depends_on?.some(d => writers.includes(d));
87
+ });
88
+ if (noDep.length > 1) {
89
+ errors.push(`Write-write overlap on "${file}" between subtasks: ${writers.join(', ')} without dependency chain`);
90
+ }
91
+ }
92
+ }
93
+ return errors;
94
+ }
95
+ export function deleteReadOverlap(subtasks) {
96
+ const results = [];
97
+ for (let i = 0; i < subtasks.length; i++) {
98
+ for (let j = 0; j < subtasks.length; j++) {
99
+ if (i === j)
100
+ continue;
101
+ const writer = subtasks[i];
102
+ const reader = subtasks[j];
103
+ if (!writer.allowed_files || !reader.read_only_files)
104
+ continue;
105
+ const readFiles = new Set(reader.read_only_files);
106
+ const writeFiles = writer.allowed_files;
107
+ const overlapping = writeFiles.filter(f => {
108
+ for (const rf of readFiles) {
109
+ if (f.startsWith(rf) || rf.startsWith(f))
110
+ return true;
111
+ }
112
+ return false;
113
+ });
114
+ if (overlapping.length > 0 && !reader.depends_on?.includes(writer.id)) {
115
+ const canAutoFix = !reader.depends_on || reader.depends_on.length === 0;
116
+ if (canAutoFix) {
117
+ results.push({
118
+ subtaskId: reader.id,
119
+ dependsOn: writer.id,
120
+ canAutoFix: true,
121
+ });
122
+ }
123
+ else {
124
+ results.push({
125
+ subtaskId: reader.id,
126
+ dependsOn: writer.id,
127
+ canAutoFix: false,
128
+ error: `Read-after-write overlap between "${writer.id}" (writer) and "${reader.id}" (reader) on "${overlapping.join(', ')}" — add depends_on: [${writer.id}]`,
129
+ });
130
+ }
131
+ }
132
+ }
133
+ }
134
+ return results;
135
+ }
136
+ export function applyAutoFixes(plan, autoFixes) {
137
+ const fixed = { ...plan, subtasks: plan.subtasks.map(s => ({ ...s })) };
138
+ for (const fix of autoFixes) {
139
+ const sub = fixed.subtasks.find(s => s.id === fix.subtaskId);
140
+ if (!sub)
141
+ continue;
142
+ const dependsOnMatch = fix.fix.match(/depends_on:\s*(\S+)/);
143
+ if (dependsOnMatch) {
144
+ const dep = dependsOnMatch[1];
145
+ if (!sub.depends_on)
146
+ sub.depends_on = [];
147
+ if (!sub.depends_on.includes(dep)) {
148
+ sub.depends_on.push(dep);
149
+ }
150
+ }
151
+ }
152
+ return fixed;
153
+ }
@@ -0,0 +1,35 @@
1
+ export class PlanCreator {
2
+ static isMultiStep(task) {
3
+ const fileCount = (task.match(/\b[\w./-]+\.[a-z]+\b/gi) || []).length;
4
+ if (fileCount > 1)
5
+ return true;
6
+ const actionWords = ['implement', 'create', 'add', 'build', 'setup', 'configure', 'write', 'make', 'develop'];
7
+ const words = task.split(/\s+/);
8
+ const hasActionWord = actionWords.some(w => task.toLowerCase().includes(w));
9
+ return hasActionWord && words.length > 8;
10
+ }
11
+ static createPlan(title, stepDescriptions) {
12
+ return {
13
+ title,
14
+ steps: stepDescriptions.map((desc, i) => ({
15
+ id: i + 1,
16
+ description: desc,
17
+ status: 'pending',
18
+ })),
19
+ createdAt: new Date().toISOString(),
20
+ };
21
+ }
22
+ static toPromptBlock(plan, currentStepIndex) {
23
+ const lines = [`[Plan: ${plan.title}] (steps: ${plan.steps.filter(s => s.status === 'done').length}/${plan.steps.length} done, current: step ${currentStepIndex + 1})`];
24
+ for (const step of plan.steps) {
25
+ const icon = step.status === 'done' ? '[x]' :
26
+ step.status === 'in_progress' ? '[*]' :
27
+ step.status === 'failed' ? '[!]' :
28
+ step.status === 'skipped' ? '[-]' :
29
+ '[ ]';
30
+ const note = step.note ? ` — ${step.note}` : '';
31
+ lines.push(`${icon} ${step.id}. ${step.description}${note}`);
32
+ }
33
+ return lines.join('\n');
34
+ }
35
+ }
@@ -0,0 +1,134 @@
1
+ import { t } from '../../i18n/index';
2
+ export class StuckDetector {
3
+ threshold;
4
+ errorThreshold;
5
+ iterationsOnCurrentStep = 0;
6
+ currentStepId = null;
7
+ toolErrors = new Map();
8
+ currentStepDescription = '';
9
+ recentToolCalls = [];
10
+ maxRecentCalls = 10;
11
+ repetitionThreshold = 3;
12
+ consecutiveFailures = 0;
13
+ lastFailedTool = '';
14
+ constructor(threshold = 8, errorThreshold = 3) {
15
+ this.threshold = threshold;
16
+ this.errorThreshold = errorThreshold;
17
+ }
18
+ recordIteration(stepId) {
19
+ if (stepId === this.currentStepId) {
20
+ this.iterationsOnCurrentStep++;
21
+ }
22
+ else {
23
+ this.currentStepId = stepId;
24
+ this.iterationsOnCurrentStep = 1;
25
+ }
26
+ }
27
+ recordToolCall(name, args) {
28
+ const argsKey = JSON.stringify(args);
29
+ this.recentToolCalls.push({ name, argsKey });
30
+ if (this.recentToolCalls.length > this.maxRecentCalls) {
31
+ this.recentToolCalls.shift();
32
+ }
33
+ }
34
+ recordToolError(toolName) {
35
+ this.toolErrors.set(toolName, (this.toolErrors.get(toolName) || 0) + 1);
36
+ this.consecutiveFailures++;
37
+ this.lastFailedTool = toolName;
38
+ }
39
+ recordToolSuccess() {
40
+ this.consecutiveFailures = 0;
41
+ this.lastFailedTool = '';
42
+ }
43
+ setCurrentStep(stepId, description) {
44
+ if (stepId !== this.currentStepId) {
45
+ this.currentStepId = stepId;
46
+ this.iterationsOnCurrentStep = 1;
47
+ }
48
+ this.currentStepDescription = description;
49
+ }
50
+ isStuck() {
51
+ return this.iterationsOnCurrentStep > this.threshold;
52
+ }
53
+ hasRepetitiveErrors(toolName) {
54
+ if (toolName) {
55
+ return (this.toolErrors.get(toolName) || 0) >= this.errorThreshold;
56
+ }
57
+ return Array.from(this.toolErrors.values()).some(c => c >= this.errorThreshold);
58
+ }
59
+ hasRepetitiveToolCalls() {
60
+ if (this.recentToolCalls.length < this.repetitionThreshold)
61
+ return false;
62
+ const last = this.recentToolCalls[this.recentToolCalls.length - 1];
63
+ let count = 1;
64
+ for (let i = this.recentToolCalls.length - 2; i >= 0; i--) {
65
+ if (this.recentToolCalls[i].name === last.name && this.recentToolCalls[i].argsKey === last.argsKey) {
66
+ count++;
67
+ }
68
+ else {
69
+ break;
70
+ }
71
+ }
72
+ return count >= this.repetitionThreshold;
73
+ }
74
+ hasConsecutiveFailures() {
75
+ return this.consecutiveFailures >= this.errorThreshold;
76
+ }
77
+ getConsecutiveFailuresCount() {
78
+ return this.consecutiveFailures;
79
+ }
80
+ getRepetitiveToolMessage() {
81
+ if (!this.hasRepetitiveToolCalls())
82
+ return '';
83
+ const last = this.recentToolCalls[this.recentToolCalls.length - 1];
84
+ return t('exec.repetitive_tool', { tool: last.name, count: this.repetitionThreshold });
85
+ }
86
+ getStuckReason() {
87
+ if (this.isStuck()) {
88
+ return t('exec.stuck', { stepId: String(this.currentStepId), description: this.currentStepDescription, iterations: this.iterationsOnCurrentStep });
89
+ }
90
+ const errorTool = Array.from(this.toolErrors.entries()).find(([_, c]) => c >= this.errorThreshold);
91
+ if (errorTool) {
92
+ return t('exec.tool_errors', { tool: errorTool[0], count: errorTool[1] });
93
+ }
94
+ return '';
95
+ }
96
+ getRecoveryMessage() {
97
+ if (this.isStuck()) {
98
+ return t('exec.stuck_recovery', { iterations: this.iterationsOnCurrentStep });
99
+ }
100
+ // Per-tool error recovery (more specific — e.g., "bash failed 3 times")
101
+ const errorTool = Array.from(this.toolErrors.entries()).find(([_, c]) => c >= this.errorThreshold);
102
+ if (errorTool) {
103
+ return t('exec.tool_errors_recovery', { tool: errorTool[0], count: errorTool[1] });
104
+ }
105
+ // Consecutive failures from different tools (generic — e.g., "5 consecutive failures")
106
+ if (this.hasConsecutiveFailures()) {
107
+ return t('exec.consecutive_failures_recovery', { count: this.consecutiveFailures });
108
+ }
109
+ if (this.hasRepetitiveToolCalls()) {
110
+ return this.getRepetitiveToolMessage();
111
+ }
112
+ return '';
113
+ }
114
+ checkOffTrack(toolName, call) {
115
+ if (!this.currentStepDescription)
116
+ return null;
117
+ const toolArgStr = JSON.stringify(call.arguments).toLowerCase();
118
+ const pathInStep = (this.currentStepDescription.match(/\b[\w./-]+\.[a-z]+/gi) || [])
119
+ .map(p => p.toLowerCase());
120
+ const pathInCall = (toolArgStr.match(/\b[\w./-]+\.[a-z]+/gi) || [])
121
+ .map(p => p.toLowerCase());
122
+ const overlaps = pathInCall.some(p => pathInStep.some(s => p.includes(s) || s.includes(p)));
123
+ if (!overlaps && pathInStep.length > 0 && pathInCall.length > 0) {
124
+ return t('exec.off_track', { stepId: String(this.currentStepId), description: this.currentStepDescription, tool: toolName });
125
+ }
126
+ return null;
127
+ }
128
+ reset() {
129
+ this.iterationsOnCurrentStep = 0;
130
+ this.toolErrors.clear();
131
+ this.consecutiveFailures = 0;
132
+ this.lastFailedTool = '';
133
+ }
134
+ }
@@ -0,0 +1,53 @@
1
+ import { PlanCreator } from './planner';
2
+ export class PlanTracker {
3
+ plan;
4
+ currentStepIndex = 0;
5
+ constructor(plan) {
6
+ this.plan = plan;
7
+ }
8
+ getPlan() {
9
+ return this.plan;
10
+ }
11
+ getCurrentStepIndex() {
12
+ return this.currentStepIndex;
13
+ }
14
+ getCurrentStep() {
15
+ return this.plan.steps[this.currentStepIndex];
16
+ }
17
+ getStep(id) {
18
+ return this.plan.steps.find(s => s.id === id);
19
+ }
20
+ updateStepStatus(id, status) {
21
+ const step = this.getStep(id);
22
+ if (step)
23
+ step.status = status;
24
+ }
25
+ addNote(id, note) {
26
+ const step = this.getStep(id);
27
+ if (step)
28
+ step.note = note;
29
+ }
30
+ advance() {
31
+ if (this.currentStepIndex < this.plan.steps.length - 1) {
32
+ this.currentStepIndex++;
33
+ this.plan.steps[this.currentStepIndex].status = 'in_progress';
34
+ return true;
35
+ }
36
+ return false;
37
+ }
38
+ isComplete() {
39
+ return this.plan.steps.every(s => s.status === 'done' || s.status === 'skipped');
40
+ }
41
+ getProgressString() {
42
+ const done = this.plan.steps.filter(s => s.status === 'done').length;
43
+ const total = this.plan.steps.length;
44
+ const pct = total > 0 ? Math.round((done / total) * 100) : 0;
45
+ const barWidth = 10;
46
+ const filled = Math.round((done / total) * barWidth);
47
+ const bar = '█'.repeat(filled) + '░'.repeat(barWidth - filled);
48
+ return `[Plan: ${this.plan.title}] ${done}/${total} ${bar} ${pct}%`;
49
+ }
50
+ toPromptBlock() {
51
+ return PlanCreator.toPromptBlock(this.plan, this.currentStepIndex);
52
+ }
53
+ }
@@ -0,0 +1 @@
1
+ export {};