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,138 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { detectLanguage } from "../detect.js";
4
+ import { languageById } from "../catalog.js";
5
+ import { ensureInstalled, resolveServer } from "../install.js";
6
+ import { ServerPool, aggregate, realRoot } from "./pool.js";
7
+ const MAX_ANALYZED_FILE_BYTES = 2 * 1024 * 1024;
8
+ /**
9
+ * Owns language detection, installation and semantic analysis for one workspace. Analysis never
10
+ * changes the outcome of an edit: callers keep their own success result and append this report.
11
+ */
12
+ export class LanguageService {
13
+ root;
14
+ settings;
15
+ progress;
16
+ pool;
17
+ /** In-flight work per file prevents duplicate installs/starts in one turn. */
18
+ inflight = new Map();
19
+ disposed = false;
20
+ constructor(options) {
21
+ this.root = realRoot(options.root);
22
+ this.settings = options.settings;
23
+ this.progress = options.progress;
24
+ this.pool = options.pool ?? new ServerPool({ requestTimeoutMs: options.settings.requestTimeoutMs });
25
+ }
26
+ get poolSize() { return this.pool.size; }
27
+ /** The already-running server for a file, if its language/root was analyzed before. */
28
+ poolFor(file, selector) {
29
+ const detection = this.detect(file);
30
+ if (!detection)
31
+ return undefined;
32
+ const id = selector ?? detection.language.id;
33
+ const configured = this.settings.servers[id];
34
+ return this.pool.find(realRoot(detection.root), id, JSON.stringify(configured ?? null));
35
+ }
36
+ detect(file) { return detectLanguage(file, this.root); }
37
+ /** Analyze a file after a read or a successful write. Never throws. */
38
+ async analyze(file, text, signal, selector) {
39
+ try {
40
+ return await this.analyzeGuarded(file, text, signal, selector);
41
+ }
42
+ catch (e) {
43
+ return { status: 'unavailable', detail: `解析できない: ${e instanceof Error ? e.message : String(e)}` };
44
+ }
45
+ }
46
+ async analyzeGuarded(file, text, signal, selector) {
47
+ if (this.disposed)
48
+ return { status: 'unavailable', detail: '言語サービスは終了済みです' };
49
+ if (Buffer.byteLength(text) > MAX_ANALYZED_FILE_BYTES) {
50
+ return { status: 'unavailable', detail: '2 MiBを超えるファイルは解析しない(本文の操作は可能)' };
51
+ }
52
+ const detection = this.detect(file);
53
+ if (!detection)
54
+ return { status: 'unavailable', detail: '対応言語ではない' };
55
+ const language = selector ? languageById(selector) : detection.language;
56
+ if (this.settings.disabled.includes(language.id)) {
57
+ return { status: 'unavailable', language: language.id, detail: `${language.id} は設定で無効` };
58
+ }
59
+ const key = `${realRoot(detection.root)}::${language.id}::${file}::${text}`;
60
+ const running = this.inflight.get(key);
61
+ if (running)
62
+ return running;
63
+ const work = this.analyzeOnce(language, detection.root, file, text, signal).finally(() => this.inflight.delete(key));
64
+ this.inflight.set(key, work);
65
+ return work;
66
+ }
67
+ async analyzeOnce(language, root, file, text, signal, selector) {
68
+ const configured = this.settings.servers[language.id];
69
+ const resolved = resolveServer(language, { disabled: false, ...(configured ? { server: configured } : {}) });
70
+ let launch = resolved.status === 'ready' && resolved.command
71
+ ? { command: resolved.command, args: resolved.args ?? [] }
72
+ : undefined;
73
+ let installed = false;
74
+ if (!launch) {
75
+ if (!this.settings.autoInstall) {
76
+ return { status: 'unavailable', language: language.id, detail: resolved.detail ?? 'サーバー未導入(自動導入は無効)' };
77
+ }
78
+ this.progress?.(`${language.id} の言語サーバーを準備しています(初回のみ)…`);
79
+ const outcome = await ensureInstalled(language, {
80
+ autoInstall: this.settings.autoInstall,
81
+ ...(configured ? { server: configured } : {}),
82
+ ...(signal ? { signal } : {}),
83
+ });
84
+ if (outcome.status !== 'ready') {
85
+ return { status: 'unavailable', language: language.id, detail: outcome.detail ?? 'サーバーを準備できません' };
86
+ }
87
+ installed = true;
88
+ const after = resolveServer(language, {});
89
+ if (after.status !== 'ready' || !after.command) {
90
+ return { status: 'unavailable', language: language.id, detail: '導入後にサーバーを解決できない' };
91
+ }
92
+ launch = { command: after.command, args: after.args ?? [] };
93
+ }
94
+ const started = await this.pool.acquire({ root: realRoot(root), language, configDigest: JSON.stringify(configured ?? null) }, launch, signal);
95
+ if (started.status !== 'ready') {
96
+ return { status: 'unavailable', language: language.id, installed, detail: started.detail ?? 'サーバーを起動できません' };
97
+ }
98
+ let sync;
99
+ try {
100
+ sync = await started.server.synchronize(file, text);
101
+ }
102
+ catch (e) {
103
+ return { status: 'partial', language: language.id, installed, detail: `診断を取得できません: ${e.message}` };
104
+ }
105
+ const combined = aggregate([{ id: language.id, status: sync.status, diagnostics: sync.diagnostics }]);
106
+ return {
107
+ status: sync.status === 'observed' ? 'ok' : 'partial',
108
+ language: language.id,
109
+ installed,
110
+ diagnostics: combined.diagnostics,
111
+ servers: combined.servers,
112
+ ...(sync.status === 'observed' ? {} : { detail: '診断はまだ通知されていません(診断0件とは区別する)' }),
113
+ };
114
+ }
115
+ async close() {
116
+ if (this.disposed)
117
+ return;
118
+ this.disposed = true;
119
+ await this.pool.disposeAll();
120
+ }
121
+ }
122
+ export function formatDiagnostics(result) {
123
+ if (result.status === 'unavailable')
124
+ return `解析: 未実施 — ${result.detail ?? '理由不明'}`;
125
+ const servers = (result.servers ?? [])
126
+ .map(server => `${server.id}:${server.status}${server.detail ? `(${server.detail})` : ''}`)
127
+ .join(' ');
128
+ const items = result.diagnostics ?? [];
129
+ const head = `解析: ${result.status}${result.language ? ` ${result.language}` : ''}${servers ? ` [${servers}]` : ''}`;
130
+ if (items.length === 0)
131
+ return `${head}${result.status === 'ok' ? '。診断0件' : ''}`;
132
+ const lines = items.slice(0, 20).map(d => ` ${d.path}:${d.line}:${d.column} ${d.severity}: ${d.message.slice(0, 300)}`);
133
+ return `${head}。${items.length}件\n${lines.join('\n')}`;
134
+ }
135
+ /** Kept for callers that need the resolved workspace root without constructing a service. */
136
+ export function workspaceRoot(root) { return realRoot(root); }
137
+ export function exists(file) { return fs.existsSync(file) && fs.statSync(file).isFile(); }
138
+ export function resolveWithin(root, file) { return path.resolve(root, file); }
@@ -0,0 +1,8 @@
1
+ /** Reads only official release origins, with a hard body bound and bounded redirects. */
2
+ export declare function download(url: string, max: number, signal?: AbortSignal): Promise<Buffer>;
3
+ export declare function installPhpantom(target: string, signal?: AbortSignal): Promise<{
4
+ command: string;
5
+ version: string;
6
+ digest: string;
7
+ receipt: Record<string, unknown>;
8
+ }>;
@@ -0,0 +1,100 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { executeBounded, privateEnvironment, sha256 } from "../lisp/runtime.js";
4
+ import { hostPlatform, phpAsset } from "./platform.js";
5
+ import { LspServer } from "./lsp/client.js";
6
+ /** Reads only official release origins, with a hard body bound and bounded redirects. */
7
+ export async function download(url, max, signal) {
8
+ const allowed = new Set(['api.github.com', 'github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com']);
9
+ const controller = AbortSignal.any([AbortSignal.timeout(120000), ...(signal ? [signal] : [])]);
10
+ for (let redirects = 0; redirects < 5; redirects++) {
11
+ const target = new URL(url);
12
+ if (target.protocol !== 'https:' || !allowed.has(target.hostname) || target.username || target.password)
13
+ throw new Error('Unapproved native release origin');
14
+ const response = await fetch(target, { redirect: 'manual', signal: controller, headers: { 'User-Agent': 'MoDKH', Accept: 'application/vnd.github+json' } });
15
+ if (response.status >= 300 && response.status < 400) {
16
+ await response.body?.cancel();
17
+ url = new URL(response.headers.get('location') ?? '', target).href;
18
+ continue;
19
+ }
20
+ if (!response.ok || !response.body)
21
+ throw new Error(`Release download HTTP ${response.status}`);
22
+ if (Number(response.headers.get('content-length') ?? 0) > max) {
23
+ await response.body.cancel();
24
+ throw new Error('Release exceeds byte limit');
25
+ }
26
+ const chunks = [];
27
+ let size = 0;
28
+ for await (const chunk of response.body) {
29
+ const bytes = Buffer.from(chunk);
30
+ size += bytes.length;
31
+ if (size > max)
32
+ throw new Error('Release exceeds byte limit');
33
+ chunks.push(bytes);
34
+ }
35
+ return Buffer.concat(chunks);
36
+ }
37
+ throw new Error('Too many official release redirects');
38
+ }
39
+ export async function installPhpantom(target, signal) {
40
+ const platform = hostPlatform();
41
+ if (!platform)
42
+ throw new Error('Unsupported PHPantom host');
43
+ const metadata = JSON.parse((await download('https://api.github.com/repos/PHPantom-dev/phpantom_lsp/releases/latest', 2 * 1024 * 1024, signal)).toString('utf8'));
44
+ if (typeof metadata.tag_name !== 'string' || !Array.isArray(metadata.assets))
45
+ throw new Error('Invalid official release metadata');
46
+ const asset = phpAsset(metadata.assets, platform);
47
+ const space = fs.statfsSync(path.dirname(target));
48
+ if (space.bavail * space.bsize < asset.size * 6 + 64 * 1024 * 1024)
49
+ throw new Error('Insufficient disk space for native archive and extraction');
50
+ const staging = fs.mkdtempSync(`${target}.staging-`);
51
+ let settled = true;
52
+ try {
53
+ const bytes = await download(asset.browser_download_url, asset.size, signal);
54
+ const archiveHash = sha256(bytes);
55
+ if (bytes.length !== asset.size || `sha256:${archiveHash}` !== asset.digest)
56
+ throw new Error('Official PHPantom archive SHA256/size mismatch');
57
+ const archive = path.join(staging, 'release.tar.gz');
58
+ fs.writeFileSync(archive, bytes, { flag: 'wx', mode: 0o600 });
59
+ const run = async (args) => {
60
+ const result = await executeBounded('/usr/bin/tar', args, { cwd: staging, env: privateEnvironment(staging), signal, timeoutMs: 30000, inputDigest: archiveHash });
61
+ settled &&= result.cleanup === 'settled';
62
+ if (result.state !== 'exited' || result.exitCode !== 0)
63
+ throw new Error(`Native extraction ${result.state}: ${result.stderr}`);
64
+ return result.stdout;
65
+ };
66
+ const names = (await run(['-tzf', archive])).trim().split('\n');
67
+ if (names.length > 128 || names.some(n => !/^[A-Za-z0-9._/-]+$/.test(n) || path.isAbsolute(n) || n.split('/').includes('..')))
68
+ throw new Error('Unsafe archive paths');
69
+ const listing = (await run(['-tvzf', archive])).trim().split('\n');
70
+ if (listing.some(line => !/^[-d]/.test(line)))
71
+ throw new Error('Archive links/special files not permitted');
72
+ await run(['-xzf', archive, '--no-same-owner']);
73
+ const binaries = names.filter(n => path.basename(n) === 'phpantom_lsp');
74
+ if (binaries.length !== 1)
75
+ throw new Error('Expected exactly one PHPantom binary');
76
+ const binary = path.join(staging, binaries[0]);
77
+ if (!fs.lstatSync(binary).isFile() || fs.realpathSync(binary) !== binary)
78
+ throw new Error('Invalid native binary');
79
+ fs.chmodSync(binary, 0o700);
80
+ const binaryHash = sha256(fs.readFileSync(binary));
81
+ const server = new LspServer({ id: 'php', command: binary, args: [], root: staging, requestTimeoutMs: 20000, env: privateEnvironment(staging), inheritEnv: false });
82
+ try {
83
+ await server.start(signal);
84
+ }
85
+ finally {
86
+ await server.dispose();
87
+ }
88
+ const receipt = { platform, release: metadata.tag_name, archiveHash, binaryHash, capabilities: server.capabilities, initialized: true, finishedAt: new Date().toISOString() };
89
+ fs.unlinkSync(archive);
90
+ fs.writeFileSync(path.join(staging, 'install-receipt.json'), JSON.stringify(receipt, null, 2));
91
+ if (fs.existsSync(target))
92
+ throw new Error('Native destination exists; refusing destructive replacement');
93
+ fs.renameSync(staging, target);
94
+ return { command: path.join(target, binaries[0]), version: metadata.tag_name, digest: binaryHash, receipt };
95
+ }
96
+ finally {
97
+ if (settled)
98
+ fs.rmSync(staging, { recursive: true, force: true });
99
+ }
100
+ }
@@ -0,0 +1,14 @@
1
+ export interface HostPlatform {
2
+ os: 'darwin' | 'linux';
3
+ arch: 'x64' | 'arm64';
4
+ target: string;
5
+ }
6
+ export declare function hostPlatform(os?: string, arch?: string): HostPlatform | undefined;
7
+ export interface ReleaseAsset {
8
+ name: string;
9
+ browser_download_url: string;
10
+ size: number;
11
+ digest?: string;
12
+ }
13
+ /** Exact official target match; never silently substitute another OS/CPU or an unchecked asset. */
14
+ export declare function phpAsset(assets: ReleaseAsset[], platform: HostPlatform): ReleaseAsset;
@@ -0,0 +1,20 @@
1
+ export function hostPlatform(os = process.platform, arch = process.arch) {
2
+ if ((os !== 'darwin' && os !== 'linux') || (arch !== 'x64' && arch !== 'arm64'))
3
+ return;
4
+ return { os, arch, target: `${arch === 'x64' ? 'x86_64' : 'aarch64'}-${os === 'darwin' ? 'apple-darwin' : 'unknown-linux-gnu'}` };
5
+ }
6
+ /** Exact official target match; never silently substitute another OS/CPU or an unchecked asset. */
7
+ export function phpAsset(assets, platform) {
8
+ const found = assets.filter(a => a.name === `phpantom_lsp-${platform.target}.tar.gz`);
9
+ if (found.length !== 1)
10
+ throw new Error(`Official PHPantom asset unavailable for ${platform.target}`);
11
+ const asset = found[0];
12
+ if (!/^sha256:[a-f0-9]{64}$/.test(asset.digest ?? ''))
13
+ throw new Error('Official SHA256 release metadata required');
14
+ const url = new URL(asset.browser_download_url);
15
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com' || !url.pathname.startsWith('/PHPantom-dev/phpantom_lsp/releases/download/'))
16
+ throw new Error('Unexpected PHPantom release origin');
17
+ if (!Number.isSafeInteger(asset.size) || asset.size < 1 || asset.size > 128 * 1024 * 1024)
18
+ throw new Error('Invalid release size');
19
+ return asset;
20
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * LSP positions are UTF-16 code units. Files are decoded as UTF-8, so a JavaScript string index
3
+ * already counts UTF-16 units; CRLF is preserved so line/character stay consistent with the server.
4
+ * These helpers never re-encode and never normalize the caller's text.
5
+ */
6
+ export declare function offsetToPosition(text: string, offset: number): {
7
+ line: number;
8
+ character: number;
9
+ };
10
+ export declare function positionToOffset(text: string, position: {
11
+ line: number;
12
+ character: number;
13
+ }): number;
14
+ /** 1-based line and column display for humans and model output. */
15
+ export declare function displayPosition(text: string, offset: number): {
16
+ line: number;
17
+ column: number;
18
+ };
19
+ export declare function fileExists(file: string): boolean;
20
+ export declare function directoryOf(file: string): string;
@@ -0,0 +1,46 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ /**
4
+ * LSP positions are UTF-16 code units. Files are decoded as UTF-8, so a JavaScript string index
5
+ * already counts UTF-16 units; CRLF is preserved so line/character stay consistent with the server.
6
+ * These helpers never re-encode and never normalize the caller's text.
7
+ */
8
+ export function offsetToPosition(text, offset) {
9
+ const limit = Math.max(0, Math.min(offset, text.length));
10
+ let line = 0, lineStart = 0;
11
+ for (let i = 0; i < limit; i++) {
12
+ if (text.charCodeAt(i) === 10) {
13
+ line++;
14
+ lineStart = i + 1;
15
+ }
16
+ }
17
+ return { line, character: limit - lineStart };
18
+ }
19
+ export function positionToOffset(text, position) {
20
+ const line = Math.max(0, Math.floor(position.line));
21
+ const character = Math.max(0, Math.floor(position.character));
22
+ let offset = 0;
23
+ for (let current = 0; current < line; current++) {
24
+ const next = text.indexOf('\n', offset);
25
+ if (next < 0)
26
+ return text.length;
27
+ offset = next + 1;
28
+ }
29
+ return Math.min(text.length, offset + character);
30
+ }
31
+ /** 1-based line and column display for humans and model output. */
32
+ export function displayPosition(text, offset) {
33
+ const { line, character } = offsetToPosition(text, offset);
34
+ return { line: line + 1, column: character + 1 };
35
+ }
36
+ export function fileExists(file) {
37
+ try {
38
+ return fs.statSync(file).isFile();
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }
44
+ export function directoryOf(file) {
45
+ return path.dirname(file);
46
+ }
@@ -0,0 +1,9 @@
1
+ export interface GrammarPaths {
2
+ wasm: string;
3
+ license: string;
4
+ bytes: Uint8Array;
5
+ }
6
+ export declare function grammarPaths(id: string): GrammarPaths | null;
7
+ export declare function availableGrammars(): string[];
8
+ /** Grammar ids whose WASM is not shipped; callers must fall back to text-only analysis. */
9
+ export declare function missingGrammars(ids: readonly string[]): string[];
@@ -0,0 +1,73 @@
1
+ import fs from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ /**
6
+ * Grammar assets ship inside the package (see scripts/build-grammars.mjs). Loading is lazy and
7
+ * cached by grammar id: a broken or missing grammar degrades that language only.
8
+ * Resolution works both from dist/language/syntax and from src/language/syntax.
9
+ */
10
+ function candidateDirectories() {
11
+ const here = path.dirname(fileURLToPath(import.meta.url));
12
+ return [
13
+ path.join(here, '..', 'grammars'), // dist/language/grammars
14
+ path.join(here, '..', '..', '..', 'dist', 'language', 'grammars'), // src/language/syntax
15
+ ];
16
+ }
17
+ function assetDirectory() {
18
+ for (const directory of candidateDirectories()) {
19
+ try {
20
+ if (fs.readdirSync(directory).length > 0)
21
+ return directory;
22
+ }
23
+ catch { /* try the next */ }
24
+ }
25
+ return null;
26
+ }
27
+ export function grammarPaths(id) {
28
+ if (!/^[a-z][a-z0-9_]*$/.test(id))
29
+ return null;
30
+ const directory = assetDirectory();
31
+ if (!directory)
32
+ return null;
33
+ const file = path.join(directory, `tree-sitter-${id}.wasm`);
34
+ if (!fs.existsSync(file))
35
+ return null;
36
+ const manifest = JSON.parse(fs.readFileSync(path.join(directory, 'manifest.json'), 'utf8'));
37
+ if (manifest.schema !== 1 || !Array.isArray(manifest.grammars))
38
+ throw new Error('Grammar integrity manifest missing or unsupported; rebuild the package');
39
+ const entries = manifest.grammars.filter((entry) => entry.id === id);
40
+ if (entries.length !== 1)
41
+ throw new Error(`Grammar ${id} is not uniquely declared in the manifest`);
42
+ const bytes = fs.readFileSync(file), entry = entries[0];
43
+ if (entry.bytes !== bytes.length || entry.sha256 !== createHash('sha256').update(bytes).digest('hex'))
44
+ throw new Error(`Grammar ${id} digest mismatch`);
45
+ const license = path.join(directory, 'LICENSE');
46
+ if (manifest.license?.file !== 'LICENSE' || manifest.license.sha256 !== createHash('sha256').update(fs.readFileSync(license)).digest('hex'))
47
+ throw new Error('Grammar license digest mismatch');
48
+ return { wasm: file, license, bytes };
49
+ }
50
+ export function availableGrammars() {
51
+ const directory = assetDirectory();
52
+ if (!directory)
53
+ return [];
54
+ try {
55
+ return fs.readdirSync(directory)
56
+ .filter(name => name.startsWith('tree-sitter-') && name.endsWith('.wasm'))
57
+ .map(name => name.slice('tree-sitter-'.length, -'.wasm'.length))
58
+ .filter(id => { try {
59
+ return grammarPaths(id) !== null;
60
+ }
61
+ catch {
62
+ return false;
63
+ } });
64
+ }
65
+ catch {
66
+ return [];
67
+ }
68
+ }
69
+ /** Grammar ids whose WASM is not shipped; callers must fall back to text-only analysis. */
70
+ export function missingGrammars(ids) {
71
+ const present = new Set(availableGrammars());
72
+ return ids.filter(id => !present.has(id));
73
+ }
@@ -0,0 +1,24 @@
1
+ export interface StructureNode {
2
+ kind: string;
3
+ name?: string;
4
+ startLine: number;
5
+ startColumn: number;
6
+ endLine: number;
7
+ endColumn: number;
8
+ }
9
+ export interface SyntaxResult {
10
+ status: 'ok' | 'unsupported' | 'error';
11
+ language: string;
12
+ /** Present only on success; a failure reason is supplied otherwise. */
13
+ nodes?: StructureNode[];
14
+ errorCount?: number;
15
+ detail?: string;
16
+ }
17
+ /** Bare `enclosing` lookups do not need naming; queries above name definitions only. */
18
+ export declare function definitionQuery(grammar: string): string | undefined;
19
+ /** A short parse proves the grammar works before it is advertised as ready. */
20
+ export declare function verifyGrammar(grammar: string): Promise<{
21
+ ok: boolean;
22
+ detail?: string;
23
+ }>;
24
+ export declare function outline(grammar: string, source: string, limit?: number): Promise<SyntaxResult>;
@@ -0,0 +1,144 @@
1
+ import fs from 'node:fs';
2
+ import { Parser, Language, Query } from 'web-tree-sitter';
3
+ import { grammarPaths } from "./assets.js";
4
+ const loaded = new Map();
5
+ let initializing = null;
6
+ /** One WASM runtime per process; grammars are loaded lazily and kept small. */
7
+ async function runtime() {
8
+ initializing ??= Parser.init();
9
+ await initializing;
10
+ }
11
+ const DEFINITION_QUERIES = {
12
+ typescript: `(function_declaration name: (identifier) @name)
13
+ (class_declaration name: (type_identifier) @name)
14
+ (interface_declaration name: (type_identifier) @name)
15
+ (type_alias_declaration name: (type_identifier) @name)
16
+ (enum_declaration name: (identifier) @name)
17
+ (method_definition name: (property_identifier) @name)
18
+ (lexical_declaration (variable_declarator name: (identifier) @name))
19
+ (export_statement declaration: (function_declaration name: (identifier) @name))`,
20
+ python: `(function_definition name: (identifier) @name)
21
+ (class_definition name: (identifier) @name)`,
22
+ rust: `(function_item name: (identifier) @name)
23
+ (struct_item name: (type_identifier) @name)
24
+ (enum_item name: (type_identifier) @name)
25
+ (trait_item name: (type_identifier) @name)
26
+ (impl_item type: (type_identifier) @name)`,
27
+ c: `(function_definition declarator: (function_declarator declarator: (identifier) @name))
28
+ (struct_specifier name: (type_identifier) @name)`,
29
+ cpp: `(function_definition declarator: (function_declarator declarator: (_) @name))
30
+ (class_specifier name: (type_identifier) @name)
31
+ (struct_specifier name: (type_identifier) @name)
32
+ (namespace_definition name: (namespace_identifier) @name)`,
33
+ ruby: `(method name: (_) @name)
34
+ (class name: (constant) @name)
35
+ (module name: (constant) @name)`,
36
+ php: `(function_definition name: (name) @name)
37
+ (class_declaration name: (name) @name)
38
+ (method_declaration name: (name) @name)`,
39
+ swift: `(function_declaration name: (simple_identifier) @name)
40
+ (class_declaration name: (type_identifier) @name)
41
+ (protocol_declaration name: (type_identifier) @name)`,
42
+ html: `(element (start_tag (tag_name) @name))`,
43
+ css: `(rule_set (selectors) @name)`,
44
+ };
45
+ // JS/TSX share the TypeScript-family grammar names but have their own wasm files.
46
+ for (const alias of ['javascript', 'tsx']) {
47
+ DEFINITION_QUERIES[alias] = DEFINITION_QUERIES['typescript'] ?? '';
48
+ }
49
+ DEFINITION_QUERIES['javascript'] = `(function_declaration name: (identifier) @name)
50
+ (class_declaration name: (identifier) @name)
51
+ (method_definition name: (property_identifier) @name)
52
+ (lexical_declaration (variable_declarator name: (identifier) @name))`;
53
+ /** Bare `enclosing` lookups do not need naming; queries above name definitions only. */
54
+ export function definitionQuery(grammar) {
55
+ return DEFINITION_QUERIES[grammar];
56
+ }
57
+ async function load(grammar) {
58
+ const cached = loaded.get(grammar);
59
+ if (cached instanceof Error)
60
+ throw cached;
61
+ if (cached)
62
+ return cached;
63
+ try {
64
+ const paths = grammarPaths(grammar);
65
+ if (!paths)
66
+ throw new Error(`文法 ${grammar} は同梱されていません`);
67
+ await runtime();
68
+ const language = await Language.load(paths.bytes);
69
+ const parser = new Parser();
70
+ parser.setLanguage(language);
71
+ const value = { parser, language };
72
+ loaded.set(grammar, value);
73
+ return value;
74
+ }
75
+ catch (e) {
76
+ const failure = e instanceof Error ? e : new Error(String(e));
77
+ loaded.set(grammar, failure);
78
+ throw failure;
79
+ }
80
+ }
81
+ /** A short parse proves the grammar works before it is advertised as ready. */
82
+ export async function verifyGrammar(grammar) {
83
+ try {
84
+ const { parser } = await load(grammar);
85
+ const tree = parser.parse('x');
86
+ if (!tree)
87
+ return { ok: false, detail: '空の構文木が返った' };
88
+ tree.delete();
89
+ return { ok: true };
90
+ }
91
+ catch (e) {
92
+ return { ok: false, detail: e instanceof Error ? e.message : String(e) };
93
+ }
94
+ }
95
+ const MAX_STRUCTURE_NODES = 400;
96
+ export async function outline(grammar, source, limit = MAX_STRUCTURE_NODES) {
97
+ const query = definitionQuery(grammar);
98
+ if (!query)
99
+ return { status: 'unsupported', language: grammar, detail: 'この言語の構造抽出は未対応' };
100
+ let tree;
101
+ try {
102
+ const bundle = await load(grammar);
103
+ tree = bundle.parser.parse(source);
104
+ if (!tree)
105
+ return { status: 'error', language: grammar, detail: '構文木を作成できなかった' };
106
+ const matcher = new Query(bundle.language, query);
107
+ const nodes = [];
108
+ for (const capture of matcher.captures(tree.rootNode)) {
109
+ if (nodes.length >= limit)
110
+ break;
111
+ const node = capture.node;
112
+ nodes.push({
113
+ kind: node.parent?.parent?.type ?? node.parent?.type ?? node.type,
114
+ name: node.text.slice(0, 200),
115
+ startLine: node.startPosition.row + 1,
116
+ startColumn: node.startPosition.column + 1,
117
+ endLine: node.endPosition.row + 1,
118
+ endColumn: node.endPosition.column + 1,
119
+ });
120
+ }
121
+ matcher.delete();
122
+ return { status: 'ok', language: grammar, nodes, errorCount: countErrors(tree.rootNode) };
123
+ }
124
+ catch (e) {
125
+ return { status: 'error', language: grammar, detail: e instanceof Error ? e.message : String(e) };
126
+ }
127
+ finally {
128
+ tree?.delete();
129
+ }
130
+ }
131
+ function countErrors(node, budget = 5000) {
132
+ const stack = [node];
133
+ let count = 0, visited = 0;
134
+ while (stack.length && visited < budget) {
135
+ const current = stack.pop();
136
+ visited++;
137
+ if (!current.hasError)
138
+ continue;
139
+ count++;
140
+ for (let i = 0; i < current.childCount; i++)
141
+ stack.push(current.child(i));
142
+ }
143
+ return count;
144
+ }
@@ -0,0 +1,6 @@
1
+ /** Only accept a package argument from the installed official README, never shell text. */
2
+ export declare function recommendedTypescript(readme: string): string | undefined;
3
+ export declare function probeTypescript(prefix: string, signal?: AbortSignal): Promise<{
4
+ version: string;
5
+ apiSha256: string;
6
+ }>;
@@ -0,0 +1,42 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { executeBounded, privateEnvironment, sha256 } from "../lisp/runtime.js";
4
+ /** Only accept a package argument from the installed official README, never shell text. */
5
+ export function recommendedTypescript(readme) {
6
+ const candidates = [...readme.matchAll(/\bnpm install[^\r\n]*\btypescript-language-server\b[^\r\n]*\btypescript@([0-9]+(?:\.[0-9x*]+){0,2})(?=\s|$)/gm)].map(match => `typescript@${match[1]}`);
7
+ return new Set(candidates).size === 1 ? candidates[0] : undefined;
8
+ }
9
+ const probe = String.raw `
10
+ const {createRequire}=require('node:module');
11
+ const ts=createRequire(process.argv[1])(process.argv[1]);
12
+ if(typeof ts.createLanguageService!=='function'||typeof ts.ScriptSnapshot?.fromString!=='function')throw Error('Missing language service API');
13
+ const text='const answer: number = "wrong";';
14
+ const service=ts.createLanguageService({
15
+ getScriptFileNames:()=>['probe.ts'],getScriptVersion:()=> '1',
16
+ getScriptSnapshot:f=>f==='probe.ts'?ts.ScriptSnapshot.fromString(text):undefined,
17
+ getCurrentDirectory:()=>process.cwd(),getCompilationSettings:()=>({noLib:true,strict:true}),
18
+ getDefaultLibFileName:()=>'',fileExists:f=>f==='probe.ts',readFile:()=>undefined
19
+ });
20
+ try{if(!service.getSemanticDiagnostics('probe.ts').some(d=>d.code===2322))throw Error('Type mismatch diagnostic missing');}
21
+ finally{service.dispose();}
22
+ process.stdout.write('MODKH_TYPESCRIPT_API_OK');
23
+ `;
24
+ export async function probeTypescript(prefix, signal) {
25
+ const api = path.join(prefix, 'node_modules/typescript/lib/typescript.js');
26
+ const bytes = fs.readFileSync(api);
27
+ const home = path.join(prefix, '.typescript-probe');
28
+ fs.mkdirSync(home, { mode: 0o700 });
29
+ try {
30
+ const result = await executeBounded(process.execPath, ['-e', probe, api], {
31
+ cwd: home, env: privateEnvironment(home), inputDigest: sha256(bytes), timeoutMs: 10000, signal,
32
+ });
33
+ if (result.state !== 'exited' || result.exitCode !== 0 || result.stdout !== 'MODKH_TYPESCRIPT_API_OK') {
34
+ throw new Error(`TypeScript language service capability failed (${result.state}): ${result.stderr.slice(-500)}`);
35
+ }
36
+ const manifest = JSON.parse(fs.readFileSync(path.join(prefix, 'node_modules/typescript/package.json'), 'utf8'));
37
+ return { version: String(manifest.version), apiSha256: sha256(bytes) };
38
+ }
39
+ finally {
40
+ fs.rmSync(home, { recursive: true, force: true });
41
+ }
42
+ }