modkh 0.0.0-stage → 0.1.0

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 (256) hide show
  1. package/README.md +24 -2
  2. package/dist/agent/bundled-skills.d.ts +13 -0
  3. package/dist/agent/bundled-skills.js +95 -0
  4. package/dist/agent/images.d.ts +10 -0
  5. package/dist/agent/images.js +33 -0
  6. package/dist/agent/loop.d.ts +56 -0
  7. package/dist/agent/loop.js +155 -0
  8. package/dist/agent/skills.d.ts +20 -0
  9. package/dist/agent/skills.js +169 -0
  10. package/dist/agent/types.d.ts +132 -0
  11. package/dist/agent/types.js +12 -0
  12. package/dist/cli/agents.d.ts +8 -0
  13. package/dist/cli/agents.js +12 -0
  14. package/dist/cli/approval.d.ts +27 -0
  15. package/dist/cli/approval.js +62 -0
  16. package/dist/cli/catalog.d.ts +39 -0
  17. package/dist/cli/catalog.js +76 -0
  18. package/dist/cli/chat.d.ts +18 -0
  19. package/dist/cli/chat.js +733 -0
  20. package/dist/cli/clipboard.d.ts +9 -0
  21. package/dist/cli/clipboard.js +54 -0
  22. package/dist/cli/color.d.ts +42 -0
  23. package/dist/cli/color.js +176 -0
  24. package/dist/cli/config.d.ts +41 -0
  25. package/dist/cli/config.js +188 -0
  26. package/dist/cli/editor.d.ts +16 -0
  27. package/dist/cli/editor.js +77 -0
  28. package/dist/cli/keys.d.ts +18 -0
  29. package/dist/cli/keys.js +82 -0
  30. package/dist/cli/language.d.ts +1 -0
  31. package/dist/cli/language.js +105 -0
  32. package/dist/cli/limits.d.ts +13 -0
  33. package/dist/cli/limits.js +19 -0
  34. package/dist/cli/lines.d.ts +18 -0
  35. package/dist/cli/lines.js +80 -0
  36. package/dist/cli/models.d.ts +4 -0
  37. package/dist/cli/models.js +69 -0
  38. package/dist/cli/permissions.d.ts +25 -0
  39. package/dist/cli/permissions.js +30 -0
  40. package/dist/cli/plugins.d.ts +1 -0
  41. package/dist/cli/plugins.js +53 -0
  42. package/dist/cli/providers.d.ts +46 -0
  43. package/dist/cli/providers.js +76 -0
  44. package/dist/cli/terminal.d.ts +143 -0
  45. package/dist/cli/terminal.js +742 -0
  46. package/dist/cli/usage.d.ts +29 -0
  47. package/dist/cli/usage.js +75 -0
  48. package/dist/index.d.ts +11 -0
  49. package/dist/index.js +164 -0
  50. package/dist/language/catalog.d.ts +44 -0
  51. package/dist/language/catalog.js +100 -0
  52. package/dist/language/commonlisp-bundled.d.ts +11 -0
  53. package/dist/language/commonlisp-bundled.js +22 -0
  54. package/dist/language/commonlisp-dependencies.d.ts +16 -0
  55. package/dist/language/commonlisp-dependencies.js +68 -0
  56. package/dist/language/commonlisp-install.d.ts +14 -0
  57. package/dist/language/commonlisp-install.js +213 -0
  58. package/dist/language/commonlisp-reader.d.ts +17 -0
  59. package/dist/language/commonlisp-reader.js +47 -0
  60. package/dist/language/commonlisp-systems.d.ts +3 -0
  61. package/dist/language/commonlisp-systems.js +32 -0
  62. package/dist/language/commonlisp-tls.d.ts +10 -0
  63. package/dist/language/commonlisp-tls.js +51 -0
  64. package/dist/language/detect.d.ts +29 -0
  65. package/dist/language/detect.js +103 -0
  66. package/dist/language/grammars/LICENSE +24 -0
  67. package/dist/language/grammars/manifest.json +76 -0
  68. package/dist/language/grammars/tree-sitter-c.wasm +0 -0
  69. package/dist/language/grammars/tree-sitter-cpp.wasm +0 -0
  70. package/dist/language/grammars/tree-sitter-css.wasm +0 -0
  71. package/dist/language/grammars/tree-sitter-html.wasm +0 -0
  72. package/dist/language/grammars/tree-sitter-javascript.wasm +0 -0
  73. package/dist/language/grammars/tree-sitter-php.wasm +0 -0
  74. package/dist/language/grammars/tree-sitter-python.wasm +0 -0
  75. package/dist/language/grammars/tree-sitter-ruby.wasm +0 -0
  76. package/dist/language/grammars/tree-sitter-rust.wasm +0 -0
  77. package/dist/language/grammars/tree-sitter-swift.wasm +0 -0
  78. package/dist/language/grammars/tree-sitter-tsx.wasm +0 -0
  79. package/dist/language/grammars/tree-sitter-typescript.wasm +0 -0
  80. package/dist/language/install.d.ts +50 -0
  81. package/dist/language/install.js +293 -0
  82. package/dist/language/lsp/client.d.ts +97 -0
  83. package/dist/language/lsp/client.js +337 -0
  84. package/dist/language/lsp/pool.d.ts +67 -0
  85. package/dist/language/lsp/pool.js +122 -0
  86. package/dist/language/lsp/service.d.ts +46 -0
  87. package/dist/language/lsp/service.js +138 -0
  88. package/dist/language/native.d.ts +8 -0
  89. package/dist/language/native.js +100 -0
  90. package/dist/language/platform.d.ts +14 -0
  91. package/dist/language/platform.js +20 -0
  92. package/dist/language/positions.d.ts +20 -0
  93. package/dist/language/positions.js +46 -0
  94. package/dist/language/syntax/assets.d.ts +9 -0
  95. package/dist/language/syntax/assets.js +73 -0
  96. package/dist/language/syntax/parser.d.ts +24 -0
  97. package/dist/language/syntax/parser.js +144 -0
  98. package/dist/language/typescript-capability.d.ts +6 -0
  99. package/dist/language/typescript-capability.js +42 -0
  100. package/dist/lisp/config.d.ts +16 -0
  101. package/dist/lisp/config.js +159 -0
  102. package/dist/lisp/routing.d.ts +5 -0
  103. package/dist/lisp/routing.js +24 -0
  104. package/dist/lisp/runtime.d.ts +21 -0
  105. package/dist/lisp/runtime.js +83 -0
  106. package/dist/memory/kiokuko.d.ts +32 -0
  107. package/dist/memory/kiokuko.js +102 -0
  108. package/dist/memory/mcp.d.ts +38 -0
  109. package/dist/memory/mcp.js +211 -0
  110. package/dist/model/ai-sdk.d.ts +27 -0
  111. package/dist/model/ai-sdk.js +180 -0
  112. package/dist/model/chatgpt/login.d.ts +42 -0
  113. package/dist/model/chatgpt/login.js +180 -0
  114. package/dist/model/chatgpt/responses.d.ts +41 -0
  115. package/dist/model/chatgpt/responses.js +202 -0
  116. package/dist/model/chatgpt/tokens.d.ts +11 -0
  117. package/dist/model/chatgpt/tokens.js +50 -0
  118. package/dist/model/connection.d.ts +6 -0
  119. package/dist/model/connection.js +65 -0
  120. package/dist/model/context.d.ts +9 -0
  121. package/dist/model/context.js +69 -0
  122. package/dist/model/factory.d.ts +25 -0
  123. package/dist/model/factory.js +88 -0
  124. package/dist/model/fixed.d.ts +17 -0
  125. package/dist/model/fixed.js +41 -0
  126. package/dist/model/reasoning.d.ts +16 -0
  127. package/dist/model/reasoning.js +62 -0
  128. package/dist/plugins/api.d.ts +60 -0
  129. package/dist/plugins/api.js +1 -0
  130. package/dist/plugins/manager.d.ts +34 -0
  131. package/dist/plugins/manager.js +261 -0
  132. package/dist/plugins/package.d.ts +13 -0
  133. package/dist/plugins/package.js +99 -0
  134. package/dist/plugins/registry.d.ts +8 -0
  135. package/dist/plugins/registry.js +14 -0
  136. package/dist/session/store.d.ts +82 -0
  137. package/dist/session/store.js +285 -0
  138. package/dist/session/workspace.d.ts +19 -0
  139. package/dist/session/workspace.js +73 -0
  140. package/dist/subagents/processes.d.ts +18 -0
  141. package/dist/subagents/processes.js +73 -0
  142. package/dist/subagents/request.d.ts +4 -0
  143. package/dist/subagents/request.js +21 -0
  144. package/dist/subagents/service.d.ts +39 -0
  145. package/dist/subagents/service.js +352 -0
  146. package/dist/subagents/settings.d.ts +10 -0
  147. package/dist/subagents/settings.js +32 -0
  148. package/dist/subagents/types.d.ts +43 -0
  149. package/dist/subagents/types.js +1 -0
  150. package/dist/subagents/verification.d.ts +31 -0
  151. package/dist/subagents/verification.js +178 -0
  152. package/dist/tools/diff.d.ts +6 -0
  153. package/dist/tools/diff.js +82 -0
  154. package/dist/tools/edit.d.ts +3 -0
  155. package/dist/tools/edit.js +152 -0
  156. package/dist/tools/files.d.ts +6 -0
  157. package/dist/tools/files.js +96 -0
  158. package/dist/tools/formal.d.ts +8 -0
  159. package/dist/tools/formal.js +77 -0
  160. package/dist/tools/guard.d.ts +7 -0
  161. package/dist/tools/guard.js +48 -0
  162. package/dist/tools/job-tools.d.ts +19 -0
  163. package/dist/tools/job-tools.js +148 -0
  164. package/dist/tools/jobs.d.ts +77 -0
  165. package/dist/tools/jobs.js +181 -0
  166. package/dist/tools/language.d.ts +6 -0
  167. package/dist/tools/language.js +174 -0
  168. package/dist/tools/registry.d.ts +28 -0
  169. package/dist/tools/registry.js +105 -0
  170. package/dist/tools/run.d.ts +13 -0
  171. package/dist/tools/run.js +159 -0
  172. package/dist/tools/search.d.ts +2 -0
  173. package/dist/tools/search.js +156 -0
  174. package/dist/tools/shell-process.d.ts +115 -0
  175. package/dist/tools/shell-process.js +286 -0
  176. package/dist/tools/skills.d.ts +2 -0
  177. package/dist/tools/skills.js +46 -0
  178. package/dist/tools/web.d.ts +24 -0
  179. package/dist/tools/web.js +386 -0
  180. package/docs/ci-repair-20261116.md +30 -0
  181. package/docs/commonlisp-provider-migration.md +22 -0
  182. package/docs/commonlisp-qlot-recovery.md +28 -0
  183. package/docs/commonlisp-tls-recovery.md +28 -0
  184. package/docs/context-efficiency.md +100 -0
  185. package/docs/input.md +66 -0
  186. package/docs/languages.md +117 -0
  187. package/docs/models.md +85 -0
  188. package/docs/modkh-evidence.json +641 -0
  189. package/docs/modkh-failure-comparison.json +675 -0
  190. package/docs/modkh-namespace.md +39 -0
  191. package/docs/modkh-qlot-evidence.json +37 -0
  192. package/docs/modkh-verification.md +173 -0
  193. package/docs/modkh.md +124 -0
  194. package/docs/presets.md +19 -0
  195. package/docs/setup.md +112 -0
  196. package/docs/subagents.md +134 -0
  197. package/docs/web.md +57 -0
  198. package/experiments/presets/common-lisp.lisp +38 -0
  199. package/experiments/presets/css.lisp +38 -0
  200. package/experiments/presets/formal.lisp +7 -0
  201. package/experiments/presets/html.lisp +38 -0
  202. package/experiments/presets/js.lisp +38 -0
  203. package/experiments/presets/php.lisp +38 -0
  204. package/experiments/presets/svelte.lisp +38 -0
  205. package/experiments/presets/tailwindcss.lisp +24 -0
  206. package/experiments/presets/ts.lisp +38 -0
  207. package/package.json +49 -4
  208. package/plugins/modkh-explorer/index.mjs +3 -0
  209. package/plugins/modkh-explorer/plugin.json +1 -0
  210. package/plugins/modkh-worker/index.mjs +3 -0
  211. package/plugins/modkh-worker/plugin.json +1 -0
  212. package/skills/kiokuko-dsh/LICENSE +21 -0
  213. package/skills/kiokuko-dsh/coding-ideal-routine-skill/SKILL.md +106 -0
  214. package/skills/kiokuko-dsh/japanese-translation-for-oss-models/SKILL.md +65 -0
  215. package/skills/kiokuko-dsh/kiokuko-architecture/SKILL.md +20 -0
  216. package/skills/kiokuko-dsh/kiokuko-architecture/references/cases.md +11 -0
  217. package/skills/kiokuko-dsh/kiokuko-benchmark/SKILL.md +20 -0
  218. package/skills/kiokuko-dsh/kiokuko-benchmark/references/cases.md +11 -0
  219. package/skills/kiokuko-dsh/kiokuko-investigate/SKILL.md +20 -0
  220. package/skills/kiokuko-dsh/kiokuko-investigate/references/cases.md +11 -0
  221. package/skills/kiokuko-dsh/kiokuko-lisp/SKILL.md +390 -0
  222. package/skills/kiokuko-dsh/kiokuko-review/SKILL.md +20 -0
  223. package/skills/kiokuko-dsh/kiokuko-review/references/cases.md +11 -0
  224. package/skills/kiokuko-dsh/kiokuko-simple-work/SKILL.md +70 -0
  225. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/SKILL.md +79 -0
  226. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/boundaries-and-ownership.md +52 -0
  227. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/domain-and-types.md +48 -0
  228. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/effects-and-data.md +43 -0
  229. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/kiokuko-patterns.md +314 -0
  230. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/problem-shaping-and-language.md +90 -0
  231. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/protocols-and-idempotency.md +42 -0
  232. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/review-checklist.md +92 -0
  233. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/verification.md +45 -0
  234. package/skills/kiokuko-dsh/kiokuko-skill-authoring/SKILL.md +20 -0
  235. package/skills/kiokuko-dsh/kiokuko-skill-authoring/references/cases.md +11 -0
  236. package/skills/kiokuko-dsh/kiokuko-soul/SKILL.md +25 -0
  237. package/skills/kiokuko-dsh/kiokuko-technical-writing/SKILL.md +20 -0
  238. package/skills/kiokuko-dsh/kiokuko-technical-writing/references/cases.md +11 -0
  239. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/SKILL.md +64 -0
  240. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/accessibility-and-navigation.md +31 -0
  241. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/async-recovery.md +49 -0
  242. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/forms-and-controls.md +35 -0
  243. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/interaction-feedback.md +34 -0
  244. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/responsive-and-platform.md +38 -0
  245. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/safety-and-review.md +43 -0
  246. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/ui-checklist.md +75 -0
  247. package/skills/kiokuko-dsh/kiokuko-verification/SKILL.md +20 -0
  248. package/skills/kiokuko-dsh/kiokuko-verification/references/cases.md +11 -0
  249. package/skills/kiokuko-dsh/manifest.json +168 -0
  250. package/skills/kiokuko-dsh/memory-reasoning/SKILL.md +44 -0
  251. package/skills/kiokuko-dsh/one-shot-software-completion/SKILL.md +113 -0
  252. package/skills/kiokuko-dsh/one-shot-software-completion/references/boundaries-and-lifecycle.md +70 -0
  253. package/skills/kiokuko-dsh/one-shot-software-completion/references/discovery-and-scope.md +71 -0
  254. package/skills/kiokuko-dsh/one-shot-software-completion/references/failure-recovery.md +43 -0
  255. package/skills/kiokuko-dsh/one-shot-software-completion/references/verification-and-completion.md +73 -0
  256. package/skills/kiokuko-dsh/veteran-programmer-skill/SKILL.md +66 -0
