micro-models-agent 0.28.9 → 0.28.17

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 (184) hide show
  1. package/dist/cli/commands.js +333 -0
  2. package/dist/cli/completer.js +168 -0
  3. package/dist/cli/index.js +2 -0
  4. package/dist/cli/main.js +140 -0
  5. package/dist/cli/repl-commands.js +633 -0
  6. package/dist/cli/repl.js +486 -0
  7. package/dist/cli/security-commands.js +166 -0
  8. package/dist/cli/setup.js +249 -0
  9. package/dist/config/config.js +202 -0
  10. package/dist/config/defaults.js +100 -0
  11. package/dist/config/experts.js +15 -0
  12. package/dist/config/index.js +3 -0
  13. package/dist/config/security.js +200 -0
  14. package/dist/config/types.js +1 -0
  15. package/dist/core/agent-moe.js +110 -0
  16. package/dist/core/agent.js +695 -0
  17. package/dist/core/bootstrap.js +337 -0
  18. package/dist/core/index.js +2 -0
  19. package/dist/core/prompt-builder.js +55 -0
  20. package/dist/core/session-logger.js +155 -0
  21. package/dist/core/types.js +1 -0
  22. package/dist/core/workspace.js +76 -0
  23. package/dist/i18n/en.json +525 -0
  24. package/dist/i18n/index.js +46 -0
  25. package/dist/i18n/ru.json +525 -0
  26. package/dist/index.js +22 -0
  27. package/dist/llm/image-utils.js +144 -0
  28. package/dist/llm/index.js +4 -0
  29. package/dist/llm/model-loader.js +78 -0
  30. package/dist/llm/openai-compat.js +353 -0
  31. package/dist/llm/orchestrator.js +194 -0
  32. package/dist/llm/provider.js +10 -0
  33. package/dist/llm/response.js +39 -0
  34. package/dist/llm/token-counter.js +39 -0
  35. package/dist/llm/types.js +1 -0
  36. package/dist/logger/app-logger.js +143 -0
  37. package/dist/logger/file-log.js +151 -0
  38. package/dist/logger/index.js +1 -0
  39. package/dist/main.js +1758 -612
  40. package/dist/migration/backup.js +45 -0
  41. package/dist/migration/detect.js +50 -0
  42. package/dist/migration/index.js +2 -0
  43. package/dist/modules/browser/actions.js +46 -0
  44. package/dist/modules/browser/cookie-store.js +24 -0
  45. package/dist/modules/browser/index.js +5 -0
  46. package/dist/modules/browser/module.js +28 -0
  47. package/dist/modules/browser/session.js +335 -0
  48. package/dist/modules/browser/snapshot.js +114 -0
  49. package/dist/modules/browser/types.js +9 -0
  50. package/dist/modules/certification/cli.js +176 -0
  51. package/dist/modules/certification/fact-checker.js +84 -0
  52. package/dist/modules/certification/loader.js +111 -0
  53. package/dist/modules/certification/manifest.js +50 -0
  54. package/dist/modules/certification/runner.js +162 -0
  55. package/dist/modules/certification/scenarios.js +124 -0
  56. package/dist/modules/certification/types.js +1 -0
  57. package/dist/modules/context/index.js +1 -0
  58. package/dist/modules/context/manager.js +349 -0
  59. package/dist/modules/execution/auditor.js +66 -0
  60. package/dist/modules/execution/index.js +8 -0
  61. package/dist/modules/execution/module.js +779 -0
  62. package/dist/modules/execution/moe-executor.js +266 -0
  63. package/dist/modules/execution/plan-coverage.js +68 -0
  64. package/dist/modules/execution/plan-persister.js +46 -0
  65. package/dist/modules/execution/plan-store.js +159 -0
  66. package/dist/modules/execution/plan-validator.js +153 -0
  67. package/dist/modules/execution/planner.js +85 -0
  68. package/dist/modules/execution/stuck-detector.js +347 -0
  69. package/dist/modules/execution/tracker.js +67 -0
  70. package/dist/modules/execution/types.js +1 -0
  71. package/dist/modules/execution/verifier.js +178 -0
  72. package/dist/modules/hallucination/confidence.js +59 -0
  73. package/dist/modules/hallucination/consistency.js +26 -0
  74. package/dist/modules/hallucination/detector.js +46 -0
  75. package/dist/modules/hallucination/factual.js +190 -0
  76. package/dist/modules/hallucination/index.js +5 -0
  77. package/dist/modules/hallucination/js-identifiers.js +72 -0
  78. package/dist/modules/hallucination/llm-judge.js +103 -0
  79. package/dist/modules/index.js +5 -0
  80. package/dist/modules/indexer/cache.js +38 -0
  81. package/dist/modules/indexer/index.js +3 -0
  82. package/dist/modules/indexer/module.js +192 -0
  83. package/dist/modules/indexer/walker.js +101 -0
  84. package/dist/modules/lsp/client.js +235 -0
  85. package/dist/modules/lsp/config.js +81 -0
  86. package/dist/modules/lsp/index.js +3 -0
  87. package/dist/modules/lsp/module.js +68 -0
  88. package/dist/modules/lsp/types.js +1 -0
  89. package/dist/modules/mcp/client.js +399 -0
  90. package/dist/modules/mcp/index.js +3 -0
  91. package/dist/modules/mcp/module.js +146 -0
  92. package/dist/modules/mcp/registry.js +15 -0
  93. package/dist/modules/memory/index.js +1 -0
  94. package/dist/modules/memory/module.js +48 -0
  95. package/dist/modules/memory/search.js +40 -0
  96. package/dist/modules/memory/store.js +69 -0
  97. package/dist/modules/pipelines/engine.js +60 -0
  98. package/dist/modules/pipelines/index.js +3 -0
  99. package/dist/modules/pipelines/parser.js +53 -0
  100. package/dist/modules/pipelines/template.js +14 -0
  101. package/dist/modules/plugins/builtin/lint-on-write.js +226 -0
  102. package/dist/modules/plugins/builtin/notify.js +8 -0
  103. package/dist/modules/plugins/index.js +1 -0
  104. package/dist/modules/plugins/loader.js +28 -0
  105. package/dist/modules/plugins/manager.js +161 -0
  106. package/dist/modules/plugins/types.js +1 -0
  107. package/dist/modules/processes/index.js +2 -0
  108. package/dist/modules/processes/registry.js +238 -0
  109. package/dist/modules/processes/runner.js +23 -0
  110. package/dist/modules/registry.js +45 -0
  111. package/dist/modules/security/audit-log.js +136 -0
  112. package/dist/modules/security/audit-notifier.js +292 -0
  113. package/dist/modules/security/command-validator.js +211 -0
  114. package/dist/modules/security/content-scanner.js +53 -0
  115. package/dist/modules/security/data-sanitizer.js +97 -0
  116. package/dist/modules/security/encryption.js +240 -0
  117. package/dist/modules/security/index.js +14 -0
  118. package/dist/modules/security/network-validator.js +79 -0
  119. package/dist/modules/security/path-validator.js +209 -0
  120. package/dist/modules/security/rate-limiter.js +119 -0
  121. package/dist/modules/security/security-policies.js +547 -0
  122. package/dist/modules/security/session-encryption.js +210 -0
  123. package/dist/modules/security/session-isolation.js +95 -0
  124. package/dist/modules/session/index.js +3 -0
  125. package/dist/modules/session/manager.js +172 -0
  126. package/dist/modules/session/module.js +24 -0
  127. package/dist/modules/session/store.js +228 -0
  128. package/dist/modules/session/types.js +1 -0
  129. package/dist/modules/skills/index.js +2 -0
  130. package/dist/modules/skills/loader.js +72 -0
  131. package/dist/modules/skills/module.js +130 -0
  132. package/dist/modules/types.js +1 -0
  133. package/dist/modules/updater/checker.js +32 -0
  134. package/dist/modules/updater/index.js +1 -0
  135. package/dist/modules/user-profile/compressor.js +16 -0
  136. package/dist/modules/user-profile/index.js +1 -0
  137. package/dist/modules/user-profile/profile.js +68 -0
  138. package/dist/tools/approve.js +32 -0
  139. package/dist/tools/attach-image.js +89 -0
  140. package/dist/tools/bash.js +337 -0
  141. package/dist/tools/browser.js +97 -0
  142. package/dist/tools/create-dir.js +55 -0
  143. package/dist/tools/delete-file.js +62 -0
  144. package/dist/tools/edit-file.js +79 -0
  145. package/dist/tools/executor.js +145 -0
  146. package/dist/tools/file-info.js +45 -0
  147. package/dist/tools/filter-tools.js +10 -0
  148. package/dist/tools/glob-tool.js +26 -0
  149. package/dist/tools/grep-tool.js +86 -0
  150. package/dist/tools/index.js +67 -0
  151. package/dist/tools/list-dir.js +47 -0
  152. package/dist/tools/load-skill.js +44 -0
  153. package/dist/tools/mcp-call.js +68 -0
  154. package/dist/tools/move-file.js +85 -0
  155. package/dist/tools/path-utils.js +51 -0
  156. package/dist/tools/pipeline-run.js +144 -0
  157. package/dist/tools/preview.js +2 -0
  158. package/dist/tools/process-kill.js +29 -0
  159. package/dist/tools/process-list.js +38 -0
  160. package/dist/tools/process-log.js +41 -0
  161. package/dist/tools/question.js +142 -0
  162. package/dist/tools/read-file.js +83 -0
  163. package/dist/tools/recall.js +110 -0
  164. package/dist/tools/registry.js +36 -0
  165. package/dist/tools/remember.js +67 -0
  166. package/dist/tools/scope-check.js +30 -0
  167. package/dist/tools/search-history.js +84 -0
  168. package/dist/tools/subagent.js +151 -0
  169. package/dist/tools/types.js +1 -0
  170. package/dist/tools/user-input.js +123 -0
  171. package/dist/tools/web-browse.js +86 -0
  172. package/dist/tools/web-fetch.js +98 -0
  173. package/dist/tools/web-search.js +78 -0
  174. package/dist/tools/write-file.js +83 -0
  175. package/dist/ui/box.js +81 -0
  176. package/dist/ui/colors.js +4 -0
  177. package/dist/ui/diff.js +178 -0
  178. package/dist/ui/index.js +6 -0
  179. package/dist/ui/md-formatter.js +212 -0
  180. package/dist/ui/output.js +13 -0
  181. package/dist/ui/renderer.js +204 -0
  182. package/dist/ui/spinner.js +70 -0
  183. package/dist/ui/table.js +144 -0
  184. package/package.json +4 -4
