modkh 0.0.0-stage → 0.2.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 (327) hide show
  1. package/README.md +66 -2
  2. package/dist/agent/bundled-skills.d.ts +13 -0
  3. package/dist/agent/bundled-skills.js +95 -0
  4. package/dist/agent/compaction.d.ts +53 -0
  5. package/dist/agent/compaction.js +191 -0
  6. package/dist/agent/images.d.ts +10 -0
  7. package/dist/agent/images.js +33 -0
  8. package/dist/agent/loop.d.ts +103 -0
  9. package/dist/agent/loop.js +267 -0
  10. package/dist/agent/skills.d.ts +26 -0
  11. package/dist/agent/skills.js +190 -0
  12. package/dist/agent/types.d.ts +137 -0
  13. package/dist/agent/types.js +12 -0
  14. package/dist/cli/agenticreplay.d.ts +1 -0
  15. package/dist/cli/agenticreplay.js +66 -0
  16. package/dist/cli/agents.d.ts +8 -0
  17. package/dist/cli/agents.js +12 -0
  18. package/dist/cli/answer-markdown.d.ts +3 -0
  19. package/dist/cli/answer-markdown.js +29 -0
  20. package/dist/cli/approval.d.ts +29 -0
  21. package/dist/cli/approval.js +92 -0
  22. package/dist/cli/catalog.d.ts +37 -0
  23. package/dist/cli/catalog.js +46 -0
  24. package/dist/cli/chat.d.ts +18 -0
  25. package/dist/cli/chat.js +1061 -0
  26. package/dist/cli/clipboard.d.ts +11 -0
  27. package/dist/cli/clipboard.js +82 -0
  28. package/dist/cli/color.d.ts +59 -0
  29. package/dist/cli/color.js +244 -0
  30. package/dist/cli/compaction-settings.d.ts +21 -0
  31. package/dist/cli/compaction-settings.js +54 -0
  32. package/dist/cli/completion-art.d.ts +2 -0
  33. package/dist/cli/completion-art.js +62 -0
  34. package/dist/cli/config.d.ts +50 -0
  35. package/dist/cli/config.js +192 -0
  36. package/dist/cli/editor.d.ts +23 -0
  37. package/dist/cli/editor.js +115 -0
  38. package/dist/cli/file-mentions.d.ts +14 -0
  39. package/dist/cli/file-mentions.js +141 -0
  40. package/dist/cli/head-checks.d.ts +41 -0
  41. package/dist/cli/head-checks.js +146 -0
  42. package/dist/cli/initial-connection.d.ts +7 -0
  43. package/dist/cli/initial-connection.js +20 -0
  44. package/dist/cli/keys.d.ts +29 -0
  45. package/dist/cli/keys.js +107 -0
  46. package/dist/cli/language.d.ts +1 -0
  47. package/dist/cli/language.js +105 -0
  48. package/dist/cli/limits.d.ts +13 -0
  49. package/dist/cli/limits.js +19 -0
  50. package/dist/cli/lines.d.ts +18 -0
  51. package/dist/cli/lines.js +80 -0
  52. package/dist/cli/model-catalog.d.ts +16 -0
  53. package/dist/cli/model-catalog.js +130 -0
  54. package/dist/cli/models.d.ts +4 -0
  55. package/dist/cli/models.js +101 -0
  56. package/dist/cli/official-models.d.ts +6 -0
  57. package/dist/cli/official-models.js +77 -0
  58. package/dist/cli/pdf.d.ts +8 -0
  59. package/dist/cli/pdf.js +71 -0
  60. package/dist/cli/permissions.d.ts +25 -0
  61. package/dist/cli/permissions.js +30 -0
  62. package/dist/cli/plugins.d.ts +1 -0
  63. package/dist/cli/plugins.js +53 -0
  64. package/dist/cli/providers.d.ts +10 -0
  65. package/dist/cli/providers.js +82 -0
  66. package/dist/cli/shell-display.d.ts +6 -0
  67. package/dist/cli/shell-display.js +35 -0
  68. package/dist/cli/stateright.d.ts +1 -0
  69. package/dist/cli/stateright.js +37 -0
  70. package/dist/cli/terminal-mouse.d.ts +21 -0
  71. package/dist/cli/terminal-mouse.js +51 -0
  72. package/dist/cli/terminal.d.ts +231 -0
  73. package/dist/cli/terminal.js +1417 -0
  74. package/dist/cli/tool-display.d.ts +9 -0
  75. package/dist/cli/tool-display.js +87 -0
  76. package/dist/cli/transcript-selection.d.ts +22 -0
  77. package/dist/cli/transcript-selection.js +75 -0
  78. package/dist/cli/usage.d.ts +22 -0
  79. package/dist/cli/usage.js +117 -0
  80. package/dist/cli/waiting-nyan.d.ts +3 -0
  81. package/dist/cli/waiting-nyan.js +17 -0
  82. package/dist/cli/waiting-whales.d.ts +3 -0
  83. package/dist/cli/waiting-whales.js +24 -0
  84. package/dist/index.d.ts +11 -0
  85. package/dist/index.js +186 -0
  86. package/dist/language/catalog.d.ts +44 -0
  87. package/dist/language/catalog.js +100 -0
  88. package/dist/language/commonlisp-bundled.d.ts +11 -0
  89. package/dist/language/commonlisp-bundled.js +22 -0
  90. package/dist/language/commonlisp-dependencies.d.ts +16 -0
  91. package/dist/language/commonlisp-dependencies.js +68 -0
  92. package/dist/language/commonlisp-install.d.ts +15 -0
  93. package/dist/language/commonlisp-install.js +214 -0
  94. package/dist/language/commonlisp-reader.d.ts +17 -0
  95. package/dist/language/commonlisp-reader.js +47 -0
  96. package/dist/language/commonlisp-systems.d.ts +3 -0
  97. package/dist/language/commonlisp-systems.js +32 -0
  98. package/dist/language/commonlisp-tls.d.ts +10 -0
  99. package/dist/language/commonlisp-tls.js +51 -0
  100. package/dist/language/detect.d.ts +29 -0
  101. package/dist/language/detect.js +103 -0
  102. package/dist/language/grammars/LICENSE +24 -0
  103. package/dist/language/grammars/manifest.json +76 -0
  104. package/dist/language/grammars/tree-sitter-c.wasm +0 -0
  105. package/dist/language/grammars/tree-sitter-cpp.wasm +0 -0
  106. package/dist/language/grammars/tree-sitter-css.wasm +0 -0
  107. package/dist/language/grammars/tree-sitter-html.wasm +0 -0
  108. package/dist/language/grammars/tree-sitter-javascript.wasm +0 -0
  109. package/dist/language/grammars/tree-sitter-php.wasm +0 -0
  110. package/dist/language/grammars/tree-sitter-python.wasm +0 -0
  111. package/dist/language/grammars/tree-sitter-ruby.wasm +0 -0
  112. package/dist/language/grammars/tree-sitter-rust.wasm +0 -0
  113. package/dist/language/grammars/tree-sitter-swift.wasm +0 -0
  114. package/dist/language/grammars/tree-sitter-tsx.wasm +0 -0
  115. package/dist/language/grammars/tree-sitter-typescript.wasm +0 -0
  116. package/dist/language/install.d.ts +50 -0
  117. package/dist/language/install.js +293 -0
  118. package/dist/language/lsp/client.d.ts +97 -0
  119. package/dist/language/lsp/client.js +340 -0
  120. package/dist/language/lsp/pool.d.ts +75 -0
  121. package/dist/language/lsp/pool.js +140 -0
  122. package/dist/language/lsp/service.d.ts +50 -0
  123. package/dist/language/lsp/service.js +174 -0
  124. package/dist/language/native.d.ts +8 -0
  125. package/dist/language/native.js +100 -0
  126. package/dist/language/platform.d.ts +14 -0
  127. package/dist/language/platform.js +20 -0
  128. package/dist/language/positions.d.ts +20 -0
  129. package/dist/language/positions.js +46 -0
  130. package/dist/language/syntax/assets.d.ts +9 -0
  131. package/dist/language/syntax/assets.js +73 -0
  132. package/dist/language/syntax/parser.d.ts +33 -0
  133. package/dist/language/syntax/parser.js +162 -0
  134. package/dist/language/typescript-capability.d.ts +6 -0
  135. package/dist/language/typescript-capability.js +42 -0
  136. package/dist/lisp/builtin-agents.d.ts +5 -0
  137. package/dist/lisp/builtin-agents.js +52 -0
  138. package/dist/lisp/config.d.ts +25 -0
  139. package/dist/lisp/config.js +202 -0
  140. package/dist/lisp/routing.d.ts +5 -0
  141. package/dist/lisp/routing.js +24 -0
  142. package/dist/lisp/runtime.d.ts +26 -0
  143. package/dist/lisp/runtime.js +107 -0
  144. package/dist/memory/kiokuko.d.ts +32 -0
  145. package/dist/memory/kiokuko.js +102 -0
  146. package/dist/memory/mcp.d.ts +38 -0
  147. package/dist/memory/mcp.js +211 -0
  148. package/dist/model/ai-sdk.d.ts +27 -0
  149. package/dist/model/ai-sdk.js +185 -0
  150. package/dist/model/chatgpt/login.d.ts +42 -0
  151. package/dist/model/chatgpt/login.js +180 -0
  152. package/dist/model/chatgpt/responses.d.ts +41 -0
  153. package/dist/model/chatgpt/responses.js +254 -0
  154. package/dist/model/chatgpt/tokens.d.ts +11 -0
  155. package/dist/model/chatgpt/tokens.js +50 -0
  156. package/dist/model/connection.d.ts +6 -0
  157. package/dist/model/connection.js +67 -0
  158. package/dist/model/context-window.d.ts +3 -0
  159. package/dist/model/context-window.js +64 -0
  160. package/dist/model/context.d.ts +11 -0
  161. package/dist/model/context.js +69 -0
  162. package/dist/model/factory.d.ts +27 -0
  163. package/dist/model/factory.js +89 -0
  164. package/dist/model/fixed.d.ts +17 -0
  165. package/dist/model/fixed.js +41 -0
  166. package/dist/model/harness-profile.d.ts +6 -0
  167. package/dist/model/harness-profile.js +23 -0
  168. package/dist/model/providers.d.ts +32 -0
  169. package/dist/model/providers.js +72 -0
  170. package/dist/model/reasoning.d.ts +16 -0
  171. package/dist/model/reasoning.js +84 -0
  172. package/dist/model/record-fetch.d.ts +2 -0
  173. package/dist/model/record-fetch.js +19 -0
  174. package/dist/plugins/api.d.ts +60 -0
  175. package/dist/plugins/api.js +1 -0
  176. package/dist/plugins/manager.d.ts +35 -0
  177. package/dist/plugins/manager.js +280 -0
  178. package/dist/plugins/package.d.ts +13 -0
  179. package/dist/plugins/package.js +99 -0
  180. package/dist/plugins/registry.d.ts +8 -0
  181. package/dist/plugins/registry.js +14 -0
  182. package/dist/session/store.d.ts +93 -0
  183. package/dist/session/store.js +311 -0
  184. package/dist/session/workspace.d.ts +19 -0
  185. package/dist/session/workspace.js +73 -0
  186. package/dist/subagents/head-assignment.d.ts +11 -0
  187. package/dist/subagents/head-assignment.js +47 -0
  188. package/dist/subagents/limits.d.ts +4 -0
  189. package/dist/subagents/limits.js +6 -0
  190. package/dist/subagents/processes.d.ts +18 -0
  191. package/dist/subagents/processes.js +73 -0
  192. package/dist/subagents/request.d.ts +4 -0
  193. package/dist/subagents/request.js +38 -0
  194. package/dist/subagents/service.d.ts +73 -0
  195. package/dist/subagents/service.js +645 -0
  196. package/dist/subagents/settings.d.ts +10 -0
  197. package/dist/subagents/settings.js +32 -0
  198. package/dist/subagents/types.d.ts +63 -0
  199. package/dist/subagents/types.js +1 -0
  200. package/dist/subagents/verification.d.ts +34 -0
  201. package/dist/subagents/verification.js +215 -0
  202. package/dist/tools/browse.d.ts +13 -0
  203. package/dist/tools/browse.js +117 -0
  204. package/dist/tools/browser-capability.d.ts +3 -0
  205. package/dist/tools/browser-capability.js +29 -0
  206. package/dist/tools/diff.d.ts +6 -0
  207. package/dist/tools/diff.js +82 -0
  208. package/dist/tools/edit.d.ts +3 -0
  209. package/dist/tools/edit.js +152 -0
  210. package/dist/tools/files.d.ts +6 -0
  211. package/dist/tools/files.js +96 -0
  212. package/dist/tools/formal-input.d.ts +6 -0
  213. package/dist/tools/formal-input.js +29 -0
  214. package/dist/tools/formal.d.ts +9 -0
  215. package/dist/tools/formal.js +79 -0
  216. package/dist/tools/guard.d.ts +7 -0
  217. package/dist/tools/guard.js +48 -0
  218. package/dist/tools/job-tools.d.ts +19 -0
  219. package/dist/tools/job-tools.js +148 -0
  220. package/dist/tools/jobs.d.ts +79 -0
  221. package/dist/tools/jobs.js +186 -0
  222. package/dist/tools/language.d.ts +6 -0
  223. package/dist/tools/language.js +172 -0
  224. package/dist/tools/lean-proof.d.ts +38 -0
  225. package/dist/tools/lean-proof.js +83 -0
  226. package/dist/tools/registry.d.ts +30 -0
  227. package/dist/tools/registry.js +113 -0
  228. package/dist/tools/run.d.ts +13 -0
  229. package/dist/tools/run.js +163 -0
  230. package/dist/tools/search.d.ts +2 -0
  231. package/dist/tools/search.js +156 -0
  232. package/dist/tools/shell-process.d.ts +115 -0
  233. package/dist/tools/shell-process.js +297 -0
  234. package/dist/tools/skills.d.ts +2 -0
  235. package/dist/tools/skills.js +46 -0
  236. package/dist/tools/stateright-runtime.d.ts +3 -0
  237. package/dist/tools/stateright-runtime.js +16 -0
  238. package/dist/tools/stateright.d.ts +3 -0
  239. package/dist/tools/stateright.js +78 -0
  240. package/dist/tools/web.d.ts +24 -0
  241. package/dist/tools/web.js +391 -0
  242. package/dist/version.d.ts +2 -0
  243. package/dist/version.js +2 -0
  244. package/docs/ci-repair-20261116.md +30 -0
  245. package/docs/commonlisp-build-output.md +14 -0
  246. package/docs/commonlisp-provider-migration.md +22 -0
  247. package/docs/commonlisp-qlot-recovery.md +28 -0
  248. package/docs/commonlisp-tls-recovery.md +28 -0
  249. package/docs/context-efficiency.md +122 -0
  250. package/docs/input.md +126 -0
  251. package/docs/languages.md +117 -0
  252. package/docs/models.md +109 -0
  253. package/docs/modkh-evidence.json +641 -0
  254. package/docs/modkh-failure-comparison.json +675 -0
  255. package/docs/modkh-namespace.md +39 -0
  256. package/docs/modkh-qlot-evidence.json +37 -0
  257. package/docs/modkh-verification.md +173 -0
  258. package/docs/modkh.md +128 -0
  259. package/docs/presets.md +64 -0
  260. package/docs/setup.md +99 -0
  261. package/docs/stateright.md +45 -0
  262. package/docs/subagents.md +152 -0
  263. package/docs/web.md +57 -0
  264. package/experiments/presets/common-lisp.lisp +38 -0
  265. package/experiments/presets/css.lisp +38 -0
  266. package/experiments/presets/formal.lisp +18 -0
  267. package/experiments/presets/html.lisp +38 -0
  268. package/experiments/presets/js.lisp +38 -0
  269. package/experiments/presets/language-microagents.lisp +29 -0
  270. package/experiments/presets/php.lisp +38 -0
  271. package/experiments/presets/svelte.lisp +38 -0
  272. package/experiments/presets/tailwindcss.lisp +24 -0
  273. package/experiments/presets/ts.lisp +38 -0
  274. package/native/stateright/Cargo.lock +478 -0
  275. package/native/stateright/Cargo.toml +11 -0
  276. package/native/stateright/src/lib.rs +163 -0
  277. package/native/stateright/src/main.rs +38 -0
  278. package/package.json +57 -4
  279. package/plugins/modkh-explorer/index.mjs +3 -0
  280. package/plugins/modkh-explorer/plugin.json +1 -0
  281. package/plugins/modkh-worker/index.mjs +3 -0
  282. package/plugins/modkh-worker/plugin.json +1 -0
  283. package/skills/kiokuko-dsh/LICENSE +21 -0
  284. package/skills/kiokuko-dsh/coding-ideal-routine-skill/SKILL.md +106 -0
  285. package/skills/kiokuko-dsh/japanese-translation-for-oss-models/SKILL.md +65 -0
  286. package/skills/kiokuko-dsh/kiokuko-architecture/SKILL.md +20 -0
  287. package/skills/kiokuko-dsh/kiokuko-architecture/references/cases.md +11 -0
  288. package/skills/kiokuko-dsh/kiokuko-benchmark/SKILL.md +20 -0
  289. package/skills/kiokuko-dsh/kiokuko-benchmark/references/cases.md +11 -0
  290. package/skills/kiokuko-dsh/kiokuko-investigate/SKILL.md +20 -0
  291. package/skills/kiokuko-dsh/kiokuko-investigate/references/cases.md +11 -0
  292. package/skills/kiokuko-dsh/kiokuko-lisp/SKILL.md +390 -0
  293. package/skills/kiokuko-dsh/kiokuko-review/SKILL.md +20 -0
  294. package/skills/kiokuko-dsh/kiokuko-review/references/cases.md +11 -0
  295. package/skills/kiokuko-dsh/kiokuko-simple-work/SKILL.md +70 -0
  296. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/SKILL.md +79 -0
  297. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/boundaries-and-ownership.md +52 -0
  298. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/domain-and-types.md +48 -0
  299. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/effects-and-data.md +43 -0
  300. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/kiokuko-patterns.md +314 -0
  301. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/problem-shaping-and-language.md +90 -0
  302. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/protocols-and-idempotency.md +42 -0
  303. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/review-checklist.md +92 -0
  304. package/skills/kiokuko-dsh/kiokuko-single-purpose-functions/references/verification.md +45 -0
  305. package/skills/kiokuko-dsh/kiokuko-skill-authoring/SKILL.md +20 -0
  306. package/skills/kiokuko-dsh/kiokuko-skill-authoring/references/cases.md +11 -0
  307. package/skills/kiokuko-dsh/kiokuko-soul/SKILL.md +25 -0
  308. package/skills/kiokuko-dsh/kiokuko-technical-writing/SKILL.md +20 -0
  309. package/skills/kiokuko-dsh/kiokuko-technical-writing/references/cases.md +11 -0
  310. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/SKILL.md +64 -0
  311. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/accessibility-and-navigation.md +31 -0
  312. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/async-recovery.md +49 -0
  313. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/forms-and-controls.md +35 -0
  314. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/interaction-feedback.md +34 -0
  315. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/responsive-and-platform.md +38 -0
  316. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/safety-and-review.md +43 -0
  317. package/skills/kiokuko-dsh/kiokuko-ui-design-soul/references/ui-checklist.md +75 -0
  318. package/skills/kiokuko-dsh/kiokuko-verification/SKILL.md +20 -0
  319. package/skills/kiokuko-dsh/kiokuko-verification/references/cases.md +11 -0
  320. package/skills/kiokuko-dsh/manifest.json +168 -0
  321. package/skills/kiokuko-dsh/memory-reasoning/SKILL.md +44 -0
  322. package/skills/kiokuko-dsh/one-shot-software-completion/SKILL.md +113 -0
  323. package/skills/kiokuko-dsh/one-shot-software-completion/references/boundaries-and-lifecycle.md +70 -0
  324. package/skills/kiokuko-dsh/one-shot-software-completion/references/discovery-and-scope.md +71 -0
  325. package/skills/kiokuko-dsh/one-shot-software-completion/references/failure-recovery.md +43 -0
  326. package/skills/kiokuko-dsh/one-shot-software-completion/references/verification-and-completion.md +73 -0
  327. package/skills/kiokuko-dsh/veteran-programmer-skill/SKILL.md +66 -0