@@ -0,0 +1,50 @@
1
+ import type { LanguageDefinition } from './catalog.ts';
2
+ export interface InstalledServer {
3
+ command: string;
4
+ args: string[];
5
+ /** Digest of the installed manifest, used to notice a changed install. */
6
+ digest: string;
7
+ version: string;
8
+ installedAt: string;
9
+ }
10
+ export declare function verifyTsserver(prefix: string): void;
11
+ export interface Resolution {
12
+ status: 'ready' | 'missing' | 'unsupported' | 'disabled' | 'error';
13
+ command?: string;
14
+ args?: string[];
15
+ detail?: string;
16
+ installed?: boolean;
17
+ }
18
+ /**
19
+ * Find a server without installing: explicit setting, then MODKH-managed prefix, then host PATH.
20
+ * Installation is a separate step so a plain read never blocks on a network download.
21
+ */
22
+ export declare function resolveServer(language: LanguageDefinition, options: {
23
+ disabled?: boolean;
24
+ server?: {
25
+ command: string;
26
+ args?: string[];
27
+ };
28
+ }): Resolution;
29
+ export interface InstallOutcome {
30
+ status: 'ready' | 'unavailable' | 'error';
31
+ detail?: string;
32
+ }
33
+ /** Idempotent: a verified install is reused, and a failed install is reported without retrying. */
34
+ export declare function ensureInstalled(language: LanguageDefinition, options: {
35
+ autoInstall: boolean;
36
+ disabled?: boolean;
37
+ server?: {
38
+ command: string;
39
+ args?: string[];
40
+ };
41
+ signal?: AbortSignal;
42
+ }): Promise<InstallOutcome>;
43
+ /** Explicit retry clears the remembered failure and re-resolves the recipe. */
44
+ export declare function clearFailure(id: string): void;
45
+ export declare function statusReport(): {
46
+ id: string;
47
+ version?: string;
48
+ command?: string;
49
+ installedAt?: string;
50
+ }[];
@@ -0,0 +1,293 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { executeBounded, privateEnvironment } from "../lisp/runtime.js";
5
+ import { CL_LSP_REPOSITORY } from "./commonlisp-bundled.js";
6
+ import { installCommonLisp, reusableCommonLisp } from "./commonlisp-install.js";
7
+ import { installPhpantom } from "./native.js";
8
+ import { hostPlatform } from "./platform.js";
9
+ import { probeTypescript, recommendedTypescript } from "./typescript-capability.js";
10
+ import { LspServer } from "./lsp/client.js";
11
+ import { languageHome } from "./detect.js";
12
+ const LOCK_STALE_MS = 10 * 60_000;
13
+ const MAKE_TIMEOUT_MS = 240_000;
14
+ function statePath() { return path.join(languageHome(), 'state.json'); }
15
+ function readState() {
16
+ try {
17
+ const parsed = JSON.parse(fs.readFileSync(statePath(), 'utf8'));
18
+ if (parsed && typeof parsed === 'object' && parsed.version === 1 && parsed.servers && typeof parsed.servers === 'object')
19
+ return parsed;
20
+ }
21
+ catch { /* missing or corrupt: start clean, never trust half-written JSON */ }
22
+ return { version: 1, servers: {} };
23
+ }
24
+ /** Write through a temporary file so a crash cannot leave a truncated manifest. */
25
+ function writeState(state) {
26
+ fs.mkdirSync(languageHome(), { recursive: true });
27
+ const target = statePath();
28
+ const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
29
+ fs.writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', flush: true });
30
+ fs.renameSync(temporary, target);
31
+ }
32
+ function digestOf(file) {
33
+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
34
+ }
35
+ function isExecutable(file) {
36
+ try {
37
+ const stat = fs.statSync(file);
38
+ if (!stat.isFile())
39
+ return false;
40
+ fs.accessSync(file, fs.constants.X_OK);
41
+ return true;
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
47
+ function versionOf(packageJson) {
48
+ try {
49
+ const parsed = JSON.parse(fs.readFileSync(packageJson, 'utf8'));
50
+ return typeof parsed.version === 'string' ? parsed.version : 'unknown';
51
+ }
52
+ catch {
53
+ return 'unknown';
54
+ }
55
+ }
56
+ function serverRoot(language) {
57
+ return path.join(languageHome(), 'servers', language.id);
58
+ }
59
+ /** Cross-process exclusion for one install target; a stale lock is reclaimed after a fixed age. */
60
+ async function withLock(target, action) {
61
+ fs.mkdirSync(path.dirname(target), { recursive: true });
62
+ const lock = `${target}.lock`;
63
+ const deadline = Date.now() + 60_000;
64
+ for (;;) {
65
+ try {
66
+ fs.mkdirSync(lock);
67
+ break;
68
+ }
69
+ catch (e) {
70
+ if (e.code !== 'EEXIST')
71
+ throw e;
72
+ try {
73
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) {
74
+ fs.rmSync(lock, { recursive: true, force: true });
75
+ continue;
76
+ }
77
+ }
78
+ catch {
79
+ continue;
80
+ }
81
+ if (Date.now() > deadline)
82
+ throw new Error('他のMODKHプロセスが導入中のため待機時間を超えました');
83
+ await new Promise(resolve => setTimeout(resolve, 250));
84
+ }
85
+ }
86
+ const heartbeat = setInterval(() => { try {
87
+ const now = new Date();
88
+ fs.utimesSync(lock, now, now);
89
+ }
90
+ catch { /* action reports its own failure */ } }, 30000);
91
+ try {
92
+ return await action();
93
+ }
94
+ finally {
95
+ clearInterval(heartbeat);
96
+ fs.rmSync(lock, { recursive: true, force: true });
97
+ }
98
+ }
99
+ async function run(command, args, signal) {
100
+ const home = path.join(languageHome(), 'runtime-home');
101
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
102
+ const result = await executeBounded(command, [...args], { cwd: home, env: privateEnvironment(home),
103
+ inputDigest: createHash('sha256').update(JSON.stringify([command, args])).digest('hex'), signal, timeoutMs: MAKE_TIMEOUT_MS, maxOutputBytes: 1024 * 1024 });
104
+ if (result.state !== 'exited')
105
+ throw new Error(`Installer ${result.state}: ${result.stderr.slice(-1000)}`);
106
+ return { code: result.exitCode ?? -1, stdout: result.stdout, stderr: result.stderr };
107
+ }
108
+ export function verifyTsserver(prefix) {
109
+ const api = path.join(prefix, 'node_modules', 'typescript', 'lib', 'tsserver.js');
110
+ if (!fs.existsSync(api) || !fs.statSync(api).isFile())
111
+ throw new Error('TypeScript dependency lacks required typescript/lib/tsserver.js API');
112
+ }
113
+ async function initializeProbe(language, command, args, root, signal) {
114
+ const server = new LspServer({ id: language.id, command, args, root, requestTimeoutMs: 10000,
115
+ env: privateEnvironment(root), inheritEnv: false });
116
+ try {
117
+ await server.start(signal);
118
+ }
119
+ finally {
120
+ await server.dispose();
121
+ }
122
+ }
123
+ /** Install into a private prefix with a private npm cache; never touch the project or the user cache. */
124
+ async function installNpm(language, signal) {
125
+ const recipe = language.install;
126
+ if (recipe?.kind !== 'npm')
127
+ throw new Error('npm 導入レシピがありません');
128
+ const target = serverRoot(language);
129
+ await withLock(target, async () => {
130
+ if (readState().servers[language.id] && resolveServer(language, {}).status === 'ready')
131
+ return;
132
+ const staging = `${target}.staging-${process.pid}-${Date.now()}`;
133
+ fs.rmSync(staging, { recursive: true, force: true });
134
+ fs.mkdirSync(staging, { recursive: true });
135
+ try {
136
+ const space = fs.statfsSync(staging);
137
+ if (space.bavail * space.bsize < 512 * 1024 * 1024)
138
+ throw new Error('Insufficient disk space for server install (512 MiB reserve)');
139
+ const cache = path.join(languageHome(), 'npm-cache');
140
+ fs.mkdirSync(cache, { recursive: true });
141
+ const result = await run('npm', [
142
+ 'install', '--prefix', staging, '--cache', cache, '--no-audit', '--no-fund', '--ignore-scripts', '--registry', 'https://registry.npmjs.org',
143
+ ...recipe.packages,
144
+ ], signal);
145
+ if (result.code !== 0) {
146
+ fs.rmSync(staging, { recursive: true, force: true });
147
+ throw new Error(`npm 導入に失敗: ${result.stderr.trim().split('\n').slice(-3).join(' ').slice(0, 400)}`);
148
+ }
149
+ let typescript;
150
+ if (['typescript', 'javascript', 'tsx'].includes(language.id)) {
151
+ let selection = 'typescript@latest';
152
+ let recommendationSha256;
153
+ // Missing JS tsserver is the compatibility trigger, not a numeric version gate.
154
+ try {
155
+ verifyTsserver(staging);
156
+ }
157
+ catch {
158
+ if (signal?.aborted)
159
+ throw new Error('TypeScript installation aborted');
160
+ const readme = fs.readFileSync(path.join(staging, 'node_modules/typescript-language-server/README.md'), 'utf8');
161
+ const recommended = recommendedTypescript(readme);
162
+ if (!recommended)
163
+ throw new Error('Missing tsserver API and no unambiguous official compatibility recommendation');
164
+ selection = recommended;
165
+ recommendationSha256 = createHash('sha256').update(readme).digest('hex');
166
+ const fallback = await run('npm', ['install', '--prefix', staging, '--cache', cache, '--no-audit', '--no-fund', '--ignore-scripts', '--registry', 'https://registry.npmjs.org', recommended], signal);
167
+ if (fallback.code !== 0)
168
+ throw new Error(`TypeScript compatibility install failed: ${fallback.stderr.slice(-400)}`);
169
+ verifyTsserver(staging);
170
+ }
171
+ typescript = { ...await probeTypescript(staging, signal), selection, recommendationSha256 };
172
+ }
173
+ // Only publish a prefix that actually contains the expected entry point.
174
+ if (!isExecutable(path.join(staging, 'node_modules', '.bin', recipe.entry))) {
175
+ fs.rmSync(staging, { recursive: true, force: true });
176
+ throw new Error(`導入後に ${recipe.entry} が見つかりません`);
177
+ }
178
+ await initializeProbe(language, path.join(staging, 'node_modules', '.bin', recipe.entry), [...(language.lsp?.args ?? [])], staging, signal);
179
+ fs.rmSync(target, { recursive: true, force: true });
180
+ fs.renameSync(staging, target);
181
+ const binary = path.join(target, 'node_modules', '.bin', recipe.entry);
182
+ const manifest = path.join(target, 'node_modules', recipe.packages[0].replace(/@[^@/]+$/, ''), 'package.json');
183
+ const lockfile = path.join(target, 'package-lock.json');
184
+ fs.writeFileSync(path.join(target, 'install-receipt.json'), JSON.stringify({
185
+ typescript, platform: hostPlatform(), packages: recipe.packages, packageName: recipe.packages[0].replace(/@[^@/]+$/, ''), binary: recipe.entry,
186
+ lockfileSha256: fs.existsSync(lockfile) ? digestOf(lockfile) : null,
187
+ binarySha256: digestOf(binary), initialized: true, finishedAt: new Date().toISOString(),
188
+ }, null, 2));
189
+ const state = readState();
190
+ state.servers[language.id] = {
191
+ command: binary,
192
+ args: [...(language.lsp?.args ?? [])],
193
+ digest: fs.existsSync(manifest) ? digestOf(manifest) : digestOf(binary),
194
+ version: fs.existsSync(manifest) ? versionOf(manifest) : 'unknown',
195
+ installedAt: new Date().toISOString(),
196
+ };
197
+ delete state.failures?.[language.id];
198
+ writeState(state);
199
+ }
200
+ finally {
201
+ fs.rmSync(staging, { recursive: true, force: true });
202
+ }
203
+ });
204
+ }
205
+ /**
206
+ * Find a server without installing: explicit setting, then MODKH-managed prefix, then host PATH.
207
+ * Installation is a separate step so a plain read never blocks on a network download.
208
+ */
209
+ export function resolveServer(language, options) {
210
+ if (options.disabled)
211
+ return { status: 'disabled', detail: `${language.id} は設定で無効` };
212
+ if (options.server)
213
+ return { status: 'ready', command: options.server.command, args: [...(options.server.args ?? language.lsp?.args ?? [])] };
214
+ const state = readState();
215
+ const managed = state.servers[language.id];
216
+ if (managed && isExecutable(managed.command) && (language.id !== 'commonlisp' || reusableCommonLisp(managed.command, managed.digest)))
217
+ return { status: 'ready', command: managed.command, args: managed.args, installed: true };
218
+ const recipe = language.install;
219
+ if (recipe?.kind === 'host') {
220
+ for (const candidate of recipe.candidates) {
221
+ if (candidate.includes('/') ? isExecutable(candidate) : isOnPath(candidate)) {
222
+ return { status: 'ready', command: candidate, args: [...(language.lsp?.args ?? [])], installed: true };
223
+ }
224
+ }
225
+ return { status: 'missing', detail: recipe.requirement ?? 'サーバーが見つかりません' };
226
+ }
227
+ return { status: 'missing' };
228
+ }
229
+ function isOnPath(binary) {
230
+ const pathValue = process.env['PATH'] ?? '';
231
+ return pathValue.split(path.delimiter).some(directory => directory.length > 0 && isExecutable(path.join(directory, binary)));
232
+ }
233
+ /** Idempotent: a verified install is reused, and a failed install is reported without retrying. */
234
+ export async function ensureInstalled(language, options) {
235
+ if (!hostPlatform())
236
+ return { status: 'unavailable', detail: `Unsupported OS/CPU: ${process.platform}/${process.arch}` };
237
+ const existing = resolveServer(language, options);
238
+ if (existing.status === 'ready')
239
+ return { status: 'ready' };
240
+ if (existing.status === 'disabled')
241
+ return { status: 'unavailable', detail: existing.detail };
242
+ if (language.install?.kind === 'host' && !['php', 'commonlisp'].includes(language.id)) {
243
+ return { status: 'unavailable', detail: `${language.install.requirement ?? 'サーバーがありません'}(自動取得は行いません)` };
244
+ }
245
+ if (!options.autoInstall)
246
+ return { status: 'unavailable', detail: '自動導入は無効です' };
247
+ const remembered = readState().failures?.[language.id];
248
+ if (remembered && (language.id !== 'commonlisp' || remembered.recipe === CL_LSP_REPOSITORY) && (remembered.retryable === false || Date.now() - Date.parse(remembered.at) < 60000))
249
+ return { status: 'unavailable', detail: `前回の導入失敗: ${remembered.reason}` };
250
+ try {
251
+ if (language.id === 'php' || language.id === 'commonlisp') {
252
+ const target = serverRoot(language);
253
+ await withLock(target, async () => {
254
+ if (resolveServer(language, {}).status === 'ready')
255
+ return;
256
+ const prior = readState().failures?.[language.id];
257
+ if (prior && (language.id !== 'commonlisp' || prior.recipe === CL_LSP_REPOSITORY) && (prior.retryable === false || Date.now() - Date.parse(prior.at) < 60000))
258
+ throw new Error(`Previous install failed: ${prior.reason}`);
259
+ const result = await (language.id === 'php' ? installPhpantom : installCommonLisp)(target, options.signal);
260
+ const state = readState();
261
+ state.servers[language.id] = { command: result.command, args: [], version: result.version, digest: result.digest, installedAt: new Date().toISOString() };
262
+ delete state.failures?.[language.id];
263
+ writeState(state);
264
+ });
265
+ }
266
+ else
267
+ await installNpm(language, options.signal);
268
+ return { status: 'ready' };
269
+ }
270
+ catch (e) {
271
+ const reason = e instanceof Error ? e.message : String(e);
272
+ // Remembering the failure is best effort: an unwritable home must not escape as a crash.
273
+ try {
274
+ const state = readState();
275
+ state.failures = { ...(state.failures ?? {}), [language.id]: { ...(language.id === 'commonlisp' ? { recipe: CL_LSP_REPOSITORY } : {}), reason: reason.slice(0, 500), at: new Date().toISOString(), retryable: !/ENOSPC|Insufficient disk|unknown/.test(reason) } };
276
+ writeState(state);
277
+ }
278
+ catch { /* the caller still receives the original reason below */ }
279
+ return { status: 'error', detail: reason };
280
+ }
281
+ }
282
+ /** Explicit retry clears the remembered failure and re-resolves the recipe. */
283
+ export function clearFailure(id) {
284
+ const state = readState();
285
+ if (!state.failures?.[id])
286
+ return;
287
+ delete state.failures[id];
288
+ writeState(state);
289
+ }
290
+ export function statusReport() {
291
+ const state = readState();
292
+ return Object.entries(state.servers).map(([id, server]) => ({ id, version: server.version, command: server.command, installedAt: server.installedAt }));
293
+ }
@@ -0,0 +1,97 @@
1
+ /** A single running server for one (root, language, config) key. */
2
+ export interface ServerDiagnostic {
3
+ path: string;
4
+ line: number;
5
+ column: number;
6
+ endLine: number;
7
+ endColumn: number;
8
+ severity: 'error' | 'warning' | 'info' | 'hint';
9
+ message: string;
10
+ source?: string;
11
+ server: string;
12
+ }
13
+ export interface OpenState {
14
+ version: number;
15
+ text: string;
16
+ /** Monotonic local counter; the server may return diagnostics for an older version. */
17
+ diagnostics: ServerDiagnostic[];
18
+ /** Version whose diagnostics were last observed, if any. */
19
+ diagnosticVersion?: number;
20
+ /** Whether the server has signalled any diagnostic result for this document at all. */
21
+ notified: boolean;
22
+ }
23
+ export interface LspServerOptions {
24
+ id: string;
25
+ command: string;
26
+ args: readonly string[];
27
+ root: string;
28
+ requestTimeoutMs: number;
29
+ /** Extra environment for the server process; used by tests to select a fixture mode. */
30
+ env?: Record<string, string>;
31
+ inheritEnv?: boolean;
32
+ log?(message: string): void;
33
+ }
34
+ export declare class LspServer {
35
+ readonly id: string;
36
+ private readonly options;
37
+ private child?;
38
+ private connection?;
39
+ private readonly open;
40
+ private starting?;
41
+ private disposed;
42
+ private disposal?;
43
+ private selectedEncoding;
44
+ /** Pull-diagnostics support, announced by the server's capabilities rather than a version string. */
45
+ private pullDiagnostics;
46
+ capabilities: Record<string, unknown>;
47
+ private diagnosticTrace;
48
+ get diagnosticEvidence(): {
49
+ pullSupported: boolean;
50
+ pushNotifications: number;
51
+ pullRequests: number;
52
+ pullReports: number;
53
+ };
54
+ constructor(options: LspServerOptions);
55
+ get running(): boolean;
56
+ get documents(): Map<string, OpenState>;
57
+ start(signal?: AbortSignal): Promise<void>;
58
+ private launch;
59
+ private configuration;
60
+ /** Servers may use UTF-8 offsets; only the announced encoding is trusted. */
61
+ get encoding(): 'utf-16' | 'utf-8' | 'utf-32';
62
+ private withTimeout;
63
+ private acceptPushDiagnostics;
64
+ openDocument(file: string, text: string): Promise<OpenState>;
65
+ /** Waits for a diagnostic result that belongs to the current version, or reports absence. */
66
+ synchronize(file: string, text: string): Promise<{
67
+ status: 'observed' | 'waiting' | 'unsupported';
68
+ diagnostics: ServerDiagnostic[];
69
+ version: number;
70
+ }>;
71
+ hover(file: string, position: {
72
+ line: number;
73
+ character: number;
74
+ }): Promise<string | null>;
75
+ definition(file: string, position: {
76
+ line: number;
77
+ character: number;
78
+ }): Promise<{
79
+ file: string;
80
+ line: number;
81
+ character: number;
82
+ }[]>;
83
+ references(file: string, position: {
84
+ line: number;
85
+ character: number;
86
+ }): Promise<{
87
+ file: string;
88
+ line: number;
89
+ character: number;
90
+ }[]>;
91
+ private locations;
92
+ private requireConnection;
93
+ dispose(): Promise<void>;
94
+ private stop;
95
+ }
96
+ export declare function rememberDocumentText(server: LspServer, file: string): string | undefined;
97
+ export declare function fileStillExists(file: string): boolean;