micro-models-agent 0.55.0 → 0.56.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 (232) hide show
  1. package/README.md +358 -358
  2. package/dist/certification/certifications.json +493 -493
  3. package/dist/main.js +2301 -1213
  4. package/dist/modules/browser/bridge-server.mjs +219 -202
  5. package/dist/skills/builtin/git.md +36 -36
  6. package/dist/skills/builtin/typescript.md +35 -35
  7. package/package.json +1 -1
  8. package/dist/cli/commands.js +0 -447
  9. package/dist/cli/completer.js +0 -167
  10. package/dist/cli/index.js +0 -2
  11. package/dist/cli/main.js +0 -153
  12. package/dist/cli/plugin-commands.js +0 -36
  13. package/dist/cli/repl-commands.js +0 -761
  14. package/dist/cli/repl.js +0 -702
  15. package/dist/cli/run-result.js +0 -33
  16. package/dist/cli/security-commands.js +0 -164
  17. package/dist/cli/setup.js +0 -237
  18. package/dist/config/config.js +0 -276
  19. package/dist/config/defaults.js +0 -141
  20. package/dist/config/domains.js +0 -179
  21. package/dist/config/experts.js +0 -15
  22. package/dist/config/index.js +0 -4
  23. package/dist/config/security.js +0 -213
  24. package/dist/config/types.js +0 -1
  25. package/dist/core/agent-moe.js +0 -102
  26. package/dist/core/agent.js +0 -1018
  27. package/dist/core/bootstrap.js +0 -481
  28. package/dist/core/crash-handler.js +0 -51
  29. package/dist/core/environment.js +0 -199
  30. package/dist/core/index.js +0 -2
  31. package/dist/core/prompt-builder.js +0 -76
  32. package/dist/core/session-logger.js +0 -251
  33. package/dist/core/types.js +0 -1
  34. package/dist/core/version.js +0 -26
  35. package/dist/core/workspace.js +0 -76
  36. package/dist/i18n/en.json +0 -679
  37. package/dist/i18n/index.js +0 -46
  38. package/dist/i18n/ru.json +0 -679
  39. package/dist/index.js +0 -22
  40. package/dist/llm/image-utils.js +0 -143
  41. package/dist/llm/index.js +0 -4
  42. package/dist/llm/model-loader.js +0 -78
  43. package/dist/llm/openai-compat.js +0 -497
  44. package/dist/llm/orchestrator.js +0 -200
  45. package/dist/llm/provider.js +0 -10
  46. package/dist/llm/response.js +0 -39
  47. package/dist/llm/token-counter.js +0 -39
  48. package/dist/llm/types.js +0 -1
  49. package/dist/logger/app-logger.js +0 -189
  50. package/dist/logger/file-log.js +0 -151
  51. package/dist/logger/index.js +0 -1
  52. package/dist/migration/backup.js +0 -45
  53. package/dist/migration/detect.js +0 -50
  54. package/dist/migration/index.js +0 -2
  55. package/dist/modules/artifacts/store.js +0 -61
  56. package/dist/modules/browser/actions.js +0 -76
  57. package/dist/modules/browser/bridge-client.js +0 -199
  58. package/dist/modules/browser/bridge-path.js +0 -10
  59. package/dist/modules/browser/cookie-store.js +0 -24
  60. package/dist/modules/browser/driver.js +0 -136
  61. package/dist/modules/browser/index.js +0 -7
  62. package/dist/modules/browser/module.js +0 -29
  63. package/dist/modules/browser/session.js +0 -342
  64. package/dist/modules/browser/snapshot.js +0 -148
  65. package/dist/modules/browser/types.js +0 -12
  66. package/dist/modules/certification/cli.js +0 -213
  67. package/dist/modules/certification/fact-checker.js +0 -82
  68. package/dist/modules/certification/loader.js +0 -106
  69. package/dist/modules/certification/manifest.js +0 -58
  70. package/dist/modules/certification/runner.js +0 -245
  71. package/dist/modules/certification/scenarios.js +0 -407
  72. package/dist/modules/certification/types.js +0 -1
  73. package/dist/modules/context/chunk-query.js +0 -100
  74. package/dist/modules/context/fact-extractor.js +0 -168
  75. package/dist/modules/context/history.js +0 -15
  76. package/dist/modules/context/index.js +0 -1
  77. package/dist/modules/context/manager.js +0 -440
  78. package/dist/modules/execution/audit-runners.js +0 -206
  79. package/dist/modules/execution/auditor.js +0 -218
  80. package/dist/modules/execution/execution-plugin.js +0 -431
  81. package/dist/modules/execution/index.js +0 -8
  82. package/dist/modules/execution/module.js +0 -625
  83. package/dist/modules/execution/moe-executor.js +0 -304
  84. package/dist/modules/execution/plan-coverage.js +0 -68
  85. package/dist/modules/execution/plan-persister.js +0 -46
  86. package/dist/modules/execution/plan-store.js +0 -196
  87. package/dist/modules/execution/plan-tool.js +0 -677
  88. package/dist/modules/execution/plan-validator.js +0 -153
  89. package/dist/modules/execution/planner.js +0 -94
  90. package/dist/modules/execution/stuck-detector.js +0 -746
  91. package/dist/modules/execution/tracker.js +0 -69
  92. package/dist/modules/execution/types.js +0 -1
  93. package/dist/modules/execution/verifier.js +0 -235
  94. package/dist/modules/execution/windows-commands.js +0 -41
  95. package/dist/modules/hallucination/confidence.js +0 -66
  96. package/dist/modules/hallucination/consistency.js +0 -26
  97. package/dist/modules/hallucination/detector.js +0 -47
  98. package/dist/modules/hallucination/factual.js +0 -169
  99. package/dist/modules/hallucination/index.js +0 -5
  100. package/dist/modules/hallucination/js-identifiers.js +0 -262
  101. package/dist/modules/hallucination/llm-judge.js +0 -101
  102. package/dist/modules/index.js +0 -5
  103. package/dist/modules/indexer/cache.js +0 -40
  104. package/dist/modules/indexer/index.js +0 -3
  105. package/dist/modules/indexer/module.js +0 -246
  106. package/dist/modules/indexer/project-profile.js +0 -183
  107. package/dist/modules/indexer/walker.js +0 -101
  108. package/dist/modules/lsp/check-tool.js +0 -58
  109. package/dist/modules/lsp/client.js +0 -389
  110. package/dist/modules/lsp/command.js +0 -60
  111. package/dist/modules/lsp/config.js +0 -135
  112. package/dist/modules/lsp/index.js +0 -3
  113. package/dist/modules/lsp/module.js +0 -260
  114. package/dist/modules/lsp/probe.js +0 -86
  115. package/dist/modules/lsp/project-root.js +0 -32
  116. package/dist/modules/lsp/startup-check.js +0 -144
  117. package/dist/modules/lsp/types.js +0 -1
  118. package/dist/modules/mcp/client.js +0 -399
  119. package/dist/modules/mcp/index.js +0 -3
  120. package/dist/modules/mcp/module.js +0 -142
  121. package/dist/modules/mcp/registry.js +0 -15
  122. package/dist/modules/memory/index.js +0 -1
  123. package/dist/modules/memory/module.js +0 -96
  124. package/dist/modules/memory/search.js +0 -42
  125. package/dist/modules/memory/store.js +0 -69
  126. package/dist/modules/pipelines/engine.js +0 -60
  127. package/dist/modules/pipelines/index.js +0 -3
  128. package/dist/modules/pipelines/parser.js +0 -56
  129. package/dist/modules/pipelines/template.js +0 -14
  130. package/dist/modules/plugins/builtin/lint-on-write.js +0 -334
  131. package/dist/modules/plugins/builtin/notify.js +0 -9
  132. package/dist/modules/plugins/index.js +0 -1
  133. package/dist/modules/plugins/loader.js +0 -70
  134. package/dist/modules/plugins/manager.js +0 -261
  135. package/dist/modules/plugins/types.js +0 -1
  136. package/dist/modules/pricing/index.js +0 -61
  137. package/dist/modules/pricing/prices.js +0 -129
  138. package/dist/modules/processes/detect.js +0 -34
  139. package/dist/modules/processes/index.js +0 -2
  140. package/dist/modules/processes/registry.js +0 -327
  141. package/dist/modules/processes/runner.js +0 -23
  142. package/dist/modules/providers/create.js +0 -22
  143. package/dist/modules/providers/fallback.js +0 -79
  144. package/dist/modules/providers/health.js +0 -46
  145. package/dist/modules/providers/index.js +0 -5
  146. package/dist/modules/providers/manager.js +0 -161
  147. package/dist/modules/providers/presets.js +0 -128
  148. package/dist/modules/providers/registry.js +0 -22
  149. package/dist/modules/providers/types.js +0 -1
  150. package/dist/modules/registry.js +0 -48
  151. package/dist/modules/security/audit-log.js +0 -136
  152. package/dist/modules/security/audit-notifier.js +0 -292
  153. package/dist/modules/security/command-validator.js +0 -219
  154. package/dist/modules/security/content-scanner.js +0 -53
  155. package/dist/modules/security/data-sanitizer.js +0 -89
  156. package/dist/modules/security/encryption.js +0 -242
  157. package/dist/modules/security/index.js +0 -14
  158. package/dist/modules/security/network-validator.js +0 -88
  159. package/dist/modules/security/path-validator.js +0 -203
  160. package/dist/modules/security/rate-limiter.js +0 -119
  161. package/dist/modules/security/security-policies.js +0 -531
  162. package/dist/modules/security/session-encryption.js +0 -210
  163. package/dist/modules/security/session-isolation.js +0 -95
  164. package/dist/modules/session/index.js +0 -3
  165. package/dist/modules/session/manager.js +0 -172
  166. package/dist/modules/session/module.js +0 -24
  167. package/dist/modules/session/store.js +0 -222
  168. package/dist/modules/session/types.js +0 -1
  169. package/dist/modules/skills/index.js +0 -2
  170. package/dist/modules/skills/loader.js +0 -72
  171. package/dist/modules/skills/matcher.js +0 -27
  172. package/dist/modules/skills/module.js +0 -129
  173. package/dist/modules/types.js +0 -1
  174. package/dist/modules/updater/checker.js +0 -96
  175. package/dist/modules/updater/index.js +0 -2
  176. package/dist/modules/updater/module.js +0 -116
  177. package/dist/modules/user-profile/compressor.js +0 -16
  178. package/dist/modules/user-profile/index.js +0 -1
  179. package/dist/modules/user-profile/profile.js +0 -68
  180. package/dist/tools/approve.js +0 -33
  181. package/dist/tools/attach-image.js +0 -101
  182. package/dist/tools/bash.js +0 -519
  183. package/dist/tools/browser.js +0 -115
  184. package/dist/tools/chunk-query.js +0 -100
  185. package/dist/tools/create-dir.js +0 -56
  186. package/dist/tools/delete-file.js +0 -63
  187. package/dist/tools/download-file.js +0 -117
  188. package/dist/tools/edit-file.js +0 -80
  189. package/dist/tools/enable-tools.js +0 -59
  190. package/dist/tools/executor.js +0 -154
  191. package/dist/tools/file-info.js +0 -47
  192. package/dist/tools/filter-tools.js +0 -17
  193. package/dist/tools/glob-tool.js +0 -27
  194. package/dist/tools/grep-tool.js +0 -125
  195. package/dist/tools/hidden-tools-block.js +0 -37
  196. package/dist/tools/index.js +0 -78
  197. package/dist/tools/list-dir.js +0 -49
  198. package/dist/tools/load-skill.js +0 -43
  199. package/dist/tools/mcp-call.js +0 -69
  200. package/dist/tools/move-file.js +0 -86
  201. package/dist/tools/path-utils.js +0 -101
  202. package/dist/tools/pipeline-run.js +0 -145
  203. package/dist/tools/preview.js +0 -2
  204. package/dist/tools/process-kill.js +0 -40
  205. package/dist/tools/process-list.js +0 -37
  206. package/dist/tools/process-log.js +0 -54
  207. package/dist/tools/question.js +0 -141
  208. package/dist/tools/read-file.js +0 -179
  209. package/dist/tools/recall.js +0 -118
  210. package/dist/tools/registry.js +0 -47
  211. package/dist/tools/remember.js +0 -68
  212. package/dist/tools/scope-check.js +0 -32
  213. package/dist/tools/search-history.js +0 -85
  214. package/dist/tools/subagent.js +0 -196
  215. package/dist/tools/types.js +0 -1
  216. package/dist/tools/user-input.js +0 -123
  217. package/dist/tools/web-browse.js +0 -87
  218. package/dist/tools/web-fetch.js +0 -119
  219. package/dist/tools/web-search.js +0 -105
  220. package/dist/tools/write-file.js +0 -82
  221. package/dist/ui/box.js +0 -77
  222. package/dist/ui/colors.js +0 -4
  223. package/dist/ui/diff.js +0 -178
  224. package/dist/ui/index.js +0 -6
  225. package/dist/ui/line-editor.js +0 -822
  226. package/dist/ui/line-math.js +0 -73
  227. package/dist/ui/md-formatter.js +0 -212
  228. package/dist/ui/output.js +0 -13
  229. package/dist/ui/plan-view.js +0 -103
  230. package/dist/ui/renderer.js +0 -259
  231. package/dist/ui/spinner.js +0 -70
  232. package/dist/ui/table.js +0 -144
