micro-models-agent 0.47.1 → 0.48.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 -312
  2. package/dist/cli/commands.js +323 -0
  3. package/dist/cli/completer.js +167 -0
  4. package/dist/cli/index.js +2 -0
  5. package/dist/cli/main.js +165 -0
  6. package/dist/cli/plugin-commands.js +36 -0
  7. package/dist/cli/repl-commands.js +661 -0
  8. package/dist/cli/repl.js +616 -0
  9. package/dist/cli/run-result.js +22 -0
  10. package/dist/cli/security-commands.js +164 -0
  11. package/dist/cli/setup.js +231 -0
  12. package/dist/config/config.js +249 -0
  13. package/dist/config/defaults.js +124 -0
  14. package/dist/config/experts.js +15 -0
  15. package/dist/config/index.js +3 -0
  16. package/dist/config/security.js +193 -0
  17. package/dist/config/types.js +1 -0
  18. package/dist/core/agent-moe.js +102 -0
  19. package/dist/core/agent.js +886 -0
  20. package/dist/core/bootstrap.js +404 -0
  21. package/dist/core/index.js +2 -0
  22. package/dist/core/prompt-builder.js +76 -0
  23. package/dist/core/session-logger.js +197 -0
  24. package/dist/core/types.js +1 -0
  25. package/dist/core/version.js +24 -0
  26. package/dist/core/workspace.js +76 -0
  27. package/dist/i18n/en.json +598 -0
  28. package/dist/i18n/index.js +46 -0
  29. package/dist/i18n/ru.json +598 -0
  30. package/dist/index.js +22 -0
  31. package/dist/llm/image-utils.js +143 -0
  32. package/dist/llm/index.js +4 -0
  33. package/dist/llm/model-loader.js +78 -0
  34. package/dist/llm/openai-compat.js +359 -0
  35. package/dist/llm/orchestrator.js +198 -0
  36. package/dist/llm/provider.js +10 -0
  37. package/dist/llm/response.js +39 -0
  38. package/dist/llm/token-counter.js +39 -0
  39. package/dist/llm/types.js +1 -0
  40. package/dist/logger/app-logger.js +143 -0
  41. package/dist/logger/file-log.js +151 -0
  42. package/dist/logger/index.js +1 -0
  43. package/dist/main.js +677 -358
  44. package/dist/migration/backup.js +45 -0
  45. package/dist/migration/detect.js +50 -0
  46. package/dist/migration/index.js +2 -0
  47. package/dist/modules/artifacts/store.js +61 -0
  48. package/dist/modules/browser/actions.js +76 -0
  49. package/dist/modules/browser/bridge-client.js +199 -0
  50. package/dist/modules/browser/bridge-path.js +10 -0
  51. package/dist/modules/browser/bridge-server.mjs +202 -202
  52. package/dist/modules/browser/cookie-store.js +24 -0
  53. package/dist/modules/browser/driver.js +136 -0
  54. package/dist/modules/browser/index.js +7 -0
  55. package/dist/modules/browser/module.js +29 -0
  56. package/dist/modules/browser/session.js +338 -0
  57. package/dist/modules/browser/snapshot.js +148 -0
  58. package/dist/modules/browser/types.js +12 -0
  59. package/dist/modules/certification/cli.js +174 -0
  60. package/dist/modules/certification/fact-checker.js +82 -0
  61. package/dist/modules/certification/loader.js +105 -0
  62. package/dist/modules/certification/manifest.js +50 -0
  63. package/dist/modules/certification/runner.js +159 -0
  64. package/dist/modules/certification/scenarios.js +124 -0
  65. package/dist/modules/certification/types.js +1 -0
  66. package/dist/modules/context/chunk-query.js +100 -0
  67. package/dist/modules/context/fact-extractor.js +162 -0
  68. package/dist/modules/context/history.js +15 -0
  69. package/dist/modules/context/index.js +1 -0
  70. package/dist/modules/context/manager.js +423 -0
  71. package/dist/modules/execution/audit-runners.js +152 -0
  72. package/dist/modules/execution/auditor.js +218 -0
  73. package/dist/modules/execution/execution-plugin.js +272 -0
  74. package/dist/modules/execution/index.js +8 -0
  75. package/dist/modules/execution/module.js +436 -0
  76. package/dist/modules/execution/moe-executor.js +291 -0
  77. package/dist/modules/execution/plan-coverage.js +68 -0
  78. package/dist/modules/execution/plan-persister.js +46 -0
  79. package/dist/modules/execution/plan-store.js +157 -0
  80. package/dist/modules/execution/plan-tool.js +508 -0
  81. package/dist/modules/execution/plan-validator.js +153 -0
  82. package/dist/modules/execution/planner.js +90 -0
  83. package/dist/modules/execution/stuck-detector.js +510 -0
  84. package/dist/modules/execution/tracker.js +67 -0
  85. package/dist/modules/execution/types.js +1 -0
  86. package/dist/modules/execution/verifier.js +222 -0
  87. package/dist/modules/execution/windows-commands.js +41 -0
  88. package/dist/modules/hallucination/confidence.js +66 -0
  89. package/dist/modules/hallucination/consistency.js +26 -0
  90. package/dist/modules/hallucination/detector.js +43 -0
  91. package/dist/modules/hallucination/factual.js +129 -0
  92. package/dist/modules/hallucination/index.js +5 -0
  93. package/dist/modules/hallucination/js-identifiers.js +262 -0
  94. package/dist/modules/hallucination/llm-judge.js +101 -0
  95. package/dist/modules/index.js +5 -0
  96. package/dist/modules/indexer/cache.js +40 -0
  97. package/dist/modules/indexer/index.js +3 -0
  98. package/dist/modules/indexer/module.js +245 -0
  99. package/dist/modules/indexer/project-profile.js +183 -0
  100. package/dist/modules/indexer/walker.js +101 -0
  101. package/dist/modules/lsp/check-tool.js +58 -0
  102. package/dist/modules/lsp/client.js +278 -0
  103. package/dist/modules/lsp/command.js +60 -0
  104. package/dist/modules/lsp/config.js +135 -0
  105. package/dist/modules/lsp/index.js +3 -0
  106. package/dist/modules/lsp/module.js +232 -0
  107. package/dist/modules/lsp/probe.js +76 -0
  108. package/dist/modules/lsp/project-root.js +32 -0
  109. package/dist/modules/lsp/startup-check.js +141 -0
  110. package/dist/modules/lsp/types.js +1 -0
  111. package/dist/modules/mcp/client.js +399 -0
  112. package/dist/modules/mcp/index.js +3 -0
  113. package/dist/modules/mcp/module.js +142 -0
  114. package/dist/modules/mcp/registry.js +15 -0
  115. package/dist/modules/memory/index.js +1 -0
  116. package/dist/modules/memory/module.js +96 -0
  117. package/dist/modules/memory/search.js +42 -0
  118. package/dist/modules/memory/store.js +69 -0
  119. package/dist/modules/pipelines/engine.js +60 -0
  120. package/dist/modules/pipelines/index.js +3 -0
  121. package/dist/modules/pipelines/parser.js +56 -0
  122. package/dist/modules/pipelines/template.js +14 -0
  123. package/dist/modules/plugins/builtin/lint-on-write.js +231 -0
  124. package/dist/modules/plugins/builtin/notify.js +9 -0
  125. package/dist/modules/plugins/index.js +1 -0
  126. package/dist/modules/plugins/loader.js +70 -0
  127. package/dist/modules/plugins/manager.js +217 -0
  128. package/dist/modules/plugins/types.js +1 -0
  129. package/dist/modules/processes/detect.js +34 -0
  130. package/dist/modules/processes/index.js +2 -0
  131. package/dist/modules/processes/registry.js +327 -0
  132. package/dist/modules/processes/runner.js +23 -0
  133. package/dist/modules/registry.js +47 -0
  134. package/dist/modules/security/audit-log.js +136 -0
  135. package/dist/modules/security/audit-notifier.js +292 -0
  136. package/dist/modules/security/command-validator.js +205 -0
  137. package/dist/modules/security/content-scanner.js +53 -0
  138. package/dist/modules/security/data-sanitizer.js +89 -0
  139. package/dist/modules/security/encryption.js +242 -0
  140. package/dist/modules/security/index.js +14 -0
  141. package/dist/modules/security/network-validator.js +71 -0
  142. package/dist/modules/security/path-validator.js +207 -0
  143. package/dist/modules/security/rate-limiter.js +119 -0
  144. package/dist/modules/security/security-policies.js +531 -0
  145. package/dist/modules/security/session-encryption.js +210 -0
  146. package/dist/modules/security/session-isolation.js +95 -0
  147. package/dist/modules/session/index.js +3 -0
  148. package/dist/modules/session/manager.js +172 -0
  149. package/dist/modules/session/module.js +24 -0
  150. package/dist/modules/session/store.js +222 -0
  151. package/dist/modules/session/types.js +1 -0
  152. package/dist/modules/skills/index.js +2 -0
  153. package/dist/modules/skills/loader.js +72 -0
  154. package/dist/modules/skills/matcher.js +27 -0
  155. package/dist/modules/skills/module.js +129 -0
  156. package/dist/modules/types.js +1 -0
  157. package/dist/modules/updater/checker.js +96 -0
  158. package/dist/modules/updater/index.js +2 -0
  159. package/dist/modules/updater/module.js +116 -0
  160. package/dist/modules/user-profile/compressor.js +16 -0
  161. package/dist/modules/user-profile/index.js +1 -0
  162. package/dist/modules/user-profile/profile.js +68 -0
  163. package/dist/skills/builtin/git.md +36 -36
  164. package/dist/skills/builtin/typescript.md +35 -35
  165. package/dist/tools/approve.js +32 -0
  166. package/dist/tools/attach-image.js +89 -0
  167. package/dist/tools/bash.js +496 -0
  168. package/dist/tools/browser.js +114 -0
  169. package/dist/tools/chunk-query.js +99 -0
  170. package/dist/tools/create-dir.js +55 -0
  171. package/dist/tools/delete-file.js +62 -0
  172. package/dist/tools/download-file.js +116 -0
  173. package/dist/tools/edit-file.js +79 -0
  174. package/dist/tools/enable-tools.js +58 -0
  175. package/dist/tools/executor.js +144 -0
  176. package/dist/tools/file-info.js +46 -0
  177. package/dist/tools/filter-tools.js +17 -0
  178. package/dist/tools/glob-tool.js +26 -0
  179. package/dist/tools/grep-tool.js +84 -0
  180. package/dist/tools/hidden-tools-block.js +37 -0
  181. package/dist/tools/index.js +78 -0
  182. package/dist/tools/list-dir.js +48 -0
  183. package/dist/tools/load-skill.js +42 -0
  184. package/dist/tools/mcp-call.js +68 -0
  185. package/dist/tools/move-file.js +85 -0
  186. package/dist/tools/path-utils.js +51 -0
  187. package/dist/tools/pipeline-run.js +144 -0
  188. package/dist/tools/preview.js +2 -0
  189. package/dist/tools/process-kill.js +29 -0
  190. package/dist/tools/process-list.js +36 -0
  191. package/dist/tools/process-log.js +45 -0
  192. package/dist/tools/question.js +140 -0
  193. package/dist/tools/read-file.js +91 -0
  194. package/dist/tools/recall.js +117 -0
  195. package/dist/tools/registry.js +47 -0
  196. package/dist/tools/remember.js +67 -0
  197. package/dist/tools/scope-check.js +30 -0
  198. package/dist/tools/search-history.js +84 -0
  199. package/dist/tools/subagent.js +196 -0
  200. package/dist/tools/types.js +1 -0
  201. package/dist/tools/user-input.js +123 -0
  202. package/dist/tools/web-browse.js +86 -0
  203. package/dist/tools/web-fetch.js +98 -0
  204. package/dist/tools/web-search.js +78 -0
  205. package/dist/tools/write-file.js +81 -0
  206. package/dist/ui/box.js +77 -0
  207. package/dist/ui/colors.js +4 -0
  208. package/dist/ui/diff.js +178 -0
  209. package/dist/ui/index.js +6 -0
  210. package/dist/ui/line-editor.js +703 -0
  211. package/dist/ui/line-math.js +69 -0
  212. package/dist/ui/md-formatter.js +212 -0
  213. package/dist/ui/output.js +13 -0
  214. package/dist/ui/plan-view.js +103 -0
  215. package/dist/ui/renderer.js +209 -0
  216. package/dist/ui/spinner.js +70 -0
  217. package/dist/ui/table.js +144 -0
  218. package/package.json +48 -48
@@ -0,0 +1,162 @@
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
+ }
@@ -0,0 +1,15 @@
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
+ }
@@ -0,0 +1 @@
1
+ export { ContextManager } from "./manager";
@@ -0,0 +1,423 @@
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
+ }