micro-models-agent 0.40.1 → 0.41.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 (171) hide show
  1. package/bin/mma.mjs +41 -41
  2. package/dist/cli/commands.js +9 -19
  3. package/dist/cli/completer.js +36 -37
  4. package/dist/cli/index.js +2 -2
  5. package/dist/cli/main.js +48 -23
  6. package/dist/cli/plugin-commands.js +36 -0
  7. package/dist/cli/repl-commands.js +40 -12
  8. package/dist/cli/repl.js +217 -87
  9. package/dist/cli/run-result.js +22 -0
  10. package/dist/cli/security-commands.js +5 -7
  11. package/dist/cli/setup.js +8 -26
  12. package/dist/config/config.js +52 -5
  13. package/dist/config/defaults.js +29 -5
  14. package/dist/config/experts.js +1 -1
  15. package/dist/config/index.js +3 -3
  16. package/dist/config/security.js +3 -10
  17. package/dist/core/agent-moe.js +2 -10
  18. package/dist/core/agent.js +273 -82
  19. package/dist/core/bootstrap.js +80 -13
  20. package/dist/core/index.js +2 -2
  21. package/dist/core/prompt-builder.js +23 -2
  22. package/dist/core/session-logger.js +46 -4
  23. package/dist/core/version.js +24 -0
  24. package/dist/i18n/en.json +75 -2
  25. package/dist/i18n/ru.json +74 -1
  26. package/dist/index.js +1 -1
  27. package/dist/llm/image-utils.js +4 -5
  28. package/dist/llm/index.js +4 -4
  29. package/dist/llm/model-loader.js +6 -6
  30. package/dist/llm/openai-compat.js +40 -34
  31. package/dist/llm/orchestrator.js +33 -29
  32. package/dist/llm/response.js +9 -9
  33. package/dist/logger/app-logger.js +1 -1
  34. package/dist/logger/index.js +1 -1
  35. package/dist/main.js +2489 -2186
  36. package/dist/migration/backup.js +13 -13
  37. package/dist/migration/detect.js +11 -11
  38. package/dist/migration/index.js +2 -2
  39. package/dist/modules/artifacts/store.js +61 -0
  40. package/dist/modules/browser/actions.js +34 -4
  41. package/dist/modules/browser/bridge-client.js +199 -0
  42. package/dist/modules/browser/bridge-path.js +10 -0
  43. package/dist/modules/browser/bridge-server.mjs +202 -202
  44. package/dist/modules/browser/cookie-store.js +6 -6
  45. package/dist/modules/browser/driver.js +136 -0
  46. package/dist/modules/browser/index.js +7 -5
  47. package/dist/modules/browser/module.js +8 -7
  48. package/dist/modules/browser/session.js +87 -84
  49. package/dist/modules/browser/snapshot.js +92 -58
  50. package/dist/modules/browser/types.js +4 -1
  51. package/dist/modules/certification/cli.js +2 -4
  52. package/dist/modules/certification/fact-checker.js +1 -3
  53. package/dist/modules/certification/loader.js +3 -9
  54. package/dist/modules/certification/runner.js +1 -4
  55. package/dist/modules/context/chunk-query.js +100 -0
  56. package/dist/modules/context/fact-extractor.js +162 -0
  57. package/dist/modules/context/history.js +15 -0
  58. package/dist/modules/context/index.js +1 -1
  59. package/dist/modules/context/manager.js +160 -86
  60. package/dist/modules/execution/audit-runners.js +152 -0
  61. package/dist/modules/execution/auditor.js +177 -25
  62. package/dist/modules/execution/execution-plugin.js +272 -0
  63. package/dist/modules/execution/module.js +201 -544
  64. package/dist/modules/execution/moe-executor.js +25 -0
  65. package/dist/modules/execution/plan-store.js +1 -3
  66. package/dist/modules/execution/plan-tool.js +508 -0
  67. package/dist/modules/execution/plan-validator.js +10 -10
  68. package/dist/modules/execution/planner.js +6 -1
  69. package/dist/modules/execution/stuck-detector.js +173 -10
  70. package/dist/modules/execution/verifier.js +86 -42
  71. package/dist/modules/execution/windows-commands.js +41 -0
  72. package/dist/modules/hallucination/confidence.js +8 -1
  73. package/dist/modules/hallucination/detector.js +2 -5
  74. package/dist/modules/hallucination/factual.js +3 -64
  75. package/dist/modules/hallucination/index.js +1 -1
  76. package/dist/modules/hallucination/js-identifiers.js +190 -0
  77. package/dist/modules/hallucination/llm-judge.js +1 -3
  78. package/dist/modules/indexer/cache.js +9 -7
  79. package/dist/modules/indexer/index.js +3 -3
  80. package/dist/modules/indexer/module.js +95 -42
  81. package/dist/modules/indexer/project-profile.js +183 -0
  82. package/dist/modules/indexer/walker.js +17 -17
  83. package/dist/modules/lsp/check-tool.js +58 -0
  84. package/dist/modules/lsp/client.js +74 -31
  85. package/dist/modules/lsp/command.js +60 -0
  86. package/dist/modules/lsp/config.js +87 -33
  87. package/dist/modules/lsp/index.js +3 -3
  88. package/dist/modules/lsp/module.js +185 -21
  89. package/dist/modules/lsp/probe.js +76 -0
  90. package/dist/modules/lsp/project-root.js +32 -0
  91. package/dist/modules/lsp/startup-check.js +141 -0
  92. package/dist/modules/mcp/module.js +2 -6
  93. package/dist/modules/memory/index.js +1 -1
  94. package/dist/modules/memory/module.js +71 -23
  95. package/dist/modules/memory/search.js +11 -9
  96. package/dist/modules/memory/store.js +13 -13
  97. package/dist/modules/pipelines/engine.js +10 -10
  98. package/dist/modules/pipelines/index.js +3 -3
  99. package/dist/modules/pipelines/parser.js +17 -14
  100. package/dist/modules/pipelines/template.js +1 -1
  101. package/dist/modules/plugins/builtin/lint-on-write.js +21 -16
  102. package/dist/modules/plugins/builtin/notify.js +3 -2
  103. package/dist/modules/plugins/index.js +1 -1
  104. package/dist/modules/plugins/loader.js +59 -17
  105. package/dist/modules/plugins/manager.js +73 -17
  106. package/dist/modules/processes/detect.js +34 -0
  107. package/dist/modules/processes/index.js +1 -1
  108. package/dist/modules/processes/registry.js +135 -46
  109. package/dist/modules/registry.js +4 -2
  110. package/dist/modules/security/audit-notifier.js +39 -39
  111. package/dist/modules/security/command-validator.js +2 -8
  112. package/dist/modules/security/data-sanitizer.js +1 -9
  113. package/dist/modules/security/encryption.js +58 -56
  114. package/dist/modules/security/network-validator.js +1 -9
  115. package/dist/modules/security/path-validator.js +1 -3
  116. package/dist/modules/security/security-policies.js +3 -19
  117. package/dist/modules/security/session-encryption.js +1 -1
  118. package/dist/modules/security/session-isolation.js +8 -8
  119. package/dist/modules/session/index.js +3 -3
  120. package/dist/modules/session/module.js +5 -5
  121. package/dist/modules/session/store.js +3 -9
  122. package/dist/modules/skills/matcher.js +27 -0
  123. package/dist/modules/skills/module.js +1 -2
  124. package/dist/modules/updater/checker.js +70 -6
  125. package/dist/modules/updater/index.js +2 -1
  126. package/dist/modules/updater/module.js +116 -0
  127. package/dist/modules/user-profile/compressor.js +2 -2
  128. package/dist/modules/user-profile/index.js +1 -1
  129. package/dist/modules/user-profile/profile.js +9 -9
  130. package/dist/tools/attach-image.js +1 -1
  131. package/dist/tools/bash.js +178 -19
  132. package/dist/tools/browser.js +46 -29
  133. package/dist/tools/chunk-query.js +99 -0
  134. package/dist/tools/download-file.js +116 -0
  135. package/dist/tools/enable-tools.js +58 -0
  136. package/dist/tools/executor.js +4 -5
  137. package/dist/tools/file-info.js +13 -12
  138. package/dist/tools/filter-tools.js +9 -2
  139. package/dist/tools/glob-tool.js +11 -11
  140. package/dist/tools/grep-tool.js +1 -3
  141. package/dist/tools/hidden-tools-block.js +37 -0
  142. package/dist/tools/index.js +13 -2
  143. package/dist/tools/list-dir.js +18 -17
  144. package/dist/tools/load-skill.js +1 -3
  145. package/dist/tools/path-utils.js +4 -4
  146. package/dist/tools/pipeline-run.js +25 -25
  147. package/dist/tools/process-kill.js +11 -11
  148. package/dist/tools/process-list.js +20 -22
  149. package/dist/tools/process-log.js +22 -18
  150. package/dist/tools/question.js +1 -3
  151. package/dist/tools/read-file.js +10 -2
  152. package/dist/tools/recall.js +44 -37
  153. package/dist/tools/registry.js +15 -4
  154. package/dist/tools/remember.js +29 -29
  155. package/dist/tools/scope-check.js +9 -9
  156. package/dist/tools/subagent.js +54 -9
  157. package/dist/tools/user-input.js +1 -1
  158. package/dist/tools/web-browse.js +3 -3
  159. package/dist/tools/web-fetch.js +3 -3
  160. package/dist/tools/web-search.js +3 -3
  161. package/dist/tools/write-file.js +1 -3
  162. package/dist/ui/box.js +1 -5
  163. package/dist/ui/index.js +6 -6
  164. package/dist/ui/line-editor.js +703 -0
  165. package/dist/ui/line-math.js +69 -0
  166. package/dist/ui/md-formatter.js +33 -33
  167. package/dist/ui/output.js +5 -5
  168. package/dist/ui/plan-view.js +103 -0
  169. package/dist/ui/renderer.js +15 -10
  170. package/dist/ui/table.js +1 -1
  171. package/package.json +48 -48