@@ -1,625 +0,0 @@
1
- import { t } from "../../i18n/index";
2
- import { PlanTracker } from "./tracker";
3
- import { StepVerifier } from "./verifier";
4
- import { StuckDetector, isSearchableError, buildSearchQuery } from "./stuck-detector";
5
- import { Auditor, findExistingFile } from "./auditor";
6
- import { PlanStore } from "./plan-store";
7
- import { getMessageText } from "../../llm/provider";
8
- import { extractFileLikeTokens, stripUrls } from "../hallucination/js-identifiers";
9
- import { existsSync, readFileSync } from "fs";
10
- import { resolve } from "path";
11
- import { performWebSearch } from "../../tools/web-search";
12
- import { getSessionSecurityConfig } from "../security/session-isolation";
13
- import { createPlanToolDefinitions } from "./plan-tool";
14
- import { createExecutionPlugin, STUCK_RECOVERY_COOLDOWN, STUCK_WARN_REPEAT_EVERY, } from "./execution-plugin";
15
- /**
16
- * Minimum interval between automatic error searches. The spec asked for a
17
- * STUCK_RECOVERY_COOLDOWN-iteration cap, but onAfterTool has no iteration
18
- * counter (executor context), so the same anti-spam protection is
19
- * time-based. Injectable via the constructor for tests (0 disables it).
20
- */
21
- const ERROR_SEARCH_MIN_INTERVAL_MS = 30000;
22
- export class ExecutionModule {
23
- name = "execution";
24
- tracker = null;
25
- verifier;
26
- stuckDetector;
27
- auditor;
28
- store;
29
- baseDir;
30
- // Skip the first audit after restoring a plan from disk — gives the user
31
- // one chance to change the subject before the audit gate locks in.
32
- _auditSkipsRemaining = 0;
33
- /**
34
- * The last plan that was COMPLETED and auto-archived. `plan update` on the
35
- * final step clears the tracker, which used to make runFinalAudit() return
36
- * null and silently skip the final audit (tests + tsc + file checks) for a
37
- * finished task. Keep the completed plan so the audit gate still runs.
38
- */
39
- completedPlan = null;
40
- /**
41
- * Deferred <system-summary> messages. Injected by onBeforeTool/onAfterTool
42
- * but flushed in onBeforeThink, so they never land between an assistant
43
- * tool_call message and its tool results (which breaks message pairing and
44
- * buries the warnings the model should react to).
45
- */
46
- pendingMessages = [];
47
- // Per-command failure counters for forbidden Windows commands (grep/sed/ls/
48
- // find/… invoked through the bash tool). A hard stop after the second
49
- // failure is evidence-based (actual command failures), not task
50
- // classification (rule #10).
51
- forbiddenBashFailures = new Map();
52
- searchRunner;
53
- webSearchThreshold;
54
- searchesThisSession = 0;
55
- retryWebSearchSignatures = new Set();
56
- lastErrorSearchAt = 0;
57
- errorSearchCooldownMs;
58
- hallucinationDetector = null;
59
- /**
60
- * The execution-plugin's mutable state. Owned HERE and passed BY REFERENCE
61
- * to the plugin factory — the plugin writes deps.state.* directly, so the
62
- * assignments are visible on the module without any write-back.
63
- */
64
- state = {
65
- lastRecoveryIteration: -STUCK_RECOVERY_COOLDOWN,
66
- consecutivePlanWarnings: 0,
67
- lastStepId: -1,
68
- stuckNotified: false,
69
- lastStuckWarnKey: "",
70
- lastStuckWarnIter: -STUCK_WARN_REPEAT_EVERY,
71
- depsGateHints: new Map(),
72
- mutationsWithoutPlan: 0,
73
- planNudgeSent: false,
74
- typecheckFailures: new Map(),
75
- };
76
- /**
77
- * Read/write accessor for the tracker, shared with the plan-tool and
78
- * execution-plugin factories. The `plan` tool's abort action clears it
79
- * (current = null) — the setter keeps this.tracker in sync. Object-literal
80
- * getters bind `this` to the literal, so the instance is captured in a
81
- * closure instead.
82
- */
83
- trackerRef = (() => {
84
- const self = this;
85
- return {
86
- get current() {
87
- return self.tracker;
88
- },
89
- set current(v) {
90
- self.tracker = v;
91
- },
92
- };
93
- })();
94
- constructor(baseDir, stuckThreshold = 6, webSearchThreshold = 5, searchRunner = performWebSearch, errorSearchCooldownMs = ERROR_SEARCH_MIN_INTERVAL_MS) {
95
- this.baseDir = baseDir;
96
- this.verifier = new StepVerifier(baseDir);
97
- this.stuckDetector = new StuckDetector(stuckThreshold, 3, webSearchThreshold);
98
- this.auditor = new Auditor(baseDir);
99
- this.store = new PlanStore(baseDir);
100
- this.webSearchThreshold = webSearchThreshold;
101
- this.searchRunner = searchRunner;
102
- this.errorSearchCooldownMs = errorSearchCooldownMs;
103
- }
104
- setPlan(plan) {
105
- this.tracker = new PlanTracker(plan);
106
- // Advance the pointer past any done/skipped steps of a restored/replanned
107
- // plan so display ("current: step N") and the off-track alignment match
108
- // reality instead of always pointing at step 1.
109
- this.tracker.syncCurrentStep();
110
- this.store.saveActive(plan);
111
- this.completedPlan = null; // a new plan supersedes the completed one
112
- this._auditSkipsRemaining = 0; // plan explicitly created — arm the audit gate
113
- }
114
- /** Wire the hallucination detector so the plan tool can check whether
115
- * a file was tracked as deleted (auto-switch kind gate). */
116
- setHallucinationDetector(detector) {
117
- this.hallucinationDetector = detector;
118
- }
119
- /** Remember the last completed plan so the final audit can still verify it
120
- * after the tracker was cleared by the auto-archive. */
121
- recordCompleted(plan) {
122
- this.completedPlan = plan;
123
- }
124
- /** Forget the completed plan (abort/delete/purge — nothing left to audit). */
125
- clearCompleted() {
126
- this.completedPlan = null;
127
- }
128
- restorePlan() {
129
- const plan = this.store.loadActive();
130
- if (!plan)
131
- return false;
132
- const restored = new PlanTracker(plan);
133
- // A plan that was already complete when saved must not come back as the
134
- // active plan — archive it so it cannot re-anchor the agent (restored
135
- // completed plans caused the "continue step 4" loop on restart).
136
- if (restored.isComplete()) {
137
- this.store.archivePlan(plan);
138
- this.tracker = null;
139
- return false;
140
- }
141
- this.tracker = restored;
142
- // Advance to the first non-done step
143
- this.tracker.syncCurrentStep();
144
- this._auditSkipsRemaining = 1; // restored plan — one free pass
145
- return true;
146
- }
147
- getTracker() {
148
- return this.tracker;
149
- }
150
- /** The currently tracked plan (single source of truth for UI consumers).
151
- * Null in a fresh session — a disk-resident plan is restored only when
152
- * resuming a session with history, so the REPL must never see stale plans. */
153
- getActivePlan() {
154
- return this.tracker?.getPlan() ?? null;
155
- }
156
- getStore() {
157
- return this.store;
158
- }
159
- getStuckDetector() {
160
- return this.stuckDetector;
161
- }
162
- /**
163
- * Automatic web search for a repeatedly failing error (>= errorWebSearch.threshold
164
- * identical signatures). Fires the search fire-and-forget (never blocks the tool
165
- * result) and queues the results as a <system-summary> in pendingMessages.
166
- *
167
- * Gates: webSearch master switch + errorWebSearch switch → repeated signature
168
- * → not-searched (or retried) → session cap → meaningful error text →
169
- * cooldown. One search per signature; empty results trigger a single retry
170
- * (unmarkErrorSearched once), then the signature stays searched.
171
- */
172
- maybeSearchError(ctx, call) {
173
- if (ctx.config?.webSearch?.enabled === false)
174
- return;
175
- const cfg = ctx.config?.errorWebSearch;
176
- if (!cfg?.enabled)
177
- return;
178
- const sig = this.stuckDetector.getRepeatedErrorSignature();
179
- if (!sig)
180
- return;
181
- if (this.stuckDetector.hasErrorSearched(sig) && !this.retryWebSearchSignatures.has(sig))
182
- return;
183
- if (this.searchesThisSession >= (cfg.maxSearchesPerSession ?? 3))
184
- return;
185
- const lastError = this.stuckDetector.getLastErrorOutput();
186
- if (!isSearchableError(lastError)) {
187
- ctx.logger?.debug(t("exec.error_search_no_query"));
188
- return;
189
- }
190
- const now = Date.now();
191
- if (now - this.lastErrorSearchAt < this.errorSearchCooldownMs)
192
- return;
193
- const stepDesc = this.tracker?.getCurrentStep()?.description ?? "";
194
- const query = buildSearchQuery(stepDesc, this.stuckDetector.getLastBashCommand(), lastError, call.name, cfg.maxQueryChars ?? 200);
195
- const count = this.stuckDetector.getErrorSignatureCount(sig);
196
- this.stuckDetector.markErrorSearched(sig);
197
- this.searchesThisSession++;
198
- this.lastErrorSearchAt = now;
199
- const networkConfig = getSessionSecurityConfig(ctx.config, ctx.sessionContext).network;
200
- this.searchRunner(query, cfg.maxResults ?? 5, networkConfig, cfg.requestTimeoutMs ?? 10000)
201
- .then((res) => {
202
- if (!res.success || res.results.length === 0) {
203
- if (!this.retryWebSearchSignatures.has(sig)) {
204
- this.retryWebSearchSignatures.add(sig);
205
- this.stuckDetector.unmarkErrorSearched(sig);
206
- }
207
- ctx.logger?.warn(t("exec.error_search_failed", { query }));
208
- ctx.sessionLog?.plan("web-search", `empty/failed: ${query}`);
209
- return;
210
- }
211
- const resultsText = res.results
212
- .map((r, i) => `${i + 1}. ${r.title} \u2014 ${r.url}\n ${r.snippet}`)
213
- .join("\n");
214
- this.pendingMessages.push({
215
- role: "user",
216
- content: `<system-summary>${t("exec.error_search_results", {
217
- sig,
218
- count: String(count),
219
- query,
220
- results: resultsText,
221
- })}</system-summary>`,
222
- });
223
- })
224
- .catch((e) => ctx.logger?.warn(`error web search: ${e.message}`));
225
- }
226
- /**
227
- * Final audit before the agent may declare the task done. Returns null when
228
- * no plan is active; otherwise checks plan completion + artifact existence.
229
- */
230
- async runFinalAudit() {
231
- // No active tracker: audit the last completed plan instead of bailing.
232
- // A plan finished via `plan update` auto-archives and clears the tracker;
233
- // without this the final audit (tests + tsc + file checks) was silently
234
- // skipped and the model could declare success on broken artifacts.
235
- if (!this.tracker) {
236
- if (!this.completedPlan)
237
- return null;
238
- const plan = this.completedPlan;
239
- const audit = await this.auditor.audit(plan);
240
- const pendingSteps = plan.steps.flatMap((s) => s.status !== "done" && s.status !== "skipped" ? [`${s.id}. ${s.description}`] : []);
241
- const done = plan.steps.filter((s) => s.status === "done").length;
242
- return {
243
- passed: audit.passed && pendingSteps.length === 0,
244
- done,
245
- total: plan.steps.length,
246
- pendingSteps,
247
- missingFiles: audit.missingFiles,
248
- summary: audit.summary,
249
- };
250
- }
251
- if (this._auditSkipsRemaining > 0) {
252
- this._auditSkipsRemaining--;
253
- return null;
254
- }
255
- const plan = this.tracker.getPlan();
256
- const audit = await this.auditor.audit(plan);
257
- const pendingSteps = plan.steps.flatMap((s) => s.status !== "done" && s.status !== "skipped" ? [`${s.id}. ${s.description}`] : []);
258
- const done = plan.steps.filter((s) => s.status === "done").length;
259
- const passed = audit.passed && pendingSteps.length === 0;
260
- return {
261
- passed,
262
- done,
263
- total: plan.steps.length,
264
- pendingSteps,
265
- missingFiles: audit.missingFiles,
266
- summary: audit.summary,
267
- };
268
- }
269
- getSystemPromptBlock() {
270
- if (!this.tracker || this.tracker.isComplete())
271
- return null;
272
- return {
273
- content: this.tracker.toPromptBlock(),
274
- priority: "critical",
275
- essential: true,
276
- estimatedTokens: 200,
277
- };
278
- }
279
- /**
280
- * Short "current plan" line for the compaction summary. Null when no plan
281
- * is active. For 9B models the explicit instruction "continue it, do NOT
282
- * create a new plan" matters — after compaction the plan block is visible
283
- * but the model re-creates the plan anyway (observed: ses_msvuao0h).
284
- *
285
- * When the plan is complete, the summary says the plan is done and the
286
- * model may create a new plan — NOT "continue step 4, do NOT create a
287
- * new plan" which anchored the ses_msxjbnm4 loop.
288
- */
289
- getPlanSummary() {
290
- if (!this.tracker)
291
- return null;
292
- const plan = this.tracker.getPlan();
293
- const done = plan.steps.filter((s) => s.status === "done").length;
294
- const total = plan.steps.length;
295
- if (this.tracker.isComplete()) {
296
- return `[${plan.id}] "${plan.title}" ${done}/${total} done — plan complete. You may create a new plan for new work (plan create), or reply with your final answer.`;
297
- }
298
- const current = this.tracker.getCurrentStepIndex() + 1;
299
- return `[${plan.id}] "${plan.title}" ${done}/${total} done, current: step ${current} — continue it (plan show / re-plan), do NOT create a new plan`;
300
- }
301
- getToolDefinitions() {
302
- return createPlanToolDefinitions({
303
- store: this.store,
304
- verifier: this.verifier,
305
- trackerRef: this.trackerRef,
306
- preserveActive: () => this.preserveActive(),
307
- setPlan: (p) => this.setPlan(p),
308
- recordCompleted: (p) => this.recordCompleted(p),
309
- clearCompleted: () => this.clearCompleted(),
310
- hasStepDeliverables: (s) => this.hasStepDeliverables(s),
311
- missingStepDeliverables: (s) => this.missingStepDeliverables(s),
312
- stillExistingDeliverables: (s) => this.stillExistingDeliverables(s),
313
- parseKinds: (a, st) => this.parseKinds(a, st),
314
- getTaskText: (c) => this.getTaskText(c),
315
- typecheckFailures: this.state.typecheckFailures,
316
- baseDir: this.baseDir,
317
- wasFileDeleted: this.hallucinationDetector
318
- ? (path) => this.hallucinationDetector.getConsistencyCheck().getDeletedFiles().includes(path)
319
- : undefined,
320
- });
321
- }
322
- getPlugin() {
323
- return createExecutionPlugin({
324
- stuckDetector: this.stuckDetector,
325
- trackerRef: this.trackerRef,
326
- pendingMessages: this.pendingMessages,
327
- forbiddenBashFailures: this.forbiddenBashFailures,
328
- state: this.state,
329
- store: this.store,
330
- checkPlanAlignment: (call) => this.checkPlanAlignment(call),
331
- advancePlanIfStepComplete: (cm, sl) => this.advancePlanIfStepComplete(cm, sl),
332
- maybeSearchError: (ctx, call) => this.maybeSearchError(ctx, call),
333
- });
334
- }
335
- preserveActive() {
336
- if (!this.tracker)
337
- return;
338
- const plan = this.tracker.getPlan();
339
- if (plan.steps.every((s) => s.status === "done" || s.status === "skipped")) {
340
- this.store.archivePlan(plan);
341
- }
342
- else {
343
- this.store.saveDraft(plan);
344
- }
345
- }
346
- checkPlanAlignment(call) {
347
- if (!this.tracker)
348
- return null;
349
- const step = this.tracker.getCurrentStep();
350
- if (!step)
351
- return null;
352
- const allowedAlways = [
353
- "plan",
354
- "todo",
355
- "verify",
356
- "list_dir",
357
- "read_file",
358
- "glob",
359
- "grep",
360
- "file_info",
361
- "load_skill",
362
- ];
363
- if (allowedAlways.includes(call.name))
364
- return null;
365
- const stepPaths = extractFileLikeTokens(stripUrls(step.description)).map((p) => p.toLowerCase());
366
- if (stepPaths.length === 0)
367
- return null;
368
- // Only path-ish arguments are inspected. JSON-stringifying the whole args
369
- // blob made write_file/edit_file `content` feed its code tokens into the
370
- // off-path check (e.g. `import "./styles.css"` inside the file body) and
371
- // raised phantom alignment warnings for on-track writes.
372
- const argStr = this.pathArgStrings(call.arguments).join(" ");
373
- const callPaths = extractFileLikeTokens(stripUrls(argStr)).map((p) => p.toLowerCase());
374
- if (callPaths.length === 0)
375
- return null;
376
- // Files that already belong to COMPLETED (done/skipped) steps are
377
- // legitimate rewrite targets — the agent iterates on them while fixing
378
- // LSP/type errors. Blocking those would stop normal bug-fixing.
379
- const plan = this.tracker.getPlan();
380
- const finishedPaths = new Set();
381
- for (const s of plan.steps) {
382
- if (s.status === "done" || s.status === "skipped") {
383
- extractFileLikeTokens(stripUrls(s.description))
384
- .map((p) => p.toLowerCase())
385
- .forEach((p) => finishedPaths.add(p));
386
- }
387
- }
388
- const offPath = callPaths.some((p) => {
389
- if (finishedPaths.has(p) || [...finishedPaths].some((s) => s.includes(p))) {
390
- return false;
391
- }
392
- return !stepPaths.some((s) => p.includes(s) || s.includes(p));
393
- });
394
- if (!offPath)
395
- return null;
396
- return t("exec.plan_warning", {
397
- step: String(step.id),
398
- description: step.description,
399
- tool: call.name,
400
- });
401
- }
402
- /** String values of the path-like arguments of a tool call. Limits the
403
- * off-path alignment check to arguments that actually name files (path,
404
- * file, dir, src, dst, source, target, input, output, destination, glob,
405
- * workdir, cwd, command, pattern) and never scans payload content. */
406
- pathArgStrings(args) {
407
- if (!args)
408
- return [];
409
- const out = [];
410
- for (const [key, value] of Object.entries(args)) {
411
- if (!/path|file|dir|src|dst|source|target|input|output|destination|glob|workdir|cwd|command|pattern|query/i.test(key)) {
412
- continue;
413
- }
414
- if (typeof value === "string")
415
- out.push(value);
416
- else if (Array.isArray(value)) {
417
- for (const v of value)
418
- if (typeof v === "string")
419
- out.push(v);
420
- }
421
- }
422
- return out;
423
- }
424
- advancePlanIfStepComplete(contextManager, sessionLog) {
425
- const step = this.tracker?.getCurrentStep();
426
- if (!step)
427
- return;
428
- const stepText = step.description.toLowerCase();
429
- // Shared file-token filter (allow-list of real extensions, extension-only
430
- // segments rejected). A step like "Удалить .js, оставить .tsx/.ts" must
431
- // NOT produce the phantom token "tsx/.ts" — that never exists, making
432
- // allGone trivially true and auto-advancing a delete step while the real
433
- // files to delete still exist (the raw regex path did exactly that).
434
- const stepPaths = extractFileLikeTokens(stripUrls(step.description)) || [];
435
- // Step gate: verify dependencies when mentioned — check BEFORE file paths.
436
- // Requires an actual package-manager verb (rule #10 — no bare keyword
437
- // matching: "init" alone or "setup project" must NOT trigger the lockfile
438
- // hint, only concrete dependency-install commands do).
439
- const isDepsStep = /(?:npm|bun|yarn|pnpm|pip|pip3|pipenv|poetry|composer|deno|go|gem|cargo)\s+(?:install|add|init|i|get)\b|bun\s+(?:add|install)|npm\s+(?:i|install|add)|(?:install|установ\w*)\s+(?:dependencies|зависимост\w*|пакет\w*|packages?)/i.test(stepText);
440
- if (isDepsStep) {
441
- const lockFiles = [
442
- "package-lock.json",
443
- "bun.lockb",
444
- "yarn.lock",
445
- "pnpm-lock.yaml",
446
- "node_modules",
447
- "go.sum",
448
- "Cargo.lock",
449
- "Pipfile.lock",
450
- "poetry.lock",
451
- "requirements.txt",
452
- ];
453
- const hasLockFile = lockFiles.some((f) => existsSync(resolve(this.baseDir, f)));
454
- if (!hasLockFile) {
455
- if (contextManager) {
456
- const hints = this.state.depsGateHints.get(step.id) || 0;
457
- this.state.depsGateHints.set(step.id, hints + 1);
458
- const force = hints >= 1;
459
- const content = force
460
- ? t("exec.step_gate_deps_force", { step: String(step.id) })
461
- : t("exec.step_gate_deps", {
462
- step: String(step.id),
463
- description: step.description,
464
- });
465
- contextManager.addMessage({
466
- role: "user",
467
- content: `<system-summary>${content}</system-summary>`,
468
- });
469
- }
470
- return;
471
- }
472
- }
473
- if (stepPaths.length === 0)
474
- return;
475
- // Resolve tokens with the SAME subtree walk the deliverable gate and the
476
- // auditor use (findExistingFile), so a nested file
477
- // ("bicycle-shop/src/bicycles.ts" for token "src/bicycles.ts") counts as
478
- // present. The old exact existsSync(resolve()) never matched nested
479
- // projects, so auto-advance stayed silent even after the model wrote the
480
- // real file.
481
- const resolved = stepPaths.map((p) => findExistingFile(this.baseDir, p));
482
- const allExist = resolved.every((r) => r !== null);
483
- const allGone = resolved.every((r) => r === null);
484
- const satisfied = step.kind === "delete" ? allGone && !allExist : allExist;
485
- if (!satisfied)
486
- return;
487
- // Step gate: verify files have content (not empty)
488
- if (step.kind !== "delete") {
489
- const emptyFiles = [];
490
- for (const r of resolved) {
491
- if (!r)
492
- continue;
493
- try {
494
- const content = readFileSync(r, "utf-8");
495
- if (content.trim().length < 10) {
496
- emptyFiles.push(r);
497
- }
498
- }
499
- catch {
500
- // If we can't read it, rely on the existence result
501
- }
502
- }
503
- if (emptyFiles.length > 0 && contextManager) {
504
- contextManager.addMessage({
505
- role: "user",
506
- content: `<system-summary>${t("exec.step_gate_empty", { step: String(step.id), files: emptyFiles.join(", ") })}</system-summary>`,
507
- });
508
- return;
509
- }
510
- }
511
- // All checks passed — advance
512
- this.tracker?.updateStepStatus(step.id, "done");
513
- const hadNext = this.tracker?.advance() ?? false;
514
- if (this.tracker) {
515
- this.store.saveActive(this.tracker.getPlan());
516
- sessionLog?.plan("auto-advance", `Step ${step.id} auto-completed | ${this.tracker.getProgressString()} | current: step ${this.tracker.getCurrentStepIndex() + 1}`);
517
- }
518
- if (contextManager) {
519
- const nextStep = hadNext ? this.tracker?.getCurrentStep() : null;
520
- const nextMsg = nextStep
521
- ? t("exec.step_gate_ok", {
522
- step: String(step.id),
523
- nextStep: String(nextStep.id),
524
- nextDesc: nextStep.description,
525
- })
526
- : t("exec.step_gate_last", { step: String(step.id) });
527
- contextManager.addMessage({
528
- role: "user",
529
- content: `<system-summary>${nextMsg}</system-summary>`,
530
- });
531
- }
532
- // Auto-archive a plan that just became complete (all steps done/skipped).
533
- // Keeps a finished plan from staying active forever and anchoring the agent
534
- // to a completed task ("continue step 4, do NOT create a new plan" — the
535
- // ses_msxjbnm4 loop). The per-step deliverable gate already verified files.
536
- if (this.tracker?.isComplete()) {
537
- const completed = this.tracker.getPlan();
538
- this.store.archivePlan(completed);
539
- this.recordCompleted(completed); // final audit still verifies it
540
- this.tracker = null;
541
- sessionLog?.plan("auto-archive", `Plan ${completed.id} complete — archived`);
542
- }
543
- }
544
- /**
545
- * File tokens named in a step description that do not resolve to a real
546
- * file. Uses the same shared token extractor (allow-list of real file
547
- * extensions, URLs stripped) and the auditor's subtree resolver, so
548
- * "bicycles.ts" finds "bicycle-shop/src/data/bicycles.ts" and a hostname in
549
- * the description is never reported as a missing deliverable. Steps with no
550
- * file tokens (pure commands, verification runs) cannot be verified.
551
- */
552
- missingStepDeliverables(step) {
553
- const tokens = extractFileLikeTokens(stripUrls(step.description));
554
- if (tokens.length === 0)
555
- return [];
556
- return tokens.filter((p) => !findExistingFile(this.baseDir, p));
557
- }
558
- /**
559
- * File tokens named in a step description that still resolve to a real
560
- * file. The inverse of missingStepDeliverables — used by the gate for
561
- * delete-kind steps ("done" means the files are gone).
562
- */
563
- stillExistingDeliverables(step) {
564
- const tokens = extractFileLikeTokens(stripUrls(step.description));
565
- if (tokens.length === 0)
566
- return [];
567
- return tokens.filter((p) => findExistingFile(this.baseDir, p));
568
- }
569
- /** Whether a step description names at least one real file token. Steps
570
- * with no file tokens (pure commands, verification runs) cannot be
571
- * auto-verified — the done-gate is vacuous for them. */
572
- hasStepDeliverables(step) {
573
- return extractFileLikeTokens(stripUrls(step.description)).length > 0;
574
- }
575
- /**
576
- * Validate the optional per-step `kinds` argument for plan create and
577
- * update-with-steps. Returns length-aligned kinds or an i18n error string.
578
- * Absent kinds → null (caller falls back to all-create semantics). Used by
579
- * BOTH branches so a rebuild via update can never silently drop kinds.
580
- */
581
- parseKinds(args, steps) {
582
- if (args.kinds === undefined)
583
- return { kinds: null, error: null };
584
- if (!Array.isArray(args.kinds)) {
585
- return { kinds: null, error: t("plan.kinds_not_array") };
586
- }
587
- const kindsRaw = args.kinds.map(String);
588
- if (kindsRaw.length !== steps.length) {
589
- return { kinds: null, error: t("plan.kinds_mismatch") };
590
- }
591
- const invalid = kindsRaw.filter((k) => k !== "create" && k !== "delete");
592
- if (invalid.length > 0) {
593
- return {
594
- kinds: null,
595
- error: t("plan.kinds_invalid", {
596
- kinds: invalid.join(", "),
597
- }),
598
- };
599
- }
600
- return { kinds: kindsRaw, error: null };
601
- }
602
- /**
603
- * Extract the original task statement from the first user message in the
604
- * conversation history. Used to validate plan coverage against requirements.
605
- */
606
- getTaskText(ctx) {
607
- const manager = ctx?.contextManager;
608
- if (!manager)
609
- return "";
610
- const history = manager.getActiveHistory();
611
- // The first user message may be an injected <system-summary> (compaction
612
- // block) — it is NOT the task. Coverage must compare the plan against the
613
- // model's real instruction (observed: a compaction summary's stale file
614
- // list produced a bogus "plan is missing files" warning).
615
- const firstUser = history.find((m) => {
616
- if (m.role !== "user")
617
- return false;
618
- const text = getMessageText(m.content);
619
- return !text.startsWith("<system-summary>") && !text.includes("[Compressed:");
620
- });
621
- if (!firstUser)
622
- return "";
623
- return getMessageText(firstUser.content).trim();
624
- }
625
- }