@@ -0,0 +1,228 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, appendFileSync, } from "fs";
2
+ import { join } from "path";
3
+ import { gzipSync } from "zlib";
4
+ import { SessionFileEncryptor } from "../security/session-encryption";
5
+ export class SessionStore {
6
+ baseDir;
7
+ encryptor = null;
8
+ // In-memory meta cache to avoid O(N²) disk reads on appendMessage.
9
+ _metaCache = new Map();
10
+ constructor(baseDir, encryptionConfig) {
11
+ this.baseDir = baseDir;
12
+ if (encryptionConfig?.enabled) {
13
+ this.encryptor = new SessionFileEncryptor(encryptionConfig);
14
+ }
15
+ }
16
+ getSessionDir(id) {
17
+ return join(this.baseDir, id);
18
+ }
19
+ /**
20
+ * Update encryption configuration
21
+ */
22
+ updateEncryption(config) {
23
+ if (config?.enabled) {
24
+ this.encryptor = new SessionFileEncryptor(config);
25
+ }
26
+ else {
27
+ this.encryptor = null;
28
+ }
29
+ }
30
+ /**
31
+ * Check if encryption is enabled
32
+ */
33
+ isEncryptionEnabled() {
34
+ return this.encryptor?.isEnabled() ?? false;
35
+ }
36
+ init() {
37
+ mkdirSync(this.baseDir, { recursive: true });
38
+ }
39
+ sessionDir(id) {
40
+ return join(this.baseDir, id);
41
+ }
42
+ metaPath(id) {
43
+ return join(this.sessionDir(id), "meta.json");
44
+ }
45
+ historyPath(id) {
46
+ return join(this.sessionDir(id), "history.jsonl");
47
+ }
48
+ sessionLogPath(id) {
49
+ return join(this.sessionDir(id), "session.jsonl");
50
+ }
51
+ sessionExists(id) {
52
+ return existsSync(this.metaPath(id));
53
+ }
54
+ saveMeta(id, meta) {
55
+ this._metaCache.set(id, meta);
56
+ const dir = this.sessionDir(id);
57
+ mkdirSync(dir, { recursive: true });
58
+ const content = JSON.stringify(meta, null, 2);
59
+ if (this.encryptor) {
60
+ writeFileSync(this.metaPath(id), this.encryptor.encryptFileContent(content), "utf-8");
61
+ }
62
+ else {
63
+ writeFileSync(this.metaPath(id), content, "utf-8");
64
+ }
65
+ }
66
+ loadMeta(id) {
67
+ const cached = this._metaCache.get(id);
68
+ if (cached)
69
+ return cached;
70
+ const path = this.metaPath(id);
71
+ if (!existsSync(path))
72
+ return null;
73
+ try {
74
+ const raw = readFileSync(path, "utf-8");
75
+ const content = this.encryptor
76
+ ? this.encryptor.decryptFileContent(raw)
77
+ : raw;
78
+ const meta = JSON.parse(content);
79
+ this._metaCache.set(id, meta);
80
+ return meta;
81
+ }
82
+ catch {
83
+ return null;
84
+ }
85
+ }
86
+ appendMessage(id, msg) {
87
+ const dir = this.sessionDir(id);
88
+ mkdirSync(dir, { recursive: true });
89
+ const line = JSON.stringify(msg);
90
+ if (this.encryptor?.isEnabled()) {
91
+ appendFileSync(this.historyPath(id), this.encryptor.encryptFileContent(line) + "\n", "utf-8");
92
+ }
93
+ else {
94
+ appendFileSync(this.historyPath(id), line + "\n", "utf-8");
95
+ }
96
+ const meta = this.loadMeta(id);
97
+ if (meta) {
98
+ meta.messageCount = (meta.messageCount || 0) + 1;
99
+ meta.updatedAt = msg.timestamp || new Date().toISOString();
100
+ this.saveMeta(id, meta);
101
+ }
102
+ }
103
+ loadHistory(id) {
104
+ const path = this.historyPath(id);
105
+ if (!existsSync(path))
106
+ return [];
107
+ try {
108
+ const raw = readFileSync(path, "utf-8");
109
+ const lines = raw.split("\n").filter(Boolean);
110
+ const parseLine = (line) => {
111
+ try {
112
+ return JSON.parse(line);
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ };
118
+ if (this.encryptor?.isEnabled()) {
119
+ return lines
120
+ .map((line) => {
121
+ try {
122
+ return this.encryptor.decryptFileContent(line);
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ })
128
+ .filter((l) => l !== null)
129
+ .map(parseLine)
130
+ .filter((m) => m !== null);
131
+ }
132
+ return lines
133
+ .map(parseLine)
134
+ .filter((m) => m !== null);
135
+ }
136
+ catch {
137
+ return [];
138
+ }
139
+ }
140
+ appendSessionLog(id, entry) {
141
+ const dir = this.sessionDir(id);
142
+ mkdirSync(dir, { recursive: true });
143
+ const line = JSON.stringify(entry);
144
+ if (this.encryptor?.isEnabled()) {
145
+ appendFileSync(this.sessionLogPath(id), this.encryptor.encryptFileContent(line) + "\n", "utf-8");
146
+ }
147
+ else {
148
+ appendFileSync(this.sessionLogPath(id), line + "\n", "utf-8");
149
+ }
150
+ }
151
+ loadSessionLog(id) {
152
+ const path = this.sessionLogPath(id);
153
+ if (!existsSync(path))
154
+ return [];
155
+ try {
156
+ const raw = readFileSync(path, "utf-8");
157
+ const lines = raw.split("\n").filter(Boolean);
158
+ const parseLine = (line) => {
159
+ try {
160
+ return JSON.parse(line);
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ };
166
+ if (this.encryptor?.isEnabled()) {
167
+ return lines
168
+ .map((line) => {
169
+ try {
170
+ return this.encryptor.decryptFileContent(line);
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ })
176
+ .filter((l) => l !== null)
177
+ .map(parseLine)
178
+ .filter((e) => e !== null);
179
+ }
180
+ return lines
181
+ .map(parseLine)
182
+ .filter((e) => e !== null);
183
+ }
184
+ catch {
185
+ return [];
186
+ }
187
+ }
188
+ listSessions() {
189
+ if (!existsSync(this.baseDir))
190
+ return [];
191
+ const entries = readdirSync(this.baseDir, { withFileTypes: true });
192
+ const sessions = [];
193
+ for (const entry of entries) {
194
+ if (entry.isDirectory()) {
195
+ const meta = this.loadMeta(entry.name);
196
+ if (meta)
197
+ sessions.push(meta);
198
+ }
199
+ }
200
+ sessions.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
201
+ return sessions;
202
+ }
203
+ deleteSession(id) {
204
+ this._metaCache.delete(id);
205
+ const dir = this.sessionDir(id);
206
+ if (existsSync(dir)) {
207
+ rmSync(dir, { recursive: true, force: true });
208
+ }
209
+ }
210
+ rotateOldSessions() {
211
+ const thirtyDaysAgo = new Date();
212
+ thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
213
+ const sessions = this.listSessions();
214
+ for (const session of sessions) {
215
+ const updatedAt = new Date(session.updatedAt);
216
+ if (updatedAt < thirtyDaysAgo) {
217
+ const historyPath = this.historyPath(session.id);
218
+ if (existsSync(historyPath)) {
219
+ const content = readFileSync(historyPath, "utf-8");
220
+ const compressed = gzipSync(content);
221
+ const gzPath = join(this.baseDir, `${session.id}.jsonl.gz`);
222
+ writeFileSync(gzPath, compressed);
223
+ rmSync(historyPath);
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export { SkillsLoader } from "./loader";
2
+ export { SkillsModule } from "./module";
@@ -0,0 +1,72 @@
1
+ import { readdirSync, readFileSync, existsSync, statSync } from "fs";
2
+ import { join } from "path";
3
+ export class SkillsLoader {
4
+ loadFromDir(dirPath) {
5
+ if (!existsSync(dirPath))
6
+ return [];
7
+ const skills = [];
8
+ this.scanDir(dirPath, skills);
9
+ return skills;
10
+ }
11
+ scanDir(dirPath, skills) {
12
+ const entries = readdirSync(dirPath);
13
+ for (const entry of entries) {
14
+ const fullPath = join(dirPath, entry);
15
+ const stat = statSync(fullPath);
16
+ if (stat.isDirectory()) {
17
+ this.scanDir(fullPath, skills);
18
+ continue;
19
+ }
20
+ if (!entry.endsWith(".md") && !entry.endsWith(".skill.md"))
21
+ continue;
22
+ const content = readFileSync(fullPath, "utf-8");
23
+ const parsed = this.parseSkillFile(content, fullPath);
24
+ if (parsed)
25
+ skills.push(parsed);
26
+ }
27
+ }
28
+ parseSkillFile(content, sourcePath) {
29
+ const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
30
+ if (!match)
31
+ return null;
32
+ const frontmatter = this.parseFrontmatter(match[1]);
33
+ if (!frontmatter.name)
34
+ return null;
35
+ if (frontmatter.mma_version && String(frontmatter.mma_version) !== "2") {
36
+ return null;
37
+ }
38
+ return {
39
+ name: frontmatter.name,
40
+ description: frontmatter.description || "",
41
+ keywords: frontmatter.keywords || [],
42
+ content: match[2].trim(),
43
+ sourcePath,
44
+ };
45
+ }
46
+ parseFrontmatter(yaml) {
47
+ const result = {};
48
+ for (const line of yaml.split("\n")) {
49
+ const kvMatch = line.match(/^(\w+):\s*(.+)$/);
50
+ if (kvMatch) {
51
+ const val = kvMatch[2].trim();
52
+ if (val.startsWith("[") && val.endsWith("]")) {
53
+ result[kvMatch[1]] = val
54
+ .slice(1, -1)
55
+ .split(",")
56
+ .map((s) => s.trim().replace(/^['"]|['"]$/g, ""));
57
+ }
58
+ else {
59
+ result[kvMatch[1]] = val.replace(/^['"]|['"]$/g, "");
60
+ }
61
+ }
62
+ }
63
+ return result;
64
+ }
65
+ loadFromAllSources(builtinDir, globalDir, projectDir) {
66
+ return [
67
+ ...this.loadFromDir(builtinDir),
68
+ ...this.loadFromDir(globalDir),
69
+ ...this.loadFromDir(projectDir),
70
+ ];
71
+ }
72
+ }
@@ -0,0 +1,130 @@
1
+ import { t } from "../../i18n/index";
2
+ export class SkillsModule {
3
+ name = "skills";
4
+ availableSkills;
5
+ loadedSkills = new Map();
6
+ budget;
7
+ currentTokens = 0;
8
+ constructor(availableSkills, budget) {
9
+ this.availableSkills = availableSkills;
10
+ this.budget = budget;
11
+ }
12
+ loadByName(name) {
13
+ if (this.loadedSkills.has(name)) {
14
+ return { success: false, message: t("skill.already_loaded", { name }) };
15
+ }
16
+ const skill = this.availableSkills.find((s) => s.name === name);
17
+ if (!skill) {
18
+ return { success: false, message: t("skill.not_found", { name }) };
19
+ }
20
+ return this.tryLoad(skill);
21
+ }
22
+ unload(name) {
23
+ const skill = this.loadedSkills.get(name);
24
+ if (!skill)
25
+ return false;
26
+ this.loadedSkills.delete(name);
27
+ this.currentTokens -= this.estimateTokens(skill.content);
28
+ return true;
29
+ }
30
+ getLoaded() {
31
+ return Array.from(this.loadedSkills.values());
32
+ }
33
+ getAvailable() {
34
+ return this.availableSkills;
35
+ }
36
+ findByName(name) {
37
+ return this.availableSkills.find((s) => s.name === name);
38
+ }
39
+ search(query) {
40
+ const q = query.toLowerCase();
41
+ return this.availableSkills.filter((s) => s.name.toLowerCase().includes(q) ||
42
+ s.description.toLowerCase().includes(q));
43
+ }
44
+ getBudget() {
45
+ return {
46
+ used: this.currentTokens,
47
+ total: this.budget,
48
+ remaining: this.budget - this.currentTokens,
49
+ };
50
+ }
51
+ getSkillContent(name) {
52
+ const skill = this.loadedSkills.get(name);
53
+ return skill ? skill.content : null;
54
+ }
55
+ getSystemPromptBlock() {
56
+ const lines = [];
57
+ if (this.availableSkills.length > 0) {
58
+ lines.push("[Available Skills]");
59
+ lines.push(t("skill.prompt_hint"));
60
+ for (const skill of this.availableSkills) {
61
+ const desc = skill.description.slice(0, 80);
62
+ lines.push(`- ${skill.name}: ${desc}`);
63
+ }
64
+ }
65
+ if (this.loadedSkills.size > 0) {
66
+ lines.push("");
67
+ lines.push("[Loaded Skills]");
68
+ for (const skill of this.loadedSkills.values()) {
69
+ lines.push(`--- ${skill.name} (${this.estimateTokens(skill.content)} tokens) ---`);
70
+ lines.push(skill.content);
71
+ lines.push("");
72
+ }
73
+ }
74
+ if (lines.length === 0)
75
+ return null;
76
+ const content = lines.join("\n");
77
+ const tokens = this.estimateTokens(content);
78
+ return {
79
+ content,
80
+ priority: "high",
81
+ essential: false,
82
+ estimatedTokens: tokens,
83
+ };
84
+ }
85
+ getPlugin() {
86
+ return {
87
+ name: "skills",
88
+ onSessionStart: (_ctx) => { },
89
+ onBeforeThink: (_ctx) => { },
90
+ };
91
+ }
92
+ tryLoad(skill) {
93
+ const tokens = this.estimateTokens(skill.content);
94
+ if (tokens > this.budget) {
95
+ return {
96
+ success: false,
97
+ message: t("skill.too_large", {
98
+ name: skill.name,
99
+ tokens,
100
+ budget: this.budget,
101
+ }),
102
+ };
103
+ }
104
+ if (this.currentTokens + tokens > this.budget) {
105
+ const remaining = this.budget - this.currentTokens;
106
+ return {
107
+ success: false,
108
+ message: t("skill.exceeds_budget", {
109
+ name: skill.name,
110
+ tokens,
111
+ remaining,
112
+ }),
113
+ };
114
+ }
115
+ this.loadedSkills.set(skill.name, skill);
116
+ this.currentTokens += tokens;
117
+ return {
118
+ success: true,
119
+ message: t("skill.loaded", {
120
+ name: skill.name,
121
+ tokens,
122
+ remaining: this.budget - this.currentTokens,
123
+ }),
124
+ skill,
125
+ };
126
+ }
127
+ estimateTokens(text) {
128
+ return Math.ceil(text.length / 4);
129
+ }
130
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ export class Updater {
2
+ currentVersion;
3
+ packageName;
4
+ constructor(currentVersion, packageName) {
5
+ this.currentVersion = currentVersion;
6
+ this.packageName = packageName;
7
+ }
8
+ getCurrentVersion() {
9
+ return this.currentVersion;
10
+ }
11
+ async check() {
12
+ try {
13
+ const response = await fetch(`https://registry.npmjs.org/${this.packageName}`, {
14
+ headers: { Accept: 'application/vnd.npm.install-v1+json' },
15
+ signal: AbortSignal.timeout(5000),
16
+ });
17
+ if (!response.ok) {
18
+ return { updateAvailable: false, current: this.currentVersion, error: `HTTP ${response.status}` };
19
+ }
20
+ const data = await response.json();
21
+ const latest = data['dist-tags']?.latest;
22
+ if (!latest) {
23
+ return { updateAvailable: false, current: this.currentVersion, error: 'No latest tag' };
24
+ }
25
+ const updateAvailable = latest !== this.currentVersion;
26
+ return { updateAvailable, current: this.currentVersion, latest };
27
+ }
28
+ catch (e) {
29
+ return { updateAvailable: false, current: this.currentVersion, error: e.message };
30
+ }
31
+ }
32
+ }
@@ -0,0 +1 @@
1
+ export { Updater } from './checker';
@@ -0,0 +1,16 @@
1
+ export class ProfileCompressor {
2
+ compress(info) {
3
+ const parts = [
4
+ `OS: ${info.os}`,
5
+ `Shell: ${info.shell}`,
6
+ `Platform: ${info.platform}`,
7
+ ];
8
+ if (Object.keys(info.preferences).length > 0) {
9
+ const prefs = Object.entries(info.preferences)
10
+ .map(([k, v]) => `${k}=${v}`)
11
+ .join(',');
12
+ parts.push(`Prefs: ${prefs}`);
13
+ }
14
+ return parts.join(', ');
15
+ }
16
+ }
@@ -0,0 +1 @@
1
+ export { UserProfile } from './profile';
@@ -0,0 +1,68 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { homedir, hostname, platform, type } from 'os';
4
+ import { env } from 'process';
5
+ import { ProfileCompressor } from './compressor';
6
+ export class UserProfile {
7
+ profileDir;
8
+ info = null;
9
+ preferences = {};
10
+ constructor(profileDir) {
11
+ this.profileDir = profileDir;
12
+ }
13
+ collect() {
14
+ this.info = {
15
+ platform: platform(),
16
+ os: `${type()} ${hostname()}`,
17
+ hostname: hostname(),
18
+ shell: env.SHELL || env.ComSpec || 'unknown',
19
+ home: homedir(),
20
+ nodeVersion: process.version,
21
+ preferences: { ...this.preferences },
22
+ };
23
+ return this.info;
24
+ }
25
+ save() {
26
+ if (!existsSync(this.profileDir)) {
27
+ mkdirSync(this.profileDir, { recursive: true });
28
+ }
29
+ writeFileSync(join(this.profileDir, 'profile.json'), JSON.stringify({ ...this.info, preferences: this.preferences }, null, 2), 'utf-8');
30
+ }
31
+ load() {
32
+ const path = join(this.profileDir, 'profile.json');
33
+ if (!existsSync(path))
34
+ return null;
35
+ try {
36
+ const data = JSON.parse(readFileSync(path, 'utf-8'));
37
+ this.info = {
38
+ platform: data.platform,
39
+ os: data.os,
40
+ hostname: data.hostname,
41
+ shell: data.shell,
42
+ home: data.home,
43
+ nodeVersion: data.nodeVersion,
44
+ preferences: data.preferences || {},
45
+ };
46
+ this.preferences = data.preferences || {};
47
+ return this.info;
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ getInfo() {
54
+ return this.info;
55
+ }
56
+ setPreference(key, value) {
57
+ this.preferences[key] = value;
58
+ }
59
+ getPreference(key) {
60
+ return this.preferences[key];
61
+ }
62
+ compress() {
63
+ if (!this.info)
64
+ this.collect();
65
+ const compressor = new ProfileCompressor();
66
+ return compressor.compress(this.info);
67
+ }
68
+ }
@@ -0,0 +1,32 @@
1
+ import { t } from "../i18n/index";
2
+ import { askChoice } from "./user-input";
3
+ export const approveTool = {
4
+ name: "approve",
5
+ description: "Request user approval for an action. The user picks Yes or No from a menu.",
6
+ tags: ["core"],
7
+ interactive: true,
8
+ parameters: {
9
+ type: "object",
10
+ properties: {
11
+ action: {
12
+ type: "string",
13
+ description: "Description of the action requiring approval",
14
+ },
15
+ },
16
+ required: ["action"],
17
+ },
18
+ handler: async (ctx, args) => {
19
+ if (ctx.exitOnComplete) {
20
+ return { success: false, output: t("tool.interactive_disabled") };
21
+ }
22
+ const action = String(args.action || "");
23
+ const indexes = await askChoice(t("tool.approve_prompt", { action }), [
24
+ { label: t("tool.approve_yes"), description: t("tool.approve_yes_desc") },
25
+ { label: t("tool.approve_no"), description: t("tool.approve_no_desc") },
26
+ ]);
27
+ if (indexes[0] === 0) {
28
+ return { success: true, output: t("tool.approved") };
29
+ }
30
+ return { success: false, output: t("tool.rejected") };
31
+ },
32
+ };
@@ -0,0 +1,89 @@
1
+ import { existsSync } from "fs";
2
+ import { resolve } from "path";
3
+ import { t } from "../i18n/index";
4
+ import { loadFileAsDataUrl, loadUrlAsDataUrl, readClipboardImage, bufferToDataUrl } from "../llm/image-utils";
5
+ import { logSecurityBlock } from "../modules/security/audit-log";
6
+ export const attachImageTool = {
7
+ name: "attach_image",
8
+ description: "Attach an image to the conversation from a file path, URL, or clipboard. The image will be included in the next message sent to the model. Supports PNG, JPEG, GIF, WebP.",
9
+ tags: ["vision", "image"],
10
+ parameters: {
11
+ type: "object",
12
+ properties: {
13
+ source: {
14
+ type: "string",
15
+ description: 'Image source: file path (e.g. "./screenshot.png"), URL (e.g. "https://example.com/img.png"), or "clipboard" to read from system clipboard.',
16
+ },
17
+ },
18
+ required: ["source"],
19
+ },
20
+ handler: async (ctx, args) => {
21
+ const source = String(args.source ?? "").trim();
22
+ if (!source) {
23
+ return { success: false, output: t("image.source_required") };
24
+ }
25
+ try {
26
+ let dataUrl;
27
+ if (source.toLowerCase() === "clipboard") {
28
+ const clipBuf = await readClipboardImage();
29
+ if (!clipBuf) {
30
+ return {
31
+ success: false,
32
+ output: t("image.clipboard_empty"),
33
+ };
34
+ }
35
+ const result = await bufferToDataUrl(clipBuf);
36
+ dataUrl = result.dataUrl;
37
+ }
38
+ else if (source.startsWith("http://") || source.startsWith("https://")) {
39
+ const result = await loadUrlAsDataUrl(source);
40
+ dataUrl = result.dataUrl;
41
+ }
42
+ else {
43
+ const absPath = resolve(ctx.baseDir, source);
44
+ if (!existsSync(absPath)) {
45
+ return {
46
+ success: false,
47
+ output: t("image.not_found", { path: source }),
48
+ };
49
+ }
50
+ // Security: check path scope
51
+ if (ctx.scope) {
52
+ const { isPathInScope } = await import("../modules/security/path-validator");
53
+ const validation = isPathInScope(ctx.baseDir, absPath, ctx.scope);
54
+ if (!validation.allowed) {
55
+ logSecurityBlock(ctx.sessionId, "file_read", validation.reason ?? "attach_image out of scope", absPath);
56
+ return {
57
+ success: false,
58
+ output: t("file.path_not_allowed", { path: source }),
59
+ };
60
+ }
61
+ }
62
+ const result = await loadFileAsDataUrl(absPath);
63
+ dataUrl = result.dataUrl;
64
+ }
65
+ // Add the image as a pending content part on the context manager
66
+ if (!ctx.contextManager) {
67
+ return {
68
+ success: false,
69
+ output: t("image.no_context"),
70
+ };
71
+ }
72
+ ctx.contextManager.addPendingImage({
73
+ type: "image_url",
74
+ image_url: { url: dataUrl },
75
+ });
76
+ const sizeKb = Math.round((dataUrl.length * 3) / 4 / 1024);
77
+ return {
78
+ success: true,
79
+ output: t("image.attached", { source, size: `${sizeKb} KB` }),
80
+ };
81
+ }
82
+ catch (err) {
83
+ return {
84
+ success: false,
85
+ output: t("image.error", { message: err.message }),
86
+ };
87
+ }
88
+ },
89
+ };