micro-models-agent 0.51.1 → 0.51.2

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 +358 -358
  2. package/dist/main.js +817 -573
  3. package/dist/modules/browser/bridge-server.mjs +202 -202
  4. package/dist/skills/builtin/git.md +36 -36
  5. package/dist/skills/builtin/typescript.md +35 -35
  6. package/package.json +48 -48
  7. package/dist/cli/commands.js +0 -323
  8. package/dist/cli/completer.js +0 -167
  9. package/dist/cli/index.js +0 -2
  10. package/dist/cli/main.js +0 -165
  11. package/dist/cli/plugin-commands.js +0 -36
  12. package/dist/cli/repl-commands.js +0 -661
  13. package/dist/cli/repl.js +0 -616
  14. package/dist/cli/run-result.js +0 -22
  15. package/dist/cli/security-commands.js +0 -164
  16. package/dist/cli/setup.js +0 -231
  17. package/dist/config/config.js +0 -249
  18. package/dist/config/defaults.js +0 -124
  19. package/dist/config/experts.js +0 -15
  20. package/dist/config/index.js +0 -3
  21. package/dist/config/security.js +0 -193
  22. package/dist/config/types.js +0 -1
  23. package/dist/core/agent-moe.js +0 -102
  24. package/dist/core/agent.js +0 -886
  25. package/dist/core/bootstrap.js +0 -404
  26. package/dist/core/index.js +0 -2
  27. package/dist/core/prompt-builder.js +0 -76
  28. package/dist/core/session-logger.js +0 -197
  29. package/dist/core/types.js +0 -1
  30. package/dist/core/version.js +0 -24
  31. package/dist/core/workspace.js +0 -76
  32. package/dist/i18n/en.json +0 -598
  33. package/dist/i18n/index.js +0 -46
  34. package/dist/i18n/ru.json +0 -598
  35. package/dist/index.js +0 -22
  36. package/dist/llm/image-utils.js +0 -143
  37. package/dist/llm/index.js +0 -4
  38. package/dist/llm/model-loader.js +0 -78
  39. package/dist/llm/openai-compat.js +0 -359
  40. package/dist/llm/orchestrator.js +0 -198
  41. package/dist/llm/provider.js +0 -10
  42. package/dist/llm/response.js +0 -39
  43. package/dist/llm/token-counter.js +0 -39
  44. package/dist/llm/types.js +0 -1
  45. package/dist/logger/app-logger.js +0 -143
  46. package/dist/logger/file-log.js +0 -151
  47. package/dist/logger/index.js +0 -1
  48. package/dist/migration/backup.js +0 -45
  49. package/dist/migration/detect.js +0 -50
  50. package/dist/migration/index.js +0 -2
  51. package/dist/modules/artifacts/store.js +0 -61
  52. package/dist/modules/browser/actions.js +0 -76
  53. package/dist/modules/browser/bridge-client.js +0 -199
  54. package/dist/modules/browser/bridge-path.js +0 -10
  55. package/dist/modules/browser/cookie-store.js +0 -24
  56. package/dist/modules/browser/driver.js +0 -136
  57. package/dist/modules/browser/index.js +0 -7
  58. package/dist/modules/browser/module.js +0 -29
  59. package/dist/modules/browser/session.js +0 -338
  60. package/dist/modules/browser/snapshot.js +0 -148
  61. package/dist/modules/browser/types.js +0 -12
  62. package/dist/modules/certification/cli.js +0 -174
  63. package/dist/modules/certification/fact-checker.js +0 -82
  64. package/dist/modules/certification/loader.js +0 -105
  65. package/dist/modules/certification/manifest.js +0 -50
  66. package/dist/modules/certification/runner.js +0 -159
  67. package/dist/modules/certification/scenarios.js +0 -124
  68. package/dist/modules/certification/types.js +0 -1
  69. package/dist/modules/context/chunk-query.js +0 -100
  70. package/dist/modules/context/fact-extractor.js +0 -162
  71. package/dist/modules/context/history.js +0 -15
  72. package/dist/modules/context/index.js +0 -1
  73. package/dist/modules/context/manager.js +0 -423
  74. package/dist/modules/execution/audit-runners.js +0 -152
  75. package/dist/modules/execution/auditor.js +0 -218
  76. package/dist/modules/execution/execution-plugin.js +0 -272
  77. package/dist/modules/execution/index.js +0 -8
  78. package/dist/modules/execution/module.js +0 -436
  79. package/dist/modules/execution/moe-executor.js +0 -291
  80. package/dist/modules/execution/plan-coverage.js +0 -68
  81. package/dist/modules/execution/plan-persister.js +0 -46
  82. package/dist/modules/execution/plan-store.js +0 -157
  83. package/dist/modules/execution/plan-tool.js +0 -508
  84. package/dist/modules/execution/plan-validator.js +0 -153
  85. package/dist/modules/execution/planner.js +0 -90
  86. package/dist/modules/execution/stuck-detector.js +0 -510
  87. package/dist/modules/execution/tracker.js +0 -67
  88. package/dist/modules/execution/types.js +0 -1
  89. package/dist/modules/execution/verifier.js +0 -222
  90. package/dist/modules/execution/windows-commands.js +0 -41
  91. package/dist/modules/hallucination/confidence.js +0 -66
  92. package/dist/modules/hallucination/consistency.js +0 -26
  93. package/dist/modules/hallucination/detector.js +0 -43
  94. package/dist/modules/hallucination/factual.js +0 -129
  95. package/dist/modules/hallucination/index.js +0 -5
  96. package/dist/modules/hallucination/js-identifiers.js +0 -262
  97. package/dist/modules/hallucination/llm-judge.js +0 -101
  98. package/dist/modules/index.js +0 -5
  99. package/dist/modules/indexer/cache.js +0 -40
  100. package/dist/modules/indexer/index.js +0 -3
  101. package/dist/modules/indexer/module.js +0 -245
  102. package/dist/modules/indexer/project-profile.js +0 -183
  103. package/dist/modules/indexer/walker.js +0 -101
  104. package/dist/modules/lsp/check-tool.js +0 -58
  105. package/dist/modules/lsp/client.js +0 -278
  106. package/dist/modules/lsp/command.js +0 -60
  107. package/dist/modules/lsp/config.js +0 -135
  108. package/dist/modules/lsp/index.js +0 -3
  109. package/dist/modules/lsp/module.js +0 -232
  110. package/dist/modules/lsp/probe.js +0 -76
  111. package/dist/modules/lsp/project-root.js +0 -32
  112. package/dist/modules/lsp/startup-check.js +0 -141
  113. package/dist/modules/lsp/types.js +0 -1
  114. package/dist/modules/mcp/client.js +0 -399
  115. package/dist/modules/mcp/index.js +0 -3
  116. package/dist/modules/mcp/module.js +0 -142
  117. package/dist/modules/mcp/registry.js +0 -15
  118. package/dist/modules/memory/index.js +0 -1
  119. package/dist/modules/memory/module.js +0 -96
  120. package/dist/modules/memory/search.js +0 -42
  121. package/dist/modules/memory/store.js +0 -69
  122. package/dist/modules/pipelines/engine.js +0 -60
  123. package/dist/modules/pipelines/index.js +0 -3
  124. package/dist/modules/pipelines/parser.js +0 -56
  125. package/dist/modules/pipelines/template.js +0 -14
  126. package/dist/modules/plugins/builtin/lint-on-write.js +0 -231
  127. package/dist/modules/plugins/builtin/notify.js +0 -9
  128. package/dist/modules/plugins/index.js +0 -1
  129. package/dist/modules/plugins/loader.js +0 -70
  130. package/dist/modules/plugins/manager.js +0 -217
  131. package/dist/modules/plugins/types.js +0 -1
  132. package/dist/modules/processes/detect.js +0 -34
  133. package/dist/modules/processes/index.js +0 -2
  134. package/dist/modules/processes/registry.js +0 -327
  135. package/dist/modules/processes/runner.js +0 -23
  136. package/dist/modules/registry.js +0 -47
  137. package/dist/modules/security/audit-log.js +0 -136
  138. package/dist/modules/security/audit-notifier.js +0 -292
  139. package/dist/modules/security/command-validator.js +0 -205
  140. package/dist/modules/security/content-scanner.js +0 -53
  141. package/dist/modules/security/data-sanitizer.js +0 -89
  142. package/dist/modules/security/encryption.js +0 -242
  143. package/dist/modules/security/index.js +0 -14
  144. package/dist/modules/security/network-validator.js +0 -71
  145. package/dist/modules/security/path-validator.js +0 -207
  146. package/dist/modules/security/rate-limiter.js +0 -119
  147. package/dist/modules/security/security-policies.js +0 -531
  148. package/dist/modules/security/session-encryption.js +0 -210
  149. package/dist/modules/security/session-isolation.js +0 -95
  150. package/dist/modules/session/index.js +0 -3
  151. package/dist/modules/session/manager.js +0 -172
  152. package/dist/modules/session/module.js +0 -24
  153. package/dist/modules/session/store.js +0 -222
  154. package/dist/modules/session/types.js +0 -1
  155. package/dist/modules/skills/index.js +0 -2
  156. package/dist/modules/skills/loader.js +0 -72
  157. package/dist/modules/skills/matcher.js +0 -27
  158. package/dist/modules/skills/module.js +0 -129
  159. package/dist/modules/types.js +0 -1
  160. package/dist/modules/updater/checker.js +0 -96
  161. package/dist/modules/updater/index.js +0 -2
  162. package/dist/modules/updater/module.js +0 -116
  163. package/dist/modules/user-profile/compressor.js +0 -16
  164. package/dist/modules/user-profile/index.js +0 -1
  165. package/dist/modules/user-profile/profile.js +0 -68
  166. package/dist/tools/approve.js +0 -32
  167. package/dist/tools/attach-image.js +0 -89
  168. package/dist/tools/bash.js +0 -496
  169. package/dist/tools/browser.js +0 -114
  170. package/dist/tools/chunk-query.js +0 -99
  171. package/dist/tools/create-dir.js +0 -55
  172. package/dist/tools/delete-file.js +0 -62
  173. package/dist/tools/download-file.js +0 -116
  174. package/dist/tools/edit-file.js +0 -79
  175. package/dist/tools/enable-tools.js +0 -58
  176. package/dist/tools/executor.js +0 -144
  177. package/dist/tools/file-info.js +0 -46
  178. package/dist/tools/filter-tools.js +0 -17
  179. package/dist/tools/glob-tool.js +0 -26
  180. package/dist/tools/grep-tool.js +0 -84
  181. package/dist/tools/hidden-tools-block.js +0 -37
  182. package/dist/tools/index.js +0 -78
  183. package/dist/tools/list-dir.js +0 -48
  184. package/dist/tools/load-skill.js +0 -42
  185. package/dist/tools/mcp-call.js +0 -68
  186. package/dist/tools/move-file.js +0 -85
  187. package/dist/tools/path-utils.js +0 -51
  188. package/dist/tools/pipeline-run.js +0 -144
  189. package/dist/tools/preview.js +0 -2
  190. package/dist/tools/process-kill.js +0 -29
  191. package/dist/tools/process-list.js +0 -36
  192. package/dist/tools/process-log.js +0 -45
  193. package/dist/tools/question.js +0 -140
  194. package/dist/tools/read-file.js +0 -91
  195. package/dist/tools/recall.js +0 -117
  196. package/dist/tools/registry.js +0 -47
  197. package/dist/tools/remember.js +0 -67
  198. package/dist/tools/scope-check.js +0 -30
  199. package/dist/tools/search-history.js +0 -84
  200. package/dist/tools/subagent.js +0 -196
  201. package/dist/tools/types.js +0 -1
  202. package/dist/tools/user-input.js +0 -123
  203. package/dist/tools/web-browse.js +0 -86
  204. package/dist/tools/web-fetch.js +0 -98
  205. package/dist/tools/web-search.js +0 -78
  206. package/dist/tools/write-file.js +0 -81
  207. package/dist/ui/box.js +0 -77
  208. package/dist/ui/colors.js +0 -4
  209. package/dist/ui/diff.js +0 -178
  210. package/dist/ui/index.js +0 -6
  211. package/dist/ui/line-editor.js +0 -703
  212. package/dist/ui/line-math.js +0 -69
  213. package/dist/ui/md-formatter.js +0 -212
  214. package/dist/ui/output.js +0 -13
  215. package/dist/ui/plan-view.js +0 -103
  216. package/dist/ui/renderer.js +0 -209
  217. package/dist/ui/spinner.js +0 -70
  218. package/dist/ui/table.js +0 -144