@@ -0,0 +1,183 @@
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,19 +1,19 @@
1
- import { readdirSync, readFileSync, statSync, existsSync, watch } from 'fs';
2
- import { join, relative, extname } from 'path';
1
+ import { readdirSync, readFileSync, statSync, existsSync, watch } from "fs";
2
+ import { join, relative, extname } from "path";
3
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',
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
15
  };
16
- const IGNORE_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.mma', 'coverage']);
16
+ const IGNORE_DIRS = new Set(["node_modules", ".git", "dist", "build", ".mma", "coverage"]);
17
17
  export class Indexer {
18
18
  baseDir;
19
19
  MAX_FILES = 1000;
@@ -63,7 +63,7 @@ export class Indexer {
63
63
  const ext = extname(entry).toLowerCase();
64
64
  const language = LANGUAGES[ext];
65
65
  if (language) {
66
- const content = readFileSync(fullPath, 'utf-8');
66
+ const content = readFileSync(fullPath, "utf-8");
67
67
  const exports = this.extractExports(content, language);
68
68
  files.push({ path: relPath, language, exports, size: stat.size });
69
69
  totalSize += stat.size;
@@ -76,7 +76,7 @@ export class Indexer {
76
76
  return { files, totalSize };
77
77
  }
78
78
  extractExports(content, language) {
79
- if (language === 'typescript' || language === 'javascript') {
79
+ if (language === "typescript" || language === "javascript") {
80
80
  const exports = [];
81
81
  const exportRegex = /export\s+(?:const|function|class|interface|type|enum|default\s+(?:class|function))\s+(\w+)/g;
82
82
  let match;
@@ -95,7 +95,7 @@ export class Indexer {
95
95
  const langs = Object.entries(byLang)
96
96
  .sort((a, b) => b[1] - a[1])
97
97
  .map(([lang, count]) => `${lang}:${count}`)
98
- .join(', ');
98
+ .join(", ");
99
99
  return `[Index: ${result.files.length} files, ${(result.totalSize / 1024).toFixed(1)}KB (${langs})]`;
100
100
  }
101
101
  }
@@ -0,0 +1,58 @@
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,5 +1,8 @@
1
1
  import { spawn, execSync } from "child_process";
2
2
  import { resolve } from "path";
3
+ import { platform } from "os";
4
+ import { resolveSpawnCommand, buildWinCommandLine } from "./command";
5
+ import { killTree } from "../processes/registry";
3
6
  const DEFAULT_TIMEOUT = 15000;
4
7
  export class LspClient {
5
8
  process = null;
@@ -11,18 +14,10 @@ export class LspClient {
11
14
  diagnosticsResolve = null;
12
15
  diagnosticsTimer = null;
13
16
  initialized = false;
14
- async checkFile(filePath, baseDir, config) {
17
+ async checkFile(filePath, baseDir, config, projectRoot = baseDir) {
15
18
  const timeout = config.timeout ?? DEFAULT_TIMEOUT;
16
19
  try {
17
- await this.startServer(config, baseDir);
18
- const rootUri = this.pathToUri(resolve(baseDir));
19
- const initResult = await this.sendRequest("initialize", {
20
- processId: process.pid,
21
- rootUri,
22
- workspaceFolders: [{ uri: rootUri, name: "workspace" }],
23
- capabilities: { textDocument: { publishDiagnostics: {} } },
24
- }, timeout);
25
- this.initialized = true;
20
+ await this.initialize(config, projectRoot, timeout);
26
21
  this.sendNotification("initialized", {});
27
22
  const uri = this.pathToUri(resolve(filePath));
28
23
  const fs = await import("fs");
@@ -31,10 +26,8 @@ export class LspClient {
31
26
  this.diagnosticsResolve = resolve;
32
27
  this.diagnostics = [];
33
28
  this.diagnosticsTimer = setTimeout(() => {
34
- if (this.diagnosticsResolve) {
35
- this.diagnosticsResolve([]);
36
- this.diagnosticsResolve = null;
37
- }
29
+ this.diagnosticsResolve?.([]);
30
+ this.diagnosticsResolve = null;
38
31
  }, timeout);
39
32
  });
40
33
  this.sendNotification("textDocument/didOpen", {
@@ -47,14 +40,51 @@ export class LspClient {
47
40
  });
48
41
  return await diagPromise;
49
42
  }
50
- catch {
51
- return [];
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));
52
46
  }
53
47
  finally {
54
48
  await this.shutdown();
55
49
  }
56
50
  }
57
- async startServer(config, baseDir) {
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) {
58
88
  if (config.autoInstall === false) {
59
89
  try {
60
90
  execSync(`where ${config.command}`, { stdio: "pipe", timeout: 3000 });
@@ -65,11 +95,21 @@ export class LspClient {
65
95
  }
66
96
  return new Promise((resolve, reject) => {
67
97
  const args = config.args ?? [];
68
- const proc = spawn(config.command, args, {
98
+ const isWin = platform() === "win32";
99
+ let spawnCommand = resolveSpawnCommand(config.command);
100
+ let spawnArgs = args;
101
+ const spawnOpts = {
69
102
  stdio: ["pipe", "pipe", "pipe"],
70
103
  env: { ...process.env, ...config.env },
71
- cwd: baseDir,
72
- });
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);
73
113
  proc.on("error", reject);
74
114
  proc.stdout.on("data", (chunk) => {
75
115
  this.handleData(chunk);
@@ -80,9 +120,8 @@ export class LspClient {
80
120
  });
81
121
  this.process = proc;
82
122
  setTimeout(() => {
83
- if (!this.initialized && this.process) {
123
+ if (!this.initialized && this.process)
84
124
  reject(new Error("LSP server start timeout"));
85
- }
86
125
  }, config.timeout ?? 10000);
87
126
  });
88
127
  }
@@ -133,10 +172,8 @@ export class LspClient {
133
172
  clearTimeout(this.diagnosticsTimer);
134
173
  this.diagnosticsTimer = null;
135
174
  }
136
- if (this.diagnosticsResolve) {
137
- this.diagnosticsResolve(this.diagnostics);
138
- this.diagnosticsResolve = null;
139
- }
175
+ this.diagnosticsResolve?.(this.diagnostics);
176
+ this.diagnosticsResolve = null;
140
177
  }
141
178
  return;
142
179
  }
@@ -192,13 +229,18 @@ export class LspClient {
192
229
  }
193
230
  finally {
194
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.
195
235
  try {
196
- this.process.kill();
236
+ killTree(this.process);
197
237
  }
198
238
  catch { }
199
239
  this.process = null;
200
240
  }
201
241
  this.initialized = false;
242
+ this.buffer = "";
243
+ this.contentLength = -1;
202
244
  if (this.diagnosticsTimer) {
203
245
  clearTimeout(this.diagnosticsTimer);
204
246
  this.diagnosticsTimer = null;
@@ -207,18 +249,19 @@ export class LspClient {
207
249
  }
208
250
  pathToUri(filePath) {
209
251
  const normalized = filePath.replace(/\\/g, "/");
210
- if (/^[a-zA-Z]:/.test(normalized)) {
211
- return `file:///${normalized}`;
212
- }
213
- return `file://${normalized}`;
252
+ return /^[a-zA-Z]:/.test(normalized) ? `file:///${normalized}` : `file://${normalized}`;
214
253
  }
215
254
  languageFromPath(filePath) {
216
255
  const ext = filePath.split(".").pop()?.toLowerCase();
217
256
  const map = {
218
257
  ts: "typescript",
219
258
  tsx: "typescriptreact",
259
+ mts: "typescript",
260
+ cts: "typescript",
220
261
  js: "javascript",
221
262
  jsx: "javascriptreact",
263
+ mjs: "javascript",
264
+ cjs: "javascript",
222
265
  py: "python",
223
266
  go: "go",
224
267
  rs: "rust",
@@ -0,0 +1,60 @@
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
+ }