micro-models-agent 2.16.1 → 2.17.2
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.
- package/CHANGELOG.md +34 -0
- package/README.md +8 -3
- package/dist/assets/app.js +1 -314
- package/dist/assets/hljs.js +5 -1244
- package/dist/assets/index.html +11 -0
- package/dist/assets/js/api.js +1 -28
- package/dist/assets/js/core/menus.js +1 -0
- package/dist/assets/js/core/store/feed.js +1 -0
- package/dist/assets/js/core/store/index.js +1 -0
- package/dist/assets/js/core/store/session.js +1 -0
- package/dist/assets/js/core/store/settings.js +1 -0
- package/dist/assets/js/core/store/tabs.js +1 -0
- package/dist/assets/js/dialog.js +1 -105
- package/dist/assets/js/dom.js +1 -178
- package/dist/assets/js/feed/core.js +1 -0
- package/dist/assets/js/feed/history.js +1 -0
- package/dist/assets/js/feed/plan.js +1 -0
- package/dist/assets/js/feed/question.js +3 -0
- package/dist/assets/js/feed/sidebar.js +1 -0
- package/dist/assets/js/feed/stream.js +1 -0
- package/dist/assets/js/feed/turn.js +5 -0
- package/dist/assets/js/feed.js +1 -1250
- package/dist/assets/js/format.js +2 -122
- package/dist/assets/js/i18n.js +1 -46
- package/dist/assets/js/rail.js +1 -114
- package/dist/assets/js/session/cmdk.js +1 -0
- package/dist/assets/js/session/composer.js +1 -0
- package/dist/assets/js/session/sessions-menu.js +1 -0
- package/dist/assets/js/session/tabs.js +1 -0
- package/dist/assets/js/settings/controls.js +1 -0
- package/dist/assets/js/settings/editors.js +1 -0
- package/dist/assets/js/settings/form.js +1 -0
- package/dist/assets/js/settings/modal.js +1 -0
- package/dist/assets/js/settings/panels.js +1 -0
- package/dist/assets/js/settings/providers.js +1 -0
- package/dist/assets/js/settings/search.js +1 -0
- package/dist/assets/js/settings/subdialog.js +1 -0
- package/dist/assets/js/settings/write.js +1 -0
- package/dist/assets/js/settings.js +1 -1914
- package/dist/assets/js/sidebar/core.js +1 -0
- package/dist/assets/js/sidebar/lsp.js +2 -0
- package/dist/assets/js/sidebar/map.js +1 -0
- package/dist/assets/js/sidebar/state.js +1 -0
- package/dist/assets/js/sidebar/trace.js +5 -0
- package/dist/assets/js/sidebar.js +1 -705
- package/dist/assets/js/store.js +1 -82
- package/dist/assets/js/subdialog.js +1 -0
- package/dist/assets/md.js +1 -291
- package/dist/assets/setup.js +3 -816
- package/dist/assets/smd.js +29 -1665
- package/dist/assets/styles.css +1 -1598
- package/dist/certification/certifications.json +1 -494
- package/dist/i18n/en.json +1 -1851
- package/dist/i18n/ru.json +1 -1854
- package/dist/main.js +815 -55797
- package/dist/modules/browser/bridge-server.mjs +2 -252
- package/package.json +10 -5
- package/dist/assets/js/settings-controls.js +0 -452
- package/dist/assets/js/tabs.js +0 -867
- package/dist/cli/cache-line.js +0 -31
- package/dist/cli/command-suggest.js +0 -39
- package/dist/cli/commands.js +0 -781
- package/dist/cli/completer.js +0 -268
- package/dist/cli/index.js +0 -3
- package/dist/cli/json-payload.js +0 -32
- package/dist/cli/main.js +0 -346
- package/dist/cli/onboarding-commands.js +0 -126
- package/dist/cli/plugin-commands.js +0 -38
- package/dist/cli/relaunch.js +0 -40
- package/dist/cli/repl-commands-lsp.js +0 -75
- package/dist/cli/repl-commands-skills.js +0 -105
- package/dist/cli/repl-commands.js +0 -1218
- package/dist/cli/repl.js +0 -1238
- package/dist/cli/run-result.js +0 -38
- package/dist/cli/security-commands.js +0 -177
- package/dist/cli/setup-order.js +0 -6
- package/dist/cli/setup-prompt.js +0 -50
- package/dist/cli/setup.js +0 -161
- package/dist/cli/web-command.js +0 -98
- package/dist/config/budget.js +0 -48
- package/dist/config/config.js +0 -345
- package/dist/config/defaults.js +0 -197
- package/dist/config/domains.js +0 -135
- package/dist/config/env.js +0 -46
- package/dist/config/experts.js +0 -17
- package/dist/config/index.js +0 -5
- package/dist/config/paths.js +0 -56
- package/dist/config/redact.js +0 -44
- package/dist/config/registry-extra.js +0 -334
- package/dist/config/registry.js +0 -584
- package/dist/config/security.js +0 -212
- package/dist/config/timeouts.js +0 -74
- package/dist/config/types.js +0 -1
- package/dist/config/utils.js +0 -57
- package/dist/core/agent/artifact-progress.js +0 -59
- package/dist/core/agent/artifact-resolve.js +0 -79
- package/dist/core/agent/audit-gate.js +0 -53
- package/dist/core/agent/compaction.js +0 -89
- package/dist/core/agent/constants.js +0 -90
- package/dist/core/agent/context-log.js +0 -454
- package/dist/core/agent/context-renderer.js +0 -45
- package/dist/core/agent/critic-gate.js +0 -132
- package/dist/core/agent/hallucination-gate.js +0 -197
- package/dist/core/agent/loop-state.js +0 -68
- package/dist/core/agent/prefix-monitor.js +0 -101
- package/dist/core/agent/reasoning-resolver.js +0 -65
- package/dist/core/agent/token-tracker.js +0 -99
- package/dist/core/agent/tool-batch.js +0 -312
- package/dist/core/agent/tool-images.js +0 -18
- package/dist/core/agent/tool-output.js +0 -116
- package/dist/core/agent/tool-pairing.js +0 -60
- package/dist/core/agent-moe.js +0 -248
- package/dist/core/agent.js +0 -1299
- package/dist/core/bootstrap/agent-phase.js +0 -66
- package/dist/core/bootstrap/config-phase.js +0 -86
- package/dist/core/bootstrap/modules-phase.js +0 -269
- package/dist/core/bootstrap/provider-phase.js +0 -183
- package/dist/core/bootstrap/session-phase.js +0 -204
- package/dist/core/bootstrap/state.js +0 -94
- package/dist/core/bootstrap/workspace-phase.js +0 -115
- package/dist/core/bootstrap.js +0 -112
- package/dist/core/crash-handler.js +0 -62
- package/dist/core/environment.js +0 -224
- package/dist/core/host-plan.js +0 -43
- package/dist/core/host.js +0 -23
- package/dist/core/index.js +0 -3
- package/dist/core/prompt-builder.js +0 -95
- package/dist/core/prompt-overflow.js +0 -306
- package/dist/core/session-logger.js +0 -375
- package/dist/core/system-prompt.js +0 -117
- package/dist/core/types.js +0 -1
- package/dist/core/version.js +0 -28
- package/dist/core/web-host.js +0 -34
- package/dist/core/workspace.js +0 -80
- package/dist/i18n/index.js +0 -80
- package/dist/index.js +0 -30
- package/dist/llm/cache-usage.js +0 -76
- package/dist/llm/image-utils.js +0 -138
- package/dist/llm/index.js +0 -4
- package/dist/llm/llm-errors.js +0 -50
- package/dist/llm/model-loader.js +0 -86
- package/dist/llm/models-dev.js +0 -121
- package/dist/llm/openai-compat.js +0 -756
- package/dist/llm/orchestrator.js +0 -294
- package/dist/llm/provider-budget.js +0 -68
- package/dist/llm/provider-context.js +0 -233
- package/dist/llm/provider.js +0 -9
- package/dist/llm/response.js +0 -44
- package/dist/llm/stream-state.js +0 -26
- package/dist/llm/token-counter.js +0 -83
- package/dist/llm/types.js +0 -1
- package/dist/logger/app-logger.js +0 -212
- package/dist/logger/file-log.js +0 -160
- package/dist/logger/index.js +0 -2
- package/dist/migration/backup.js +0 -56
- package/dist/migration/detect.js +0 -61
- package/dist/migration/index.js +0 -3
- package/dist/modules/artifacts/store.js +0 -62
- package/dist/modules/browser/actions.js +0 -79
- package/dist/modules/browser/bridge-client.js +0 -203
- package/dist/modules/browser/bridge-path.js +0 -10
- package/dist/modules/browser/console-buffer.js +0 -37
- package/dist/modules/browser/cookie-store.js +0 -29
- package/dist/modules/browser/driver-types.js +0 -1
- package/dist/modules/browser/driver.js +0 -186
- package/dist/modules/browser/index.js +0 -9
- package/dist/modules/browser/module.js +0 -30
- package/dist/modules/browser/session.js +0 -322
- package/dist/modules/browser/snapshot.js +0 -154
- package/dist/modules/browser/types.js +0 -13
- package/dist/modules/certification/cli.js +0 -264
- package/dist/modules/certification/fact-checker.js +0 -90
- package/dist/modules/certification/loader.js +0 -127
- package/dist/modules/certification/manifest.js +0 -231
- package/dist/modules/certification/runner.js +0 -233
- package/dist/modules/certification/scenarios.js +0 -586
- package/dist/modules/certification/syntax-scenarios.js +0 -50
- package/dist/modules/certification/types.js +0 -1
- package/dist/modules/context/chunk-query.js +0 -122
- package/dist/modules/context/fact-extractor.js +0 -170
- package/dist/modules/context/history.js +0 -15
- package/dist/modules/context/index.js +0 -2
- package/dist/modules/context/manager.js +0 -482
- package/dist/modules/critic/client.js +0 -176
- package/dist/modules/critic/evidence.js +0 -81
- package/dist/modules/critic/provider.js +0 -45
- package/dist/modules/critic/tools.js +0 -78
- package/dist/modules/critic/types.js +0 -1
- package/dist/modules/execution/audit-runners.js +0 -206
- package/dist/modules/execution/auditor.js +0 -222
- package/dist/modules/execution/execution-plugin.js +0 -478
- package/dist/modules/execution/index.js +0 -8
- package/dist/modules/execution/input-from.js +0 -70
- package/dist/modules/execution/module.js +0 -891
- package/dist/modules/execution/moe-executor.js +0 -443
- package/dist/modules/execution/plan-actions.js +0 -642
- package/dist/modules/execution/plan-checks.js +0 -35
- package/dist/modules/execution/plan-coverage.js +0 -71
- package/dist/modules/execution/plan-persister.js +0 -46
- package/dist/modules/execution/plan-steps.js +0 -31
- package/dist/modules/execution/plan-store.js +0 -274
- package/dist/modules/execution/plan-tool.js +0 -249
- package/dist/modules/execution/plan-validator.js +0 -197
- package/dist/modules/execution/planner.js +0 -103
- package/dist/modules/execution/stuck-detector.js +0 -834
- package/dist/modules/execution/tracker.js +0 -92
- package/dist/modules/execution/transient-error.js +0 -30
- package/dist/modules/execution/types.js +0 -1
- package/dist/modules/execution/verifier.js +0 -343
- package/dist/modules/execution/windows-commands.js +0 -52
- package/dist/modules/hallucination/artifact-claim.js +0 -93
- package/dist/modules/hallucination/confidence.js +0 -81
- package/dist/modules/hallucination/consistency.js +0 -37
- package/dist/modules/hallucination/detector.js +0 -57
- package/dist/modules/hallucination/factual.js +0 -205
- package/dist/modules/hallucination/index.js +0 -6
- package/dist/modules/hallucination/js-identifiers.js +0 -261
- package/dist/modules/hallucination/llm-judge.js +0 -116
- package/dist/modules/hallucination/success-claim.js +0 -59
- package/dist/modules/index.js +0 -5
- package/dist/modules/indexer/cache.js +0 -88
- package/dist/modules/indexer/index.js +0 -4
- package/dist/modules/indexer/map-command.js +0 -33
- package/dist/modules/indexer/map-select.js +0 -87
- package/dist/modules/indexer/module.js +0 -293
- package/dist/modules/indexer/project-profile.js +0 -184
- package/dist/modules/indexer/symbols.js +0 -189
- package/dist/modules/indexer/walker.js +0 -285
- package/dist/modules/lsp/check-tool.js +0 -61
- package/dist/modules/lsp/client.js +0 -406
- package/dist/modules/lsp/command.js +0 -53
- package/dist/modules/lsp/config.js +0 -189
- package/dist/modules/lsp/index.js +0 -4
- package/dist/modules/lsp/module.js +0 -295
- package/dist/modules/lsp/probe.js +0 -86
- package/dist/modules/lsp/project-root.js +0 -69
- package/dist/modules/lsp/startup-check.js +0 -154
- package/dist/modules/lsp/types.js +0 -1
- package/dist/modules/mcp/client.js +0 -445
- package/dist/modules/mcp/index.js +0 -4
- package/dist/modules/mcp/module.js +0 -295
- package/dist/modules/mcp/registry.js +0 -20
- package/dist/modules/memory/index.js +0 -2
- package/dist/modules/memory/module.js +0 -101
- package/dist/modules/memory/search.js +0 -45
- package/dist/modules/memory/store.js +0 -107
- package/dist/modules/onboarding/init.js +0 -47
- package/dist/modules/onboarding/meet.js +0 -30
- package/dist/modules/onboarding/mode.js +0 -30
- package/dist/modules/onboarding/prompts.js +0 -43
- package/dist/modules/pipelines/engine.js +0 -70
- package/dist/modules/pipelines/index.js +0 -4
- package/dist/modules/pipelines/parser.js +0 -59
- package/dist/modules/pipelines/template.js +0 -18
- package/dist/modules/plugins/builtin/lint-on-write.js +0 -377
- package/dist/modules/plugins/builtin/notify.js +0 -11
- package/dist/modules/plugins/index.js +0 -2
- package/dist/modules/plugins/loader.js +0 -85
- package/dist/modules/plugins/manager.js +0 -244
- package/dist/modules/plugins/types.js +0 -1
- package/dist/modules/pricing/index.js +0 -70
- package/dist/modules/pricing/prices.js +0 -147
- package/dist/modules/processes/detect.js +0 -34
- package/dist/modules/processes/index.js +0 -4
- package/dist/modules/processes/kill-tree.js +0 -52
- package/dist/modules/processes/registry.js +0 -294
- package/dist/modules/processes/runner.js +0 -23
- package/dist/modules/providers/cache.js +0 -23
- package/dist/modules/providers/capabilities.js +0 -28
- package/dist/modules/providers/create.js +0 -21
- package/dist/modules/providers/factory.js +0 -28
- package/dist/modules/providers/fallback.js +0 -81
- package/dist/modules/providers/health.js +0 -47
- package/dist/modules/providers/index.js +0 -6
- package/dist/modules/providers/manager.js +0 -207
- package/dist/modules/providers/naming.js +0 -15
- package/dist/modules/providers/preflight.js +0 -71
- package/dist/modules/providers/presets.js +0 -232
- package/dist/modules/providers/registry.js +0 -27
- package/dist/modules/providers/types.js +0 -1
- package/dist/modules/reasoning/policy.js +0 -42
- package/dist/modules/reasoning/probe.js +0 -116
- package/dist/modules/registry.js +0 -48
- package/dist/modules/security/audit-log.js +0 -119
- package/dist/modules/security/audit-notifier.js +0 -267
- package/dist/modules/security/command-validator.js +0 -272
- package/dist/modules/security/content-scanner.js +0 -53
- package/dist/modules/security/data-sanitizer.js +0 -82
- package/dist/modules/security/encryption.js +0 -216
- package/dist/modules/security/index.js +0 -15
- package/dist/modules/security/network-validator.js +0 -236
- package/dist/modules/security/path-validator.js +0 -261
- package/dist/modules/security/protected-paths.js +0 -73
- package/dist/modules/security/rate-limiter.js +0 -98
- package/dist/modules/security/security-policies.js +0 -499
- package/dist/modules/security/session-encryption.js +0 -182
- package/dist/modules/security/session-isolation.js +0 -75
- package/dist/modules/session/auto-name.js +0 -63
- package/dist/modules/session/export.js +0 -98
- package/dist/modules/session/index.js +0 -4
- package/dist/modules/session/manager.js +0 -234
- package/dist/modules/session/module.js +0 -33
- package/dist/modules/session/store.js +0 -295
- package/dist/modules/session/types.js +0 -1
- package/dist/modules/setup/answers.js +0 -35
- package/dist/modules/setup/apply.js +0 -79
- package/dist/modules/setup/discovery.js +0 -72
- package/dist/modules/skills/index.js +0 -3
- package/dist/modules/skills/loader.js +0 -86
- package/dist/modules/skills/matcher.js +0 -27
- package/dist/modules/skills/module.js +0 -141
- package/dist/modules/types.js +0 -1
- package/dist/modules/updater/changelog-reader.js +0 -93
- package/dist/modules/updater/checker.js +0 -101
- package/dist/modules/updater/dev-detect.js +0 -18
- package/dist/modules/updater/index.js +0 -4
- package/dist/modules/updater/module.js +0 -129
- package/dist/modules/user-profile/compressor.js +0 -18
- package/dist/modules/user-profile/index.js +0 -2
- package/dist/modules/user-profile/profile.js +0 -77
- package/dist/modules/webui/answer-api.js +0 -29
- package/dist/modules/webui/assets.js +0 -50
- package/dist/modules/webui/body.js +0 -21
- package/dist/modules/webui/commands-settings.js +0 -209
- package/dist/modules/webui/commands-shared.js +0 -60
- package/dist/modules/webui/commands.js +0 -174
- package/dist/modules/webui/config-api.js +0 -134
- package/dist/modules/webui/file-api.js +0 -202
- package/dist/modules/webui/forward.js +0 -159
- package/dist/modules/webui/history-api.js +0 -112
- package/dist/modules/webui/host-state.js +0 -60
- package/dist/modules/webui/i18n-api.js +0 -9
- package/dist/modules/webui/limits.js +0 -6
- package/dist/modules/webui/log-forward.js +0 -20
- package/dist/modules/webui/memory-commands.js +0 -64
- package/dist/modules/webui/model-cache.js +0 -18
- package/dist/modules/webui/module.js +0 -148
- package/dist/modules/webui/persist.js +0 -24
- package/dist/modules/webui/prompt-io.js +0 -97
- package/dist/modules/webui/providers-api.js +0 -337
- package/dist/modules/webui/providers-view.js +0 -56
- package/dist/modules/webui/reasoning-view.js +0 -15
- package/dist/modules/webui/run-agent.js +0 -81
- package/dist/modules/webui/server.js +0 -284
- package/dist/modules/webui/sessions-api.js +0 -178
- package/dist/modules/webui/settings-api.js +0 -561
- package/dist/modules/webui/setup-api.js +0 -201
- package/dist/modules/webui/state.js +0 -74
- package/dist/modules/webui/util.js +0 -261
- package/dist/output/bus.js +0 -37
- package/dist/output/channel.js +0 -285
- package/dist/output/format.js +0 -15
- package/dist/output/index.js +0 -8
- package/dist/output/json-sink.js +0 -24
- package/dist/output/machine.js +0 -9
- package/dist/output/session-sink.js +0 -27
- package/dist/output/types.js +0 -1
- package/dist/tools/approve.js +0 -41
- package/dist/tools/attach-image.js +0 -102
- package/dist/tools/auto-fixer.js +0 -180
- package/dist/tools/auto-tags.js +0 -83
- package/dist/tools/bash.js +0 -649
- package/dist/tools/browser.js +0 -160
- package/dist/tools/chunk-query.js +0 -112
- package/dist/tools/create-dir.js +0 -60
- package/dist/tools/delete-file.js +0 -67
- package/dist/tools/download-file.js +0 -142
- package/dist/tools/edit-file.js +0 -136
- package/dist/tools/enable-tools.js +0 -59
- package/dist/tools/executor.js +0 -304
- package/dist/tools/file-info.js +0 -49
- package/dist/tools/filter-tools.js +0 -17
- package/dist/tools/glob-tool.js +0 -37
- package/dist/tools/grep-tool.js +0 -142
- package/dist/tools/hidden-tools-block.js +0 -37
- package/dist/tools/index.js +0 -88
- package/dist/tools/list-dir.js +0 -53
- package/dist/tools/load-skill.js +0 -51
- package/dist/tools/mcp-call.js +0 -80
- package/dist/tools/meet-done.js +0 -14
- package/dist/tools/move-file.js +0 -94
- package/dist/tools/path-utils.js +0 -108
- package/dist/tools/pipeline-run.js +0 -167
- package/dist/tools/preview.js +0 -2
- package/dist/tools/process-ids.js +0 -31
- package/dist/tools/process-kill.js +0 -33
- package/dist/tools/process-list.js +0 -38
- package/dist/tools/process-log.js +0 -49
- package/dist/tools/process-wait.js +0 -63
- package/dist/tools/prompt-io.js +0 -29
- package/dist/tools/question.js +0 -288
- package/dist/tools/read-file.js +0 -200
- package/dist/tools/recall.js +0 -124
- package/dist/tools/registry.js +0 -48
- package/dist/tools/remember.js +0 -72
- package/dist/tools/scope-check.js +0 -32
- package/dist/tools/scope-request.js +0 -96
- package/dist/tools/search-history.js +0 -88
- package/dist/tools/session-info.js +0 -46
- package/dist/tools/set-thinking.js +0 -75
- package/dist/tools/subagent.js +0 -257
- package/dist/tools/syntax-validator.js +0 -379
- package/dist/tools/types.js +0 -1
- package/dist/tools/user-input.js +0 -134
- package/dist/tools/web-browse.js +0 -93
- package/dist/tools/web-fetch.js +0 -108
- package/dist/tools/web-search.js +0 -107
- package/dist/tools/write-file.js +0 -128
- package/dist/ui/action-log.js +0 -13
- package/dist/ui/box.js +0 -78
- package/dist/ui/colors.js +0 -6
- package/dist/ui/diff.js +0 -189
- package/dist/ui/index.js +0 -7
- package/dist/ui/line-editor.js +0 -1083
- package/dist/ui/line-math.js +0 -98
- package/dist/ui/md-formatter.js +0 -322
- package/dist/ui/output.js +0 -19
- package/dist/ui/plan-view.js +0 -109
- package/dist/ui/renderer.js +0 -589
- package/dist/ui/spinner.js +0 -91
- package/dist/ui/table.js +0 -142
- package/dist/ui/theme.js +0 -143
- package/dist/utils/child-run.js +0 -20
- package/dist/utils/error.js +0 -4
- package/dist/utils/index.js +0 -6
- package/dist/utils/retry.js +0 -17
- package/dist/utils/sleep.js +0 -23
- package/dist/utils/truncate.js +0 -9
package/dist/ui/line-editor.js
DELETED
|
@@ -1,1083 +0,0 @@
|
|
|
1
|
-
// Строчный редактор: raw-ввод, история, Tab-комплит, DSR-якорь кадра (см. DSR ниже).
|
|
2
|
-
import * as readline from "readline";
|
|
3
|
-
import stringWidth from "string-width";
|
|
4
|
-
import { pc } from "./colors";
|
|
5
|
-
import { readEnv } from "../config/env";
|
|
6
|
-
import { buildLayout, layoutIndexFor, visualColAt, charOffsetFor, charLen, stripAnsi, } from "./line-math";
|
|
7
|
-
/** Многострочный редактор ввода с историей и Tab-комплитом (raw-режим TTY). */
|
|
8
|
-
export class LineEditor {
|
|
9
|
-
input;
|
|
10
|
-
output;
|
|
11
|
-
/** Хук хоста: true — поглотить клавишу до обработки редактором. */
|
|
12
|
-
onKeyInput;
|
|
13
|
-
onInterrupt;
|
|
14
|
-
promptStr;
|
|
15
|
-
completer;
|
|
16
|
-
history;
|
|
17
|
-
historySize;
|
|
18
|
-
lines = [""];
|
|
19
|
-
row = 0;
|
|
20
|
-
col = 0;
|
|
21
|
-
/** Перенос не-TTY чанкованного ввода (частичная строка между чтениями). */
|
|
22
|
-
pendingLine = "";
|
|
23
|
-
historyIndex = -1;
|
|
24
|
-
stash = null;
|
|
25
|
-
isDone = false;
|
|
26
|
-
isPaste = false;
|
|
27
|
-
/** Вставленное копятся между `paste-start` и `paste-end`.
|
|
28
|
-
* Вставляется одним батчем на `paste-end`: один рендер вместо рендера на
|
|
29
|
-
* клавишу, чтобы вставка выглядела вставкой, а не быстрой печатью. */
|
|
30
|
-
pasteBuffer = "";
|
|
31
|
-
/** Была ли последняя вставленная клавиша голым CR: схлопывает CRLF-пару
|
|
32
|
-
* в один перевод строки (текст из буфера Windows). */
|
|
33
|
-
pasteLastWasCR = false;
|
|
34
|
-
lastWasCR = false;
|
|
35
|
-
questionCb = null;
|
|
36
|
-
/** Активная Tab-сессия комплита. Пока стоит, ↑/↓/Tab крутят кандидатов, а
|
|
37
|
-
* Esc возвращает `original`; любая другая клавиша сессию роняет. */
|
|
38
|
-
completionSession = null;
|
|
39
|
-
rawMode = false;
|
|
40
|
-
listeners = {};
|
|
41
|
-
/** stdin-хендлеры из конструктора: снимаются в close(), чтобы пересоздание
|
|
42
|
-
* редактора не копило протухшие слушатели. */
|
|
43
|
-
dsrDataHandler;
|
|
44
|
-
keypressHandler;
|
|
45
|
-
dataHandler;
|
|
46
|
-
endHandler;
|
|
47
|
-
/** Визуальный ряд (внутри рисуемого кадра), куда последний рендер поставил
|
|
48
|
-
* курсор. Фолбэк для возврата на первую строку кадра перед перерисовкой,
|
|
49
|
-
* пока нет абсолютного якоря. Относительные ходы ломаются при скролле
|
|
50
|
-
* терминала (кадр уезжает вверх, счётчик — нет), что дублировало
|
|
51
|
-
* многострочный ввод. */
|
|
52
|
-
prevCursorRow = 0;
|
|
53
|
-
/** Абсолютный 1-based экранный ряд первой визуальной строки кадра. Выучен
|
|
54
|
-
* из одного DSR-ответа о позиции курсора (`ESC[6n`), шлётся раз на показ
|
|
55
|
-
* промпта. Дальше якорь ведётся детерминированной скролл-математикой, новых
|
|
56
|
-
* запросов нет (защита от рассинхрона ConPTY). Без ответа (таймаут/битый
|
|
57
|
-
* терминал) — фолбэк на относительные ходы. */
|
|
58
|
-
frameTopAbs = null;
|
|
59
|
-
/** Ждём ли DSR-ответ (ровно один outstanding-запрос). */
|
|
60
|
-
dsrPending = false;
|
|
61
|
-
/** Буфер частичных DSR-escape, разрезанных между чанками. */
|
|
62
|
-
dsrTail = "";
|
|
63
|
-
/** Визуальный ряд курсора ровно в момент отправки outstanding DSR-запроса.
|
|
64
|
-
* Ответ матчится против него, а не `prevCursorRow`: промежуточные рендеры
|
|
65
|
-
* перезаписывают тот, пока запрос ещё летит. */
|
|
66
|
-
dsrQueryRow = 0;
|
|
67
|
-
/** Выкл — клавиши игнорятся (кроме Ctrl+C), пока агент стримит: терминалом
|
|
68
|
-
* в этой фазе владеет хост. */
|
|
69
|
-
inputEnabled = true;
|
|
70
|
-
/** Вкл — кадр промпта не рисуется; экраном владеет агент. */
|
|
71
|
-
frameSuspended = false;
|
|
72
|
-
/** Сбрасывает `dsrPending`, если DSR-ответ не пришёл: фолбэк на относительные
|
|
73
|
-
* ходы вместо клина на битом терминале. */
|
|
74
|
-
dsrTimer = null;
|
|
75
|
-
constructor(opts) {
|
|
76
|
-
this.input = opts.input;
|
|
77
|
-
this.output = opts.output;
|
|
78
|
-
this.promptStr = opts.prompt ?? "";
|
|
79
|
-
this.completer = opts.completer;
|
|
80
|
-
this.onInterrupt = opts.onInterrupt;
|
|
81
|
-
this.history = opts.history ?? [];
|
|
82
|
-
this.historySize = opts.historySize ?? 50;
|
|
83
|
-
if (this.history.length > this.historySize) {
|
|
84
|
-
this.history = this.history.slice(-this.historySize);
|
|
85
|
-
}
|
|
86
|
-
if (this.input.isTTY) {
|
|
87
|
-
this.rawMode = typeof this.input.setRawMode === "function";
|
|
88
|
-
if (this.rawMode)
|
|
89
|
-
this.input.setRawMode(true);
|
|
90
|
-
this.enableTerminalProtocols();
|
|
91
|
-
// Сырой слушатель DSR-ответов о позиции курсора. Живёт рядом с keypress-эмитером
|
|
92
|
-
// readline (оба получают каждый чанк); ответы могут приходить склеенными с
|
|
93
|
-
// обычными клавишами — отсюда глобальный regex.
|
|
94
|
-
this.dsrDataHandler = (buf) => this.consumeDsrReplies(buf.toString("utf-8"));
|
|
95
|
-
this.input.on("data", this.dsrDataHandler);
|
|
96
|
-
readline.emitKeypressEvents(this.input);
|
|
97
|
-
this.keypressHandler = (str, key) => this.onKey(str, key);
|
|
98
|
-
this.input.on("keypress", this.keypressHandler);
|
|
99
|
-
// Редактор теперь владеет stdin: взводим flowing, даже если прошлый
|
|
100
|
-
// потребитель его стопил (напр. визард настройки).
|
|
101
|
-
this.input.resume();
|
|
102
|
-
}
|
|
103
|
-
else {
|
|
104
|
-
this.dataHandler = (buf) => this.onData(buf);
|
|
105
|
-
this.input.on("data", this.dataHandler);
|
|
106
|
-
this.endHandler = () => {
|
|
107
|
-
const last = this.lines.join("\n");
|
|
108
|
-
this.lines = [""];
|
|
109
|
-
this.row = 0;
|
|
110
|
-
this.col = 0;
|
|
111
|
-
if (last)
|
|
112
|
-
this.emitLine(last);
|
|
113
|
-
this.emitClose();
|
|
114
|
-
};
|
|
115
|
-
this.input.on("end", this.endHandler);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
on(event, listener) {
|
|
119
|
-
if (event === "line") {
|
|
120
|
-
this.listeners.line = listener;
|
|
121
|
-
}
|
|
122
|
-
else {
|
|
123
|
-
this.listeners.close = listener;
|
|
124
|
-
}
|
|
125
|
-
return this;
|
|
126
|
-
}
|
|
127
|
-
setPrompt(prompt) {
|
|
128
|
-
this.promptStr = prompt;
|
|
129
|
-
if (this.input.isTTY)
|
|
130
|
-
this.render();
|
|
131
|
-
}
|
|
132
|
-
prompt(_preserveCursor) {
|
|
133
|
-
if (this.input.isTTY)
|
|
134
|
-
this.render();
|
|
135
|
-
}
|
|
136
|
-
write(s) {
|
|
137
|
-
this.insertText(s);
|
|
138
|
-
}
|
|
139
|
-
setInputEnabled(enabled) {
|
|
140
|
-
this.inputEnabled = enabled;
|
|
141
|
-
}
|
|
142
|
-
isInputEnabled() {
|
|
143
|
-
return this.inputEnabled;
|
|
144
|
-
}
|
|
145
|
-
isFrameSuspended() {
|
|
146
|
-
return this.frameSuspended;
|
|
147
|
-
}
|
|
148
|
-
/** Clear the prompt frame (the agent takes over the terminal) and stop
|
|
149
|
-
* rendering until `resumeFrame()`. */
|
|
150
|
-
suspendFrame() {
|
|
151
|
-
if (!this.input.isTTY || this.isDone)
|
|
152
|
-
return;
|
|
153
|
-
const out = [];
|
|
154
|
-
if (this.frameTopAbs !== null)
|
|
155
|
-
out.push(`\x1b[${this.frameTopAbs};1H`);
|
|
156
|
-
else if (this.prevCursorRow > 0)
|
|
157
|
-
out.push(`\x1b[${this.prevCursorRow}A`);
|
|
158
|
-
out.push("\r\x1b[J");
|
|
159
|
-
this.output.write(out.join(""));
|
|
160
|
-
this.invalidateAnchor();
|
|
161
|
-
this.frameSuspended = true;
|
|
162
|
-
}
|
|
163
|
-
/** Restore the frame after streaming. */
|
|
164
|
-
resumeFrame() {
|
|
165
|
-
this.frameSuspended = false;
|
|
166
|
-
this.invalidateAnchor();
|
|
167
|
-
this.render();
|
|
168
|
-
}
|
|
169
|
-
/** Print a block of lines above the current prompt frame without erasing
|
|
170
|
-
* the input buffer. When the frame is suspended the block is printed in
|
|
171
|
-
* place and the suspension is preserved. */
|
|
172
|
-
printAbove(text) {
|
|
173
|
-
if (!this.input.isTTY || this.isDone) {
|
|
174
|
-
this.output.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
const wasSuspended = this.frameSuspended;
|
|
178
|
-
this.frameSuspended = false;
|
|
179
|
-
const out = [];
|
|
180
|
-
if (this.frameTopAbs !== null)
|
|
181
|
-
out.push(`\x1b[${this.frameTopAbs};1H`);
|
|
182
|
-
else if (this.prevCursorRow > 0)
|
|
183
|
-
out.push(`\x1b[${this.prevCursorRow}A`);
|
|
184
|
-
out.push("\r\x1b[J");
|
|
185
|
-
out.push(text.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n").join("\r\n"));
|
|
186
|
-
out.push("\r\n");
|
|
187
|
-
this.output.write(out.join(""));
|
|
188
|
-
this.invalidateAnchor();
|
|
189
|
-
if (wasSuspended)
|
|
190
|
-
this.frameSuspended = true;
|
|
191
|
-
else
|
|
192
|
-
this.render();
|
|
193
|
-
}
|
|
194
|
-
reset() {
|
|
195
|
-
this.lines = [""];
|
|
196
|
-
this.row = 0;
|
|
197
|
-
this.col = 0;
|
|
198
|
-
this.historyIndex = -1;
|
|
199
|
-
this.stash = null;
|
|
200
|
-
this.completionSession = null;
|
|
201
|
-
this.invalidateAnchor();
|
|
202
|
-
if (this.input.isTTY)
|
|
203
|
-
this.render();
|
|
204
|
-
}
|
|
205
|
-
question(query, cb) {
|
|
206
|
-
this.questionCb = cb;
|
|
207
|
-
this.promptStr = query;
|
|
208
|
-
this.lines = [""];
|
|
209
|
-
this.row = 0;
|
|
210
|
-
this.col = 0;
|
|
211
|
-
this.completionSession = null;
|
|
212
|
-
this.invalidateAnchor();
|
|
213
|
-
if (this.input.isTTY)
|
|
214
|
-
this.render();
|
|
215
|
-
}
|
|
216
|
-
close() {
|
|
217
|
-
if (this.isDone)
|
|
218
|
-
return;
|
|
219
|
-
this.isDone = true;
|
|
220
|
-
this.disableTerminalProtocols();
|
|
221
|
-
if (this.dsrDataHandler)
|
|
222
|
-
this.input.removeListener("data", this.dsrDataHandler);
|
|
223
|
-
if (this.keypressHandler)
|
|
224
|
-
this.input.removeListener("keypress", this.keypressHandler);
|
|
225
|
-
if (this.dataHandler)
|
|
226
|
-
this.input.removeListener("data", this.dataHandler);
|
|
227
|
-
if (this.endHandler)
|
|
228
|
-
this.input.removeListener("end", this.endHandler);
|
|
229
|
-
if (this.rawMode && this.input.setRawMode) {
|
|
230
|
-
this.input.setRawMode(false);
|
|
231
|
-
}
|
|
232
|
-
if (this.dsrTimer) {
|
|
233
|
-
clearTimeout(this.dsrTimer);
|
|
234
|
-
this.dsrTimer = null;
|
|
235
|
-
}
|
|
236
|
-
this.emitClose();
|
|
237
|
-
}
|
|
238
|
-
// ── Ввод ──
|
|
239
|
-
onData(buf) {
|
|
240
|
-
if (this.isDone)
|
|
241
|
-
return;
|
|
242
|
-
let text = buf.toString("utf-8");
|
|
243
|
-
text = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
244
|
-
const parts = text.split("\n");
|
|
245
|
-
// Незавершённый хвост — в следующий чанк: немедленный эмит разрезал бы
|
|
246
|
-
// `"hello wor" + "ld\n"` на две неверные строки.
|
|
247
|
-
this.pendingLine += parts[0];
|
|
248
|
-
for (let i = 1; i < parts.length; i++) {
|
|
249
|
-
this.emitLine(this.pendingLine);
|
|
250
|
-
this.lines = [""];
|
|
251
|
-
this.row = 0;
|
|
252
|
-
this.col = 0;
|
|
253
|
-
this.pendingLine = parts[i];
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
onKey(str, key) {
|
|
257
|
-
if (this.isDone)
|
|
258
|
-
return;
|
|
259
|
-
if (!this.inputEnabled) {
|
|
260
|
-
// На стриме уважаются только прерывающие клавиши: Ctrl+C абортит прогон,
|
|
261
|
-
// Esc форвардится, чтобы хост реализовал двойной-Esc аборт.
|
|
262
|
-
const k = key;
|
|
263
|
-
if (k?.ctrl && k.name === "c") {
|
|
264
|
-
this.ctrlC();
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
if (k?.name === "escape") {
|
|
268
|
-
this.onKeyInput?.(str, key);
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
return;
|
|
272
|
-
}
|
|
273
|
-
// Сессия комплита приоритетнее хост-хуков: Esc обязан вернуть исходный
|
|
274
|
-
// partial, а не дёрнуть хостовый Esc-хендлинг; стрелки/Tab — крутить.
|
|
275
|
-
// Любая другая клавиша роняет сессию и обрабатывается обычно (с хост-хуком).
|
|
276
|
-
if (this.completionSession) {
|
|
277
|
-
const ck = key;
|
|
278
|
-
const plain = !ck.ctrl && !ck.meta;
|
|
279
|
-
if (ck?.name === "down" && plain) {
|
|
280
|
-
this.cycleCompletion(1);
|
|
281
|
-
return;
|
|
282
|
-
}
|
|
283
|
-
if (ck?.name === "up" && plain) {
|
|
284
|
-
this.cycleCompletion(-1);
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
if (ck?.name === "tab") {
|
|
288
|
-
this.cycleCompletion(1);
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
if (ck?.name === "escape") {
|
|
292
|
-
this.cancelCompletion();
|
|
293
|
-
return;
|
|
294
|
-
}
|
|
295
|
-
this.completionSession = null;
|
|
296
|
-
}
|
|
297
|
-
if (this.onKeyInput?.(str, key))
|
|
298
|
-
return;
|
|
299
|
-
const k = key;
|
|
300
|
-
const name = k?.name ?? "undefined";
|
|
301
|
-
const seq = k?.sequence ?? str ?? "";
|
|
302
|
-
if (name === "undefined" && /^\x1b\[\d+(?:;\d+)?u$/.test(seq)) {
|
|
303
|
-
const m = seq.match(/^\x1b\[(\d+)(?:;(\d+))?u$/);
|
|
304
|
-
if (m && Number(m[1]) === 13 && Number(m[2] ?? 0) !== 0) {
|
|
305
|
-
this.insertNewline();
|
|
306
|
-
}
|
|
307
|
-
return;
|
|
308
|
-
}
|
|
309
|
-
// Отчёт о позиции курсора (`ESC[row;colR`) — никогда не ввод: на части связок
|
|
310
|
-
// Windows/ConPTY + Bun хвостовой "R" протекает в буфер и портит ответ
|
|
311
|
-
// (каждый промпт отвечал "R"). Глотаем последовательность целиком.
|
|
312
|
-
if (/^\x1b\[\d+;\d+R$/.test(seq))
|
|
313
|
-
return;
|
|
314
|
-
if (name === "paste-start" || seq === "\x1b[200~") {
|
|
315
|
-
this.isPaste = true;
|
|
316
|
-
this.pasteBuffer = "";
|
|
317
|
-
this.pasteLastWasCR = false;
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
if (name === "paste-end" || seq === "\x1b[201~") {
|
|
321
|
-
this.isPaste = false;
|
|
322
|
-
if (this.pasteBuffer) {
|
|
323
|
-
this.insertPaste(this.pasteBuffer);
|
|
324
|
-
}
|
|
325
|
-
else {
|
|
326
|
-
this.render();
|
|
327
|
-
}
|
|
328
|
-
this.pasteBuffer = "";
|
|
329
|
-
this.pasteLastWasCR = false;
|
|
330
|
-
return;
|
|
331
|
-
}
|
|
332
|
-
if (this.isPaste) {
|
|
333
|
-
if (name === "return" || seq === "\r") {
|
|
334
|
-
this.pasteBuffer += "\n";
|
|
335
|
-
this.pasteLastWasCR = true;
|
|
336
|
-
}
|
|
337
|
-
else if (name === "enter" || seq === "\n") {
|
|
338
|
-
if (this.pasteLastWasCR) {
|
|
339
|
-
this.pasteLastWasCR = false;
|
|
340
|
-
}
|
|
341
|
-
else {
|
|
342
|
-
this.pasteBuffer += "\n";
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
else if (str) {
|
|
346
|
-
this.pasteLastWasCR = false;
|
|
347
|
-
this.pasteBuffer += str;
|
|
348
|
-
}
|
|
349
|
-
return;
|
|
350
|
-
}
|
|
351
|
-
if (name === "return" && (seq === "\x1b\r" || k.meta)) {
|
|
352
|
-
this.insertNewline();
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
if (name === "undefined" && seq === "\x1b\r") {
|
|
356
|
-
this.insertNewline();
|
|
357
|
-
return;
|
|
358
|
-
}
|
|
359
|
-
if (k?.ctrl && name === "j") {
|
|
360
|
-
this.insertNewline();
|
|
361
|
-
return;
|
|
362
|
-
}
|
|
363
|
-
if (name === "escape")
|
|
364
|
-
return;
|
|
365
|
-
switch (name) {
|
|
366
|
-
case "return":
|
|
367
|
-
this.lastWasCR = true;
|
|
368
|
-
this.submit();
|
|
369
|
-
return;
|
|
370
|
-
case "enter":
|
|
371
|
-
if (this.lastWasCR) {
|
|
372
|
-
this.lastWasCR = false;
|
|
373
|
-
return;
|
|
374
|
-
}
|
|
375
|
-
// В question-режиме LF тоже сабмитит (скрипты/пайпы шлют \n без \r спереди,
|
|
376
|
-
// в отличие от настоящих терминалов).
|
|
377
|
-
if (this.questionCb) {
|
|
378
|
-
this.submit();
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
this.insertNewline();
|
|
382
|
-
return;
|
|
383
|
-
case "backspace":
|
|
384
|
-
this.lastWasCR = false;
|
|
385
|
-
this.backspace();
|
|
386
|
-
return;
|
|
387
|
-
case "delete":
|
|
388
|
-
this.lastWasCR = false;
|
|
389
|
-
this.deleteForward();
|
|
390
|
-
return;
|
|
391
|
-
case "left":
|
|
392
|
-
this.lastWasCR = false;
|
|
393
|
-
this.moveLeft();
|
|
394
|
-
return;
|
|
395
|
-
case "right":
|
|
396
|
-
this.lastWasCR = false;
|
|
397
|
-
this.moveRight();
|
|
398
|
-
return;
|
|
399
|
-
case "up":
|
|
400
|
-
this.lastWasCR = false;
|
|
401
|
-
this.moveUp();
|
|
402
|
-
return;
|
|
403
|
-
case "down":
|
|
404
|
-
this.lastWasCR = false;
|
|
405
|
-
this.moveDown();
|
|
406
|
-
return;
|
|
407
|
-
case "home":
|
|
408
|
-
this.lastWasCR = false;
|
|
409
|
-
this.moveHome();
|
|
410
|
-
return;
|
|
411
|
-
case "end":
|
|
412
|
-
this.lastWasCR = false;
|
|
413
|
-
this.moveEnd();
|
|
414
|
-
return;
|
|
415
|
-
case "pageup":
|
|
416
|
-
this.lastWasCR = false;
|
|
417
|
-
this.moveToStart();
|
|
418
|
-
return;
|
|
419
|
-
case "pagedown":
|
|
420
|
-
this.lastWasCR = false;
|
|
421
|
-
this.moveToEnd();
|
|
422
|
-
return;
|
|
423
|
-
case "tab":
|
|
424
|
-
this.lastWasCR = false;
|
|
425
|
-
this.tabComplete();
|
|
426
|
-
return;
|
|
427
|
-
}
|
|
428
|
-
if (k?.ctrl) {
|
|
429
|
-
this.lastWasCR = false;
|
|
430
|
-
switch (name) {
|
|
431
|
-
case "c":
|
|
432
|
-
this.ctrlC();
|
|
433
|
-
return;
|
|
434
|
-
case "d":
|
|
435
|
-
this.ctrlD();
|
|
436
|
-
return;
|
|
437
|
-
case "a":
|
|
438
|
-
this.moveHome();
|
|
439
|
-
return;
|
|
440
|
-
case "e":
|
|
441
|
-
this.moveEnd();
|
|
442
|
-
return;
|
|
443
|
-
case "u":
|
|
444
|
-
this.killToStart();
|
|
445
|
-
return;
|
|
446
|
-
case "k":
|
|
447
|
-
this.killToEnd();
|
|
448
|
-
return;
|
|
449
|
-
case "w":
|
|
450
|
-
this.killWordBefore();
|
|
451
|
-
return;
|
|
452
|
-
case "l":
|
|
453
|
-
this.clearScreen();
|
|
454
|
-
return;
|
|
455
|
-
default:
|
|
456
|
-
return;
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
if (k?.meta) {
|
|
460
|
-
this.lastWasCR = false;
|
|
461
|
-
switch (name) {
|
|
462
|
-
case "b":
|
|
463
|
-
this.moveWordLeft();
|
|
464
|
-
return;
|
|
465
|
-
case "f":
|
|
466
|
-
this.moveWordRight();
|
|
467
|
-
return;
|
|
468
|
-
case "d":
|
|
469
|
-
this.killWordAfter();
|
|
470
|
-
return;
|
|
471
|
-
default:
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
if (str && !/^[\u0000-\u001f\u007f]/.test(str)) {
|
|
476
|
-
this.lastWasCR = false;
|
|
477
|
-
this.insertText(str);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
submit() {
|
|
481
|
-
this.completionSession = null;
|
|
482
|
-
if (this.questionCb) {
|
|
483
|
-
const cb = this.questionCb;
|
|
484
|
-
this.questionCb = null;
|
|
485
|
-
const answer = this.lines.join("\n").trim();
|
|
486
|
-
this.commitFrame();
|
|
487
|
-
this.output.write("\r\n");
|
|
488
|
-
this.invalidateAnchor();
|
|
489
|
-
this.lines = [""];
|
|
490
|
-
this.row = 0;
|
|
491
|
-
this.col = 0;
|
|
492
|
-
cb(answer);
|
|
493
|
-
return;
|
|
494
|
-
}
|
|
495
|
-
const text = this.lines.join("\n");
|
|
496
|
-
if (text.trim()) {
|
|
497
|
-
this.history.push(text);
|
|
498
|
-
if (this.history.length > this.historySize) {
|
|
499
|
-
this.history = this.history.slice(-this.historySize);
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
this.historyIndex = -1;
|
|
503
|
-
this.stash = null;
|
|
504
|
-
this.commitFrame();
|
|
505
|
-
this.output.write("\r\n");
|
|
506
|
-
this.invalidateAnchor();
|
|
507
|
-
this.lines = [""];
|
|
508
|
-
this.row = 0;
|
|
509
|
-
this.col = 0;
|
|
510
|
-
this.emitLine(text);
|
|
511
|
-
}
|
|
512
|
-
/** Move the cursor to the end of the buffer's last visual row so the
|
|
513
|
-
* submitted text stays on screen (commit), without erasing the frame.
|
|
514
|
-
* Uses the absolute anchor when known — relative moves land short once
|
|
515
|
-
* a tall frame has scrolled the terminal. */
|
|
516
|
-
commitFrame() {
|
|
517
|
-
const layout = this.visibleLayout();
|
|
518
|
-
const lastLen = charLen(stripAnsi(layout[layout.length - 1].text));
|
|
519
|
-
if (this.frameTopAbs !== null) {
|
|
520
|
-
this.output.write(`\x1b[${this.frameTopAbs + layout.length - 1};${lastLen + 1}H`);
|
|
521
|
-
return;
|
|
522
|
-
}
|
|
523
|
-
const idx = layoutIndexFor(layout, this.row, this.col);
|
|
524
|
-
const rowsDown = layout.length - 1 - idx;
|
|
525
|
-
const out = [];
|
|
526
|
-
if (rowsDown > 0)
|
|
527
|
-
out.push(`\x1b[${rowsDown}B`);
|
|
528
|
-
out.push("\r");
|
|
529
|
-
if (lastLen > 0)
|
|
530
|
-
out.push(`\x1b[${lastLen}C`);
|
|
531
|
-
this.output.write(out.join(""));
|
|
532
|
-
}
|
|
533
|
-
ctrlC() {
|
|
534
|
-
this.lines = [""];
|
|
535
|
-
this.row = 0;
|
|
536
|
-
this.col = 0;
|
|
537
|
-
this.completionSession = null;
|
|
538
|
-
this.invalidateAnchor();
|
|
539
|
-
this.render();
|
|
540
|
-
if (this.onInterrupt) {
|
|
541
|
-
this.onInterrupt();
|
|
542
|
-
return;
|
|
543
|
-
}
|
|
544
|
-
// Дефолт: эмитим, только если слушают. С нулём хендлеров process.emit("SIGINT")
|
|
545
|
-
// выполняет действие ПО УМОЛЧАНИЮ (смерть процесса); у REPL слушатель всегда
|
|
546
|
-
// стоит, так что прод не страдает.
|
|
547
|
-
if (process.listenerCount("SIGINT") > 0) {
|
|
548
|
-
process.emit("SIGINT");
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
ctrlD() {
|
|
552
|
-
if (this.lines.length === 1 && this.lines[0] === "") {
|
|
553
|
-
this.emitClose();
|
|
554
|
-
}
|
|
555
|
-
else {
|
|
556
|
-
this.deleteForward();
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
// ── Примитивы правки ──
|
|
560
|
-
currentChars() {
|
|
561
|
-
return Array.from(this.lines[this.row]);
|
|
562
|
-
}
|
|
563
|
-
setCurrentChars(chars) {
|
|
564
|
-
this.lines[this.row] = chars.join("");
|
|
565
|
-
}
|
|
566
|
-
insertText(text) {
|
|
567
|
-
this.completionSession = null;
|
|
568
|
-
const sanitized = text.replace(/\r\n/g, "\n").replace(/\r/g, "");
|
|
569
|
-
const chars = this.currentChars();
|
|
570
|
-
const t = Array.from(sanitized);
|
|
571
|
-
chars.splice(this.col, 0, ...t);
|
|
572
|
-
this.setCurrentChars(chars);
|
|
573
|
-
this.col += t.length;
|
|
574
|
-
this.render();
|
|
575
|
-
}
|
|
576
|
-
/** Пакетная вставка текста под курсор. Режет по переводам строк, чтобы буфер
|
|
577
|
-
* держал строку на элемент (а не литеральные `\n`), и рендерит один раз:
|
|
578
|
-
* вставка должна выглядеть вставкой, а не печатью. */
|
|
579
|
-
insertPaste(text) {
|
|
580
|
-
const segments = text.split("\n");
|
|
581
|
-
if (segments.length === 1) {
|
|
582
|
-
this.insertText(segments[0]);
|
|
583
|
-
return;
|
|
584
|
-
}
|
|
585
|
-
const chars = this.currentChars();
|
|
586
|
-
const head = chars.slice(0, this.col).join("");
|
|
587
|
-
const tail = chars.slice(this.col).join("");
|
|
588
|
-
const lines = [head + segments[0]];
|
|
589
|
-
for (let i = 1; i < segments.length - 1; i++)
|
|
590
|
-
lines.push(segments[i]);
|
|
591
|
-
lines.push(segments[segments.length - 1] + tail);
|
|
592
|
-
this.lines.splice(this.row, 1, ...lines);
|
|
593
|
-
this.row += segments.length - 1;
|
|
594
|
-
this.col = charLen(segments[segments.length - 1]);
|
|
595
|
-
this.render();
|
|
596
|
-
}
|
|
597
|
-
insertNewline() {
|
|
598
|
-
const chars = this.currentChars();
|
|
599
|
-
const rest = chars.slice(this.col).join("");
|
|
600
|
-
this.setCurrentChars(chars.slice(0, this.col));
|
|
601
|
-
this.lines.splice(this.row + 1, 0, rest);
|
|
602
|
-
this.row++;
|
|
603
|
-
this.col = 0;
|
|
604
|
-
this.render();
|
|
605
|
-
}
|
|
606
|
-
backspace() {
|
|
607
|
-
const chars = this.currentChars();
|
|
608
|
-
if (this.col > 0) {
|
|
609
|
-
chars.splice(this.col - 1, 1);
|
|
610
|
-
this.setCurrentChars(chars);
|
|
611
|
-
this.col--;
|
|
612
|
-
}
|
|
613
|
-
else if (this.row > 0) {
|
|
614
|
-
const prevLen = charLen(this.lines[this.row - 1]);
|
|
615
|
-
this.lines[this.row - 1] = this.lines[this.row - 1] + this.lines[this.row];
|
|
616
|
-
this.lines.splice(this.row, 1);
|
|
617
|
-
this.row--;
|
|
618
|
-
this.col = prevLen;
|
|
619
|
-
}
|
|
620
|
-
this.render();
|
|
621
|
-
}
|
|
622
|
-
deleteForward() {
|
|
623
|
-
const chars = this.currentChars();
|
|
624
|
-
if (this.col < chars.length) {
|
|
625
|
-
chars.splice(this.col, 1);
|
|
626
|
-
this.setCurrentChars(chars);
|
|
627
|
-
}
|
|
628
|
-
else if (this.row < this.lines.length - 1) {
|
|
629
|
-
this.lines[this.row] = this.lines[this.row] + this.lines[this.row + 1];
|
|
630
|
-
this.lines.splice(this.row + 1, 1);
|
|
631
|
-
}
|
|
632
|
-
this.render();
|
|
633
|
-
}
|
|
634
|
-
killToStart() {
|
|
635
|
-
const chars = this.currentChars();
|
|
636
|
-
this.setCurrentChars(chars.slice(this.col));
|
|
637
|
-
this.col = 0;
|
|
638
|
-
this.render();
|
|
639
|
-
}
|
|
640
|
-
killToEnd() {
|
|
641
|
-
const chars = this.currentChars();
|
|
642
|
-
this.setCurrentChars(chars.slice(0, this.col));
|
|
643
|
-
this.render();
|
|
644
|
-
}
|
|
645
|
-
killWordBefore() {
|
|
646
|
-
const chars = this.currentChars();
|
|
647
|
-
let i = this.col;
|
|
648
|
-
while (i > 0 && /\s/.test(chars[i - 1]))
|
|
649
|
-
i--;
|
|
650
|
-
while (i > 0 && !/\s/.test(chars[i - 1]))
|
|
651
|
-
i--;
|
|
652
|
-
chars.splice(i, this.col - i);
|
|
653
|
-
this.setCurrentChars(chars);
|
|
654
|
-
this.col = i;
|
|
655
|
-
this.render();
|
|
656
|
-
}
|
|
657
|
-
killWordAfter() {
|
|
658
|
-
const chars = this.currentChars();
|
|
659
|
-
const n = chars.length;
|
|
660
|
-
let i = this.col;
|
|
661
|
-
while (i < n && /\s/.test(chars[i]))
|
|
662
|
-
i++;
|
|
663
|
-
while (i < n && !/\s/.test(chars[i]))
|
|
664
|
-
i++;
|
|
665
|
-
chars.splice(this.col, i - this.col);
|
|
666
|
-
this.setCurrentChars(chars);
|
|
667
|
-
this.render();
|
|
668
|
-
}
|
|
669
|
-
// ---- navigation ----
|
|
670
|
-
moveLeft() {
|
|
671
|
-
if (this.col > 0) {
|
|
672
|
-
this.col--;
|
|
673
|
-
}
|
|
674
|
-
else if (this.row > 0) {
|
|
675
|
-
this.row--;
|
|
676
|
-
this.col = charLen(this.lines[this.row]);
|
|
677
|
-
}
|
|
678
|
-
this.render();
|
|
679
|
-
}
|
|
680
|
-
moveRight() {
|
|
681
|
-
if (this.col < charLen(this.lines[this.row])) {
|
|
682
|
-
this.col++;
|
|
683
|
-
}
|
|
684
|
-
else if (this.row < this.lines.length - 1) {
|
|
685
|
-
this.row++;
|
|
686
|
-
this.col = 0;
|
|
687
|
-
}
|
|
688
|
-
this.render();
|
|
689
|
-
}
|
|
690
|
-
moveUp() {
|
|
691
|
-
const layout = this.layout();
|
|
692
|
-
const idx = layoutIndexFor(layout, this.row, this.col);
|
|
693
|
-
const vcol = visualColAt(layout, idx, this.col);
|
|
694
|
-
if (idx > 0) {
|
|
695
|
-
const target = layout[idx - 1];
|
|
696
|
-
this.row = target.bufRow;
|
|
697
|
-
this.col = charOffsetFor(layout, idx - 1, vcol);
|
|
698
|
-
this.render();
|
|
699
|
-
}
|
|
700
|
-
else {
|
|
701
|
-
this.historyPrev();
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
moveDown() {
|
|
705
|
-
const layout = this.layout();
|
|
706
|
-
const idx = layoutIndexFor(layout, this.row, this.col);
|
|
707
|
-
const vcol = visualColAt(layout, idx, this.col);
|
|
708
|
-
if (idx < layout.length - 1) {
|
|
709
|
-
const target = layout[idx + 1];
|
|
710
|
-
this.row = target.bufRow;
|
|
711
|
-
this.col = charOffsetFor(layout, idx + 1, vcol);
|
|
712
|
-
this.render();
|
|
713
|
-
}
|
|
714
|
-
else {
|
|
715
|
-
this.historyNext();
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
moveHome() {
|
|
719
|
-
this.col = 0;
|
|
720
|
-
this.render();
|
|
721
|
-
}
|
|
722
|
-
moveEnd() {
|
|
723
|
-
this.col = charLen(this.lines[this.row]);
|
|
724
|
-
this.render();
|
|
725
|
-
}
|
|
726
|
-
moveToStart() {
|
|
727
|
-
this.row = 0;
|
|
728
|
-
this.col = 0;
|
|
729
|
-
this.render();
|
|
730
|
-
}
|
|
731
|
-
moveToEnd() {
|
|
732
|
-
this.row = this.lines.length - 1;
|
|
733
|
-
this.col = charLen(this.lines[this.row]);
|
|
734
|
-
this.render();
|
|
735
|
-
}
|
|
736
|
-
moveWordLeft() {
|
|
737
|
-
const chars = this.currentChars();
|
|
738
|
-
let i = this.col;
|
|
739
|
-
while (i > 0 && /\s/.test(chars[i - 1]))
|
|
740
|
-
i--;
|
|
741
|
-
while (i > 0 && !/\s/.test(chars[i - 1]))
|
|
742
|
-
i--;
|
|
743
|
-
this.col = i;
|
|
744
|
-
this.render();
|
|
745
|
-
}
|
|
746
|
-
moveWordRight() {
|
|
747
|
-
const chars = this.currentChars();
|
|
748
|
-
const n = chars.length;
|
|
749
|
-
let i = this.col;
|
|
750
|
-
while (i < n && !/\s/.test(chars[i]))
|
|
751
|
-
i++;
|
|
752
|
-
while (i < n && /\s/.test(chars[i]))
|
|
753
|
-
i++;
|
|
754
|
-
this.col = i;
|
|
755
|
-
this.render();
|
|
756
|
-
}
|
|
757
|
-
historyPrev() {
|
|
758
|
-
if (this.history.length === 0)
|
|
759
|
-
return;
|
|
760
|
-
if (this.historyIndex === -1) {
|
|
761
|
-
this.stash = {
|
|
762
|
-
lines: this.lines.slice(),
|
|
763
|
-
row: this.row,
|
|
764
|
-
col: this.col,
|
|
765
|
-
};
|
|
766
|
-
this.historyIndex = 0;
|
|
767
|
-
}
|
|
768
|
-
else if (this.historyIndex < this.history.length - 1) {
|
|
769
|
-
this.historyIndex++;
|
|
770
|
-
}
|
|
771
|
-
else {
|
|
772
|
-
return;
|
|
773
|
-
}
|
|
774
|
-
this.applyHistoryEntry();
|
|
775
|
-
}
|
|
776
|
-
historyNext() {
|
|
777
|
-
if (this.historyIndex === -1)
|
|
778
|
-
return;
|
|
779
|
-
if (this.historyIndex > 0) {
|
|
780
|
-
this.historyIndex--;
|
|
781
|
-
this.applyHistoryEntry();
|
|
782
|
-
}
|
|
783
|
-
else if (this.stash) {
|
|
784
|
-
this.lines = this.stash.lines.slice();
|
|
785
|
-
this.row = this.stash.row;
|
|
786
|
-
this.col = this.stash.col;
|
|
787
|
-
this.historyIndex = -1;
|
|
788
|
-
this.stash = null;
|
|
789
|
-
this.render();
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
applyHistoryEntry() {
|
|
793
|
-
this.completionSession = null;
|
|
794
|
-
const entry = this.history[this.history.length - 1 - this.historyIndex];
|
|
795
|
-
this.lines = entry.split("\n");
|
|
796
|
-
if (this.lines.length === 0)
|
|
797
|
-
this.lines = [""];
|
|
798
|
-
this.row = this.lines.length - 1;
|
|
799
|
-
this.col = charLen(this.lines[this.row]);
|
|
800
|
-
this.render();
|
|
801
|
-
}
|
|
802
|
-
// ---- completion / misc ----
|
|
803
|
-
/** Replace the UTF-16 range `[from, from + removeText.length)` on the
|
|
804
|
-
* current buffer line with `insertText`, placing the cursor right after. */
|
|
805
|
-
replaceCompletionToken(from, removeText, insertText) {
|
|
806
|
-
const line = this.lines[this.row];
|
|
807
|
-
const head = line.slice(0, from);
|
|
808
|
-
const tail = line.slice(from + removeText.length);
|
|
809
|
-
this.lines[this.row] = head + insertText + tail;
|
|
810
|
-
this.col = charLen(head) + charLen(insertText);
|
|
811
|
-
}
|
|
812
|
-
/** Position of `partial` under the cursor (fallback: last in the line), or
|
|
813
|
-
* -1 when not found. */
|
|
814
|
-
partialStart(line, partial) {
|
|
815
|
-
const chars = Array.from(line);
|
|
816
|
-
const beforeCursor = chars.slice(0, this.col).join("");
|
|
817
|
-
let from = beforeCursor.lastIndexOf(partial);
|
|
818
|
-
if (from === -1)
|
|
819
|
-
from = line.lastIndexOf(partial);
|
|
820
|
-
return from;
|
|
821
|
-
}
|
|
822
|
-
applyCompletionCandidate(index) {
|
|
823
|
-
const s = this.completionSession;
|
|
824
|
-
if (!s)
|
|
825
|
-
return;
|
|
826
|
-
const chosen = s.items[index].value;
|
|
827
|
-
this.replaceCompletionToken(s.from, s.inserted, chosen);
|
|
828
|
-
s.index = index;
|
|
829
|
-
s.inserted = chosen;
|
|
830
|
-
this.render();
|
|
831
|
-
}
|
|
832
|
-
cycleCompletion(delta) {
|
|
833
|
-
const s = this.completionSession;
|
|
834
|
-
if (!s)
|
|
835
|
-
return;
|
|
836
|
-
const n = s.items.length;
|
|
837
|
-
if (n === 0)
|
|
838
|
-
return;
|
|
839
|
-
const next = (s.index + delta + n) % n;
|
|
840
|
-
this.applyCompletionCandidate(next);
|
|
841
|
-
}
|
|
842
|
-
cancelCompletion() {
|
|
843
|
-
const s = this.completionSession;
|
|
844
|
-
if (!s)
|
|
845
|
-
return;
|
|
846
|
-
this.replaceCompletionToken(s.from, s.inserted, s.original);
|
|
847
|
-
this.completionSession = null;
|
|
848
|
-
this.render();
|
|
849
|
-
}
|
|
850
|
-
tabComplete() {
|
|
851
|
-
if (!this.completer)
|
|
852
|
-
return;
|
|
853
|
-
const line = this.lines[this.row];
|
|
854
|
-
const [matches, partial] = this.completer(line);
|
|
855
|
-
if (matches.length === 0) {
|
|
856
|
-
this.output.write("\x07");
|
|
857
|
-
return;
|
|
858
|
-
}
|
|
859
|
-
if (matches.length === 1) {
|
|
860
|
-
// Дополняем partial ПОД КУРСОРОМ, а не последнее вхождение в строке: при
|
|
861
|
-
// курсоре в середине lastIndexOf() вставлял в конец строки.
|
|
862
|
-
const from = this.partialStart(line, partial);
|
|
863
|
-
if (from === -1) {
|
|
864
|
-
this.output.write("\x07");
|
|
865
|
-
return;
|
|
866
|
-
}
|
|
867
|
-
this.replaceCompletionToken(from, partial, matches[0].value);
|
|
868
|
-
this.render();
|
|
869
|
-
return;
|
|
870
|
-
}
|
|
871
|
-
const from = this.partialStart(line, partial);
|
|
872
|
-
if (from === -1) {
|
|
873
|
-
this.output.write("\x07");
|
|
874
|
-
return;
|
|
875
|
-
}
|
|
876
|
-
const width = this.columns();
|
|
877
|
-
const limit = width - 1;
|
|
878
|
-
const rows = matches.map((m) => {
|
|
879
|
-
const plain = m.description ? ` ${m.value} ${m.description}` : ` ${m.value}`;
|
|
880
|
-
if (limit <= 0)
|
|
881
|
-
return "";
|
|
882
|
-
if (stringWidth(plain) <= limit) {
|
|
883
|
-
return m.description ? ` ${m.value} ${pc.dim(m.description)}` : ` ${m.value}`;
|
|
884
|
-
}
|
|
885
|
-
// Режем по видимым колонкам (одних кодпоинтов мало для CJK/emoji).
|
|
886
|
-
let acc = "";
|
|
887
|
-
let w = 0;
|
|
888
|
-
for (const ch of plain) {
|
|
889
|
-
const cw = stringWidth(ch);
|
|
890
|
-
if (w + cw > limit - 1)
|
|
891
|
-
break;
|
|
892
|
-
acc += ch;
|
|
893
|
-
w += cw;
|
|
894
|
-
}
|
|
895
|
-
return `${acc}…`;
|
|
896
|
-
});
|
|
897
|
-
this.output.write(`\r\n${rows.join("\r\n")}\r\n`);
|
|
898
|
-
// Напечатанный список увёл курсор ниже старого кадра. Сбрасываем абсолютный
|
|
899
|
-
// якорь, чтобы следующий рендер позиционировался ОТНОСИТЕЛЬНО текущего
|
|
900
|
-
// курсора (под списком). Сохранение DSR-якоря возвращало кадр на старую
|
|
901
|
-
// абсолютную строку, и его `\x1b[J` стирал список: на Linux/macOS кандидаты
|
|
902
|
-
// мигали и исчезали.
|
|
903
|
-
this.invalidateAnchor();
|
|
904
|
-
// Старт сессии циклирования с первым кандидатом в буфере:
|
|
905
|
-
// ↑/↓/Tab крутят напечатанный список на месте.
|
|
906
|
-
this.completionSession = {
|
|
907
|
-
items: matches,
|
|
908
|
-
index: 0,
|
|
909
|
-
from,
|
|
910
|
-
original: partial,
|
|
911
|
-
inserted: matches[0].value,
|
|
912
|
-
};
|
|
913
|
-
this.replaceCompletionToken(from, partial, matches[0].value);
|
|
914
|
-
this.render();
|
|
915
|
-
}
|
|
916
|
-
clearScreen() {
|
|
917
|
-
this.output.write("\x1b[2J\x1b[H");
|
|
918
|
-
this.invalidateAnchor();
|
|
919
|
-
this.render();
|
|
920
|
-
}
|
|
921
|
-
// ── Рендеринг ──
|
|
922
|
-
columns() {
|
|
923
|
-
return this.output.columns || 80;
|
|
924
|
-
}
|
|
925
|
-
layout() {
|
|
926
|
-
const promptWidth = stringWidth(stripAnsi(this.promptStr));
|
|
927
|
-
return buildLayout(this.lines, this.columns(), Math.max(1, this.columns() - promptWidth));
|
|
928
|
-
}
|
|
929
|
-
/** 1-based высота терминала, null — неизвестна (тесты / не-TTY). */
|
|
930
|
-
screenRows() {
|
|
931
|
-
const r = this.output.rows;
|
|
932
|
-
return typeof r === "number" && r > 3 ? r : null;
|
|
933
|
-
}
|
|
934
|
-
/**
|
|
935
|
-
* Можно ли слать запрос позиции курсора (`ESC[6n`). На Windows — opt-in:
|
|
936
|
-
* ConPTY может декодировать ответ `ESC[row;colR` как ввод, что портит ответы
|
|
937
|
-
* (визард настройки отвечал на каждый промпт "R").
|
|
938
|
-
* `MMA_DSR=1` форсит вкл, `MMA_DSR=0` — выкл; иначе по умолчанию вкл.
|
|
939
|
-
*/
|
|
940
|
-
dsrEnabled() {
|
|
941
|
-
if (readEnv("DSR") === "1")
|
|
942
|
-
return true;
|
|
943
|
-
if (readEnv("DSR") === "0")
|
|
944
|
-
return false;
|
|
945
|
-
return process.platform !== "win32";
|
|
946
|
-
}
|
|
947
|
-
/** Режет рисуемый кадр до видимого экрана. Кадр выше терминала нельзя
|
|
948
|
-
* перерисовать на месте (верх уехал в скролл), так что рисуется только хвост;
|
|
949
|
-
* абсолютный якорь держит следующий рендер консистентным в любом случае. */
|
|
950
|
-
visibleLayout() {
|
|
951
|
-
const layout = this.layout();
|
|
952
|
-
const H = this.screenRows();
|
|
953
|
-
const maxRows = H ? H - 2 : 0;
|
|
954
|
-
if (maxRows > 0 && layout.length > maxRows) {
|
|
955
|
-
return layout.slice(layout.length - maxRows);
|
|
956
|
-
}
|
|
957
|
-
return layout;
|
|
958
|
-
}
|
|
959
|
-
/** Забывает выученную абсолютную позицию кадра: курсор прыгнул в неизвестное
|
|
960
|
-
* место (внешний вывод, чистка экрана, свежий промпт). Следующий рендер
|
|
961
|
-
* переспросит через DSR. */
|
|
962
|
-
invalidateAnchor() {
|
|
963
|
-
this.frameTopAbs = null;
|
|
964
|
-
this.dsrPending = false;
|
|
965
|
-
this.dsrTail = "";
|
|
966
|
-
this.prevCursorRow = 0;
|
|
967
|
-
if (this.dsrTimer) {
|
|
968
|
-
clearTimeout(this.dsrTimer);
|
|
969
|
-
this.dsrTimer = null;
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
/** Парсит DSR-ответы `ESC[row;colR`. Буферит разрезанные escape между чанками.
|
|
973
|
-
* Принимает максимум один ответ (outstanding-запрос); лишние молча дропаются.
|
|
974
|
-
* Строку валидирует против `screenRows()`, отсекая неправдоподобные значения ConPTY. */
|
|
975
|
-
consumeDsrReplies(chunk) {
|
|
976
|
-
this.dsrTail = (this.dsrTail + chunk).slice(-80);
|
|
977
|
-
const m = /\x1b\[(\d+);(\d+)R/.exec(this.dsrTail);
|
|
978
|
-
if (!m)
|
|
979
|
-
return;
|
|
980
|
-
this.dsrTail = "";
|
|
981
|
-
if (!this.dsrPending)
|
|
982
|
-
return;
|
|
983
|
-
this.dsrPending = false;
|
|
984
|
-
const row = Number(m[1]);
|
|
985
|
-
if (this.dsrTimer) {
|
|
986
|
-
clearTimeout(this.dsrTimer);
|
|
987
|
-
this.dsrTimer = null;
|
|
988
|
-
}
|
|
989
|
-
// Верх кадра = строка ответа минус визуальный ряд курсора на момент запроса.
|
|
990
|
-
// `dsrQueryRow`, а не `prevCursorRow`: промежуточные рендеры могли двинуть
|
|
991
|
-
// курсор, пока запрос летел.
|
|
992
|
-
const top = row - this.dsrQueryRow;
|
|
993
|
-
const H = this.screenRows();
|
|
994
|
-
if (top >= 1 && (H === null || top <= H))
|
|
995
|
-
this.frameTopAbs = top;
|
|
996
|
-
}
|
|
997
|
-
render() {
|
|
998
|
-
if (!this.input.isTTY || this.isDone || this.frameSuspended)
|
|
999
|
-
return;
|
|
1000
|
-
const layout = this.visibleLayout();
|
|
1001
|
-
const promptWidth = stringWidth(stripAnsi(this.promptStr));
|
|
1002
|
-
const idx = layoutIndexFor(layout, this.row, this.col);
|
|
1003
|
-
const vcol = visualColAt(layout, idx, this.col);
|
|
1004
|
-
const rowsAfter = layout.length - idx - 1;
|
|
1005
|
-
const ccol = (idx === 0 ? promptWidth : 0) + vcol;
|
|
1006
|
-
const out = [];
|
|
1007
|
-
// Возврат на первую строку кадра перед перерисовкой. Абсолютное
|
|
1008
|
-
// позиционирование (выученное одним DSR-запросом на промпт) иммунно к
|
|
1009
|
-
// скроллу; относительные ходы вверх — фолбэк до прихода первого ответа.
|
|
1010
|
-
if (this.frameTopAbs !== null) {
|
|
1011
|
-
out.push(`\x1b[${this.frameTopAbs};1H`);
|
|
1012
|
-
}
|
|
1013
|
-
else if (this.prevCursorRow > 0) {
|
|
1014
|
-
out.push(`\x1b[${this.prevCursorRow}A`);
|
|
1015
|
-
out.push("\r");
|
|
1016
|
-
}
|
|
1017
|
-
else {
|
|
1018
|
-
out.push("\r");
|
|
1019
|
-
}
|
|
1020
|
-
for (let i = 0; i < layout.length; i++) {
|
|
1021
|
-
out.push("\x1b[2K");
|
|
1022
|
-
if (i === 0)
|
|
1023
|
-
out.push(this.promptStr);
|
|
1024
|
-
out.push(layout[i].text);
|
|
1025
|
-
if (i < layout.length - 1)
|
|
1026
|
-
out.push("\r\n");
|
|
1027
|
-
}
|
|
1028
|
-
out.push("\x1b[J");
|
|
1029
|
-
if (rowsAfter > 0)
|
|
1030
|
-
out.push(`\x1b[${rowsAfter}A`);
|
|
1031
|
-
out.push("\r");
|
|
1032
|
-
if (ccol > 0)
|
|
1033
|
-
out.push(`\x1b[${ccol}C`);
|
|
1034
|
-
this.output.write(out.join(""));
|
|
1035
|
-
this.prevCursorRow = idx;
|
|
1036
|
-
// Детерминированная скролл-математика: обновляем якорь для СЛЕДУЮЩЕГО рендера.
|
|
1037
|
-
// После записи L строк от frameTopAbs терминал скроллится, если кадр вылез за
|
|
1038
|
-
// низ экрана; новый верх кадра считается локально, новых DSR-запросов не надо.
|
|
1039
|
-
if (this.frameTopAbs !== null) {
|
|
1040
|
-
const H = this.screenRows();
|
|
1041
|
-
if (H) {
|
|
1042
|
-
const T = this.frameTopAbs;
|
|
1043
|
-
const L = layout.length;
|
|
1044
|
-
if (T + L - 1 > H)
|
|
1045
|
-
this.frameTopAbs = H - L + 1;
|
|
1046
|
-
// else: no scroll, anchor unchanged
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
else if (!this.dsrPending && this.questionCb === null && this.dsrEnabled()) {
|
|
1050
|
-
// Один DSR-запрос на кадр, дальше якорь ведёт локальная скролл-математика.
|
|
1051
|
-
// В question-режиме не спрашиваем (см. dsrEnabled). Таймаут сбрасывает
|
|
1052
|
-
// dsrPending, чтобы неотвечающий терминал откатился на относительные ходы.
|
|
1053
|
-
this.dsrPending = true;
|
|
1054
|
-
this.dsrQueryRow = idx;
|
|
1055
|
-
this.output.write("\x1b[6n");
|
|
1056
|
-
if (this.dsrTimer)
|
|
1057
|
-
clearTimeout(this.dsrTimer);
|
|
1058
|
-
this.dsrTimer = setTimeout(() => {
|
|
1059
|
-
this.dsrPending = false;
|
|
1060
|
-
this.dsrTimer = null;
|
|
1061
|
-
}, 150);
|
|
1062
|
-
}
|
|
1063
|
-
}
|
|
1064
|
-
enableTerminalProtocols() {
|
|
1065
|
-
this.output.write("\x1b[?2004h");
|
|
1066
|
-
this.output.write("\x1b[>1u");
|
|
1067
|
-
}
|
|
1068
|
-
disableTerminalProtocols() {
|
|
1069
|
-
this.output.write("\x1b[?2004l");
|
|
1070
|
-
this.output.write("\x1b[<u");
|
|
1071
|
-
}
|
|
1072
|
-
emitLine(line) {
|
|
1073
|
-
this.listeners.line?.(line);
|
|
1074
|
-
}
|
|
1075
|
-
emitClose() {
|
|
1076
|
-
// Сброс финальной строки без перевода из чанкованного не-TTY ввода.
|
|
1077
|
-
if (this.pendingLine) {
|
|
1078
|
-
this.emitLine(this.pendingLine);
|
|
1079
|
-
this.pendingLine = "";
|
|
1080
|
-
}
|
|
1081
|
-
this.listeners.close?.();
|
|
1082
|
-
}
|
|
1083
|
-
}
|