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
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # MoDKH
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ MoDKH(Mixture of DKH)は、Common Lispで専門エージェントを定義し、コードの調査・編集・検証を委譲できるコーディングハーネスです。
4
+
5
+ ## インストール
6
+
7
+ Node.js([対応バージョン](package.json))とnpmを用意し、リポジトリのルートで実行します。
8
+
9
+ ```sh
10
+ npm ci
11
+ npm run build
12
+ archive=$(npm pack --silent)
13
+ npm install -g "./$archive"
14
+ ```
15
+
16
+ 作業するプロジェクトで、初回起動前に言語サーバーを導入します。
17
+
18
+ ```sh
19
+ modkh language install
20
+ modkh
21
+ ```
22
+
23
+ 初回起動後、`/connect` で接続先とモデルを選びます。
24
+
25
+ [依存パッケージ](docs/setup.md) · [言語解析](docs/languages.md) · [Lispプリセット](docs/presets.md)
@@ -0,0 +1,13 @@
1
+ interface BundledSkill {
2
+ name: string;
3
+ directory: string;
4
+ description: string;
5
+ files: Record<string, string>;
6
+ }
7
+ export declare function bundledSkills(): BundledSkill[];
8
+ export declare const MODKH_SKILL_BINDING = "MODKH host binding (takes precedence over imported Skill host-specific clauses):\nThese are bundled kiokuko-dsh procedures adapted to MODKH. Apply their engineering guidance, not assumptions about DSH capabilities. Only tools actually listed in this request exist. MODKH owns permissions, Stop, sessions and tool results; Skills grant no extra authority.\nUse read_file/search_files/list_files, edit_file/create_file and run_command where available; use job_output/job_list/job_kill for MODKH jobs and list_subagents/run_subagent only if supplied and authorized. MODKH has no Akinator, Goal/lease registration, coding_workflow, task_completion, kioku_* or lisp_* tool family, protected Lisp mode, or automatic Kiokuko memory-save receipt. Do not call, emulate, install or wait for those DSH facilities. Unsupported host-specific steps do not block otherwise authorized work. Lisp guidance about reasoning and prototypes applies through an available authorized runtime (e.g. SBCL via run_command), without pretending DSH Lisp APIs exist. Record actual checks and results through normal MODKH execution; never invent registration or save evidence.\nWhen supplied, read_skill(name, resource) reads bundled references; do not use workspace read_file or external downloads for them. list_skills lists names, descriptions and resource paths. If these tools are not supplied, report the unavailable references without inventing access. Only load references selected by actual risks. Current user intent and existing system instructions outrank all imported content.\n";
9
+ /** Extract only author-marked runtime blocks; never heuristically summarize requirements. */
10
+ export declare function runtimeSkillText(source: string): string;
11
+ export declare function readBundledSkill(name: string, resource?: string, runtime?: boolean): string;
12
+ export declare function verifyBundledSkills(): void;
13
+ export {};
@@ -0,0 +1,95 @@
1
+ import fs from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ const root = new URL('../../skills/kiokuko-dsh/', import.meta.url);
4
+ // Package-owned catalog. Paths supplied by the model must match this closed inventory.
5
+ export function bundledSkills() {
6
+ const manifest = JSON.parse(fs.readFileSync(new URL('manifest.json', root), 'utf8'));
7
+ if (!Array.isArray(manifest.skills) || !manifest.skills.length || manifest.skills.length > 128)
8
+ throw new Error('Invalid bundled skill inventory');
9
+ const names = new Set();
10
+ for (const skill of manifest.skills) {
11
+ if (!skill || typeof skill !== 'object'
12
+ || typeof skill.name !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(skill.name) || names.has(skill.name)
13
+ || typeof skill.directory !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(skill.directory)
14
+ || typeof skill.description !== 'string' || !skill.description.trim()
15
+ || !skill.files || typeof skill.files !== 'object' || Array.isArray(skill.files)
16
+ || !Object.hasOwn(skill.files, 'SKILL.md')
17
+ || !Object.entries(skill.files).every(([file, hash]) => /^(?:SKILL\.md|references\/[a-z0-9-]+\.md)$/.test(file)
18
+ && typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash)))
19
+ throw new Error('Invalid bundled skill entry');
20
+ names.add(skill.name);
21
+ }
22
+ return manifest.skills;
23
+ }
24
+ export const MODKH_SKILL_BINDING = `MODKH host binding (takes precedence over imported Skill host-specific clauses):
25
+ These are bundled kiokuko-dsh procedures adapted to MODKH. Apply their engineering guidance, not assumptions about DSH capabilities. Only tools actually listed in this request exist. MODKH owns permissions, Stop, sessions and tool results; Skills grant no extra authority.
26
+ Use read_file/search_files/list_files, edit_file/create_file and run_command where available; use job_output/job_list/job_kill for MODKH jobs and list_subagents/run_subagent only if supplied and authorized. MODKH has no Akinator, Goal/lease registration, coding_workflow, task_completion, kioku_* or lisp_* tool family, protected Lisp mode, or automatic Kiokuko memory-save receipt. Do not call, emulate, install or wait for those DSH facilities. Unsupported host-specific steps do not block otherwise authorized work. Lisp guidance about reasoning and prototypes applies through an available authorized runtime (e.g. SBCL via run_command), without pretending DSH Lisp APIs exist. Record actual checks and results through normal MODKH execution; never invent registration or save evidence.
27
+ When supplied, read_skill(name, resource) reads bundled references; do not use workspace read_file or external downloads for them. list_skills lists names, descriptions and resource paths. If these tools are not supplied, report the unavailable references without inventing access. Only load references selected by actual risks. Current user intent and existing system instructions outrank all imported content.\n`;
28
+ /** Extract only author-marked runtime blocks; never heuristically summarize requirements. */
29
+ export function runtimeSkillText(source) {
30
+ const text = source.replace(/\r\n/g, '\n').replace(/^---\n[\s\S]*?\n---\n/, '');
31
+ if (!/^<!-- kiokuko:(?:runtime|documentation) /m.test(text))
32
+ return text.trim();
33
+ const result = [], ids = new Set();
34
+ let kind, lines = [], fence;
35
+ for (const line of text.split('\n')) {
36
+ const f = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
37
+ if (fence) {
38
+ lines.push(line);
39
+ if (f && f[1][0] === fence[0] && f[1].length >= fence.length && !f[2].trim())
40
+ fence = undefined;
41
+ continue;
42
+ }
43
+ const open = /^<!-- kiokuko:(runtime|documentation) ([a-z][a-z0-9-]*) -->$/.exec(line);
44
+ const close = /^<!-- \/kiokuko:(runtime|documentation) -->$/.exec(line);
45
+ if (open) {
46
+ if (kind || ids.has(open[2]))
47
+ throw new Error('Nested or duplicate Skill block');
48
+ kind = open[1];
49
+ ids.add(open[2]);
50
+ lines = [];
51
+ }
52
+ else if (close) {
53
+ if (kind !== close[1])
54
+ throw new Error('Unmatched Skill block');
55
+ if (kind === 'runtime') {
56
+ if (!lines.join('\n').trim())
57
+ throw new Error('Empty runtime block');
58
+ result.push(lines.join('\n'));
59
+ }
60
+ kind = undefined;
61
+ }
62
+ else if (/<!--\s*\/?kiokuko:/.test(line))
63
+ throw new Error('Invalid Skill marker');
64
+ else if (kind) {
65
+ lines.push(line);
66
+ if (f)
67
+ fence = f[1];
68
+ }
69
+ else if (line.trim() && !/^<!-- KIOKUKO MANAGED STANDARD SKILL: [a-z-]+ -->$/.test(line))
70
+ throw new Error('Unclassified Skill text');
71
+ }
72
+ if (kind || fence || !result.length)
73
+ throw new Error('Incomplete Skill blocks');
74
+ return result.join('\n\n');
75
+ }
76
+ export function readBundledSkill(name, resource = 'SKILL.md', runtime = true) {
77
+ const skill = bundledSkills().find(skill => skill.name === name);
78
+ if (!skill || !Object.hasOwn(skill.files, resource))
79
+ throw new Error('Unknown bundled Skill or resource');
80
+ const bytes = fs.readFileSync(new URL(`${skill.directory}/${resource}`, root));
81
+ if (bytes.length > 256 * 1024 || createHash('sha256').update(bytes).digest('hex') !== skill.files[resource])
82
+ throw new Error('Bundled Skill integrity mismatch');
83
+ const source = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
84
+ return runtime ? runtimeSkillText(source) : source;
85
+ }
86
+ export function verifyBundledSkills() {
87
+ const names = new Set();
88
+ for (const skill of bundledSkills()) {
89
+ if (names.has(skill.name))
90
+ throw new Error('Duplicate Skill name');
91
+ names.add(skill.name);
92
+ for (const resource of Object.keys(skill.files))
93
+ readBundledSkill(skill.name, resource);
94
+ }
95
+ }
@@ -0,0 +1,10 @@
1
+ export interface ImageAttachment {
2
+ mediaType: 'image/png';
3
+ data: string;
4
+ }
5
+ export declare const MAX_IMAGE_BYTES: number;
6
+ export declare const MAX_IMAGES = 4;
7
+ /** Clipboard and persisted JSON are data boundaries; never treat image text as a path or URL. */
8
+ export declare function parseImage(value: unknown): ImageAttachment;
9
+ export declare function parseImages(value: unknown): ImageAttachment[];
10
+ export declare function imageDataUrl(image: ImageAttachment): string;
@@ -0,0 +1,33 @@
1
+ export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
2
+ export const MAX_IMAGES = 4;
3
+ /** Clipboard and persisted JSON are data boundaries; never treat image text as a path or URL. */
4
+ export function parseImage(value) {
5
+ if (!value || typeof value !== 'object')
6
+ throw new Error('画像データが不正です');
7
+ const image = value;
8
+ if (image.mediaType !== 'image/png' || typeof image.data !== 'string'
9
+ || image.data.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4
10
+ || image.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(image.data)) {
11
+ throw new Error('画像はPNG形式・1枚5 MiB以内で指定してください');
12
+ }
13
+ const bytes = Buffer.from(image.data, 'base64');
14
+ if (bytes.length > MAX_IMAGE_BYTES || bytes.length < 33 || bytes.toString('base64') !== image.data
15
+ || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
16
+ || bytes.toString('ascii', 12, 16) !== 'IHDR')
17
+ throw new Error('PNG画像データが不正です');
18
+ const width = bytes.readUInt32BE(16), height = bytes.readUInt32BE(20);
19
+ if (!width || !height || width * height > 40_000_000)
20
+ throw new Error('画像は4,000万画素以内にしてください');
21
+ return { mediaType: 'image/png', data: image.data };
22
+ }
23
+ export function parseImages(value) {
24
+ if (value === undefined)
25
+ return [];
26
+ if (!Array.isArray(value) || value.length > MAX_IMAGES)
27
+ throw new Error(`添付画像は最大${MAX_IMAGES}枚です`);
28
+ return value.map(parseImage);
29
+ }
30
+ export function imageDataUrl(image) {
31
+ const checked = parseImage(image);
32
+ return `data:${checked.mediaType};base64,${checked.data}`;
33
+ }
@@ -0,0 +1,56 @@
1
+ import type { AgentMessage, Model, ToolCall, ToolResult } from './types.ts';
2
+ import { ToolRegistry } from '../tools/registry.ts';
3
+ import { type SkillContext } from './skills.ts';
4
+ export interface LoopHooks {
5
+ /** Selected guidance and byte size, not a provider token/cost measurement. */
6
+ onSkillContext?(context: SkillContext): void;
7
+ /** Input passed to the adapter, not proof of provider receipt or memory application. */
8
+ onModelRequest?(): void;
9
+ onModelActivity?(stage: 'reasoning' | 'tool-input'): void;
10
+ /** Provider-reported reasoning text, for display only; it never enters the transcript messages. */
11
+ onReasoning?(delta: string): void;
12
+ /** Provider-reported token usage for one completed step; never an estimate. */
13
+ onUsage?(usage: {
14
+ input?: number;
15
+ output?: number;
16
+ cacheRead?: number;
17
+ cacheWrite?: number;
18
+ }): void;
19
+ onText?(delta: string): void;
20
+ onToolCall?(call: ToolCall): void;
21
+ onToolResult?(r: ToolResult): void;
22
+ }
23
+ export interface AgentLoopOptions {
24
+ model: Model;
25
+ registry: ToolRegistry;
26
+ root: string;
27
+ system?: string;
28
+ /** Embedders can disable automatic purpose-specific guidance. */
29
+ skills?: boolean;
30
+ /** このターンでの推論レベル(/reasoning で指定)。省略はプロバイダーの初期値。 */
31
+ reasoning?: import('./types.ts').ReasoningLevel;
32
+ signal: AbortSignal;
33
+ approval: import('./types.ts').ApprovalGate;
34
+ hooks?: LoopHooks;
35
+ maxTurns?: number;
36
+ /** Persist newly appended messages synchronously; failure prevents further effects. */
37
+ checkpoint?(): void;
38
+ /** Optional post-effect analysis; its failure never changes the tool result or replays an effect. */
39
+ analyze?(file: string, kind: 'read' | 'write'): Promise<string | null>;
40
+ /** Background-job registry owned by the caller; absent means foreground execution only. */
41
+ jobs?: import('../tools/jobs.ts').JobRegistry;
42
+ }
43
+ /** complete means response finished, not verified achievement of the user's goal. */
44
+ export type TurnOutcome = 'complete' | 'interrupted' | 'error' | 'turn-limit';
45
+ export interface TurnResult {
46
+ outcome: TurnOutcome;
47
+ errorMessage?: string;
48
+ }
49
+ /**
50
+ * Safety valve, not a work budget. Real tasks legitimately need hundreds of tool round trips,
51
+ * so the default is high enough that ordinary work never reaches it; the cap exists only to stop
52
+ * a model that loops forever. Reaching it preserves the session and can be continued.
53
+ */
54
+ export declare const DEFAULT_MAX_TURNS = 500;
55
+ /** Preserve partial evidence, journal before effects, never replay uncertain calls. */
56
+ export declare function runAgentLoop(messages: AgentMessage[], opts: AgentLoopOptions): Promise<TurnResult>;
@@ -0,0 +1,155 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { ToolRegistry } from "../tools/registry.js";
3
+ import { prepareSkillContext } from "./skills.js";
4
+ /**
5
+ * Safety valve, not a work budget. Real tasks legitimately need hundreds of tool round trips,
6
+ * so the default is high enough that ordinary work never reaches it; the cap exists only to stop
7
+ * a model that loops forever. Reaching it preserves the session and can be continued.
8
+ */
9
+ export const DEFAULT_MAX_TURNS = 500;
10
+ /** Call IDs belong to this conversation, not a global registry or another repository. */
11
+ function previousCalls(messages) {
12
+ const ledger = new Map();
13
+ for (const message of messages) {
14
+ if (message.role === 'assistant') {
15
+ for (const call of message.toolCalls ?? []) {
16
+ if (!ledger.has(call.id))
17
+ ledger.set(call.id, { call });
18
+ }
19
+ }
20
+ else if (message.role === 'tool') {
21
+ for (const result of message.results) {
22
+ const entry = ledger.get(result.callId);
23
+ if (entry && !entry.result)
24
+ entry.result = result;
25
+ }
26
+ }
27
+ }
28
+ return ledger;
29
+ }
30
+ /** Preserve partial evidence, journal before effects, never replay uncertain calls. */
31
+ export async function runAgentLoop(messages, opts) {
32
+ const maxTurns = opts.maxTurns ?? DEFAULT_MAX_TURNS;
33
+ const toolSpecs = opts.registry.specs();
34
+ const ledger = previousCalls(messages);
35
+ if (opts.signal.aborted)
36
+ return { outcome: 'interrupted' };
37
+ const task = messages.findLast(message => message.role === 'user');
38
+ const skills = opts.skills === false ? undefined : prepareSkillContext(task?.content ?? '', opts.root);
39
+ if (skills)
40
+ opts.hooks?.onSkillContext?.(skills);
41
+ const system = skills?.text ? (opts.system ?? '') + skills.text : opts.system;
42
+ const append = (message) => {
43
+ messages.push(message);
44
+ opts.checkpoint?.();
45
+ };
46
+ for (let turn = 0; turn < maxTurns; turn++) {
47
+ if (opts.signal.aborted)
48
+ return { outcome: 'interrupted' };
49
+ // A background job that settled since the last step is input the model has not seen.
50
+ // Injecting it as a user turn keeps the notification inside the normal message contract.
51
+ const notices = opts.jobs?.takeNotices() ?? [];
52
+ if (notices.length > 0)
53
+ append({ role: 'user', content: `(バックグラウンドジョブの完了通知)\n${notices.join('\n\n')}` });
54
+ let text = '';
55
+ const calls = [];
56
+ let stopReason;
57
+ let errorMessage;
58
+ try {
59
+ opts.hooks?.onModelRequest?.();
60
+ for await (const ev of opts.model.stream({
61
+ messages, tools: toolSpecs, system,
62
+ ...(opts.reasoning ? { reasoning: opts.reasoning } : {}),
63
+ }, opts.signal)) {
64
+ if (opts.signal.aborted)
65
+ break;
66
+ if (ev.type === 'usage') {
67
+ opts.hooks?.onUsage?.(ev);
68
+ }
69
+ else if (ev.type === 'activity') {
70
+ opts.hooks?.onModelActivity?.(ev.stage);
71
+ }
72
+ else if (ev.type === 'text-delta') {
73
+ text += ev.text;
74
+ opts.hooks?.onText?.(ev.text);
75
+ }
76
+ else if (ev.type === 'reasoning-delta') {
77
+ opts.hooks?.onReasoning?.(ev.text);
78
+ }
79
+ else if (ev.type === 'tool-call') {
80
+ calls.push(ev.call);
81
+ opts.hooks?.onToolCall?.(ev.call);
82
+ }
83
+ else {
84
+ stopReason = ev.stopReason;
85
+ errorMessage = ev.errorMessage;
86
+ break;
87
+ }
88
+ }
89
+ }
90
+ catch (e) {
91
+ stopReason = 'error';
92
+ errorMessage = e instanceof Error ? e.message : String(e);
93
+ }
94
+ append({ role: 'assistant', content: text, ...(calls.length ? { toolCalls: calls } : {}) });
95
+ const interrupted = opts.signal.aborted || stopReason === 'aborted';
96
+ if (interrupted || stopReason === 'error' || stopReason === undefined) {
97
+ if (calls.length)
98
+ append({ role: 'tool', results: calls.map(call => ({
99
+ callId: call.id, name: call.name, status: 'not-executed',
100
+ output: '応答が中断・失敗したため実行していない',
101
+ })) });
102
+ return interrupted ? { outcome: 'interrupted' }
103
+ : { outcome: 'error', errorMessage: errorMessage ?? 'モデル応答が終了イベントなしで切れた' };
104
+ }
105
+ if (calls.length === 0) {
106
+ // A job that settled while this answer was streaming still owes the model a report.
107
+ // Yield one more step instead of closing the turn on an unread completion.
108
+ const pending = opts.jobs?.takeNotices() ?? [];
109
+ if (pending.length > 0) {
110
+ append({ role: 'user', content: `(バックグラウンドジョブの完了通知)\n${pending.join('\n\n')}` });
111
+ continue;
112
+ }
113
+ return stopReason === 'stop' ? { outcome: 'complete' }
114
+ : { outcome: 'error', errorMessage: 'ツール終了イベントに呼び出しがない' };
115
+ }
116
+ let uncertain = false;
117
+ for (const call of calls) {
118
+ let result;
119
+ const prior = ledger.get(call.id);
120
+ const unresolved = opts.registry.get(call.name)?.readOnly ? undefined : [...ledger.values()].find(entry => (!entry.result || entry.result.status === 'unknown') && opts.registry.sameOperation(entry.call, call, {
121
+ root: opts.root, approval: opts.approval, signal: opts.signal,
122
+ }));
123
+ if (opts.signal.aborted) {
124
+ result = { callId: call.id, name: call.name, status: 'not-executed', output: '中断済みのため実行していない' };
125
+ }
126
+ else if (prior) {
127
+ result = !isDeepStrictEqual(prior.call, call)
128
+ ? { callId: call.id, name: call.name, status: 'error', output: '[CALL_ID_CONFLICT] 同じIDで実行内容が異なる' }
129
+ : prior.result ?? { callId: call.id, name: call.name, status: 'unknown', output: '前回の要求に結果がない。再実行せず状態を確認する' };
130
+ }
131
+ else if (uncertain) {
132
+ result = { callId: call.id, name: call.name, status: 'not-executed', output: '先行処理が結果不明のため実行していない' };
133
+ }
134
+ else if (unresolved) {
135
+ result = { callId: call.id, name: call.name, status: 'unknown',
136
+ output: `前回要求(${unresolved.call.id})が結果不明で、同一操作または別操作と確認できない。新しいIDでも再送せず状態を確認する` };
137
+ }
138
+ else {
139
+ ledger.set(call.id, { call });
140
+ result = await opts.registry.executeOne(call, {
141
+ root: opts.root, approval: opts.approval, signal: opts.signal,
142
+ ...(opts.analyze ? { analyze: opts.analyze } : {}),
143
+ ...(opts.jobs ? { jobs: opts.jobs } : {}),
144
+ });
145
+ ledger.set(call.id, { call, result });
146
+ }
147
+ append({ role: 'tool', results: [result] });
148
+ opts.hooks?.onToolResult?.(result);
149
+ uncertain ||= result.status === 'unknown';
150
+ }
151
+ if (opts.signal.aborted || uncertain)
152
+ return { outcome: 'interrupted' };
153
+ }
154
+ return { outcome: 'turn-limit', errorMessage: `ツール往復が上限(${maxTurns}回)に達した。ここまでの実行と結果は保存済み` };
155
+ }
@@ -0,0 +1,20 @@
1
+ export interface TaskSkill {
2
+ name: string;
3
+ description: string;
4
+ keywords: string[];
5
+ /** Workspace-relative file, read only after selection. */
6
+ path?: string;
7
+ bundled?: boolean;
8
+ instructions?: string;
9
+ }
10
+ export interface SkillContext {
11
+ text: string;
12
+ selected: string[];
13
+ warnings: string[];
14
+ bytes: number;
15
+ }
16
+ export declare const SKILL_CONTEXT_BYTES: number;
17
+ /** Explicit mentions precede deterministic task matches; no paid classifier call. */
18
+ export declare function selectTaskSkills(task: string, catalog: readonly TaskSkill[]): TaskSkill[];
19
+ /** Per user turn, not per tool step. Never append instructions to persistent conversation history. */
20
+ export declare function prepareSkillContext(task: string, root: string): SkillContext;
@@ -0,0 +1,169 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { bundledSkills, readBundledSkill, MODKH_SKILL_BINDING } from "./bundled-skills.js";
4
+ export const SKILL_CONTEXT_BYTES = 48 * 1024;
5
+ const LOCAL_SKILL_BYTES = 12 * 1024;
6
+ const MAX_SKILLS = 3;
7
+ const MAX_CATALOG_BYTES = 64 * 1024;
8
+ const ROUTES = {
9
+ 'kiokuko-investigate': ['investigate', 'research', 'explain', '調査', '原因', '説明'],
10
+ 'kiokuko-architecture': ['architecture', 'design', '設計', 'アーキテクチャ'],
11
+ 'kiokuko-review': ['review', 'audit', 'レビュー', '監査'],
12
+ 'kiokuko-benchmark': ['benchmark', 'performance', 'speed', 'ベンチマーク', '性能', '高速化'],
13
+ 'kiokuko-verification': ['verify', 'test', '検証', 'テスト'],
14
+ 'kiokuko-skill-authoring': ['skill', 'skills', 'スキル'],
15
+ 'kiokuko-technical-writing': ['readme', 'documentation', 'ドキュメント', '手順書'],
16
+ 'kiokuko-simple-work': ['minimal', 'simple', 'yagni', '最小', '簡単'],
17
+ 'kiokuko-ui-design-soul': ['ui', 'ux', 'frontend', '画面', 'レイアウト', 'フォーム'],
18
+ 'veteran-programmer-skill': ['install', 'deploy', 'migration', 'state', '配布', '導入', '状態', '移行'],
19
+ 'memory-reasoning': ['memory', '記憶'],
20
+ 'kiokuko-lisp': ['lisp', 'sbcl', 'common-lisp'],
21
+ };
22
+ const CODING = ['implement', 'implementation', 'feature', 'refactor', 'fix', 'debug', 'bug', 'coding', 'code', '実装', '機能', '修正', 'バグ', 'コード', 'リファクタ', '導入'];
23
+ const CODING_CORE = ['coding-ideal-routine-skill', 'one-shot-software-completion', 'kiokuko-single-purpose-functions'];
24
+ function builtinCatalog() {
25
+ return bundledSkills().map(skill => ({ name: skill.name, description: skill.description, keywords: ROUTES[skill.name] ?? [], bundled: true }));
26
+ }
27
+ function matches(task, keyword) {
28
+ if (/^[a-z0-9_-]+$/i.test(keyword)) {
29
+ const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
30
+ return new RegExp(`(^|[^a-z0-9_-])${escaped}($|[^a-z0-9_-])`, 'i').test(task);
31
+ }
32
+ return task.toLowerCase().includes(keyword.toLowerCase());
33
+ }
34
+ /** Explicit mentions precede deterministic task matches; no paid classifier call. */
35
+ export function selectTaskSkills(task, catalog) {
36
+ const mentions = new Set([...task.matchAll(/\$([a-z][a-z0-9-]*)/g)].map(match => match[1]));
37
+ return catalog.map(skill => ({ skill,
38
+ explicit: mentions.has(skill.name),
39
+ score: skill.keywords.filter(keyword => matches(task, keyword)).length,
40
+ })).filter(item => item.explicit || item.score > 0)
41
+ .sort((a, b) => Number(b.explicit) - Number(a.explicit) || b.score - a.score || a.skill.name.localeCompare(b.skill.name, 'en'))
42
+ .slice(0, MAX_SKILLS).map(item => item.skill);
43
+ }
44
+ /** Bounded regular files within the canonical workspace; symlink escapes never become instructions. */
45
+ function readLocal(root, relative, limit) {
46
+ if (path.isAbsolute(relative))
47
+ throw new Error('absolute path');
48
+ const file = fs.realpathSync(path.resolve(root, relative));
49
+ const rel = path.relative(root, file);
50
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
51
+ throw new Error('outside workspace');
52
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW);
53
+ try {
54
+ const stat = fs.fstatSync(fd);
55
+ if (!stat.isFile() || stat.size > limit)
56
+ throw new Error('not a bounded regular file');
57
+ const buffer = Buffer.alloc(limit + 1);
58
+ let size = 0;
59
+ while (size < buffer.length) {
60
+ const count = fs.readSync(fd, buffer, size, buffer.length - size, null);
61
+ if (!count)
62
+ break;
63
+ size += count;
64
+ }
65
+ if (size > limit)
66
+ throw new Error('file grew beyond limit');
67
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, size));
68
+ }
69
+ finally {
70
+ fs.closeSync(fd);
71
+ }
72
+ }
73
+ function localCatalog(root, warnings, builtin) {
74
+ let text;
75
+ try {
76
+ text = readLocal(root, '.modkh/skills.json', MAX_CATALOG_BYTES);
77
+ }
78
+ catch (error) {
79
+ if (error.code !== 'ENOENT')
80
+ warnings.push('スキル一覧を読めないため組み込み手順のみ使用');
81
+ return [];
82
+ }
83
+ try {
84
+ const items = JSON.parse(text);
85
+ if (!Array.isArray(items) || items.length > 128)
86
+ throw new Error('invalid catalog');
87
+ const names = new Set(builtin.map(skill => skill.name));
88
+ return items.map((item) => {
89
+ if (!item || typeof item !== 'object')
90
+ throw new Error('invalid entry');
91
+ const value = item;
92
+ if (typeof value.name !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value.name) || names.has(value.name)
93
+ || typeof value.description !== 'string' || value.description.length > 500
94
+ || !Array.isArray(value.keywords) || value.keywords.length > 32
95
+ || !value.keywords.every(k => typeof k === 'string' && k.trim().length > 0 && k.length <= 80)
96
+ || typeof value.path !== 'string' || value.path.length > 500)
97
+ throw new Error('invalid entry');
98
+ names.add(value.name);
99
+ return { name: value.name, description: value.description, keywords: value.keywords, path: value.path };
100
+ });
101
+ }
102
+ catch {
103
+ warnings.push('スキル一覧の形式が不正なため組み込み手順のみ使用');
104
+ return [];
105
+ }
106
+ }
107
+ /** Per user turn, not per tool step. Never append instructions to persistent conversation history. */
108
+ export function prepareSkillContext(task, root) {
109
+ const warnings = [];
110
+ let canonical;
111
+ try {
112
+ canonical = fs.realpathSync(root);
113
+ }
114
+ catch {
115
+ return { text: '', selected: [], warnings: ['作業ルートを確認できないためスキル注入を省略'], bytes: 0 };
116
+ }
117
+ let builtin = [];
118
+ try {
119
+ builtin = builtinCatalog();
120
+ }
121
+ catch {
122
+ warnings.push('同梱スキル一覧を読めないため注入を省略');
123
+ }
124
+ const catalog = [...builtin, ...localCatalog(canonical, warnings, builtin)];
125
+ const optional = selectTaskSkills(task, catalog);
126
+ const names = new Set(optional.map(skill => skill.name));
127
+ const coding = CODING.some(word => matches(task, word));
128
+ if (coding)
129
+ for (const name of CODING_CORE)
130
+ names.add(name);
131
+ if (matches(task, 'review') || matches(task, 'レビュー'))
132
+ names.add('kiokuko-single-purpose-functions');
133
+ if (/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(task) || matches(task, 'Japanese'))
134
+ names.add('natural-japanese-output');
135
+ if (names.size)
136
+ names.add('kiokuko-soul');
137
+ // Host entry and mandatory code guidance precede optional specialists; no top-three cutoff on core contracts.
138
+ const order = ['kiokuko-soul', ...CODING_CORE, ...optional.map(skill => skill.name), 'natural-japanese-output'];
139
+ const selected = [...new Set(order)].filter(name => names.has(name)).map(name => catalog.find(skill => skill.name === name)).filter((skill) => !!skill);
140
+ const header = '\n\n' + MODKH_SKILL_BINDING;
141
+ let text = '';
142
+ const delivered = [];
143
+ const bodies = new Set();
144
+ for (const skill of selected) {
145
+ let body;
146
+ try {
147
+ body = skill.bundled ? readBundledSkill(skill.name) : skill.instructions ?? readLocal(canonical, skill.path, LOCAL_SKILL_BYTES);
148
+ }
149
+ catch {
150
+ warnings.push(`${skill.name}: 本文を安全に読めないため省略`);
151
+ continue;
152
+ }
153
+ if (!body.trim()) {
154
+ warnings.push(`${skill.name}: 本文が空のため省略`);
155
+ continue;
156
+ }
157
+ if (bodies.has(body))
158
+ continue;
159
+ const section = `\n[${skill.name}]\n${body}\n`;
160
+ if (Buffer.byteLength((text || header) + section) > SKILL_CONTEXT_BYTES) {
161
+ warnings.push(`${skill.name}: 注入上限を超えるため本文全体を省略`);
162
+ continue;
163
+ }
164
+ text = (text || header) + section;
165
+ bodies.add(body);
166
+ delivered.push(skill.name);
167
+ }
168
+ return { text, selected: delivered, warnings, bytes: Buffer.byteLength(text) };
169
+ }