@@ -1,162 +0,0 @@
1
- import { getMessageText } from "../../llm/provider";
2
- /**
3
- * Regex-based fact extraction from tool/assistant messages. Owns the file /
4
- * deleted / decision / error fact lists that survive compaction. Extracted
5
- * from ContextManager so the ~115-line regex logic has one home (rule #2).
6
- */
7
- export class FactExtractor {
8
- fileFacts = [];
9
- deletedFacts = [];
10
- decisionFacts = [];
11
- errorFacts = [];
12
- readFacts = [];
13
- static MAX_FACTS = 20;
14
- get errorCount() {
15
- return this.errorFacts.length;
16
- }
17
- /** Scan a batch of compacted turns and fold their facts into the lists. */
18
- extract(turns) {
19
- // Absolute Windows paths ("E:\proj\src\a.ts") need an optional drive prefix;
20
- // without it the colon breaks the match and the fact is silently dropped.
21
- const DRIVE = "(?:[a-zA-Z]:[\\\\/])?";
22
- const createdPatterns = [
23
- new RegExp(`(?:Created|Updated|Written|Moved|Replaced in) ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
24
- new RegExp(`Файл (?:создан|обновлён|записан|перемещён):? ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
25
- new RegExp(`file (?:created|updated|written|moved):? ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
26
- ];
27
- const deletedPatterns = [
28
- new RegExp(`Deleted ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
29
- new RegExp(`(?:Удалён|Файл удалён):? ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
30
- ];
31
- // read_file output header — locale-independent prefix `── path (ext, …`
32
- // (en: "lines", ru: "строк"). The path is already prefixed with the same
33
- // box-drawing marker in both locales, so the pattern needs no localization.
34
- const readPatterns = [new RegExp(`── (${DRIVE}[\\w./\\\\-]+\\.[a-z]+) \\(`, "gi")];
35
- const newFiles = [];
36
- const newDeleted = [];
37
- const newDecisions = [];
38
- const newErrors = [];
39
- const newReads = [];
40
- // Track the LAST tool event per path so a delete followed by a re-create
41
- // (or vice versa) in the same window resolves to its final state instead of
42
- // being both filtered out of [Files:] and reported as [Deleted:].
43
- const lastEvent = new Map();
44
- for (const msg of turns) {
45
- const content = getMessageText(msg.content);
46
- // The system prompt is never a fact source — the memory module embeds
47
- // errors.md (with historical "Tool X failed Nx" entries from PAST days)
48
- // there, and extracting that text as current [Errors:] misleads the model
49
- // into thinking IT is failing (observed: ses_msvuao0h — a stale
50
- // "edit_file failed 3x" from 2026-08-15 landed in every compaction
51
- // summary as if it were the live session's failure).
52
- if (msg.role === "system")
53
- continue;
54
- // Never feed a previous <system-summary> block into new facts — that is
55
- // the source of recursive summary nesting (summary inside summary).
56
- if (msg.role === "user" &&
57
- (content.startsWith("<system-summary>") || content.includes("[Compressed:"))) {
58
- continue;
59
- }
60
- if (msg.role === "tool") {
61
- for (const pattern of createdPatterns) {
62
- for (const match of content.matchAll(pattern)) {
63
- newFiles.push(match[1]);
64
- lastEvent.set(match[1], "file");
65
- }
66
- }
67
- for (const pattern of deletedPatterns) {
68
- for (const match of content.matchAll(pattern)) {
69
- newDeleted.push(match[1]);
70
- lastEvent.set(match[1], "deleted");
71
- }
72
- }
73
- for (const pattern of readPatterns) {
74
- for (const match of content.matchAll(pattern)) {
75
- newReads.push(match[1]);
76
- }
77
- }
78
- if (content.includes("Plan:") && content.includes("[")) {
79
- const planLine = content.split("\n").find((line) => line.includes("Plan:"));
80
- if (planLine)
81
- newDecisions.push(planLine.trim());
82
- }
83
- }
84
- if (msg.role === "assistant") {
85
- if (content.includes("decided:") || content.includes("decision:")) {
86
- const line = content
87
- .split("\n")
88
- .find((l) => l.includes("decided:") || l.includes("decision:"));
89
- if (line)
90
- newDecisions.push(line.trim().slice(0, 200));
91
- }
92
- }
93
- if (msg.role === "tool" || msg.role === "assistant") {
94
- if (content.includes("Error:") ||
95
- content.includes("failed") ||
96
- content.includes("Ошибка:") ||
97
- content.includes("не удалось")) {
98
- const line = content
99
- .split("\n")
100
- .find((l) => l.includes("Error:") ||
101
- l.includes("failed") ||
102
- l.includes("Ошибка:") ||
103
- l.includes("не удалось"));
104
- if (line)
105
- newErrors.push(line.trim().slice(0, 250));
106
- }
107
- }
108
- }
109
- // Deduplicate and cap facts to prevent unbounded growth. Files that were
110
- // DELETED leave the "known files" list — a deleted file must not keep
111
- // being reported as existing (observed: deleted .js files listed in
112
- // every [Files: ...] block for the whole session). A path that is deleted
113
- // then RE-CREATED (delete_file A → write_file A) is un-deleted: the last
114
- // event in the window wins, so it returns to [Files:] and leaves [Deleted:].
115
- const dedup = (arr) => [...new Set(arr)];
116
- const finalFiles = dedup(newFiles.filter((p) => lastEvent.get(p) === "file"));
117
- const finalDeleted = dedup(newDeleted.filter((p) => lastEvent.get(p) === "deleted"));
118
- this.fileFacts = dedup([...this.fileFacts, ...finalFiles].filter((p) => !finalDeleted.includes(p))).slice(-FactExtractor.MAX_FACTS);
119
- this.deletedFacts = dedup([...this.deletedFacts, ...finalDeleted].filter((p) => !finalFiles.includes(p))).slice(-FactExtractor.MAX_FACTS);
120
- this.decisionFacts = dedup([...this.decisionFacts, ...newDecisions]).slice(-FactExtractor.MAX_FACTS);
121
- this.errorFacts = dedup([...this.errorFacts, ...newErrors]).slice(-FactExtractor.MAX_FACTS);
122
- this.readFacts = dedup([...this.readFacts, ...newReads]).slice(-FactExtractor.MAX_FACTS);
123
- }
124
- /** `[Files: a; b]` line for a compaction summary, or null. */
125
- filesLine() {
126
- const deletedSet = new Set(this.deletedFacts);
127
- const liveFiles = this.fileFacts.filter((p) => !deletedSet.has(p));
128
- if (liveFiles.length === 0)
129
- return null;
130
- return `[Files: ${liveFiles.slice(-15).join("; ")}]`;
131
- }
132
- /** `[Deleted: c]` line, or null. */
133
- deletedLine() {
134
- if (this.deletedFacts.length === 0)
135
- return null;
136
- return `[Deleted: ${this.deletedFacts.slice(-10).join("; ")}]`;
137
- }
138
- /** `[Decisions: d]` line, or null. */
139
- decisionsLine() {
140
- if (this.decisionFacts.length === 0)
141
- return null;
142
- return `[Decisions: ${this.decisionFacts.slice(-5).join("; ")}]`;
143
- }
144
- /** `[Errors: e]` line, or null. */
145
- errorsLine() {
146
- if (this.errorFacts.length === 0)
147
- return null;
148
- return `[Errors: ${this.errorFacts.slice(-3).join("; ")}]`;
149
- }
150
- /**
151
- * `[Read: p1; p2]` line — files already inspected via read_file. Lets the
152
- * model re-orient after compaction without rescanning the whole project: it
153
- * knows which files were already read and only re-reads what changed
154
- * (observed: post-compaction the model re-read the same files it had already
155
- * inspected, because "already read" never survived compaction).
156
- */
157
- readLine() {
158
- if (this.readFacts.length === 0)
159
- return null;
160
- return `[Read: ${this.readFacts.slice(-12).join("; ")}]`;
161
- }
162
- }
@@ -1,15 +0,0 @@
1
- import { appendFileSync, mkdirSync, existsSync } from 'fs';
2
- import { join } from 'path';
3
- export class SessionHistoryWriter {
4
- historyPath;
5
- constructor(sessionsDir, sessionId) {
6
- const sessionDir = join(sessionsDir, sessionId);
7
- if (!existsSync(sessionDir)) {
8
- mkdirSync(sessionDir, { recursive: true });
9
- }
10
- this.historyPath = join(sessionDir, 'history.jsonl');
11
- }
12
- append(msg) {
13
- appendFileSync(this.historyPath, JSON.stringify(msg) + '\n', 'utf-8');
14
- }
15
- }
@@ -1 +0,0 @@
1
- export { ContextManager } from "./manager";
@@ -1,423 +0,0 @@
1
- import { getMessageText } from "../../llm/provider";
2
- import { FactExtractor } from "./fact-extractor";
3
- const COMPACTION_INTERVAL = 15;
4
- const KEEP_LAST_N = 6;
5
- function summarizeArgs(args) {
6
- if (!args)
7
- return "";
8
- if (typeof args === "string")
9
- return args.slice(0, 80);
10
- try {
11
- const keys = Object.keys(args);
12
- return keys.slice(0, 3).join(", ");
13
- }
14
- catch {
15
- return String(args).slice(0, 80);
16
- }
17
- }
18
- function truncate(s, max) {
19
- if (s.length <= max)
20
- return s;
21
- return s.slice(0, max - 3) + "...";
22
- }
23
- function looksLikeErrorPaste(text) {
24
- // Error markers.
25
- if (/(?:^|\s)ERROR|Error:|error TS\d+|Transform failed|\[plugin:|SyntaxError|Cannot find|Uncaught|exception/i.test(text)) {
26
- return true;
27
- }
28
- // Structural signals of pasted compiler/runtime output: source frames
29
- // ("270| }_s(...)"), path:line:col references, and stack-trace lines.
30
- if (/(?:^|\n)\s*\d+\s*\|/.test(text))
31
- return true;
32
- if (/[\w./\\-]+\.[a-z]{1,6}:\d+:\d+/.test(text))
33
- return true;
34
- if (/(?:^|\n)\s*at\s+\S+/.test(text))
35
- return true;
36
- return false;
37
- }
38
- export function extractTriedAndFailed(messages) {
39
- const failures = new Map();
40
- for (const msg of messages) {
41
- if (msg.role === "tool" && msg.name && msg.success === false) {
42
- const key = `${msg.name}:${summarizeArgs(msg.arguments)}`;
43
- const existing = failures.get(key);
44
- const errorText = truncate(typeof msg.content === "string" ? msg.content : getMessageText(msg.content), 100);
45
- if (existing) {
46
- existing.count++;
47
- }
48
- else {
49
- failures.set(key, {
50
- tool: msg.name,
51
- args: summarizeArgs(msg.arguments),
52
- error: errorText,
53
- count: 1,
54
- });
55
- }
56
- }
57
- }
58
- return Array.from(failures.values()).filter((f) => f.count >= 2);
59
- }
60
- export class ContextManager {
61
- contextWindow;
62
- messages = [];
63
- compactedBlock = null;
64
- iterationsSinceCompaction = 0;
65
- compactionCount = 0;
66
- peakTokens = 0;
67
- budget;
68
- compactionThreshold;
69
- facts = new FactExtractor();
70
- /** Latest real user instruction (skips <system-summary> blocks). */
71
- lastUserTask = "";
72
- /** First real user instruction of the session — survives resetUserTurn(). */
73
- sessionMission = "";
74
- /** Latest user message that looks like a pasted error/log (never a task). */
75
- lastUserFeedback = "";
76
- tokenCounter;
77
- pendingImageParts = [];
78
- toolTokens = 0;
79
- onCompact = null;
80
- /**
81
- * Optional short line appended to the compaction summary so the model knows
82
- * an active plan exists with progress. Wired from bootstrap to the execution
83
- * module — without it, a 9B model re-creates a plan from scratch right after
84
- * compaction (observed: ses_msvuao0h — plan_e07pb2 (1/6) was discarded for a
85
- * fresh plan_xzq9xe the same iteration the old plan was still visible).
86
- */
87
- planSummaryProvider = null;
88
- constructor(contextWindow, contextBudget, tokenCounter) {
89
- this.contextWindow = contextWindow;
90
- this.compactionThreshold = contextBudget?.compactionThreshold ?? 0.75;
91
- this.budget = this.calculateBudget(contextWindow, contextBudget);
92
- this.tokenCounter = tokenCounter ?? null;
93
- }
94
- /**
95
- * Provide a short "current plan" line for the compaction summary, or null
96
- * when no plan is active. Injected once at bootstrap (not per-turn state).
97
- */
98
- setPlanSummaryProvider(fn) {
99
- this.planSummaryProvider = fn;
100
- }
101
- calculateBudget(window, contextBudget) {
102
- if (contextBudget) {
103
- const systemPrompt = Math.floor(window * contextBudget.systemPrompt);
104
- const responseReserve = Math.floor(window * contextBudget.responseReserve);
105
- const history = Math.max(0, window - systemPrompt - responseReserve);
106
- return { systemPrompt, responseReserve, history };
107
- }
108
- // Fallback for backwards compatibility (tests, subagents without explicit budget)
109
- return {
110
- systemPrompt: Math.floor(window * 0.25),
111
- responseReserve: Math.floor(window * 0.12),
112
- history: Math.floor(window * 0.63),
113
- };
114
- }
115
- getBudget() {
116
- return { ...this.budget };
117
- }
118
- getCompactionCount() {
119
- return this.compactionCount;
120
- }
121
- getIterationsSinceCompaction() {
122
- return this.iterationsSinceCompaction;
123
- }
124
- noteIteration() {
125
- this.iterationsSinceCompaction++;
126
- }
127
- /**
128
- * Start a fresh user turn. The 15-iteration compaction interval must not
129
- * leak across user messages — otherwise a turn that ends at iteration 14
130
- * forces a compaction on the very first iteration of the next user message
131
- * (observed: compaction fired on iteration 8 of a new turn, deleting the
132
- * user's freshly-sent task alongside 40+ old turns). Facts are kept.
133
- */
134
- resetUserTurn() {
135
- this.iterationsSinceCompaction = 0;
136
- // A new user message begins a new turn — drop the previous turn's task
137
- // so the fresh instruction becomes the one preserved at compaction. The
138
- // session mission survives: an error/log paste in the new turn must not
139
- // erase the original goal.
140
- this.lastUserTask = "";
141
- this.lastUserFeedback = "";
142
- }
143
- getQuality() {
144
- const usedTokens = this.getEstimatedTokens();
145
- const tokenLoad = Math.max(0, 1 - usedTokens / this.budget.history);
146
- // Recoverable penalty: each compaction loses some information, but the
147
- // penalty is CAPPED so cumulative compactions can never permanently pin
148
- // quality below the forced-compaction trigger (40%). Before this cap, a
149
- // session with ~7+ compactions clamped the term to 0 forever; combined
150
- // with heavy token load + error density, quality stuck below 40 and a
151
- // compaction fired on EVERY iteration (observed: 56 compactions in 28 min).
152
- const COMPACTION_PENALTY_FLOOR = 0.5;
153
- const compactionLoss = Math.max(COMPACTION_PENALTY_FLOOR, 1 - this.compactionCount * 0.15);
154
- const msgCount = this.messages.length || 1;
155
- const errorDensity = Math.max(0, 1 - Math.min(1, this.facts.errorCount / msgCount));
156
- const freshness = Math.max(0, 1 - this.iterationsSinceCompaction / COMPACTION_INTERVAL);
157
- const score = tokenLoad * 0.4 + compactionLoss * 0.25 + errorDensity * 0.2 + freshness * 0.15;
158
- return Math.round(Math.min(100, Math.max(0, score * 100)));
159
- }
160
- addMessage(msg) {
161
- // Track the task the agent is working on so it survives compaction. The
162
- // user's real instruction is the FIRST non-system-summary user message of
163
- // the turn; everything after it (tool results, retry nudges) are injected
164
- // `user` envelopes that must not overwrite it (observed: after compaction
165
- // the model had forgotten "удали /bicycles, почини стили" and re-read
166
- // files aimlessly for 40+ iterations).
167
- if (msg.role === "user") {
168
- const text = typeof msg.content === "string" ? msg.content : getMessageText(msg.content);
169
- if (text.trim() && !text.startsWith("<system-summary>") && !text.includes("[Compressed:")) {
170
- if (looksLikeErrorPaste(text) && (this.lastUserTask || this.sessionMission)) {
171
- this.lastUserFeedback = text.trim().slice(0, 400);
172
- }
173
- else if (!this.lastUserTask && !this.lastUserFeedback) {
174
- // No new task inside a turn that already captured an error/log paste:
175
- // the paste's follow-up messages are tool-result continuations, not a
176
- // fresh instruction, so the session mission must win at compaction.
177
- this.lastUserTask = text.trim();
178
- if (!this.sessionMission)
179
- this.sessionMission = text.trim();
180
- }
181
- }
182
- }
183
- // Auto-attach pending images to the next user message
184
- if (msg.role === "user" && this.pendingImageParts.length > 0) {
185
- const textPart = {
186
- type: "text",
187
- text: typeof msg.content === "string" ? msg.content : getMessageText(msg.content),
188
- };
189
- msg = {
190
- ...msg,
191
- content: [textPart, ...this.pendingImageParts],
192
- };
193
- this.pendingImageParts = [];
194
- }
195
- this.messages.push(msg);
196
- const tokens = this.getEstimatedTokens();
197
- if (tokens > this.peakTokens)
198
- this.peakTokens = tokens;
199
- }
200
- /**
201
- * Queue an image part to be attached to the next user message.
202
- */
203
- addPendingImage(part) {
204
- this.pendingImageParts.push(part);
205
- }
206
- /**
207
- * Check if there are pending images waiting to be attached.
208
- */
209
- hasPendingImages() {
210
- return this.pendingImageParts.length > 0;
211
- }
212
- /**
213
- * Get pending image parts without clearing them.
214
- */
215
- getPendingImages() {
216
- return [...this.pendingImageParts];
217
- }
218
- /**
219
- * Clear pending images (e.g., if user sends a text-only message).
220
- */
221
- clearPendingImages() {
222
- this.pendingImageParts = [];
223
- }
224
- getMessageCount() {
225
- return this.messages.length;
226
- }
227
- estimateMessageTokens(m) {
228
- const text = getMessageText(m.content);
229
- if (this.tokenCounter) {
230
- let t = this.tokenCounter.count(text);
231
- // Image tokens: base64 ~130 tokens per 512x512 tile; rough estimate
232
- if (Array.isArray(m.content)) {
233
- for (const part of m.content) {
234
- if (part.type === "image_url" && part.image_url?.url) {
235
- const b64Len = part.image_url.url.includes(",")
236
- ? (part.image_url.url.split(",")[1]?.length ?? 0)
237
- : part.image_url.url.length;
238
- // ~130 tokens per 512 bytes of base64
239
- t += Math.ceil(b64Len / 512) * 130;
240
- }
241
- }
242
- }
243
- if (m.tool_calls) {
244
- for (const tc of m.tool_calls) {
245
- t += this.tokenCounter.count(tc.id);
246
- t += this.tokenCounter.count(tc.function.name);
247
- t += this.tokenCounter.count(tc.function.arguments);
248
- t += 4;
249
- }
250
- }
251
- return t;
252
- }
253
- let t = Math.ceil(text.length / 2);
254
- if (Array.isArray(m.content)) {
255
- for (const part of m.content) {
256
- if (part.type === "image_url" && part.image_url?.url) {
257
- const b64Len = part.image_url.url.includes(",")
258
- ? (part.image_url.url.split(",")[1]?.length ?? 0)
259
- : part.image_url.url.length;
260
- t += Math.ceil(b64Len / 512) * 130;
261
- }
262
- }
263
- }
264
- if (m.tool_calls) {
265
- for (const tc of m.tool_calls) {
266
- t += Math.ceil(tc.id.length / 2);
267
- t += Math.ceil(tc.function.name.length / 2);
268
- t += Math.ceil(tc.function.arguments.length / 2);
269
- t += 4;
270
- }
271
- }
272
- return t;
273
- }
274
- needsCompaction() {
275
- if (this.iterationsSinceCompaction >= COMPACTION_INTERVAL)
276
- return true;
277
- const totalTokens = this.messages.reduce((sum, m) => sum + this.estimateMessageTokens(m), 0);
278
- return totalTokens > this.budget.history * this.compactionThreshold;
279
- }
280
- compact() {
281
- // Capture the pre-compaction state BEFORE any counters reset or rise —
282
- // qualityBefore must reflect the context the model actually saw.
283
- const tokensBefore = this.getEstimatedTokens();
284
- const qualityBefore = this.getQuality();
285
- const messagesBefore = this.messages.length;
286
- // Reset the counter even when nothing to compact — otherwise
287
- // needsCompaction() returns true forever after 15 iterations with few messages.
288
- this.iterationsSinceCompaction = 0;
289
- if (this.messages.length <= KEEP_LAST_N * 2)
290
- return null;
291
- this.compactionCount++;
292
- const cutoff = this.messages.length - KEEP_LAST_N * 2;
293
- const oldTurns = this.messages.slice(0, cutoff);
294
- const recentTurns = this.messages.slice(cutoff);
295
- this.facts.extract(oldTurns);
296
- const parts = [];
297
- parts.push(`[Compressed: ${oldTurns.length} old turns removed]`);
298
- // Carry the user's actual instruction forward — the model must never lose
299
- // the task it is working on just because 40 turns got compacted away. The
300
- // per-turn task falls back to the session mission (first real instruction)
301
- // so a pasted error/log in the current turn cannot erase the goal.
302
- const task = (this.lastUserTask || this.sessionMission).slice(0, 400);
303
- if (task)
304
- parts.push(`[Task: ${task}]`);
305
- if (this.lastUserFeedback && !task.startsWith(this.lastUserFeedback)) {
306
- parts.push(`[User feedback: ${this.lastUserFeedback}]`);
307
- }
308
- // Orient the model after compaction: an active plan must not be re-created
309
- // from scratch (see planSummaryProvider doc).
310
- const planLine = this.planSummaryProvider?.();
311
- if (planLine)
312
- parts.push(`[Plan: ${planLine}]`);
313
- const filesLine = this.facts.filesLine();
314
- if (filesLine)
315
- parts.push(filesLine);
316
- const deletedLine = this.facts.deletedLine();
317
- if (deletedLine)
318
- parts.push(deletedLine);
319
- const readLine = this.facts.readLine();
320
- if (readLine)
321
- parts.push(readLine);
322
- const decisionsLine = this.facts.decisionsLine();
323
- if (decisionsLine)
324
- parts.push(decisionsLine);
325
- const errorsLine = this.facts.errorsLine();
326
- if (errorsLine)
327
- parts.push(errorsLine);
328
- const triedAndFailed = extractTriedAndFailed(oldTurns);
329
- if (triedAndFailed.length > 0) {
330
- const lines = triedAndFailed.map((t) => `- ${t.tool}(${t.args}): ${t.error} (failed ${t.count}x)`);
331
- parts.push(`[Already tried & failed — do NOT repeat:]\n${lines.join("\n")}`);
332
- }
333
- this.compactedBlock = parts.join(" ");
334
- const summary = {
335
- role: "user",
336
- content: `<system-summary>${this.compactedBlock}</system-summary>`,
337
- };
338
- const firstSystem = this.messages.find((m) => m.role === "system");
339
- // Filter out stale system-summary messages from recent turns to prevent nesting
340
- const freshRecent = recentTurns.filter((m) => {
341
- if (m.role !== "user")
342
- return true;
343
- const text = getMessageText(m.content);
344
- return !text.startsWith("<system-summary>");
345
- });
346
- this.messages = [...(firstSystem ? [firstSystem] : []), summary, ...freshRecent];
347
- this.iterationsSinceCompaction = 0;
348
- if (this.onCompact) {
349
- this.onCompact(summary);
350
- }
351
- return {
352
- removedTurns: oldTurns.length,
353
- keptTurns: freshRecent.length,
354
- tokensBefore,
355
- tokensAfter: this.getEstimatedTokens(),
356
- qualityBefore,
357
- qualityAfter: this.getQuality(),
358
- messagesBefore,
359
- messagesAfter: this.messages.length,
360
- summary: this.compactedBlock ?? "",
361
- };
362
- }
363
- /**
364
- * Snapshot of the current context state — used to log the initial context
365
- * structure at session start and per-iteration context stats.
366
- */
367
- getSnapshot() {
368
- return {
369
- window: this.contextWindow,
370
- budget: { ...this.budget },
371
- tokens: this.getEstimatedTokens(),
372
- toolTokens: this.toolTokens,
373
- messageCount: this.messages.length,
374
- quality: this.getQuality(),
375
- compactionCount: this.compactionCount,
376
- iterationsSinceCompaction: this.iterationsSinceCompaction,
377
- };
378
- }
379
- /**
380
- * Replace the system prompt in place (keeps it first) or prepend a new one.
381
- * Used to refresh dynamic prompt blocks (e.g. the plan checklist) mid-run.
382
- */
383
- updateSystemPrompt(content) {
384
- const idx = this.messages.findIndex((m) => m.role === "system");
385
- if (idx >= 0) {
386
- this.messages[idx] = { ...this.messages[idx], content };
387
- }
388
- else {
389
- this.messages.unshift({ role: "system", content });
390
- }
391
- }
392
- getActiveHistory() {
393
- return [...this.messages];
394
- }
395
- /**
396
- * Reset everything that belongs to the current conversation turn.
397
- * Fact lists (FactExtractor) intentionally survive clear() — they are
398
- * session-scoped compaction state, not per-turn.
399
- */
400
- clear() {
401
- this.messages = [];
402
- this.compactedBlock = null;
403
- this.iterationsSinceCompaction = 0;
404
- this.compactionCount = 0;
405
- this.peakTokens = 0;
406
- this.lastUserTask = "";
407
- this.lastUserFeedback = "";
408
- this.sessionMission = "";
409
- }
410
- getEstimatedTokens() {
411
- return (this.messages.reduce((sum, m) => sum + this.estimateMessageTokens(m), 0) + this.toolTokens);
412
- }
413
- setToolTokens(tokens) {
414
- this.toolTokens = tokens;
415
- }
416
- resize(contextWindow, contextBudget, tokenCounter) {
417
- this.contextWindow = contextWindow;
418
- this.budget = this.calculateBudget(contextWindow, contextBudget);
419
- if (tokenCounter !== undefined) {
420
- this.tokenCounter = tokenCounter ?? null;
421
- }
422
- }
423
- }