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,6 @@
1
+ export type OfficialProvider = 'openai' | 'chatgpt';
2
+ export declare function hasModelCredentials(provider: OfficialProvider): boolean;
3
+ /** Fetch afresh for each picker; never substitute a baked-in list or persist account entitlements. */
4
+ export declare function fetchOfficialModels(provider: OfficialProvider, signal: AbortSignal): Promise<string[]>;
5
+ /** Own cancellation and diagnostics, keeping failed retrieval distinct from an empty catalogue. */
6
+ export declare function officialModelChoices(provider: OfficialProvider, write: (text: string) => void, signal?: AbortSignal): Promise<string[] | null>;
@@ -0,0 +1,77 @@
1
+ import { currentChatGptTokens } from "../model/chatgpt/login.js";
2
+ import { loadChatGptTokens } from "../model/chatgpt/tokens.js";
3
+ import { resolveApiKey } from "./keys.js";
4
+ // Codex catalogue protocol compatibility, not the MoDKH application version.
5
+ // https://github.com/openai/codex/releases/tag/rust-v0.169.0
6
+ const CODEX_CATALOG_VERSION = '0.169.0';
7
+ export function hasModelCredentials(provider) {
8
+ return provider === 'chatgpt' ? loadChatGptTokens() !== null
9
+ : Boolean(resolveApiKey('openai', process.env, 'OPENAI_API_KEY'));
10
+ }
11
+ /** Fetch afresh for each picker; never substitute a baked-in list or persist account entitlements. */
12
+ export async function fetchOfficialModels(provider, signal) {
13
+ const headers = { accept: 'application/json' };
14
+ let endpoint;
15
+ if (provider === 'chatgpt') {
16
+ const tokens = await currentChatGptTokens(signal);
17
+ headers.authorization = `Bearer ${tokens.accessToken}`;
18
+ if (tokens.accountId)
19
+ headers['ChatGPT-Account-Id'] = tokens.accountId;
20
+ endpoint = `https://chatgpt.com/backend-api/codex/models?client_version=${CODEX_CATALOG_VERSION}`;
21
+ }
22
+ else {
23
+ const key = resolveApiKey('openai', process.env, 'OPENAI_API_KEY');
24
+ if (!key)
25
+ throw new Error('OPENAI_API_KEY が未設定です。/connect openai で認証してください');
26
+ headers.authorization = `Bearer ${key}`;
27
+ endpoint = 'https://api.openai.com/v1/models';
28
+ }
29
+ const response = await fetch(endpoint, { headers, signal, redirect: 'error' });
30
+ if (!response.ok)
31
+ throw new Error(`公式モデル一覧の取得に失敗しました: HTTP ${response.status}`);
32
+ const body = await response.json();
33
+ const rows = body && typeof body === 'object'
34
+ ? body[provider === 'chatgpt' ? 'models' : 'data'] : undefined;
35
+ if (!Array.isArray(rows))
36
+ throw new Error('公式モデル一覧の応答形式が不正です');
37
+ const ids = [];
38
+ for (const row of rows) {
39
+ if (!row || typeof row !== 'object')
40
+ throw new Error('公式モデル一覧のモデル形式が不正です');
41
+ const id = row[provider === 'chatgpt' ? 'slug' : 'id'];
42
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._:/-]*$/.test(id)) {
43
+ throw new Error('公式モデル一覧のモデルIDが不正です');
44
+ }
45
+ if (provider === 'chatgpt' && row.visibility !== 'list')
46
+ continue;
47
+ ids.push(`${provider}/${id}`);
48
+ }
49
+ return [...new Set(ids)];
50
+ }
51
+ /** Own cancellation and diagnostics, keeping failed retrieval distinct from an empty catalogue. */
52
+ export async function officialModelChoices(provider, write, signal) {
53
+ const controller = new AbortController();
54
+ const cancel = () => controller.abort();
55
+ if (!signal)
56
+ process.on('SIGINT', cancel);
57
+ const activeSignal = signal ?? controller.signal;
58
+ write(`${provider}: 公式モデル一覧を取得中…(Ctrl+Cで中止)\n`);
59
+ try {
60
+ const models = await fetchOfficialModels(provider, AbortSignal.any([activeSignal, AbortSignal.timeout(10_000)]));
61
+ write(`${provider}: 公式モデル一覧 ${models.length}件\n`);
62
+ return models;
63
+ }
64
+ catch (error) {
65
+ const message = activeSignal.aborted ? '取得を中止しました'
66
+ : error instanceof Error && error.name === 'TimeoutError' ? '取得がタイムアウトしました'
67
+ : error instanceof Error && error.message.startsWith('公式モデル一覧') ? error.message
68
+ : hasModelCredentials(provider) ? '公式モデル一覧を取得できませんでした。通信と認証を確認してください'
69
+ : provider === 'openai' ? 'OPENAI_API_KEY が未設定です。/connect openai から接続してください'
70
+ : 'ChatGPT認証が必要です。/connect chatgpt から接続してください';
71
+ write(`(${provider}: ${message}。一覧を開き直すと再取得します。モデルIDの直接入力も使えます)\n`);
72
+ return activeSignal.aborted ? null : [];
73
+ }
74
+ finally {
75
+ process.removeListener('SIGINT', cancel);
76
+ }
77
+ }
@@ -0,0 +1,8 @@
1
+ import { type ImageAttachment } from '../agent/images.ts';
2
+ export declare const pdfUsage = "/pdf [--pages 2-4] @<PDF\u306E\u30D1\u30B9> [| <\u4F9D\u983C\u6587>]";
3
+ export declare function isPdfPathPrefix(text: string): boolean;
4
+ export declare function readPdfRequest(root: string, line: string, signal: AbortSignal, availableImages: number): Promise<{
5
+ prompt: string;
6
+ text: string;
7
+ images: ImageAttachment[];
8
+ }>;
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs/promises';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { assertRealInRoot, resolveInRoot } from "../tools/guard.js";
5
+ import { MAX_IMAGES, MAX_IMAGE_BYTES, parseImage } from "../agent/images.js";
6
+ const run = promisify(execFile);
7
+ export const pdfUsage = '/pdf [--pages 2-4] @<PDFのパス> [| <依頼文>]';
8
+ const pdfPrefix = /^\/pdf[ \t]+(?:--pages[ \t]+(\d+)(?:-(\d+))?[ \t]+)?/;
9
+ export function isPdfPathPrefix(text) {
10
+ return pdfPrefix.exec(text.trimStart())?.[0] === text.trimStart() && !text.includes('\n');
11
+ }
12
+ function parsePdfRequest(line) {
13
+ const prefix = pdfPrefix.exec(line);
14
+ if (!prefix)
15
+ throw new Error(pdfUsage);
16
+ const args = line.slice(prefix[0].length);
17
+ const mention = /^@("(?:[^"\\\r\n]|\\["\\])*"|[^\s"|]+)\s*(?:\|(.+))?$/.exec(args);
18
+ if (mention) {
19
+ const filename = mention[1].startsWith('"') ? JSON.parse(mention[1]) : mention[1];
20
+ if (!filename.trim() || (mention[2] !== undefined && !mention[2].trim()))
21
+ throw new Error(pdfUsage);
22
+ return { filename, prompt: mention[2]?.trim() ?? 'このPDFの内容を要約してください。', start: prefix[1], end: prefix[2] };
23
+ }
24
+ const legacy = /^([^|]+)\|(.+)$/.exec(args);
25
+ if (args.startsWith('@') || !legacy?.[1].trim() || !legacy[2].trim())
26
+ throw new Error(pdfUsage);
27
+ return { filename: legacy[1].trim(), prompt: legacy[2].trim(), start: prefix[1], end: prefix[2] };
28
+ }
29
+ async function poppler(command, args, maxBuffer, signal) {
30
+ try {
31
+ const { stdout } = await run(command, args, {
32
+ encoding: 'buffer', env: { ...process.env, LC_ALL: 'C' }, maxBuffer, signal, timeout: 15000,
33
+ });
34
+ return stdout;
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ throw new Error(`Poppler の ${command} が必要です`);
39
+ if (error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
40
+ throw new Error('ページの変換結果が大きすぎます');
41
+ }
42
+ throw error;
43
+ }
44
+ }
45
+ export async function readPdfRequest(root, line, signal, availableImages) {
46
+ const { filename, prompt, start, end } = parsePdfRequest(line);
47
+ const file = resolveInRoot(root, filename);
48
+ assertRealInRoot(root, file);
49
+ const stat = await fs.stat(file);
50
+ if (!stat.isFile() || stat.size > 32 * 1024 * 1024)
51
+ throw new Error('32 MiB以内のPDFファイルを指定してください');
52
+ const info = await poppler('pdfinfo', [file], 1024 * 1024, signal);
53
+ const pages = Number(/^Pages:\s+(\d+)\s*$/m.exec(info.toString())?.[1]);
54
+ if (!Number.isSafeInteger(pages) || pages < 1)
55
+ throw new Error('PDFのページ数を取得できません');
56
+ const first = Number(start ?? 1), last = Number(end ?? start ?? pages);
57
+ if (first < 1 || last < first || last > pages)
58
+ throw new Error(`ページ範囲は1〜${pages}で指定してください`);
59
+ if (last - first + 1 > availableImages)
60
+ throw new Error(`全${pages}ページ。添付は画像と合わせて最大${MAX_IMAGES}枚です。--pages で範囲を指定してください`);
61
+ const images = [];
62
+ const text = [`PDF資料: ${filename}(全${pages}ページ)`];
63
+ for (let page = first; page <= last; page++) {
64
+ const range = ['-f', String(page), '-l', String(page)];
65
+ const body = await poppler('pdftotext', [...range, '-layout', '-enc', 'UTF-8', file, '-'], 32 * 1024, signal);
66
+ const png = await poppler('pdftoppm', [...range, '-singlefile', '-scale-to', '1600', '-png', file], MAX_IMAGE_BYTES, signal);
67
+ images.push(parseImage({ mediaType: 'image/png', data: png.toString('base64') }));
68
+ text.push(`ページ ${page}\n${body.toString().trim() || '(テキスト層なし。添付画像を参照)'}`);
69
+ }
70
+ return { prompt, text: text.join('\n\n'), images };
71
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Approval policy for effectful tools.
3
+ *
4
+ * This decides when MODKH asks the human; it is not an OS sandbox. `all` and `workspace` still run
5
+ * commands with the user's own privileges, so the distinction is about prompting, not isolation.
6
+ */
7
+ export type PermissionPolicy = 'all' | 'workspace' | 'none';
8
+ /** Widest first, so the list reads as a scale. */
9
+ export declare const POLICY_LEVELS: readonly PermissionPolicy[];
10
+ /** The default keeps the old behaviour for reads/edits inside the workspace but stops prompting
11
+ * on every ordinary command, which is what made routine work tedious. */
12
+ export declare const DEFAULT_POLICY: PermissionPolicy;
13
+ export declare function parsePermissionPolicy(value: string): PermissionPolicy | null;
14
+ export interface ApprovalDecisionInput {
15
+ policy: PermissionPolicy;
16
+ kind: 'edit' | 'command';
17
+ /** True only when the resolved target is proven outside the working root. */
18
+ outsideWorkspace: boolean;
19
+ }
20
+ /**
21
+ * `workspace` never asks for effects inside the root; it still asks for anything that escaped it.
22
+ * A caller that cannot prove the target is inside must pass outsideWorkspace: true.
23
+ */
24
+ export declare function shouldAsk(input: ApprovalDecisionInput): boolean;
25
+ export declare function describePolicy(policy: PermissionPolicy): string;
@@ -0,0 +1,30 @@
1
+ /** Widest first, so the list reads as a scale. */
2
+ export const POLICY_LEVELS = ['all', 'workspace', 'none'];
3
+ /** The default keeps the old behaviour for reads/edits inside the workspace but stops prompting
4
+ * on every ordinary command, which is what made routine work tedious. */
5
+ export const DEFAULT_POLICY = 'workspace';
6
+ export function parsePermissionPolicy(value) {
7
+ const normalized = value.trim().toLowerCase();
8
+ return POLICY_LEVELS.includes(normalized) ? normalized : null;
9
+ }
10
+ /**
11
+ * `workspace` never asks for effects inside the root; it still asks for anything that escaped it.
12
+ * A caller that cannot prove the target is inside must pass outsideWorkspace: true.
13
+ */
14
+ export function shouldAsk(input) {
15
+ if (input.policy === 'all')
16
+ return false;
17
+ if (input.policy === 'none')
18
+ return true;
19
+ return input.outsideWorkspace;
20
+ }
21
+ export function describePolicy(policy) {
22
+ switch (policy) {
23
+ case 'all':
24
+ return 'all — 承認を求めず自動実行する(ワークスペース外も含む)';
25
+ case 'workspace':
26
+ return 'workspace — ワークスペース内は自動、外に出る操作だけ確認する';
27
+ case 'none':
28
+ return 'none — 読み取り以外は毎回確認する';
29
+ }
30
+ }
@@ -0,0 +1 @@
1
+ export declare function runPluginCommand(positional: string): Promise<void>;
@@ -0,0 +1,53 @@
1
+ import path from 'node:path';
2
+ import { PluginManager } from "../plugins/manager.js";
3
+ import { createTerminal } from "./terminal.js";
4
+ export async function runPluginCommand(positional) {
5
+ const manager = new PluginManager();
6
+ const split = positional.indexOf(' ');
7
+ const action = split < 0 ? positional : positional.slice(0, split);
8
+ const target = split < 0 ? '' : positional.slice(split + 1);
9
+ if (action === 'list' && !target) {
10
+ const { registry, diagnostics } = manager.discover();
11
+ for (const diagnostic of diagnostics)
12
+ process.stderr.write(`${diagnostic}\n`);
13
+ for (const row of registry.list())
14
+ process.stdout.write(`${row.id} ${row.enabled ? 'enabled' : 'disabled'} ${row.kind} ${row.version} ${row.digest}\n`);
15
+ if (!registry.list().length)
16
+ process.stdout.write('利用可能なプラグインはありません。\n');
17
+ return;
18
+ }
19
+ if (action === 'add' && target) {
20
+ const directory = path.resolve(target);
21
+ const preview = manager.preview(directory);
22
+ const ui = createTerminal(process.cwd());
23
+ const ac = new AbortController();
24
+ const stop = () => ac.abort();
25
+ process.on('SIGINT', stop);
26
+ try {
27
+ ui.write(`任意のNode.jsコードを実行するプラグインです。OSサンドボックスではありません。\n${preview.manifest.id} ${preview.manifest.version}\n${directory}\nSHA256: ${preview.digest}\n`);
28
+ const answer = await ui.ask('この内容を信頼して登録しますか? [y/N]', ac.signal);
29
+ if (ac.signal.aborted || answer?.trim().toLowerCase() !== 'y') {
30
+ ui.write('登録しませんでした。\n');
31
+ return;
32
+ }
33
+ const installed = manager.install(directory, preview.digest);
34
+ ui.write(`登録しました: ${installed.id}\n`);
35
+ }
36
+ finally {
37
+ process.removeListener('SIGINT', stop);
38
+ ui.close();
39
+ }
40
+ return;
41
+ }
42
+ if ((action === 'enable' || action === 'disable') && target) {
43
+ manager.setEnabled(target, action === 'enable');
44
+ process.stdout.write(`${target}: ${action} (新規の子の起動に反映。実行中の子は維持)\n`);
45
+ return;
46
+ }
47
+ if (action === 'remove' && target) {
48
+ manager.remove(target);
49
+ process.stdout.write(`登録を解除しました: ${target}。監査用パッケージと履歴は保持します。\n`);
50
+ return;
51
+ }
52
+ throw new Error('使い方: modkh plugin list | add <directory> | enable <id> | disable <id> | remove <id>');
53
+ }
@@ -0,0 +1,10 @@
1
+ import type { ChatTerminal } from './terminal.ts';
2
+ import { modelProviders, CONNECT_PROVIDERS } from './catalog.ts';
3
+ export { CONNECT_PROVIDERS, modelProviders };
4
+ export declare function chooseProvider(ui: ChatTerminal, current: string | null): Promise<string | null>;
5
+ export declare function confirmRemoteAgent(ui: ChatTerminal): Promise<boolean>;
6
+ /**
7
+ * プロバイダーのモデルを選ぶ。一覧は開くたびにプロバイダーから取得し、固定値は使わない。
8
+ * 取得できなくても「モデルIDを直接入力」で先へ進める。
9
+ */
10
+ export declare function chooseProviderModel(ui: ChatTerminal, provider: string): Promise<string | null>;
@@ -0,0 +1,82 @@
1
+ import { modelProviders, toRefs, SEARCH_ROW_VALUE, CONNECT_PROVIDERS, LOCAL_MODEL_REFS } from "./catalog.js";
2
+ import { officialModelChoices } from "./official-models.js";
3
+ import { providerModelChoices } from "./model-catalog.js";
4
+ import { knownProviders, supportsLiveModels } from "../model/providers.js";
5
+ export { CONNECT_PROVIDERS, modelProviders };
6
+ export async function chooseProvider(ui, current) {
7
+ ui.write(current ? `接続中: ${current}\n` : '未接続です。\n');
8
+ return ui.choose('Connect an integration — 認証先', modelProviders().map(p => ({ ...p,
9
+ detail: `${current?.startsWith(`${p.value}/`) || p.value === 'openai' && current?.startsWith('chatgpt/') ? '選択中 · ' : ''}${p.detail}`,
10
+ })));
11
+ }
12
+ export async function confirmRemoteAgent(ui) {
13
+ return await ui.choose('Hermes側でツール実行 — MODKHの承認・Stopの保証対象外', [
14
+ { value: 'back', label: '戻る' },
15
+ { value: 'connect', label: 'Hermes Agent に接続', detail: 'サーバー側の権限・設定を使用' },
16
+ ]) === 'connect';
17
+ }
18
+ /**
19
+ * プロバイダーのモデルを選ぶ。一覧は開くたびにプロバイダーから取得し、固定値は使わない。
20
+ * 取得できなくても「モデルIDを直接入力」で先へ進める。
21
+ */
22
+ export async function chooseProviderModel(ui, provider) {
23
+ let refs;
24
+ if (provider === 'openai' || provider === 'chatgpt') {
25
+ const official = await officialModelChoices(provider, text => ui.write(text));
26
+ if (official === null)
27
+ return null;
28
+ refs = official;
29
+ }
30
+ else if (provider === 'fixed' || provider === 'compatible') {
31
+ // プロバイダーが公開する一覧が無い擬似接続先。IDは直接入力してもらう。
32
+ refs = LOCAL_MODEL_REFS.filter(ref => ref.startsWith(`${provider}/`));
33
+ }
34
+ else if (knownProviders().includes(provider) && supportsLiveModels(provider)) {
35
+ const result = await providerModelChoices(provider, text => ui.write(text));
36
+ if (result === null)
37
+ return null;
38
+ refs = toRefs(provider, result.ids);
39
+ }
40
+ else {
41
+ ui.write(`(${provider}: 一覧APIがないためモデルIDを入力してください)\n`);
42
+ refs = [];
43
+ }
44
+ const choices = refs.map(ref => ({ value: ref, label: ref }));
45
+ choices.push({ value: 'custom', label: 'モデルIDを直接入力', detail: '一覧にないモデル' });
46
+ const askManual = async () => {
47
+ const model = (await ui.ask('モデルID(空行・/cancelで戻る)'))?.trim();
48
+ if (!model || model === '/cancel')
49
+ return null;
50
+ if (model.startsWith('/')) {
51
+ ui.unread(model);
52
+ return null;
53
+ }
54
+ return model.startsWith(`${provider}/`) ? model : `${provider}/${model}`;
55
+ };
56
+ for (;;) {
57
+ // The search row is pinned first so a bare Enter never connects to an arbitrary model.
58
+ const selected = await ui.choose(`${provider} — モデルを選択`, [
59
+ { value: SEARCH_ROW_VALUE, label: '🔍 キーワード検索', pinned: true },
60
+ ...choices,
61
+ ]);
62
+ if (selected !== SEARCH_ROW_VALUE) {
63
+ return selected === 'custom' ? await askManual() : selected;
64
+ }
65
+ // Choosing the row with a keyword already typed just reopens the same filtered list; an empty
66
+ // box asks for the keyword explicitly so the row is never a dead end.
67
+ const keyword = (await ui.ask('キーワード検索(空白区切りは語順自由。例: seek deep / 空行・/cancelで戻る)'))?.trim();
68
+ if (!keyword || keyword === '/cancel')
69
+ continue;
70
+ if (keyword.startsWith('/')) {
71
+ ui.unread(keyword);
72
+ return null;
73
+ }
74
+ const reopened = await ui.choose(`${provider} — モデルを選択`, [
75
+ { value: SEARCH_ROW_VALUE, label: '🔍 キーワード検索', pinned: true },
76
+ ...choices,
77
+ ], keyword);
78
+ if (reopened === SEARCH_ROW_VALUE)
79
+ continue;
80
+ return reopened === 'custom' ? await askManual() : reopened;
81
+ }
82
+ }
@@ -0,0 +1,6 @@
1
+ /** Display-only shell presentation. Model results and session records keep their full evidence. */
2
+ export declare function shellCall(args: Record<string, unknown>): string;
3
+ export declare function shellOutput(result: {
4
+ status: string;
5
+ output: string;
6
+ }): string;
@@ -0,0 +1,35 @@
1
+ /** Display-only shell presentation. Model results and session records keep their full evidence. */
2
+ export function shellCall(args) {
3
+ const title = typeof args.description === 'string' ? args.description.replace(/\s+/g, ' ').trim() : '';
4
+ const command = typeof args.command === 'string' ? args.command : '';
5
+ const lines = command.split('\n');
6
+ return `\n╭ ${title || 'コマンド実行'}\n${lines.map((line, i) => `│ ${i === 0 ? '$ ' : ' '}${line}`).join('\n')}\n`;
7
+ }
8
+ export function shellOutput(result) {
9
+ const lines = result.output.split('\n');
10
+ // Only the protocol header introduces stdout/stderr. Do not reinterpret arbitrary text
11
+ // from tools without a shell result (approval denial, background promotion, etc.).
12
+ const header = lines.findIndex(line => /^\[exit code: [^\]]+\](?: \[signal: [^\]]+\])?$/.test(line));
13
+ const exit = header < 0 ? undefined : lines[header].match(/^\[exit code: ([^\]]+)\](.*)$/);
14
+ const body = lines.filter((_line, index) => index !== header).map((line, index) => {
15
+ if (header >= 0 && index >= header) {
16
+ if (line === '--- stdout ---')
17
+ return null;
18
+ if (line === '--- stderr ---')
19
+ return '標準エラー';
20
+ }
21
+ return line;
22
+ }).filter((line) => line !== null);
23
+ while (body[0] === '')
24
+ body.shift();
25
+ while (body.at(-1) === '')
26
+ body.pop();
27
+ const visible = body.length > 20
28
+ ? [...body.slice(0, 8), `… ${body.length - 20}行省略(全文はセッション記録)`, ...body.slice(-12)] : body;
29
+ const status = result.status === 'ok'
30
+ ? exit ? exit[1] === '0' ? '終了' : '失敗' : '受付'
31
+ : result.status === 'unknown' ? '中断・結果不明'
32
+ : result.status === 'not-executed' ? '未実行' : '実行エラー';
33
+ const footer = `${status}${exit ? ` · exit ${exit[1]}${exit[2]}` : ''}`;
34
+ return `${visible.map(line => `│ ${line}`).join('\n')}${visible.length ? '\n' : ''}╰ ${footer}\n\n`;
35
+ }
@@ -0,0 +1 @@
1
+ export declare function runStaterightCommand(action: string): Promise<void>;
@@ -0,0 +1,37 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { executeBounded } from "../lisp/runtime.js";
3
+ import { findStateright, staterightRoot } from "../tools/stateright-runtime.js";
4
+ export async function runStaterightCommand(action) {
5
+ if (!['install', 'status'].includes(action))
6
+ throw new Error('使い方: modkh stateright install | status');
7
+ const root = fileURLToPath(new URL('../../', import.meta.url));
8
+ const controller = new AbortController();
9
+ const abort = () => controller.abort();
10
+ process.once('SIGINT', abort);
11
+ try {
12
+ if (action === 'install') {
13
+ process.stdout.write('Stateright検証器を構築・導入中(Rust/Cargoが必要)…\n');
14
+ const receipt = await executeBounded('cargo', ['install', '--locked', '--path', `${root}native/stateright`, '--root', staterightRoot(), '--force'], { cwd: root, env: process.env, inputDigest: '', timeoutMs: 600_000, maxOutputBytes: 32768, outputOverflow: 'tail', signal: controller.signal });
15
+ if (receipt.state !== 'exited' || receipt.exitCode !== 0 || receipt.cleanup !== 'settled')
16
+ throw new Error(`Stateright導入失敗: ${receipt.state}\n${receipt.stderr}`);
17
+ }
18
+ const command = findStateright();
19
+ if (!command) {
20
+ process.stdout.write('Stateright: 未導入。modkh stateright install で導入できます。\n');
21
+ return;
22
+ }
23
+ const receipt = await executeBounded(command, ['--protocol'], { cwd: root, env: process.env, inputDigest: '', timeoutMs: 5000, signal: controller.signal });
24
+ let info;
25
+ try {
26
+ info = JSON.parse(receipt.stdout);
27
+ }
28
+ catch { /* invalid protocol */ }
29
+ if (receipt.state !== 'exited' || receipt.exitCode !== 0 || receipt.cleanup !== 'settled' || info?.name !== 'modkh-stateright' || info?.schemaVersion !== 1) {
30
+ throw new Error('Stateright検証器のプロトコルが不正です。modkh stateright install で更新してください。');
31
+ }
32
+ process.stdout.write(`Stateright: 利用可能\n${command}\n次のmodkh起動で前鬼が自動登録されます。\n`);
33
+ }
34
+ finally {
35
+ process.removeListener('SIGINT', abort);
36
+ }
37
+ }
@@ -0,0 +1,21 @@
1
+ export interface ScreenPoint {
2
+ row: number;
3
+ column: number;
4
+ }
5
+ export interface MouseReport extends ScreenPoint {
6
+ button: number;
7
+ released: boolean;
8
+ }
9
+ /** Deliver mouse reports before readline can interpret them as keyboard input. */
10
+ export declare class TerminalMouseInput {
11
+ private readonly decoder;
12
+ private tail;
13
+ private timer?;
14
+ private readonly keyboard;
15
+ private readonly mouse;
16
+ private readonly inPaste;
17
+ constructor(keyboard: (text: string) => void, mouse: (event: MouseReport) => void, inPaste: () => boolean);
18
+ write: (chunk: Buffer | string) => void;
19
+ close(): void;
20
+ private flush;
21
+ }
@@ -0,0 +1,51 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ const report = /\x1b\[<(\d{1,3});(\d{1,5});(\d{1,5})([Mm])/g;
3
+ const incomplete = /\x1b(?:\[(?:<(?:\d{0,3}(?:;\d{0,5}(?:;\d{0,5})?)?)?)?)?(?![\s\S])/;
4
+ /** Deliver mouse reports before readline can interpret them as keyboard input. */
5
+ export class TerminalMouseInput {
6
+ decoder = new StringDecoder('utf8');
7
+ tail = '';
8
+ timer;
9
+ keyboard;
10
+ mouse;
11
+ inPaste;
12
+ constructor(keyboard, mouse, inPaste) {
13
+ this.keyboard = keyboard;
14
+ this.mouse = mouse;
15
+ this.inPaste = inPaste;
16
+ }
17
+ write = (chunk) => {
18
+ clearTimeout(this.timer);
19
+ const input = this.tail + (typeof chunk === 'string' ? chunk : this.decoder.write(chunk));
20
+ this.tail = '';
21
+ let offset = 0;
22
+ for (const match of input.matchAll(report)) {
23
+ this.keyboard(input.slice(offset, match.index));
24
+ if (this.inPaste())
25
+ this.keyboard(match[0]);
26
+ else
27
+ this.mouse({ button: Number(match[1]), column: Number(match[2]), row: Number(match[3]), released: match[4] === 'm' });
28
+ offset = match.index + match[0].length;
29
+ }
30
+ const rest = input.slice(offset);
31
+ const partial = incomplete.exec(rest);
32
+ if (partial) {
33
+ this.tail = partial[0];
34
+ this.keyboard(rest.slice(0, partial.index));
35
+ // A standalone Escape is also a key. Give fragmented reports time to arrive.
36
+ this.timer = setTimeout(this.flush, 35).unref();
37
+ }
38
+ else
39
+ this.keyboard(rest);
40
+ };
41
+ close() {
42
+ clearTimeout(this.timer);
43
+ this.tail = '';
44
+ }
45
+ flush = () => {
46
+ const text = this.tail;
47
+ this.tail = '';
48
+ if (!text.startsWith('\x1b[<'))
49
+ this.keyboard(text);
50
+ };
51
+ }