@code-yeongyu/senpi 2026.9.23-2 → 2026.9.23-3
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 +24 -0
- package/dist/bundle/chunks/{app-server-command-UO3ODP6D.js → app-server-command-U5Y46LHO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OLJ7LQJY.js → chunk-BBOQ5H4W.js} +1 -1
- package/dist/bundle/chunks/{chunk-7EH64T6E.js → chunk-ORCF262V.js} +2 -2
- package/dist/bundle/chunks/{chunk-BPHXJ4N2.js → chunk-R6F525XB.js} +1 -1
- package/dist/bundle/chunks/{chunk-LMO3WYKH.js → chunk-TH4PERSI.js} +131 -124
- package/dist/bundle/chunks/{chunk-IBHBWRC4.js → chunk-TUVSARCZ.js} +2 -2
- package/dist/bundle/chunks/{chunk-WJ2BGYFK.js → chunk-XPDV6SIX.js} +1 -1
- package/dist/bundle/chunks/{chunk-IDJUNOOR.js → chunk-Y4AJLTFT.js} +2 -2
- package/dist/bundle/chunks/{cli-main-LUQZADLN.js → cli-main-65WMMIRT.js} +1 -1
- package/dist/bundle/chunks/{interactive-host-runtime-A6PM52FT.js → interactive-host-runtime-DUNYT24Q.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-VR7QYMAE.js → interactive-mode-SCG5PQZ6.js} +1 -1
- package/dist/bundle/chunks/{list-tips-VGOIMT6W.js → list-tips-Z62FXPOJ.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-LYOVVA75.js → multi-session-host-QC6BZZNH.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-OMEJACX6.js → package-manager-cli-23GULCVL.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-AKGJA73P.js → rpc-mode-ZQ4E6FFA.js} +1 -1
- package/dist/bundle/chunks/{session-picker-UE5LOM6W.js → session-picker-CO2ZK3EC.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +202 -195
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/executable-model-support.d.ts +19 -0
- package/dist/core/extensions/builtin/anthropic-subscription/executable-model-support.d.ts.map +1 -0
- package/dist/core/extensions/builtin/anthropic-subscription/executable-model-support.js +76 -0
- package/dist/core/extensions/builtin/anthropic-subscription/executable-model-support.js.map +1 -0
- package/dist/core/extensions/builtin/anthropic-subscription/executable-path-lookup.d.ts +7 -2
- package/dist/core/extensions/builtin/anthropic-subscription/executable-path-lookup.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/executable-path-lookup.js +28 -3
- package/dist/core/extensions/builtin/anthropic-subscription/executable-path-lookup.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/executable.d.ts +11 -0
- package/dist/core/extensions/builtin/anthropic-subscription/executable.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/executable.js +31 -10
- package/dist/core/extensions/builtin/anthropic-subscription/executable.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/guidance.d.ts +2 -1
- package/dist/core/extensions/builtin/anthropic-subscription/guidance.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/guidance.js +18 -2
- package/dist/core/extensions/builtin/anthropic-subscription/guidance.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream-guidance.d.ts +2 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream-guidance.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream-guidance.js +2 -2
- package/dist/core/extensions/builtin/anthropic-subscription/stream-guidance.js.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream.d.ts.map +1 -1
- package/dist/core/extensions/builtin/anthropic-subscription/stream.js +5 -3
- package/dist/core/extensions/builtin/anthropic-subscription/stream.js.map +1 -1
- package/dist/core/extensions/builtin/goal/cache-warm-renderer.d.ts +6 -0
- package/dist/core/extensions/builtin/goal/cache-warm-renderer.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/cache-warm-renderer.js +8 -0
- package/dist/core/extensions/builtin/goal/cache-warm-renderer.js.map +1 -1
- package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/index.js +4 -2
- package/dist/core/extensions/builtin/goal/index.js.map +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts +3 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
- package/dist/core/extensions/builtin/goal/monitor-continuation.js +32 -10
- package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
- package/dist/core/extensions/builtin/goal/parked-wait.d.ts +16 -0
- package/dist/core/extensions/builtin/goal/parked-wait.d.ts.map +1 -0
- package/dist/core/extensions/builtin/goal/parked-wait.js +54 -0
- package/dist/core/extensions/builtin/goal/parked-wait.js.map +1 -0
- package/dist/core/extensions/builtin/mcp/auth/commands-auth-dispatch.d.ts +1 -1
- package/dist/core/extensions/builtin/mcp/auth/commands-auth-dispatch.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/auth/commands-auth-dispatch.js +8 -2
- package/dist/core/extensions/builtin/mcp/auth/commands-auth-dispatch.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/auth/commands-auth.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/auth/commands-auth.js +15 -4
- package/dist/core/extensions/builtin/mcp/auth/commands-auth.js.map +1 -1
- package/dist/core/extensions/builtin/mcp/commands.d.ts.map +1 -1
- package/dist/core/extensions/builtin/mcp/commands.js +2 -0
- package/dist/core/extensions/builtin/mcp/commands.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts +5 -5
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +16 -11
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +5 -5
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +9 -6
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js.map +1 -1
- package/dist/core/extensions/builtin/prompt-preset/test-decision.d.ts +2 -0
- package/dist/core/extensions/builtin/prompt-preset/test-decision.d.ts.map +1 -0
- package/dist/core/extensions/builtin/prompt-preset/test-decision.js +5 -0
- package/dist/core/extensions/builtin/prompt-preset/test-decision.js.map +1 -0
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +6 -1
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +5 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +10 -1
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/model-config.d.ts +1 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +26 -20
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/models-json-migration.d.ts +30 -0
- package/dist/core/models-json-migration.d.ts.map +1 -0
- package/dist/core/models-json-migration.js +257 -0
- package/dist/core/models-json-migration.js.map +1 -0
- package/dist/core/output-guard.d.ts +2 -0
- package/dist/core/output-guard.d.ts.map +1 -1
- package/dist/core/output-guard.js +31 -0
- package/dist/core/output-guard.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +16 -6
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-overrides.d.ts +8 -0
- package/dist/core/settings-overrides.d.ts.map +1 -0
- package/dist/core/settings-overrides.js +28 -0
- package/dist/core/settings-overrides.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +4 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.d.ts +10 -1
- package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +22 -0
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/exploration-call.d.ts +12 -0
- package/dist/modes/interactive/components/exploration-call.d.ts.map +1 -0
- package/dist/modes/interactive/components/exploration-call.js +41 -0
- package/dist/modes/interactive/components/exploration-call.js.map +1 -0
- package/dist/modes/interactive/components/exploration-group.d.ts +19 -0
- package/dist/modes/interactive/components/exploration-group.d.ts.map +1 -0
- package/dist/modes/interactive/components/exploration-group.js +89 -0
- package/dist/modes/interactive/components/exploration-group.js.map +1 -0
- package/dist/modes/interactive/components/exploration-transcript-container.d.ts +18 -0
- package/dist/modes/interactive/components/exploration-transcript-container.d.ts.map +1 -0
- package/dist/modes/interactive/components/exploration-transcript-container.js +67 -0
- package/dist/modes/interactive/components/exploration-transcript-container.js.map +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts +7 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +24 -35
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/replay-assistant-tools.d.ts +14 -0
- package/dist/modes/interactive/replay-assistant-tools.d.ts.map +1 -0
- package/dist/modes/interactive/replay-assistant-tools.js +33 -0
- package/dist/modes/interactive/replay-assistant-tools.js.map +1 -0
- package/dist/modes/interactive/tool-progress.d.ts +2 -0
- package/dist/modes/interactive/tool-progress.d.ts.map +1 -1
- package/dist/modes/interactive/tool-progress.js +5 -2
- package/dist/modes/interactive/tool-progress.js.map +1 -1
- package/dist/modes/interactive/tui-renderer.d.ts.map +1 -1
- package/dist/modes/interactive/tui-renderer.js +6 -1
- package/dist/modes/interactive/tui-renderer.js.map +1 -1
- package/docs/extensions.md +8 -0
- package/docs/mcp.md +9 -6
- package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +16 -0
- package/node_modules/@code-yeongyu/senpi-codemode/README.md +10 -8
- package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/display-code.ts +145 -0
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-request.ts +7 -12
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +2 -2
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/render.ts +34 -16
- package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +1 -4
- package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/node_modules/@earendil-works/pi-pty/package.json +1 -1
- package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/stderr-observer.d.ts +3 -0
- package/node_modules/@earendil-works/pi-tui/dist/stderr-observer.d.ts.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/stderr-observer.js +14 -0
- package/node_modules/@earendil-works/pi-tui/dist/stderr-observer.js.map +1 -0
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +4 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js +8 -12
- package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
- package/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -12,6 +12,30 @@
|
|
|
12
12
|
|
|
13
13
|
### Removed
|
|
14
14
|
|
|
15
|
+
## [2026.9.23-3] - 2026-09-23
|
|
16
|
+
|
|
17
|
+
### Breaking Changes
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
|
|
21
|
+
- The interactive TUI shows consecutive `read`, `grep`, `find`, and `ls` calls as one exploration cell, the way Codex does: `• Explored` followed by lines such as `Read a.ts, b.ts`, `Search <pattern> in <dir>`, and `List <dir>`, with no line ranges or output. Reading one file three times now shows its name once instead of three cards. A failed call stays in the cell and is counted as ` · 1 failed`. Press the tool-expand key (default `ctrl+o`) or click the header to see the original cards. Any other tool, assistant text, or your next message ends the cell, and resumed sessions show the same cells. ([#2042](https://github.com/code-yeongyu/senpi/issues/2042))
|
|
22
|
+
|
|
23
|
+
### Changed
|
|
24
|
+
|
|
25
|
+
- The GPT-5.6 and GPT-6 system prompts no longer demand a failing test before every behavior change. They now read the tests that already cover the area as the behavior of record, reproduce a bug before fixing it, let the run prove the change, and add a test only where the repository keeps tests for that behavior and a regression would otherwise pass unnoticed - the stance the Claude and Kimi prompts already had. Sessions on those models stop producing tests that only restate a small change. ([#2035](https://github.com/code-yeongyu/senpi/issues/2035))
|
|
26
|
+
|
|
27
|
+
### Fixed
|
|
28
|
+
|
|
29
|
+
- A Goal parked on a live wake source shows one `Cache-warm` card per wait instead of a stack of `iteration 1` cards. A config reload used to re-append the parked wait as a new iteration-1 card, drop its cache line, and restart the backstop clock from the reload, which could push the wake past the prompt-cache TTL the card promised; the reload now keeps the same wait, iteration, cache figures, and ready time. The wait card also turns into the `Cache-warm wake` card when the wait ends instead of stacking a second card, and resumed sessions that already recorded stacked cards show one. Extensions can opt into the same in-place update with the new `replaces` option of `pi.registerEntryRenderer()`. ([#2051](https://github.com/code-yeongyu/senpi/issues/2051))
|
|
30
|
+
|
|
31
|
+
- Hidden diagnostics no longer duplicate the terminal screen when mouse capture is enabled. Messages saved only to the debug log leave the current frame intact; errors actually printed to the terminal still reset mouse targeting. ([#1879](https://github.com/code-yeongyu/senpi/issues/1879))
|
|
32
|
+
- A `models.json` written before the subscription provider rename is now updated to the new provider ids (`chatgpt-subscription`, `anthropic-subscription`) automatically on the first launch, keeping its comments and formatting and a timestamped backup of the original, instead of printing "models.json uses renamed provider ids" on every launch. ([#2044](https://github.com/code-yeongyu/senpi/issues/2044))
|
|
33
|
+
- `--no-model-fallback`, `SENPI_NO_FALLBACK=1`, `--no-ask-user` and `--theme` now hold for the whole session. They were silently dropped the first time the session saved any setting, so a run that opted out of model fallback could still answer from a different model. Changing the same setting yourself during the session (for example with `/fallback`) still takes effect. ([#2052](https://github.com/code-yeongyu/senpi/issues/2052))
|
|
34
|
+
- When a Claude subscription model rejects the local Claude Code as too old, the message now names the binary that ran and where it came from (`CLAUDE_CODE_EXECUTABLE`, the copy senpi ships, or `claude` on your PATH) and gives the fix that works for that binary, instead of always telling you to update senpi. On Windows, a Claude Code installed with `npm i -g @anthropic-ai/claude-code` is now found and used when it is newer than the bundled copy. ([#2053](https://github.com/code-yeongyu/senpi/issues/2053))
|
|
35
|
+
- `/mcp auth <server>` opens the system browser and keeps the complete authorization URL in the transcript instead of replacing it with a progress notice. Browser launch failures leave manual authorization usable, and the MCP documentation now names the supported `auth`, `auth-start`, and `auth-complete` commands. ([oh-my-openagent#6724](https://github.com/code-yeongyu/oh-my-openagent/issues/6724))
|
|
36
|
+
|
|
37
|
+
### Removed
|
|
38
|
+
|
|
15
39
|
## [2026.9.23-2] - 2026-09-23
|
|
16
40
|
|
|
17
41
|
### Breaking Changes
|
package/dist/bundle/chunks/{app-server-command-UO3ODP6D.js → app-server-command-U5Y46LHO.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{import_websocket_server,wrapper_default}from"./chunk-YBZDAABT.js";import{AuthStorage,DefaultResourceLoader,GOAL_STORE_CHANGED_EVENT,ModelRegistry,clearGoal,createAgentSession,createGoal,createPendingQuestion,defaultModelPerProvider,formatProviderNativeBody,formatProviderNativeSummary,getMcpService,goalStoreRef,loadMcpConfig,loadSkills,readGoal,resolveAuthMode,updateGoal}from"./chunk-
|
|
2
|
+
import{import_websocket_server,wrapper_default}from"./chunk-YBZDAABT.js";import{AuthStorage,DefaultResourceLoader,GOAL_STORE_CHANGED_EVENT,ModelRegistry,clearGoal,createAgentSession,createGoal,createPendingQuestion,defaultModelPerProvider,formatProviderNativeBody,formatProviderNativeSummary,getMcpService,goalStoreRef,loadMcpConfig,loadSkills,readGoal,resolveAuthMode,updateGoal}from"./chunk-TH4PERSI.js";import{require_ignore}from"./chunk-R6F525XB.js";import"./chunk-UYCGOK6M.js";import"./chunk-BBOQ5H4W.js";import{SessionManager,loadEntriesFromFile}from"./chunk-67Z5WNA4.js";import"./chunk-GFUZPFHN.js";import{getCredentialAccounts,getModels,getProviders,getSupportedThinkingLevels,pinCredentialAccount,removeCredentialAccount,subscribeProviderAccountEvents}from"./chunk-XPDV6SIX.js";import{getAvailableThemesWithPaths,getThemeByName,takeOverStdout,theme,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-Y4AJLTFT.js";import{x}from"./chunk-ORCF262V.js";import"./chunk-XTXBPXZZ.js";import{SettingsManager}from"./chunk-TUVSARCZ.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-DUV3UFKX.js";import{acquireOwnershipSafeLock}from"./chunk-3XHWW7SQ.js";import"./chunk-HH3KJDWA.js";import{parseDaemonPidFile,processMatchesPidFile,readProcessStartTime,stopValidatedPid,waitForGone,waitForStartTime}from"./chunk-7PANH3NB.js";import{attachJsonlLineReader}from"./chunk-NNHFMZD5.js";import"./chunk-FIJJKSPL.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-IDSOMHWS.js";import"./chunk-2NFHX2FJ.js";import"./chunk-FHXKBENX.js";import"./chunk-X3T45623.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-HKE42SWX.js";import"./chunk-SUQDU5KM.js";import"./chunk-VKBY4F76.js";import"./chunk-26UBFF6N.js";import"./chunk-UCTYTLP3.js";import"./chunk-L6JO4M6J.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-KLDLZHHS.js";import"./chunk-PRC5XIIH.js";import"./chunk-34HMVB33.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_SESSION_DIR,VERSION,getAgentDir,getSessionsDir,resolvePath}from"./chunk-Y65WFI5H.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-IXAUDPOK.js";import"./chunk-XYM54ZWK.js";import"./chunk-WVGCQOLJ.js";import"./chunk-BPX6QWPD.js";import{normalizeProviderId}from"./chunk-IVYZMSFY.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import{__toESM}from"./chunk-IKOFCODM.js";import{isIP}from"node:net";var APP_SERVER_LISTEN_USAGE="Invalid --listen value. Use stdio://, unix://, unix:///abs/path, or ws://IP:PORT.";function formatAppServerUsage(){let listenForms="stdio://|unix://|unix:///abs/path|ws://IP:PORT";return[`Usage: ${APP_NAME} app-server [--listen <${listenForms}>] [--ws-auth <token-file|off>] [--json-logs]`,` ${APP_NAME} app-server daemon <start|stop|status|restart> [--listen <${listenForms}>]`].join(`
|
|
3
3
|
`)}function parseListen(value){if(value==="stdio://")return{kind:"stdio",url:"stdio://"};if(value==="unix://")return{kind:"unix",url:"unix://"};if(value.startsWith("unix:///")){let path=value.slice(7);return path.startsWith("/")?{kind:"unix",url:value,path}:void 0}if(!value.startsWith("ws://"))return;let parsed;try{parsed=new URL(value)}catch(error){if(error instanceof TypeError)return;throw error}let port=Number(parsed.port);if(!(parsed.protocol!=="ws:"||parsed.username!==""||parsed.password!==""||parsed.pathname!=="/"||parsed.search!==""||parsed.hash!==""||parsed.port===""||!Number.isInteger(port)||port<1||port>65535||isIP(parsed.hostname)===0))return{kind:"ws",url:value,host:parsed.hostname,port}}function parseDaemonVerb(value){switch(value){case"start":case"stop":case"status":case"restart":return value;default:return}}function parseWsAuth(value){return value==="off"?{kind:"off"}:{kind:"token-file",path:value}}function parseServerArgs(args){let listen3={kind:"stdio",url:"stdio://"},wsAuth,jsonLogs=!1;for(let index=0;index<args.length;index++){let arg=args[index];if(arg==="--listen"){let value=args[index+1];if(value===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};let parsed=parseListen(value);if(parsed===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};listen3=parsed,index++;continue}if(arg==="--ws-auth"){let value=args[index+1];if(value===void 0)return{kind:"usage-error",message:"--ws-auth requires <token-file|off>."};wsAuth=parseWsAuth(value),index++;continue}if(arg==="--json-logs"){jsonLogs=!0;continue}return{kind:"usage-error",message:`Unexpected app-server argument: ${arg}`}}return{kind:"server",listen:listen3,wsAuth,jsonLogs}}function parseDaemonArgs(args){let verb=parseDaemonVerb(args[0]);if(verb===void 0)return{kind:"usage-error",message:"Usage: app-server daemon <start|stop|status|restart>."};let listen3={kind:"ws",url:"ws://127.0.0.1:18800",host:"127.0.0.1",port:18800};for(let index=1;index<args.length;index++){let arg=args[index];if(arg==="--listen"){let value=args[index+1];if(value===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};let parsed=parseListen(value);if(parsed===void 0)return{kind:"usage-error",message:APP_SERVER_LISTEN_USAGE};listen3=parsed,index++;continue}return{kind:"usage-error",message:`Unexpected app-server daemon argument: ${arg}`}}return{kind:"daemon",verb,listen:listen3}}function parseAppServerCliArgs(args){return args[0]==="daemon"?parseDaemonArgs(args.slice(1)):parseServerArgs(args)}var RpcHandlerError=class extends Error{constructor(error){super(error.message),this.name="RpcHandlerError",this.rpcError=error}};function invalidRequestError(){return{code:-32600,message:"Invalid request"}}function methodNotFoundError(method){return{code:-32601,message:`Method not found: ${method}`}}function invalidParamsError(){return{code:-32602,message:"Invalid params"}}function internalError(message="Internal error"){return{code:-32603,message}}function notInitializedError(){return{code:-32600,message:"Not initialized"}}function alreadyInitializedError(){return{code:-32600,message:"Already initialized"}}function experimentalCapabilityError(method){return{code:-32600,message:`${method} requires experimentalApi capability`}}function registerExtensionRequestMethod(registry,getThread){registry.register("extension_request",{scope:"thread",handler:async({request})=>{let params=request.params;if(typeof params!="object"||params===null||Array.isArray(params))throw new RpcHandlerError({code:-32602,message:"Invalid params"});let threadId=Reflect.get(params,"threadId"),name=Reflect.get(params,"name");if(typeof threadId!="string"||threadId.length===0||typeof name!="string"||name.length===0)throw new RpcHandlerError({code:-32602,message:"Invalid params"});try{return await getThread(threadId).extensionRunner.requestRpc(name,Reflect.get(params,"data"))}catch(error){throw new RpcHandlerError(internalError(error instanceof Error?error.message:String(error)))}}})}function createRegistry(){return new InMemoryMethodRegistry}var InMemoryMethodRegistry=class{constructor(){this.methods=new Map}register(method,registration){this.methods.set(method,registration)}async dispatch(connection,request){if(!connection.initialized){let registration2=this.methods.get(request.method);if(request.method!=="initialize"||registration2?.requiresInit!==!1)return{id:request.id,error:notInitializedError()}}if(connection.initialized&&request.method==="initialize")return{id:request.id,error:alreadyInitializedError()};let registration=this.methods.get(request.method);if(!registration)return{id:request.id,error:methodNotFoundError(request.method)};if(registration.experimental===!0&&connection.capabilities?.experimentalApi!==!0)return{id:request.id,error:experimentalCapabilityError(request.method)};try{let result=await registration.handler({connection,request});return{id:request.id,result}}catch(error){return error instanceof RpcHandlerError?{id:request.id,error:error.rpcError}:{id:request.id,error:internalError(error instanceof Error?error.message:String(error))}}}};function registerFuzzyFileSearchMethods(registry,service){registry.register("fuzzyFileSearch",{scope:"global",handler:({request})=>service.search(parseOneShotParams(request.params))}),registry.register("fuzzyFileSearch/sessionStart",{experimental:!0,scope:"global",handler:({request})=>service.startSession(parseSessionStartParams(request.params))}),registry.register("fuzzyFileSearch/sessionUpdate",{experimental:!0,scope:"global",handler:({request})=>service.updateSession(parseSessionUpdateParams(request.params))}),registry.register("fuzzyFileSearch/sessionStop",{experimental:!0,scope:"global",handler:({request})=>service.stopSession(parseSessionStopParams(request.params))})}function parseOneShotParams(value){let params=objectParams(value,"fuzzyFileSearch");return{query:requiredString(params.query,"fuzzyFileSearch query"),roots:requiredStringArray(params.roots,"fuzzyFileSearch roots"),cancellationToken:optionalString(params.cancellationToken,"fuzzyFileSearch cancellationToken")}}function parseSessionStartParams(value){let params=objectParams(value,"fuzzyFileSearch/sessionStart");return{sessionId:requiredString(params.sessionId,"fuzzyFileSearch/sessionStart sessionId"),roots:requiredStringArray(params.roots,"fuzzyFileSearch/sessionStart roots")}}function parseSessionUpdateParams(value){let params=objectParams(value,"fuzzyFileSearch/sessionUpdate");return{sessionId:requiredString(params.sessionId,"fuzzyFileSearch/sessionUpdate sessionId"),query:requiredString(params.query,"fuzzyFileSearch/sessionUpdate query")}}function parseSessionStopParams(value){let params=objectParams(value,"fuzzyFileSearch/sessionStop");return{sessionId:requiredString(params.sessionId,"fuzzyFileSearch/sessionStop sessionId")}}function objectParams(value,method){if(!isRecord(value))throw invalidRequest(`${method} params must be an object`);return value}function requiredString(value,field){if(typeof value!="string")throw invalidRequest(`${field} must be a string`);return value}function requiredStringArray(value,field){if(!Array.isArray(value)||value.some(entry=>typeof entry!="string"))throw invalidRequest(`${field} must be an array of strings`);return value}function optionalString(value,field){if(value==null)return null;if(typeof value!="string")throw invalidRequest(`${field} must be a string or null`);return value}function invalidRequest(message){return new RpcHandlerError({code:-32600,message})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}import{lstat,readdir}from"node:fs/promises";import{basename,join as join2,relative as relative2,resolve,sep as sep2}from"node:path";var import_ignore=__toESM(require_ignore(),1);import{readFile}from"node:fs/promises";import{join,relative,sep}from"node:path";async function addGitignoreScope(matchers,directory){let gitignore=await readableText(join(directory,".gitignore"));return gitignore===void 0?matchers:[...matchers,{directory,matcher:(0,import_ignore.default)().add(gitignore)}]}function isIgnored(matchers,path,isDirectory){let ignored=!1;for(let scope of matchers){let relativePath=relative(scope.directory,path).split(sep).join("/"),result=scope.matcher.test(isDirectory?`${relativePath}/`:relativePath);result.ignored&&(ignored=!0),result.unignored&&(ignored=!1)}return ignored}async function readableText(path){try{return await readFile(path,"utf8")}catch(error){if(error instanceof Error)return;throw error}}var FUZZY_SEARCH_MAX_DEPTH=12,FUZZY_SEARCH_MAX_VISITED_ENTRIES=5e4,FUZZY_SEARCH_RESULT_LIMIT=50,FILENAME_MATCH_BONUS=1e6,CHARACTER_MATCH_SCORE=10,CONTIGUOUS_MATCH_BONUS=20,BOUNDARY_MATCH_BONUS=5,CANCELLATION_YIELD_INTERVAL=256;async function collectFuzzyFileEntries(roots,options={}){let entries=[],state={visitedEntries:0,stopped:!1},maxDepth=options.maxDepth??FUZZY_SEARCH_MAX_DEPTH,maxVisitedEntries=options.maxVisitedEntries??FUZZY_SEARCH_MAX_VISITED_ENTRIES;for(let root of roots){if(options.signal?.aborted||state.stopped)break;let absoluteRoot=resolve(root),rootStat=await readableStat(absoluteRoot);!rootStat?.isDirectory()||rootStat.isSymbolicLink()||await walkDirectory({wireRoot:root,absoluteRoot,absoluteDirectory:absoluteRoot,depth:0,matchers:[],entries,state,signal:options.signal,maxDepth,maxVisitedEntries})}return entries}function rankFuzzyFileEntries(query,entries){if(query.length===0)return[];let results=[];for(let entry of entries){let filenameMatch=scoreSubsequence(entry.fileName,query),pathMatch=filenameMatch??scoreSubsequence(entry.path,query);if(!pathMatch)continue;let filenameOffset=Array.from(entry.path).length-Array.from(entry.fileName).length,indices=filenameMatch?filenameMatch.indices.map(index=>index+filenameOffset):pathMatch.indices;results.push({root:entry.root,path:entry.path,match_type:entry.matchType,file_name:entry.fileName,score:pathMatch.score+(filenameMatch?FILENAME_MATCH_BONUS:0),indices})}return results.sort(compareResults),results.slice(0,FUZZY_SEARCH_RESULT_LIMIT)}async function walkDirectory(input){let matchers=await addGitignoreScope(input.matchers,input.absoluteDirectory),directoryEntries=await readableDirectory(input.absoluteDirectory);directoryEntries.sort((left,right)=>compareText(left.name,right.name));for(let directoryEntry of directoryEntries){if(input.signal?.aborted||input.state.stopped)return;if(input.state.visitedEntries>=input.maxVisitedEntries){input.state.stopped=!0;return}if(input.state.visitedEntries+=1,directoryEntry.name===".git"||directoryEntry.name==="node_modules"||directoryEntry.isSymbolicLink())continue;let isDirectory=directoryEntry.isDirectory();if(!isDirectory&&!directoryEntry.isFile())continue;let absolutePath=join2(input.absoluteDirectory,directoryEntry.name),relativePath=toPosixPath(relative2(input.absoluteRoot,absolutePath));if(isIgnored(matchers,absolutePath,isDirectory))continue;input.entries.push({root:input.wireRoot,path:relativePath,matchType:isDirectory?"directory":"file",fileName:basename(relativePath)});let entryDepth=input.depth+1;isDirectory&&entryDepth<input.maxDepth&&await walkDirectory({...input,absoluteDirectory:absolutePath,depth:entryDepth,matchers}),input.state.visitedEntries%CANCELLATION_YIELD_INTERVAL===0&&await yieldToEventLoop()}}function scoreSubsequence(candidate,query){let normalizedCandidate=normalizeText(candidate),normalizedQuery=query.toLowerCase(),contiguousStart=normalizedCandidate.value.indexOf(normalizedQuery),normalizedIndices=[];if(contiguousStart>=0){let cursor=contiguousStart;for(let character of normalizedQuery)normalizedIndices.push(cursor),cursor+=character.length}else{let cursor=0;for(let character of normalizedQuery){let matchIndex=normalizedCandidate.value.indexOf(character,cursor);if(matchIndex<0)return;normalizedIndices.push(matchIndex),cursor=matchIndex+character.length}}let indices=[];for(let normalizedIndex of normalizedIndices){let sourceIndex=normalizedCandidate.sourceIndices[normalizedIndex];if(sourceIndex===void 0)return;indices.at(-1)!==sourceIndex&&indices.push(sourceIndex)}let candidateCharacters=Array.from(candidate),score=indices.length*CHARACTER_MATCH_SCORE;for(let index=0;index<indices.length;index++){let current=indices[index];if(current===void 0)continue;let previous=indices[index-1];previous!==void 0&¤t===previous+1&&(score+=CONTIGUOUS_MATCH_BONUS),(current===0||isBoundary(candidateCharacters[current-1]))&&(score+=BOUNDARY_MATCH_BONUS)}return{score,indices}}function normalizeText(value){let sourceIndices=[];for(let[sourceIndex,character]of Array.from(value).entries())for(let index=0;index<character.toLowerCase().length;index++)sourceIndices.push(sourceIndex);return{value:value.toLowerCase(),sourceIndices}}function compareResults(left,right){return left.score!==right.score?right.score-left.score:compareText(left.path,right.path)}function compareText(left,right){return left<right?-1:left>right?1:0}function isBoundary(character){return character==="/"||character==="-"||character==="_"||character==="."||character===" "}async function readableDirectory(path){try{return await readdir(path,{withFileTypes:!0})}catch(error){if(error instanceof Error)return[];throw error}}async function readableStat(path){try{return await lstat(path)}catch(error){if(error instanceof Error)return;throw error}}function toPosixPath(path){return path.split(sep2).join("/")}function yieldToEventLoop(){return new Promise(resolve4=>setImmediate(resolve4))}var FuzzyFileSearchService=class{constructor(options){this.activeSearches=new Set,this.pendingSearches=new Map,this.sessions=new Map,this.disposed=!1,this.broadcast=options.broadcast,this.collectEntries=options.collectEntries??((roots,signal)=>collectFuzzyFileEntries(roots,{signal})),this.rankEntries=options.rankEntries??rankFuzzyFileEntries}async search(params){if(this.disposed)return{files:[]};let controller=new AbortController;this.activeSearches.add(controller);let token=params.cancellationToken;token!==null&&(this.pendingSearches.get(token)?.abort(),this.pendingSearches.set(token,controller));try{if(params.query.length===0)return{files:[]};let entries=await this.collectEntries(params.roots,controller.signal);return controller.signal.aborted||this.disposed?{files:[]}:{files:this.rankEntries(params.query,entries)}}finally{this.activeSearches.delete(controller),token!==null&&this.pendingSearches.get(token)===controller&&this.pendingSearches.delete(token)}}startSession(params){if(params.sessionId.length===0)throw invalidRequest2("sessionId must not be empty");this.cancelSession(params.sessionId);let session={id:params.sessionId,roots:params.roots,controller:new AbortController,query:"",version:0,entries:void 0,active:!this.disposed,completedVersion:void 0};return this.sessions.set(session.id,session),this.runTraversal(session),{}}updateSession(params){let session=this.sessions.get(params.sessionId);if(!session?.active)throw invalidRequest2(`fuzzy file search session not found: ${params.sessionId}`);return session.query=params.query,session.version+=1,session.entries!==void 0&&this.emitVersion(session,session.version),{}}stopSession(params){return this.cancelSession(params.sessionId),{}}dispose(){if(!this.disposed){this.disposed=!0;for(let controller of this.activeSearches)controller.abort();this.activeSearches.clear(),this.pendingSearches.clear();for(let session of this.sessions.values())this.deactivate(session);this.sessions.clear()}}async runTraversal(session){let entries;try{entries=await this.collectEntries(session.roots,session.controller.signal)}catch(error){if(!(error instanceof Error))throw error;entries=[]}if(this.isLive(session))for(session.entries=entries;this.isLive(session);){let version=session.version;if(await this.emitVersion(session,version))break}}async emitVersion(session,version){if(await Promise.resolve(),!this.isLive(session)||session.version!==version||session.entries===void 0)return!1;if(session.completedVersion===version)return!0;let query=session.query,files=query.length===0?[]:this.rankEntries(query,session.entries);return!this.isLive(session)||session.version!==version||(this.broadcast({method:"fuzzyFileSearch/sessionUpdated",params:{sessionId:session.id,query,files}}),!this.isLive(session)||session.version!==version)?!1:(session.completedVersion=version,this.broadcast({method:"fuzzyFileSearch/sessionCompleted",params:{sessionId:session.id}}),!0)}cancelSession(sessionId){let session=this.sessions.get(sessionId);session&&(this.deactivate(session),this.sessions.get(sessionId)===session&&this.sessions.delete(sessionId))}deactivate(session){session.active=!1,session.controller.abort()}isLive(session){return!this.disposed&&session.active&&this.sessions.get(session.id)===session}};function invalidRequest2(message){return new RpcHandlerError({code:-32600,message})}var APPROVAL_DECISIONS=["accept","acceptForSession","decline","cancel"],PERMISSION_OPTIONS=["Allow once","Allow always","Deny","Deny with feedback"],CANCEL_REASON="approval request was cancelled because the turn ended",NO_SUBSCRIBER_REASON="no client connected to approve";var ApprovalBridge=class{constructor(sendToThreadSubscribers){this.nextServerRequestId=0,this.pending=new Map,this.sessionAllows=new Set,this.sendToThreadSubscribers=sendToThreadSubscribers}get pendingCount(){return this.pending.size}requestApproval(threadId,kind,payload){let allowKey=createAllowKey(threadId,kind,payload);if(allowKey&&this.sessionAllows.has(allowKey))return Promise.resolve({allow:!0,decision:"acceptForSession"});let requestId=this.nextServerRequestId;this.nextServerRequestId+=1;let request=buildApprovalRequest(threadId,requestId,kind,payload);return new Promise(resolve4=>{this.pending.set(requestId,{threadId,request,allowKey,resolve:resolve4}),!(this.sendToThreadSubscribers(threadId,request)>0)&&(this.pending.delete(requestId),resolve4({allow:!1,decision:"decline",reason:NO_SUBSCRIBER_REASON}))})}resolveResponse(response){let pending=this.pending.get(response.id);if(!pending)return!1;let decision=readDecision(response);return this.pending.delete(response.id),decision==="acceptForSession"&&pending.allowKey&&this.sessionAllows.add(pending.allowKey),this.emitResolved(pending.threadId,response.id),pending.resolve(decisionToOutcome(decision,readReason(response))),!0}replayPendingForThread(threadId){let replayed=0;for(let pending of this.pending.values())pending.threadId===threadId&&(this.sendToThreadSubscribers(threadId,pending.request),replayed+=1);return replayed}cancelPendingForThread(threadId){let cancelled=0;for(let[requestId,pending]of Array.from(this.pending.entries()))pending.threadId===threadId&&(this.pending.delete(requestId),this.emitResolved(threadId,requestId),pending.resolve({allow:!1,decision:"cancel",reason:CANCEL_REASON}),cancelled+=1);return cancelled}emitResolved(threadId,requestId){this.sendToThreadSubscribers(threadId,{method:"serverRequest/resolved",params:{threadId,requestId}})}};function buildApprovalRequest(threadId,requestId,kind,payload){let base={threadId,turnId:payload.turnId??"turn-approval",itemId:payload.itemId??(kind==="commandExecution"?"approval-command":"approval-file-change"),startedAtMs:Date.now()};return kind==="fileChange"?{id:requestId,method:"item/fileChange/requestApproval",params:{...base,reason:payload.reason??null,grantRoot:payload.grantRoot??null}}:{id:requestId,method:"item/commandExecution/requestApproval",params:{...base,approvalId:payload.approvalId??null,environmentId:payload.environmentId??null,reason:payload.reason??null,command:payload.command??null,cwd:payload.cwd??null,availableDecisions:[...APPROVAL_DECISIONS]}}}function decisionToOutcome(decision,reason){return decision==="accept"||decision==="acceptForSession"?{allow:!0,decision}:reason?{allow:!1,decision,reason}:{allow:!1,decision}}function readDecision(response){let decision=isRecord2(response.result)?response.result.decision:void 0;return isApprovalDecision(decision)?decision:"cancel"}function readReason(response){let resultReason=isRecord2(response.result)?response.result.reason??response.result.message:void 0,errorReason=isRecord2(response.error)?response.error.message:void 0,reason=typeof resultReason=="string"?resultReason:errorReason;return typeof reason=="string"&&reason.length>0?reason:void 0}function createAllowKey(threadId,kind,payload){if(!(!payload.toolName||typeof payload.command!="string"))return`${threadId}\0${kind}\0${payload.toolName}\0${payload.command}`}function isApprovalDecision(value){return value==="accept"||value==="acceptForSession"||value==="decline"||value==="cancel"}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function createAppServerUIContext(bridge,threadId,userInput,getTurnId=()=>"turn-user-input"){let pendingInput,editorText="",editorFactory,toolsExpanded=!1;return{question(request,opts){return userInput?.requestUserInput(threadId,getTurnId(),request.requestId,request,opts)??Promise.resolve({status:"unavailable",answers:{},unanswered:request.questions.map(question=>question.id)})},async select(title,options){let prompt=parsePermissionPrompt(title);if(!prompt||!isPermissionOptions(options))return;let outcome=await bridge.requestApproval(threadId,prompt.kind,{turnId:"turn-approval",itemId:`approval-${prompt.toolName}`,toolName:prompt.toolName,command:prompt.command,reason:prompt.reason});return outcome.decision==="accept"?"Allow once":outcome.decision==="acceptForSession"?"Allow always":outcome.reason&&outcome.reason!==NO_SUBSCRIBER_REASON&&outcome.reason!==CANCEL_REASON?(pendingInput=outcome.reason,"Deny with feedback"):"Deny"},async confirm(title,message){return(await bridge.requestApproval(threadId,"commandExecution",{turnId:"turn-approval",itemId:"approval-confirm",toolName:"confirm",command:title,reason:message})).allow},async input(){let value=pendingInput;return pendingInput=void 0,value},notify(){},onTerminalInput(){return()=>{}},setStatus(){},setWorkingMessage(){},setWorkingVisible(){},setWorkingIndicator(){},setHiddenThinkingLabel(){},setWidget(){},setFooter(){},setHeader(){},setTitle(){},custom(){return Promise.reject(new Error("Custom UI is not available in app-server mode."))},pasteToEditor(text){editorText=text},setEditorText(text){editorText=text},getEditorText(){return editorText},async editor(_title,prefill){return prefill},addAutocompleteProvider(){},setEditorComponent(factory){editorFactory=factory},getEditorComponent(){return editorFactory},theme,getAllThemes:getAvailableThemesWithPaths,getTheme(name){return getThemeByName(name)},setTheme(_nextTheme){return{success:!1,error:"Theme switching is not available in app-server mode."}},getToolsExpanded(){return toolsExpanded},setToolsExpanded(expanded){toolsExpanded=expanded}}}function parsePermissionPrompt(title){let[firstLine="",...rest]=title.split(`
|
|
4
4
|
`),prefix="Permission required: ";if(!firstLine.startsWith(prefix))return;let toolName=firstLine.slice(prefix.length).trim(),reason=rest.join(`
|
|
5
5
|
`).trim();return{kind:permissionKind(toolName),toolName,command:readLineValue(reason,"Command: $ ")??readLineValue(reason,"File: ")??readLineValue(reason,"Path: ")??null,reason}}function permissionKind(toolName){return toolName==="edit"||toolName==="write"||toolName==="apply_patch"||toolName==="multiedit"?"fileChange":"commandExecution"}function readLineValue(text,prefix){return text.split(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{KeybindingsManager,TUI_KEYBINDINGS}from"./chunk-
|
|
2
|
+
import{KeybindingsManager,TUI_KEYBINDINGS}from"./chunk-ORCF262V.js";import{getAgentDir,stripBom}from"./chunk-Y65WFI5H.js";import{existsSync,readFileSync}from"fs";import{join}from"path";function useWindowsKeybindings(platform=process.platform,env=process.env){return platform==="win32"||platform==="linux"&&!!(env.WSL_DISTRO_NAME||env.WSL_INTEROP)}var windowsKeybindings=useWindowsKeybindings(),QUESTION_ANSWER_PRIMARY_KEY="alt+up",QUESTION_ANSWER_FALLBACK_KEY="alt+a",KEYBINDINGS={...TUI_KEYBINDINGS,"tui.editor.undo":{...TUI_KEYBINDINGS["tui.editor.undo"],defaultKeys:process.platform==="win32"?"ctrl+z":windowsKeybindings?"alt+z":"ctrl+-"},"tui.altScreen.previousPrompt":{...TUI_KEYBINDINGS["tui.altScreen.previousPrompt"],defaultKeys:windowsKeybindings?"ctrl+up":["ctrl+shift+up","ctrl+up"]},"tui.altScreen.nextPrompt":{...TUI_KEYBINDINGS["tui.altScreen.nextPrompt"],defaultKeys:windowsKeybindings?"ctrl+down":["ctrl+shift+down","ctrl+down"]},"tui.altScreen.search":{...TUI_KEYBINDINGS["tui.altScreen.search"],defaultKeys:windowsKeybindings?"ctrl+f":"ctrl+shift+f"},"app.interrupt":{defaultKeys:"escape",description:"Cancel or abort"},"app.clear":{defaultKeys:"ctrl+c",description:"Clear editor"},"app.exit":{defaultKeys:"ctrl+d",description:"Exit when editor is empty"},"app.suspend":{defaultKeys:process.platform==="win32"?[]:"ctrl+z",description:"Suspend to background"},"app.thinking.cycle":{defaultKeys:"shift+tab",description:"Cycle thinking level"},"app.thinking.save":{defaultKeys:"ctrl+s",description:"Save thinking level"},"app.model.cycleForward":{defaultKeys:"ctrl+p",description:"Cycle to next model"},"app.model.cycleBackward":{defaultKeys:windowsKeybindings?"alt+p":"shift+ctrl+p",description:"Cycle to previous model"},"app.model.select":{defaultKeys:"ctrl+l",description:"Open model selector"},"app.history.search":{defaultKeys:"ctrl+r",description:"Search prompt history across sessions"},"app.tools.expand":{defaultKeys:"ctrl+o",description:"Toggle tool output"},"app.thinking.toggle":{defaultKeys:"ctrl+t",description:"Toggle thinking blocks"},"app.session.toggleNamedFilter":{defaultKeys:"ctrl+n",description:"Toggle named session filter"},"app.editor.external":{defaultKeys:"ctrl+g",description:"Open external editor"},"app.message.copy":{defaultKeys:"ctrl+x",description:"Copy message to clipboard"},"app.message.followUp":{defaultKeys:windowsKeybindings?"ctrl+q":"alt+enter",description:"Queue follow-up message"},"app.message.dequeue":{defaultKeys:windowsKeybindings?"alt+q":"alt+up",description:"Restore queued messages"},"app.question.answer":{defaultKeys:[QUESTION_ANSWER_PRIMARY_KEY,QUESTION_ANSWER_FALLBACK_KEY],description:"Open the pending question"},"app.question.next":{defaultKeys:"alt+down",description:"Show the next pending question"},"app.clipboard.pasteImage":{defaultKeys:windowsKeybindings?"alt+v":"ctrl+v",description:"Paste image from clipboard (text fallback)"},"app.session.new":{defaultKeys:[],description:"Start a new session"},"app.session.tree":{defaultKeys:[],description:"Open session tree"},"app.session.fork":{defaultKeys:[],description:"Fork current session"},"app.session.resume":{defaultKeys:[],description:"Resume a session"},"app.session.renameCurrent":{defaultKeys:[],description:"Rename the current session"},"app.tree.foldOrUp":{defaultKeys:process.platform==="darwin"?["alt+left","ctrl+left"]:["ctrl+left","alt+left"],description:"Fold tree branch or move up"},"app.tree.unfoldOrDown":{defaultKeys:process.platform==="darwin"?["alt+right","ctrl+right"]:["ctrl+right","alt+right"],description:"Unfold tree branch or move down"},"app.tree.editLabel":{defaultKeys:"shift+l",description:"Edit tree label"},"app.tree.editMessage":{defaultKeys:"ctrl+e",description:"Edit the selected assistant response, or reopen a user message in the editor"},"app.tree.toggleLabelTimestamp":{defaultKeys:"shift+t",description:"Toggle tree label timestamps"},"app.session.togglePath":{defaultKeys:"ctrl+p",description:"Toggle session path display"},"app.session.toggleSort":{defaultKeys:"ctrl+s",description:"Toggle session sort mode"},"app.session.rename":{defaultKeys:"ctrl+r",description:"Rename session"},"app.session.delete":{defaultKeys:"ctrl+d",description:"Delete session"},"app.session.deleteNoninvasive":{defaultKeys:"ctrl+backspace",description:"Delete session when query is empty"},"app.models.save":{defaultKeys:"ctrl+s",description:"Save model selection"},"app.models.toggleFavorite":{defaultKeys:"ctrl+f",description:"Toggle favorite model"},"app.models.enableAll":{defaultKeys:"ctrl+a",description:"Enable all models"},"app.models.clearAll":{defaultKeys:"ctrl+x",description:"Clear all models"},"app.models.toggleProvider":{defaultKeys:"ctrl+p",description:"Toggle all models for provider"},"app.models.reorderUp":{defaultKeys:"alt+up",description:"Move model up in order"},"app.models.reorderDown":{defaultKeys:"alt+down",description:"Move model down in order"},"app.tree.filter.default":{defaultKeys:"ctrl+d",description:"Tree filter: default view"},"app.tree.filter.noTools":{defaultKeys:"ctrl+t",description:"Tree filter: hide tool results"},"app.tree.filter.userOnly":{defaultKeys:"ctrl+u",description:"Tree filter: user messages only"},"app.tree.filter.labeledOnly":{defaultKeys:"ctrl+l",description:"Tree filter: labeled entries only"},"app.tree.filter.all":{defaultKeys:"ctrl+a",description:"Tree filter: show all entries"},"app.tree.filter.cycleForward":{defaultKeys:"ctrl+o",description:"Tree filter: cycle forward"},"app.tree.filter.cycleBackward":{defaultKeys:"shift+ctrl+o",description:"Tree filter: cycle backward"}},KEYBINDING_NAME_MIGRATIONS={cursorUp:"tui.editor.cursorUp",cursorDown:"tui.editor.cursorDown",cursorLeft:"tui.editor.cursorLeft",cursorRight:"tui.editor.cursorRight",cursorWordLeft:"tui.editor.cursorWordLeft",cursorWordRight:"tui.editor.cursorWordRight",cursorLineStart:"tui.editor.cursorLineStart",cursorLineEnd:"tui.editor.cursorLineEnd",jumpForward:"tui.editor.jumpForward",jumpBackward:"tui.editor.jumpBackward",pageUp:"tui.editor.pageUp",pageDown:"tui.editor.pageDown",deleteCharBackward:"tui.editor.deleteCharBackward",deleteCharForward:"tui.editor.deleteCharForward",deleteWordBackward:"tui.editor.deleteWordBackward",deleteWordForward:"tui.editor.deleteWordForward",deleteToLineStart:"tui.editor.deleteToLineStart",deleteToLineEnd:"tui.editor.deleteToLineEnd",yank:"tui.editor.yank",yankPop:"tui.editor.yankPop",undo:"tui.editor.undo",newLine:"tui.input.newLine",submit:"tui.input.submit",tab:"tui.input.tab",copy:"tui.input.copy",selectUp:"tui.select.up",selectDown:"tui.select.down",selectPageUp:"tui.select.pageUp",selectPageDown:"tui.select.pageDown",selectConfirm:"tui.select.confirm",selectCancel:"tui.select.cancel",interrupt:"app.interrupt",clear:"app.clear",exit:"app.exit",suspend:"app.suspend",cycleThinkingLevel:"app.thinking.cycle",cycleModelForward:"app.model.cycleForward",cycleModelBackward:"app.model.cycleBackward",selectModel:"app.model.select",expandTools:"app.tools.expand",toggleThinking:"app.thinking.toggle",toggleSessionNamedFilter:"app.session.toggleNamedFilter",externalEditor:"app.editor.external",followUp:"app.message.followUp",dequeue:"app.message.dequeue",pasteImage:"app.clipboard.pasteImage",newSession:"app.session.new",tree:"app.session.tree",fork:"app.session.fork",resume:"app.session.resume",treeFoldOrUp:"app.tree.foldOrUp",treeUnfoldOrDown:"app.tree.unfoldOrDown",treeEditLabel:"app.tree.editLabel",treeEditMessage:"app.tree.editMessage",treeToggleLabelTimestamp:"app.tree.toggleLabelTimestamp",toggleSessionPath:"app.session.togglePath",toggleSessionSort:"app.session.toggleSort",renameSession:"app.session.rename",deleteSession:"app.session.delete",deleteSessionNoninvasive:"app.session.deleteNoninvasive"};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function hasOwn(value,key){return Object.hasOwn(value,key)}function isLegacyKeybindingName(key){return key in KEYBINDING_NAME_MIGRATIONS}function toKeybindingsConfig(value){let config={};for(let[key,binding]of Object.entries(value)){if(typeof binding=="string"){config[key]=binding;continue}Array.isArray(binding)&&binding.every(entry=>typeof entry=="string")&&(config[key]=binding)}return config}function migrateKeybindingsConfig(rawConfig){let config={},migrated=!1;for(let[key,value]of Object.entries(rawConfig)){let nextKey=isLegacyKeybindingName(key)?KEYBINDING_NAME_MIGRATIONS[key]:key;if(nextKey!==key&&(migrated=!0),key!==nextKey&&hasOwn(rawConfig,nextKey)){migrated=!0;continue}config[nextKey]=value}return{config:orderKeybindingsConfig(config),migrated}}function orderKeybindingsConfig(config){let ordered={};for(let keybinding of Object.keys(KEYBINDINGS))hasOwn(config,keybinding)&&(ordered[keybinding]=config[keybinding]);let extras=Object.keys(config).filter(key=>!hasOwn(ordered,key)).sort();for(let key of extras)ordered[key]=config[key];return ordered}function loadRawConfig(path){if(existsSync(path))try{let parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")));return isRecord(parsed)?parsed:void 0}catch{return}}var KeybindingsManager2=class _KeybindingsManager extends KeybindingsManager{constructor(userBindings={},configPath){super(KEYBINDINGS,userBindings),this.configPath=configPath}static create(agentDir=getAgentDir()){let configPath=join(agentDir,"keybindings.json"),userBindings=_KeybindingsManager.loadFromFile(configPath);return new _KeybindingsManager(userBindings,configPath)}reload(){this.configPath&&this.setUserBindings(_KeybindingsManager.loadFromFile(this.configPath))}getEffectiveConfig(){return this.getResolvedBindings()}static loadFromFile(path){let rawConfig=loadRawConfig(path);return rawConfig?toKeybindingsConfig(migrateKeybindingsConfig(rawConfig).config):{}}};export{QUESTION_ANSWER_PRIMARY_KEY,QUESTION_ANSWER_FALLBACK_KEY,KEYBINDINGS,migrateKeybindingsConfig,KeybindingsManager2 as KeybindingsManager};
|
|
@@ -104,8 +104,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
|
|
|
104
104
|
`),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
|
|
105
105
|
\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}deleteAltScreenKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta:wheelEvent.direction*this.getWheelScrollLines(wheelEvent.button)}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):this.shouldDeferViewportInputToOverlay()?void 0:(this.routeWheel(wheelEvent),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){return decodeMouseButton(button)}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result,applyFocus=!0){let focusTarget=applyFocus&&result.focus?this.resolveMouseFocusTarget(result.focusTarget??result.target.component):null,focusChanged=focusTarget!==null&&this.getFocusedComponent()!==focusTarget;return focusTarget&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),focusBeforeClick=this.getFocusedComponent(),clickResult=this.dispatchMouseToTarget(clickEvent,target);if(clickResult){let keepHandlerFocus=this.getFocusedComponent()!==focusBeforeClick;render=this.applyMouseDispatchResult(clickEvent,clickResult,!keepHandlerFocus)||render}}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){return parseWheelEvent(data)}getWheelScrollLines(button){return(button&8)!==0?this.wheelScrollLines*ALT_WHEEL_SCROLL_MULTIPLIER:this.wheelScrollLines}routeWheel(event){let remaining=event.direction*this.getWheelScrollLines(event.button),seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){return parseSgrMouseEvent(data)}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter3.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
|
|
106
106
|
`);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let ok=await this.copySelection(text);return this.flash(ok?"Copied!":"Copy failed"),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b2)=>b2.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return isMouseSequence(data)}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,availableWidth=Math.max(0,(scrollbarColumn??clip.x+clip.width)-clip.x),text=truncateToWidth(this.scrollToEndIndicator(),availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let column=clip.x+Math.floor((availableWidth-textWidth)/2),result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,""));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imagesNeedRedraw=screen.some((line,row)=>line!==this.previousScreen[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteAltScreenKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));buffer+=preparedKittyScreen.evictedImageDeletion;for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};var TuiMainScreen=class extends TuiBase{constructor(...args){super(...args),this.mode="regular",this.trackingEnabled=!1,this.clicks=new MouseClickSynthesizer,this.layoutRevision=0,this.committedMouseLines=[],this.committedMouseComponents=[],this.addInputListener(data=>this.handleMouseInput(data))}applyMouseTracking(enabled){let supported=!!process.stdout.isTTY&&!process.env.TERMUX_VERSION&&(process.platform!=="win32"||!!process.env.WT_SESSION),next=enabled&&supported&&!this.stopped;this.clicks.cancel(),this.mousePress=void 0,this.trackingEnabled!==next&&(this.trackingEnabled=next,this.terminal.write(next?MOUSE_TRACKING.inline:MOUSE_TRACKING.disable))}beforeTerminalStop(){this.terminal.write(MOUSE_TRACKING.disable),this.trackingEnabled=!1,this.clicks.cancel(),this.mousePress=void 0}doRender(){if(this.stopped)return;this.mouseExternalWritePending&&(this.mouseExternalWritePending=!1,this.terminal.write(`\r
|
|
107
|
-
`),this.restoreRenderState({previousLines:[],previousWidth:0,previousHeight:0,cursorRow:0,hardwareCursorRow:0,maxLinesRendered:0,previousViewportTop:0})),super.doRender(),this.noteCommittedMouseFrame();let components=[],visit=component=>{if(components.push(component),component instanceof Container)for(let child of component.children)visit(child)};for(let root of this.getMouseLayoutRoots())visit(root);(this.previousLines.length!==this.committedMouseLines.length||this.previousLines.some((line,index)=>line!==this.committedMouseLines[index])||components.length!==this.committedMouseComponents.length||components.some((component,index)=>component!==this.committedMouseComponents[index]))&&this.layoutRevision++,this.committedMouseLines=[...this.previousLines],this.committedMouseComponents=components,this.calibrateMouseAnchor()}applyMouseResult(result){if(!result?.focus)return;let target=this.resolveMouseFocusTarget(result.focusTarget??result.target.component);target&&this.setFocus(target)}handleMouseInput(data){if(!isMouseSequence(data))return{consume:!1};let raw=parseSgrMouseEvent(data);if(!this.trackingEnabled||!raw||raw.button!==0)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let frameLine=this.resolveFrameLine(raw.y+1);if(frameLine===void 0||raw.x>=this.terminal.columns)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let event=toTuiMouseEvent(raw.release?"release":"press",raw,this.terminal);if(raw.release){let press=this.mousePress;if(this.mousePress=void 0,!press||press.epoch!==this.placementEpoch||press.revision!==this.layoutRevision||press.x!==raw.x||press.y!==raw.y)return this.clicks.cancel(),{consume:!0};let count=this.clicks.release(raw,press.target.component,this.placementEpoch);if(count!==void 0){let click={...event,type:"click",clickCount:count},focusBeforeClick=this.getFocusedComponent(),clickResult=dispatchMouseEvent(press.target.component,retargetMouseEvent(click,press.target));this.getFocusedComponent()===focusBeforeClick&&this.applyMouseResult(clickResult),this.requestRender()}}else{let overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:dispatchMouseEvent(this,{...event,y:frameLine,height:this.previousLines.length}));this.mousePress=void 0,result?(this.applyMouseResult(result),this.mousePress={target:result.target,epoch:this.placementEpoch,revision:this.layoutRevision,x:raw.x,y:raw.y},this.clicks.press(raw,result.target.component,this.placementEpoch)):this.clicks.cancel(),this.requestRender()}return{consume:!0}}captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}};var dist_exports={};__export(dist_exports,{AltScreenSearchComponent:()=>AltScreenSearchComponent,Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,IMAGE_MARKER_REGEX:()=>IMAGE_MARKER_REGEX,IMAGE_MARKER_SINGLE:()=>IMAGE_MARKER_SINGLE,Image:()=>Image,ImageMarkerRegistry:()=>ImageMarkerRegistry,Input:()=>Input,KITTY_PLACEHOLDER_MAX:()=>KITTY_PLACEHOLDER_MAX,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,MOUSE_TRACKING:()=>MOUSE_TRACKING,Markdown:()=>Markdown,Marked:()=>Q,MouseClickSynthesizer:()=>MouseClickSynthesizer,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI:()=>TUI,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,buildKittyPlaceholderRow:()=>buildKittyPlaceholderRow,calculateImageRows:()=>calculateImageRows,clearRenderCache:()=>clearRenderCache,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,decodeMouseButton:()=>decodeMouseButton,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,expandPasteMarkers:()=>expandPasteMarkers,findAltScreenSearchMatches:()=>findAltScreenSearchMatches,formatImageMarker:()=>formatImageMarker,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getAltScreenSearchMatchKey:()=>getAltScreenSearchMatchKey,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getGraphemeSegmenter:()=>getGraphemeSegmenter,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getMarkdownHighlightCallCount:()=>getMarkdownHighlightCallCount,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getWebpDimensions:()=>getWebpDimensions,getWordSegmenter:()=>getWordSegmenter,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,imageMarkerId:()=>imageMarkerId,isFocusable:()=>isFocusable,isImageMarker:()=>isImageMarker,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isMouseSequence:()=>isMouseSequence,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,outerKittyGraphicsMode:()=>outerKittyGraphicsMode,parseKey:()=>parseKey,parseOsc11BackgroundColor:()=>parseOsc11BackgroundColor,parseSgrMouseEvent:()=>parseSgrMouseEvent,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,parseWheelEvent:()=>parseWheelEvent,renderImage:()=>renderImage,resetCapabilitiesCache:()=>resetCapabilitiesCache,resetMarkdownHighlightCallCount:()=>resetMarkdownHighlightCallCount,sanitizeTerminalLabel:()=>sanitizeTerminalLabel,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,shortenImagePath:()=>shortenImagePath,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,toTuiMouseEvent:()=>toTuiMouseEvent,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi,wrapTmuxPassthrough:()=>wrapTmuxPassthrough});var Box=class{constructor(paddingX=1,paddingY=1,bgFn){this.children=[],this.disposed=!1,this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache(),component.dispose?.())}clear(){for(let child of this.children)child.dispose?.();this.children=[],this.invalidateCache()}detachAll(){this.children=[],this.invalidateCache()}dispose(){if(!this.disposed){this.disposed=!0;for(let child of this.children)child.dispose?.();this.invalidateCache()}}setBgFn(bgFn){this.bgFn=bgFn}invalidateCache(){this.cache=void 0}matchCache(width,childLines,bgSample){let cache=this.cache;return!!cache&&cache.width===width&&cache.bgSample===bgSample&&cache.childLines.length===childLines.length&&cache.childLines.every((line,i)=>line===childLines[i])}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth);mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(leftPad+line)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(width,childLines,bgSample))return this.cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));for(let line of childLines)result.push(this.applyBg(line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));return this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?applyBackgroundToLine(padded,width,this.bgFn):padded}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.frames=[...DEFAULT_FRAMES],this.intervalMs=DEFAULT_INTERVAL_MS,this.currentFrame=0,this.indicatorIntervalId=null,this.messageIntervalId=null,this.indicatorFormatter=void 0,this.messageFormatter=void 0,this.messageIntervalMs=DEFAULT_INTERVAL_MS,this.messageAnimationStartedAt=0,this.ui=null,this.renderIndicatorVerbatim=!1,this.message="Loading...",this.lastDisplayedText=void 0,this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.messageFormatter&&(this.messageAnimationStartedAt=Date.now()),this.updateDisplay(),this.restartAnimation()}stop(){this.indicatorIntervalId&&(clearInterval(this.indicatorIntervalId),this.indicatorIntervalId=null),this.messageIntervalId&&(clearInterval(this.messageIntervalId),this.messageIntervalId=null)}dispose(){this.stop()}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.indicatorFormatter=indicator?.indicatorFormatter,this.messageFormatter=indicator?.messageFormatter,this.messageIntervalMs=indicator?.messageIntervalMs&&indicator.messageIntervalMs>0?indicator.messageIntervalMs:this.intervalMs,this.currentFrame=0,this.messageAnimationStartedAt=Date.now(),this.start()}restartAnimation(){this.stop(),this.frames.length>1&&(this.indicatorIntervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs),this.indicatorIntervalId.unref?.()),(this.indicatorFormatter||this.messageFormatter)&&(this.messageAnimationStartedAt=Date.now(),this.messageIntervalId=setInterval(()=>{this.updateDisplay()},this.messageIntervalMs),this.messageIntervalId.unref?.())}getRenderedIndicator(animationElapsedMs=this.getAnimationElapsedMs()){let frame=this.frames[this.currentFrame]??"";return frame.length===0?"":this.indicatorFormatter?this.indicatorFormatter(frame,animationElapsedMs):this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}getAnimationElapsedMs(){return Math.max(0,Date.now()-this.messageAnimationStartedAt)}updateDisplay(){let animationElapsedMs=this.getAnimationElapsedMs(),renderedFrame=this.getRenderedIndicator(animationElapsedMs),indicator=renderedFrame.length>0?`${renderedFrame} `:"",renderedMessage=this.messageFormatter?this.messageFormatter(this.message,animationElapsedMs):this.messageColorFn(this.message),displayedText=`${indicator}${renderedMessage}`;displayedText!==this.lastDisplayedText&&(this.lastDisplayedText=displayedText,this.setText(displayedText),this.ui&&this.ui.requestRender())}};var CancellableLoader=class extends Loader{constructor(){super(...arguments),this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var IMAGE_MARKER_REGEX=/\[Image #([1-9]\d*)\]/g,IMAGE_MARKER_SINGLE=/^\[Image #([1-9]\d*)\]$/;function formatImageMarker(id){return`[Image #${id}]`}function isImageMarker(segment){return segment.length>=10&&IMAGE_MARKER_SINGLE.test(segment)}function imageMarkerId(segment){let match=segment.length>=10?IMAGE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function countOccurrences(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}var ImageMarkerRegistry=class{constructor(){this.entries=new Set,this.imageCounter=0}add(){let id=++this.imageCounter;return this.entries.add(id),formatImageMarker(id)}authorizedMarkers(text){let markers=new Set;for(let id of this.entries){let marker=formatImageMarker(id);countOccurrences(text,marker)===1&&markers.add(marker)}return markers}canonicalize(text){let order=this.ids(text);if(order.length===0)return{text,order};let renumbered=new Map;for(let[index,id]of order.entries())renumbered.set(id,index+1);let updatedText=text.replace(IMAGE_MARKER_REGEX,marker=>{let id=imageMarkerId(marker),newId=id===void 0?void 0:renumbered.get(id);return newId===void 0?marker:formatImageMarker(newId)});return this.entries=new Set(order.map((_2,index)=>index+1)),this.imageCounter=this.entries.size,{text:updatedText,order}}clear(){this.entries.clear(),this.imageCounter=0}ids(text){let authorized=this.authorizedMarkers(text),ordered=[];for(let match of text.matchAll(IMAGE_MARKER_REGEX))authorized.has(match[0])&&ordered.push(Number.parseInt(match[1],10));return ordered}install(state,text){this.restore(state),this.prune(text)}prune(text,previousText){for(let id of[...this.entries]){let marker=formatImageMarker(id);(!(previousText===void 0||countOccurrences(previousText,marker)===1)||countOccurrences(text,marker)!==1)&&this.entries.delete(id)}this.imageCounter=Math.max(...this.entries,0)}remove(id,text){if(!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence(text,formatImageMarker(id),""),higherIds=[...this.entries].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){this.entries.delete(oldId);let marker=formatImageMarker(oldId);if(countOccurrences(updatedText,marker)!==1)continue;let newId=oldId-1;updatedText=replaceSingleOccurrence(updatedText,marker,formatImageMarker(newId)),this.entries.add(newId)}return this.imageCounter=Math.max(...this.entries,0),{text:updatedText,removed:!0}}restore(state){this.entries=new Set(state.ids),this.imageCounter=Math.max(state.imageCounter,...this.entries,0)}snapshot(){return{ids:[...this.entries].sort((a,b2)=>a-b2),imageCounter:this.imageCounter}}};var PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function formatPasteMarker(id,lineCount,charCount){return lineCount>10?`[paste #${id} +${lineCount} lines]`:`[paste #${id} ${charCount} chars]`}function countLines(content){let lineCount=1;for(let index=0;index<content.length;index++)content.charCodeAt(index)===10&&lineCount++;return lineCount}function createEntry(id,content,marker){let charCount=content.length,lineMatch=marker?.match(PASTE_MARKER_SINGLE)?.[3]?.match(/^\+(\d+) lines$/),lineCount=lineMatch?Number.parseInt(lineMatch[1],10):countLines(content),canonical=formatPasteMarker(id,lineCount,charCount);return{content,marker:marker===canonical?marker:canonical,lineCount,charCount}}function countOccurrences2(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence2(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}function entriesFromState(state){let entries=new Map;for(let[id,content]of state.pastes)entries.set(id,createEntry(id,content,state.markers?.get(id)));return entries}function expandPasteMarkers(text,state){let entries=entriesFromState(state),byMarker=new Map;for(let entry of entries.values())byMarker.set(entry.marker,entry);let matches=[],counts=new Map;for(let match of text.matchAll(PASTE_MARKER_REGEX)){let marker=match[0];byMarker.has(marker)&&(matches.push({start:match.index,end:match.index+marker.length,marker}),counts.set(marker,(counts.get(marker)??0)+1))}if(matches.length===0)return text;let chunks=[],offset=0;for(let match of matches){chunks.push(text.slice(offset,match.start));let entry=byMarker.get(match.marker);chunks.push(counts.get(match.marker)===1?entry.content:match.marker),offset=match.end}return chunks.push(text.slice(offset)),chunks.join("")}function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function pasteMarkerId(segment){let match=segment.length>=10?PASTE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function segmentWithMarkers(text,baseSegmenter,validMarkers){if(validMarkers.size===0)return baseSegmenter.segment(text);let found=[];for(let marker2 of validMarkers){let start=text.indexOf(marker2);start!==-1&&found.push({start,end:start+marker2.length})}if(found.length===0)return baseSegmenter.segment(text);found.sort((a,b2)=>a.start-b2.start||b2.end-a.end);let markers=[];for(let range of found){let previous=markers[markers.length-1];previous&&range.start<previous.end||markers.push(range)}let result=[],markerIndex=0,marker=markers[0];for(let segment of baseSegmenter.segment(text)){for(;marker&&segment.index>=marker.end;)marker=markers[++markerIndex];!marker||segment.index<marker.start?result.push(segment):segment.index===marker.start&&result.push({segment:text.slice(marker.start,marker.end),index:marker.start,input:text})}return result}var PasteMarkerRegistry=class{constructor(){this.entries=new Map,this.pasteCounter=0,this.metadataBuilds=0}add(content,lineCount,charCount){let id=++this.pasteCounter,marker=formatPasteMarker(id,lineCount,charCount);return this.entries.set(id,{content,marker,lineCount,charCount}),this.metadataBuilds++,marker}authorizedMarkers(text){let markers=new Set;for(let entry of this.entries.values())countOccurrences2(text,entry.marker)===1&&markers.add(entry.marker);return markers}clear(){this.entries.clear(),this.pasteCounter=0}expand(text){return expandPasteMarkers(text,this.snapshot())}get metadataBuildCount(){return this.metadataBuilds}install(state,text){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0),this.prune(text)}prune(text,previousText){for(let[id,entry]of this.entries)(!(previousText===void 0||countOccurrences2(previousText,entry.marker)===1)||countOccurrences2(text,entry.marker)!==1)&&this.entries.delete(id);this.pasteCounter=Math.max(...this.entries.keys(),0)}remove(id,text){let removedEntry=this.entries.get(id);if(!removedEntry||!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence2(text,removedEntry.marker,""),higherIds=[...this.entries.keys()].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){let entry=this.entries.get(oldId);if(this.entries.delete(oldId),countOccurrences2(updatedText,entry.marker)!==1)continue;let newId=oldId-1,renamed=formatPasteMarker(newId,entry.lineCount,entry.charCount);updatedText=replaceSingleOccurrence2(updatedText,entry.marker,renamed),this.entries.set(newId,{...entry,marker:renamed})}return this.pasteCounter=Math.max(...this.entries.keys(),0),{text:updatedText,removed:!0}}snapshot(){let pastes=new Map,markers=new Map;for(let[id,entry]of this.entries)pastes.set(id,entry.content),markers.set(id,entry.marker);return{pastes,markers,pasteCounter:this.pasteCounter}}restore(state){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0)}};import*as fs2 from"node:fs";import*as path3 from"node:path";import{createRequire as createRequire2}from"node:module";import*as path2 from"node:path";import{createRequire}from"node:module";import{dirname as dirname3,isAbsolute as isAbsolute2,join as join3}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function resolvePackageEntry(resolveOverride){if(resolveOverride)return resolveOverride(TUI_PACKAGE_NAME);try{return fileURLToPath(import.meta.resolve(TUI_PACKAGE_NAME))}catch{}return moduleRequire.resolve(TUI_PACKAGE_NAME)}function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname3(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=resolvePackageEntry(options.resolvePackage);packageEntry&&isAbsolute2(packageEntry)&&candidates.push(join3(dirname3(packageEntry),"..",nativePath))}catch{}return candidates.push(join3(moduleDir,"..",nativePath),join3(moduleDir,nativePath),join3(dirname3(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path2.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}import{StringDecoder}from"node:string_decoder";import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~";function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let seqEnd=1;for(;seqEnd<=remaining.length;){let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else{let codepoint=remaining.codePointAt(0),character=String.fromCodePoint(codepoint);sequences.push(character),pos+=character.length}}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{constructor(options={}){super(),this.buffer="",this.timeout=null,this.discardingMouseFragment=!1,this.pasteMode=!1,this.pasteBuffer="",this.decoder=new StringDecoder("utf8"),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str,decodedFromBuffer=!1;if(Buffer.isBuffer(data))if(!((this.decoder.lastNeed??0)>0)&&data.length===1&&data[0]>=128&&data[0]<194){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=this.decoder.write(data),decodedFromBuffer=!0;else str=data;if(str.length===0&&this.buffer.length===0){decodedFromBuffer||this.emitDataSequence("");return}if(this.discardingMouseFragment){let terminator=str.search(/[\x40-\x7e]/),escapeIndex=str.indexOf(ESC);if(escapeIndex!==-1&&(terminator===-1||escapeIndex<terminator))str=str.slice(escapeIndex);else{if(terminator===-1)return;str=str.slice(terminator+1)}this.discardingMouseFragment=!1}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder,this.buffer.startsWith("\x1B[<")?(this.mouseFragmentStartedAt??=Date.now(),this.buffer.length>64&&(this.buffer="",this.discardingMouseFragment=!0)):this.mouseFragmentStartedAt=void 0;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];if(this.buffer.startsWith("\x1B[<")){let remaining=750-(Date.now()-(this.mouseFragmentStartedAt??Date.now()));return remaining>0&&this.buffer.length<=64?this.timeout=setTimeout(()=>this.flush(),remaining):(this.buffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!0),[]}let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!1,this.pendingKittyPrintableCodepoint=void 0,this.decoder=new StringDecoder("utf8")}getBuffer(){return this.buffer}destroy(){this.clear()}};import{execFileSync as execFileSync2}from"node:child_process";function queryTmuxCursorPosition(pane,deadline,execFile){let read=()=>{let remaining=deadline-Date.now();if(!(remaining<=0))try{let args=["display-message","-p","-t",pane,"#{cursor_y} #{cursor_x}"],output=execFile?execFile("tmux",args):execFileSync2("tmux",args,{encoding:"utf8",timeout:remaining,stdio:["ignore","pipe","ignore"]}),match=/^(\d+) (\d+)$/.exec(output.trim());if(!match||Date.now()>=deadline)return;let row=Number(match[1])+1,column=Number(match[2])+1;return Number.isSafeInteger(row)&&Number.isSafeInteger(column)?{row,column}:void 0}catch{return}},first=read();return!first||deadline-Date.now()<=10?Promise.resolve(void 0):new Promise(resolve=>{setTimeout(()=>{let second=read();resolve(second?.row===first.row&&second.column===first.column?second:void 0)},10)})}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,DEAD_TERMINAL_ERROR_CODES=new Set(["EIO","EPIPE","ENOTCONN"]),EIO_ERRNO=5,EPIPE_ERRNO=32,DEAD_TERMINAL_ERRNOS=new Set([EIO_ERRNO,EPIPE_ERRNO]),ERRNO_IN_MESSAGE_PATTERN=/errno:\s*(\d+)/,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u\x1B[c`;function parseCursorPositionResponse(sequence){let match=/^\x1b\[\?(\d+);(\d+)(?:;(\d+))?R$/.exec(sequence);return match?{row:Number(match[1]),column:Number(match[2]),...match[3]===void 0?{}:{page:Number(match[3])}}:void 0}function parseKeyboardProtocolNegotiationSequence(sequence){let cursorPosition=parseCursorPositionResponse(sequence);if(cursorPosition)return{type:"cursor-position",...cursorPosition};let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}function normalizeWarpWslShiftEnterInput(data,env=process.env,platform=process.platform,socketExists=socketPath=>{try{return fs2.statSync(socketPath).isSocket()}catch{return!1}}){if(data!==`
|
|
108
|
-
`||platform!=="linux"||isMultiplexerSession(env)||env.SSH_CONNECTION?.trim()||env.SSH_CLIENT?.trim()||env.SSH_TTY?.trim())return data;let isWarp=!!(env.WARP_SESSION_ID?.trim()||env.WARP_TERMINAL_SESSION_UUID?.trim()),interopPath=env.WSL_INTEROP?.trim(),isWsl=isWarp&&interopPath!==void 0&&/^\/run\/WSL\/\d+_interop$/.test(interopPath)&&socketExists(interopPath);return isWarp&&isWsl?NATIVE_SHIFT_ENTER_SEQUENCE:data}function keyboardEnhancementEnabled(){let value=process.env.PI_TUI_KEYBOARD_PROTOCOL;return value===void 0?!0:!["0","false","no","off"].includes(value.toLowerCase())}function isDeadTerminalError(error){if(!(error instanceof Error))return!1;if("code"in error&&typeof error.code=="string")return DEAD_TERMINAL_ERROR_CODES.has(error.code);if("errno"in error&&error.errno===EIO_ERRNO)return!0;let messageErrno=ERRNO_IN_MESSAGE_PATTERN.exec(error.message);return messageErrno?DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1],10)):!1}var STDIN_ERROR_HANDLER_GRACE_MS=250,stdinErrorSubscribers=new Set;function isTerminalDetachStdinError(err){if(err.code==="EIO")return!0;let errno=err.errno;return errno===EIO_ERRNO||errno===-EIO_ERRNO}var dispatchStdinError=err=>{if(!isTerminalDetachStdinError(err)){if(!process.stdin.listeners("error").some(listener=>listener!==dispatchStdinError))throw err;return}for(let subscriber of stdinErrorSubscribers)subscriber(err)};function subscribeToStdinErrors(subscriber){stdinErrorSubscribers.size===0&&process.stdin.on("error",dispatchStdinError),stdinErrorSubscribers.add(subscriber)}function unsubscribeFromStdinErrors(subscriber){stdinErrorSubscribers.delete(subscriber),stdinErrorSubscribers.size===0&&process.stdin.removeListener("error",dispatchStdinError)}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{constructor(options){this.wasRaw=!1,this.externalWriteObservers=new Set,this.keyboardNegotiationSettled=!1,this.cursorQueryTimedOut=!1,this.forwardingExternalWrite=!1,this._kittyProtocolActive=!1,this._modifyOtherKeysActive=!1,this.keyboardProtocolPushed=!1,this.keyboardProtocolNegotiationBuffer="",this.discardingPrivateResponse=!1,this.writeLogPath=(()=>{let env=process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs2.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path3.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})(),this.onExternalStdoutWrite=options?.onExternalStdoutWrite,this.tmuxExecFile=options?.tmuxExecFile}get kittyProtocolActive(){return this._kittyProtocolActive}queryCursorPosition(){if(this.cursorQuery)return this.cursorQuery.promise;if(!this.inputHandler||this.cursorQueryTimedOut)return Promise.resolve(void 0);let resolve,promise=new Promise(settle=>{resolve=settle}),timer=setTimeout(()=>{this.cursorQueryTimedOut=!0,this.settleCursorQuery(void 0)},750);return this.cursorQuery={promise,resolve,timer,issued:!1,tmuxPane:process.env.TMUX_PANE,deadline:Date.now()+750},this.issueCursorQuery(),promise}issueCursorQuery(){if(!this.keyboardNegotiationSettled||!this.cursorQuery||this.cursorQuery.issued)return;this.cursorQuery.issued=!0,this.rawWrite("\x1B[?6n");let pending=this.cursorQuery;pending?.tmuxPane!==void 0&&queryTmuxCursorPosition(pending.tmuxPane,pending.deadline,this.tmuxExecFile).then(position=>{this.cursorQuery===pending&&(Date.now()>=pending.deadline&&(this.cursorQueryTimedOut=!0),this.settleCursorQuery(this.cursorQueryTimedOut?void 0:position))})}settleCursorQuery(position){let pending=this.cursorQuery;pending&&(this.cursorQuery=void 0,clearTimeout(pending.timer),pending.resolve(position))}observeExternalWrites(listener){return this.externalWriteObservers.add(listener),this.inputHandler&&(this.installExternalStdoutGuard(),this.installExternalStderrObserver()),()=>{this.externalWriteObservers.delete(listener)}}noteExternalWrite(){for(let listener of this.externalWriteObservers)listener()}installExternalStderrObserver(){if(this.originalStderrWrite||this.externalWriteObservers.size===0)return;let original=process.stderr.write;this.originalStderrWrite=original,process.stderr.write=((...args)=>(this.noteExternalWrite(),original.apply(process.stderr,args)))}rawWrite(data){if(this.rawStdoutWrite){this.rawStdoutWrite(data);return}process.stdout.write(data)}installExternalStdoutGuard(){let handler=this.onExternalStdoutWrite;if(!handler&&this.externalWriteObservers.size===0||this.originalStdoutWrite)return;this.originalStdoutWrite=process.stdout.write;let rawWrite=process.stdout.write.bind(process.stdout);this.rawStdoutWrite=rawWrite,process.stdout.write=((chunk,encodingOrCallback,callback)=>{let cb=typeof encodingOrCallback=="function"?encodingOrCallback:callback,encoding=typeof encodingOrCallback=="string"?encodingOrCallback:void 0,text=typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding);if(this.noteExternalWrite(),!handler||this.forwardingExternalWrite)return rawWrite(text),cb?.(null),!0;this.forwardingExternalWrite=!0;try{handler(text)}catch{rawWrite(text)}finally{this.forwardingExternalWrite=!1}return cb?.(null),!0})}removeExternalStdoutGuard(){this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite,this.originalStdoutWrite=void 0,this.rawStdoutWrite=void 0)}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.installExternalStdoutGuard(),this.installExternalStderrObserver(),this.keyboardNegotiationSettled=!keyboardEnhancementEnabled(),this.cursorQueryTimedOut=!1,this.discardingPrivateResponse=!1,this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),this.stdinErrorHandlerCleanupTimer&&(clearTimeout(this.stdinErrorHandlerCleanupTimer),this.stdinErrorHandlerCleanupTimer=void 0),this.stdinErrorHandler||(this.stdinErrorHandler=()=>{},subscribeToStdinErrors(this.stdinErrorHandler)),this.rawWrite("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(this.discardingPrivateResponse)if(sequence.startsWith("\x1B"))this.discardingPrivateResponse=!1;else{/[\x40-\x7e]/.test(sequence)&&(this.discardingPrivateResponse=!1);return}let negotiationSequence=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)||this.forwardInputSequence(sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),keyboardEnhancementEnabled()&&((process.env.TMUX!==void 0||process.env.TMUX_PANE!==void 0)&&this.enableModifyOtherKeys(),this.keyboardProtocolPushed=!0,this.clearKeyboardProtocolNegotiationBuffer(),this.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY))}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(!negotiationSequence)return!1;if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="cursor-position"){if(this.cursorQuery?.issued&&this.cursorQuery.tmuxPane===void 0){let{type:_type,...position}=negotiationSequence;this.settleCursorQuery(position)}return!0}return this.keyboardNegotiationSettled=!0,this.issueCursorQuery(),negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence2;if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return negotiationSequence;if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(discardTail=!1){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;if(this.clearKeyboardProtocolNegotiationBuffer(),/^\x1b\[\?[\d;]*$/.test(sequence)){this.discardingPrivateResponse=discardTail;return}this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput(!0)},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(this.rawWrite("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(this.rawWrite("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.settleCursorQuery(void 0),this.originalStderrWrite&&(process.stderr.write=this.originalStderrWrite,this.originalStderrWrite=void 0),this.clearProgressInterval()&&this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.rawWrite("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;if(this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode)try{process.stdin.setRawMode(this.wasRaw)}catch(error){if(!isDeadTerminalError(error))throw error}this.removeExternalStdoutGuard(),this.scheduleStdinErrorHandlerCleanup()}scheduleStdinErrorHandlerCleanup(){if(!this.stdinErrorHandler||this.stdinErrorHandlerCleanupTimer)return;let handler=this.stdinErrorHandler;this.stdinErrorHandlerCleanupTimer=setTimeout(()=>{this.stdinErrorHandlerCleanupTimer=void 0,this.stdinErrorHandler===handler&&(this.stdinErrorHandler=void 0,unsubscribeFromStdinErrors(handler))},STDIN_ERROR_HANDLER_GRACE_MS),this.stdinErrorHandlerCleanupTimer.unref()}write(data){if(this.rawWrite(data),this.writeLogPath)try{fs2.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?this.rawWrite(`\x1B[${lines}B`):lines<0&&this.rawWrite(`\x1B[${-lines}A`)}hideCursor(){this.rawWrite("\x1B[?25l")}showCursor(){this.rawWrite("\x1B[?25h")}clearLine(){this.rawWrite("\x1B[K")}clearFromCursor(){this.rawWrite("\x1B[J")}clearScreen(){this.rawWrite("\x1B[2J\x1B[H")}setTitle(title){let sanitizedTitle=title.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");this.rawWrite(`\x1B]0;${sanitizedTitle}\x07`)}setProgress(active){active?(this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var FAKE_CURSOR_END2="\x1B[7m \x1B[0m";function clampMentions(mentions,length){return mentions.map(range=>({start:Math.max(0,range.start),end:Math.min(length,range.end)})).filter(range=>range.start<range.end)}function cutPoints(length,mentions,cursorGlyph){let cuts=new Set([0,length]);for(let range of mentions)cuts.add(range.start),cuts.add(range.end);return cursorGlyph&&(cuts.add(cursorGlyph.start),cuts.add(cursorGlyph.end)),[...cuts].sort((left,right)=>left-right)}function renderEditorLine(input){let{text,cursor}=input,mentions=clampMentions(input.mentions,text.length),cursorInText=cursor!==void 0&&cursor.pos<text.length,cursorGlyph=cursorInText&&cursor.drawFakeCursor?{start:cursor.pos,end:cursor.pos+input.firstGrapheme(text.slice(cursor.pos)).length}:void 0,points=cutPoints(text.length,mentions,cursorGlyph),out="";for(let index=0;index<points.length-1;index++){let from=points[index]??0,to=points[index+1]??from;cursorInText&&from===cursor.pos&&(out+=cursor.marker);let segment=text.slice(from,to);cursorGlyph&&from===cursorGlyph.start?out+=`\x1B[7m${segment}\x1B[0m`:mentions.some(range=>from>=range.start&&to<=range.end)?out+=input.mentionStyle(segment):out+=segment}return cursor!==void 0&&!cursorInText&&(out+=cursor.marker,cursor.drawFakeCursor)?{text:out+FAKE_CURSOR_END2,cursorAppended:!0}:{text:out,cursorAppended:!1}}var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter4=getWordSegmenter();function isAtomicMarker(segment){return isPasteMarker(segment)||isImageMarker(segment)}function markerKind(segment){if(isPasteMarker(segment))return"paste";if(isImageMarker(segment))return"image"}function containsMarkerPrefix(text){return text.includes("[paste #")||text.includes("[Image #")}function isPrintableAsciiText(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code<32||code>126)return!1}return!0}function wordWrapAsciiLine(line,maxWidth){if(line.length<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],chunkStart=0;for(;chunkStart<line.length;){let chunkEnd=Math.min(line.length,chunkStart+maxWidth);if(chunkEnd<line.length){let breakAt=-1;for(let i=chunkEnd;i>chunkStart;i--){let code=line.charCodeAt(i-1);if(code===32||code===9){breakAt=i-1;break}}breakAt>chunkStart&&(chunkEnd=breakAt)}let raw=line.slice(chunkStart,chunkEnd),text=raw.trimEnd();for((text||chunks.length===0)&&chunks.push({text,startIndex:chunkStart,endIndex:chunkStart+raw.length}),chunkStart=chunkEnd;chunkStart<line.length;){let code=line.charCodeAt(chunkStart);if(code!==32&&code!==9)break;chunkStart++}}return chunks.length>0?chunks:[{text:"",startIndex:0,endIndex:0}]}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(preSegmented===void 0&&!/\s/.test(line)&&!containsMarkerPrefix(line)&&isPrintableAsciiText(line))return wordWrapAsciiLine(line,maxWidth);if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isAtomicMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&¤tWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isAtomicMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isAtomicMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isAtomicMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#","$"];function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`(?:^|[\\s])[${triggerCharacters.map(escapeCharacterClass).join("")}][^\\s]*$`)}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${escapedWithoutAt.join("")}][^\\s]*)$`)}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{constructor(tui,theme,options={}){this.state={lines:[""],cursorLine:0,cursorCol:0},this.focused=!1,this.paddingX=0,this.lastWidth=80,this.renderedVisibleLineCount=1,this.renderedAutocompleteHeight=0,this.scrollOffset=0,this.autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS],this.autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters),this.autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters),this.autocompleteState=null,this.autocompletePrefix="",this.autocompleteMaxVisible=5,this.autocompleteRequestTask=Promise.resolve(),this.autocompleteStartToken=0,this.autocompleteRequestId=0,this.pasteMarkers=new PasteMarkerRegistry,this.imageMarkers=new ImageMarkerRegistry,this.pasteBuffer="",this.isInPaste=!1,this.history=[],this.historyIndex=-1,this.historyDraft=null,this.killRing=new KillRing,this.lastAction=null,this.jumpMode=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.undoStack=new UndoStack,this.wrappedLineCache=[],this.disableSubmit=!1,this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0,this.terminalEnvironment=options.terminalEnvironment,this.terminalPlatform=options.terminalPlatform,this.terminalSocketExists=options.terminalSocketExists;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter4:graphemeSegmenter2,this.authorizedMarkers(text))}authorizedMarkers(text){let imageMarkers=this.imageMarkers.authorizedMarkers(text);if(imageMarkers.size===0)return this.pasteMarkers.authorizedMarkers(text);let merged=new Set(this.pasteMarkers.authorizedMarkers(text));for(let marker of imageMarkers)merged.add(marker);return merged}removePasteMarker(id){let removal=this.pasteMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
|
|
107
|
+
`),this.restoreRenderState({previousLines:[],previousWidth:0,previousHeight:0,cursorRow:0,hardwareCursorRow:0,maxLinesRendered:0,previousViewportTop:0})),super.doRender(),this.noteCommittedMouseFrame();let components=[],visit=component=>{if(components.push(component),component instanceof Container)for(let child of component.children)visit(child)};for(let root of this.getMouseLayoutRoots())visit(root);(this.previousLines.length!==this.committedMouseLines.length||this.previousLines.some((line,index)=>line!==this.committedMouseLines[index])||components.length!==this.committedMouseComponents.length||components.some((component,index)=>component!==this.committedMouseComponents[index]))&&this.layoutRevision++,this.committedMouseLines=[...this.previousLines],this.committedMouseComponents=components,this.calibrateMouseAnchor()}applyMouseResult(result){if(!result?.focus)return;let target=this.resolveMouseFocusTarget(result.focusTarget??result.target.component);target&&this.setFocus(target)}handleMouseInput(data){if(!isMouseSequence(data))return{consume:!1};let raw=parseSgrMouseEvent(data);if(!this.trackingEnabled||!raw||raw.button!==0)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let frameLine=this.resolveFrameLine(raw.y+1);if(frameLine===void 0||raw.x>=this.terminal.columns)return this.clicks.cancel(),this.mousePress=void 0,{consume:!0};let event=toTuiMouseEvent(raw.release?"release":"press",raw,this.terminal);if(raw.release){let press=this.mousePress;if(this.mousePress=void 0,!press||press.epoch!==this.placementEpoch||press.revision!==this.layoutRevision||press.x!==raw.x||press.y!==raw.y)return this.clicks.cancel(),{consume:!0};let count=this.clicks.release(raw,press.target.component,this.placementEpoch);if(count!==void 0){let click={...event,type:"click",clickCount:count},focusBeforeClick=this.getFocusedComponent(),clickResult=dispatchMouseEvent(press.target.component,retargetMouseEvent(click,press.target));this.getFocusedComponent()===focusBeforeClick&&this.applyMouseResult(clickResult),this.requestRender()}}else{let overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:dispatchMouseEvent(this,{...event,y:frameLine,height:this.previousLines.length}));this.mousePress=void 0,result?(this.applyMouseResult(result),this.mousePress={target:result.target,epoch:this.placementEpoch,revision:this.layoutRevision,x:raw.x,y:raw.y},this.clicks.press(raw,result.target.component,this.placementEpoch)):this.clicks.cancel(),this.requestRender()}return{consume:!0}}captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}};var dist_exports={};__export(dist_exports,{AltScreenSearchComponent:()=>AltScreenSearchComponent,Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,IMAGE_MARKER_REGEX:()=>IMAGE_MARKER_REGEX,IMAGE_MARKER_SINGLE:()=>IMAGE_MARKER_SINGLE,Image:()=>Image,ImageMarkerRegistry:()=>ImageMarkerRegistry,Input:()=>Input,KITTY_PLACEHOLDER_MAX:()=>KITTY_PLACEHOLDER_MAX,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,MOUSE_TRACKING:()=>MOUSE_TRACKING,Markdown:()=>Markdown,Marked:()=>Q,MouseClickSynthesizer:()=>MouseClickSynthesizer,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI:()=>TUI,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,buildKittyPlaceholderRow:()=>buildKittyPlaceholderRow,calculateImageRows:()=>calculateImageRows,clearRenderCache:()=>clearRenderCache,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,decodeMouseButton:()=>decodeMouseButton,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,expandPasteMarkers:()=>expandPasteMarkers,findAltScreenSearchMatches:()=>findAltScreenSearchMatches,formatImageMarker:()=>formatImageMarker,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getAltScreenSearchMatchKey:()=>getAltScreenSearchMatchKey,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getGraphemeSegmenter:()=>getGraphemeSegmenter,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getMarkdownHighlightCallCount:()=>getMarkdownHighlightCallCount,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getWebpDimensions:()=>getWebpDimensions,getWordSegmenter:()=>getWordSegmenter,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,imageMarkerId:()=>imageMarkerId,isFocusable:()=>isFocusable,isImageMarker:()=>isImageMarker,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isMouseSequence:()=>isMouseSequence,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,outerKittyGraphicsMode:()=>outerKittyGraphicsMode,parseKey:()=>parseKey,parseOsc11BackgroundColor:()=>parseOsc11BackgroundColor,parseSgrMouseEvent:()=>parseSgrMouseEvent,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,parseWheelEvent:()=>parseWheelEvent,renderImage:()=>renderImage,resetCapabilitiesCache:()=>resetCapabilitiesCache,resetMarkdownHighlightCallCount:()=>resetMarkdownHighlightCallCount,sanitizeTerminalLabel:()=>sanitizeTerminalLabel,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,shortenImagePath:()=>shortenImagePath,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,toTuiMouseEvent:()=>toTuiMouseEvent,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi,wrapTmuxPassthrough:()=>wrapTmuxPassthrough});var Box=class{constructor(paddingX=1,paddingY=1,bgFn){this.children=[],this.disposed=!1,this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}addChild(component){this.children.push(component),this.invalidateCache()}removeChild(component){let index=this.children.indexOf(component);index!==-1&&(this.children.splice(index,1),this.invalidateCache(),component.dispose?.())}clear(){for(let child of this.children)child.dispose?.();this.children=[],this.invalidateCache()}detachAll(){this.children=[],this.invalidateCache()}dispose(){if(!this.disposed){this.disposed=!0;for(let child of this.children)child.dispose?.();this.invalidateCache()}}setBgFn(bgFn){this.bgFn=bgFn}invalidateCache(){this.cache=void 0}matchCache(width,childLines,bgSample){let cache=this.cache;return!!cache&&cache.width===width&&cache.bgSample===bgSample&&cache.childLines.length===childLines.length&&cache.childLines.every((line,i)=>line===childLines[i])}invalidate(){this.invalidateCache();for(let child of this.children)child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let mouseChildren=this.mouseLayout?.width===contentWidth?this.mouseLayout.children:this.children.map(component=>({component,height:component.render(contentWidth).length})),childY=0;for(let{component:child,height:childHeight}of mouseChildren){if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){if(this.children.length===0)return[];let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),childLines=[],mouseChildren=[];for(let child of this.children){let lines=child.render(contentWidth);mouseChildren.push({component:child,height:lines.length});for(let line of lines)childLines.push(leftPad+line)}if(this.mouseLayout={width:contentWidth,children:mouseChildren},childLines.length===0)return[];let bgSample=this.bgFn?this.bgFn("test"):void 0;if(this.matchCache(width,childLines,bgSample))return this.cache.lines;let result=[];for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));for(let line of childLines)result.push(this.applyBg(line,width));for(let i=0;i<this.paddingY;i++)result.push(this.applyBg("",width));return this.cache={childLines,width,bgSample,lines:result},result}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded);return this.bgFn?applyBackgroundToLine(padded,width,this.bgFn):padded}};var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,Loader=class extends Text{constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.frames=[...DEFAULT_FRAMES],this.intervalMs=DEFAULT_INTERVAL_MS,this.currentFrame=0,this.indicatorIntervalId=null,this.messageIntervalId=null,this.indicatorFormatter=void 0,this.messageFormatter=void 0,this.messageIntervalMs=DEFAULT_INTERVAL_MS,this.messageAnimationStartedAt=0,this.ui=null,this.renderIndicatorVerbatim=!1,this.message="Loading...",this.lastDisplayedText=void 0,this.ui=ui,this.spinnerColorFn=spinnerColorFn,this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.messageFormatter&&(this.messageAnimationStartedAt=Date.now()),this.updateDisplay(),this.restartAnimation()}stop(){this.indicatorIntervalId&&(clearInterval(this.indicatorIntervalId),this.indicatorIntervalId=null),this.messageIntervalId&&(clearInterval(this.messageIntervalId),this.messageIntervalId=null)}dispose(){this.stop()}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.indicatorFormatter=indicator?.indicatorFormatter,this.messageFormatter=indicator?.messageFormatter,this.messageIntervalMs=indicator?.messageIntervalMs&&indicator.messageIntervalMs>0?indicator.messageIntervalMs:this.intervalMs,this.currentFrame=0,this.messageAnimationStartedAt=Date.now(),this.start()}restartAnimation(){this.stop(),this.frames.length>1&&(this.indicatorIntervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay()},this.intervalMs),this.indicatorIntervalId.unref?.()),(this.indicatorFormatter||this.messageFormatter)&&(this.messageAnimationStartedAt=Date.now(),this.messageIntervalId=setInterval(()=>{this.updateDisplay()},this.messageIntervalMs),this.messageIntervalId.unref?.())}getRenderedIndicator(animationElapsedMs=this.getAnimationElapsedMs()){let frame=this.frames[this.currentFrame]??"";return frame.length===0?"":this.indicatorFormatter?this.indicatorFormatter(frame,animationElapsedMs):this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}getAnimationElapsedMs(){return Math.max(0,Date.now()-this.messageAnimationStartedAt)}updateDisplay(){let animationElapsedMs=this.getAnimationElapsedMs(),renderedFrame=this.getRenderedIndicator(animationElapsedMs),indicator=renderedFrame.length>0?`${renderedFrame} `:"",renderedMessage=this.messageFormatter?this.messageFormatter(this.message,animationElapsedMs):this.messageColorFn(this.message),displayedText=`${indicator}${renderedMessage}`;displayedText!==this.lastDisplayedText&&(this.lastDisplayedText=displayedText,this.setText(displayedText),this.ui&&this.ui.requestRender())}};var CancellableLoader=class extends Loader{constructor(){super(...arguments),this.abortController=new AbortController}get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var IMAGE_MARKER_REGEX=/\[Image #([1-9]\d*)\]/g,IMAGE_MARKER_SINGLE=/^\[Image #([1-9]\d*)\]$/;function formatImageMarker(id){return`[Image #${id}]`}function isImageMarker(segment){return segment.length>=10&&IMAGE_MARKER_SINGLE.test(segment)}function imageMarkerId(segment){let match=segment.length>=10?IMAGE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function countOccurrences(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}var ImageMarkerRegistry=class{constructor(){this.entries=new Set,this.imageCounter=0}add(){let id=++this.imageCounter;return this.entries.add(id),formatImageMarker(id)}authorizedMarkers(text){let markers=new Set;for(let id of this.entries){let marker=formatImageMarker(id);countOccurrences(text,marker)===1&&markers.add(marker)}return markers}canonicalize(text){let order=this.ids(text);if(order.length===0)return{text,order};let renumbered=new Map;for(let[index,id]of order.entries())renumbered.set(id,index+1);let updatedText=text.replace(IMAGE_MARKER_REGEX,marker=>{let id=imageMarkerId(marker),newId=id===void 0?void 0:renumbered.get(id);return newId===void 0?marker:formatImageMarker(newId)});return this.entries=new Set(order.map((_2,index)=>index+1)),this.imageCounter=this.entries.size,{text:updatedText,order}}clear(){this.entries.clear(),this.imageCounter=0}ids(text){let authorized=this.authorizedMarkers(text),ordered=[];for(let match of text.matchAll(IMAGE_MARKER_REGEX))authorized.has(match[0])&&ordered.push(Number.parseInt(match[1],10));return ordered}install(state,text){this.restore(state),this.prune(text)}prune(text,previousText){for(let id of[...this.entries]){let marker=formatImageMarker(id);(!(previousText===void 0||countOccurrences(previousText,marker)===1)||countOccurrences(text,marker)!==1)&&this.entries.delete(id)}this.imageCounter=Math.max(...this.entries,0)}remove(id,text){if(!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence(text,formatImageMarker(id),""),higherIds=[...this.entries].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){this.entries.delete(oldId);let marker=formatImageMarker(oldId);if(countOccurrences(updatedText,marker)!==1)continue;let newId=oldId-1;updatedText=replaceSingleOccurrence(updatedText,marker,formatImageMarker(newId)),this.entries.add(newId)}return this.imageCounter=Math.max(...this.entries,0),{text:updatedText,removed:!0}}restore(state){this.entries=new Set(state.ids),this.imageCounter=Math.max(state.imageCounter,...this.entries,0)}snapshot(){return{ids:[...this.entries].sort((a,b2)=>a-b2),imageCounter:this.imageCounter}}};var PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function formatPasteMarker(id,lineCount,charCount){return lineCount>10?`[paste #${id} +${lineCount} lines]`:`[paste #${id} ${charCount} chars]`}function countLines(content){let lineCount=1;for(let index=0;index<content.length;index++)content.charCodeAt(index)===10&&lineCount++;return lineCount}function createEntry(id,content,marker){let charCount=content.length,lineMatch=marker?.match(PASTE_MARKER_SINGLE)?.[3]?.match(/^\+(\d+) lines$/),lineCount=lineMatch?Number.parseInt(lineMatch[1],10):countLines(content),canonical=formatPasteMarker(id,lineCount,charCount);return{content,marker:marker===canonical?marker:canonical,lineCount,charCount}}function countOccurrences2(text,marker){let count=0,offset=0;for(;offset<=text.length-marker.length;){let index=text.indexOf(marker,offset);if(index===-1)break;count++,offset=index+marker.length}return count}function replaceSingleOccurrence2(text,marker,replacement){let index=text.indexOf(marker);return index===-1||text.indexOf(marker,index+marker.length)!==-1?text:text.slice(0,index)+replacement+text.slice(index+marker.length)}function entriesFromState(state){let entries=new Map;for(let[id,content]of state.pastes)entries.set(id,createEntry(id,content,state.markers?.get(id)));return entries}function expandPasteMarkers(text,state){let entries=entriesFromState(state),byMarker=new Map;for(let entry of entries.values())byMarker.set(entry.marker,entry);let matches=[],counts=new Map;for(let match of text.matchAll(PASTE_MARKER_REGEX)){let marker=match[0];byMarker.has(marker)&&(matches.push({start:match.index,end:match.index+marker.length,marker}),counts.set(marker,(counts.get(marker)??0)+1))}if(matches.length===0)return text;let chunks=[],offset=0;for(let match of matches){chunks.push(text.slice(offset,match.start));let entry=byMarker.get(match.marker);chunks.push(counts.get(match.marker)===1?entry.content:match.marker),offset=match.end}return chunks.push(text.slice(offset)),chunks.join("")}function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function pasteMarkerId(segment){let match=segment.length>=10?PASTE_MARKER_SINGLE.exec(segment):null;return match?Number.parseInt(match[1],10):void 0}function segmentWithMarkers(text,baseSegmenter,validMarkers){if(validMarkers.size===0)return baseSegmenter.segment(text);let found=[];for(let marker2 of validMarkers){let start=text.indexOf(marker2);start!==-1&&found.push({start,end:start+marker2.length})}if(found.length===0)return baseSegmenter.segment(text);found.sort((a,b2)=>a.start-b2.start||b2.end-a.end);let markers=[];for(let range of found){let previous=markers[markers.length-1];previous&&range.start<previous.end||markers.push(range)}let result=[],markerIndex=0,marker=markers[0];for(let segment of baseSegmenter.segment(text)){for(;marker&&segment.index>=marker.end;)marker=markers[++markerIndex];!marker||segment.index<marker.start?result.push(segment):segment.index===marker.start&&result.push({segment:text.slice(marker.start,marker.end),index:marker.start,input:text})}return result}var PasteMarkerRegistry=class{constructor(){this.entries=new Map,this.pasteCounter=0,this.metadataBuilds=0}add(content,lineCount,charCount){let id=++this.pasteCounter,marker=formatPasteMarker(id,lineCount,charCount);return this.entries.set(id,{content,marker,lineCount,charCount}),this.metadataBuilds++,marker}authorizedMarkers(text){let markers=new Set;for(let entry of this.entries.values())countOccurrences2(text,entry.marker)===1&&markers.add(entry.marker);return markers}clear(){this.entries.clear(),this.pasteCounter=0}expand(text){return expandPasteMarkers(text,this.snapshot())}get metadataBuildCount(){return this.metadataBuilds}install(state,text){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0),this.prune(text)}prune(text,previousText){for(let[id,entry]of this.entries)(!(previousText===void 0||countOccurrences2(previousText,entry.marker)===1)||countOccurrences2(text,entry.marker)!==1)&&this.entries.delete(id);this.pasteCounter=Math.max(...this.entries.keys(),0)}remove(id,text){let removedEntry=this.entries.get(id);if(!removedEntry||!this.entries.delete(id))return{text,removed:!1};let updatedText=replaceSingleOccurrence2(text,removedEntry.marker,""),higherIds=[...this.entries.keys()].filter(entryId=>entryId>id).sort((a,b2)=>a-b2);for(let oldId of higherIds){let entry=this.entries.get(oldId);if(this.entries.delete(oldId),countOccurrences2(updatedText,entry.marker)!==1)continue;let newId=oldId-1,renamed=formatPasteMarker(newId,entry.lineCount,entry.charCount);updatedText=replaceSingleOccurrence2(updatedText,entry.marker,renamed),this.entries.set(newId,{...entry,marker:renamed})}return this.pasteCounter=Math.max(...this.entries.keys(),0),{text:updatedText,removed:!0}}snapshot(){let pastes=new Map,markers=new Map;for(let[id,entry]of this.entries)pastes.set(id,entry.content),markers.set(id,entry.marker);return{pastes,markers,pasteCounter:this.pasteCounter}}restore(state){this.entries=entriesFromState(state),this.metadataBuilds+=this.entries.size,this.pasteCounter=Math.max(state.pasteCounter,...this.entries.keys(),0)}};import*as fs2 from"node:fs";import*as path3 from"node:path";import{createRequire as createRequire2}from"node:module";import*as path2 from"node:path";import{createRequire}from"node:module";import{dirname as dirname3,isAbsolute as isAbsolute2,join as join3}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function resolvePackageEntry(resolveOverride){if(resolveOverride)return resolveOverride(TUI_PACKAGE_NAME);try{return fileURLToPath(import.meta.resolve(TUI_PACKAGE_NAME))}catch{}return moduleRequire.resolve(TUI_PACKAGE_NAME)}function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname3(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=resolvePackageEntry(options.resolvePackage);packageEntry&&isAbsolute2(packageEntry)&&candidates.push(join3(dirname3(packageEntry),"..",nativePath))}catch{}return candidates.push(join3(moduleDir,"..",nativePath),join3(moduleDir,nativePath),join3(dirname3(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path2.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}function observeProcessStderrWrites(listener){let original=process.stderr.write,observed=function(...args){return listener(),Reflect.apply(original,this,args)};return process.stderr.write=observed,()=>{process.stderr.write===observed&&(process.stderr.write=original)}}import{StringDecoder}from"node:string_decoder";import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~";function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let seqEnd=1;for(;seqEnd<=remaining.length;){let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else{let codepoint=remaining.codePointAt(0),character=String.fromCodePoint(codepoint);sequences.push(character),pos+=character.length}}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{constructor(options={}){super(),this.buffer="",this.timeout=null,this.discardingMouseFragment=!1,this.pasteMode=!1,this.pasteBuffer="",this.decoder=new StringDecoder("utf8"),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str,decodedFromBuffer=!1;if(Buffer.isBuffer(data))if(!((this.decoder.lastNeed??0)>0)&&data.length===1&&data[0]>=128&&data[0]<194){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=this.decoder.write(data),decodedFromBuffer=!0;else str=data;if(str.length===0&&this.buffer.length===0){decodedFromBuffer||this.emitDataSequence("");return}if(this.discardingMouseFragment){let terminator=str.search(/[\x40-\x7e]/),escapeIndex=str.indexOf(ESC);if(escapeIndex!==-1&&(terminator===-1||escapeIndex<terminator))str=str.slice(escapeIndex);else{if(terminator===-1)return;str=str.slice(terminator+1)}this.discardingMouseFragment=!1}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder,this.buffer.startsWith("\x1B[<")?(this.mouseFragmentStartedAt??=Date.now(),this.buffer.length>64&&(this.buffer="",this.discardingMouseFragment=!0)):this.mouseFragmentStartedAt=void 0;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];if(this.buffer.startsWith("\x1B[<")){let remaining=750-(Date.now()-(this.mouseFragmentStartedAt??Date.now()));return remaining>0&&this.buffer.length<=64?this.timeout=setTimeout(()=>this.flush(),remaining):(this.buffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!0),[]}let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.mouseFragmentStartedAt=void 0,this.discardingMouseFragment=!1,this.pendingKittyPrintableCodepoint=void 0,this.decoder=new StringDecoder("utf8")}getBuffer(){return this.buffer}destroy(){this.clear()}};import{execFileSync as execFileSync2}from"node:child_process";function queryTmuxCursorPosition(pane,deadline,execFile){let read=()=>{let remaining=deadline-Date.now();if(!(remaining<=0))try{let args=["display-message","-p","-t",pane,"#{cursor_y} #{cursor_x}"],output=execFile?execFile("tmux",args):execFileSync2("tmux",args,{encoding:"utf8",timeout:remaining,stdio:["ignore","pipe","ignore"]}),match=/^(\d+) (\d+)$/.exec(output.trim());if(!match||Date.now()>=deadline)return;let row=Number(match[1])+1,column=Number(match[2])+1;return Number.isSafeInteger(row)&&Number.isSafeInteger(column)?{row,column}:void 0}catch{return}},first=read();return!first||deadline-Date.now()<=10?Promise.resolve(void 0):new Promise(resolve=>{setTimeout(()=>{let second=read();resolve(second?.row===first.row&&second.column===first.column?second:void 0)},10)})}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,DEAD_TERMINAL_ERROR_CODES=new Set(["EIO","EPIPE","ENOTCONN"]),EIO_ERRNO=5,EPIPE_ERRNO=32,DEAD_TERMINAL_ERRNOS=new Set([EIO_ERRNO,EPIPE_ERRNO]),ERRNO_IN_MESSAGE_PATTERN=/errno:\s*(\d+)/,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u\x1B[c`;function parseCursorPositionResponse(sequence){let match=/^\x1b\[\?(\d+);(\d+)(?:;(\d+))?R$/.exec(sequence);return match?{row:Number(match[1]),column:Number(match[2]),...match[3]===void 0?{}:{page:Number(match[3])}}:void 0}function parseKeyboardProtocolNegotiationSequence(sequence){let cursorPosition=parseCursorPositionResponse(sequence);if(cursorPosition)return{type:"cursor-position",...cursorPosition};let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}function normalizeWarpWslShiftEnterInput(data,env=process.env,platform=process.platform,socketExists=socketPath=>{try{return fs2.statSync(socketPath).isSocket()}catch{return!1}}){if(data!==`
|
|
108
|
+
`||platform!=="linux"||isMultiplexerSession(env)||env.SSH_CONNECTION?.trim()||env.SSH_CLIENT?.trim()||env.SSH_TTY?.trim())return data;let isWarp=!!(env.WARP_SESSION_ID?.trim()||env.WARP_TERMINAL_SESSION_UUID?.trim()),interopPath=env.WSL_INTEROP?.trim(),isWsl=isWarp&&interopPath!==void 0&&/^\/run\/WSL\/\d+_interop$/.test(interopPath)&&socketExists(interopPath);return isWarp&&isWsl?NATIVE_SHIFT_ENTER_SEQUENCE:data}function keyboardEnhancementEnabled(){let value=process.env.PI_TUI_KEYBOARD_PROTOCOL;return value===void 0?!0:!["0","false","no","off"].includes(value.toLowerCase())}function isDeadTerminalError(error){if(!(error instanceof Error))return!1;if("code"in error&&typeof error.code=="string")return DEAD_TERMINAL_ERROR_CODES.has(error.code);if("errno"in error&&error.errno===EIO_ERRNO)return!0;let messageErrno=ERRNO_IN_MESSAGE_PATTERN.exec(error.message);return messageErrno?DEAD_TERMINAL_ERRNOS.has(Number.parseInt(messageErrno[1],10)):!1}var STDIN_ERROR_HANDLER_GRACE_MS=250,stdinErrorSubscribers=new Set;function isTerminalDetachStdinError(err){if(err.code==="EIO")return!0;let errno=err.errno;return errno===EIO_ERRNO||errno===-EIO_ERRNO}var dispatchStdinError=err=>{if(!isTerminalDetachStdinError(err)){if(!process.stdin.listeners("error").some(listener=>listener!==dispatchStdinError))throw err;return}for(let subscriber of stdinErrorSubscribers)subscriber(err)};function subscribeToStdinErrors(subscriber){stdinErrorSubscribers.size===0&&process.stdin.on("error",dispatchStdinError),stdinErrorSubscribers.add(subscriber)}function unsubscribeFromStdinErrors(subscriber){stdinErrorSubscribers.delete(subscriber),stdinErrorSubscribers.size===0&&process.stdin.removeListener("error",dispatchStdinError)}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{constructor(options){this.wasRaw=!1,this.externalWriteObservers=new Set,this.keyboardNegotiationSettled=!1,this.cursorQueryTimedOut=!1,this.forwardingExternalWrite=!1,this._kittyProtocolActive=!1,this._modifyOtherKeysActive=!1,this.keyboardProtocolPushed=!1,this.keyboardProtocolNegotiationBuffer="",this.discardingPrivateResponse=!1,this.writeLogPath=(()=>{let env=process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs2.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path3.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})(),this.onExternalStdoutWrite=options?.onExternalStdoutWrite,this.observeExternalStderrWrites=options?.observeExternalStderrWrites??observeProcessStderrWrites,this.tmuxExecFile=options?.tmuxExecFile}get kittyProtocolActive(){return this._kittyProtocolActive}queryCursorPosition(){if(this.cursorQuery)return this.cursorQuery.promise;if(!this.inputHandler||this.cursorQueryTimedOut)return Promise.resolve(void 0);let resolve,promise=new Promise(settle=>{resolve=settle}),timer=setTimeout(()=>{this.cursorQueryTimedOut=!0,this.settleCursorQuery(void 0)},750);return this.cursorQuery={promise,resolve,timer,issued:!1,tmuxPane:process.env.TMUX_PANE,deadline:Date.now()+750},this.issueCursorQuery(),promise}issueCursorQuery(){if(!this.keyboardNegotiationSettled||!this.cursorQuery||this.cursorQuery.issued)return;this.cursorQuery.issued=!0,this.rawWrite("\x1B[?6n");let pending=this.cursorQuery;pending?.tmuxPane!==void 0&&queryTmuxCursorPosition(pending.tmuxPane,pending.deadline,this.tmuxExecFile).then(position=>{this.cursorQuery===pending&&(Date.now()>=pending.deadline&&(this.cursorQueryTimedOut=!0),this.settleCursorQuery(this.cursorQueryTimedOut?void 0:position))})}settleCursorQuery(position){let pending=this.cursorQuery;pending&&(this.cursorQuery=void 0,clearTimeout(pending.timer),pending.resolve(position))}observeExternalWrites(listener){return this.externalWriteObservers.add(listener),this.inputHandler&&(this.installExternalStdoutGuard(),this.installExternalStderrObserver()),()=>{this.externalWriteObservers.delete(listener)}}noteExternalWrite(){for(let listener of this.externalWriteObservers)listener()}installExternalStderrObserver(){this.stopExternalStderrObservation||this.externalWriteObservers.size===0||(this.stopExternalStderrObservation=this.observeExternalStderrWrites(()=>this.noteExternalWrite()))}rawWrite(data){if(this.rawStdoutWrite){this.rawStdoutWrite(data);return}process.stdout.write(data)}installExternalStdoutGuard(){let handler=this.onExternalStdoutWrite;if(!handler&&this.externalWriteObservers.size===0||this.originalStdoutWrite)return;this.originalStdoutWrite=process.stdout.write;let rawWrite=process.stdout.write.bind(process.stdout);this.rawStdoutWrite=rawWrite,process.stdout.write=((chunk,encodingOrCallback,callback)=>{let cb=typeof encodingOrCallback=="function"?encodingOrCallback:callback,encoding=typeof encodingOrCallback=="string"?encodingOrCallback:void 0,text=typeof chunk=="string"?chunk:Buffer.from(chunk).toString(encoding);if(!handler||this.forwardingExternalWrite)return this.noteExternalWrite(),rawWrite(text),cb?.(null),!0;this.forwardingExternalWrite=!0;try{handler(text)}catch{this.noteExternalWrite(),rawWrite(text)}finally{this.forwardingExternalWrite=!1}return cb?.(null),!0})}removeExternalStdoutGuard(){this.originalStdoutWrite&&(process.stdout.write=this.originalStdoutWrite,this.originalStdoutWrite=void 0,this.rawStdoutWrite=void 0)}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.installExternalStdoutGuard(),this.installExternalStderrObserver(),this.keyboardNegotiationSettled=!keyboardEnhancementEnabled(),this.cursorQueryTimedOut=!1,this.discardingPrivateResponse=!1,this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),this.stdinErrorHandlerCleanupTimer&&(clearTimeout(this.stdinErrorHandlerCleanupTimer),this.stdinErrorHandlerCleanupTimer=void 0),this.stdinErrorHandler||(this.stdinErrorHandler=()=>{},subscribeToStdinErrors(this.stdinErrorHandler)),this.rawWrite("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(this.discardingPrivateResponse)if(sequence.startsWith("\x1B"))this.discardingPrivateResponse=!1;else{/[\x40-\x7e]/.test(sequence)&&(this.discardingPrivateResponse=!1);return}let negotiationSequence=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}this.handleKeyboardProtocolNegotiationSequence(negotiationSequence)||this.forwardInputSequence(sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),keyboardEnhancementEnabled()&&((process.env.TMUX!==void 0||process.env.TMUX_PANE!==void 0)&&this.enableModifyOtherKeys(),this.keyboardProtocolPushed=!0,this.clearKeyboardProtocolNegotiationBuffer(),this.rawWrite(KITTY_KEYBOARD_PROTOCOL_QUERY))}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(!negotiationSequence)return!1;if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="cursor-position"){if(this.cursorQuery?.issued&&this.cursorQuery.tmuxPane===void 0){let{type:_type,...position}=negotiationSequence;this.settleCursorQuery(position)}return!0}return this.keyboardNegotiationSettled=!0,this.issueCursorQuery(),negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence2;if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return negotiationSequence;if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(discardTail=!1){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;if(this.clearKeyboardProtocolNegotiationBuffer(),/^\x1b\[\?[\d;]*$/.test(sequence)){this.discardingPrivateResponse=discardTail;return}this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput(!0)},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(this.rawWrite("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(this.rawWrite("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.settleCursorQuery(void 0),this.stopExternalStderrObservation?.(),this.stopExternalStderrObservation=void 0,this.clearProgressInterval()&&this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.rawWrite("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;if(this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(this.rawWrite("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode)try{process.stdin.setRawMode(this.wasRaw)}catch(error){if(!isDeadTerminalError(error))throw error}this.removeExternalStdoutGuard(),this.scheduleStdinErrorHandlerCleanup()}scheduleStdinErrorHandlerCleanup(){if(!this.stdinErrorHandler||this.stdinErrorHandlerCleanupTimer)return;let handler=this.stdinErrorHandler;this.stdinErrorHandlerCleanupTimer=setTimeout(()=>{this.stdinErrorHandlerCleanupTimer=void 0,this.stdinErrorHandler===handler&&(this.stdinErrorHandler=void 0,unsubscribeFromStdinErrors(handler))},STDIN_ERROR_HANDLER_GRACE_MS),this.stdinErrorHandlerCleanupTimer.unref()}write(data){if(this.rawWrite(data),this.writeLogPath)try{fs2.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?this.rawWrite(`\x1B[${lines}B`):lines<0&&this.rawWrite(`\x1B[${-lines}A`)}hideCursor(){this.rawWrite("\x1B[?25l")}showCursor(){this.rawWrite("\x1B[?25h")}clearLine(){this.rawWrite("\x1B[K")}clearFromCursor(){this.rawWrite("\x1B[J")}clearScreen(){this.rawWrite("\x1B[2J\x1B[H")}setTitle(title){let sanitizedTitle=title.replace(/[\u0000-\u001f\u007f-\u009f]/g,"");this.rawWrite(`\x1B]0;${sanitizedTitle}\x07`)}setProgress(active){active?(this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{this.rawWrite(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),this.rawWrite(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var FAKE_CURSOR_END2="\x1B[7m \x1B[0m";function clampMentions(mentions,length){return mentions.map(range=>({start:Math.max(0,range.start),end:Math.min(length,range.end)})).filter(range=>range.start<range.end)}function cutPoints(length,mentions,cursorGlyph){let cuts=new Set([0,length]);for(let range of mentions)cuts.add(range.start),cuts.add(range.end);return cursorGlyph&&(cuts.add(cursorGlyph.start),cuts.add(cursorGlyph.end)),[...cuts].sort((left,right)=>left-right)}function renderEditorLine(input){let{text,cursor}=input,mentions=clampMentions(input.mentions,text.length),cursorInText=cursor!==void 0&&cursor.pos<text.length,cursorGlyph=cursorInText&&cursor.drawFakeCursor?{start:cursor.pos,end:cursor.pos+input.firstGrapheme(text.slice(cursor.pos)).length}:void 0,points=cutPoints(text.length,mentions,cursorGlyph),out="";for(let index=0;index<points.length-1;index++){let from=points[index]??0,to=points[index+1]??from;cursorInText&&from===cursor.pos&&(out+=cursor.marker);let segment=text.slice(from,to);cursorGlyph&&from===cursorGlyph.start?out+=`\x1B[7m${segment}\x1B[0m`:mentions.some(range=>from>=range.start&&to<=range.end)?out+=input.mentionStyle(segment):out+=segment}return cursor!==void 0&&!cursorInText&&(out+=cursor.marker,cursor.drawFakeCursor)?{text:out+FAKE_CURSOR_END2,cursorAppended:!0}:{text:out,cursorAppended:!1}}var graphemeSegmenter2=getGraphemeSegmenter(),wordSegmenter4=getWordSegmenter();function isAtomicMarker(segment){return isPasteMarker(segment)||isImageMarker(segment)}function markerKind(segment){if(isPasteMarker(segment))return"paste";if(isImageMarker(segment))return"image"}function containsMarkerPrefix(text){return text.includes("[paste #")||text.includes("[Image #")}function isPrintableAsciiText(text){for(let i=0;i<text.length;i++){let code=text.charCodeAt(i);if(code<32||code>126)return!1}return!0}function wordWrapAsciiLine(line,maxWidth){if(line.length<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],chunkStart=0;for(;chunkStart<line.length;){let chunkEnd=Math.min(line.length,chunkStart+maxWidth);if(chunkEnd<line.length){let breakAt=-1;for(let i=chunkEnd;i>chunkStart;i--){let code=line.charCodeAt(i-1);if(code===32||code===9){breakAt=i-1;break}}breakAt>chunkStart&&(chunkEnd=breakAt)}let raw=line.slice(chunkStart,chunkEnd),text=raw.trimEnd();for((text||chunks.length===0)&&chunks.push({text,startIndex:chunkStart,endIndex:chunkStart+raw.length}),chunkStart=chunkEnd;chunkStart<line.length;){let code=line.charCodeAt(chunkStart);if(code!==32&&code!==9)break;chunkStart++}}return chunks.length>0?chunks:[{text:"",startIndex:0,endIndex:0}]}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(preSegmented===void 0&&!/\s/.test(line)&&!containsMarkerPrefix(line)&&isPrintableAsciiText(line))return wordWrapAsciiLine(line,maxWidth);if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...graphemeSegmenter2.segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isAtomicMarker(grapheme)&&isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&¤tWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth){let subChunks=wordWrapLine(grapheme,maxWidth);for(let j=0;j<subChunks.length-1;j++){let sc=subChunks[j];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isAtomicMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&next&&!isWhitespaceChar(next.segment)){let isCjk=!isAtomicMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isAtomicMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#","$"];function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`(?:^|[\\s])[${triggerCharacters.map(escapeCharacterClass).join("")}][^\\s]*$`)}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`(?:^|[ \\t])(?:@(?:"[^"]*|[^\\s]*)|[${escapedWithoutAt.join("")}][^\\s]*)$`)}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{constructor(tui,theme,options={}){this.state={lines:[""],cursorLine:0,cursorCol:0},this.focused=!1,this.paddingX=0,this.lastWidth=80,this.renderedVisibleLineCount=1,this.renderedAutocompleteHeight=0,this.scrollOffset=0,this.autocompleteTriggerCharacters=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS],this.autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters),this.autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters),this.autocompleteState=null,this.autocompletePrefix="",this.autocompleteMaxVisible=5,this.autocompleteRequestTask=Promise.resolve(),this.autocompleteStartToken=0,this.autocompleteRequestId=0,this.pasteMarkers=new PasteMarkerRegistry,this.imageMarkers=new ImageMarkerRegistry,this.pasteBuffer="",this.isInPaste=!1,this.history=[],this.historyIndex=-1,this.historyDraft=null,this.killRing=new KillRing,this.lastAction=null,this.jumpMode=null,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.undoStack=new UndoStack,this.wrappedLineCache=[],this.disableSubmit=!1,this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0,this.terminalEnvironment=options.terminalEnvironment,this.terminalPlatform=options.terminalPlatform,this.terminalSocketExists=options.terminalSocketExists;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}segment(text,mode){return segmentWithMarkers(text,mode==="word"?wordSegmenter4:graphemeSegmenter2,this.authorizedMarkers(text))}authorizedMarkers(text){let imageMarkers=this.imageMarkers.authorizedMarkers(text);if(imageMarkers.size===0)return this.pasteMarkers.authorizedMarkers(text);let merged=new Set(this.pasteMarkers.authorizedMarkers(text));for(let marker of imageMarkers)merged.add(marker);return merged}removePasteMarker(id){let removal=this.pasteMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
|
|
109
109
|
`),!0):!1}removeImageMarker(id){let survivors=this.imageMarkers.ids(this.getText()).filter(entryId=>entryId!==id),removal=this.imageMarkers.remove(id,this.getText());return removal.removed?(this.state.lines=removal.text.split(`
|
|
110
110
|
`),this.onImageMarkersChanged?.(survivors),!0):!1}removeMarkerSegment(segment){switch(markerKind(segment)){case"paste":{let id=pasteMarkerId(segment);return id!==void 0&&this.removePasteMarker(id)}case"image":{let id=imageMarkerId(segment);return id!==void 0&&this.removeImageMarker(id)}default:return!1}}notifyImageMarkersChanged(){this.onImageMarkersChanged?.(this.imageMarkers.ids(this.getText()))}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
|
|
111
111
|
`);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){this.wrappedLineCache.length=0}getWrappedLine(lineIndex,contentWidth){let line=this.state.lines[lineIndex]||"",cached=this.wrappedLineCache[lineIndex];if(cached&&cached.lineRef===line&&cached.contentWidth===contentWidth)return cached;let width=isPrintableAsciiText(line)?line.length:visibleWidth(line);if(containsMarkerPrefix(line))return{width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth,[...this.segment(line,"grapheme")])};let wrapped={lineRef:line,contentWidth,width,chunks:width<=contentWidth?[{text:line,startIndex:0,endIndex:line.length}]:wordWrapLine(line,contentWidth)};return this.wrappedLineCache[lineIndex]=wrapped,wrapped}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let layoutLines=this.layoutText(layoutWidth),terminalRows=this.tui.terminal.rows,maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused,drawFakeCursor=!this.tui.getShowHardwareCursor(),mentionStyle=this.theme.mention,mentionRangesByLine=new Map,mentionRangesFor=layoutLine=>{if(!mentionStyle||!this.autocompleteProvider?.getMentionRanges)return[];let ranges=mentionRangesByLine.get(layoutLine.logicalLine);return ranges===void 0&&(ranges=this.autocompleteProvider.getMentionRanges(this.state.lines[layoutLine.logicalLine]??""),mentionRangesByLine.set(layoutLine.logicalLine,ranges)),ranges.map(range=>({start:range.start-layoutLine.startIndex,end:range.end-layoutLine.startIndex}))};for(let layoutLine of visibleLines){let lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1,cursor=layoutLine.hasCursor&&layoutLine.cursorPos!==void 0?{pos:layoutLine.cursorPos,marker:emitCursorMarker?CURSOR_MARKER:"",drawFakeCursor}:void 0,rendered=renderEditorLine({text:layoutLine.text,mentions:mentionRangesFor(layoutLine),mentionStyle:mentionStyle??(text=>text),cursor,firstGrapheme:text=>[...this.segment(text,"grapheme")][0]?.segment??""}),displayText=rendered.text;rendered.cursorAppended&&(lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>contentWidth&&paddingX>0&&(cursorInPadding=!0));let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){let lineWidth=visibleWidth(line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.max(1,event.width-paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(data){data=normalizeWarpWslShiftEnterInput(data,this.terminalEnvironment,this.terminalPlatform,this.terminalSocketExists);let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(kb.matches(data,"tui.select.confirm")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&¤tLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
|