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,183 +0,0 @@
1
- import { readFileSync, existsSync } from "fs";
2
- import { join } from "path";
3
- import { t } from "../../i18n/index";
4
- const MANIFEST_ORDER = [
5
- "package.json",
6
- "pyproject.toml",
7
- "Cargo.toml",
8
- "go.mod",
9
- "requirements.txt",
10
- ];
11
- const MAX_DEPS = 5;
12
- const MAX_DEV_DEPS = 3;
13
- const MAX_SCRIPTS = 3;
14
- /**
15
- * Find the first existing manifest in priority order (best-effort, root only).
16
- */
17
- export function detectManifest(baseDir) {
18
- for (const manifest of MANIFEST_ORDER) {
19
- if (existsSync(join(baseDir, manifest)))
20
- return manifest;
21
- }
22
- return null;
23
- }
24
- /** Strip version specifiers from a manifest dependency entry. */
25
- function cleanDependency(entry) {
26
- let name = entry.trim();
27
- const eq = name.indexOf("=");
28
- if (eq > 0)
29
- name = name.slice(0, eq);
30
- const ineq = name.search(/[<>=!~^]/);
31
- if (ineq > 0)
32
- name = name.slice(0, ineq);
33
- return name.replace(/["',]/g, "").trim();
34
- }
35
- function readPackageJson(baseDir) {
36
- try {
37
- const raw = JSON.parse(readFileSync(join(baseDir, "package.json"), "utf-8"));
38
- if (!raw || typeof raw !== "object")
39
- return null;
40
- const profile = {
41
- runtime: "node",
42
- deps: Object.keys(raw.dependencies || {}),
43
- devDeps: Object.keys(raw.devDependencies || {}),
44
- scripts: {},
45
- };
46
- if (typeof raw.name === "string" && raw.name)
47
- profile.name = raw.name;
48
- if (raw.scripts && typeof raw.scripts === "object") {
49
- for (const [key, val] of Object.entries(raw.scripts)) {
50
- if (typeof val === "string" && val)
51
- profile.scripts[key] = val;
52
- }
53
- }
54
- return profile;
55
- }
56
- catch {
57
- return null;
58
- }
59
- }
60
- function readPyproject(baseDir) {
61
- try {
62
- const content = readFileSync(join(baseDir, "pyproject.toml"), "utf-8");
63
- const profile = { runtime: "python", deps: [], devDeps: [], scripts: {} };
64
- const nameMatch = content.match(/^\s*name\s*=\s*"([^"]+)"/m);
65
- if (nameMatch)
66
- profile.name = nameMatch[1];
67
- const depsBlock = content.match(/dependencies\s*=\s*\[([\s\S]*?)\]/);
68
- if (depsBlock) {
69
- profile.deps = [...depsBlock[1].matchAll(/"([^"]+)"/g)]
70
- .map((m) => cleanDependency(m[1]))
71
- .filter(Boolean);
72
- }
73
- return profile;
74
- }
75
- catch {
76
- return null;
77
- }
78
- }
79
- function readCargo(baseDir) {
80
- try {
81
- const content = readFileSync(join(baseDir, "Cargo.toml"), "utf-8");
82
- const profile = { runtime: "rust", deps: [], devDeps: [], scripts: {} };
83
- const nameMatch = content.match(/^\s*name\s*=\s*"([^"]+)"/m);
84
- if (nameMatch)
85
- profile.name = nameMatch[1];
86
- let inDeps = false;
87
- for (const line of content.split("\n")) {
88
- const trimmed = line.trim();
89
- if (/^\[.*\]$/.test(trimmed)) {
90
- inDeps = trimmed === "[dependencies]";
91
- continue;
92
- }
93
- if (inDeps && /^[A-Za-z0-9_-]+\s*=/.test(trimmed)) {
94
- profile.deps.push(trimmed.split("=")[0].trim());
95
- }
96
- }
97
- return profile;
98
- }
99
- catch {
100
- return null;
101
- }
102
- }
103
- function readGoMod(baseDir) {
104
- try {
105
- const content = readFileSync(join(baseDir, "go.mod"), "utf-8");
106
- const profile = { runtime: "go", deps: [], devDeps: [], scripts: {} };
107
- const moduleMatch = content.match(/^module\s+(\S+)/m);
108
- if (moduleMatch)
109
- profile.name = moduleMatch[1];
110
- for (const line of content.split("\n")) {
111
- const m = line.match(/^\s*(\S+)\s+v[\d.]+/);
112
- if (m && !line.startsWith("//"))
113
- profile.deps.push(m[1]);
114
- }
115
- return profile;
116
- }
117
- catch {
118
- return null;
119
- }
120
- }
121
- function readRequirements(baseDir) {
122
- try {
123
- const content = readFileSync(join(baseDir, "requirements.txt"), "utf-8");
124
- const profile = { runtime: "python", deps: [], devDeps: [], scripts: {} };
125
- for (const line of content.split("\n")) {
126
- const trimmed = line.trim();
127
- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("-"))
128
- continue;
129
- profile.deps.push(cleanDependency(trimmed));
130
- }
131
- return profile;
132
- }
133
- catch {
134
- return null;
135
- }
136
- }
137
- /**
138
- * Read a compact project profile from the workspace manifest (best-effort).
139
- * Returns null when no readable manifest is present.
140
- */
141
- export function readProjectProfile(baseDir) {
142
- const manifest = detectManifest(baseDir);
143
- if (!manifest)
144
- return null;
145
- switch (manifest) {
146
- case "package.json":
147
- return readPackageJson(baseDir);
148
- case "pyproject.toml":
149
- return readPyproject(baseDir);
150
- case "Cargo.toml":
151
- return readCargo(baseDir);
152
- case "go.mod":
153
- return readGoMod(baseDir);
154
- case "requirements.txt":
155
- return readRequirements(baseDir);
156
- default:
157
- return null;
158
- }
159
- }
160
- /** One-line stack-neutral summary of the project profile. */
161
- export function formatProjectProfile(profile) {
162
- const parts = [];
163
- if (profile.deps.length > 0) {
164
- parts.push(`${t("indexer.stack_deps")}: ${profile.deps.slice(0, MAX_DEPS).join(", ")}`);
165
- }
166
- if (profile.devDeps.length > 0) {
167
- parts.push(`${t("indexer.stack_dev")}: ${profile.devDeps.slice(0, MAX_DEV_DEPS).join(", ")}`);
168
- }
169
- const scripts = Object.entries(profile.scripts).slice(0, MAX_SCRIPTS);
170
- if (scripts.length > 0) {
171
- parts.push(`${t("indexer.stack_scripts")}: ${scripts.map(([k, v]) => `${k}=${v}`).join(", ")}`);
172
- }
173
- const name = profile.name ? ` ${profile.name}` : "";
174
- return `[Stack: ${profile.runtime}${name} — ${parts.join(" | ")}]`;
175
- }
176
- /**
177
- * Convenience: detect + read + format in one call. Returns null when the
178
- * workspace has no readable manifest.
179
- */
180
- export function buildProjectProfileLine(baseDir) {
181
- const profile = readProjectProfile(baseDir);
182
- return profile ? formatProjectProfile(profile) : null;
183
- }
@@ -1,101 +0,0 @@
1
- import { readdirSync, readFileSync, statSync, existsSync, watch } from "fs";
2
- import { join, relative, extname } from "path";
3
- const LANGUAGES = {
4
- ".ts": "typescript",
5
- ".tsx": "typescript-react",
6
- ".js": "javascript",
7
- ".jsx": "javascript-react",
8
- ".json": "json",
9
- ".md": "markdown",
10
- ".yaml": "yaml",
11
- ".yml": "yaml",
12
- ".py": "python",
13
- ".rs": "rust",
14
- ".go": "go",
15
- };
16
- const IGNORE_DIRS = new Set(["node_modules", ".git", "dist", "build", ".mma", "coverage"]);
17
- export class Indexer {
18
- baseDir;
19
- MAX_FILES = 1000;
20
- watcher = null;
21
- constructor(baseDir) {
22
- this.baseDir = baseDir;
23
- }
24
- watch(callback) {
25
- this.watcher = watch(this.baseDir, { recursive: true }, (event, filename) => {
26
- if (filename && !Array.from(IGNORE_DIRS).some((dir) => filename.includes(dir))) {
27
- callback(event, filename);
28
- }
29
- });
30
- }
31
- unwatch() {
32
- if (this.watcher) {
33
- this.watcher.close();
34
- this.watcher = null;
35
- }
36
- }
37
- async walk() {
38
- const files = [];
39
- let totalSize = 0;
40
- let count = 0;
41
- const walkDir = (dir) => {
42
- if (!existsSync(dir))
43
- return;
44
- let entries;
45
- try {
46
- entries = readdirSync(dir);
47
- }
48
- catch {
49
- return;
50
- }
51
- for (const entry of entries) {
52
- if (count >= this.MAX_FILES)
53
- return;
54
- const fullPath = join(dir, entry);
55
- const relPath = relative(this.baseDir, fullPath);
56
- const stat = statSync(fullPath);
57
- if (stat.isDirectory()) {
58
- if (!IGNORE_DIRS.has(entry)) {
59
- walkDir(fullPath);
60
- }
61
- }
62
- else if (stat.isFile()) {
63
- const ext = extname(entry).toLowerCase();
64
- const language = LANGUAGES[ext];
65
- if (language) {
66
- const content = readFileSync(fullPath, "utf-8");
67
- const exports = this.extractExports(content, language);
68
- files.push({ path: relPath, language, exports, size: stat.size });
69
- totalSize += stat.size;
70
- count++;
71
- }
72
- }
73
- }
74
- };
75
- walkDir(this.baseDir);
76
- return { files, totalSize };
77
- }
78
- extractExports(content, language) {
79
- if (language === "typescript" || language === "javascript") {
80
- const exports = [];
81
- const exportRegex = /export\s+(?:const|function|class|interface|type|enum|default\s+(?:class|function))\s+(\w+)/g;
82
- let match;
83
- while ((match = exportRegex.exec(content)) !== null) {
84
- exports.push(match[1]);
85
- }
86
- return exports;
87
- }
88
- return [];
89
- }
90
- summarize(result) {
91
- const byLang = {};
92
- for (const f of result.files) {
93
- byLang[f.language] = (byLang[f.language] || 0) + 1;
94
- }
95
- const langs = Object.entries(byLang)
96
- .sort((a, b) => b[1] - a[1])
97
- .map(([lang, count]) => `${lang}:${count}`)
98
- .join(", ");
99
- return `[Index: ${result.files.length} files, ${(result.totalSize / 1024).toFixed(1)}KB (${langs})]`;
100
- }
101
- }
@@ -1,58 +0,0 @@
1
- import { readdir, stat } from "fs/promises";
2
- import { resolve, relative } from "path";
3
- import { getServerForFile } from "./config";
4
- /** lsp_check directory mode: walk depth and per-call file cap. */
5
- export const MAX_LSP_CHECK_FILES = 15;
6
- const MAX_LSP_WALK_DEPTH = 4;
7
- const SKIP_DIRS = new Set(["node_modules", ".git", ".mma", "dist"]);
8
- export const severityLabels = {
9
- 1: "error",
10
- 2: "warning",
11
- 3: "info",
12
- 4: "hint",
13
- };
14
- /**
15
- * Resolve the target to a file (single check) or a bounded list of source
16
- * files (directory check, capped at MAX_LSP_CHECK_FILES). Only files with a
17
- * configured LSP server are collected, so unsupported extensions are simply
18
- * not checked rather than producing noise.
19
- */
20
- export async function collectCheckFiles(resolved, config) {
21
- const info = await stat(resolved).catch(() => null);
22
- if (!info)
23
- return [];
24
- if (info.isFile())
25
- return [resolved];
26
- const out = [];
27
- await walkDir(resolved, 0, out, config);
28
- return out;
29
- }
30
- async function walkDir(dir, depth, out, config) {
31
- if (depth > MAX_LSP_WALK_DEPTH || out.length >= MAX_LSP_CHECK_FILES)
32
- return;
33
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
34
- for (const entry of entries) {
35
- if (out.length >= MAX_LSP_CHECK_FILES)
36
- break;
37
- if (entry.isDirectory()) {
38
- if (SKIP_DIRS.has(entry.name))
39
- continue;
40
- await walkDir(resolve(dir, entry.name), depth + 1, out, config);
41
- }
42
- else if (entry.isFile() && getServerForFile(resolve(dir, entry.name), config)) {
43
- out.push(resolve(dir, entry.name));
44
- }
45
- }
46
- }
47
- export function formatCheckDiagnostics(items, baseDir) {
48
- return items
49
- .slice(0, 40)
50
- .map(({ file, diag }) => {
51
- const rel = relative(baseDir, file).replace(/\\/g, "/");
52
- const line = diag.range.start.line + 1;
53
- const col = diag.range.start.character + 1;
54
- const sev = severityLabels[diag.severity] ?? "unknown";
55
- return ` ${rel}(${line},${col}): ${sev}: ${diag.message}`;
56
- })
57
- .join("\n");
58
- }
@@ -1,278 +0,0 @@
1
- import { spawn, execSync } from "child_process";
2
- import { resolve } from "path";
3
- import { platform } from "os";
4
- import { resolveSpawnCommand, buildWinCommandLine } from "./command";
5
- import { killTree } from "../processes/registry";
6
- const DEFAULT_TIMEOUT = 15000;
7
- export class LspClient {
8
- process = null;
9
- requestId = 0;
10
- pending = new Map();
11
- buffer = "";
12
- contentLength = -1;
13
- diagnostics = [];
14
- diagnosticsResolve = null;
15
- diagnosticsTimer = null;
16
- initialized = false;
17
- async checkFile(filePath, baseDir, config, projectRoot = baseDir) {
18
- const timeout = config.timeout ?? DEFAULT_TIMEOUT;
19
- try {
20
- await this.initialize(config, projectRoot, timeout);
21
- this.sendNotification("initialized", {});
22
- const uri = this.pathToUri(resolve(filePath));
23
- const fs = await import("fs");
24
- const content = fs.readFileSync(filePath, "utf-8");
25
- const diagPromise = new Promise((resolve) => {
26
- this.diagnosticsResolve = resolve;
27
- this.diagnostics = [];
28
- this.diagnosticsTimer = setTimeout(() => {
29
- this.diagnosticsResolve?.([]);
30
- this.diagnosticsResolve = null;
31
- }, timeout);
32
- });
33
- this.sendNotification("textDocument/didOpen", {
34
- textDocument: {
35
- uri,
36
- languageId: this.languageFromPath(filePath),
37
- version: 1,
38
- text: content,
39
- },
40
- });
41
- return await diagPromise;
42
- }
43
- catch (e) {
44
- // Re-throw so the LspModule can surface failures instead of hiding them.
45
- throw e instanceof Error ? e : new Error(String(e));
46
- }
47
- finally {
48
- await this.shutdown();
49
- }
50
- }
51
- /**
52
- * Lightweight "does the server actually start" probe: spawn + initialize +
53
- * shutdown. Used by the REPL banner to surface a dead server (npx
54
- * auto-install failure, wrong package name, missing binary) up front instead
55
- * of the first write_file timing out.
56
- */
57
- async probe(config, projectRoot, timeout) {
58
- try {
59
- await this.initialize(config, projectRoot, timeout);
60
- }
61
- finally {
62
- await this.shutdown();
63
- }
64
- }
65
- async initialize(config, projectRoot, timeout) {
66
- await this.startServer(config, projectRoot);
67
- const rootUri = this.pathToUri(projectRoot);
68
- const initParams = {
69
- processId: process.pid,
70
- rootUri,
71
- workspaceFolders: [{ uri: rootUri, name: "workspace" }],
72
- capabilities: { textDocument: { publishDiagnostics: {} } },
73
- };
74
- try {
75
- await this.sendRequest("initialize", initParams, timeout);
76
- }
77
- catch (e) {
78
- // npx auto-install can blow past the initialize timeout on first run — retry once.
79
- if (!(e instanceof Error) || !e.message.includes("initialize"))
80
- throw e;
81
- await this.shutdown();
82
- await this.startServer(config, projectRoot);
83
- await this.sendRequest("initialize", initParams, timeout);
84
- }
85
- this.initialized = true;
86
- }
87
- async startServer(config, projectRoot) {
88
- if (config.autoInstall === false) {
89
- try {
90
- execSync(`where ${config.command}`, { stdio: "pipe", timeout: 3000 });
91
- }
92
- catch {
93
- throw new Error(`${config.command} not found in PATH`);
94
- }
95
- }
96
- return new Promise((resolve, reject) => {
97
- const args = config.args ?? [];
98
- const isWin = platform() === "win32";
99
- let spawnCommand = resolveSpawnCommand(config.command);
100
- let spawnArgs = args;
101
- const spawnOpts = {
102
- stdio: ["pipe", "pipe", "pipe"],
103
- env: { ...process.env, ...config.env },
104
- cwd: projectRoot,
105
- };
106
- if (isWin) {
107
- // A `.cmd` shim can't be spawned directly under Node (`spawn npx EINVAL`) — run via cmd.exe.
108
- spawnCommand = buildWinCommandLine(spawnCommand, args);
109
- spawnArgs = [];
110
- spawnOpts.shell = true;
111
- }
112
- const proc = spawn(spawnCommand, spawnArgs, spawnOpts);
113
- proc.on("error", reject);
114
- proc.stdout.on("data", (chunk) => {
115
- this.handleData(chunk);
116
- });
117
- proc.stderr.on("data", () => { });
118
- proc.once("spawn", () => {
119
- resolve();
120
- });
121
- this.process = proc;
122
- setTimeout(() => {
123
- if (!this.initialized && this.process)
124
- reject(new Error("LSP server start timeout"));
125
- }, config.timeout ?? 10000);
126
- });
127
- }
128
- handleData(chunk) {
129
- this.buffer += chunk.toString();
130
- this.parseMessages();
131
- }
132
- parseMessages() {
133
- while (true) {
134
- if (this.contentLength === -1) {
135
- const headerEnd = this.buffer.indexOf("\r\n\r\n");
136
- if (headerEnd === -1)
137
- return;
138
- const header = this.buffer.slice(0, headerEnd);
139
- const match = header.match(/Content-Length: (\d+)/i);
140
- if (!match) {
141
- this.buffer = this.buffer.slice(headerEnd + 4);
142
- this.contentLength = -1;
143
- continue;
144
- }
145
- this.contentLength = parseInt(match[1], 10);
146
- // Guard against malicious/buggy servers sending absurd Content-Length
147
- if (this.contentLength > 10 * 1024 * 1024) {
148
- this.buffer = this.buffer.slice(headerEnd + 4);
149
- this.contentLength = -1;
150
- continue;
151
- }
152
- this.buffer = this.buffer.slice(headerEnd + 4);
153
- }
154
- if (this.buffer.length < this.contentLength)
155
- return;
156
- const body = this.buffer.slice(0, this.contentLength);
157
- this.buffer = this.buffer.slice(this.contentLength);
158
- this.contentLength = -1;
159
- try {
160
- const msg = JSON.parse(body);
161
- this.handleMessage(msg);
162
- }
163
- catch { }
164
- }
165
- }
166
- handleMessage(msg) {
167
- if (msg.method === "textDocument/publishDiagnostics") {
168
- const params = msg.params;
169
- if (params?.diagnostics) {
170
- this.diagnostics = params.diagnostics;
171
- if (this.diagnosticsTimer) {
172
- clearTimeout(this.diagnosticsTimer);
173
- this.diagnosticsTimer = null;
174
- }
175
- this.diagnosticsResolve?.(this.diagnostics);
176
- this.diagnosticsResolve = null;
177
- }
178
- return;
179
- }
180
- if (msg.id !== undefined && msg.id !== null) {
181
- const pending = this.pending.get(msg.id);
182
- if (pending) {
183
- this.pending.delete(msg.id);
184
- if (msg.error) {
185
- pending.reject(new Error(String(msg.error.message ?? "LSP error")));
186
- }
187
- else {
188
- pending.resolve(msg.result);
189
- }
190
- }
191
- }
192
- }
193
- sendRequest(method, params, timeout) {
194
- return new Promise((resolve, reject) => {
195
- const id = ++this.requestId;
196
- this.pending.set(id, { resolve, reject });
197
- const message = JSON.stringify({ jsonrpc: "2.0", id, method, params });
198
- this.write(message);
199
- setTimeout(() => {
200
- if (this.pending.has(id)) {
201
- this.pending.delete(id);
202
- reject(new Error(`LSP request timeout: ${method}`));
203
- }
204
- }, timeout);
205
- });
206
- }
207
- sendNotification(method, params) {
208
- const message = JSON.stringify({ jsonrpc: "2.0", method, params });
209
- this.write(message);
210
- }
211
- write(message) {
212
- if (!this.process?.stdin?.writable)
213
- return;
214
- const header = `Content-Length: ${Buffer.byteLength(message)}\r\n\r\n`;
215
- try {
216
- this.process.stdin.write(header + message);
217
- }
218
- catch { }
219
- }
220
- async shutdown() {
221
- try {
222
- if (this.process && this.initialized && this.process.stdin?.writable) {
223
- this.sendRequest("shutdown", null, 3000).catch(() => { });
224
- this.sendNotification("exit", null);
225
- await new Promise((r) => setTimeout(r, 200));
226
- }
227
- }
228
- catch {
229
- }
230
- finally {
231
- if (this.process) {
232
- // The direct child on win32 is the cmd.exe wrapper; killing it alone
233
- // orphans the npx → node → tsserver tree (observed as leaked node
234
- // processes after every check). Tree-kill so the whole chain dies.
235
- try {
236
- killTree(this.process);
237
- }
238
- catch { }
239
- this.process = null;
240
- }
241
- this.initialized = false;
242
- this.buffer = "";
243
- this.contentLength = -1;
244
- if (this.diagnosticsTimer) {
245
- clearTimeout(this.diagnosticsTimer);
246
- this.diagnosticsTimer = null;
247
- }
248
- }
249
- }
250
- pathToUri(filePath) {
251
- const normalized = filePath.replace(/\\/g, "/");
252
- return /^[a-zA-Z]:/.test(normalized) ? `file:///${normalized}` : `file://${normalized}`;
253
- }
254
- languageFromPath(filePath) {
255
- const ext = filePath.split(".").pop()?.toLowerCase();
256
- const map = {
257
- ts: "typescript",
258
- tsx: "typescriptreact",
259
- mts: "typescript",
260
- cts: "typescript",
261
- js: "javascript",
262
- jsx: "javascriptreact",
263
- mjs: "javascript",
264
- cjs: "javascript",
265
- py: "python",
266
- go: "go",
267
- rs: "rust",
268
- json: "json",
269
- html: "html",
270
- css: "css",
271
- scss: "scss",
272
- md: "markdown",
273
- yaml: "yaml",
274
- yml: "yaml",
275
- };
276
- return map[ext ?? ""] ?? "plaintext";
277
- }
278
- }
@@ -1,60 +0,0 @@
1
- import { delimiter, join } from "path";
2
- import { existsSync } from "fs";
3
- import { platform } from "os";
4
- const WIN_EXTS = [".cmd", ".bat", ".exe", ".com"];
5
- /**
6
- * Resolve the command string passed to `child_process.spawn` on Windows.
7
- *
8
- * Node's `spawn` cannot execute `.cmd`/`.bat` shims directly without a shell,
9
- * and a bare `npx` fails with `spawn npx ENOENT` because on Windows the
10
- * real executable is `npx.cmd`. This returns the first existing shim
11
- * (`npx.cmd`, `npx.bat`, `npx.exe`, ...) found on PATH, or the bare command
12
- * when nothing exists (the spawn will then fail with a meaningful ENOENT).
13
- *
14
- * Non-Windows platforms and commands that already carry an extension or a
15
- * path separator are returned unchanged.
16
- */
17
- export function resolveSpawnCommand(command, platformName = platform(), pathEnv = process.env.PATH ?? "") {
18
- if (platformName !== "win32")
19
- return command;
20
- // Already a path or has an extension — pass through.
21
- if (command.includes("/") ||
22
- command.includes("\\") ||
23
- WIN_EXTS.some((ext) => command.toLowerCase().endsWith(ext))) {
24
- return command;
25
- }
26
- const dirs = pathEnv.split(delimiter).filter(Boolean);
27
- for (const dir of dirs) {
28
- for (const ext of WIN_EXTS) {
29
- const candidate = join(dir, `${command}${ext}`);
30
- if (existsSync(candidate))
31
- return `${command}${ext}`;
32
- }
33
- }
34
- return command;
35
- }
36
- /**
37
- * Join a resolved command and its args into a single cmd.exe command line.
38
- *
39
- * Under Node on Windows, `spawn` of a `.cmd`/`.bat` shim WITHOUT a shell throws
40
- * `spawn EINVAL` (CreateProcess cannot run batch files directly). Resolving
41
- * `npx` → `npx.cmd` fixes the old `ENOENT` but not the `EINVAL` — the spawn
42
- * still has no shell. The reliable fix is to run the whole command line through
43
- * `cmd.exe /d /s /c` (i.e. `spawn(line, { shell: true })`). This helper builds
44
- * that line, quoting any argument that contains cmd.exe metacharacters so the
45
- * package names and flags in LSP configs (`typescript-language-server --stdio`,
46
- * `pyright --stdio`) survive the round-trip.
47
- *
48
- * Non-Windows platforms never call this (they spawn the resolved command +
49
- * args directly, no shell).
50
- */
51
- export function buildWinCommandLine(command, args) {
52
- const quote = (part) => {
53
- if (part === "")
54
- return '""';
55
- if (!/[\s"&|^<>()%!]/.test(part))
56
- return part;
57
- return `"${part.replace(/"/g, '\\"')}"`;
58
- };
59
- return [command, ...args].map(quote).join(" ");
60
- }