@@ -0,0 +1,107 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { spawn } from 'node:child_process';
5
+ import { StringDecoder } from 'node:string_decoder';
6
+ import { createHash } from 'node:crypto';
7
+ export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
8
+ export function privateEnvironment(home) {
9
+ return { PATH: process.env.PATH ?? '/usr/bin:/bin', LANG: process.env.LANG ?? 'C.UTF-8',
10
+ HOME: home, TMPDIR: home, XDG_CONFIG_HOME: home, XDG_CACHE_HOME: home,
11
+ XDG_DATA_HOME: home, XDG_STATE_HOME: home,
12
+ ...(process.env.SBCL_HOME ? { SBCL_HOME: process.env.SBCL_HOME } : {}) };
13
+ }
14
+ export function temporaryDirectory(prefix) { return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); }
15
+ /** shell:false, bounded pipes and owned POSIX process group. Escaped sessions are not a sandbox. */
16
+ export function executeBounded(command, args, options) {
17
+ const base = { state: 'not-started', exitCode: null, signal: null, stdout: '', stderr: '', inputDigest: options.inputDigest, cleanup: 'settled' };
18
+ if (options.signal?.aborted)
19
+ return Promise.resolve(base);
20
+ if (process.platform === 'win32')
21
+ return Promise.resolve({ ...base, stderr: 'POSIX process groups required' });
22
+ return new Promise(resolve => {
23
+ const child = spawn(command, args, { cwd: options.cwd, env: options.env, shell: false, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
24
+ let closed = false, finished = false, bytes = 0;
25
+ const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
26
+ let stopped;
27
+ let poll, deadline;
28
+ const alive = () => {
29
+ if (!child.pid)
30
+ return false;
31
+ try {
32
+ process.kill(-child.pid, 0);
33
+ return true;
34
+ }
35
+ catch (e) {
36
+ return e.code !== 'ESRCH';
37
+ }
38
+ };
39
+ const kill = () => { if (child.pid) {
40
+ try {
41
+ process.kill(-child.pid, 'SIGKILL');
42
+ }
43
+ catch { /* checked at settlement */ }
44
+ } };
45
+ const finish = (unknown = false) => {
46
+ if (finished || (!unknown && (!closed || alive())))
47
+ return;
48
+ finished = true;
49
+ clearTimeout(timer);
50
+ clearTimeout(deadline);
51
+ clearInterval(poll);
52
+ options.signal?.removeEventListener('abort', abort);
53
+ child.stdout?.destroy();
54
+ child.stderr?.destroy();
55
+ resolve({ ...base, outputBytes: bytes, ...(stopped ? { terminationReason: stopped } : {}), state: unknown ? 'unknown' : stopped ?? (base.exitCode === null ? 'not-started' : 'exited'), cleanup: unknown ? 'unknown' : 'settled' });
56
+ };
57
+ const stop = (state) => {
58
+ stopped ??= state;
59
+ kill();
60
+ poll ??= setInterval(() => finish(), 20);
61
+ deadline ??= setTimeout(() => finish(true), 3000);
62
+ };
63
+ const abort = () => stop('aborted');
64
+ const timer = setTimeout(() => stop('timed-out'), options.timeoutMs);
65
+ options.signal?.addEventListener('abort', abort, { once: true });
66
+ if (options.signal?.aborted)
67
+ abort();
68
+ const append = (key, data) => {
69
+ const budget = options.maxOutputBytes ?? 256 * 1024;
70
+ if (options.outputOverflow === 'tail') {
71
+ bytes += data.length;
72
+ const addition = decoders[key].write(data);
73
+ const text = base[key] + addition;
74
+ const buffer = Buffer.from(text);
75
+ const other = key === 'stdout' ? 'stderr' : 'stdout';
76
+ const otherBuffer = Buffer.from(base[other]);
77
+ let otherStart = Math.max(0, otherBuffer.length - Math.max(0, budget - Buffer.byteLength(addition)));
78
+ if (otherStart > 0) {
79
+ base.outputTruncated = true;
80
+ while (otherStart < otherBuffer.length && (otherBuffer[otherStart] & 0xc0) === 0x80)
81
+ otherStart++;
82
+ base[other] = otherBuffer.subarray(otherStart).toString('utf8');
83
+ }
84
+ const limit = Math.max(0, budget - Buffer.byteLength(base[other]));
85
+ let start = Math.max(0, buffer.length - limit);
86
+ if (start > 0) {
87
+ base.outputTruncated = true;
88
+ while (start < buffer.length && (buffer[start] & 0xc0) === 0x80)
89
+ start++;
90
+ }
91
+ base[key] = buffer.subarray(start).toString('utf8');
92
+ return;
93
+ }
94
+ const room = Math.max(0, budget - bytes);
95
+ base[key] += decoders[key].write(data.subarray(0, room));
96
+ bytes += data.length;
97
+ if (bytes > budget)
98
+ stop('output-limit');
99
+ };
100
+ child.stdout?.on('data', (data) => append('stdout', data));
101
+ child.stderr?.on('data', (data) => append('stderr', data));
102
+ child.on('error', error => { base.stderr = error.message.slice(0, 4096); });
103
+ child.on('exit', (code, signal) => { base.exitCode = code; base.signal = signal; if (alive())
104
+ stop('unknown'); });
105
+ child.on('close', (code, signal) => { closed = true; base.stdout += decoders.stdout.end(); base.stderr += decoders.stderr.end(); base.exitCode = code; base.signal = signal; finish(); });
106
+ });
107
+ }
@@ -0,0 +1,32 @@
1
+ import { type McpOptions } from './mcp.ts';
2
+ export interface MemoryPolicy {
3
+ globalRead: boolean;
4
+ globalWrite: boolean;
5
+ projects: {
6
+ id: string;
7
+ name: string;
8
+ read: boolean;
9
+ }[];
10
+ raw: string;
11
+ }
12
+ export interface CaptureProposal {
13
+ title: string;
14
+ body: string;
15
+ }
16
+ /** unknownは送信済み・結果不明。保存の自動再送をしてはいけない。 */
17
+ export type CaptureOutcome = 'saved' | 'declined' | 'unavailable' | 'unknown';
18
+ export type KiokukoMemoryOptions = McpOptions;
19
+ export interface KiokukoMemory {
20
+ /** memory_policy の取得。接続不能や無効は null(コーディングは続く)。 */
21
+ policy(signal?: AbortSignal): Promise<MemoryPolicy | null>;
22
+ /** policy が読み取りを許可したグローバル/プロジェクトだけを検索する。 */
23
+ recall(query: string, projectId?: string, signal?: AbortSignal): Promise<string | null>;
24
+ /** 表示した提案そのものが承認され、Stopされていない場合だけ保存を送信する。 */
25
+ captureIfApproved(proposal: CaptureProposal, confirm: (display: string) => Promise<boolean>, signal?: AbortSignal): Promise<CaptureOutcome>;
26
+ close(): Promise<void>;
27
+ }
28
+ /**
29
+ * Kiokuko 本体メモリへの接続。既定は無効。
30
+ * 補助機能の障害は本作業へthrowせず、利用不可と保存結果不明を区別する。
31
+ */
32
+ export declare function openKiokukoMemory(enabled: boolean, options?: Partial<KiokukoMemoryOptions>): KiokukoMemory;
@@ -0,0 +1,102 @@
1
+ import { McpStdioClient, McpRequestError } from "./mcp.js";
2
+ const DEFAULT_COMMAND = 'kiokuko';
3
+ const DEFAULT_ARGS = ['mcp', '--profile', 'chatgpt-memory'];
4
+ function disabled() {
5
+ return {
6
+ async policy() { return null; },
7
+ async recall() { return null; },
8
+ async captureIfApproved() { return 'declined'; },
9
+ async close() { },
10
+ };
11
+ }
12
+ /**
13
+ * Kiokuko 本体メモリへの接続。既定は無効。
14
+ * 補助機能の障害は本作業へthrowせず、利用不可と保存結果不明を区別する。
15
+ */
16
+ export function openKiokukoMemory(enabled, options) {
17
+ if (!enabled)
18
+ return disabled();
19
+ const client = new McpStdioClient({
20
+ ...options,
21
+ command: options?.command ?? DEFAULT_COMMAND,
22
+ args: options?.args ?? DEFAULT_ARGS,
23
+ });
24
+ let policy = null;
25
+ const getPolicy = async (signal) => {
26
+ if (signal?.aborted)
27
+ return null;
28
+ if (policy !== null)
29
+ return policy;
30
+ if (!(await client.connect(signal))) {
31
+ if (client.lastError && !signal?.aborted)
32
+ process.stderr.write(`modkh memory: ${client.lastError}\n`);
33
+ return null;
34
+ }
35
+ try {
36
+ const raw = await client.callTool('memory_policy', {}, signal);
37
+ const parsed = JSON.parse(raw);
38
+ if (signal?.aborted)
39
+ return null;
40
+ policy = {
41
+ globalRead: parsed.global?.read === true,
42
+ globalWrite: parsed.global?.write === true,
43
+ projects: (parsed.projects ?? []).map((p) => ({ id: p.id, name: p.name, read: p.read === true })),
44
+ raw,
45
+ };
46
+ return policy;
47
+ }
48
+ catch (e) {
49
+ client.lastError = `memory_policy の取得に失敗した: ${e.message}`;
50
+ return null;
51
+ }
52
+ };
53
+ return {
54
+ policy: getPolicy,
55
+ async recall(query, projectId, signal) {
56
+ const p = await getPolicy(signal);
57
+ if (p === null || signal?.aborted)
58
+ return null;
59
+ const readable = projectId === undefined
60
+ ? p.globalRead : p.projects.some((project) => project.id === projectId && project.read);
61
+ if (!readable)
62
+ return null;
63
+ try {
64
+ const args = { query };
65
+ if (projectId !== undefined)
66
+ args['project'] = projectId;
67
+ return await client.callTool('memory_recall', args, signal);
68
+ }
69
+ catch (e) {
70
+ client.lastError = `memory_recall に失敗した: ${e.message}`;
71
+ return null;
72
+ }
73
+ },
74
+ async captureIfApproved(proposal, confirm, signal) {
75
+ // 呼出元がawait中にオブジェクトを変更しても、承認内容を変えない。
76
+ const snapshot = { title: proposal.title, body: proposal.body };
77
+ if (signal?.aborted)
78
+ return 'declined';
79
+ try {
80
+ const p = await getPolicy(signal);
81
+ if (signal?.aborted)
82
+ return 'declined';
83
+ if (p === null || !p.globalWrite)
84
+ return 'unavailable';
85
+ const display = [
86
+ 'メモリ保存の提案(保存先: グローバルのみ)',
87
+ `タイトル: ${snapshot.title}`, '本文:', snapshot.body,
88
+ ].join('\n');
89
+ if (!(await confirm(display)) || signal?.aborted)
90
+ return 'declined';
91
+ await client.callTool('memory_capture', snapshot, signal);
92
+ return 'saved';
93
+ }
94
+ catch (e) {
95
+ if (e instanceof McpRequestError && e.outcomeUnknown)
96
+ return 'unknown';
97
+ return signal?.aborted ? 'declined' : 'unavailable';
98
+ }
99
+ },
100
+ async close() { await client.close(); },
101
+ };
102
+ }
@@ -0,0 +1,38 @@
1
+ export interface McpOptions {
2
+ command: string;
3
+ args?: string[];
4
+ /** 子プロセスへ渡す追加環境変数(検証用)。 */
5
+ env?: Record<string, string>;
6
+ connectTimeoutMs?: number;
7
+ callTimeoutMs?: number;
8
+ }
9
+ /** 応答を失った要求は、サーバー側で実行済みの可能性がある。 */
10
+ export declare class McpRequestError extends Error {
11
+ readonly outcomeUnknown: boolean;
12
+ constructor(message: string, outcomeUnknown: boolean);
13
+ }
14
+ /** newline-delimited JSON-RPC 2.0。要求の再送は行わない。 */
15
+ export declare class McpStdioClient {
16
+ private child;
17
+ private connecting;
18
+ private stopping;
19
+ private closed;
20
+ private nextId;
21
+ private pending;
22
+ private readonly connectTimeoutMs;
23
+ private readonly callTimeoutMs;
24
+ private readonly opts;
25
+ lastError: string | null;
26
+ constructor(opts: McpOptions);
27
+ connect(signal?: AbortSignal): Promise<boolean>;
28
+ private start;
29
+ listTools(signal?: AbortSignal): Promise<{
30
+ name: string;
31
+ description?: string;
32
+ }[]>;
33
+ callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<string>;
34
+ private request;
35
+ private failAll;
36
+ close(): Promise<void>;
37
+ private stopChild;
38
+ }
@@ -0,0 +1,211 @@
1
+ import { spawn } from 'node:child_process';
2
+ /** 応答を失った要求は、サーバー側で実行済みの可能性がある。 */
3
+ export class McpRequestError extends Error {
4
+ outcomeUnknown;
5
+ constructor(message, outcomeUnknown) {
6
+ super(message);
7
+ this.name = 'McpRequestError';
8
+ this.outcomeUnknown = outcomeUnknown;
9
+ }
10
+ }
11
+ /** newline-delimited JSON-RPC 2.0。要求の再送は行わない。 */
12
+ export class McpStdioClient {
13
+ child = null;
14
+ connecting = null;
15
+ stopping = null;
16
+ closed = false;
17
+ nextId = 1;
18
+ pending = new Map();
19
+ connectTimeoutMs;
20
+ callTimeoutMs;
21
+ opts;
22
+ lastError = null;
23
+ constructor(opts) {
24
+ this.opts = opts;
25
+ this.connectTimeoutMs = opts.connectTimeoutMs ?? 10_000;
26
+ this.callTimeoutMs = opts.callTimeoutMs ?? 30_000;
27
+ }
28
+ async connect(signal) {
29
+ if (this.closed || signal?.aborted)
30
+ return false;
31
+ if (this.connecting)
32
+ return this.connecting;
33
+ if (this.stopping)
34
+ await this.stopping;
35
+ if (this.closed || signal?.aborted)
36
+ return false;
37
+ if (this.child)
38
+ return true;
39
+ this.connecting = this.start(signal);
40
+ try {
41
+ return await this.connecting;
42
+ }
43
+ finally {
44
+ this.connecting = null;
45
+ }
46
+ }
47
+ async start(signal) {
48
+ let child;
49
+ try {
50
+ child = spawn(this.opts.command, this.opts.args ?? [], {
51
+ stdio: ['pipe', 'pipe', 'pipe'],
52
+ env: this.opts.env ? { ...process.env, ...this.opts.env } : process.env,
53
+ });
54
+ }
55
+ catch (e) {
56
+ this.lastError = `MCP起動に失敗した: ${e.message}`;
57
+ return false;
58
+ }
59
+ this.child = child;
60
+ let buffer = '';
61
+ let stderrTail = '';
62
+ child.on('error', (e) => {
63
+ this.lastError = `MCPプロセスエラー: ${e.message}`;
64
+ this.failAll(this.lastError);
65
+ });
66
+ // EPIPEはChildProcessではなくstdinにも届く。未処理errorで本作業を落とさない。
67
+ child.stdin?.on('error', (e) => this.failAll(`MCP送信に失敗した: ${e.message}`));
68
+ child.stderr?.setEncoding('utf8');
69
+ child.stderr?.on('data', (chunk) => { stderrTail = (stderrTail + chunk).slice(-800); });
70
+ child.on('close', () => {
71
+ if (this.child !== child)
72
+ return;
73
+ this.child = null;
74
+ this.failAll('MCPプロセスが終了した');
75
+ });
76
+ child.stdout?.setEncoding('utf8');
77
+ child.stdout?.on('data', (chunk) => {
78
+ buffer += chunk;
79
+ // 補助プロセスの無制限出力で親をメモリ不足にしない。
80
+ if (Buffer.byteLength(buffer) > 1024 * 1024) {
81
+ buffer = '';
82
+ child.stdout?.pause();
83
+ this.failAll('MCP応答が上限を超えた');
84
+ void this.stopChild(child);
85
+ return;
86
+ }
87
+ for (;;) {
88
+ const at = buffer.indexOf('\n');
89
+ if (at < 0)
90
+ break;
91
+ const line = buffer.slice(0, at).trim();
92
+ buffer = buffer.slice(at + 1);
93
+ if (!line)
94
+ continue;
95
+ let msg;
96
+ try {
97
+ msg = JSON.parse(line);
98
+ }
99
+ catch {
100
+ continue;
101
+ }
102
+ if (!msg || typeof msg.id !== 'number')
103
+ continue;
104
+ const pending = this.pending.get(msg.id);
105
+ if (!pending)
106
+ continue;
107
+ if (msg.jsonrpc !== '2.0' || (!('result' in msg) && !msg.error)) {
108
+ pending.reject(new McpRequestError('MCP応答が不正', true));
109
+ }
110
+ else if (msg.error) {
111
+ pending.reject(new McpRequestError(msg.error.message, false));
112
+ }
113
+ else
114
+ pending.resolve(msg.result);
115
+ }
116
+ });
117
+ try {
118
+ const result = await this.request('initialize', {
119
+ protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'modkh', version: '0.1.0' },
120
+ }, this.connectTimeoutMs, signal);
121
+ if (!result || typeof result !== 'object')
122
+ throw new Error('MCP初期化応答が不正');
123
+ if (signal?.aborted || this.closed)
124
+ throw new Error('MCP接続を中断した');
125
+ child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized', params: {} })}\n`);
126
+ return true;
127
+ }
128
+ catch (e) {
129
+ this.lastError = `MCP初期化に失敗した: ${e.message}` +
130
+ (stderrTail ? ` / stderr: ${stderrTail.trim()}` : '');
131
+ await this.stopChild(child);
132
+ return false;
133
+ }
134
+ }
135
+ async listTools(signal) {
136
+ const result = await this.request('tools/list', {}, undefined, signal);
137
+ return result?.tools ?? [];
138
+ }
139
+ async callTool(name, args, signal) {
140
+ const result = await this.request('tools/call', { name, arguments: args }, undefined, signal);
141
+ if (!result || !Array.isArray(result.content)) {
142
+ throw new McpRequestError('MCPツール応答が不正', true);
143
+ }
144
+ const text = result.content.filter((c) => c?.type === 'text' && typeof c.text === 'string')
145
+ .map((c) => c.text).join('\n');
146
+ if (result.isError)
147
+ throw new McpRequestError(text || 'MCPツールがエラーを返した', false);
148
+ return text;
149
+ }
150
+ request(method, params, timeoutMs = this.callTimeoutMs, signal) {
151
+ const child = this.child;
152
+ if (signal?.aborted)
153
+ return Promise.reject(new McpRequestError('MCP要求は中断済み', false));
154
+ if (this.closed || this.stopping || !child?.stdin || child.stdin.destroyed) {
155
+ return Promise.reject(new McpRequestError('MCPに接続していない', false));
156
+ }
157
+ const id = this.nextId++;
158
+ const message = `${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`;
159
+ return new Promise((resolve, reject) => {
160
+ const cleanup = () => {
161
+ clearTimeout(timer);
162
+ signal?.removeEventListener('abort', onAbort);
163
+ this.pending.delete(id);
164
+ };
165
+ const fail = (reason) => {
166
+ this.pending.get(id)?.reject(new McpRequestError(reason, true));
167
+ void this.stopChild(child);
168
+ };
169
+ const onAbort = () => fail(`MCP応答待ちを中断した: ${method}`);
170
+ const timer = setTimeout(() => fail(`MCP応答がタイムアウトした: ${method}`), timeoutMs);
171
+ this.pending.set(id, {
172
+ resolve: (value) => { cleanup(); resolve(value); },
173
+ reject: (error) => { cleanup(); reject(error); },
174
+ });
175
+ signal?.addEventListener('abort', onAbort, { once: true });
176
+ child.stdin.write(message, (error) => {
177
+ if (error)
178
+ fail(`MCP送信に失敗した: ${error.message}`);
179
+ });
180
+ });
181
+ }
182
+ failAll(message) {
183
+ for (const pending of this.pending.values())
184
+ pending.reject(new McpRequestError(message, true));
185
+ }
186
+ async close() {
187
+ this.closed = true;
188
+ if (this.child)
189
+ await this.stopChild(this.child);
190
+ else if (this.stopping)
191
+ await this.stopping;
192
+ }
193
+ stopChild(child) {
194
+ if (this.stopping)
195
+ return this.stopping;
196
+ if (this.child !== child)
197
+ return Promise.resolve();
198
+ this.failAll('MCPを切断した');
199
+ this.stopping = new Promise((resolve) => {
200
+ const timer = setTimeout(() => {
201
+ child.kill('SIGKILL');
202
+ child.stdout?.destroy();
203
+ child.stderr?.destroy();
204
+ child.stdin?.destroy();
205
+ }, 250);
206
+ child.once('close', () => { clearTimeout(timer); resolve(); });
207
+ child.kill('SIGTERM');
208
+ }).finally(() => { this.stopping = null; });
209
+ return this.stopping;
210
+ }
211
+ }
@@ -0,0 +1,27 @@
1
+ import { type LanguageModel } from 'ai';
2
+ import type { Model, ModelEvent, ModelRequest } from '../agent/types.ts';
3
+ export interface AiSdkModelOptions {
4
+ id: string;
5
+ languageModel: LanguageModel;
6
+ /** 無通信タイムアウト: 受信が続く限り延びる。既定600秒。 */
7
+ timeoutMs?: number;
8
+ /**
9
+ * providerOptions のキー確定用プロバイダー名。未指定なら推論オプションを送らない
10
+ * (既存の呼び出し元の挙動を変えない)。
11
+ */
12
+ provider?: string;
13
+ }
14
+ /**
15
+ * AI SDK (Vercel AI SDK) 経由の Model 実装。1回の stream() は1ステップ
16
+ * (テキスト+ツール要求まで)。ツール実行と次ステップは Agent ループが担う。
17
+ * 中断は abortSignal で伝え、'aborted' で静かに終わる。
18
+ */
19
+ export declare class AiSdkModel implements Model {
20
+ readonly id: string;
21
+ private readonly lm;
22
+ private readonly timeoutMs;
23
+ private readonly provider?;
24
+ constructor(opts: AiSdkModelOptions);
25
+ /** 無通信タイムアウト。受信が続く限り延期され、何も来なければ締め切る。 */
26
+ stream(req: ModelRequest, signal: AbortSignal): AsyncIterable<ModelEvent>;
27
+ }