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,82 @@
1
+ // 行単位の最小 unified diff。外部依存を増やさないために簡易 LCS で実装する。
2
+ // 編集対象は小さいことが前提で、O(n*m) の表は実用上十分。
3
+ export function diffLines(before, after) {
4
+ const a = before.length === 0 ? [] : before.split('\n');
5
+ const b = after.length === 0 ? [] : after.split('\n');
6
+ // 末尾改行による空の最終行を揃える
7
+ if (a.length > 0 && a[a.length - 1] === '')
8
+ a.pop();
9
+ if (b.length > 0 && b[b.length - 1] === '')
10
+ b.pop();
11
+ const n = a.length;
12
+ const m = b.length;
13
+ // lcs[i][j] = a[i..] と b[j..] の LCS 長
14
+ const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
15
+ for (let i = n - 1; i >= 0; i--) {
16
+ for (let j = m - 1; j >= 0; j--) {
17
+ lcs[i][j] = a[i] === b[j]
18
+ ? lcs[i + 1][j + 1] + 1
19
+ : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
20
+ }
21
+ }
22
+ const out = [];
23
+ let i = 0;
24
+ let j = 0;
25
+ while (i < n && j < m) {
26
+ if (a[i] === b[j]) {
27
+ out.push({ kind: 'context', text: a[i] });
28
+ i++;
29
+ j++;
30
+ }
31
+ else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
32
+ out.push({ kind: 'del', text: a[i] });
33
+ i++;
34
+ }
35
+ else {
36
+ out.push({ kind: 'add', text: b[j] });
37
+ j++;
38
+ }
39
+ }
40
+ while (i < n) {
41
+ out.push({ kind: 'del', text: a[i] });
42
+ i++;
43
+ }
44
+ while (j < m) {
45
+ out.push({ kind: 'add', text: b[j] });
46
+ j++;
47
+ }
48
+ return out;
49
+ }
50
+ export function renderDiff(title, before, after) {
51
+ const lines = diffLines(before, after);
52
+ const parts = [`--- ${title}`, `+++ ${title}`];
53
+ let k = 0;
54
+ let addCount = 0;
55
+ let delCount = 0;
56
+ for (const l of lines) {
57
+ if (l.kind === 'add')
58
+ addCount++;
59
+ if (l.kind === 'del')
60
+ delCount++;
61
+ }
62
+ parts.push(`@@ -${0},+${0} @@ (${addCount} 追加, ${delCount} 削除)`);
63
+ while (k < lines.length) {
64
+ if (lines[k].kind === 'context') {
65
+ parts.push(` ${lines[k].text}`);
66
+ k++;
67
+ continue;
68
+ }
69
+ let s = k;
70
+ while (k < lines.length && lines[k].kind !== 'context')
71
+ k++;
72
+ // 変更ブロックの前後1行を文脈として出す
73
+ const start = Math.max(0, s - 1);
74
+ const end = Math.min(lines.length, k + 1);
75
+ for (let t = start; t < end; t++) {
76
+ const kind = lines[t].kind;
77
+ const prefix = kind === 'add' ? '+ ' : kind === 'del' ? '- ' : ' ';
78
+ parts.push(prefix + lines[t].text);
79
+ }
80
+ }
81
+ return parts.join('\n');
82
+ }
@@ -0,0 +1,3 @@
1
+ import { type Tool } from '../agent/types.ts';
2
+ export declare const createFileTool: Tool;
3
+ export declare const editFileTool: Tool;
@@ -0,0 +1,152 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { ToolError } from "../agent/types.js";
4
+ import { resolveInRoot, assertRealInRoot } from "./guard.js";
5
+ import { renderDiff } from "./diff.js";
6
+ import { safeAnalysis } from "./files.js";
7
+ function requireString(v, name) {
8
+ if (typeof v !== 'string') {
9
+ throw new ToolError('INVALID_ARGS', `${name} は文字列で指定する`);
10
+ }
11
+ return v;
12
+ }
13
+ /** 未作成部分も含む実際の作成先。等価な親ディレクトリの追加は対象変更にしない。 */
14
+ function creationTarget(root, abs) {
15
+ assertRealInRoot(root, abs);
16
+ let probe = abs;
17
+ for (;;) {
18
+ try {
19
+ return path.resolve(fs.realpathSync(probe), path.relative(probe, abs));
20
+ }
21
+ catch (e) {
22
+ const parent = path.dirname(probe);
23
+ if (e.code !== 'ENOENT' || parent === probe)
24
+ throw e;
25
+ probe = parent;
26
+ }
27
+ }
28
+ }
29
+ // ---------------------------------------------------------------------------
30
+ // create_file: 新規作成(既存は拒否)。承認ゲートに内容の差分を見せてから書く。
31
+ // ---------------------------------------------------------------------------
32
+ export const createFileTool = {
33
+ name: 'create_file',
34
+ description: '新しいファイルを作る(既存なら失敗)。content は全文。承認を得てから書き込む。',
35
+ parameters: {
36
+ type: 'object',
37
+ properties: {
38
+ path: { type: 'string', description: '作るファイル(ルート相対)' },
39
+ content: { type: 'string', description: '書き込む全文' },
40
+ },
41
+ required: ['path', 'content'],
42
+ },
43
+ async execute(args, ctx) {
44
+ const rel = requireString(args.path, 'path');
45
+ const content = requireString(args.content, 'content');
46
+ const abs = resolveInRoot(ctx.root, rel);
47
+ if (fs.existsSync(abs)) {
48
+ throw new ToolError('ALREADY_EXISTS', `既に存在する: ${rel}(edit_file を使う)`);
49
+ }
50
+ // 承認前は検査だけ行い、親ディレクトリも作らない。
51
+ const approvedTarget = creationTarget(ctx.root, abs);
52
+ const diff = renderDiff(rel, '', content);
53
+ const ok = await ctx.approval.approve({
54
+ kind: 'edit',
55
+ title: `新規作成 ${rel}`,
56
+ detail: diff,
57
+ // The target was resolved and proven inside the root above.
58
+ outsideWorkspace: false,
59
+ });
60
+ if (!ok)
61
+ throw new ToolError('DENIED', `承認されなかったため書き込まない: ${rel}`);
62
+ if (ctx.signal?.aborted)
63
+ throw new ToolError('NOT_EXECUTED', '中断済みのため書き込まない');
64
+ try {
65
+ if (creationTarget(ctx.root, abs) !== approvedTarget || fs.existsSync(abs)) {
66
+ throw new Error('作成先が変更されたか、既に存在する');
67
+ }
68
+ }
69
+ catch (e) {
70
+ throw new ToolError('NOT_EXECUTED', `承認後の作成先を確認できないため書き込まない: ${e.message}`);
71
+ }
72
+ const createdParent = fs.mkdirSync(path.dirname(abs), { recursive: true });
73
+ // ここからは親ディレクトリを作成済みかもしれない。予期しない失敗を未実行とは扱わない。
74
+ assertRealInRoot(ctx.root, abs);
75
+ try {
76
+ fs.writeFileSync(abs, content, { encoding: 'utf8', flag: 'wx' });
77
+ }
78
+ catch (e) {
79
+ if (e.code !== 'EEXIST')
80
+ throw e;
81
+ if (createdParent !== undefined) {
82
+ throw new ToolError('CREATE_CONFLICT', '親ディレクトリは作成したが、競合したファイルには書き込んでいない');
83
+ }
84
+ throw new ToolError('NOT_EXECUTED', '同名ファイルが作成されたため書き込んでいない');
85
+ }
86
+ const notice = ctx.analyze ? await safeAnalysis(() => ctx.analyze(abs, 'write')) : '';
87
+ return `${rel} を作成した(${Buffer.byteLength(content, 'utf8')}バイト)${notice ? `\n\n${notice}` : ''}`;
88
+ },
89
+ };
90
+ // ---------------------------------------------------------------------------
91
+ // edit_file: 一致1回の置換。見つからない・複数あるはどちらも拒否。
92
+ // 承認ゲートに差分を見せ、承認されて初めて書き込む。
93
+ // ---------------------------------------------------------------------------
94
+ export const editFileTool = {
95
+ name: 'edit_file',
96
+ description: 'old_string と一致する部分を new_string で置き換える。一致は1回だけ(0回・複数回は失敗)。差分を見せて承認後に書き込む。',
97
+ parameters: {
98
+ type: 'object',
99
+ properties: {
100
+ path: { type: 'string', description: '編集するファイル(ルート相対)' },
101
+ old_string: { type: 'string', description: '置き換える対象(一意に一致すること)' },
102
+ new_string: { type: 'string', description: '置き換え後の文字列' },
103
+ },
104
+ required: ['path', 'old_string', 'new_string'],
105
+ },
106
+ async execute(args, ctx) {
107
+ const rel = requireString(args.path, 'path');
108
+ const before = requireString(args.old_string, 'old_string');
109
+ const after = requireString(args.new_string, 'new_string');
110
+ if (before.length === 0) {
111
+ throw new ToolError('INVALID_ARGS', 'old_string は空にできない');
112
+ }
113
+ const abs = resolveInRoot(ctx.root, rel);
114
+ const approvedTarget = assertRealInRoot(ctx.root, abs);
115
+ let old;
116
+ try {
117
+ old = fs.readFileSync(abs, 'utf8');
118
+ }
119
+ catch {
120
+ throw new ToolError('NOT_FOUND', `読めないファイル: ${rel}`);
121
+ }
122
+ const at = old.indexOf(before);
123
+ if (at < 0)
124
+ throw new ToolError('MATCH_MISSING', 'old_string が見つからない');
125
+ if (old.indexOf(before, at + 1) >= 0) {
126
+ throw new ToolError('MATCH_AMBIGUOUS', 'old_string が複数箇所で一致する(一意にする)');
127
+ }
128
+ const updated = old.slice(0, at) + after + old.slice(at + before.length);
129
+ const diff = renderDiff(rel, old, updated);
130
+ const ok = await ctx.approval.approve({
131
+ kind: 'edit',
132
+ title: `編集 ${rel}`,
133
+ detail: diff,
134
+ outsideWorkspace: false,
135
+ });
136
+ if (!ok)
137
+ throw new ToolError('DENIED', `承認されなかったため書き込まない: ${rel}`);
138
+ if (ctx.signal?.aborted)
139
+ throw new ToolError('NOT_EXECUTED', '中断済みのため書き込まない');
140
+ try {
141
+ if (assertRealInRoot(ctx.root, abs) !== approvedTarget || fs.readFileSync(abs, 'utf8') !== old) {
142
+ throw new Error('承認待ちの間に対象が変更された');
143
+ }
144
+ }
145
+ catch (e) {
146
+ throw new ToolError('NOT_EXECUTED', `承認後の対象を確認できないため書き込まない: ${e.message}`);
147
+ }
148
+ fs.writeFileSync(abs, updated, { encoding: 'utf8' });
149
+ const notice = ctx.analyze ? await safeAnalysis(() => ctx.analyze(abs, 'write')) : '';
150
+ return `${rel} を編集した${notice ? `\n\n${notice}` : ''}`;
151
+ },
152
+ };
@@ -0,0 +1,6 @@
1
+ import { type Tool } from '../agent/types.ts';
2
+ export declare const listFilesTool: Tool;
3
+ export { searchFilesTool } from './search.ts';
4
+ /** Analysis is advisory: a failure is reported but never replaces the tool's own result. */
5
+ export declare function safeAnalysis(run: () => Promise<string | null>): Promise<string>;
6
+ export declare const readFileTool: Tool;
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import { ToolError } from "../agent/types.js";
3
+ import { resolveInRoot, assertRealInRoot } from "./guard.js";
4
+ // ---------------------------------------------------------------------------
5
+ // list_files: ルート相対の1ディレクトリを一覧する(浅い)。
6
+ // ---------------------------------------------------------------------------
7
+ export const listFilesTool = {
8
+ readOnly: true,
9
+ name: 'list_files',
10
+ description: 'ディレクトリ直下のエントリを一覧する。path は作業ルート相対(省略時はルート)。再帰しない。',
11
+ parameters: {
12
+ type: 'object',
13
+ properties: {
14
+ path: { type: 'string', description: '一覧するディレクトリ(ルート相対)' },
15
+ },
16
+ },
17
+ async execute(args, ctx) {
18
+ const dir = resolveInRoot(ctx.root, args.path ?? '.');
19
+ assertRealInRoot(ctx.root, dir);
20
+ let entries;
21
+ try {
22
+ entries = fs.readdirSync(dir, { withFileTypes: true });
23
+ }
24
+ catch (e) {
25
+ throw new ToolError('LIST_FAILED', `一覧できない: ${dir}: ${e.message}`);
26
+ }
27
+ entries.sort((x, y) => x.name.localeCompare(y.name));
28
+ const rows = entries.map((e) => {
29
+ const suffix = e.isDirectory() ? '/' : '';
30
+ return e.name + suffix;
31
+ });
32
+ return `作業場所: ${dir}\n${rows.length === 0 ? '(空)' : rows.join('\n')}`;
33
+ },
34
+ };
35
+ // ---------------------------------------------------------------------------
36
+ // search_files: 除外設定と出力量の上限は専用モジュールが所有する。
37
+ // ---------------------------------------------------------------------------
38
+ export { searchFilesTool } from "./search.js";
39
+ const READ_DEFAULT_LIMIT = 500;
40
+ const READ_MAX_FILE_BYTES = 2 * 1024 * 1024;
41
+ /** Analysis is advisory: a failure is reported but never replaces the tool's own result. */
42
+ export async function safeAnalysis(run) {
43
+ try {
44
+ return (await run()) ?? '';
45
+ }
46
+ catch (e) {
47
+ return `解析: 失敗 — ${e instanceof Error ? e.message : String(e)}(本文の操作は成功)`;
48
+ }
49
+ }
50
+ export const readFileTool = {
51
+ readOnly: true,
52
+ name: 'read_file',
53
+ description: 'テキストファイルを読む。offset(1開始行)と limit(既定500行)が使える。path はルート相対。',
54
+ parameters: {
55
+ type: 'object',
56
+ properties: {
57
+ path: { type: 'string', description: '読むファイル(ルート相対)' },
58
+ offset: { type: 'number', description: '開始行(1開始)' },
59
+ limit: { type: 'number', description: '読む行数(既定500)' },
60
+ },
61
+ required: ['path'],
62
+ },
63
+ async execute(args, ctx) {
64
+ const abs = resolveInRoot(ctx.root, args.path);
65
+ assertRealInRoot(ctx.root, abs);
66
+ let stat;
67
+ try {
68
+ stat = fs.statSync(abs);
69
+ }
70
+ catch {
71
+ throw new ToolError('READ_FAILED', `読めないファイル: ${args.path}`);
72
+ }
73
+ if (stat.isDirectory()) {
74
+ throw new ToolError('READ_FAILED', `ディレクトリは読めない: ${args.path}`);
75
+ }
76
+ if (stat.size > READ_MAX_FILE_BYTES) {
77
+ throw new ToolError('READ_FAILED', `大きすぎるファイル(${stat.size}バイト): ${args.path}`);
78
+ }
79
+ const offset = argPositiveInt(args.offset, 'offset') ?? 1;
80
+ const limit = argPositiveInt(args.limit, 'limit') ?? READ_DEFAULT_LIMIT;
81
+ const lines = fs.readFileSync(abs, 'utf8').split('\n');
82
+ const sliced = lines.slice(offset - 1, offset - 1 + limit);
83
+ const body = sliced.map((l, i) => `${offset + i}: ${l}`).join('\n');
84
+ const analysis = ctx.analyze ? await safeAnalysis(() => ctx.analyze(abs, 'read')) : null;
85
+ return `${args.path} (${lines.length - 1}行中 ${offset}行目から${sliced.length}行)\n${body}${analysis ? `\n\n${analysis}` : ''}`;
86
+ },
87
+ };
88
+ function argPositiveInt(v, name) {
89
+ if (v === undefined)
90
+ return undefined;
91
+ const n = Number(v);
92
+ if (!Number.isInteger(n) || n < 1) {
93
+ throw new ToolError('INVALID_ARGS', `${name} は1以上の整数`);
94
+ }
95
+ return n;
96
+ }
@@ -0,0 +1,8 @@
1
+ import type { Tool } from '../agent/types.ts';
2
+ export interface FormalSettings {
3
+ lean?: string;
4
+ java?: string;
5
+ tlaJar?: string;
6
+ timeoutMs?: number;
7
+ }
8
+ export declare function formalTools(settings: FormalSettings): Tool[];
@@ -0,0 +1,77 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ToolError } from "../agent/types.js";
4
+ import { assertRealInRoot, resolveInRoot } from "./guard.js";
5
+ import { executeBounded, privateEnvironment, sha256, temporaryDirectory } from "../lisp/runtime.js";
6
+ function snapshot(root, value, extension) {
7
+ if (typeof value !== 'string' || path.extname(value) !== extension)
8
+ throw new ToolError('INVALID_ARGS', `Explicit ${extension} input required`);
9
+ if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(path.basename(value)))
10
+ throw new ToolError('INVALID_ARGS', 'Input basename must start with a letter, not a verifier option');
11
+ const file = resolveInRoot(root, value);
12
+ const real = assertRealInRoot(root, file);
13
+ if (real !== file)
14
+ throw new ToolError('DENIED', 'Formal inputs must not be symlinks');
15
+ const expected = fs.lstatSync(file);
16
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
17
+ try {
18
+ const stat = fs.fstatSync(fd);
19
+ if (!stat.isFile() || stat.size > 256 * 1024 || stat.ino !== expected.ino || stat.dev !== expected.dev)
20
+ throw new ToolError('INVALID_ARGS', 'Invalid or changed formal input (256 KiB limit)');
21
+ const bytes = fs.readFileSync(fd);
22
+ if (bytes.length > 256 * 1024)
23
+ throw new ToolError('TOO_LARGE', 'Formal input grew during read');
24
+ return { name: path.basename(file), bytes, digest: sha256(bytes) };
25
+ }
26
+ finally {
27
+ fs.closeSync(fd);
28
+ }
29
+ }
30
+ export function formalTools(settings) {
31
+ return ['lean', 'tla'].map(verifier => ({
32
+ name: `verify_${verifier}`,
33
+ description: verifier === 'lean' ? 'Compile standalone Lean. Compiler acceptance always remains PROOF_UNVERIFIED; does not validate the intended target theorem.' : 'Check a standalone finite TLA+ model and explicit cfg with host-configured TLC. Not proof of implementation equivalence.',
34
+ parameters: { type: 'object', properties: { path: { type: 'string' }, ...(verifier === 'tla' ? { config: { type: 'string' } } : {}) }, required: verifier === 'tla' ? ['path', 'config'] : ['path'] },
35
+ async execute(args, ctx) {
36
+ const source = snapshot(ctx.root, args.path, verifier === 'lean' ? '.lean' : '.tla');
37
+ const config = verifier === 'tla' ? snapshot(ctx.root, args.config, '.cfg') : undefined;
38
+ const runtime = verifier === 'lean' ? settings.lean : settings.java;
39
+ if (!runtime || (verifier === 'tla' && !settings.tlaJar))
40
+ throw new ToolError('NOT_EXECUTED', 'Host must configure official verifier executable (and TLC jar); no model-selected binary');
41
+ // Local imports are unsupported; standard distribution imports still do not prove a theorem.
42
+ if (verifier === 'lean' && [...source.bytes.toString('utf8').matchAll(/^\s*import\s+([^\r\n]+)/gm)].some(m => !m[1].split(/\s+/).every(name => /^(Init|Lean|Std)(\.[A-Za-z0-9_]+)*$/.test(name))))
43
+ throw new ToolError('UNSUPPORTED', 'Project imports require a reviewed dependency closure; standalone wrapper only');
44
+ const hashes = { source: source.digest, ...(config ? { config: config.digest } : {}) };
45
+ if (!await ctx.approval.approve({ kind: 'command', title: `MoDKH ${verifier} verification`, detail: `${runtime}\n${JSON.stringify(hashes)}\nTrusted executable inputs: metaprograms may execute OS code. Temporary directory is NOT a sandbox.`, signal: ctx.signal }))
46
+ throw new ToolError('DENIED', 'Verification not approved');
47
+ if (ctx.signal?.aborted)
48
+ throw new ToolError('NOT_EXECUTED', 'Verification aborted before launch');
49
+ const dir = temporaryDirectory('modkh-formal-');
50
+ let settled = true;
51
+ try {
52
+ fs.writeFileSync(path.join(dir, source.name), source.bytes, { flag: 'wx', mode: 0o600 });
53
+ if (config)
54
+ fs.writeFileSync(path.join(dir, config.name), config.bytes, { flag: 'wx', mode: 0o600 });
55
+ const argv = verifier === 'lean' ? ['-DwarningAsError=true', source.name]
56
+ : ['-Xmx512m', '-cp', path.resolve(settings.tlaJar), 'tlc2.TLC', '-workers', '1', '-config', config.name, source.name];
57
+ const receipt = await executeBounded(runtime, argv, { cwd: dir, env: privateEnvironment(dir), inputDigest: sha256(JSON.stringify(hashes)),
58
+ timeoutMs: Math.min(settings.timeoutMs ?? 30000, 30000), maxOutputBytes: 256 * 1024, signal: ctx.signal });
59
+ settled = receipt.cleanup === 'settled';
60
+ const exited = receipt.state === 'exited';
61
+ const accepted = exited && receipt.exitCode === 0;
62
+ const complete = accepted && /Model checking completed\. No error has been found\./.test(receipt.stdout) && /\d+ distinct states found/.test(receipt.stdout);
63
+ const status = verifier === 'lean' && accepted ? 'accepted' : verifier === 'tla' && complete ? 'passed'
64
+ : exited && receipt.exitCode !== 0 ? 'failed' : receipt.state === 'not-started' ? 'not-executed' : 'unverified';
65
+ const evidence = { verifier, status, hashes, receipt,
66
+ ...(verifier === 'lean' ? { proofStatus: 'unverified', code: 'PROOF_UNVERIFIED', reason: 'Compiler acceptance is not target-theorem validation' }
67
+ : { scope: 'Only this finite model/config; not implementation equivalence. Constants, constraints, fairness and deadlock behavior are defined by these exact hashed inputs.', config: config.bytes.toString('utf8').slice(0, 16384) }),
68
+ };
69
+ return { status: receipt.cleanup === 'unknown' ? 'unknown' : verifier === 'tla' && complete ? 'ok' : 'error', output: JSON.stringify(evidence) };
70
+ }
71
+ finally {
72
+ if (settled)
73
+ fs.rmSync(dir, { recursive: true, force: true });
74
+ }
75
+ },
76
+ }));
77
+ }
@@ -0,0 +1,7 @@
1
+ /** 作業ルート内の絶対パスへ解決する。ルート外や空は ToolError。 */
2
+ export declare function resolveInRoot(root: string, rel: unknown): string;
3
+ /**
4
+ * symlink による脱出を防ぐ。パス自身(なければ最も近い存在する親)を実パスで確認する。
5
+ * ファイル・ディレクトリの両方に使う。返り値は実パス。
6
+ */
7
+ export declare function assertRealInRoot(root: string, abs: string): string;
@@ -0,0 +1,48 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { ToolError } from "../agent/types.js";
4
+ /** 作業ルート内の絶対パスへ解決する。ルート外や空は ToolError。 */
5
+ export function resolveInRoot(root, rel) {
6
+ if (typeof rel !== 'string' || rel.length === 0) {
7
+ throw new ToolError('INVALID_PATH', 'path は空でない文字列で指定する');
8
+ }
9
+ const abs = path.resolve(root, rel);
10
+ const inside = path.relative(root, abs);
11
+ if (inside.startsWith('..') || path.isAbsolute(inside)) {
12
+ throw new ToolError('OUT_OF_ROOT', `作業ルート外への参照は拒否する: ${rel}`);
13
+ }
14
+ return abs;
15
+ }
16
+ /**
17
+ * symlink による脱出を防ぐ。パス自身(なければ最も近い存在する親)を実パスで確認する。
18
+ * ファイル・ディレクトリの両方に使う。返り値は実パス。
19
+ */
20
+ export function assertRealInRoot(root, abs) {
21
+ let probe = abs;
22
+ for (;;) {
23
+ try {
24
+ const real = fs.realpathSync(probe);
25
+ assertInsideRealRoot(root, real);
26
+ return real;
27
+ }
28
+ catch (e) {
29
+ if (e.code === 'ENOENT') {
30
+ const parent = path.dirname(probe);
31
+ if (parent === probe) {
32
+ throw new ToolError('OUT_OF_ROOT', `ルートが解決できない: ${abs}`);
33
+ }
34
+ probe = parent;
35
+ continue;
36
+ }
37
+ throw e;
38
+ }
39
+ }
40
+ }
41
+ function assertInsideRealRoot(root, realAbs) {
42
+ const realRoot = fs.realpathSync(root);
43
+ const rel = path.relative(realRoot, realAbs);
44
+ // rel === '' はルート自身なので内側として扱う。ルート外だけを拒否する。
45
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
46
+ throw new ToolError('OUT_OF_ROOT', `シンボリックリンク経由のルート外参照は拒否する: ${realAbs}`);
47
+ }
48
+ }
@@ -0,0 +1,19 @@
1
+ import { type Tool } from '../agent/types.ts';
2
+ import { describeShellResult, type ShellName } from './shell-process.ts';
3
+ import type { JobRegistry } from './jobs.ts';
4
+ /** Shared with the foreground tool so both paths resolve and approve identically. */
5
+ export declare function prepareCommand(args: Record<string, unknown>, root: string): {
6
+ command: string;
7
+ cwd: string;
8
+ cwdRel: string;
9
+ shell: ShellName;
10
+ description?: string;
11
+ };
12
+ /**
13
+ * job_output / job_list / job_kill.
14
+ *
15
+ * Reads are cursor-based: a stream job returns only what is new since the previous read, so
16
+ * repeated polling during a long build does not re-send the whole log into the context.
17
+ */
18
+ export declare function jobTools(jobs: JobRegistry): Tool[];
19
+ export { describeShellResult };
@@ -0,0 +1,148 @@
1
+ import { ToolError } from "../agent/types.js";
2
+ import { resolveInRoot, assertRealInRoot } from "./guard.js";
3
+ import { describeShellResult, SHELLS } from "./shell-process.js";
4
+ function requireString(v, name) {
5
+ if (typeof v !== 'string' || v.length === 0) {
6
+ throw new ToolError('INVALID_ARGS', `${name} は空でない文字列で指定する`);
7
+ }
8
+ return v;
9
+ }
10
+ function optionalString(v, name, max) {
11
+ if (v === undefined)
12
+ return undefined;
13
+ if (typeof v !== 'string' || v.length > max)
14
+ throw new ToolError('INVALID_ARGS', `${name} は${max}文字以内の文字列で指定する`);
15
+ return v;
16
+ }
17
+ function shellArg(v) {
18
+ const value = optionalString(v, 'shell', 8);
19
+ if (value === undefined)
20
+ return 'sh';
21
+ if (!SHELLS.includes(value)) {
22
+ throw new ToolError('INVALID_ARGS', `shell は ${SHELLS.join(' | ')} のいずれか`);
23
+ }
24
+ return value;
25
+ }
26
+ /** Shared with the foreground tool so both paths resolve and approve identically. */
27
+ export function prepareCommand(args, root) {
28
+ const command = requireString(args.command, 'command');
29
+ const cwdRel = args.cwd === undefined ? '.' : requireString(args.cwd, 'cwd');
30
+ const shell = shellArg(args.shell);
31
+ const description = optionalString(args.description, 'description', 200);
32
+ const cwd = resolveInRoot(root, cwdRel);
33
+ assertRealInRoot(root, cwd);
34
+ return { command, cwd, cwdRel, shell, ...(description === undefined ? {} : { description }) };
35
+ }
36
+ function statusLine(view) {
37
+ const parts = [`[status: ${view.status}]`];
38
+ if (view.exitCode !== undefined && view.exitCode !== null)
39
+ parts.push(`[exit code: ${view.exitCode}]`);
40
+ if (view.detail)
41
+ parts.push(`[${view.detail}]`);
42
+ const elapsed = Math.round(((view.finishedAt ?? Date.now()) - view.startedAt) / 1000);
43
+ parts.push(`${elapsed}秒`);
44
+ return parts.join(' ');
45
+ }
46
+ /**
47
+ * job_output / job_list / job_kill.
48
+ *
49
+ * Reads are cursor-based: a stream job returns only what is new since the previous read, so
50
+ * repeated polling during a long build does not re-send the whole log into the context.
51
+ */
52
+ export function jobTools(jobs) {
53
+ const output = {
54
+ name: 'job_output',
55
+ readOnly: true,
56
+ description: 'バックグラウンドジョブの出力を読む。前回の読み取り以降に増えた分だけを返す。'
57
+ + 'wait を指定すると、新しい出力が出るかジョブが終わるまで待つ。'
58
+ + '応答の末尾に [status: ...] が付く。status が running ならまだ実行中。',
59
+ parameters: {
60
+ type: 'object',
61
+ properties: {
62
+ job_id: { type: 'string', description: 'run_command が返した job_id' },
63
+ wait: { type: 'boolean', description: '新しい出力か終了を待つ(既定 false)' },
64
+ timeout_ms: { type: 'number', description: 'wait の上限(ミリ秒、既定30000、上限300000)' },
65
+ },
66
+ required: ['job_id'],
67
+ },
68
+ async execute(args, ctx) {
69
+ const id = requireString(args.job_id, 'job_id');
70
+ const wait = args.wait === true;
71
+ const timeoutRaw = args.timeout_ms;
72
+ const timeout = timeoutRaw === undefined ? 30_000
73
+ : typeof timeoutRaw === 'number' && Number.isSafeInteger(timeoutRaw) && timeoutRaw > 0 && timeoutRaw <= 300_000 ? timeoutRaw
74
+ : null;
75
+ if (timeout === null)
76
+ throw new ToolError('INVALID_ARGS', 'timeout_ms は1〜300000の整数で指定する');
77
+ if (wait)
78
+ await jobs.wait(id, timeout, ctx.signal);
79
+ const read = jobs.read(id);
80
+ const parts = [statusLine(read.job)];
81
+ if (read.dropped > 0)
82
+ parts.push(`[前回の読み取り位置より古い出力 ${read.dropped} 文字は保持上限を超えて破棄された]`);
83
+ if (read.stdout)
84
+ parts.push(`--- stdout ---\n${read.stdout}`.trimEnd());
85
+ if (read.stderr)
86
+ parts.push(`--- stderr ---\n${read.stderr}`.trimEnd());
87
+ if (!read.stdout && !read.stderr)
88
+ parts.push(wait ? '(新しい出力なし)' : '(まだ出力なし)');
89
+ return parts.join('\n');
90
+ },
91
+ };
92
+ const list = {
93
+ name: 'job_list',
94
+ readOnly: true,
95
+ description: 'バックグラウンドジョブの一覧と状態を返す。',
96
+ parameters: { type: 'object', properties: {} },
97
+ async execute() {
98
+ const views = jobs.list();
99
+ if (views.length === 0)
100
+ return '(実行中のジョブはない)';
101
+ return views.map(view => {
102
+ const head = `${view.id} ${view.kind} ${view.status} ${view.label}`;
103
+ return view.detail ? `${head} [${view.detail}]` : head;
104
+ }).join('\n');
105
+ },
106
+ };
107
+ const kill = {
108
+ name: 'job_kill',
109
+ description: 'バックグラウンドジョブを停止する。停止の確認まで待ってから結果を返す。',
110
+ parameters: {
111
+ type: 'object',
112
+ properties: {
113
+ job_id: { type: 'string', description: '停止するジョブ' },
114
+ reason: { type: 'string', description: '停止する理由(記録用)' },
115
+ },
116
+ required: ['job_id'],
117
+ },
118
+ async execute(args) {
119
+ const id = requireString(args.job_id, 'job_id');
120
+ const reason = optionalString(args.reason, 'reason', 200);
121
+ const started = await jobs.kill(id, reason);
122
+ // Report the settled state, not just the request: a kill that silently failed is worse
123
+ // than no kill, because the human believes the work stopped.
124
+ const deadline = Date.now() + 5000;
125
+ for (;;) {
126
+ const view = jobs.get(id);
127
+ if (!view)
128
+ throw new ToolError('NOT_EXECUTED', `不明なジョブ: ${id}`);
129
+ if (view.status !== 'running' && view.status !== 'stopping') {
130
+ const read = jobs.read(id);
131
+ const parts = [statusLine(view)];
132
+ if (read.stdout)
133
+ parts.push(`--- stdout ---\n${read.stdout}`.trimEnd());
134
+ if (read.stderr)
135
+ parts.push(`--- stderr ---\n${read.stderr}`.trimEnd());
136
+ return parts.join('\n');
137
+ }
138
+ if (Date.now() > deadline) {
139
+ throw new ToolError('ABORTED', `停止を要求したが、確認できないまま時間切れ: ${id}(status=${view.status})`);
140
+ }
141
+ await jobs.wait(id, 100);
142
+ }
143
+ void started;
144
+ },
145
+ };
146
+ return [output, list, kill];
147
+ }
148
+ export { describeShellResult };