micro-models-agent 2.16.1 → 2.17.1

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 (427) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/assets/app.js +1 -314
  3. package/dist/assets/hljs.js +5 -1244
  4. package/dist/assets/index.html +11 -0
  5. package/dist/assets/js/api.js +1 -28
  6. package/dist/assets/js/core/menus.js +1 -0
  7. package/dist/assets/js/core/store/feed.js +1 -0
  8. package/dist/assets/js/core/store/index.js +1 -0
  9. package/dist/assets/js/core/store/session.js +1 -0
  10. package/dist/assets/js/core/store/settings.js +1 -0
  11. package/dist/assets/js/core/store/tabs.js +1 -0
  12. package/dist/assets/js/dialog.js +1 -105
  13. package/dist/assets/js/dom.js +1 -178
  14. package/dist/assets/js/feed/core.js +1 -0
  15. package/dist/assets/js/feed/history.js +1 -0
  16. package/dist/assets/js/feed/plan.js +1 -0
  17. package/dist/assets/js/feed/question.js +3 -0
  18. package/dist/assets/js/feed/sidebar.js +1 -0
  19. package/dist/assets/js/feed/stream.js +1 -0
  20. package/dist/assets/js/feed/turn.js +5 -0
  21. package/dist/assets/js/feed.js +1 -1250
  22. package/dist/assets/js/format.js +2 -122
  23. package/dist/assets/js/i18n.js +1 -46
  24. package/dist/assets/js/rail.js +1 -114
  25. package/dist/assets/js/session/cmdk.js +1 -0
  26. package/dist/assets/js/session/composer.js +1 -0
  27. package/dist/assets/js/session/sessions-menu.js +1 -0
  28. package/dist/assets/js/session/tabs.js +1 -0
  29. package/dist/assets/js/settings/controls.js +1 -0
  30. package/dist/assets/js/settings/editors.js +1 -0
  31. package/dist/assets/js/settings/form.js +1 -0
  32. package/dist/assets/js/settings/modal.js +1 -0
  33. package/dist/assets/js/settings/panels.js +1 -0
  34. package/dist/assets/js/settings/providers.js +1 -0
  35. package/dist/assets/js/settings/search.js +1 -0
  36. package/dist/assets/js/settings/subdialog.js +1 -0
  37. package/dist/assets/js/settings/write.js +1 -0
  38. package/dist/assets/js/settings.js +1 -1914
  39. package/dist/assets/js/sidebar/core.js +1 -0
  40. package/dist/assets/js/sidebar/lsp.js +2 -0
  41. package/dist/assets/js/sidebar/map.js +1 -0
  42. package/dist/assets/js/sidebar/state.js +1 -0
  43. package/dist/assets/js/sidebar/trace.js +5 -0
  44. package/dist/assets/js/sidebar.js +1 -705
  45. package/dist/assets/js/store.js +1 -82
  46. package/dist/assets/js/subdialog.js +1 -0
  47. package/dist/assets/md.js +1 -291
  48. package/dist/assets/setup.js +3 -816
  49. package/dist/assets/smd.js +29 -1665
  50. package/dist/assets/styles.css +1 -1598
  51. package/dist/certification/certifications.json +1 -494
  52. package/dist/i18n/en.json +1 -1851
  53. package/dist/i18n/ru.json +1 -1854
  54. package/dist/main.js +815 -55797
  55. package/dist/modules/browser/bridge-server.mjs +2 -252
  56. package/package.json +10 -5
  57. package/dist/assets/js/settings-controls.js +0 -452
  58. package/dist/assets/js/tabs.js +0 -867
  59. package/dist/cli/cache-line.js +0 -31
  60. package/dist/cli/command-suggest.js +0 -39
  61. package/dist/cli/commands.js +0 -781
  62. package/dist/cli/completer.js +0 -268
  63. package/dist/cli/index.js +0 -3
  64. package/dist/cli/json-payload.js +0 -32
  65. package/dist/cli/main.js +0 -346
  66. package/dist/cli/onboarding-commands.js +0 -126
  67. package/dist/cli/plugin-commands.js +0 -38
  68. package/dist/cli/relaunch.js +0 -40
  69. package/dist/cli/repl-commands-lsp.js +0 -75
  70. package/dist/cli/repl-commands-skills.js +0 -105
  71. package/dist/cli/repl-commands.js +0 -1218
  72. package/dist/cli/repl.js +0 -1238
  73. package/dist/cli/run-result.js +0 -38
  74. package/dist/cli/security-commands.js +0 -177
  75. package/dist/cli/setup-order.js +0 -6
  76. package/dist/cli/setup-prompt.js +0 -50
  77. package/dist/cli/setup.js +0 -161
  78. package/dist/cli/web-command.js +0 -98
  79. package/dist/config/budget.js +0 -48
  80. package/dist/config/config.js +0 -345
  81. package/dist/config/defaults.js +0 -197
  82. package/dist/config/domains.js +0 -135
  83. package/dist/config/env.js +0 -46
  84. package/dist/config/experts.js +0 -17
  85. package/dist/config/index.js +0 -5
  86. package/dist/config/paths.js +0 -56
  87. package/dist/config/redact.js +0 -44
  88. package/dist/config/registry-extra.js +0 -334
  89. package/dist/config/registry.js +0 -584
  90. package/dist/config/security.js +0 -212
  91. package/dist/config/timeouts.js +0 -74
  92. package/dist/config/types.js +0 -1
  93. package/dist/config/utils.js +0 -57
  94. package/dist/core/agent/artifact-progress.js +0 -59
  95. package/dist/core/agent/artifact-resolve.js +0 -79
  96. package/dist/core/agent/audit-gate.js +0 -53
  97. package/dist/core/agent/compaction.js +0 -89
  98. package/dist/core/agent/constants.js +0 -90
  99. package/dist/core/agent/context-log.js +0 -454
  100. package/dist/core/agent/context-renderer.js +0 -45
  101. package/dist/core/agent/critic-gate.js +0 -132
  102. package/dist/core/agent/hallucination-gate.js +0 -197
  103. package/dist/core/agent/loop-state.js +0 -68
  104. package/dist/core/agent/prefix-monitor.js +0 -101
  105. package/dist/core/agent/reasoning-resolver.js +0 -65
  106. package/dist/core/agent/token-tracker.js +0 -99
  107. package/dist/core/agent/tool-batch.js +0 -312
  108. package/dist/core/agent/tool-images.js +0 -18
  109. package/dist/core/agent/tool-output.js +0 -116
  110. package/dist/core/agent/tool-pairing.js +0 -60
  111. package/dist/core/agent-moe.js +0 -248
  112. package/dist/core/agent.js +0 -1299
  113. package/dist/core/bootstrap/agent-phase.js +0 -66
  114. package/dist/core/bootstrap/config-phase.js +0 -86
  115. package/dist/core/bootstrap/modules-phase.js +0 -269
  116. package/dist/core/bootstrap/provider-phase.js +0 -183
  117. package/dist/core/bootstrap/session-phase.js +0 -204
  118. package/dist/core/bootstrap/state.js +0 -94
  119. package/dist/core/bootstrap/workspace-phase.js +0 -115
  120. package/dist/core/bootstrap.js +0 -112
  121. package/dist/core/crash-handler.js +0 -62
  122. package/dist/core/environment.js +0 -224
  123. package/dist/core/host-plan.js +0 -43
  124. package/dist/core/host.js +0 -23
  125. package/dist/core/index.js +0 -3
  126. package/dist/core/prompt-builder.js +0 -95
  127. package/dist/core/prompt-overflow.js +0 -306
  128. package/dist/core/session-logger.js +0 -375
  129. package/dist/core/system-prompt.js +0 -117
  130. package/dist/core/types.js +0 -1
  131. package/dist/core/version.js +0 -28
  132. package/dist/core/web-host.js +0 -34
  133. package/dist/core/workspace.js +0 -80
  134. package/dist/i18n/index.js +0 -80
  135. package/dist/index.js +0 -30
  136. package/dist/llm/cache-usage.js +0 -76
  137. package/dist/llm/image-utils.js +0 -138
  138. package/dist/llm/index.js +0 -4
  139. package/dist/llm/llm-errors.js +0 -50
  140. package/dist/llm/model-loader.js +0 -86
  141. package/dist/llm/models-dev.js +0 -121
  142. package/dist/llm/openai-compat.js +0 -756
  143. package/dist/llm/orchestrator.js +0 -294
  144. package/dist/llm/provider-budget.js +0 -68
  145. package/dist/llm/provider-context.js +0 -233
  146. package/dist/llm/provider.js +0 -9
  147. package/dist/llm/response.js +0 -44
  148. package/dist/llm/stream-state.js +0 -26
  149. package/dist/llm/token-counter.js +0 -83
  150. package/dist/llm/types.js +0 -1
  151. package/dist/logger/app-logger.js +0 -212
  152. package/dist/logger/file-log.js +0 -160
  153. package/dist/logger/index.js +0 -2
  154. package/dist/migration/backup.js +0 -56
  155. package/dist/migration/detect.js +0 -61
  156. package/dist/migration/index.js +0 -3
  157. package/dist/modules/artifacts/store.js +0 -62
  158. package/dist/modules/browser/actions.js +0 -79
  159. package/dist/modules/browser/bridge-client.js +0 -203
  160. package/dist/modules/browser/bridge-path.js +0 -10
  161. package/dist/modules/browser/console-buffer.js +0 -37
  162. package/dist/modules/browser/cookie-store.js +0 -29
  163. package/dist/modules/browser/driver-types.js +0 -1
  164. package/dist/modules/browser/driver.js +0 -186
  165. package/dist/modules/browser/index.js +0 -9
  166. package/dist/modules/browser/module.js +0 -30
  167. package/dist/modules/browser/session.js +0 -322
  168. package/dist/modules/browser/snapshot.js +0 -154
  169. package/dist/modules/browser/types.js +0 -13
  170. package/dist/modules/certification/cli.js +0 -264
  171. package/dist/modules/certification/fact-checker.js +0 -90
  172. package/dist/modules/certification/loader.js +0 -127
  173. package/dist/modules/certification/manifest.js +0 -231
  174. package/dist/modules/certification/runner.js +0 -233
  175. package/dist/modules/certification/scenarios.js +0 -586
  176. package/dist/modules/certification/syntax-scenarios.js +0 -50
  177. package/dist/modules/certification/types.js +0 -1
  178. package/dist/modules/context/chunk-query.js +0 -122
  179. package/dist/modules/context/fact-extractor.js +0 -170
  180. package/dist/modules/context/history.js +0 -15
  181. package/dist/modules/context/index.js +0 -2
  182. package/dist/modules/context/manager.js +0 -482
  183. package/dist/modules/critic/client.js +0 -176
  184. package/dist/modules/critic/evidence.js +0 -81
  185. package/dist/modules/critic/provider.js +0 -45
  186. package/dist/modules/critic/tools.js +0 -78
  187. package/dist/modules/critic/types.js +0 -1
  188. package/dist/modules/execution/audit-runners.js +0 -206
  189. package/dist/modules/execution/auditor.js +0 -222
  190. package/dist/modules/execution/execution-plugin.js +0 -478
  191. package/dist/modules/execution/index.js +0 -8
  192. package/dist/modules/execution/input-from.js +0 -70
  193. package/dist/modules/execution/module.js +0 -891
  194. package/dist/modules/execution/moe-executor.js +0 -443
  195. package/dist/modules/execution/plan-actions.js +0 -642
  196. package/dist/modules/execution/plan-checks.js +0 -35
  197. package/dist/modules/execution/plan-coverage.js +0 -71
  198. package/dist/modules/execution/plan-persister.js +0 -46
  199. package/dist/modules/execution/plan-steps.js +0 -31
  200. package/dist/modules/execution/plan-store.js +0 -274
  201. package/dist/modules/execution/plan-tool.js +0 -249
  202. package/dist/modules/execution/plan-validator.js +0 -197
  203. package/dist/modules/execution/planner.js +0 -103
  204. package/dist/modules/execution/stuck-detector.js +0 -834
  205. package/dist/modules/execution/tracker.js +0 -92
  206. package/dist/modules/execution/transient-error.js +0 -30
  207. package/dist/modules/execution/types.js +0 -1
  208. package/dist/modules/execution/verifier.js +0 -343
  209. package/dist/modules/execution/windows-commands.js +0 -52
  210. package/dist/modules/hallucination/artifact-claim.js +0 -93
  211. package/dist/modules/hallucination/confidence.js +0 -81
  212. package/dist/modules/hallucination/consistency.js +0 -37
  213. package/dist/modules/hallucination/detector.js +0 -57
  214. package/dist/modules/hallucination/factual.js +0 -205
  215. package/dist/modules/hallucination/index.js +0 -6
  216. package/dist/modules/hallucination/js-identifiers.js +0 -261
  217. package/dist/modules/hallucination/llm-judge.js +0 -116
  218. package/dist/modules/hallucination/success-claim.js +0 -59
  219. package/dist/modules/index.js +0 -5
  220. package/dist/modules/indexer/cache.js +0 -88
  221. package/dist/modules/indexer/index.js +0 -4
  222. package/dist/modules/indexer/map-command.js +0 -33
  223. package/dist/modules/indexer/map-select.js +0 -87
  224. package/dist/modules/indexer/module.js +0 -293
  225. package/dist/modules/indexer/project-profile.js +0 -184
  226. package/dist/modules/indexer/symbols.js +0 -189
  227. package/dist/modules/indexer/walker.js +0 -285
  228. package/dist/modules/lsp/check-tool.js +0 -61
  229. package/dist/modules/lsp/client.js +0 -406
  230. package/dist/modules/lsp/command.js +0 -53
  231. package/dist/modules/lsp/config.js +0 -189
  232. package/dist/modules/lsp/index.js +0 -4
  233. package/dist/modules/lsp/module.js +0 -295
  234. package/dist/modules/lsp/probe.js +0 -86
  235. package/dist/modules/lsp/project-root.js +0 -69
  236. package/dist/modules/lsp/startup-check.js +0 -154
  237. package/dist/modules/lsp/types.js +0 -1
  238. package/dist/modules/mcp/client.js +0 -445
  239. package/dist/modules/mcp/index.js +0 -4
  240. package/dist/modules/mcp/module.js +0 -295
  241. package/dist/modules/mcp/registry.js +0 -20
  242. package/dist/modules/memory/index.js +0 -2
  243. package/dist/modules/memory/module.js +0 -101
  244. package/dist/modules/memory/search.js +0 -45
  245. package/dist/modules/memory/store.js +0 -107
  246. package/dist/modules/onboarding/init.js +0 -47
  247. package/dist/modules/onboarding/meet.js +0 -30
  248. package/dist/modules/onboarding/mode.js +0 -30
  249. package/dist/modules/onboarding/prompts.js +0 -43
  250. package/dist/modules/pipelines/engine.js +0 -70
  251. package/dist/modules/pipelines/index.js +0 -4
  252. package/dist/modules/pipelines/parser.js +0 -59
  253. package/dist/modules/pipelines/template.js +0 -18
  254. package/dist/modules/plugins/builtin/lint-on-write.js +0 -377
  255. package/dist/modules/plugins/builtin/notify.js +0 -11
  256. package/dist/modules/plugins/index.js +0 -2
  257. package/dist/modules/plugins/loader.js +0 -85
  258. package/dist/modules/plugins/manager.js +0 -244
  259. package/dist/modules/plugins/types.js +0 -1
  260. package/dist/modules/pricing/index.js +0 -70
  261. package/dist/modules/pricing/prices.js +0 -147
  262. package/dist/modules/processes/detect.js +0 -34
  263. package/dist/modules/processes/index.js +0 -4
  264. package/dist/modules/processes/kill-tree.js +0 -52
  265. package/dist/modules/processes/registry.js +0 -294
  266. package/dist/modules/processes/runner.js +0 -23
  267. package/dist/modules/providers/cache.js +0 -23
  268. package/dist/modules/providers/capabilities.js +0 -28
  269. package/dist/modules/providers/create.js +0 -21
  270. package/dist/modules/providers/factory.js +0 -28
  271. package/dist/modules/providers/fallback.js +0 -81
  272. package/dist/modules/providers/health.js +0 -47
  273. package/dist/modules/providers/index.js +0 -6
  274. package/dist/modules/providers/manager.js +0 -207
  275. package/dist/modules/providers/naming.js +0 -15
  276. package/dist/modules/providers/preflight.js +0 -71
  277. package/dist/modules/providers/presets.js +0 -232
  278. package/dist/modules/providers/registry.js +0 -27
  279. package/dist/modules/providers/types.js +0 -1
  280. package/dist/modules/reasoning/policy.js +0 -42
  281. package/dist/modules/reasoning/probe.js +0 -116
  282. package/dist/modules/registry.js +0 -48
  283. package/dist/modules/security/audit-log.js +0 -119
  284. package/dist/modules/security/audit-notifier.js +0 -267
  285. package/dist/modules/security/command-validator.js +0 -272
  286. package/dist/modules/security/content-scanner.js +0 -53
  287. package/dist/modules/security/data-sanitizer.js +0 -82
  288. package/dist/modules/security/encryption.js +0 -216
  289. package/dist/modules/security/index.js +0 -15
  290. package/dist/modules/security/network-validator.js +0 -236
  291. package/dist/modules/security/path-validator.js +0 -261
  292. package/dist/modules/security/protected-paths.js +0 -73
  293. package/dist/modules/security/rate-limiter.js +0 -98
  294. package/dist/modules/security/security-policies.js +0 -499
  295. package/dist/modules/security/session-encryption.js +0 -182
  296. package/dist/modules/security/session-isolation.js +0 -75
  297. package/dist/modules/session/auto-name.js +0 -63
  298. package/dist/modules/session/export.js +0 -98
  299. package/dist/modules/session/index.js +0 -4
  300. package/dist/modules/session/manager.js +0 -234
  301. package/dist/modules/session/module.js +0 -33
  302. package/dist/modules/session/store.js +0 -295
  303. package/dist/modules/session/types.js +0 -1
  304. package/dist/modules/setup/answers.js +0 -35
  305. package/dist/modules/setup/apply.js +0 -79
  306. package/dist/modules/setup/discovery.js +0 -72
  307. package/dist/modules/skills/index.js +0 -3
  308. package/dist/modules/skills/loader.js +0 -86
  309. package/dist/modules/skills/matcher.js +0 -27
  310. package/dist/modules/skills/module.js +0 -141
  311. package/dist/modules/types.js +0 -1
  312. package/dist/modules/updater/changelog-reader.js +0 -93
  313. package/dist/modules/updater/checker.js +0 -101
  314. package/dist/modules/updater/dev-detect.js +0 -18
  315. package/dist/modules/updater/index.js +0 -4
  316. package/dist/modules/updater/module.js +0 -129
  317. package/dist/modules/user-profile/compressor.js +0 -18
  318. package/dist/modules/user-profile/index.js +0 -2
  319. package/dist/modules/user-profile/profile.js +0 -77
  320. package/dist/modules/webui/answer-api.js +0 -29
  321. package/dist/modules/webui/assets.js +0 -50
  322. package/dist/modules/webui/body.js +0 -21
  323. package/dist/modules/webui/commands-settings.js +0 -209
  324. package/dist/modules/webui/commands-shared.js +0 -60
  325. package/dist/modules/webui/commands.js +0 -174
  326. package/dist/modules/webui/config-api.js +0 -134
  327. package/dist/modules/webui/file-api.js +0 -202
  328. package/dist/modules/webui/forward.js +0 -159
  329. package/dist/modules/webui/history-api.js +0 -112
  330. package/dist/modules/webui/host-state.js +0 -60
  331. package/dist/modules/webui/i18n-api.js +0 -9
  332. package/dist/modules/webui/limits.js +0 -6
  333. package/dist/modules/webui/log-forward.js +0 -20
  334. package/dist/modules/webui/memory-commands.js +0 -64
  335. package/dist/modules/webui/model-cache.js +0 -18
  336. package/dist/modules/webui/module.js +0 -148
  337. package/dist/modules/webui/persist.js +0 -24
  338. package/dist/modules/webui/prompt-io.js +0 -97
  339. package/dist/modules/webui/providers-api.js +0 -337
  340. package/dist/modules/webui/providers-view.js +0 -56
  341. package/dist/modules/webui/reasoning-view.js +0 -15
  342. package/dist/modules/webui/run-agent.js +0 -81
  343. package/dist/modules/webui/server.js +0 -284
  344. package/dist/modules/webui/sessions-api.js +0 -178
  345. package/dist/modules/webui/settings-api.js +0 -561
  346. package/dist/modules/webui/setup-api.js +0 -201
  347. package/dist/modules/webui/state.js +0 -74
  348. package/dist/modules/webui/util.js +0 -261
  349. package/dist/output/bus.js +0 -37
  350. package/dist/output/channel.js +0 -285
  351. package/dist/output/format.js +0 -15
  352. package/dist/output/index.js +0 -8
  353. package/dist/output/json-sink.js +0 -24
  354. package/dist/output/machine.js +0 -9
  355. package/dist/output/session-sink.js +0 -27
  356. package/dist/output/types.js +0 -1
  357. package/dist/tools/approve.js +0 -41
  358. package/dist/tools/attach-image.js +0 -102
  359. package/dist/tools/auto-fixer.js +0 -180
  360. package/dist/tools/auto-tags.js +0 -83
  361. package/dist/tools/bash.js +0 -649
  362. package/dist/tools/browser.js +0 -160
  363. package/dist/tools/chunk-query.js +0 -112
  364. package/dist/tools/create-dir.js +0 -60
  365. package/dist/tools/delete-file.js +0 -67
  366. package/dist/tools/download-file.js +0 -142
  367. package/dist/tools/edit-file.js +0 -136
  368. package/dist/tools/enable-tools.js +0 -59
  369. package/dist/tools/executor.js +0 -304
  370. package/dist/tools/file-info.js +0 -49
  371. package/dist/tools/filter-tools.js +0 -17
  372. package/dist/tools/glob-tool.js +0 -37
  373. package/dist/tools/grep-tool.js +0 -142
  374. package/dist/tools/hidden-tools-block.js +0 -37
  375. package/dist/tools/index.js +0 -88
  376. package/dist/tools/list-dir.js +0 -53
  377. package/dist/tools/load-skill.js +0 -51
  378. package/dist/tools/mcp-call.js +0 -80
  379. package/dist/tools/meet-done.js +0 -14
  380. package/dist/tools/move-file.js +0 -94
  381. package/dist/tools/path-utils.js +0 -108
  382. package/dist/tools/pipeline-run.js +0 -167
  383. package/dist/tools/preview.js +0 -2
  384. package/dist/tools/process-ids.js +0 -31
  385. package/dist/tools/process-kill.js +0 -33
  386. package/dist/tools/process-list.js +0 -38
  387. package/dist/tools/process-log.js +0 -49
  388. package/dist/tools/process-wait.js +0 -63
  389. package/dist/tools/prompt-io.js +0 -29
  390. package/dist/tools/question.js +0 -288
  391. package/dist/tools/read-file.js +0 -200
  392. package/dist/tools/recall.js +0 -124
  393. package/dist/tools/registry.js +0 -48
  394. package/dist/tools/remember.js +0 -72
  395. package/dist/tools/scope-check.js +0 -32
  396. package/dist/tools/scope-request.js +0 -96
  397. package/dist/tools/search-history.js +0 -88
  398. package/dist/tools/session-info.js +0 -46
  399. package/dist/tools/set-thinking.js +0 -75
  400. package/dist/tools/subagent.js +0 -257
  401. package/dist/tools/syntax-validator.js +0 -379
  402. package/dist/tools/types.js +0 -1
  403. package/dist/tools/user-input.js +0 -134
  404. package/dist/tools/web-browse.js +0 -93
  405. package/dist/tools/web-fetch.js +0 -108
  406. package/dist/tools/web-search.js +0 -107
  407. package/dist/tools/write-file.js +0 -128
  408. package/dist/ui/action-log.js +0 -13
  409. package/dist/ui/box.js +0 -78
  410. package/dist/ui/colors.js +0 -6
  411. package/dist/ui/diff.js +0 -189
  412. package/dist/ui/index.js +0 -7
  413. package/dist/ui/line-editor.js +0 -1083
  414. package/dist/ui/line-math.js +0 -98
  415. package/dist/ui/md-formatter.js +0 -322
  416. package/dist/ui/output.js +0 -19
  417. package/dist/ui/plan-view.js +0 -109
  418. package/dist/ui/renderer.js +0 -589
  419. package/dist/ui/spinner.js +0 -91
  420. package/dist/ui/table.js +0 -142
  421. package/dist/ui/theme.js +0 -143
  422. package/dist/utils/child-run.js +0 -20
  423. package/dist/utils/error.js +0 -4
  424. package/dist/utils/index.js +0 -6
  425. package/dist/utils/retry.js +0 -17
  426. package/dist/utils/sleep.js +0 -23
  427. package/dist/utils/truncate.js +0 -9
