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,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
+ }
@@ -0,0 +1,180 @@
1
+ import { streamText, jsonSchema, tool, } from 'ai';
2
+ import { toolContext } from "./context.js";
3
+ import { reasoningProviderOptions } from "./reasoning.js";
4
+ import { parseImages } from "../agent/images.js";
5
+ function toCoreMessages(req) {
6
+ const out = [];
7
+ const outputs = toolContext(req.messages);
8
+ for (const [index, m] of req.messages.entries()) {
9
+ if (m.role === 'user') {
10
+ const images = parseImages(m.images);
11
+ out.push({ role: 'user', content: images.length ? [
12
+ ...(m.content ? [{ type: 'text', text: m.content }] : []),
13
+ ...images.map(image => ({ type: 'file', data: Buffer.from(image.data, 'base64'), mediaType: image.mediaType })),
14
+ ] : m.content });
15
+ }
16
+ else if (m.role === 'assistant') {
17
+ const content = [];
18
+ if (m.content.length > 0)
19
+ content.push({ type: 'text', text: m.content });
20
+ for (const c of m.toolCalls ?? []) {
21
+ const part = {
22
+ type: 'tool-call',
23
+ toolCallId: c.id,
24
+ toolName: c.name,
25
+ input: c.args,
26
+ };
27
+ content.push(part);
28
+ }
29
+ out.push({ role: 'assistant', content });
30
+ }
31
+ else {
32
+ const parts = m.results.map((r, resultIndex) => ({
33
+ type: 'tool-result',
34
+ toolCallId: r.callId,
35
+ toolName: r.name,
36
+ output: { type: 'text', value: JSON.stringify({ status: r.status, output: outputs.get(`${index}:${resultIndex}`) }) },
37
+ }));
38
+ out.push({ role: 'tool', content: parts });
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+ /** モデルへ渡すツール定義。execute は持たせず、実行は CLI 側で承認付きで行う。 */
44
+ function toAiSdkTools(specs) {
45
+ const out = {};
46
+ for (const s of specs) {
47
+ out[s.name] = tool({
48
+ description: s.description,
49
+ inputSchema: jsonSchema(s.parameters),
50
+ });
51
+ }
52
+ return out;
53
+ }
54
+ /**
55
+ * AI SDK (Vercel AI SDK) 経由の Model 実装。1回の stream() は1ステップ
56
+ * (テキスト+ツール要求まで)。ツール実行と次ステップは Agent ループが担う。
57
+ * 中断は abortSignal で伝え、'aborted' で静かに終わる。
58
+ */
59
+ export class AiSdkModel {
60
+ id;
61
+ lm;
62
+ timeoutMs;
63
+ provider;
64
+ constructor(opts) {
65
+ this.id = opts.id;
66
+ this.lm = opts.languageModel;
67
+ this.provider = opts.provider;
68
+ this.timeoutMs = opts.timeoutMs ?? 600000;
69
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0)
70
+ throw new Error('timeoutMs must be a positive integer');
71
+ }
72
+ /** 無通信タイムアウト。受信が続く限り延期され、何も来なければ締め切る。 */
73
+ async *stream(req, signal) {
74
+ let aborted = false;
75
+ let timedOut = false;
76
+ const deadline = new AbortController();
77
+ let timer;
78
+ const arm = () => { clearTimeout(timer); timer = setTimeout(() => { timedOut = true; deadline.abort(); }, this.timeoutMs); };
79
+ arm();
80
+ const requestSignal = AbortSignal.any([signal, deadline.signal]);
81
+ let activity;
82
+ let usage;
83
+ let errorMessage;
84
+ let sawToolCall = false;
85
+ let finishReason;
86
+ const reasoning = reasoningProviderOptions(this.provider ?? '', req.reasoning);
87
+ const thinking = this.provider === 'anthropic' && reasoning?.anthropic !== undefined;
88
+ const thinkingBudget = thinking
89
+ ? reasoning.anthropic.thinking.budgetTokens : undefined;
90
+ try {
91
+ const result = streamText({
92
+ model: this.lm,
93
+ messages: toCoreMessages(req),
94
+ system: req.system,
95
+ tools: toAiSdkTools(req.tools),
96
+ abortSignal: requestSignal,
97
+ // fullStream below owns errors; the SDK default logs entire request bodies to stderr.
98
+ onError: () => { },
99
+ maxRetries: 0, // A transport failure does not establish that the request was unsent.
100
+ // providerOptions の実値はすべて JSON オブジェクト。SDK型は index signature が緩いため型の詰め替え。
101
+ ...(reasoning ? { providerOptions: reasoning } : {}),
102
+ ...(thinking ? { maxOutputTokens: (thinkingBudget ?? 0) + 8192 } : {}),
103
+ });
104
+ for await (const part of result.fullStream) {
105
+ arm(); // 受信が継続している間は制限時間を延ばす
106
+ if (part.type === 'reasoning-start' || part.type === 'reasoning-delta') {
107
+ if (activity !== 'reasoning') {
108
+ activity = 'reasoning';
109
+ yield { type: 'activity', stage: activity };
110
+ }
111
+ if (part.type === 'reasoning-delta' && part.text.length > 0)
112
+ yield { type: 'reasoning-delta', text: part.text };
113
+ }
114
+ else if (part.type === 'tool-input-start') {
115
+ if (activity !== 'tool-input') {
116
+ activity = 'tool-input';
117
+ yield { type: 'activity', stage: activity };
118
+ }
119
+ }
120
+ else if (part.type === 'text-delta') {
121
+ activity = undefined;
122
+ yield { type: 'text-delta', text: part.text };
123
+ }
124
+ else if (part.type === 'tool-call') {
125
+ sawToolCall = true;
126
+ yield {
127
+ type: 'tool-call',
128
+ call: {
129
+ id: part.toolCallId,
130
+ name: part.toolName,
131
+ args: (part.input ?? {}),
132
+ },
133
+ };
134
+ }
135
+ else if (part.type === 'finish') {
136
+ // totalUsage is the provider's own count; undefined means unreported, not zero.
137
+ if (part.totalUsage) {
138
+ usage = {
139
+ input: part.totalUsage.inputTokens,
140
+ output: part.totalUsage.outputTokens,
141
+ cacheRead: part.totalUsage.inputTokenDetails?.cacheReadTokens,
142
+ cacheWrite: part.totalUsage.inputTokenDetails?.cacheWriteTokens,
143
+ };
144
+ }
145
+ if (part.finishReason === 'stop' || part.finishReason === 'tool-calls') {
146
+ finishReason = part.finishReason;
147
+ }
148
+ else {
149
+ errorMessage = `モデル応答は未完了: ${part.finishReason}`;
150
+ }
151
+ }
152
+ else if (part.type === 'error') {
153
+ errorMessage = part.error?.message ?? String(part.error);
154
+ }
155
+ }
156
+ aborted = signal.aborted;
157
+ }
158
+ catch (e) {
159
+ aborted = signal.aborted;
160
+ if (!aborted)
161
+ errorMessage = e.message;
162
+ }
163
+ finally {
164
+ clearTimeout(timer);
165
+ }
166
+ if (timedOut && !signal.aborted)
167
+ errorMessage = `モデル応答が制限時間(${this.timeoutMs}ms)を超えるまで何も受信しませんでした。自動再送はしません。`;
168
+ if (usage && (usage.input !== undefined || usage.output !== undefined))
169
+ yield { type: 'usage', ...usage };
170
+ if (aborted) {
171
+ yield { type: 'finish', stopReason: 'aborted' };
172
+ }
173
+ else if (errorMessage !== undefined || finishReason === undefined || (finishReason === 'tool-calls') !== sawToolCall) {
174
+ yield { type: 'finish', stopReason: 'error', errorMessage: errorMessage ?? 'モデル終了イベントがない、またはツール要求と終了理由が不整合' };
175
+ }
176
+ else {
177
+ yield { type: 'finish', stopReason: finishReason };
178
+ }
179
+ }
180
+ }
@@ -0,0 +1,42 @@
1
+ import { type ChatGptTokens } from './tokens.ts';
2
+ export interface LoginConfig {
3
+ issuer: string;
4
+ clientId: string;
5
+ redirectPort: number;
6
+ }
7
+ export declare const DEFAULT_LOGIN: LoginConfig;
8
+ export interface PkcePair {
9
+ verifier: string;
10
+ challenge: string;
11
+ }
12
+ export declare function createPkcePair(): PkcePair;
13
+ export interface AuthorizeOptions {
14
+ issuer: string;
15
+ clientId: string;
16
+ redirectUri: string;
17
+ verifier: string;
18
+ state: string;
19
+ }
20
+ export declare function buildAuthorizeUrl(o: AuthorizeOptions): string;
21
+ export type TokenResponse = ChatGptTokens;
22
+ export interface ExchangeOptions {
23
+ issuer: string;
24
+ clientId: string;
25
+ code: string;
26
+ verifier: string;
27
+ redirectUri: string;
28
+ fetchImpl?: typeof fetch;
29
+ signal?: AbortSignal;
30
+ }
31
+ export declare function exchangeCode(o: ExchangeOptions): Promise<TokenResponse>;
32
+ /** Refresh only before sending a new model request; never replay a failed model request. */
33
+ export declare function currentChatGptTokens(signal?: AbortSignal): Promise<ChatGptTokens>;
34
+ export interface LoginOptions {
35
+ config?: LoginConfig;
36
+ openUrl?: (url: string) => void | Promise<void>;
37
+ write?: (text: string) => void;
38
+ signal?: AbortSignal;
39
+ timeoutMs?: number;
40
+ }
41
+ /** Own the listener from bind through exchange/save; the browser reports success only after saving. */
42
+ export declare function loginChatGpt(opts?: LoginOptions): Promise<ChatGptTokens>;
@@ -0,0 +1,180 @@
1
+ import crypto from 'node:crypto';
2
+ import http from 'node:http';
3
+ import { spawn } from 'node:child_process';
4
+ import { saveChatGptTokens, loadChatGptTokens } from "./tokens.js";
5
+ export const DEFAULT_LOGIN = {
6
+ issuer: 'https://auth.openai.com', clientId: 'app_EMoioEEEJzSuZ1pPfKS5baDe', redirectPort: 1455,
7
+ };
8
+ export function createPkcePair() {
9
+ const verifier = crypto.randomBytes(48).toString('base64url');
10
+ return { verifier, challenge: crypto.createHash('sha256').update(verifier).digest('base64url') };
11
+ }
12
+ export function buildAuthorizeUrl(o) {
13
+ const u = new URL('/oauth/authorize', o.issuer);
14
+ u.search = new URLSearchParams({ response_type: 'code', client_id: o.clientId,
15
+ redirect_uri: o.redirectUri, scope: 'openid profile email offline_access', state: o.state,
16
+ code_challenge: crypto.createHash('sha256').update(o.verifier).digest('base64url'),
17
+ code_challenge_method: 'S256', id_token_add_organizations: 'true', codex_cli_simplified_flow: 'true',
18
+ }).toString();
19
+ return u.toString();
20
+ }
21
+ function jwtExpiry(token) {
22
+ try {
23
+ const exp = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()).exp;
24
+ return typeof exp === 'number' && Number.isFinite(exp) && exp > 0 ? new Date(exp * 1000).toISOString() : undefined;
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /** Read account routing metadata, not an authorization decision. The server validates the token. */
31
+ function tokenAccount(token) {
32
+ if (typeof token !== 'string')
33
+ return undefined;
34
+ try {
35
+ const body = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
36
+ const account = body['https://api.openai.com/auth']?.chatgpt_account_id;
37
+ return typeof account === 'string' ? account : undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ async function requestTokens(config, fields, signal, fetchImpl = fetch) {
44
+ const res = await fetchImpl(new URL('/oauth/token', config.issuer), {
45
+ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },
46
+ body: new URLSearchParams({ client_id: config.clientId, ...fields }),
47
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),
48
+ redirect: 'error',
49
+ });
50
+ // Never print token endpoint bodies: they may include credentials or the submitted code.
51
+ if (!res.ok)
52
+ throw new Error(`トークン交換に失敗した: HTTP ${res.status}。/connect chatgpt で再認証してください`);
53
+ const body = await res.json();
54
+ if (typeof body.access_token !== 'string' || !body.access_token)
55
+ throw new Error('トークン応答に access_token がない');
56
+ return {
57
+ accessToken: body.access_token,
58
+ refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,
59
+ expiresAt: typeof body.expires_in === 'number' && body.expires_in > 0
60
+ ? new Date(Date.now() + body.expires_in * 1000).toISOString() : jwtExpiry(body.access_token),
61
+ accountId: typeof body.account_id === 'string' ? body.account_id
62
+ : tokenAccount(body.id_token) ?? tokenAccount(body.access_token),
63
+ };
64
+ }
65
+ export function exchangeCode(o) {
66
+ return requestTokens(o, { grant_type: 'authorization_code', code: o.code,
67
+ redirect_uri: o.redirectUri, code_verifier: o.verifier }, o.signal, o.fetchImpl);
68
+ }
69
+ /** Refresh only before sending a new model request; never replay a failed model request. */
70
+ export async function currentChatGptTokens(signal) {
71
+ const tokens = loadChatGptTokens();
72
+ if (!tokens)
73
+ throw new Error('ChatGPTにログインしていない: /connect chatgpt で認証してください');
74
+ const expiry = tokens.expiresAt ?? jwtExpiry(tokens.accessToken);
75
+ if (!expiry || Date.parse(expiry) > Date.now() + 60_000)
76
+ return tokens;
77
+ if (!tokens.refreshToken)
78
+ throw new Error('ChatGPTの認証期限が切れています。/connect chatgpt で再認証してください');
79
+ const renewed = await requestTokens(DEFAULT_LOGIN, { grant_type: 'refresh_token', refresh_token: tokens.refreshToken }, signal);
80
+ signal?.throwIfAborted();
81
+ const result = { ...renewed, refreshToken: renewed.refreshToken ?? tokens.refreshToken, accountId: renewed.accountId ?? tokens.accountId };
82
+ saveChatGptTokens(result);
83
+ return result;
84
+ }
85
+ async function openBrowser(url) {
86
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';
87
+ const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];
88
+ await new Promise((resolve, reject) => {
89
+ const child = spawn(command, args, { stdio: 'ignore' });
90
+ const timer = setTimeout(() => { child.kill(); reject(new Error('ブラウザ起動がタイムアウトしました')); }, 5000);
91
+ child.once('error', (e) => { clearTimeout(timer); reject(e); });
92
+ child.once('close', (code) => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error('ブラウザを開けません')); });
93
+ });
94
+ }
95
+ /** Own the listener from bind through exchange/save; the browser reports success only after saving. */
96
+ export async function loginChatGpt(opts = {}) {
97
+ const cfg = opts.config ?? DEFAULT_LOGIN;
98
+ const write = opts.write ?? ((text) => process.stdout.write(text));
99
+ const ac = new AbortController();
100
+ const signal = AbortSignal.any([ac.signal, ...(opts.signal ? [opts.signal] : []), AbortSignal.timeout(opts.timeoutMs ?? 300_000)]);
101
+ signal.throwIfAborted();
102
+ const onSigint = () => ac.abort(new Error('認証を中止しました'));
103
+ process.on('SIGINT', onSigint);
104
+ const { verifier } = createPkcePair();
105
+ const state = crypto.randomBytes(24).toString('hex');
106
+ let redirectUri = '';
107
+ let claimed = false;
108
+ let resolveResult;
109
+ let rejectResult;
110
+ const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });
111
+ // Attach a handler immediately; bind/browser failures can happen before the caller awaits result.
112
+ void result.catch(() => { });
113
+ const server = http.createServer((req, res) => {
114
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
115
+ const reply = (status, text) => {
116
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' });
117
+ res.end(text);
118
+ };
119
+ if (req.method !== 'GET' || url.pathname !== '/auth/callback') {
120
+ reply(404, 'Not found');
121
+ return;
122
+ }
123
+ if (url.searchParams.get('state') !== state) {
124
+ reply(400, '不正な認証stateです。元の認証画面からやり直してください。');
125
+ return;
126
+ }
127
+ if (claimed) {
128
+ reply(409, '認証処理中です。端末を確認してください。');
129
+ return;
130
+ }
131
+ const code = url.searchParams.get('code');
132
+ if (url.searchParams.has('error') || !code) {
133
+ reply(400, '認証は完了しませんでした。MODKHで再試行してください。');
134
+ rejectResult(new Error('認証が拒否されたか、認可コードがありません。/connect chatgpt で再試行してください'));
135
+ return;
136
+ }
137
+ claimed = true;
138
+ write('認可を受信しました。トークンを交換しています…\n');
139
+ void exchangeCode({ ...cfg, code, verifier, redirectUri, signal }).then((tokens) => {
140
+ signal.throwIfAborted();
141
+ saveChatGptTokens(tokens);
142
+ reply(200, 'MODKH: 認証情報を保存しました。このタブを閉じて端末へ戻ってください。');
143
+ resolveResult(tokens);
144
+ }).catch((error) => { reply(500, 'MODKH: 認証を保存できませんでした。端末の案内を確認してください。'); rejectResult(error); });
145
+ });
146
+ const onAbort = () => rejectResult(new Error(signal.reason?.name === 'TimeoutError'
147
+ ? '認証がタイムアウトしました。/connect chatgpt で再試行してください' : '認証を中止しました'));
148
+ signal.addEventListener('abort', onAbort, { once: true });
149
+ try {
150
+ await new Promise((resolve, reject) => {
151
+ server.once('error', reject);
152
+ server.listen(cfg.redirectPort, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); });
153
+ });
154
+ server.on('error', rejectResult);
155
+ signal.throwIfAborted();
156
+ const port = server.address().port;
157
+ redirectUri = `http://127.0.0.1:${port}/auth/callback`;
158
+ const url = buildAuthorizeUrl({ ...cfg, redirectUri, verifier, state });
159
+ if (opts.openUrl)
160
+ await opts.openUrl(url);
161
+ else {
162
+ write(`ChatGPTのブラウザ認証を開きます。開かない場合は次のURLを使用してください:\n${url}\n待機中… Ctrl+C で中止\n`);
163
+ await openBrowser(url).catch(() => write('ブラウザを自動起動できませんでした。上のURLを手動で開いてください。\n'));
164
+ }
165
+ return await result;
166
+ }
167
+ catch (error) {
168
+ if (error.code === 'EADDRINUSE') {
169
+ throw new Error(`認証ポート ${cfg.redirectPort} は使用中です。他のログイン処理を終了してから /connect chatgpt で再試行してください`);
170
+ }
171
+ throw error;
172
+ }
173
+ finally {
174
+ ac.abort();
175
+ signal.removeEventListener('abort', onAbort);
176
+ process.removeListener('SIGINT', onSigint);
177
+ server.closeAllConnections();
178
+ await new Promise((resolve) => server.close(() => resolve()));
179
+ }
180
+ }