package/dist/cli/repl.js DELETED
@@ -1,1238 +0,0 @@
1
- // Интерактивный REPL: ввод, прогоны агента, slash-команды, баннер, история.
2
- import * as readline from "readline";
3
- import { pc } from "../ui/colors";
4
- import { LineEditor } from "../ui/line-editor";
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
6
- import { dirname, join } from "path";
7
- import { homedir } from "os";
8
- import { Completer, SlashCommandProvider, SessionNameProvider, SubcommandProvider, SkillNameProvider, ProviderArgProvider, ModelArgProvider, FilePathProvider, ConfigKeyProvider, ConfigValueProvider, FlagProvider, CommandArgProvider, buildSlashCompletions, } from "./completer";
9
- import { Renderer } from "../ui/renderer";
10
- import { resolveVerbosity, glyph, toolAccent } from "../ui/theme";
11
- import { getLastAction } from "../ui/action-log";
12
- import { divider } from "../ui/box";
13
- import { t } from "../i18n/index";
14
- import { createHostBridge } from "../core/host";
15
- import { planSnapshotFromModule, adaptActivePlan } from "../core/host-plan";
16
- import { registerAllCommands } from "./repl-commands";
17
- import { captureConfigSnapshot } from "../config/registry";
18
- import { activeProviderEndpoint } from "../modules/providers/manager";
19
- import { probeLspServers } from "../modules/lsp/probe";
20
- import { FileOnlyLogger } from "../modules/lsp/client";
21
- import { DEFAULT_LSP_CONFIG } from "../modules/lsp/config";
22
- import { errMsg } from "../utils";
23
- import { SessionLogger } from "../core/session-logger";
24
- import { exitMeetMode } from "../modules/onboarding/mode";
25
- import { formatPlanChecklist, stepContextForTool } from "../ui/plan-view";
26
- import { formatCost } from "../modules/pricing/prices";
27
- import { formatCacheLine } from "./cache-line";
28
- import { probeProviders, targetsFromProviders } from "../modules/providers/health";
29
- import { formatWarning } from "../ui/md-formatter";
30
- import { defaultOutputBus, getDefaultChannel, SessionOutputSink, writeNonTtyLine, } from "../output";
31
- import { createPromptIO } from "../tools/prompt-io";
32
- import { MMA_DIR_NAME, projectMmaDir } from "../config/paths";
33
- import { MMA_ENV, readEnv } from "../config/env";
34
- /** Рендерит бар использования контекста с компакциями и качеством. */
35
- function formatContextBar(used, limit, compactions, quality) {
36
- const pct = Math.min(100, Math.round((used / limit) * 100));
37
- const barLen = 20;
38
- const filled = Math.round((pct / 100) * barLen);
39
- const bar = pc.green("█".repeat(filled)) + pc.dim("░".repeat(barLen - filled));
40
- const pctStr = pct >= 75 ? pc.yellow(`${pct}%`) : pc.dim(`${pct}%`);
41
- let line = ` ${bar} ${pctStr} ${pc.dim(`(${used} / ${limit} tokens)`)}`;
42
- if (compactions !== undefined) {
43
- line += pc.dim(` compactions: ${compactions}`);
44
- }
45
- if (quality !== undefined) {
46
- const qColor = quality >= 70 ? pc.green : quality >= 40 ? pc.yellow : pc.red;
47
- line += ` ${qColor(`quality: ${quality}%`)}`;
48
- }
49
- return line;
50
- }
51
- export { createHostBridge };
52
- /** Интерактивный REPL терминала: владеет stdin, гоняет ходы агента, slash-команды. */
53
- export class Repl {
54
- /** Глобальный SIGINT-хендлер, общий на все инстансы Repl (см. registerSigint). */
55
- static sigintHandler;
56
- completer = new Completer();
57
- modelCache = [];
58
- /** Boot-снапшот управляемых ключей: `/config reset` откатывает из него. */
59
- configSnapshot = new Map();
60
- running = false;
61
- agentRunning = false;
62
- inputLocked = false;
63
- historyPath;
64
- history = [];
65
- maxHistory = 1000;
66
- lastEscTime = 0;
67
- doubleEscDelay = 500;
68
- configDir;
69
- baseDir;
70
- noAgentsMd;
71
- pendingClipboardImage = null;
72
- exitOnClose = false;
73
- /** Владелец состояния плана (bootstrap). В тестах null — план-UI деградирует. */
74
- execModule;
75
- /**
76
- * True, лишь когда кадр промпта ввода реально на экране. Промпт-синк канала
77
- * неактивен до тех пор, чтобы стартовый баннер печатался plain, а не стирал/
78
- * перерисовывал никогда не рисованный кадр.
79
- */
80
- promptPresented = false;
81
- /**
82
- * Ставит `runAgent`, чтобы slash-путь знал: прогон уже вернул промпт и второй
83
- * раз его показывать нельзя (напр. `/run`).
84
- */
85
- runHandledPrompt = false;
86
- rl;
87
- agent;
88
- config;
89
- sessionManager;
90
- skillsModule;
91
- pluginManager;
92
- logger;
93
- slog;
94
- /**
95
- * Расшаренный инстанс HostBridge (для плагинов; заодно движок `Host`-поверхности).
96
- * Лениво строится, если PluginManager не аттачили.
97
- */
98
- hostBridge;
99
- /**
100
- * Персистит события вывода с `data.persist === true` в активную сессию.
101
- * Инертен, пока нет SessionManager; перепривязывается через `/reload`.
102
- */
103
- sessionOutput;
104
- envReport;
105
- /** Фоновый пробник реально загруженного контекста модели (bootstrap). */
106
- contextProbe;
107
- /**
108
- * Единый писатель терминала этого REPL. Публичен (не private), потому что
109
- * `ReplContext` отдаёт его slash-командам как `ctx.output`; private-поле не
110
- * удовлетворило бы публичному свойству интерфейса.
111
- */
112
- output;
113
- /** Мост, дающий каналу рисовать поверх живого кадра ввода. */
114
- promptSink;
115
- /** PromptIO с осознанием терминала, ставится на экзекутор тулов агента. */
116
- promptIO;
117
- get toolCtx() {
118
- return this.agent.toolContext;
119
- }
120
- constructor(agent, config, sessionManager, skillsModule, pluginManager, configDir, baseDir, noAgentsMd, logger, exitOnClose, envReport, historyPath, execModule, contextProbe, output) {
121
- this.agent = agent;
122
- this.config = config;
123
- this.exitOnClose = exitOnClose === true;
124
- this.sessionManager = sessionManager;
125
- this.skillsModule = skillsModule;
126
- this.pluginManager = pluginManager;
127
- this.logger = logger;
128
- this.envReport = envReport;
129
- this.contextProbe = contextProbe;
130
- this.execModule = execModule;
131
- this.slog = new SessionLogger(sessionManager, logger);
132
- this.bindSessionOutput();
133
- this.configDir = configDir || join(homedir(), MMA_DIR_NAME);
134
- this.baseDir = baseDir || process.cwd();
135
- this.noAgentsMd = noAgentsMd === true;
136
- this.historyPath = historyPath ?? join(homedir(), ".mma", "repl-history");
137
- this.loadHistory();
138
- const editorCompleter = (line) => {
139
- const [matches, partial] = this.completer.complete(line);
140
- if (matches.length > 0)
141
- return [matches, partial];
142
- return [[], line];
143
- };
144
- // Комплитер node-readline понимает только plain-строковые совпадения.
145
- const readlineCompleter = (line) => {
146
- const [items, partial] = editorCompleter(line);
147
- return [items.map((i) => i.value), partial];
148
- };
149
- if (process.stdin.isTTY) {
150
- this.rl = new LineEditor({
151
- input: process.stdin,
152
- output: process.stdout,
153
- prompt: this.inputPrompt(),
154
- history: this.history,
155
- historySize: this.maxHistory,
156
- completer: editorCompleter,
157
- });
158
- }
159
- else {
160
- this.rl = readline.createInterface({
161
- input: process.stdin,
162
- output: process.stdout,
163
- prompt: this.inputPrompt(),
164
- history: this.history,
165
- historySize: this.maxHistory,
166
- tabSize: 2,
167
- completer: readlineCompleter,
168
- });
169
- }
170
- this.output = output ?? getDefaultChannel();
171
- this.promptSink = {
172
- isActive: () => this.rl instanceof LineEditor &&
173
- this.promptPresented &&
174
- !this.agentRunning &&
175
- !this.inputLocked,
176
- printAbove: (text) => {
177
- if (this.rl instanceof LineEditor) {
178
- this.rl.printAbove(text);
179
- return;
180
- }
181
- // Не-TTY фолбэк (readline / пайпнутый stdin): кадра ввода для перерисовки
182
- // сверху нет — пишем напрямую через санкционированный машинный хелпер:
183
- // `printAbove` здесь не про что.
184
- writeNonTtyLine(text);
185
- },
186
- clearScreen: () => {
187
- if (this.rl instanceof LineEditor)
188
- this.rl.clearScreen();
189
- },
190
- };
191
- this.output.attachPrompt(this.promptSink);
192
- // Промпт-поверхность с осознанием терминала для интерактивных тулов (question/approve).
193
- // stdin владеет REPL и на время прогона он в `streaming`: тулы обязаны одалживать
194
- // редактор под вопрос, а не открывать конкурирующий readline, который подерётся
195
- // с raw-режимом LineEditor.
196
- this.promptIO = createPromptIO({
197
- ask: (prompt) => this.askViaEditor(prompt),
198
- print: (line) => this.output.writeLine(line),
199
- });
200
- this.agent.setPromptIO?.(this.promptIO);
201
- registerAllCommands(this);
202
- this.configSnapshot = captureConfigSnapshot(this.config);
203
- this.setupCompleter();
204
- this.setupListeners();
205
- // Отдаём агента плагинам (web UI и др.) через узкий мост.
206
- if (pluginManager) {
207
- this.attachHostBridge(pluginManager);
208
- }
209
- }
210
- /** (Пере)аттач плагинного HostBridge. Зовётся в конструкторе и после того, как
211
- * /reload заменил PluginManager: без этого перезагруженный web-ui плагин
212
- * молча теряет способность сабмитить сообщения. */
213
- attachHostBridge(pm) {
214
- const manager = pm ?? this.pluginManager;
215
- if (!manager)
216
- return;
217
- this.hostBridge ??= this.buildHostBridge();
218
- manager.setHostBridge(this.hostBridge);
219
- }
220
- /** Единый busy-предикат для `Host`-поверхности и моста. */
221
- isAgentBusy() {
222
- return this.agentRunning;
223
- }
224
- /** Строит HostBridge поверх обычного run-пути этого REPL. */
225
- buildHostBridge() {
226
- return createHostBridge({
227
- isBusy: () => this.isAgentBusy(),
228
- addPendingImage: (url) => {
229
- this.agent.contextManager?.addPendingImage?.({
230
- type: "image_url",
231
- image_url: { url },
232
- });
233
- },
234
- runAgent: (text) => this.runAgent(text),
235
- interruptRun: () => this.agent.shutdown(),
236
- });
237
- }
238
- /** Лениво резолвит общий мост, чтобы `Host`-методы работали без плагинов. */
239
- getHostBridge() {
240
- this.hostBridge ??= this.buildHostBridge();
241
- return this.hostBridge;
242
- }
243
- /** (Пере)привязка синка вывода сессии после конструктора или `/reload`. */
244
- bindSessionOutput() {
245
- this.sessionOutput?.dispose();
246
- this.sessionOutput = this.sessionManager
247
- ? new SessionOutputSink(defaultOutputBus, this.sessionManager)
248
- : undefined;
249
- }
250
- /**
251
- * Перезагрузка агента и модулей (команда /reload). Живёт здесь, а не в
252
- * repl-commands, потому что меняет mutable-поля класса — команда через
253
- * интерфейс только вызывает `ctx.reload()`, не ломая readonly-контракт.
254
- */
255
- async reload() {
256
- const { loadConfig } = await import("../config/config");
257
- const { bootstrap } = await import("../core/bootstrap");
258
- this.agent.shutdown();
259
- const projectConfigPath = join(this.baseDir, ".mmrc");
260
- const { config: freshConfig } = loadConfig({
261
- configDir: this.configDir,
262
- projectConfigPath,
263
- });
264
- Object.assign(this.config, freshConfig);
265
- const result = await bootstrap(this.configDir, this.baseDir, false, false);
266
- this.agent = result.agent;
267
- // Переустанавливаем промпт-поверхность на свежезабутстрапленного агента: замыкание
268
- // `askViaEditor` этого REPL принадлежит всё ещё этому инстансу.
269
- this.agent.setPromptIO?.(this.promptIO);
270
- this.sessionManager = result.sessionManager;
271
- this.skillsModule = result.skillsModule;
272
- this.pluginManager = result.pluginManager;
273
- this.execModule = result.execModule;
274
- this.bindSessionOutput();
275
- // У свежего PluginManager моста нет — перерегистрируем, иначе плагины вроде
276
- // web-ui молча теряют управление агентом.
277
- this.attachHostBridge(result.pluginManager);
278
- this.setupCompleter();
279
- }
280
- /** Грузит историю ввода из файла. */
281
- loadHistory() {
282
- if (existsSync(this.historyPath)) {
283
- try {
284
- const raw = readFileSync(this.historyPath, "utf-8");
285
- this.history = raw.split("\n").filter(Boolean).slice(-this.maxHistory);
286
- }
287
- catch {
288
- this.history = [];
289
- }
290
- }
291
- }
292
- /** Сохраняет историю ввода. Падение каталога переживает молча, не бросает. */
293
- saveHistory() {
294
- try {
295
- // Каталога истории может не быть (напр. temp снесли в тесте или при teardown
296
- // сессии). Пересоздаём; сейв бросать не должен никогда.
297
- mkdirSync(dirname(this.historyPath), { recursive: true });
298
- const allHistory = this.history.slice(-this.maxHistory);
299
- writeFileSync(this.historyPath, allHistory.join("\n"), "utf-8");
300
- }
301
- catch (e) {
302
- this.logger?.debug(`Failed to save REPL history: ${e.message}`);
303
- }
304
- }
305
- /** Строит комплитер с нуля. */
306
- setupCompleter() {
307
- // Пересборка с нуля: /reload зовёт снова после bootstrap, и перерегистрация
308
- // без reset дублировала бы каждого провайдера.
309
- this.completer.reset();
310
- // `this.commands` ключуется каноническими именами И алиасами; итерация даёт
311
- // каждый дополняемый токен с описанием его команды.
312
- const slashCommands = buildSlashCompletions(this.commands);
313
- this.completer.registerProvider(new SlashCommandProvider(slashCommands));
314
- if (this.sessionManager) {
315
- this.completer.registerProvider(new SessionNameProvider(() => this.sessionManager.list().map((s) => s.name), [
316
- "/resume",
317
- "/delete",
318
- "/export",
319
- ]));
320
- }
321
- if (this.skillsModule) {
322
- this.completer.registerProvider(new SubcommandProvider("skill", [
323
- { name: "list", description: t("skill.sub_list") },
324
- { name: "loaded", description: t("skill.sub_loaded") },
325
- { name: "load", description: t("skill.sub_load") },
326
- { name: "unload", description: t("skill.sub_unload") },
327
- { name: "search", description: t("skill.sub_search") },
328
- ]));
329
- this.completer.registerProvider(new SkillNameProvider(this.skillsModule));
330
- }
331
- // Комплит субкоманд + аргументов управления provider/model.
332
- this.completer.registerProvider(new SubcommandProvider("provider", [
333
- { name: "list", description: t("provider.sub_list") },
334
- { name: "use", description: t("provider.sub_use") },
335
- { name: "add", description: t("provider.sub_add") },
336
- ]));
337
- this.completer.registerProvider(new SubcommandProvider("model", [
338
- { name: "list", description: t("model.sub_list") },
339
- { name: "use", description: t("model.sub_use") },
340
- ]));
341
- this.completer.registerProvider(new SubcommandProvider("map", [
342
- { name: "summary", description: t("map.sub_summary") },
343
- { name: "refresh", description: t("map.sub_refresh") },
344
- { name: "find", description: t("map.sub_find") },
345
- ]));
346
- this.completer.registerProvider(new SubcommandProvider("context", [
347
- { name: "system", description: t("context.sub_system") },
348
- { name: "reserve", description: t("context.sub_reserve") },
349
- ]));
350
- this.completer.registerProvider(new SubcommandProvider("lsp", [
351
- { name: "status", description: t("lsp.sub_status") },
352
- { name: "restart", description: t("lsp.sub_restart") },
353
- { name: "check", description: t("lsp.sub_check") },
354
- ]));
355
- this.completer.registerProvider(new SubcommandProvider("reasoning", [
356
- { name: "show", description: t("reasoning.sub_show") },
357
- { name: "hide", description: t("reasoning.sub_hide") },
358
- { name: "level", description: t("reasoning.sub_level") },
359
- ]));
360
- this.completer.registerProvider(new SubcommandProvider("verbose", [
361
- { name: "quiet", description: t("verbose.sub_quiet") },
362
- { name: "normal", description: t("verbose.sub_normal") },
363
- { name: "verbose", description: t("verbose.sub_verbose") },
364
- ]));
365
- this.completer.registerProvider(new SubcommandProvider("security", [
366
- { name: "status", description: t("cli.security.status") },
367
- ]));
368
- this.completer.registerProvider(new ConfigKeyProvider());
369
- this.completer.registerProvider(new ConfigValueProvider());
370
- this.completer.registerProvider(new FlagProvider());
371
- this.completer.registerProvider(new CommandArgProvider(() => Array.from(this.commands.entries())
372
- .filter(([key, cmd]) => key === cmd.name)
373
- .map(([, cmd]) => cmd.name)));
374
- const entryLabels = this.config.provider?.entries?.map((e) => e.label || e.type) ?? [];
375
- if (entryLabels.length > 0) {
376
- this.completer.registerProvider(new ProviderArgProvider(entryLabels));
377
- }
378
- this.completer.registerProvider(new ModelArgProvider(() => this.modelCache));
379
- // Комплит путей якорится на workspace агента, а не process.cwd().
380
- this.completer.registerProvider(new FilePathProvider(this.baseDir));
381
- // Греем кеш моделей фоном (бесплатный listModels-вызов).
382
- this.refreshModelCache();
383
- }
384
- /** Перестройка реестра + комплитера — после смены `/config locale`. */
385
- reregisterCommands() {
386
- this.commands.clear();
387
- registerAllCommands(this);
388
- this.setupCompleter();
389
- }
390
- /** Boot-снапшот управляемых ключей для `/config reset`. */
391
- getConfigSnapshot() {
392
- return this.configSnapshot;
393
- }
394
- /** Кешированные id моделей активного провайдера (пусто, пока офлайн). */
395
- knownModels() {
396
- return this.modelCache;
397
- }
398
- /**
399
- * Фоновое обновление кешированного списка моделей для `/model use <Tab>`.
400
- * Best-effort: при провале кеш хранит прошлое содержимое.
401
- */
402
- refreshModelCache() {
403
- void (async () => {
404
- try {
405
- const name = this.config.provider.active ||
406
- this.config.provider.entries?.[0]?.label ||
407
- this.config.provider.type;
408
- const provider = this.agent.getProviderFor(name);
409
- if (!provider)
410
- return;
411
- const models = await provider.listModels();
412
- if (models.length > 0) {
413
- this.modelCache = models.sort();
414
- }
415
- }
416
- catch {
417
- // keep previous cache
418
- }
419
- })();
420
- }
421
- setupListeners() {
422
- let multiLineBuffer = "";
423
- let inMultiLine = false;
424
- this.rl.on("line", async (line) => {
425
- const trimmed = line.trim();
426
- if (this.agentRunning || this.inputLocked) {
427
- if (trimmed) {
428
- this.history.push(trimmed);
429
- if (this.history.length > this.maxHistory) {
430
- this.history = this.history.slice(-this.maxHistory);
431
- }
432
- }
433
- return;
434
- }
435
- if (trimmed) {
436
- this.history.push(trimmed);
437
- if (this.history.length > this.maxHistory) {
438
- this.history = this.history.slice(-this.maxHistory);
439
- }
440
- }
441
- if (inMultiLine) {
442
- multiLineBuffer += `\n${line}`;
443
- if (!this.isMultiLineInput(multiLineBuffer)) {
444
- inMultiLine = false;
445
- const fullInput = multiLineBuffer.trim();
446
- multiLineBuffer = "";
447
- if (fullInput) {
448
- if (fullInput.startsWith("/")) {
449
- await this.executeCommand(fullInput);
450
- this.afterCommand();
451
- }
452
- else {
453
- await this.runAgent(fullInput);
454
- }
455
- }
456
- }
457
- else {
458
- this.rl.setPrompt(this.inputPrompt(true));
459
- this.rl.prompt();
460
- }
461
- return;
462
- }
463
- if (this.isMultiLineInput(trimmed)) {
464
- inMultiLine = true;
465
- multiLineBuffer = trimmed;
466
- this.rl.setPrompt(this.inputPrompt(true));
467
- this.rl.prompt();
468
- return;
469
- }
470
- if (!trimmed) {
471
- this.rl.setPrompt(this.inputPrompt());
472
- this.rl.prompt();
473
- return;
474
- }
475
- if (trimmed.startsWith("/")) {
476
- await this.executeCommand(trimmed);
477
- this.afterCommand();
478
- }
479
- else {
480
- await this.runAgent(trimmed);
481
- }
482
- });
483
- this.rl.on("close", () => {
484
- this.running = false;
485
- this.saveHistory();
486
- this.agent.shutdown();
487
- // Закрываем лог сессии на выходе из REPL.
488
- this.logger?.closeSessionLog();
489
- if (this.exitOnClose)
490
- process.exit(0);
491
- });
492
- if (this.exitOnClose && !process.stdin.isTTY) {
493
- process.stdin.on("end", () => {
494
- this.running = false;
495
- this.saveHistory();
496
- this.agent.shutdown();
497
- // Закрываем лог сессии на выходе из REPL.
498
- this.logger?.closeSessionLog();
499
- process.exit(0);
500
- });
501
- }
502
- if (this.rl instanceof LineEditor) {
503
- this.rl.onKeyInput = (str, key) => this.handleSpecialKey(str, key);
504
- }
505
- let forceExitTimer = null;
506
- // Запас на очистку (сессия, MCP, дочерние процессы) после второго Ctrl+C.
507
- const FORCE_EXIT_MS = 5000;
508
- // Идемпотентная регистрация: второй Repl в том же процессе не добавляет
509
- // ещё один глобальный SIGINT-хендлер. Протёкшие хендлеры инстансов REPL,
510
- // созданные в тестах, стреляли process.exit(0) на ЛЮБОЙ process.emit("SIGINT")
511
- // в другом месте и молча убивали весь bun-раннер тестов.
512
- if (typeof Repl.sigintHandler === "function") {
513
- process.removeListener("SIGINT", Repl.sigintHandler);
514
- }
515
- Repl.sigintHandler = () => {
516
- if (this.agentRunning) {
517
- this.output.writeLine(pc.yellow(t("repl.ctrl_c_interrupt")));
518
- this.agent.shutdown();
519
- this.agentRunning = false;
520
- if (forceExitTimer)
521
- clearTimeout(forceExitTimer);
522
- forceExitTimer = setTimeout(() => {
523
- this.output.writeLine(pc.yellow(t("repl.force_exit")));
524
- process.exit(1);
525
- }, FORCE_EXIT_MS).unref();
526
- }
527
- else {
528
- process.exit(0);
529
- }
530
- };
531
- process.on("SIGINT", Repl.sigintHandler);
532
- }
533
- /**
534
- * Перепоказ промпта ввода после slash-команды. У команд нет владения жизненным
535
- * циклом кадра, им нужна явная перерисовка. Путь агента осознанно исключён:
536
- * finally `runAgent` зовёт `LineEditor.resumeFrame()` как единственный показ —
537
- * промпт здесь дал бы двойную отрисовку.
538
- */
539
- presentPrompt() {
540
- if (!this.running)
541
- return;
542
- this.rl.setPrompt(this.inputPrompt());
543
- this.rl.prompt();
544
- this.promptPresented = true;
545
- }
546
- /** Возврат обычного промпта после стартового вопроса, если активен LineEditor. */
547
- restoreStartupPrompt() {
548
- if (this.rl instanceof LineEditor) {
549
- this.rl.setPrompt(this.inputPrompt());
550
- this.rl.prompt();
551
- this.promptPresented = true;
552
- }
553
- }
554
- /**
555
- * Ярлык reasoning в промпте ввода. В `auto` эффективный уровень обычно решает
556
- * политика поитерационно, так что показываем лишь факт автоматики. При явном
557
- * оверрайде юзера (`/reasoning <level>`, персистентный) или активном
558
- * `set_thinking`-оверрайде агента (транзиентный) — `auto→<level>`. В фикс.
559
- * режиме — эффективный уровень.
560
- */
561
- reasoningLabel() {
562
- const mode = this.config.reasoning?.mode ?? "default";
563
- if (mode !== "auto")
564
- return this.agent.reasoningLevel ?? mode;
565
- const rs = this.agent.reasoningState;
566
- const cooldown = this.config.reasoning?.overrideCooldown ?? 0;
567
- const transientActive = rs.overrideIteration >= 0 && this.agent.currentIteration - rs.overrideIteration <= cooldown;
568
- if (rs.manual || transientActive)
569
- return `auto→${this.agent.reasoningLevel}`;
570
- return "auto";
571
- }
572
- /** Локализованный промпт ввода со встроенным режимом/уровнем reasoning. */
573
- inputPrompt(continuation = false) {
574
- const key = continuation ? "repl.you_reasoning_cont" : "repl.you_reasoning";
575
- return pc.cyan(t(key, { level: this.reasoningLabel() }));
576
- }
577
- /**
578
- * Учёт промпта после slash-команды. Команда, прогнавшая прогон (напр. `/run`),
579
- * уже вернула себе промпт через `runAgent`: повторный показ двоил бы рендер,
580
- * так что скипаем ровно раз. Все прочие команды показывают промпт здесь.
581
- */
582
- afterCommand() {
583
- if (this.runHandledPrompt) {
584
- this.runHandledPrompt = false;
585
- return;
586
- }
587
- this.presentPrompt();
588
- }
589
- /** Спецклавиши: двойной Esc — аборт прогона, Ctrl+V — вставка картинки, Ctrl+O — детали. */
590
- handleSpecialKey(_str, key) {
591
- if (key.name === "escape") {
592
- // Декодер keypress Bun схлопывает быстрый двойной Esc в один keypress, чей
593
- // `sequence` содержит два ESC-байта ("\x1b\x1b"). Подсчёт байтов (не событий)
594
- // ловит и схлопнутый случай, и два раздельных Esc в окне.
595
- const escBytes = key.sequence ? (key.sequence.match(/\x1b/g) || []).length : 1;
596
- const now = Date.now();
597
- const withinWindow = now - this.lastEscTime < this.doubleEscDelay;
598
- this.lastEscTime = now;
599
- if (escBytes >= 2 || withinWindow) {
600
- this.lastEscTime = 0;
601
- if (this.agentRunning) {
602
- this.output.writeLine(pc.yellow(`\n${t("repl.interrupt")}`));
603
- this.agent.shutdown();
604
- }
605
- }
606
- return true;
607
- }
608
- if (key.ctrl && key.name === "v" && !this.agentRunning) {
609
- this.pasteClipboardImage();
610
- return true;
611
- }
612
- if (key.ctrl && key.name === "o" && !this.agentRunning) {
613
- this.reprintLastAction();
614
- return true;
615
- }
616
- return false;
617
- }
618
- /** Ctrl+O — допечатка полных деталей последнего действия. */
619
- reprintLastAction() {
620
- const last = getLastAction();
621
- if (!last) {
622
- this.output.writeLine(pc.dim(t("repl.last_action_none")));
623
- return;
624
- }
625
- const mark = last.status === "error"
626
- ? pc.red(glyph.failure)
627
- : last.status === "warn"
628
- ? pc.yellow(glyph.warning)
629
- : pc.green(glyph.success);
630
- const accent = toolAccent(last.tool);
631
- const head = `${accent(glyph.action)} ${accent(last.label)}${last.args ? ` ${pc.dim("·")} ${pc.dim(last.args)}` : ""} ${mark} ${pc.dim(`${last.durationMs}ms`)}`;
632
- const lines = [head, ...last.body.map((l) => ` ${l}`)];
633
- this.output.writeLine(`\n${lines.join("\n")}`);
634
- if (this.rl instanceof LineEditor) {
635
- this.rl.reset();
636
- this.rl.prompt();
637
- }
638
- }
639
- /** Вставка картинки из буфера обмена (Ctrl+V). */
640
- async pasteClipboardImage() {
641
- try {
642
- const { readClipboardImage, bufferToDataUrl } = await import("../llm/image-utils");
643
- const clipBuf = await readClipboardImage();
644
- if (clipBuf) {
645
- const { dataUrl } = await bufferToDataUrl(clipBuf);
646
- this.pendingClipboardImage = dataUrl;
647
- const sizeKb = Math.round((dataUrl.length * 3) / 4 / 1024);
648
- this.output.writeLine(pc.green(`\n${t("image.attached", { source: "clipboard", size: `${sizeKb} KB` })}`));
649
- if (this.rl instanceof LineEditor)
650
- this.rl.reset();
651
- this.rl.prompt();
652
- }
653
- else {
654
- this.output.writeLine(pc.yellow(`\n${t("image.clipboard_empty")}`));
655
- if (this.rl instanceof LineEditor)
656
- this.rl.reset();
657
- this.rl.prompt();
658
- }
659
- }
660
- catch {
661
- // Чтение буфера не удалось — игнорим, пусть терминал вставит текст штатно.
662
- }
663
- }
664
- /** Проверка незакрытого многострочного ввода (хвостовой `\` или `{` без `}`). */
665
- isMultiLineInput(line) {
666
- if (line.endsWith("\\"))
667
- return true;
668
- const openBraces = (line.match(/\{/g) || []).length;
669
- const closeBraces = (line.match(/\}/g) || []).length;
670
- if (openBraces > closeBraces)
671
- return true;
672
- return false;
673
- }
674
- /** Прогон хода агента: стрим в рендерер, футер, бары, возврат промпта. */
675
- async runAgent(input) {
676
- if (this.agentRunning)
677
- return;
678
- this.agentRunning = true;
679
- try {
680
- if (this.pendingClipboardImage) {
681
- const contextManager = this.agent.contextManager;
682
- if (contextManager) {
683
- contextManager.addPendingImage({
684
- type: "image_url",
685
- image_url: { url: this.pendingClipboardImage },
686
- });
687
- }
688
- this.pendingClipboardImage = null;
689
- }
690
- this.logger?.logREPL("user", input);
691
- // Кадр промпта сейчас снимется; гасим синк до любого стримленного вывода,
692
- // чтобы ничего не пыталось рисовать поверх него.
693
- this.promptPresented = false;
694
- // Отдаём терминал каналу на время прогона: редактор перестаёт рисовать кадр
695
- // и игнорит клавиши, и стрим не портит строку ввода. suspendFrame() идёт до
696
- // reset(), который иначе нарисовал бы кадр лишь затем, чтобы стереть.
697
- if (this.rl instanceof LineEditor) {
698
- this.rl.suspendFrame();
699
- this.rl.setInputEnabled(false);
700
- this.rl.reset();
701
- }
702
- this.output.beginStreaming();
703
- // Разделитель + ярлык агента, сырьём (без trailing newline): следующий чанк
704
- // Renderer.text() добавляет свой ведущий "\n", и writeLine здесь вставил бы
705
- // пустую строку ("Agent:\n\n...").
706
- this.output.writeRaw(`\r${divider()}\n${pc.green(t("repl.agent"))}`);
707
- const renderer = new Renderer({
708
- spinner: this.config.ui?.spinner ?? true,
709
- baseDir: this.baseDir,
710
- channel: this.output,
711
- verbosity: resolveVerbosity(this.config.ui),
712
- });
713
- renderer.showLoader();
714
- const result = await this.agent.run(input, (c) => renderer.text(c), (m) => renderer.meta(m), (ev) => {
715
- if (ev.type === "start") {
716
- renderer.toolStart(ev.tool, ev.args, stepContextForTool(this.execModule?.getActivePlan() ?? null, ev.tool, ev.args), ev.icon);
717
- }
718
- else {
719
- renderer.toolEnd(ev.tool, ev.duration ?? 0, ev.error, ev.ctxDelta, ev.costUsd);
720
- if (ev.tool === "plan" || ev.tool === "todo" || ev.tool === "plan_step") {
721
- this.renderPlan(renderer);
722
- }
723
- }
724
- }, (phase) => {
725
- if (phase === "thinking") {
726
- renderer.thinkingStart();
727
- }
728
- else {
729
- renderer.thinkingEnd();
730
- }
731
- }, (reasoning) => renderer.reasoning(reasoning));
732
- renderer.flush();
733
- if (result.provider && result.model) {
734
- renderer.footer(result.model, result.provider, result.llmDurationMs ?? result.durationMs ?? 0);
735
- }
736
- this.output.writeLine("");
737
- this.logger?.logREPL(result.success ? "assistant" : "system", result.text?.slice(0, 400) || result.error || "");
738
- if (!result.success) {
739
- this.output.writeLine(pc.red(`${t("error.prefix")}${result.error}`), "stderr");
740
- }
741
- this.showContextBar(result);
742
- // Закрываем ход агента: разделитель перед следующим промптом визуально
743
- // разводит соседние сообщения юзера/агента.
744
- this.output.writeLine(`\n${divider()}`);
745
- }
746
- finally {
747
- this.agentRunning = false;
748
- this.output.endStreaming();
749
- if (this.rl instanceof LineEditor) {
750
- this.rl.setInputEnabled(true);
751
- // Единственный показ промпта на пути агента: resumeFrame() перерисовывает
752
- // кадр, так что слушатель `line` после runAgent() промпт НЕ показывает
753
- // (после slash-команд — показывает). Промпт переставляем первым, чтобы
754
- // уровень reasoning, сменённый set_thinking в прогоне, отразился на
755
- // возобновлённом кадре.
756
- this.rl.setPrompt(this.inputPrompt());
757
- this.rl.resumeFrame();
758
- this.promptPresented = true;
759
- }
760
- else {
761
- // У пайпнутого/не-TTY фолбэка кадра для resume нет; показываем readline-
762
- // промпт здесь ради старого пост-прогонного поведения.
763
- this.presentPrompt();
764
- }
765
- const onboardingCtx = this.agent.tryToolContext();
766
- if (onboardingCtx?.onboarding?.done) {
767
- exitMeetMode(this);
768
- this.slog.logOnboarding("meet_done", { model: this.config.model });
769
- this.output.writeLine(pc.dim(t("repl.meet_done")));
770
- }
771
- this.runHandledPrompt = true;
772
- }
773
- }
774
- /** Печать чеклиста плана, трекаемого ExecutionModule.
775
- * Зовётся только на plan/todo-событиях (событие изменения), не поллится:
776
- * дисковый план прошлой сессии не протечёт в чат. */
777
- renderPlan(renderer) {
778
- const plan = this.execModule?.getActivePlan();
779
- if (!plan)
780
- return;
781
- renderer.planBlock(formatPlanChecklist(plan));
782
- }
783
- commands = new Map();
784
- /** Регистрирует slash-команду (имя + алиасы). */
785
- registerCommand(cmd) {
786
- this.commands.set(cmd.name, cmd);
787
- if (cmd.aliases) {
788
- for (const alias of cmd.aliases) {
789
- this.commands.set(alias, cmd);
790
- }
791
- }
792
- }
793
- /** Эксклюзивный ввод: визард владеет терминалом через свои `rl.question()`. */
794
- async withExclusiveInput(fn) {
795
- // Между вопросами активного кадра нет, так что меню/результаты скана пишутся
796
- // напрямую: обёртка beginModal/endModal сложила бы ВЕСЬ транскрипт в очередь,
797
- // и юзер видел бы голые `: ` промпты до конца. `inputLocked` гасит
798
- // `promptSink.isActive()`, пуская записи напрямую.
799
- this.inputLocked = true;
800
- try {
801
- await fn();
802
- }
803
- finally {
804
- this.inputLocked = false;
805
- }
806
- }
807
- /**
808
- * Одалживает терминал под один вопрос интерактивного тула и возвращает обратно.
809
- * На время прогона LineEditor suspended с выключенным вводом; включение ввода +
810
- * resume кадра даёт `question()` читать клавиши, пока агент блокирован, а `finally`
811
- * восстанавливает ровно стрим-состояние, и рендерер агента работает дальше как ни в чём.
812
- *
813
- * Порядок важен: `beginModal()` сначала сбрасывает вывод, ещё буферный у стрим-канала,
814
- * чтобы напечатался plain до возврата кадра; `endModal()` идёт лишь после повторного
815
- * suspend кадра, чтобы события, накопленные за вопрос, сбросились plain, а не побили кадр.
816
- */
817
- async askViaEditor(prompt) {
818
- const editor = this.rl instanceof LineEditor ? this.rl : null;
819
- const wasSuspended = editor ? editor.isFrameSuspended() : true;
820
- const wasEnabled = editor ? editor.isInputEnabled() : false;
821
- this.output.beginModal();
822
- if (editor) {
823
- editor.setInputEnabled(true);
824
- editor.resumeFrame();
825
- }
826
- try {
827
- return await new Promise((resolve) => this.rl.question(prompt, resolve));
828
- }
829
- finally {
830
- if (editor) {
831
- editor.setInputEnabled(wasEnabled);
832
- if (wasSuspended)
833
- editor.suspendFrame();
834
- else
835
- editor.resumeFrame();
836
- }
837
- this.output.endModal();
838
- }
839
- }
840
- /** Host/HostBridge: true, пока агент крутит ход. */
841
- isBusy() {
842
- return this.isAgentBusy();
843
- }
844
- /** Host/HostBridge: сабмит через общий мост (тот же run-путь). */
845
- submit(text, opts) {
846
- return this.getHostBridge().submit(text, opts);
847
- }
848
- /** Host/HostBridge: прерывание текущего прогона (в idle — no-op). */
849
- interrupt() {
850
- this.getHostBridge().interrupt();
851
- }
852
- /** Host/HostBridge: подписка на общую шину вывода. */
853
- subscribeOutput(fn) {
854
- return defaultOutputBus.subscribe(fn);
855
- }
856
- /** Host: прогон slash-команды через ту же handler-map, что и ручной ввод. */
857
- async executeCommand(line) {
858
- const trimmed = line.trim();
859
- if (!trimmed.startsWith("/"))
860
- return;
861
- await this.dispatchCommand(trimmed);
862
- }
863
- /** Host: снапшот план/сессия/модель для UI-поверхностей. */
864
- getState() {
865
- const meta = this.sessionManager?.getActiveMeta();
866
- return {
867
- busy: this.agentRunning,
868
- sessionId: meta?.id,
869
- sessionName: meta?.name,
870
- model: this.config.model,
871
- provider: this.config.provider?.active,
872
- plan: planSnapshotFromModule(adaptActivePlan(this.execModule?.getActivePlan())),
873
- };
874
- }
875
- async dispatchCommand(input) {
876
- const parts = input.split(/\s+/);
877
- const name = parts[0].slice(1);
878
- const args = parts.slice(1);
879
- // Сбрасываем протухший run-флаг прошлого прямого прогона, чтобы решение
880
- // presentPrompt() этой команды строилось на её собственном действии.
881
- this.runHandledPrompt = false;
882
- const cmd = this.commands.get(name);
883
- if (!cmd) {
884
- // Бывшие алиасы, уехавшие в субкоманду: указываем на новый синтаксис,
885
- // а не на голое "unknown command".
886
- const formerAliases = { use: "resume" };
887
- const suggestion = formerAliases[name];
888
- if (suggestion) {
889
- this.output.writeLine(pc.red(t("cli.unknown_command", { input: `/${name}`, suggestion: `/${suggestion}` })));
890
- }
891
- else {
892
- this.output.writeLine(`${pc.red(t("cli.unknown_cmd", { name }))} ${t("cli.help_hint")}`);
893
- }
894
- return;
895
- }
896
- try {
897
- await cmd.action(args);
898
- }
899
- catch (err) {
900
- this.output.writeLine(pc.red(t("error.command_error", {
901
- message: errMsg(err),
902
- })), "stderr");
903
- }
904
- }
905
- /** Показ помощи: общая или по команде (`/help <команда>`). */
906
- showHelp(command) {
907
- const { COMMAND_GROUPS } = require("./repl-commands");
908
- if (command) {
909
- const name = command.replace(/^\//, "");
910
- const cmd = this.commands.get(name);
911
- if (!cmd) {
912
- this.output.writeLine(pc.red(t("repl.help_unknown", { name })));
913
- return;
914
- }
915
- this.output.writeLine(pc.bold(pc.cyan(`/${cmd.name}`)));
916
- this.output.writeLine(` ${cmd.description}`);
917
- if (cmd.usage)
918
- this.output.writeLine(` ${pc.dim(cmd.usage)}`);
919
- if (cmd.aliases?.length) {
920
- this.output.writeLine(pc.dim(` ${t("repl.help_aliases", { names: cmd.aliases.join(", ") })}`));
921
- }
922
- if (cmd.examples?.length) {
923
- this.output.writeLine(pc.dim(` ${t("repl.help_examples")}`));
924
- for (const ex of cmd.examples)
925
- this.output.writeLine(pc.dim(` ${ex}`));
926
- }
927
- return;
928
- }
929
- const order = ["general", "agent", "session", "skill"];
930
- const seen = new Set();
931
- for (const groupKey of order) {
932
- const cmds = [];
933
- for (const [name, cmd] of this.commands) {
934
- if (cmd.aliases?.includes(name))
935
- continue;
936
- if (seen.has(cmd.name))
937
- continue;
938
- const group = COMMAND_GROUPS[cmd.name] ?? "general";
939
- if (group !== groupKey)
940
- continue;
941
- seen.add(cmd.name);
942
- cmds.push(cmd);
943
- }
944
- if (cmds.length === 0)
945
- continue;
946
- this.output.writeLine(pc.bold(t(`repl.group.${groupKey}`)));
947
- for (const cmd of cmds) {
948
- const aliases = cmd.aliases?.length ? ` (${pc.dim(cmd.aliases.join(", "))})` : "";
949
- this.output.writeLine(` ${pc.cyan(`/${cmd.name}`)}${aliases} ${pc.dim(cmd.description)}`);
950
- if (cmd.usage) {
951
- this.output.writeLine(` ${pc.dim(cmd.usage)}`);
952
- }
953
- }
954
- this.output.writeLine("");
955
- }
956
- }
957
- lastCompactionShown = 0;
958
- showContextBar(result) {
959
- if (result.contextUsed === undefined ||
960
- result.contextLimit === undefined ||
961
- result.contextLimit <= 0) {
962
- return;
963
- }
964
- const ui = this.config.ui;
965
- if (ui?.showContextStats) {
966
- this.output.writeLine("");
967
- const ctxLine = formatContextBar(result.contextUsed, result.contextLimit, result.compactionCount, result.contextQuality);
968
- this.output.writeLine(ctxLine);
969
- if (result.totalTokens !== undefined && result.totalTokens > 0) {
970
- const apiLine = pc.dim(t("repl.api_line", {
971
- prompt: String(result.promptTokens),
972
- completion: String(result.completionTokens),
973
- total: String(result.totalTokens),
974
- }));
975
- this.output.writeLine(apiLine);
976
- }
977
- if (result.totalCost !== undefined && result.totalCost > 0) {
978
- this.output.writeLine(pc.yellow(` ${t("repl.cost", { cost: formatCost(result.totalCost) })}`));
979
- }
980
- const cacheLine = formatCacheLine(result.cache);
981
- if (cacheLine) {
982
- this.output.writeLine(pc.dim(` ${cacheLine}`));
983
- }
984
- }
985
- else if (ui?.showCompaction && result.compactionCount !== undefined) {
986
- if (result.compactionCount > this.lastCompactionShown) {
987
- this.lastCompactionShown = result.compactionCount;
988
- this.output.writeLine(pc.dim(`\n ⟳ ${t("repl.compacted", { count: String(result.compactionCount) })}`));
989
- }
990
- }
991
- }
992
- async start() {
993
- this.running = true;
994
- const info = [];
995
- const row = (label, value) => {
996
- info.push(` ${pc.yellow(label)} ${value}`);
997
- };
998
- const ctx = this.config.contextWindow;
999
- const sysBudget = Math.floor(ctx * this.config.contextBudget.systemPrompt);
1000
- const resBudget = Math.floor(ctx * this.config.contextBudget.responseReserve);
1001
- const histBudget = ctx - sysBudget - resBudget;
1002
- row(t("repl.model"), pc.white(this.config.model));
1003
- // Плоские поля протухают после `/provider use` — истина в entries.
1004
- const endpoint = activeProviderEndpoint(this.config.provider);
1005
- row(t("repl.provider"), `${endpoint.type} → ${pc.dim(endpoint.baseUrl)}`);
1006
- row(t("repl.context"), `${pc.white(String(ctx))} ${pc.dim(`(sys:${sysBudget} res:${resBudget} hist:${histBudget})`)}`);
1007
- const si = this.agent.getSystemPromptInfo();
1008
- row(t("repl.sysprompt_label"), pc.dim(t("repl.sysprompt_size", { used: si.tokenCount, budget: sysBudget })));
1009
- if (this.skillsModule) {
1010
- const budget = this.skillsModule.getBudget();
1011
- row(t("repl.skills_label"), t("repl.skills_available", {
1012
- count: String(this.skillsModule.getAvailable().length),
1013
- budget: String(budget.total),
1014
- }));
1015
- }
1016
- if (this.pluginManager) {
1017
- const infos = this.pluginManager.getPluginInfos().filter(({ plugin }) => !plugin.isBuiltin);
1018
- if (infos.length > 0) {
1019
- const pluginNames = infos
1020
- .map(({ plugin, source }) => {
1021
- const version = plugin.version ? `${pc.dim(plugin.version)}` : "";
1022
- const origin = source ? pc.dim(` [${source}]`) : "";
1023
- return `${plugin.name}${version}${origin}`;
1024
- })
1025
- .join(", ");
1026
- row(t("repl.plugins_label"), t("repl.plugins_active", { count: String(infos.length), names: pluginNames }));
1027
- }
1028
- }
1029
- const mcpServers = this.config.mcpServers || {};
1030
- const enabledServers = Object.entries(mcpServers).filter(([, s]) => s.enabled !== false);
1031
- if (enabledServers.length > 0) {
1032
- const names = enabledServers.map(([name]) => name).join(", ");
1033
- row(t("repl.mcp_label"), `${pc.white(String(enabledServers.length))} ${pc.dim(`(${names})`)}`);
1034
- }
1035
- // Показываем workspace агента (каталог `-d`), а не process cwd: `bun run`
1036
- // ставит cwd в корень пакета, где агент НЕ работает.
1037
- row(t("repl.work_dir"), pc.dim(this.baseDir));
1038
- if (this.noAgentsMd) {
1039
- row(t("repl.agents_label"), pc.red(t("repl.disabled")));
1040
- }
1041
- else {
1042
- const agentsMdCandidates = [
1043
- join(this.baseDir, "AGENTS.md"),
1044
- join(projectMmaDir(this.baseDir), "AGENTS.md"),
1045
- join(this.configDir, "AGENTS.md"),
1046
- ];
1047
- const foundAgents = agentsMdCandidates.filter((p) => existsSync(p));
1048
- if (foundAgents.length > 0) {
1049
- for (const p of foundAgents) {
1050
- row(t("repl.agents_label"), pc.dim(p));
1051
- }
1052
- }
1053
- else {
1054
- row(t("repl.agents_label"), pc.dim(t("repl.not_found")));
1055
- }
1056
- }
1057
- const meta = this.sessionManager?.getActiveMeta();
1058
- if (meta) {
1059
- const sessionPath = join(this.configDir, "sessions", meta.id);
1060
- row(t("repl.session_label"), `${pc.cyan(meta.name)} ${pc.dim(`(${meta.id.slice(0, 12)})`)} — ${meta.messageCount} ${t("repl.msgs")} ${pc.dim(sessionPath)}`);
1061
- }
1062
- // Статус LSP пробнится фоном — баннер блокировать нельзя.
1063
- const isTty = process.stdout.isTTY === true;
1064
- const lspEnabled = isTty && (this.config.lsp ?? DEFAULT_LSP_CONFIG).enabled !== false;
1065
- // Plain-баннер без рамки: построчно, с переносом по ширине.
1066
- for (const line of info) {
1067
- this.output.writeLine(pc.dim(line).trimEnd());
1068
- }
1069
- this.output.writeLine("");
1070
- // Хинт про legacy-конфиг.
1071
- try {
1072
- const { existsSync: exists } = await import("fs");
1073
- const { join: pathJoin } = await import("path");
1074
- const { hasDomainFiles } = await import("../config/domains");
1075
- const legacyPath = pathJoin(this.configDir, "config.json");
1076
- if (exists(legacyPath) && !hasDomainFiles(this.configDir)) {
1077
- this.output.writeLine(pc.yellow(` ${t("config.legacy_hint")}`));
1078
- this.output.writeLine("");
1079
- }
1080
- }
1081
- catch {
1082
- // Хинт best-effort: ошибка чтения его просто скипает.
1083
- }
1084
- // Единственный показ промпта на старте: баннер выше печатался plain
1085
- // (promptPresented был false), так что стирать кадр здесь нечего.
1086
- this.rl.prompt();
1087
- this.promptPresented = true;
1088
- try {
1089
- if (readEnv("START_MEET") === "1" || readEnv("START_INIT") === "1") {
1090
- const mode = readEnv("START_MEET") === "1" ? "meet" : "init";
1091
- delete process.env[MMA_ENV.START_MEET];
1092
- delete process.env[MMA_ENV.START_INIT];
1093
- this.slog.logOnboarding(`${mode}_start`, { model: this.config.model });
1094
- if (mode === "meet") {
1095
- const { runMeet } = await import("../modules/onboarding/meet");
1096
- await runMeet(this);
1097
- }
1098
- else {
1099
- const { runInit } = await import("../modules/onboarding/init");
1100
- await runInit(this);
1101
- this.slog.logOnboarding("init_done", { model: this.config.model });
1102
- }
1103
- }
1104
- else if (readEnv("POST_SETUP") === "1" && process.stdout.isTTY === true) {
1105
- const { preflightFromConfig } = await import("../modules/providers/preflight");
1106
- const pre = await preflightFromConfig(this);
1107
- if (pre.ok) {
1108
- this.output.writeLine(pc.dim(`${t("repl.meet_offer")} ${t("repl.meet_offer_hint")}`));
1109
- const answer = (await new Promise((resolve) => this.rl.question("[Y/n] ", resolve)))
1110
- .trim()
1111
- .toLowerCase();
1112
- const yes = answer === "" ||
1113
- answer === "y" ||
1114
- answer === "yes" ||
1115
- answer === "да" ||
1116
- answer === "д";
1117
- if (yes) {
1118
- this.slog.logOnboarding("meet_start", { model: this.config.model });
1119
- const { runMeet } = await import("../modules/onboarding/meet");
1120
- await runMeet(this, { preflight: async () => pre });
1121
- }
1122
- else {
1123
- this.restoreStartupPrompt();
1124
- }
1125
- }
1126
- else {
1127
- this.output.writeLine(pc.yellow(t("onboarding.provider_down", { cmd: "meet" })));
1128
- this.output.writeLine(t("onboarding.provider_down_hint", { cmd: "meet" }));
1129
- }
1130
- }
1131
- }
1132
- catch (err) {
1133
- this.logger?.debug(`Onboarding startup skipped: ${String(err)}`);
1134
- this.restoreStartupPrompt();
1135
- }
1136
- if (lspEnabled) {
1137
- this.probeLspBanner()
1138
- .then((lspSummary) => {
1139
- if (lspSummary) {
1140
- const line = `${pc.green(t("repl.agent"))}${pc.yellow(t("repl.lsp_label"))} ${lspSummary}`;
1141
- // Строкой промпта владеет канал: ручной erase + prompt()-хак не нужен.
1142
- this.output.writeLine(`${divider()}\n${line}`);
1143
- }
1144
- })
1145
- .catch(() => { });
1146
- }
1147
- if ((this.config.provider.entries?.length ?? 0) > 1) {
1148
- // Phase 4.4: фоновый health-пробник всех entries (бесплатные listModels).
1149
- // Упавшие провайдеры — предупреждениями: фейловер (Phase 4.2) молча
1150
- // замаскировал бы мёртвый primary.
1151
- void probeProviders(targetsFromProviders((this.config.provider.entries ?? [])
1152
- .map((e) => ({
1153
- name: e.label || e.type,
1154
- provider: this.agent.getProviderFor(e.label || e.type),
1155
- }))
1156
- .filter((x) => Boolean(x.provider))), { timeoutMs: 5000 })
1157
- .then((results) => {
1158
- for (const r of results) {
1159
- if (!r.ok && r.name !== this.config.provider.active) {
1160
- this.output.writeLine(formatWarning(t("repl.provider_down", { name: r.name, error: r.error ?? "" })));
1161
- }
1162
- }
1163
- })
1164
- .catch(() => { });
1165
- }
1166
- // Контекст-пробник (фоном): сверяем контекст, с которым модель реально
1167
- // загружена, против настроенного окна. Тот же неблокирующий баннер-паттерн,
1168
- // что у LSP-пробника выше.
1169
- if (this.contextProbe) {
1170
- void this.contextProbe
1171
- .then((probe) => {
1172
- if (!probe)
1173
- return;
1174
- // Запись пробника персистит bootstrap (все режимы); здесь только строка баннера.
1175
- const line = probe.actual < this.config.contextWindow
1176
- ? `${pc.yellow("⚠")} ${t("repl.context_probe_small", { model: probe.model, actual: probe.actual, configured: this.config.contextWindow })}`
1177
- : probe.actual > this.config.contextWindow
1178
- ? `${pc.dim(t("repl.context_probe_big", { model: probe.model, actual: probe.actual }))}`
1179
- : null;
1180
- if (line) {
1181
- // Строкой промпта владеет канал: ручной erase + prompt()-хак не нужен.
1182
- this.output.writeLine(`${divider()}\n${line}`);
1183
- }
1184
- })
1185
- .catch(() => { });
1186
- }
1187
- }
1188
- /**
1189
- * Пробнит LSP-серверы, применимые к текущему проекту, и форматирует однострочную
1190
- * сводку баннера, напр. "✓ typescript (1.2s)" или "✗ css — timeout".
1191
- * Null, если LSP выключен или серверов нет.
1192
- */
1193
- async probeLspBanner() {
1194
- const config = this.config.lsp ?? DEFAULT_LSP_CONFIG;
1195
- try {
1196
- const lspOnlyLogger = this.logger ? new FileOnlyLogger(this.logger) : undefined;
1197
- const summary = await probeLspServers(config, this.baseDir, { logger: lspOnlyLogger });
1198
- // Результаты LSP-пробника — в сессию, для пост-мортем видимости.
1199
- this.slog.logSessionStart({
1200
- environment: this.envReport,
1201
- lspProbe: {
1202
- ok: summary.ok.map((r) => ({ language: r.language, durationMs: r.durationMs })),
1203
- failed: summary.failed.map((r) => ({
1204
- language: r.language,
1205
- error: r.error,
1206
- durationMs: r.durationMs,
1207
- })),
1208
- noneApplicable: summary.noneApplicable,
1209
- },
1210
- });
1211
- if (summary.noneApplicable)
1212
- return null;
1213
- const parts = [];
1214
- for (const r of summary.ok) {
1215
- parts.push(pc.green(`✓ ${r.language}${pc.dim(` (${(r.durationMs / 1000).toFixed(1)}s)`)}`));
1216
- }
1217
- for (const r of summary.failed) {
1218
- const reason = r.error?.includes("timeout") ? t("repl.lsp_timeout") : t("repl.lsp_failed");
1219
- parts.push(pc.red(`✗ ${r.language}${pc.dim(` — ${reason}`)}`));
1220
- }
1221
- return parts.join(" ");
1222
- }
1223
- catch {
1224
- return pc.yellow(t("repl.lsp_unknown"));
1225
- }
1226
- }
1227
- /** Останов REPL: сейв истории, шатдаун агента, закрытие лога сессии. */
1228
- stop() {
1229
- this.running = false;
1230
- this.saveHistory();
1231
- this.agent.shutdown();
1232
- this.sessionOutput?.dispose();
1233
- this.sessionOutput = undefined;
1234
- // Закрываем лог сессии на останове REPL.
1235
- this.logger?.closeSessionLog();
1236
- this.rl.close();
1237
- }
1238
- }