diff --git a/.envrc b/.envrc index 3550a30f2d..45c59523cb 100644 --- a/.envrc +++ b/.envrc @@ -1 +1,5 @@ +watch_file pyproject.toml uv.lock +watch_file ui-tui/package-lock.json ui-tui/package.json +watch_file flake.nix flake.lock nix/devShell.nix nix/tui.nix nix/package.nix nix/python.nix + use flake diff --git a/.gitignore b/.gitignore index 137793bb1d..e516d154f3 100644 --- a/.gitignore +++ b/.gitignore @@ -60,5 +60,6 @@ mini-swe-agent/ # Nix .direnv/ +.nix-stamps/ result website/static/api/skills-index.json diff --git a/AGENTS.md b/AGENTS.md index 98d1f87430..8bd979b058 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,6 +56,19 @@ hermes-agent/ │ ├── run.py # Main loop, slash commands, message dispatch │ ├── session.py # SessionStore — conversation persistence │ └── platforms/ # Adapters: telegram, discord, slack, whatsapp, homeassistant, signal, qqbot +├── ui-tui/ # Ink (React) terminal UI — `hermes --tui` +│ ├── src/entry.tsx # TTY gate + render() +│ ├── src/app.tsx # Main state machine and UI +│ ├── src/gatewayClient.ts # Child process + JSON-RPC bridge +│ ├── src/app/ # Decomposed app logic (event handler, slash handler, stores, hooks) +│ ├── src/components/ # Ink components (branding, markdown, prompts, pickers, etc.) +│ ├── src/hooks/ # useCompletion, useInputHistory, useQueue, useVirtualHistory +│ └── src/lib/ # Pure helpers (history, osc52, text, rpc, messages) +├── tui_gateway/ # Python JSON-RPC backend for the TUI +│ ├── entry.py # stdio entrypoint +│ ├── server.py # RPC handlers and session logic +│ ├── render.py # Optional rich/ANSI bridge +│ └── slash_worker.py # Persistent HermesCLI subprocess for slash commands ├── acp_adapter/ # ACP server (VS Code / Zed / JetBrains integration) ├── cron/ # Scheduler (jobs.py, scheduler.py) ├── environments/ # RL training environments (Atropos) @@ -179,6 +192,59 @@ if canonical == "mycommand": --- +## TUI Architecture (ui-tui + tui_gateway) + +The TUI is a full replacement for the classic (prompt_toolkit) CLI, activated via `hermes --tui` or `HERMES_TUI=1`. + +### Process Model + +``` +hermes --tui + └─ Node (Ink) ──stdio JSON-RPC── Python (tui_gateway) + │ └─ AIAgent + tools + sessions + └─ renders transcript, composer, prompts, activity +``` + +TypeScript owns the screen. Python owns sessions, tools, model calls, and slash command logic. + +### Transport + +Newline-delimited JSON-RPC over stdio. Requests from Ink, events from Python. See `tui_gateway/server.py` for the full method/event catalog. + +### Key Surfaces + +| Surface | Ink component | Gateway method | +|---------|---------------|----------------| +| Chat streaming | `app.tsx` + `messageLine.tsx` | `prompt.submit` → `message.delta/complete` | +| Tool activity | `thinking.tsx` | `tool.start/progress/complete` | +| Approvals | `prompts.tsx` | `approval.respond` ← `approval.request` | +| Clarify/sudo/secret | `prompts.tsx`, `maskedPrompt.tsx` | `clarify/sudo/secret.respond` | +| Session picker | `sessionPicker.tsx` | `session.list/resume` | +| Slash commands | Local handler + fallthrough | `slash.exec` → `_SlashWorker`, `command.dispatch` | +| Completions | `useCompletion` hook | `complete.slash`, `complete.path` | +| Theming | `theme.ts` + `branding.tsx` | `gateway.ready` with skin data | + +### Slash Command Flow + +1. Built-in client commands (`/help`, `/quit`, `/clear`, `/resume`, `/copy`, `/paste`, etc.) handled locally in `app.tsx` +2. Everything else → `slash.exec` (runs in persistent `_SlashWorker` subprocess) → `command.dispatch` fallback + +### Dev Commands + +```bash +cd ui-tui +npm install # first time +npm run dev # watch mode (rebuilds hermes-ink + tsx --watch) +npm start # production +npm run build # full build (hermes-ink + tsc) +npm run type-check # typecheck only (tsc --noEmit) +npm run lint # eslint +npm run fmt # prettier +npm test # vitest +``` + +--- + ## Adding New Tools Requires changes in **2 files**: diff --git a/README.md b/README.md index 088c3b91b9..622910b3a9 100644 --- a/README.md +++ b/README.md @@ -141,11 +141,18 @@ See `hermes claw migrate --help` for all options, or use the `openclaw-migration We welcome contributions! See the [Contributing Guide](https://hermes-agent.nousresearch.com/docs/developer-guide/contributing) for development setup, code style, and PR process. -Quick start for contributors: +Quick start for contributors — clone and go with `setup-hermes.sh`: ```bash git clone https://github.com/NousResearch/hermes-agent.git cd hermes-agent +./setup-hermes.sh # installs uv, creates venv, installs .[all], symlinks ~/.local/bin/hermes +./hermes # auto-detects the venv, no need to `source` first +``` + +Manual path (equivalent to the above): + +```bash curl -LsSf https://astral.sh/uv/install.sh | sh uv venv venv --python 3.11 source venv/bin/activate diff --git a/cli.py b/cli.py index 4102dcf021..c0c17babc4 100644 --- a/cli.py +++ b/cli.py @@ -18,6 +18,8 @@ import os import shutil import sys import json +import re +import base64 import atexit import tempfile import time @@ -78,6 +80,42 @@ _project_env = Path(__file__).parent / '.env' load_hermes_dotenv(hermes_home=_hermes_home, project_env=_project_env) +_REASONING_TAGS = ( + "REASONING_SCRATCHPAD", + "think", + "reasoning", + "THINKING", + "thinking", +) + + +def _strip_reasoning_tags(text: str) -> str: + cleaned = text + for tag in _REASONING_TAGS: + cleaned = re.sub(rf"<{tag}>.*?\s*", "", cleaned, flags=re.DOTALL) + cleaned = re.sub(rf"<{tag}>.*$", "", cleaned, flags=re.DOTALL) + return cleaned.strip() + + +def _assistant_content_as_text(content: Any) -> str: + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): + parts = [ + str(part.get("text", "")) + for part in content + if isinstance(part, dict) and part.get("type") == "text" + ] + return "\n".join(p for p in parts if p) + return str(content) + + +def _assistant_copy_text(content: Any) -> str: + return _strip_reasoning_tags(_assistant_content_as_text(content)) + + # ============================================================================= # Configuration Loading # ============================================================================= @@ -1172,6 +1210,10 @@ def _resolve_attachment_path(raw_path: str) -> Path | None: return None expanded = os.path.expandvars(os.path.expanduser(token)) + if os.name != "nt": + normalized = expanded.replace("\\", "/") + if len(normalized) >= 3 and normalized[1] == ":" and normalized[2] == "/" and normalized[0].isalpha(): + expanded = f"/mnt/{normalized[0].lower()}/{normalized[3:]}" path = Path(expanded) if not path.is_absolute(): base_dir = Path(os.getenv("TERMINAL_CWD", os.getcwd())) @@ -1254,10 +1296,12 @@ def _detect_file_drop(user_input: str) -> "dict | None": or stripped.startswith("~") or stripped.startswith("./") or stripped.startswith("../") + or (len(stripped) >= 3 and stripped[1] == ":" and stripped[2] in ("\\", "/") and stripped[0].isalpha()) or stripped.startswith('"/') or stripped.startswith('"~') or stripped.startswith("'/") or stripped.startswith("'~") + or (len(stripped) >= 4 and stripped[0] in ("'", '"') and stripped[2] == ":" and stripped[3] in ("\\", "/") and stripped[1].isalpha()) ) if not starts_like_path: return None @@ -3125,21 +3169,6 @@ class HermesCLI: MAX_ASST_LEN = 200 # truncate assistant text MAX_ASST_LINES = 3 # max lines of assistant text - def _strip_reasoning(text: str) -> str: - """Remove ... blocks - from displayed text (reasoning model internal thoughts).""" - import re - cleaned = re.sub( - r".*?\s*", - "", text, flags=re.DOTALL, - ) - # Also strip unclosed reasoning tags at the end - cleaned = re.sub( - r".*$", - "", cleaned, flags=re.DOTALL, - ) - return cleaned.strip() - # Collect displayable entries (skip system, tool-result messages) entries = [] # list of (role, display_text) _last_asst_idx = None # index of last assistant entry @@ -3171,7 +3200,7 @@ class HermesCLI: elif role == "assistant": text = "" if content is None else str(content) - text = _strip_reasoning(text) + text = _strip_reasoning_tags(text) parts = [] full_parts = [] # un-truncated version if text: @@ -3510,6 +3539,26 @@ class HermesCLI: killed = process_registry.kill_all() print(f" ✅ Stopped {killed} process(es).") + def _handle_agents_command(self): + """Handle /agents — show background processes and agent status.""" + from tools.process_registry import format_uptime_short, process_registry + + processes = process_registry.list_sessions() + running = [p for p in processes if p.get("status") == "running"] + finished = [p for p in processes if p.get("status") != "running"] + + _cprint(f" Running processes: {len(running)}") + for p in running: + cmd = p.get("command", "")[:80] + up = format_uptime_short(p.get("uptime_seconds", 0)) + _cprint(f" {p.get('session_id', '?')} · {up} · {cmd}") + + if finished: + _cprint(f" Recently finished: {len(finished)}") + + agent_running = getattr(self, "_agent_running", False) + _cprint(f" Agent: {'running' if agent_running else 'idle'}") + def _handle_paste_command(self): """Handle /paste — explicitly check clipboard for an image. @@ -3535,6 +3584,61 @@ class HermesCLI: else: _cprint(f" {_DIM}(._.) No image found in clipboard{_RST}") + def _write_osc52_clipboard(self, text: str) -> None: + """Copy *text* to terminal clipboard via OSC 52.""" + payload = base64.b64encode(text.encode("utf-8")).decode("ascii") + seq = f"\x1b]52;c;{payload}\x07" + out = getattr(self, "_app", None) + output = getattr(out, "output", None) if out else None + if output and hasattr(output, "write_raw"): + output.write_raw(seq) + output.flush() + return + if output and hasattr(output, "write"): + output.write(seq) + output.flush() + return + sys.stdout.write(seq) + sys.stdout.flush() + + def _handle_copy_command(self, cmd_original: str) -> None: + """Handle /copy [number] — copy assistant output to clipboard.""" + parts = cmd_original.split(maxsplit=1) + arg = parts[1].strip() if len(parts) > 1 else "" + + assistant = [m for m in self.conversation_history if m.get("role") == "assistant"] + if not assistant: + _cprint(" Nothing to copy yet.") + return + + if arg: + try: + idx = int(arg) - 1 + except ValueError: + _cprint(" Usage: /copy [number]") + return + if idx < 0 or idx >= len(assistant): + _cprint(f" Invalid response number. Use 1-{len(assistant)}.") + return + else: + idx = len(assistant) - 1 + while idx >= 0 and not _assistant_copy_text(assistant[idx].get("content")): + idx -= 1 + if idx < 0: + _cprint(" Nothing to copy in assistant responses yet.") + return + + text = _assistant_copy_text(assistant[idx].get("content")) + if not text: + _cprint(" Nothing to copy in that assistant response.") + return + + try: + self._write_osc52_clipboard(text) + _cprint(f" Copied assistant response #{idx + 1} to clipboard") + except Exception as e: + _cprint(f" Clipboard copy failed: {e}") + def _handle_image_command(self, cmd_original: str): """Handle /image — attach a local image file for the next prompt.""" raw_args = (cmd_original.split(None, 1)[1].strip() if " " in cmd_original else "") @@ -3671,7 +3775,7 @@ class HermesCLI: skin = get_active_skin() separator_color = skin.get_color("banner_dim", "#B8860B") accent_color = skin.get_color("ui_accent", "#FFBF00") - label_color = skin.get_color("ui_label", "#4dd0e1") + label_color = skin.get_color("ui_label", "#DAA520") except Exception: separator_color, accent_color, label_color = "#B8860B", "#FFBF00", "cyan" toolsets_info = "" @@ -5553,6 +5657,8 @@ class HermesCLI: self._show_usage() elif canonical == "insights": self._show_insights(cmd_original) + elif canonical == "copy": + self._handle_copy_command(cmd_original) elif canonical == "debug": self._handle_debug_command() elif canonical == "paste": @@ -5596,6 +5702,8 @@ class HermesCLI: self._handle_snapshot_command(cmd_original) elif canonical == "stop": self._handle_stop_command() + elif canonical == "agents": + self._handle_agents_command() elif canonical == "background": self._handle_background_command(cmd_original) elif canonical == "btw": diff --git a/docs/plans/2026-04-01-ink-gateway-tui-migration-plan.md b/docs/plans/2026-04-01-ink-gateway-tui-migration-plan.md new file mode 100644 index 0000000000..0210a878cb --- /dev/null +++ b/docs/plans/2026-04-01-ink-gateway-tui-migration-plan.md @@ -0,0 +1,108 @@ +# Ink Gateway TUI Migration — Post-mortem + +Planned: 2026-04-01 · Delivered: 2026-04 · Status: shipped, classic (prompt_toolkit) CLI still present + +## What Shipped + +Three layers, same repo, Python runtime unchanged. + +``` +ui-tui (Node/TS) ──stdio JSON-RPC──▶ tui_gateway (Py) ──▶ AIAgent (run_agent.py) +``` + +### Backend — `tui_gateway/` + +``` +tui_gateway/ +├── entry.py # subprocess entrypoint, stdio read/write loop +├── server.py # everything: sessions dict, @method handlers, _emit +├── render.py # stream renderer, diff rendering, message rendering +├── slash_worker.py # subprocess that runs hermes_cli slash commands +└── __init__.py +``` + +`server.py` owns the full runtime-control surface: session store (`_sessions: dict[str, dict]`), method registry (`@method("…")` decorator), event emitter (`_emit`), agent lifecycle (`_make_agent`, `_init_session`, `_wire_callbacks`), approval/sudo/clarify round-trips, and JSON-RPC dispatch. + +Protocol methods (`@method(...)` in `server.py`): + +- session: `session.{create, resume, list, close, interrupt, usage, history, compress, branch, title, save, undo}` +- prompt: `prompt.{submit, background, btw}` +- tools: `tools.{list, show, configure}` +- slash: `slash.exec`, `command.{dispatch, resolve}`, `commands.catalog`, `complete.{path, slash}` +- approvals: `approval.respond`, `sudo.respond`, `clarify.respond`, `secret.respond` +- config/state: `config.{get, set, show}`, `model.options`, `reload.mcp` +- ops: `shell.exec`, `cli.exec`, `terminal.resize`, `input.detect_drop`, `clipboard.paste`, `paste.collapse`, `image.attach`, `process.stop` +- misc: `agents.list`, `skills.manage`, `plugins.list`, `cron.manage`, `insights.get`, `rollback.{list, diff, restore}`, `browser.manage` + +Protocol events (`_emit(…)` → handled in `ui-tui/src/app/createGatewayEventHandler.ts`): + +- lifecycle: `gateway.{ready, stderr}`, `session.info`, `skin.changed` +- stream: `message.{start, delta, complete}`, `thinking.delta`, `reasoning.{delta, available}`, `status.update` +- tools: `tool.{start, progress, complete, generating}`, `subagent.{start, thinking, tool, progress, complete}` +- interactive: `approval.request`, `sudo.request`, `clarify.request`, `secret.request` +- async: `background.complete`, `btw.complete`, `error` + +### Frontend — `ui-tui/src/` + +``` +src/ +├── entry.tsx # node bootstrap: bootBanner → spawn python → dynamic-import Ink → render() +├── app.tsx # wraps +├── bootBanner.ts # raw-ANSI banner to stdout in ~2ms, pre-React +├── gatewayClient.ts # JSON-RPC client over child_process stdio +├── gatewayTypes.ts # typed RPC responses + GatewayEvent union +├── theme.ts # DEFAULT_THEME + fromSkin +│ +├── app/ # hooks + stores — the orchestration layer +│ ├── uiStore.ts # nanostore: sid, info, busy, usage, theme, status… +│ ├── turnStore.ts # nanostore: per-turn activity / reasoning / tools +│ ├── turnController.ts # imperative singleton for stream-time operations +│ ├── overlayStore.ts # nanostore: modal/overlay state +│ ├── useMainApp.ts # top-level composition hook +│ ├── useSessionLifecycle.ts # session.create/resume/close/reset +│ ├── useSubmission.ts # shell/slash/prompt dispatch + interpolation +│ ├── useConfigSync.ts # config.get + mtime poll +│ ├── useComposerState.ts # input buffer, paste snippets, editor mode +│ ├── useInputHandlers.ts # key bindings +│ ├── createGatewayEventHandler.ts # event-stream dispatcher +│ ├── createSlashHandler.ts # slash command router (registry + python fallback) +│ └── slash/commands/ # core.ts, ops.ts, session.ts — TS-owned slash commands +│ +├── components/ # AppLayout, AppChrome, AppOverlays, MessageLine, Thinking, Markdown, pickers, prompts, Banner, SessionPanel +├── config/ # env, limits, timing constants +├── content/ # charms, faces, fortunes, hotkeys, placeholders, verbs +├── domain/ # details, messages, paths, roles, slash, usage, viewport +├── protocol/ # interpolation, paste regex +├── hooks/ # useCompletion, useInputHistory, useQueue, useVirtualHistory +└── lib/ # history, messages, osc52, rpc, text +``` + +### CLI entry points — `hermes_cli/main.py` + +- `hermes --tui` → `node dist/entry.js` (auto-builds when `.ts`/`.tsx` newer than `dist/entry.js`) +- `hermes --tui --dev` → `tsx src/entry.tsx` (skip build) +- `HERMES_TUI_DIR=…` → external prebuilt dist (nix, distro packaging) + +## Diverged From Original Plan + +| Plan | Reality | Why | +|---|---|---| +| `tui_gateway/{controller,session_state,events,protocol}.py` | all collapsed into `server.py` | no second consumer ever emerged, keeping one file cheaper than four | +| `ui-tui/src/main.tsx` | split into `entry.tsx` (bootstrap) + `app.tsx` (shell) | boot banner + early python spawn wanted a pre-React moment | +| `ui-tui/src/state/store.ts` | three nanostores (`uiStore`, `turnStore`, `overlayStore`) | separate lifetimes: ui persists, turn resets per reply, overlay is modal | +| `approval.requested` / `sudo.requested` / `clarify.requested` | `*.request` (no `-ed`) | cosmetic | +| `session.cancel` | dropped | `session.interrupt` covers it | +| `HERMES_EXPERIMENTAL_TUI=1`, `display.experimental_tui: true`, `/tui on/off/status` | none shipped | `--tui` went from opt-in to first-class without an experimental phase | + +## Post-migration Additions (not in original plan) + +- **Async `session.create`** — returns sid in ~1ms, agent builds on a background thread, `session.info` broadcasts when ready; `_wait_agent()` gates every agent-touching handler via `_sess` +- **`bootBanner`** — raw-ANSI logo painted to stdout at T≈2ms, before Ink loads; `` wipes it seamlessly when React mounts +- **Selection uniform bg** — `theme.color.selectionBg` wired via `useSelection().setSelectionBgColor`; replaces SGR-inverse per-cell swap that fragmented over amber/gold fg +- **Slash command registry** — TS-owned commands in `app/slash/commands/{core,ops,session}.ts`, everything else falls through to `slash.exec` (python worker) +- **Turn store + controller split** — imperative singleton (`turnController`) holds refs/timers, nanostore (`turnStore`) holds render-visible state + +## What's Still Open + +- **Classic CLI not deleted.** `cli.py` still has ~80 `prompt_toolkit` references; classic REPL is still the default when `--tui` is absent. The original plan's "Cut 4 · prompt_toolkit removal later" hasn't happened. +- **No config-file opt-in.** `HERMES_EXPERIMENTAL_TUI` and `display.experimental_tui` were never built; only the CLI flag exists. Fine for now — if we want "default to TUI", a single line in `main.py` flips it. diff --git a/docs/skins/example-skin.yaml b/docs/skins/example-skin.yaml index b81ae00f8d..fb0be89da6 100644 --- a/docs/skins/example-skin.yaml +++ b/docs/skins/example-skin.yaml @@ -6,6 +6,11 @@ # All fields are optional — missing values inherit from the default skin. # Activate with: /skin or display.skin: in config.yaml # +# Keys are marked: +# (both) — applies to both the classic CLI and the TUI +# (classic) — classic CLI only (see hermes --tui in user-guide/tui.md) +# (tui) — TUI only +# # See hermes_cli/skin_engine.py for the full schema reference. # ============================================================================ @@ -14,43 +19,47 @@ name: example description: An example custom skin — copy and modify this template # ── Colors ────────────────────────────────────────────────────────────────── -# Hex color values for Rich markup. These control the CLI's visual palette. +# Hex color values. These control the visual palette. colors: - # Banner panel (the startup welcome box) + # Banner panel (the startup welcome box) — (both) banner_border: "#CD7F32" # Panel border banner_title: "#FFD700" # Panel title text banner_accent: "#FFBF00" # Section headers (Available Tools, Skills, etc.) banner_dim: "#B8860B" # Dim/muted text (separators, model info) banner_text: "#FFF8DC" # Body text (tool names, skill names) - # UI elements - ui_accent: "#FFBF00" # General accent color + # UI elements — (both) + ui_accent: "#FFBF00" # General accent (falls back to banner_accent) ui_label: "#4dd0e1" # Labels ui_ok: "#4caf50" # Success indicators ui_error: "#ef5350" # Error indicators ui_warn: "#ffa726" # Warning indicators # Input area - prompt: "#FFF8DC" # Prompt text color - input_rule: "#CD7F32" # Horizontal rule around input + prompt: "#FFF8DC" # Prompt text / `❯` glyph color (both) + input_rule: "#CD7F32" # Horizontal rule above input (classic) - # Response box - response_border: "#FFD700" # Response box border (ANSI color) + # Response box — (classic) + response_border: "#FFD700" # Response box border - # Session display - session_label: "#DAA520" # Session label - session_border: "#8B8682" # Session ID dim color + # Session display — (both) + session_label: "#DAA520" # "Session: " label + session_border: "#8B8682" # Session ID text - # TUI surfaces - status_bar_bg: "#1a1a2e" # Status / usage bar background - voice_status_bg: "#1a1a2e" # Voice-mode badge background - completion_menu_bg: "#1a1a2e" # Completion list background - completion_menu_current_bg: "#333355" # Active completion row background - completion_menu_meta_bg: "#1a1a2e" # Completion meta column background - completion_menu_meta_current_bg: "#333355" # Active completion meta background + # TUI / CLI surfaces — (classic: status bar, voice badge, completion meta) + status_bar_bg: "#1a1a2e" # Status / usage bar background (classic) + voice_status_bg: "#1a1a2e" # Voice-mode badge background (classic) + completion_menu_bg: "#1a1a2e" # Completion list background (both) + completion_menu_current_bg: "#333355" # Active completion row background (both) + completion_menu_meta_bg: "#1a1a2e" # Completion meta column bg (classic) + completion_menu_meta_current_bg: "#333355" # Active meta bg (classic) + + # Drag-to-select background — (tui) + selection_bg: "#3a3a55" # Uniform selection highlight in the TUI # ── Spinner ───────────────────────────────────────────────────────────────── -# Customize the animated spinner shown during API calls and tool execution. +# (classic) — the TUI uses its own animated indicators; spinner config here +# is only read by the classic prompt_toolkit CLI. spinner: # Faces shown while waiting for the API response waiting_faces: @@ -78,17 +87,17 @@ spinner: # - ["⟪▲", "▲⟫"] # ── Branding ──────────────────────────────────────────────────────────────── -# Text strings used throughout the CLI interface. +# Text strings used throughout the interface. branding: - agent_name: "Hermes Agent" # Banner title, about display - welcome: "Welcome! Type your message or /help for commands." - goodbye: "Goodbye! ⚕" # Exit message - response_label: " ⚕ Hermes " # Response box header label - prompt_symbol: "❯ " # Input prompt symbol - help_header: "(^_^)? Available Commands" # /help header text + agent_name: "Hermes Agent" # (both) Banner title, about display + welcome: "Welcome! Type your message or /help for commands." # (both) + goodbye: "Goodbye! ⚕" # (both) Exit message + response_label: " ⚕ Hermes " # (classic) Response box header label + prompt_symbol: "❯ " # (both) Input prompt glyph + help_header: "(^_^)? Available Commands" # (both) /help overlay title # ── Tool Output ───────────────────────────────────────────────────────────── -# Character used as the prefix for tool output lines. +# Character used as the prefix for tool output lines. (both) # Default is "┊" (thin dotted vertical line). Some alternatives: # "╎" (light triple dash vertical) # "▏" (left one-eighth block) diff --git a/flake.lock b/flake.lock index 78ceba92d7..305b79526e 100644 --- a/flake.lock +++ b/flake.lock @@ -36,6 +36,26 @@ "type": "github" } }, + "npm-lockfile-fix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1775903712, + "narHash": "sha256-2GV79U6iVH4gKAPWYrxUReB0S41ty/Y3dBLquU8AlaA=", + "owner": "jeslie0", + "repo": "npm-lockfile-fix", + "rev": "c6093acb0c0548e0f9b8b3d82918823721930fe8", + "type": "github" + }, + "original": { + "owner": "jeslie0", + "repo": "npm-lockfile-fix", + "type": "github" + } + }, "pyproject-build-systems": { "inputs": { "nixpkgs": [ @@ -124,6 +144,7 @@ "inputs": { "flake-parts": "flake-parts", "nixpkgs": "nixpkgs", + "npm-lockfile-fix": "npm-lockfile-fix", "pyproject-build-systems": "pyproject-build-systems", "pyproject-nix": "pyproject-nix_2", "uv2nix": "uv2nix_2" diff --git a/flake.nix b/flake.nix index 919fa434dc..fcb5eaa619 100644 --- a/flake.nix +++ b/flake.nix @@ -19,11 +19,20 @@ url = "github:pyproject-nix/build-system-pkgs"; inputs.nixpkgs.follows = "nixpkgs"; }; + npm-lockfile-fix = { + url = "github:jeslie0/npm-lockfile-fix"; + inputs.nixpkgs.follows = "nixpkgs"; + }; }; - outputs = inputs: + outputs = + inputs: inputs.flake-parts.lib.mkFlake { inherit inputs; } { - systems = [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ]; + systems = [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; imports = [ ./nix/packages.nix diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 7c0376776b..e6dedfda49 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -1579,7 +1579,20 @@ class BasePlatformAdapter(ABC): # session lifecycle and its cleanup races with the running task # (see PR #4926). cmd = event.get_command() - if cmd in ("approve", "deny", "status", "stop", "new", "reset", "background", "restart", "queue", "q"): + if cmd in ( + "approve", + "deny", + "status", + "agents", + "tasks", + "stop", + "new", + "reset", + "background", + "restart", + "queue", + "q", + ): logger.debug( "[%s] Command '/%s' bypassing active-session guard for %s", self.name, cmd, session_key, diff --git a/gateway/run.py b/gateway/run.py index bef967f8ac..ea747321f9 100644 --- a/gateway/run.py +++ b/gateway/run.py @@ -3029,6 +3029,10 @@ class GatewayRunner: return await self._handle_approve_command(event) return await self._handle_deny_command(event) + # /agents (/tasks alias) should be query-only and never interrupt. + if _cmd_def_inner and _cmd_def_inner.name == "agents": + return await self._handle_agents_command(event) + # /background must bypass the running-agent guard — it starts a # parallel task and must never interrupt the active conversation. if _cmd_def_inner and _cmd_def_inner.name == "background": @@ -3136,6 +3140,9 @@ class GatewayRunner: if canonical == "status": return await self._handle_status_command(event) + if canonical == "agents": + return await self._handle_agents_command(event) + if canonical == "restart": return await self._handle_restart_command(event) @@ -4591,6 +4598,96 @@ class GatewayRunner: ]) return "\n".join(lines) + + async def _handle_agents_command(self, event: MessageEvent) -> str: + """Handle /agents command - list active agents and running tasks.""" + from tools.process_registry import format_uptime_short, process_registry + + now = time.time() + current_session_key = self._session_key_for_source(event.source) + + running_agents: dict = getattr(self, "_running_agents", {}) or {} + running_started: dict = getattr(self, "_running_agents_ts", {}) or {} + + agent_rows: list[dict] = [] + for session_key, agent in running_agents.items(): + started = float(running_started.get(session_key, now)) + elapsed = max(0, int(now - started)) + is_pending = agent is _AGENT_PENDING_SENTINEL + agent_rows.append( + { + "session_key": session_key, + "elapsed": elapsed, + "state": "starting" if is_pending else "running", + "session_id": "" if is_pending else str(getattr(agent, "session_id", "") or ""), + "model": "" if is_pending else str(getattr(agent, "model", "") or ""), + } + ) + + agent_rows.sort(key=lambda row: row["elapsed"], reverse=True) + + running_processes: list[dict] = [] + try: + running_processes = [ + p for p in process_registry.list_sessions() + if p.get("status") == "running" + ] + except Exception: + running_processes = [] + + background_tasks = [ + t for t in (getattr(self, "_background_tasks", set()) or set()) + if hasattr(t, "done") and not t.done() + ] + + lines = [ + "🤖 **Active Agents & Tasks**", + "", + f"**Active agents:** {len(agent_rows)}", + ] + + if agent_rows: + for idx, row in enumerate(agent_rows[:12], 1): + current = " · this chat" if row["session_key"] == current_session_key else "" + sid = f" · `{row['session_id']}`" if row["session_id"] else "" + model = f" · `{row['model']}`" if row["model"] else "" + lines.append( + f"{idx}. `{row['session_key']}` · {row['state']} · " + f"{format_uptime_short(row['elapsed'])}{sid}{model}{current}" + ) + if len(agent_rows) > 12: + lines.append(f"... and {len(agent_rows) - 12} more") + + lines.extend( + [ + "", + f"**Running background processes:** {len(running_processes)}", + ] + ) + if running_processes: + for proc in running_processes[:12]: + cmd = " ".join(str(proc.get("command", "")).split()) + if len(cmd) > 90: + cmd = cmd[:87] + "..." + lines.append( + f"- `{proc.get('session_id', '?')}` · " + f"{format_uptime_short(int(proc.get('uptime_seconds', 0)))} · `{cmd}`" + ) + if len(running_processes) > 12: + lines.append(f"... and {len(running_processes) - 12} more") + + lines.extend( + [ + "", + f"**Gateway async jobs:** {len(background_tasks)}", + ] + ) + + if not agent_rows and not running_processes and not background_tasks: + lines.append("") + lines.append("No active agents or running tasks.") + + return "\n".join(lines) async def _handle_stop_command(self, event: MessageEvent) -> str: """Handle /stop command - interrupt a running agent. diff --git a/hermes_cli/clipboard.py b/hermes_cli/clipboard.py index fd81ed4c8b..facc8f3c50 100644 --- a/hermes_cli/clipboard.py +++ b/hermes_cli/clipboard.py @@ -7,8 +7,8 @@ CLI tools that ship with the platform (or are commonly installed). Platform support: macOS — osascript (always available), pngpaste (if installed) - Windows — PowerShell via .NET System.Windows.Forms.Clipboard - WSL2 — powershell.exe via .NET System.Windows.Forms.Clipboard + Windows — PowerShell via WinForms, Get-Clipboard, file-drop fallback + WSL2 — powershell.exe via WinForms, Get-Clipboard, file-drop fallback Linux — wl-paste (Wayland), xclip (X11) """ @@ -46,10 +46,11 @@ def has_clipboard_image() -> bool: return _macos_has_image() if sys.platform == "win32": return _windows_has_image() - if _is_wsl(): - return _wsl_has_image() - if os.environ.get("WAYLAND_DISPLAY"): - return _wayland_has_image() + # Match _linux_save fallthrough order: WSL → Wayland → X11 + if _is_wsl() and _wsl_has_image(): + return True + if os.environ.get("WAYLAND_DISPLAY") and _wayland_has_image(): + return True return _xclip_has_image() @@ -135,6 +136,114 @@ _PS_EXTRACT_IMAGE = ( "[System.Convert]::ToBase64String($ms.ToArray())" ) +_PS_CHECK_IMAGE_GET_CLIPBOARD = ( + "try { " + "$img = Get-Clipboard -Format Image -ErrorAction Stop;" + "if ($null -ne $img) { 'True' } else { 'False' }" + "} catch { 'False' }" +) + +_PS_EXTRACT_IMAGE_GET_CLIPBOARD = ( + "try { " + "Add-Type -AssemblyName System.Drawing;" + "Add-Type -AssemblyName PresentationCore;" + "Add-Type -AssemblyName WindowsBase;" + "$img = Get-Clipboard -Format Image -ErrorAction Stop;" + "if ($null -eq $img) { exit 1 }" + "$ms = New-Object System.IO.MemoryStream;" + "if ($img -is [System.Drawing.Image]) {" + "$img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)" + "} elseif ($img -is [System.Windows.Media.Imaging.BitmapSource]) {" + "$enc = New-Object System.Windows.Media.Imaging.PngBitmapEncoder;" + "$enc.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($img));" + "$enc.Save($ms)" + "} else { exit 2 }" + "[System.Convert]::ToBase64String($ms.ToArray())" + "} catch { exit 1 }" +) + +_FILEDROP_IMAGE_EXTS = "'.png','.jpg','.jpeg','.gif','.webp','.bmp','.tiff','.tif'" + +_PS_CHECK_FILEDROP_IMAGE = ( + "try { " + "$files = Get-Clipboard -Format FileDropList -ErrorAction Stop;" + f"$exts = @({_FILEDROP_IMAGE_EXTS});" + "$hit = $files | Where-Object { $exts -contains ([System.IO.Path]::GetExtension($_).ToLowerInvariant()) } | Select-Object -First 1;" + "if ($null -ne $hit) { 'True' } else { 'False' }" + "} catch { 'False' }" +) + +_PS_EXTRACT_FILEDROP_IMAGE = ( + "try { " + "$files = Get-Clipboard -Format FileDropList -ErrorAction Stop;" + f"$exts = @({_FILEDROP_IMAGE_EXTS});" + "$hit = $files | Where-Object { $exts -contains ([System.IO.Path]::GetExtension($_).ToLowerInvariant()) } | Select-Object -First 1;" + "if ($null -eq $hit) { exit 1 }" + "[System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($hit))" + "} catch { exit 1 }" +) + +_POWERSHELL_HAS_IMAGE_SCRIPTS = ( + _PS_CHECK_IMAGE, + _PS_CHECK_IMAGE_GET_CLIPBOARD, + _PS_CHECK_FILEDROP_IMAGE, +) + +_POWERSHELL_EXTRACT_IMAGE_SCRIPTS = ( + _PS_EXTRACT_IMAGE, + _PS_EXTRACT_IMAGE_GET_CLIPBOARD, + _PS_EXTRACT_FILEDROP_IMAGE, +) + + +def _run_powershell(exe: str, script: str, timeout: int) -> subprocess.CompletedProcess: + return subprocess.run( + [exe, "-NoProfile", "-NonInteractive", "-Command", script], + capture_output=True, text=True, timeout=timeout, + ) + + +def _write_base64_image(dest: Path, b64_data: str) -> bool: + image_bytes = base64.b64decode(b64_data, validate=True) + dest.write_bytes(image_bytes) + return dest.exists() and dest.stat().st_size > 0 + + +def _powershell_has_image(exe: str, *, timeout: int, label: str) -> bool: + for script in _POWERSHELL_HAS_IMAGE_SCRIPTS: + try: + r = _run_powershell(exe, script, timeout=timeout) + if r.returncode == 0 and "True" in r.stdout: + return True + except FileNotFoundError: + logger.debug("%s not found — clipboard unavailable", exe) + return False + except Exception as e: + logger.debug("%s clipboard image check failed: %s", label, e) + return False + + +def _powershell_save_image(exe: str, dest: Path, *, timeout: int, label: str) -> bool: + for script in _POWERSHELL_EXTRACT_IMAGE_SCRIPTS: + try: + r = _run_powershell(exe, script, timeout=timeout) + if r.returncode != 0: + continue + + b64_data = r.stdout.strip() + if not b64_data: + continue + + if _write_base64_image(dest, b64_data): + return True + except FileNotFoundError: + logger.debug("%s not found — clipboard unavailable", exe) + return False + except Exception as e: + logger.debug("%s clipboard image extraction failed: %s", label, e) + dest.unlink(missing_ok=True) + return False + # ── Native Windows ──────────────────────────────────────────────────────── @@ -175,15 +284,7 @@ def _windows_has_image() -> bool: ps = _get_ps_exe() if ps is None: return False - try: - r = subprocess.run( - [ps, "-NoProfile", "-NonInteractive", "-Command", _PS_CHECK_IMAGE], - capture_output=True, text=True, timeout=5, - ) - return r.returncode == 0 and "True" in r.stdout - except Exception as e: - logger.debug("Windows clipboard image check failed: %s", e) - return False + return _powershell_has_image(ps, timeout=5, label="Windows") def _windows_save(dest: Path) -> bool: @@ -192,26 +293,7 @@ def _windows_save(dest: Path) -> bool: if ps is None: logger.debug("No PowerShell found — Windows clipboard image paste unavailable") return False - try: - r = subprocess.run( - [ps, "-NoProfile", "-NonInteractive", "-Command", _PS_EXTRACT_IMAGE], - capture_output=True, text=True, timeout=15, - ) - if r.returncode != 0: - return False - - b64_data = r.stdout.strip() - if not b64_data: - return False - - png_bytes = base64.b64decode(b64_data) - dest.write_bytes(png_bytes) - return dest.exists() and dest.stat().st_size > 0 - - except Exception as e: - logger.debug("Windows clipboard image extraction failed: %s", e) - dest.unlink(missing_ok=True) - return False + return _powershell_save_image(ps, dest, timeout=15, label="Windows") # ── Linux ──────────────────────────────────────────────────────────────── @@ -235,45 +317,12 @@ def _linux_save(dest: Path) -> bool: def _wsl_has_image() -> bool: """Check if Windows clipboard has an image (via powershell.exe).""" - try: - r = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", - _PS_CHECK_IMAGE], - capture_output=True, text=True, timeout=8, - ) - return r.returncode == 0 and "True" in r.stdout - except FileNotFoundError: - logger.debug("powershell.exe not found — WSL clipboard unavailable") - except Exception as e: - logger.debug("WSL clipboard check failed: %s", e) - return False + return _powershell_has_image("powershell.exe", timeout=8, label="WSL") def _wsl_save(dest: Path) -> bool: """Extract clipboard image via powershell.exe → base64 → decode to PNG.""" - try: - r = subprocess.run( - ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", - _PS_EXTRACT_IMAGE], - capture_output=True, text=True, timeout=15, - ) - if r.returncode != 0: - return False - - b64_data = r.stdout.strip() - if not b64_data: - return False - - png_bytes = base64.b64decode(b64_data) - dest.write_bytes(png_bytes) - return dest.exists() and dest.stat().st_size > 0 - - except FileNotFoundError: - logger.debug("powershell.exe not found — WSL clipboard unavailable") - except Exception as e: - logger.debug("WSL clipboard extraction failed: %s", e) - dest.unlink(missing_ok=True) - return False + return _powershell_save_image("powershell.exe", dest, timeout=15, label="WSL") # ── Wayland (wl-paste) ────────────────────────────────────────────────── diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py index 09ecfca54e..2c6cf75004 100644 --- a/hermes_cli/commands.py +++ b/hermes_cli/commands.py @@ -87,6 +87,8 @@ COMMAND_REGISTRY: list[CommandDef] = [ aliases=("bg",), args_hint=""), CommandDef("btw", "Ephemeral side question using session context (no tools, not persisted)", "Session", args_hint=""), + CommandDef("agents", "Show active agents and running tasks", "Session", + aliases=("tasks",)), CommandDef("queue", "Queue a prompt for the next turn (doesn't interrupt)", "Session", aliases=("q",), args_hint=""), CommandDef("status", "Show session info", "Session"), @@ -99,7 +101,7 @@ COMMAND_REGISTRY: list[CommandDef] = [ # Configuration CommandDef("config", "Show current configuration", "Configuration", cli_only=True), - CommandDef("model", "Switch model for this session", "Configuration", args_hint="[model] [--global]"), + CommandDef("model", "Switch model for this session", "Configuration", args_hint="[model] [--provider name] [--global]"), CommandDef("provider", "Show available providers and current provider", "Configuration"), CommandDef("gquota", "Show Google Gemini Code Assist quota usage", "Info"), @@ -120,7 +122,7 @@ COMMAND_REGISTRY: list[CommandDef] = [ args_hint="[normal|fast|status]", subcommands=("normal", "fast", "status", "on", "off")), CommandDef("skin", "Show or change the display skin/theme", "Configuration", - cli_only=True, args_hint="[name]"), + args_hint="[name]"), CommandDef("voice", "Toggle voice mode", "Configuration", args_hint="[on|off|tts|status]", subcommands=("on", "off", "tts", "status")), @@ -155,7 +157,9 @@ COMMAND_REGISTRY: list[CommandDef] = [ args_hint="[days]"), CommandDef("platforms", "Show gateway/messaging platform status", "Info", cli_only=True, aliases=("gateway",)), - CommandDef("paste", "Check clipboard for an image and attach it", "Info", + CommandDef("copy", "Copy the last assistant response to clipboard", "Info", + cli_only=True, args_hint="[number]"), + CommandDef("paste", "Attach clipboard image from your clipboard", "Info", cli_only=True), CommandDef("image", "Attach a local image file for your next prompt", "Info", cli_only=True, args_hint=""), @@ -1044,6 +1048,51 @@ class SlashCommandCompleter(Completer): display_meta=f"{fp} {meta}" if meta else fp, ) + @staticmethod + def _skin_completions(sub_text: str, sub_lower: str): + """Yield completions for /skin from available skins.""" + try: + from hermes_cli.skin_engine import list_skins + for s in list_skins(): + name = s["name"] + if name.startswith(sub_lower) and name != sub_lower: + yield Completion( + name, + start_position=-len(sub_text), + display=name, + display_meta=s.get("description", "") or s.get("source", ""), + ) + except Exception: + pass + + @staticmethod + def _personality_completions(sub_text: str, sub_lower: str): + """Yield completions for /personality from configured personalities.""" + try: + from hermes_cli.config import load_config + personalities = load_config().get("agent", {}).get("personalities", {}) + if "none".startswith(sub_lower) and "none" != sub_lower: + yield Completion( + "none", + start_position=-len(sub_text), + display="none", + display_meta="clear personality overlay", + ) + for name, prompt in personalities.items(): + if name.startswith(sub_lower) and name != sub_lower: + if isinstance(prompt, dict): + meta = prompt.get("description") or prompt.get("system_prompt", "")[:50] + else: + meta = str(prompt)[:50] + yield Completion( + name, + start_position=-len(sub_text), + display=name, + display_meta=meta, + ) + except Exception: + pass + def _model_completions(self, sub_text: str, sub_lower: str): """Yield completions for /model from config aliases + built-in aliases.""" seen = set() @@ -1098,10 +1147,17 @@ class SlashCommandCompleter(Completer): sub_text = parts[1] if len(parts) > 1 else "" sub_lower = sub_text.lower() - # Dynamic model alias completions for /model - if " " not in sub_text and base_cmd == "/model": - yield from self._model_completions(sub_text, sub_lower) - return + # Dynamic completions for commands with runtime lists + if " " not in sub_text: + if base_cmd == "/model": + yield from self._model_completions(sub_text, sub_lower) + return + if base_cmd == "/skin": + yield from self._skin_completions(sub_text, sub_lower) + return + if base_cmd == "/personality": + yield from self._personality_completions(sub_text, sub_lower) + return # Static subcommand completions if " " not in sub_text and base_cmd in SUBCOMMANDS and self._command_allowed(base_cmd): diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 10597db15d..2fb27dd2da 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -45,11 +45,13 @@ Usage: import argparse import os +import shutil import subprocess import sys from pathlib import Path from typing import Optional + def _require_tty(command_name: str) -> None: """Exit with a clear error if stdin is not a terminal. @@ -71,6 +73,7 @@ def _require_tty(command_name: str) -> None: PROJECT_ROOT = Path(__file__).parent.parent.resolve() sys.path.insert(0, str(PROJECT_ROOT)) + # --------------------------------------------------------------------------- # Profile override — MUST happen before any hermes module import. # @@ -101,6 +104,7 @@ def _apply_profile_override() -> None: if profile_name is None: try: from hermes_constants import get_default_hermes_root + active_path = get_default_hermes_root() / "active_profile" if active_path.exists(): name = active_path.read_text().strip() @@ -114,13 +118,17 @@ def _apply_profile_override() -> None: if profile_name is not None: try: from hermes_cli.profiles import resolve_profile_env + hermes_home = resolve_profile_env(profile_name) except (ValueError, FileNotFoundError) as exc: print(f"Error: {exc}", file=sys.stderr) sys.exit(1) except Exception as exc: # A bug in profiles.py must NEVER prevent hermes from starting - print(f"Warning: profile override failed ({exc}), using default", file=sys.stderr) + print( + f"Warning: profile override failed ({exc}), using default", + file=sys.stderr, + ) return os.environ["HERMES_HOME"] = hermes_home # Strip the flag from argv so argparse doesn't choke @@ -128,25 +136,28 @@ def _apply_profile_override() -> None: for i, arg in enumerate(argv): if arg in ("--profile", "-p"): start = i + 1 # +1 because argv is sys.argv[1:] - sys.argv = sys.argv[:start] + sys.argv[start + consume:] + sys.argv = sys.argv[:start] + sys.argv[start + consume :] break elif arg.startswith("--profile="): start = i + 1 - sys.argv = sys.argv[:start] + sys.argv[start + 1:] + sys.argv = sys.argv[:start] + sys.argv[start + 1 :] break + _apply_profile_override() # Load .env from ~/.hermes/.env first, then project root as dev fallback. # User-managed env files should override stale shell exports on restart. from hermes_cli.config import get_hermes_home from hermes_cli.env_loader import load_hermes_dotenv -load_hermes_dotenv(project_env=PROJECT_ROOT / '.env') + +load_hermes_dotenv(project_env=PROJECT_ROOT / ".env") # Initialize centralized file logging early — all `hermes` subcommands # (chat, setup, gateway, config, etc.) write to agent.log + errors.log. try: from hermes_logging import setup_logging as _setup_logging + _setup_logging(mode="cli") except Exception: pass # best-effort — don't crash the CLI if logging setup fails @@ -155,6 +166,7 @@ except Exception: try: from hermes_cli.config import load_config as _load_config_early from hermes_constants import apply_ipv4_preference as _apply_ipv4 + _early_cfg = _load_config_early() _net = _early_cfg.get("network", {}) if isinstance(_net, dict) and _net.get("force_ipv4"): @@ -201,6 +213,7 @@ def _has_any_provider_configured() -> bool: # tool credentials (Claude Code, Codex CLI) that shouldn't silently skip # the setup wizard on a fresh install. from hermes_cli.config import DEFAULT_CONFIG + _DEFAULT_MODEL = DEFAULT_CONFIG.get("model", "") cfg = load_config() model_cfg = cfg.get("model") @@ -218,7 +231,13 @@ def _has_any_provider_configured() -> bool: from hermes_cli.auth import PROVIDER_REGISTRY # Collect all provider env vars - provider_env_vars = {"OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "OPENAI_BASE_URL"} + provider_env_vars = { + "OPENROUTER_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "ANTHROPIC_TOKEN", + "OPENAI_BASE_URL", + } for pconfig in PROVIDER_REGISTRY.values(): if pconfig.auth_type == "api_key": provider_env_vars.update(pconfig.api_key_env_vars) @@ -256,6 +275,7 @@ def _has_any_provider_configured() -> bool: if auth_file.exists(): try: import json + auth = json.loads(auth_file.read_text()) active = auth.get("active_provider") if active: @@ -265,7 +285,6 @@ def _has_any_provider_configured() -> bool: except Exception: pass - # Check config.yaml — if model is a dict with an explicit provider set, # the user has gone through setup (fresh installs have model as a plain # string). Also covers custom endpoints that store api_key/base_url in @@ -282,9 +301,15 @@ def _has_any_provider_configured() -> bool: # being installed doesn't mean the user wants Hermes to use their tokens. if _has_hermes_config: try: - from agent.anthropic_adapter import read_claude_code_credentials, is_claude_code_token_valid + from agent.anthropic_adapter import ( + read_claude_code_credentials, + is_claude_code_token_valid, + ) + creds = read_claude_code_credentials() - if creds and (is_claude_code_token_valid(creds) or creds.get("refreshToken")): + if creds and ( + is_claude_code_token_valid(creds) or creds.get("refreshToken") + ): return True except Exception: pass @@ -346,10 +371,10 @@ def _session_browse_picker(sessions: list) -> Optional[str]: if curses.has_colors(): curses.start_color() curses.use_default_colors() - curses.init_pair(1, curses.COLOR_GREEN, -1) # selected + curses.init_pair(1, curses.COLOR_GREEN, -1) # selected curses.init_pair(2, curses.COLOR_YELLOW, -1) # header - curses.init_pair(3, curses.COLOR_CYAN, -1) # search - curses.init_pair(4, 8, -1) # dim + curses.init_pair(3, curses.COLOR_CYAN, -1) # search + curses.init_pair(4, 8, -1) # dim cursor = 0 scroll_offset = 0 @@ -390,7 +415,9 @@ def _session_browse_picker(sessions: list) -> Optional[str]: name_width = max(20, max_x - fixed_cols) col_header = f" {'Title / Preview':<{name_width}} {'Active':<10} {'Src':<5} {'ID'}" try: - dim_attr = curses.color_pair(4) if curses.has_colors() else curses.A_DIM + dim_attr = ( + curses.color_pair(4) if curses.has_colors() else curses.A_DIM + ) stdscr.addnstr(1, 0, col_header, max_x - 1, dim_attr) except curses.error: pass @@ -417,10 +444,12 @@ def _session_browse_picker(sessions: list) -> Optional[str]: elif cursor >= scroll_offset + visible_rows: scroll_offset = cursor - visible_rows + 1 - for draw_i, i in enumerate(range( - scroll_offset, - min(len(filtered), scroll_offset + visible_rows) - )): + for draw_i, i in enumerate( + range( + scroll_offset, + min(len(filtered), scroll_offset + visible_rows), + ) + ): y = draw_i + 3 if y >= max_y - 1: break @@ -446,18 +475,23 @@ def _session_browse_picker(sessions: list) -> Optional[str]: else: footer = f" 0/{len(sessions)} sessions" try: - stdscr.addnstr(footer_y, 0, footer, max_x - 1, - curses.color_pair(4) if curses.has_colors() else curses.A_DIM) + stdscr.addnstr( + footer_y, + 0, + footer, + max_x - 1, + curses.color_pair(4) if curses.has_colors() else curses.A_DIM, + ) except curses.error: pass stdscr.refresh() key = stdscr.getch() - if key in (curses.KEY_UP, ): + if key in (curses.KEY_UP,): if filtered: cursor = (cursor - 1) % len(filtered) - elif key in (curses.KEY_DOWN, ): + elif key in (curses.KEY_DOWN,): if filtered: cursor = (cursor + 1) % len(filtered) elif key in (curses.KEY_ENTER, 10, 13): @@ -483,7 +517,7 @@ def _session_browse_picker(sessions: list) -> Optional[str]: filtered = list(sessions) cursor = 0 scroll_offset = 0 - elif key == ord('q') and not search_text: + elif key == ord("q") and not search_text: return elif 32 <= key <= 126: # Printable character → add to search filter @@ -526,12 +560,13 @@ def _session_browse_picker(sessions: list) -> Optional[str]: return None -def _resolve_last_cli_session() -> Optional[str]: - """Look up the most recent CLI session ID from SQLite. Returns None if unavailable.""" +def _resolve_last_session(source: str = "cli") -> Optional[str]: + """Look up the most recent session ID for a source.""" try: from hermes_state import SessionDB + db = SessionDB() - sessions = db.search_sessions(source="cli", limit=1) + sessions = db.search_sessions(source=source, limit=1) db.close() if sessions: return sessions[0]["id"] @@ -579,8 +614,10 @@ def _exec_in_container(container_info: dict, cli_args: list): runtime = shutil.which(backend) if not runtime: - print(f"Error: {backend} not found on PATH. Cannot route to container.", - file=sys.stderr) + print( + f"Error: {backend} not found on PATH. Cannot route to container.", + file=sys.stderr, + ) sys.exit(1) # Rootful containers (NixOS systemd service) are invisible to unprivileged @@ -588,14 +625,16 @@ def _exec_in_container(container_info: dict, cli_args: list): # Probe whether the runtime can see the container; if not, try via sudo. sudo_path = None probe = _probe_container( - [runtime, "inspect", "--format", "ok", container_name], backend, + [runtime, "inspect", "--format", "ok", container_name], + backend, ) if probe.returncode != 0: sudo_path = shutil.which("sudo") if sudo_path: probe2 = _probe_container( [sudo_path, "-n", runtime, "inspect", "--format", "ok", container_name], - backend, via_sudo=True, + backend, + via_sudo=True, ) if probe2.returncode != 0: print( @@ -608,10 +647,10 @@ def _exec_in_container(container_info: dict, cli_args: list): f"\n" f"On NixOS:\n" f"\n" - f' security.sudo.extraRules = [{{\n' + f" security.sudo.extraRules = [{{\n" f' users = [ "{os.getenv("USER", "your-user")}" ];\n' f' commands = [{{ command = "{runtime}"; options = [ "NOPASSWD" ]; }}];\n' - f' }}];\n' + f" }}];\n" f"\n" f"Or run: sudo hermes {' '.join(cli_args)}", file=sys.stderr, @@ -636,7 +675,8 @@ def _exec_in_container(container_info: dict, cli_args: list): cmd_prefix = [sudo_path, "-n", runtime] if sudo_path else [runtime] exec_cmd = ( - cmd_prefix + ["exec"] + cmd_prefix + + ["exec"] + tty_flags + ["-u", exec_user] + env_flags @@ -656,6 +696,7 @@ def _resolve_session_by_name_or_id(name_or_id: str) -> Optional[str]: """ try: from hermes_state import SessionDB + db = SessionDB() # Try as exact session ID first @@ -673,9 +714,298 @@ def _resolve_session_by_name_or_id(name_or_id: str) -> Optional[str]: return None +def _print_tui_exit_summary(session_id: Optional[str]) -> None: + """Print a shell-visible epilogue after TUI exits.""" + target = session_id or _resolve_last_session(source="tui") + if not target: + return + + db = None + try: + from hermes_state import SessionDB + + db = SessionDB() + session = db.get_session(target) + if not session: + return + + title = db.get_session_title(target) + message_count = int(session.get("message_count") or 0) + input_tokens = int(session.get("input_tokens") or 0) + output_tokens = int(session.get("output_tokens") or 0) + cache_read_tokens = int(session.get("cache_read_tokens") or 0) + cache_write_tokens = int(session.get("cache_write_tokens") or 0) + reasoning_tokens = int(session.get("reasoning_tokens") or 0) + total_tokens = ( + input_tokens + + output_tokens + + cache_read_tokens + + cache_write_tokens + + reasoning_tokens + ) + except Exception: + return + finally: + if db is not None: + db.close() + + print() + print("Resume this session with:") + print(f" hermes --tui --resume {target}") + if title: + print(f' hermes --tui -c "{title}"') + print() + print(f"Session: {target}") + if title: + print(f"Title: {title}") + print(f"Messages: {message_count}") + print( + "Tokens: " + f"{total_tokens} (in {input_tokens}, out {output_tokens}, " + f"cache {cache_read_tokens + cache_write_tokens}, reasoning {reasoning_tokens})" + ) + + +def _tui_need_npm_install(root: Path) -> bool: + """True when @hermes/ink is missing or node_modules is behind package-lock.json (post-pull).""" + ink = root / "node_modules" / "@hermes" / "ink" / "package.json" + if not ink.is_file(): + return True + lock = root / "package-lock.json" + if not lock.is_file(): + return False + marker = root / "node_modules" / ".package-lock.json" + if not marker.is_file(): + return True + return lock.stat().st_mtime > marker.stat().st_mtime + + +def _find_bundled_tui(tui_dir: Path) -> Optional[Path]: + """Directory whose dist/entry.js we should run: HERMES_TUI_DIR first, else repo ui-tui.""" + env = os.environ.get("HERMES_TUI_DIR") + if env: + p = Path(env) + if (p / "dist" / "entry.js").exists() and not _tui_need_npm_install(p): + return p + if (tui_dir / "dist" / "entry.js").exists() and not _tui_need_npm_install(tui_dir): + return tui_dir + return None + + +def _tui_build_needed(tui_dir: Path) -> bool: + entry = tui_dir / "dist" / "entry.js" + if not entry.exists(): + return True + dist_m = entry.stat().st_mtime + skip = frozenset({"node_modules", "dist"}) + for dirpath, dirnames, filenames in os.walk(tui_dir, topdown=True): + dirnames[:] = [d for d in dirnames if d not in skip] + for fn in filenames: + if fn.endswith((".ts", ".tsx")): + if os.path.getmtime(os.path.join(dirpath, fn)) > dist_m: + return True + for meta in ( + "package.json", + "package-lock.json", + "tsconfig.json", + "tsconfig.build.json", + ): + mp = tui_dir / meta + if mp.exists() and mp.stat().st_mtime > dist_m: + return True + return False + + +def _hermes_ink_bundle_stale(tui_dir: Path) -> bool: + ink_root = tui_dir / "packages" / "hermes-ink" + bundle = ink_root / "dist" / "ink-bundle.js" + if not bundle.exists(): + return True + bm = bundle.stat().st_mtime + skip = frozenset({"node_modules", "dist"}) + for dirpath, dirnames, filenames in os.walk(ink_root, topdown=True): + dirnames[:] = [d for d in dirnames if d not in skip] + for fn in filenames: + if fn.endswith((".ts", ".tsx")): + if os.path.getmtime(os.path.join(dirpath, fn)) > bm: + return True + mp = ink_root / "package.json" + if mp.exists() and mp.stat().st_mtime > bm: + return True + return False + + +def _ensure_tui_node() -> None: + """Make sure `node` + `npm` are on PATH for the TUI. + + If either is missing and scripts/lib/node-bootstrap.sh is available, source + it and call `ensure_node` (fnm/nvm/proto/brew/bundled cascade). After + install, capture the resolved node binary path from the bash subprocess + and prepend its directory to os.environ["PATH"] so shutil.which finds the + new binaries in this Python process — regardless of which version manager + was used (nvm, fnm, proto, brew, or the bundled fallback). + + Idempotent no-op when node+npm are already discoverable. Set + ``HERMES_SKIP_NODE_BOOTSTRAP=1`` to disable auto-install. + """ + if shutil.which("node") and shutil.which("npm"): + return + if os.environ.get("HERMES_SKIP_NODE_BOOTSTRAP"): + return + + helper = PROJECT_ROOT / "scripts" / "lib" / "node-bootstrap.sh" + if not helper.is_file(): + return + + hermes_home = os.environ.get("HERMES_HOME") or str(Path.home() / ".hermes") + try: + # Helper writes logs to stderr; we ask bash to print `command -v node` + # on stdout once ensure_node succeeds. Subshell PATH edits don't leak + # back into Python, so the stdout capture is the bridge. + result = subprocess.run( + [ + "bash", + "-c", + f'source "{helper}" >&2 && ensure_node >&2 && command -v node', + ], + env={**os.environ, "HERMES_HOME": hermes_home}, + capture_output=True, + text=True, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return + + parts = os.environ.get("PATH", "").split(os.pathsep) + extras: list[Path] = [] + + resolved = (result.stdout or "").strip() + if resolved: + extras.append(Path(resolved).resolve().parent) + + extras.extend([Path(hermes_home) / "node" / "bin", Path.home() / ".local" / "bin"]) + + for extra in extras: + s = str(extra) + if extra.is_dir() and s not in parts: + parts.insert(0, s) + os.environ["PATH"] = os.pathsep.join(parts) + + +def _make_tui_argv(tui_dir: Path, tui_dev: bool) -> tuple[list[str], Path]: + """TUI: --dev → tsx src; else node dist (HERMES_TUI_DIR or ui-tui, build when stale).""" + _ensure_tui_node() + + def _node_bin(bin: str) -> str: + path = shutil.which(bin) + if not path: + print(f"{bin} not found — install Node.js to use the TUI.") + sys.exit(1) + return path + + # pre-built dist + node_modules (nix / full HERMES_TUI_DIR) skips npm. + if not tui_dev: + ext_dir = os.environ.get("HERMES_TUI_DIR") + if ext_dir: + p = Path(ext_dir) + if (p / "dist" / "entry.js").exists() and not _tui_need_npm_install(p): + node = _node_bin("node") + return [node, str(p / "dist" / "entry.js")], p + + npm = _node_bin("npm") + if _tui_need_npm_install(tui_dir): + if not os.environ.get("HERMES_QUIET"): + print("Installing TUI dependencies…") + result = subprocess.run( + [npm, "install", "--silent", "--no-fund", "--no-audit", "--progress=false"], + cwd=str(tui_dir), + stdout=subprocess.DEVNULL, + stderr=subprocess.PIPE, + text=True, + env={**os.environ, "CI": "1"}, + ) + if result.returncode != 0: + err = (result.stderr or "").strip() + preview = "\n".join(err.splitlines()[-30:]) + print("npm install failed.") + if preview: + print(preview) + sys.exit(1) + + if tui_dev: + if _hermes_ink_bundle_stale(tui_dir): + result = subprocess.run( + [npm, "run", "build", "--prefix", "packages/hermes-ink"], + cwd=str(tui_dir), + capture_output=True, + text=True, + ) + if result.returncode != 0: + combined = f"{result.stdout or ''}{result.stderr or ''}".strip() + preview = "\n".join(combined.splitlines()[-30:]) + print("@hermes/ink build failed.") + if preview: + print(preview) + sys.exit(1) + tsx = tui_dir / "node_modules" / ".bin" / "tsx" + if tsx.exists(): + return [str(tsx), "src/entry.tsx"], tui_dir + return [npm, "start"], tui_dir + + if _tui_build_needed(tui_dir): + result = subprocess.run( + [npm, "run", "build"], + cwd=str(tui_dir), + capture_output=True, + text=True, + ) + if result.returncode != 0: + combined = f"{result.stdout or ''}{result.stderr or ''}".strip() + preview = "\n".join(combined.splitlines()[-30:]) + print("TUI build failed.") + if preview: + print(preview) + sys.exit(1) + + root = _find_bundled_tui(tui_dir) + if not root: + print("TUI build did not produce dist/entry.js") + sys.exit(1) + + node = _node_bin("node") + return [node, str(root / "dist" / "entry.js")], root + + +def _launch_tui(resume_session_id: Optional[str] = None, tui_dev: bool = False): + """Replace current process with the TUI.""" + tui_dir = PROJECT_ROOT / "ui-tui" + + env = os.environ.copy() + env["HERMES_PYTHON_SRC_ROOT"] = os.environ.get( + "HERMES_PYTHON_SRC_ROOT", str(PROJECT_ROOT) + ) + env.setdefault("HERMES_PYTHON", sys.executable) + env.setdefault("HERMES_CWD", os.getcwd()) + if resume_session_id: + env["HERMES_TUI_RESUME"] = resume_session_id + + argv, cwd = _make_tui_argv(tui_dir, tui_dev) + try: + code = subprocess.call(argv, cwd=str(cwd), env=env) + except KeyboardInterrupt: + code = 130 + + if code in (0, 130): + _print_tui_exit_summary(resume_session_id) + + sys.exit(code) + + def cmd_chat(args): """Run interactive chat CLI.""" - # Resolve --continue into --resume with the latest CLI session or by name + use_tui = getattr(args, "tui", False) or os.environ.get("HERMES_TUI") == "1" + + # Resolve --continue into --resume with the latest session or by name continue_val = getattr(args, "continue_last", None) if continue_val and not getattr(args, "resume", None): if isinstance(continue_val, str): @@ -689,11 +1019,15 @@ def cmd_chat(args): sys.exit(1) else: # -c with no argument — continue the most recent session - last_id = _resolve_last_cli_session() + source = "tui" if use_tui else "cli" + last_id = _resolve_last_session(source=source) + if not last_id and source == "tui": + last_id = _resolve_last_session(source="cli") if last_id: args.resume = last_id else: - print("No previous CLI session found to continue.") + kind = "TUI" if use_tui else "CLI" + print(f"No previous {kind} session found to continue.") sys.exit(1) # Resolve --resume by title if it's not a direct session ID @@ -708,12 +1042,17 @@ def cmd_chat(args): # First-run guard: check if any provider is configured before launching if not _has_any_provider_configured(): print() - print("It looks like Hermes isn't configured yet -- no API keys or providers found.") + print( + "It looks like Hermes isn't configured yet -- no API keys or providers found." + ) print() print(" Run: hermes setup") print() - from hermes_cli.setup import is_interactive_stdin, print_noninteractive_setup_guidance + from hermes_cli.setup import ( + is_interactive_stdin, + print_noninteractive_setup_guidance, + ) if not is_interactive_stdin(): print_noninteractive_setup_guidance( @@ -735,6 +1074,7 @@ def cmd_chat(args): # Start update check in background (runs while other init happens) try: from hermes_cli.banner import prefetch_update_check + prefetch_update_check() except Exception: pass @@ -742,6 +1082,7 @@ def cmd_chat(args): # Sync bundled skills on every CLI launch (fast -- skips unchanged skills) try: from tools.skills_sync import sync_skills + sync_skills(quiet=True) except Exception: pass @@ -754,9 +1095,15 @@ def cmd_chat(args): if getattr(args, "source", None): os.environ["HERMES_SESSION_SOURCE"] = args.source + if use_tui: + _launch_tui( + getattr(args, "resume", None), + tui_dev=getattr(args, "tui_dev", False), + ) + # Import and run the CLI from cli import main as cli_main - + # Build kwargs from args kwargs = { "model": args.model, @@ -775,7 +1122,7 @@ def cmd_chat(args): } # Filter out None values kwargs = {k: v for k, v in kwargs.items() if v is not None} - + try: cli_main(**kwargs) except ValueError as e: @@ -786,6 +1133,7 @@ def cmd_chat(args): def cmd_gateway(args): """Gateway management commands.""" from hermes_cli.gateway import gateway_command + gateway_command(args) @@ -808,7 +1156,9 @@ def cmd_whatsapp(args): print() print(" 1. Separate bot number (recommended)") print(" People message the bot's number directly — cleanest experience.") - print(" Requires a second phone number with WhatsApp installed on a device.") + print( + " Requires a second phone number with WhatsApp installed on a device." + ) print() print(" 2. Personal number (self-chat)") print(" You message yourself to talk to the agent.") @@ -843,7 +1193,9 @@ def cmd_whatsapp(args): print(" ✓ Mode: personal number (self-chat)") else: wa_mode = current_mode - mode_label = "separate bot number" if wa_mode == "bot" else "personal number (self-chat)" + mode_label = ( + "separate bot number" if wa_mode == "bot" else "personal number (self-chat)" + ) print(f"\n✓ Mode: {mode_label}") # ── Step 2: Enable WhatsApp ────────────────────────────────────────── @@ -865,7 +1217,9 @@ def cmd_whatsapp(args): response = "n" if response.lower() in ("y", "yes"): if wa_mode == "bot": - phone = input(" Phone numbers that can message the bot (comma-separated): ").strip() + phone = input( + " Phone numbers that can message the bot (comma-separated): " + ).strip() else: phone = input(" Your phone number (e.g. 15551234567): ").strip() if phone: @@ -875,7 +1229,9 @@ def cmd_whatsapp(args): print() if wa_mode == "bot": print(" Who should be allowed to message the bot?") - phone = input(" Phone numbers (comma-separated, or * for anyone): ").strip() + phone = input( + " Phone numbers (comma-separated, or * for anyone): " + ).strip() else: phone = input(" Your phone number (e.g. 15551234567): ").strip() if phone: @@ -916,11 +1272,14 @@ def cmd_whatsapp(args): if (session_dir / "creds.json").exists(): print("✓ Existing WhatsApp session found") try: - response = input("\n Re-pair? This will clear the existing session. [y/N] ").strip() + response = input( + "\n Re-pair? This will clear the existing session. [y/N] " + ).strip() except (EOFError, KeyboardInterrupt): response = "n" if response.lower() in ("y", "yes"): import shutil + shutil.rmtree(session_dir, ignore_errors=True) session_dir.mkdir(parents=True, exist_ok=True) print(" ✓ Session cleared") @@ -979,6 +1338,7 @@ def cmd_whatsapp(args): def cmd_setup(args): """Interactive setup wizard.""" from hermes_cli.setup import run_setup_wizard + run_setup_wizard(args) @@ -997,9 +1357,15 @@ def select_provider_and_model(args=None): persistence. """ from hermes_cli.auth import ( - resolve_provider, AuthError, format_auth_error, + resolve_provider, + AuthError, + format_auth_error, + ) + from hermes_cli.config import ( + get_compatible_custom_providers, + load_config, + get_env_value, ) - from hermes_cli.config import get_compatible_custom_providers, load_config, get_env_value config = load_config() current_model = config.get("model") @@ -1010,15 +1376,14 @@ def select_provider_and_model(args=None): # Read effective provider the same way the CLI does at startup: # config.yaml model.provider > env var > auto-detect import os + config_provider = None model_cfg = config.get("model") if isinstance(model_cfg, dict): config_provider = model_cfg.get("provider") effective_provider = ( - config_provider - or os.getenv("HERMES_INFERENCE_PROVIDER") - or "auto" + config_provider or os.getenv("HERMES_INFERENCE_PROVIDER") or "auto" ) try: active = resolve_provider(effective_provider) @@ -1075,7 +1440,9 @@ def select_provider_and_model(args=None): return custom_provider_map # Add user-defined custom providers from config.yaml - _custom_provider_map = _named_custom_provider_map(config) # key → {name, base_url, api_key} + _custom_provider_map = _named_custom_provider_map( + config + ) # key → {name, base_url, api_key} for key, provider_info in _custom_provider_map.items(): name = provider_info["name"] base_url = provider_info["base_url"] @@ -1095,13 +1462,16 @@ def select_provider_and_model(args=None): ordered.append((key, label)) ordered.append(("custom", "Custom endpoint (enter URL manually)")) - _has_saved_custom_list = isinstance(config.get("custom_providers"), list) and bool(config.get("custom_providers")) + _has_saved_custom_list = isinstance(config.get("custom_providers"), list) and bool( + config.get("custom_providers") + ) if _has_saved_custom_list: ordered.append(("remove-custom", "Remove a saved custom provider")) ordered.append(("cancel", "Cancel")) provider_idx = _prompt_provider_choice( - [label for _, label in ordered], default=default_idx, + [label for _, label in ordered], + default=default_idx, ) if provider_idx is None or ordered[provider_idx][0] == "cancel": print("No change.") @@ -1126,7 +1496,10 @@ def select_provider_and_model(args=None): _model_flow_copilot(config, current_model) elif selected_provider == "custom": _model_flow_custom(config) - elif selected_provider.startswith("custom:") or selected_provider in _custom_provider_map: + elif ( + selected_provider.startswith("custom:") + or selected_provider in _custom_provider_map + ): provider_info = _named_custom_provider_map(load_config()).get(selected_provider) if provider_info is None: print( @@ -1143,15 +1516,36 @@ def select_provider_and_model(args=None): _model_flow_kimi(config, current_model) elif selected_provider == "bedrock": _model_flow_bedrock(config, current_model) - elif selected_provider in ("gemini", "deepseek", "xai", "zai", "kimi-coding-cn", "minimax", "minimax-cn", "kilocode", "opencode-zen", "opencode-go", "ai-gateway", "alibaba", "huggingface", "xiaomi", "arcee", "nvidia", "ollama-cloud"): + elif selected_provider in ( + "gemini", + "deepseek", + "xai", + "zai", + "kimi-coding-cn", + "minimax", + "minimax-cn", + "kilocode", + "opencode-zen", + "opencode-go", + "ai-gateway", + "alibaba", + "huggingface", + "xiaomi", + "arcee", + "nvidia", + "ollama-cloud", + ): _model_flow_api_key_provider(config, selected_provider, current_model) # ── Post-switch cleanup: clear stale OPENAI_BASE_URL ────────────── # When the user switches to a named provider (anything except "custom"), # a leftover OPENAI_BASE_URL in ~/.hermes/.env can poison auxiliary # clients that use provider:auto. Clear it proactively. (#5161) - if selected_provider not in ("custom", "cancel", "remove-custom") \ - and not selected_provider.startswith("custom:"): + if selected_provider not in ( + "custom", + "cancel", + "remove-custom", + ) and not selected_provider.startswith("custom:"): _clear_stale_openai_base_url() @@ -1178,9 +1572,11 @@ def _clear_stale_openai_base_url(): stale_url = get_env_value("OPENAI_BASE_URL") if stale_url: save_env_value("OPENAI_BASE_URL", "") - print(f"Cleared stale OPENAI_BASE_URL from .env (was: {stale_url[:40]}...)" - if len(stale_url) > 40 - else f"Cleared stale OPENAI_BASE_URL from .env (was: {stale_url})") + print( + f"Cleared stale OPENAI_BASE_URL from .env (was: {stale_url[:40]}...)" + if len(stale_url) > 40 + else f"Cleared stale OPENAI_BASE_URL from .env (was: {stale_url})" + ) def _prompt_provider_choice(choices, *, default=0): @@ -1192,6 +1588,7 @@ def _prompt_provider_choice(choices, *, default=0): """ try: from hermes_cli.setup import _curses_prompt_choice + idx = _curses_prompt_choice("Select provider:", choices, default) if idx >= 0: print() @@ -1223,7 +1620,11 @@ def _prompt_provider_choice(choices, *, default=0): def _model_flow_openrouter(config, current_model=""): """OpenRouter provider: ensure API key, then pick model.""" - from hermes_cli.auth import _prompt_model_selection, _save_model_choice, deactivate_provider + from hermes_cli.auth import ( + _prompt_model_selection, + _save_model_choice, + deactivate_provider, + ) from hermes_cli.config import get_env_value, save_env_value api_key = get_env_value("OPENROUTER_API_KEY") @@ -1233,6 +1634,7 @@ def _model_flow_openrouter(config, current_model=""): print() try: import getpass + key = getpass.getpass("OpenRouter API key (or Enter to cancel): ").strip() except (KeyboardInterrupt, EOFError): print() @@ -1245,17 +1647,21 @@ def _model_flow_openrouter(config, current_model=""): print() from hermes_cli.models import model_ids, get_pricing_for_provider + openrouter_models = model_ids(force_refresh=True) # Fetch live pricing (non-blocking — returns empty dict on failure) pricing = get_pricing_for_provider("openrouter", force_refresh=True) - selected = _prompt_model_selection(openrouter_models, current_model=current_model, pricing=pricing) + selected = _prompt_model_selection( + openrouter_models, current_model=current_model, pricing=pricing + ) if selected: _save_model_choice(selected) # Update config provider and deactivate any OAuth provider from hermes_cli.config import load_config, save_config + cfg = load_config() model = cfg.get("model") if not isinstance(model, dict): @@ -1274,12 +1680,22 @@ def _model_flow_openrouter(config, current_model=""): def _model_flow_nous(config, current_model="", args=None): """Nous Portal provider: ensure logged in, then pick model.""" from hermes_cli.auth import ( - get_provider_auth_state, _prompt_model_selection, _save_model_choice, - _update_config_for_provider, resolve_nous_runtime_credentials, - AuthError, format_auth_error, - _login_nous, PROVIDER_REGISTRY, + get_provider_auth_state, + _prompt_model_selection, + _save_model_choice, + _update_config_for_provider, + resolve_nous_runtime_credentials, + AuthError, + format_auth_error, + _login_nous, + PROVIDER_REGISTRY, + ) + from hermes_cli.config import ( + get_env_value, + load_config, + save_config, + save_env_value, ) - from hermes_cli.config import get_env_value, load_config, save_config, save_env_value from hermes_cli.nous_subscription import prompt_enable_tool_gateway import argparse @@ -1318,9 +1734,13 @@ def _model_flow_nous(config, current_model="", args=None): # The live /models endpoint returns hundreds of models; the curated list # shows only agentic models users recognize from OpenRouter. from hermes_cli.models import ( - _PROVIDER_MODELS, get_pricing_for_provider, filter_nous_free_models, - check_nous_free_tier, partition_nous_models_by_tier, + _PROVIDER_MODELS, + get_pricing_for_provider, + filter_nous_free_models, + check_nous_free_tier, + partition_nous_models_by_tier, ) + model_ids = _PROVIDER_MODELS.get("nous", []) if not model_ids: print("No curated models available for Nous Portal.") @@ -1337,9 +1757,14 @@ def _model_flow_nous(config, current_model="", args=None): print("Re-authenticating with Nous Portal...\n") try: mock_args = argparse.Namespace( - portal_url=None, inference_url=None, client_id=None, - scope=None, no_browser=False, timeout=15.0, - ca_bundle=None, insecure=False, + portal_url=None, + inference_url=None, + client_id=None, + scope=None, + no_browser=False, + timeout=15.0, + ca_bundle=None, + insecure=False, ) _login_nous(mock_args, PROVIDER_REGISTRY["nous"]) except Exception as login_exc: @@ -1360,7 +1785,9 @@ def _model_flow_nous(config, current_model="", args=None): model_ids = filter_nous_free_models(model_ids, pricing) unavailable_models: list[str] = [] if free_tier: - model_ids, unavailable_models = partition_nous_models_by_tier(model_ids, pricing, free_tier=True) + model_ids, unavailable_models = partition_nous_models_by_tier( + model_ids, pricing, free_tier=True + ) if not model_ids and not unavailable_models: print("No models available for Nous Portal after filtering.") @@ -1379,15 +1806,21 @@ def _model_flow_nous(config, current_model="", args=None): print("No free models currently available.") if unavailable_models: from hermes_cli.auth import DEFAULT_NOUS_PORTAL_URL + _url = (_nous_portal_url or DEFAULT_NOUS_PORTAL_URL).rstrip("/") print(f"Upgrade at {_url} to access paid models.") return - print(f"Showing {len(model_ids)} curated models — use \"Enter custom model name\" for others.") + print( + f'Showing {len(model_ids)} curated models — use "Enter custom model name" for others.' + ) selected = _prompt_model_selection( - model_ids, current_model=current_model, pricing=pricing, - unavailable_models=unavailable_models, portal_url=_nous_portal_url, + model_ids, + current_model=current_model, + pricing=pricing, + unavailable_models=unavailable_models, + portal_url=_nous_portal_url, ) if selected: _save_model_choice(selected) @@ -1423,9 +1856,13 @@ def _model_flow_nous(config, current_model="", args=None): def _model_flow_openai_codex(config, current_model=""): """OpenAI Codex provider: ensure logged in, then pick model.""" from hermes_cli.auth import ( - get_codex_auth_status, _prompt_model_selection, _save_model_choice, - _update_config_for_provider, _login_openai_codex, - PROVIDER_REGISTRY, DEFAULT_CODEX_BASE_URL, + get_codex_auth_status, + _prompt_model_selection, + _save_model_choice, + _update_config_for_provider, + _login_openai_codex, + PROVIDER_REGISTRY, + DEFAULT_CODEX_BASE_URL, ) from hermes_cli.codex_models import get_codex_model_ids import argparse @@ -1456,6 +1893,7 @@ def _model_flow_openai_codex(config, current_model=""): if not _codex_token: try: from hermes_cli.auth import resolve_codex_runtime_credentials + _codex_creds = resolve_codex_runtime_credentials() _codex_token = _codex_creds.get("api_key") except Exception: @@ -1472,7 +1910,6 @@ def _model_flow_openai_codex(config, current_model=""): print("No change.") - _DEFAULT_QWEN_PORTAL_MODELS = [ "qwen3-coder-plus", "qwen3-coder", @@ -1575,7 +2012,9 @@ def _model_flow_google_gemini_cli(_config, current_model=""): if project_id: print(f" Using GCP project: {project_id}") else: - print(" No GCP project configured — free tier will be auto-provisioned on first request.") + print( + " No GCP project configured — free tier will be auto-provisioned on first request." + ) except Exception as exc: print(f"Failed to resolve Gemini credentials: {exc}") return @@ -1585,14 +2024,16 @@ def _model_flow_google_gemini_cli(_config, current_model=""): selected = _prompt_model_selection(models, current_model=default) if selected: _save_model_choice(selected) - _update_config_for_provider("google-gemini-cli", DEFAULT_GEMINI_CLOUDCODE_BASE_URL) - print(f"Default model set to: {selected} (via Google Gemini OAuth / Code Assist)") + _update_config_for_provider( + "google-gemini-cli", DEFAULT_GEMINI_CLOUDCODE_BASE_URL + ) + print( + f"Default model set to: {selected} (via Google Gemini OAuth / Code Assist)" + ) else: print("No change.") - - def _model_flow_custom(config): """Custom endpoint: collect URL, API key, and model name. @@ -1613,9 +2054,14 @@ def _model_flow_custom(config): print() try: - base_url = input(f"API base URL [{current_url or 'e.g. https://api.example.com/v1'}]: ").strip() + base_url = input( + f"API base URL [{current_url or 'e.g. https://api.example.com/v1'}]: " + ).strip() import getpass - api_key = getpass.getpass(f"API key [{current_key[:8] + '...' if current_key else 'optional'}]: ").strip() + + api_key = getpass.getpass( + f"API key [{current_key[:8] + '...' if current_key else 'optional'}]: " + ).strip() except (KeyboardInterrupt, EOFError): print("\nCancelled.") return @@ -1636,7 +2082,10 @@ def _model_flow_custom(config): # in the base URL for OpenAI-compatible chat completions. Prompt the # user if the URL looks like a local server without /v1. _url_lower = effective_url.rstrip("/").lower() - _looks_local = any(h in _url_lower for h in ("localhost", "127.0.0.1", "0.0.0.0", ":11434", ":8080", ":5000")) + _looks_local = any( + h in _url_lower + for h in ("localhost", "127.0.0.1", "0.0.0.0", ":11434", ":8080", ":5000") + ) if _looks_local and not _url_lower.endswith("/v1"): print() print(f" Hint: Did you mean to add /v1 at the end?") @@ -1677,7 +2126,9 @@ def _model_flow_custom(config): if probe.get("suggested_base_url"): suggested = probe["suggested_base_url"] if suggested.endswith("/v1"): - print(f" If this server expects /v1 in the path, try base URL: {suggested}") + print( + f" If this server expects /v1 in the path, try base URL: {suggested}" + ) else: print(f" If /v1 should not be in the base URL, try: {suggested}") @@ -1696,7 +2147,9 @@ def _model_flow_custom(config): print(" Available models:") for i, m in enumerate(detected_models, 1): print(f" {i}. {m}") - pick = input(f" Select model [1-{len(detected_models)}] or type name: ").strip() + pick = input( + f" Select model [1-{len(detected_models)}] or type name: " + ).strip() if pick.isdigit() and 1 <= int(pick) <= len(detected_models): model_name = detected_models[int(pick) - 1] elif pick: @@ -1704,7 +2157,9 @@ def _model_flow_custom(config): else: model_name = input("Model name (e.g. gpt-4, llama-3-70b): ").strip() - context_length_str = input("Context length in tokens [leave blank for auto-detect]: ").strip() + context_length_str = input( + "Context length in tokens [leave blank for auto-detect]: " + ).strip() # Prompt for a display name — shown in the provider menu on future runs default_name = _auto_provider_name(effective_url) @@ -1716,7 +2171,11 @@ def _model_flow_custom(config): context_length = None if context_length_str: try: - context_length = int(context_length_str.replace(",", "").replace("k", "000").replace("K", "000")) + context_length = int( + context_length_str.replace(",", "") + .replace("k", "000") + .replace("K", "000") + ) if context_length <= 0: context_length = None except ValueError: @@ -1764,8 +2223,13 @@ def _model_flow_custom(config): print("Endpoint saved. Use `/model` in chat or `hermes model` to set a model.") # Auto-save to custom_providers so it appears in the menu next time - _save_custom_provider(effective_url, effective_key, model_name or "", - context_length=context_length, name=display_name) + _save_custom_provider( + effective_url, + effective_key, + model_name or "", + context_length=context_length, + name=display_name, + ) def _auto_provider_name(base_url: str) -> str: @@ -1776,6 +2240,7 @@ def _auto_provider_name(base_url: str) -> str: user for a display name during custom endpoint setup. """ import re + clean = base_url.replace("https://", "").replace("http://", "").rstrip("/") clean = re.sub(r"/v1/?$", "", clean) name = clean.split("/")[0] @@ -1788,8 +2253,9 @@ def _auto_provider_name(base_url: str) -> str: return name -def _save_custom_provider(base_url, api_key="", model="", context_length=None, - name=None): +def _save_custom_provider( + base_url, api_key="", model="", context_length=None, name=None +): """Save a custom endpoint to custom_providers in config.yaml. Deduplicates by base_url — if the URL already exists, updates the @@ -1805,7 +2271,9 @@ def _save_custom_provider(base_url, api_key="", model="", context_length=None, # Check if this URL is already saved — update model/context_length if so for entry in providers: - if isinstance(entry, dict) and entry.get("base_url", "").rstrip("/") == base_url.rstrip("/"): + if isinstance(entry, dict) and entry.get("base_url", "").rstrip( + "/" + ) == base_url.rstrip("/"): changed = False if model and entry.get("model") != model: entry["model"] = model @@ -1837,7 +2305,7 @@ def _save_custom_provider(base_url, api_key="", model="", context_length=None, providers.append(entry) cfg["custom_providers"] = providers save_config(cfg) - print(f" 💾 Saved to custom providers as \"{name}\" (edit in config.yaml)") + print(f' 💾 Saved to custom providers as "{name}" (edit in config.yaml)') def _remove_custom_provider(config): @@ -1865,15 +2333,20 @@ def _remove_custom_provider(config): try: from simple_term_menu import TerminalMenu + menu = TerminalMenu( - [f" {c}" for c in choices], cursor_index=0, - menu_cursor="-> ", menu_cursor_style=("fg_red", "bold"), + [f" {c}" for c in choices], + cursor_index=0, + menu_cursor="-> ", + menu_cursor_style=("fg_red", "bold"), menu_highlight_style=("fg_red",), - cycle_cursor=True, clear_screen=False, + cycle_cursor=True, + clear_screen=False, title="Select provider to remove:", ) idx = menu.show() from hermes_cli.curses_ui import flush_stdin + flush_stdin() print() except (ImportError, NotImplementedError, OSError, subprocess.SubprocessError): @@ -1893,8 +2366,10 @@ def _remove_custom_provider(config): removed = providers.pop(idx) cfg["custom_providers"] = providers save_config(cfg) - removed_name = removed.get("name", "unnamed") if isinstance(removed, dict) else str(removed) - print(f"✅ Removed \"{removed_name}\" from custom providers.") + removed_name = ( + removed.get("name", "unnamed") if isinstance(removed, dict) else str(removed) + ) + print(f'✅ Removed "{removed_name}" from custom providers.') def _model_flow_named_custom(config, provider_info): @@ -1932,19 +2407,23 @@ def _model_flow_named_custom(config, provider_info): print(f"Found {len(models)} model(s):\n") try: from simple_term_menu import TerminalMenu + menu_items = [ - f" {m} (current)" if m == saved_model else f" {m}" - for m in models + f" {m} (current)" if m == saved_model else f" {m}" for m in models ] + [" Cancel"] menu = TerminalMenu( - menu_items, cursor_index=default_idx, - menu_cursor="-> ", menu_cursor_style=("fg_green", "bold"), + menu_items, + cursor_index=default_idx, + menu_cursor="-> ", + menu_cursor_style=("fg_green", "bold"), menu_highlight_style=("fg_green",), - cycle_cursor=True, clear_screen=False, + cycle_cursor=True, + clear_screen=False, title=f"Select model from {name}:", ) idx = menu.show() from hermes_cli.curses_ui import flush_stdin + flush_stdin() print() if idx is None or idx >= len(models): @@ -2057,7 +2536,11 @@ def _set_reasoning_effort(config, effort: str) -> None: def _prompt_reasoning_effort_selection(efforts, current_effort=""): """Prompt for a reasoning effort. Returns effort, 'none', or None to keep current.""" - deduped = list(dict.fromkeys(str(effort).strip().lower() for effort in efforts if str(effort).strip())) + deduped = list( + dict.fromkeys( + str(effort).strip().lower() for effort in efforts if str(effort).strip() + ) + ) canonical_order = ("minimal", "low", "medium", "high", "xhigh") ordered = [effort for effort in canonical_order if effort in deduped] ordered.extend(effort for effort in deduped if effort not in canonical_order) @@ -2099,6 +2582,7 @@ def _prompt_reasoning_effort_selection(efforts, current_effort=""): ) idx = menu.show() from hermes_cli.curses_ui import flush_stdin + flush_stdin() if idx is None: return None @@ -2167,7 +2651,9 @@ def _model_flow_copilot(config, current_model=""): print("No GitHub token configured for GitHub Copilot.") print() print(" Supported token types:") - print(" → OAuth token (gho_*) via `copilot login` or device code flow") + print( + " → OAuth token (gho_*) via `copilot login` or device code flow" + ) print(" → Fine-grained PAT (github_pat_*) with Copilot Requests permission") print(" → GitHub App token (ghu_*) via environment variable") print(" ✗ Classic PAT (ghp_*) NOT supported by Copilot API") @@ -2186,6 +2672,7 @@ def _model_flow_copilot(config, current_model=""): if choice == "1": try: from hermes_cli.copilot_auth import copilot_device_code_login + token = copilot_device_code_login() if token: save_env_value("COPILOT_GITHUB_TOKEN", token) @@ -2200,6 +2687,7 @@ def _model_flow_copilot(config, current_model=""): elif choice == "2": try: import getpass + new_key = getpass.getpass(" Token (COPILOT_GITHUB_TOKEN): ").strip() except (KeyboardInterrupt, EOFError): print() @@ -2210,6 +2698,7 @@ def _model_flow_copilot(config, current_model=""): # Validate token type try: from hermes_cli.copilot_auth import validate_copilot_token + valid, msg = validate_copilot_token(new_key) if not valid: print(f" ✗ {msg}") @@ -2238,23 +2727,34 @@ def _model_flow_copilot(config, current_model=""): effective_base = pconfig.inference_base_url catalog = fetch_github_model_catalog(api_key) - live_models = [item.get("id", "") for item in catalog if item.get("id")] if catalog else fetch_api_models(api_key, effective_base) - normalized_current_model = normalize_copilot_model_id( - current_model, - catalog=catalog, - api_key=api_key, - ) or current_model + live_models = ( + [item.get("id", "") for item in catalog if item.get("id")] + if catalog + else fetch_api_models(api_key, effective_base) + ) + normalized_current_model = ( + normalize_copilot_model_id( + current_model, + catalog=catalog, + api_key=api_key, + ) + or current_model + ) if live_models: model_list = [model_id for model_id in live_models if model_id] print(f" Found {len(model_list)} model(s) from GitHub Copilot") else: model_list = _PROVIDER_MODELS.get(provider_id, []) if model_list: - print(" ⚠ Could not auto-detect models from GitHub Copilot — showing defaults.") + print( + " ⚠ Could not auto-detect models from GitHub Copilot — showing defaults." + ) print(' Use "Enter custom model name" if you do not see your model.') if model_list: - selected = _prompt_model_selection(model_list, current_model=normalized_current_model) + selected = _prompt_model_selection( + model_list, current_model=normalized_current_model + ) else: try: selected = input("Model name: ").strip() @@ -2262,11 +2762,14 @@ def _model_flow_copilot(config, current_model=""): selected = None if selected: - selected = normalize_copilot_model_id( - selected, - catalog=catalog, - api_key=api_key, - ) or selected + selected = ( + normalize_copilot_model_id( + selected, + catalog=catalog, + api_key=api_key, + ) + or selected + ) initial_cfg = load_config() current_effort = _current_reasoning_effort(initial_cfg) reasoning_efforts = github_model_reasoning_efforts( @@ -2333,7 +2836,9 @@ def _model_flow_copilot_acp(config, current_model=""): pconfig = PROVIDER_REGISTRY[provider_id] status = get_external_process_provider_status(provider_id) - resolved_command = status.get("resolved_command") or status.get("command") or "copilot" + resolved_command = ( + status.get("resolved_command") or status.get("command") or "copilot" + ) effective_base = status.get("base_url") or pconfig.inference_base_url print(" GitHub Copilot ACP delegates Hermes turns to `copilot --acp`.") @@ -2347,7 +2852,9 @@ def _model_flow_copilot_acp(config, current_model=""): creds = resolve_external_process_provider_credentials(provider_id) except Exception as exc: print(f" ⚠ {exc}") - print(" Set HERMES_COPILOT_ACP_COMMAND or COPILOT_CLI_PATH if Copilot CLI is installed elsewhere.") + print( + " Set HERMES_COPILOT_ACP_COMMAND or COPILOT_CLI_PATH if Copilot CLI is installed elsewhere." + ) return effective_base = creds.get("base_url") or effective_base @@ -2360,11 +2867,14 @@ def _model_flow_copilot_acp(config, current_model=""): pass catalog = fetch_github_model_catalog(catalog_api_key) - normalized_current_model = normalize_copilot_model_id( - current_model, - catalog=catalog, - api_key=catalog_api_key, - ) or current_model + normalized_current_model = ( + normalize_copilot_model_id( + current_model, + catalog=catalog, + api_key=catalog_api_key, + ) + or current_model + ) if catalog: model_list = [item.get("id", "") for item in catalog if item.get("id")] @@ -2372,7 +2882,9 @@ def _model_flow_copilot_acp(config, current_model=""): else: model_list = _PROVIDER_MODELS.get("copilot", []) if model_list: - print(" ⚠ Could not auto-detect models from GitHub Copilot — showing defaults.") + print( + " ⚠ Could not auto-detect models from GitHub Copilot — showing defaults." + ) print(' Use "Enter custom model name" if you do not see your model.') if model_list: @@ -2390,11 +2902,14 @@ def _model_flow_copilot_acp(config, current_model=""): print("No change.") return - selected = normalize_copilot_model_id( - selected, - catalog=catalog, - api_key=catalog_api_key, - ) or selected + selected = ( + normalize_copilot_model_id( + selected, + catalog=catalog, + api_key=catalog_api_key, + ) + or selected + ) _save_model_choice(selected) cfg = load_config() @@ -2420,10 +2935,18 @@ def _model_flow_kimi(config, current_model=""): No manual base URL prompt — endpoint is determined by key prefix. """ from hermes_cli.auth import ( - PROVIDER_REGISTRY, KIMI_CODE_BASE_URL, _prompt_model_selection, - _save_model_choice, deactivate_provider, + PROVIDER_REGISTRY, + KIMI_CODE_BASE_URL, + _prompt_model_selection, + _save_model_choice, + deactivate_provider, + ) + from hermes_cli.config import ( + get_env_value, + save_env_value, + load_config, + save_config, ) - from hermes_cli.config import get_env_value, save_env_value, load_config, save_config provider_id = "kimi-coding" pconfig = PROVIDER_REGISTRY[provider_id] @@ -2442,6 +2965,7 @@ def _model_flow_kimi(config, current_model=""): if key_env: try: import getpass + new_key = getpass.getpass(f"{key_env} (or Enter to cancel): ").strip() except (KeyboardInterrupt, EOFError): print() @@ -2518,8 +3042,17 @@ def _model_flow_bedrock_api_key(config, region, current_model=""): For developers who don't have an AWS account but received a Bedrock API Key from their AWS admin. Works like any OpenAI-compatible endpoint. """ - from hermes_cli.auth import _prompt_model_selection, _save_model_choice, deactivate_provider - from hermes_cli.config import load_config, save_config, get_env_value, save_env_value + from hermes_cli.auth import ( + _prompt_model_selection, + _save_model_choice, + deactivate_provider, + ) + from hermes_cli.config import ( + load_config, + save_config, + get_env_value, + save_env_value, + ) from hermes_cli.models import _PROVIDER_MODELS mantle_base_url = f"https://bedrock-mantle.{region}.api.aws/v1" @@ -2533,6 +3066,7 @@ def _model_flow_bedrock_api_key(config, region, current_model=""): print() try: import getpass + api_key = getpass.getpass(" Bedrock API Key: ").strip() except (KeyboardInterrupt, EOFError): print() @@ -2597,7 +3131,11 @@ def _model_flow_bedrock(config, current_model=""): Auth is handled by the AWS SDK default credential chain (env vars, profile, instance role), so no API key prompt is needed. """ - from hermes_cli.auth import _prompt_model_selection, _save_model_choice, deactivate_provider + from hermes_cli.auth import ( + _prompt_model_selection, + _save_model_choice, + deactivate_provider, + ) from hermes_cli.config import load_config, save_config from hermes_cli.models import _PROVIDER_MODELS @@ -2661,8 +3199,13 @@ def _model_flow_bedrock(config, current_model=""): if live_models: _EXCLUDE_PREFIXES = ( - "stability.", "cohere.embed", "twelvelabs.", "us.stability.", - "us.cohere.embed", "us.twelvelabs.", "global.cohere.embed", + "stability.", + "cohere.embed", + "twelvelabs.", + "us.stability.", + "us.cohere.embed", + "us.twelvelabs.", + "global.cohere.embed", "global.twelvelabs.", ) _EXCLUDE_SUBSTRINGS = ("safeguard", "voxtral", "palmyra-vision") @@ -2714,13 +3257,19 @@ def _model_flow_bedrock(config, current_model=""): deduped.sort(key=_sort_key) model_list = [m["id"] for m in deduped] - print(f" Found {len(model_list)} text model(s) (filtered from {len(live_models)} total)") + print( + f" Found {len(model_list)} text model(s) (filtered from {len(live_models)} total)" + ) else: model_list = _PROVIDER_MODELS.get("bedrock", []) if model_list: - print(f" Using {len(model_list)} curated models (live discovery unavailable)") + print( + f" Using {len(model_list)} curated models (live discovery unavailable)" + ) else: - print(" No models found. Check IAM permissions for bedrock:ListFoundationModels.") + print( + " No models found. Check IAM permissions for bedrock:ListFoundationModels." + ) return # 4. Model selection @@ -2761,11 +3310,22 @@ def _model_flow_bedrock(config, current_model=""): def _model_flow_api_key_provider(config, provider_id, current_model=""): """Generic flow for API-key providers (z.ai, MiniMax, OpenCode, etc.).""" from hermes_cli.auth import ( - PROVIDER_REGISTRY, _prompt_model_selection, _save_model_choice, + PROVIDER_REGISTRY, + _prompt_model_selection, + _save_model_choice, deactivate_provider, ) - from hermes_cli.config import get_env_value, save_env_value, load_config, save_config - from hermes_cli.models import fetch_api_models, opencode_model_api_mode, normalize_opencode_model_id + from hermes_cli.config import ( + get_env_value, + save_env_value, + load_config, + save_config, + ) + from hermes_cli.models import ( + fetch_api_models, + opencode_model_api_mode, + normalize_opencode_model_id, + ) pconfig = PROVIDER_REGISTRY[provider_id] key_env = pconfig.api_key_env_vars[0] if pconfig.api_key_env_vars else "" @@ -2783,6 +3343,7 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""): if key_env: try: import getpass + new_key = getpass.getpass(f"{key_env} (or Enter to cancel): ").strip() except (KeyboardInterrupt, EOFError): print() @@ -2810,7 +3371,9 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""): override = "" if override and base_url_env: if not override.startswith(("http://", "https://")): - print(" Invalid URL — must start with http:// or https://. Keeping current value.") + print( + " Invalid URL — must start with http:// or https://. Keeping current value." + ) else: save_env_value(base_url_env, override) effective_base = override @@ -2823,8 +3386,11 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""): # Ollama Cloud: dedicated merged discovery (live API + models.dev + disk cache) if provider_id == "ollama-cloud": from hermes_cli.models import fetch_ollama_cloud_models + api_key_for_probe = existing_key or (get_env_value(key_env) if key_env else "") - model_list = fetch_ollama_cloud_models(api_key=api_key_for_probe, base_url=effective_base) + model_list = fetch_ollama_cloud_models( + api_key=api_key_for_probe, base_url=effective_base + ) if model_list: print(f" Found {len(model_list)} model(s) from Ollama Cloud") else: @@ -2834,6 +3400,7 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""): mdev_models: list = [] try: from agent.models_dev import list_agentic_models + mdev_models = list_agentic_models(provider_id) except Exception: pass @@ -2844,9 +3411,13 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""): elif curated and len(curated) >= 8: # Curated list is substantial — use it directly, skip live probe model_list = curated - print(f" Showing {len(model_list)} curated models — use \"Enter custom model name\" for others.") + print( + f' Showing {len(model_list)} curated models — use "Enter custom model name" for others.' + ) else: - api_key_for_probe = existing_key or (get_env_value(key_env) if key_env else "") + api_key_for_probe = existing_key or ( + get_env_value(key_env) if key_env else "" + ) live_models = fetch_api_models(api_key_for_probe, effective_base) if live_models and len(live_models) >= len(curated): model_list = live_models @@ -2854,11 +3425,15 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""): else: model_list = curated if model_list: - print(f" Showing {len(model_list)} curated models — use \"Enter custom model name\" for others.") + print( + f' Showing {len(model_list)} curated models — use "Enter custom model name" for others.' + ) # else: no defaults either, will fall through to raw input if provider_id in {"opencode-zen", "opencode-go"}: - model_list = [normalize_opencode_model_id(provider_id, mid) for mid in model_list] + model_list = [ + normalize_opencode_model_id(provider_id, mid) for mid in model_list + ] current_model = normalize_opencode_model_id(provider_id, current_model) model_list = list(dict.fromkeys(mid for mid in model_list if mid)) @@ -2914,13 +3489,15 @@ def _run_anthropic_oauth_flow(save_env_value): except Exception: creds = None if creds and ( - is_claude_code_token_valid(creds) - or bool(creds.get("refreshToken")) + is_claude_code_token_valid(creds) or bool(creds.get("refreshToken")) ): use_anthropic_claude_code_credentials(save_fn=save_env_value) print(" ✓ Claude Code credentials linked.") from hermes_constants import display_hermes_home as _dhh_fn - print(f" Hermes will use Claude's credential store directly instead of copying a setup-token into {_dhh_fn()}/.env.") + + print( + f" Hermes will use Claude's credential store directly instead of copying a setup-token into {_dhh_fn()}/.env." + ) return True return False @@ -2943,7 +3520,10 @@ def _run_anthropic_oauth_flow(save_env_value): print() try: import getpass - manual_token = getpass.getpass(" Paste setup-token (or Enter to cancel): ").strip() + + manual_token = getpass.getpass( + " Paste setup-token (or Enter to cancel): " + ).strip() except (KeyboardInterrupt, EOFError): print() return False @@ -2971,6 +3551,7 @@ def _run_anthropic_oauth_flow(save_env_value): print() try: import getpass + token = getpass.getpass(" Setup-token (or Enter to cancel): ").strip() except (KeyboardInterrupt, EOFError): print() @@ -2986,21 +3567,29 @@ def _run_anthropic_oauth_flow(save_env_value): def _model_flow_anthropic(config, current_model=""): """Flow for Anthropic provider — OAuth subscription, API key, or Claude Code creds.""" from hermes_cli.auth import ( - _prompt_model_selection, _save_model_choice, + _prompt_model_selection, + _save_model_choice, deactivate_provider, ) from hermes_cli.config import ( - save_env_value, load_config, save_config, + save_env_value, + load_config, + save_config, save_anthropic_api_key, ) from hermes_cli.models import _PROVIDER_MODELS # Check ALL credential sources from hermes_cli.auth import get_anthropic_key + existing_key = get_anthropic_key() cc_available = False try: - from agent.anthropic_adapter import read_claude_code_credentials, is_claude_code_token_valid + from agent.anthropic_adapter import ( + read_claude_code_credentials, + is_claude_code_token_valid, + ) + cc_creds = read_claude_code_credentials() if cc_creds and is_claude_code_token_valid(cc_creds): cc_available = True @@ -3057,6 +3646,7 @@ def _model_flow_anthropic(config, current_model=""): print() try: import getpass + api_key = getpass.getpass(" API key (sk-ant-...): ").strip() except (KeyboardInterrupt, EOFError): print() @@ -3107,60 +3697,70 @@ def _model_flow_anthropic(config, current_model=""): def cmd_login(args): """Authenticate Hermes CLI with a provider.""" from hermes_cli.auth import login_command + login_command(args) def cmd_logout(args): """Clear provider authentication.""" from hermes_cli.auth import logout_command + logout_command(args) def cmd_auth(args): """Manage pooled credentials.""" from hermes_cli.auth_commands import auth_command + auth_command(args) def cmd_status(args): """Show status of all components.""" from hermes_cli.status import show_status + show_status(args) def cmd_cron(args): """Cron job management.""" from hermes_cli.cron import cron_command + cron_command(args) def cmd_webhook(args): """Webhook subscription management.""" from hermes_cli.webhook import webhook_command + webhook_command(args) def cmd_doctor(args): """Check configuration and dependencies.""" from hermes_cli.doctor import run_doctor + run_doctor(args) def cmd_dump(args): """Dump setup summary for support/debugging.""" from hermes_cli.dump import run_dump + run_dump(args) def cmd_debug(args): """Debug tools (share report, etc.).""" from hermes_cli.debug import run_debug + run_debug(args) def cmd_config(args): """Configuration management.""" from hermes_cli.config import config_command + config_command(args) @@ -3168,15 +3768,18 @@ def cmd_backup(args): """Back up Hermes home directory to a zip file.""" if getattr(args, "quick", False): from hermes_cli.backup import run_quick_backup + run_quick_backup(args) else: from hermes_cli.backup import run_backup + run_backup(args) def cmd_import(args): """Restore a Hermes backup from a zip file.""" from hermes_cli.backup import run_import + run_import(args) @@ -3184,13 +3787,14 @@ def cmd_version(args): """Show version.""" print(f"Hermes Agent v{__version__} ({__release_date__})") print(f"Project: {PROJECT_ROOT}") - + # Show Python version print(f"Python: {sys.version.split()[0]}") - + # Check for key dependencies try: import openai + print(f"OpenAI SDK: {openai.__version__}") except ImportError: print("OpenAI SDK: Not installed") @@ -3199,6 +3803,7 @@ def cmd_version(args): try: from hermes_cli.banner import check_for_updates from hermes_cli.config import recommended_update_command + behind = check_for_updates() if behind and behind > 0: commits_word = "commit" if behind == 1 else "commits" @@ -3216,6 +3821,7 @@ def cmd_uninstall(args): """Uninstall Hermes Agent.""" _require_tty("uninstall") from hermes_cli.uninstall import run_uninstall + run_uninstall(args) @@ -3233,12 +3839,14 @@ def _clear_bytecode_cache(root: Path) -> int: for dirpath, dirnames, _ in os.walk(root): # Skip venv / node_modules / .git entirely dirnames[:] = [ - d for d in dirnames + d + for d in dirnames if d not in ("venv", ".venv", "node_modules", ".git", ".worktrees") ] if os.path.basename(dirpath) == "__pycache__": try: import shutil as _shutil + _shutil.rmtree(dirpath) removed += 1 except OSError: @@ -3279,6 +3887,7 @@ def _gateway_prompt(prompt_text: str, default: str = "", timeout: float = 300.0) # Poll for response import time as _time + deadline = _time.monotonic() + timeout while _time.monotonic() < deadline: if response_path.exists(): @@ -3311,6 +3920,7 @@ def _build_web_ui(web_dir: Path, *, fatal: bool = False) -> bool: if not (web_dir / "package.json").exists(): return True import shutil + npm = shutil.which("npm") if not npm: if fatal: @@ -3320,15 +3930,19 @@ def _build_web_ui(web_dir: Path, *, fatal: bool = False) -> bool: print("→ Building web UI...") r1 = subprocess.run([npm, "install", "--silent"], cwd=web_dir, capture_output=True) if r1.returncode != 0: - print(f" {'✗' if fatal else '⚠'} Web UI npm install failed" - + ("" if fatal else " (hermes web will not be available)")) + print( + f" {'✗' if fatal else '⚠'} Web UI npm install failed" + + ("" if fatal else " (hermes web will not be available)") + ) if fatal: print(" Run manually: cd web && npm install && npm run build") return False r2 = subprocess.run([npm, "run", "build"], cwd=web_dir, capture_output=True) if r2.returncode != 0: - print(f" {'✗' if fatal else '⚠'} Web UI build failed" - + ("" if fatal else " (hermes web will not be available)")) + print( + f" {'✗' if fatal else '⚠'} Web UI build failed" + + ("" if fatal else " (hermes web will not be available)") + ) if fatal: print(" Run manually: cd web && npm install && npm run build") return False @@ -3338,34 +3952,41 @@ def _build_web_ui(web_dir: Path, *, fatal: bool = False) -> bool: def _update_via_zip(args): """Update Hermes Agent by downloading a ZIP archive. - - Used on Windows when git file I/O is broken (antivirus, NTFS filter + + Used on Windows when git file I/O is broken (antivirus, NTFS filter drivers causing 'Invalid argument' errors on file creation). """ import shutil import tempfile import zipfile from urllib.request import urlretrieve - + branch = "main" - zip_url = f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip" - + zip_url = ( + f"https://github.com/NousResearch/hermes-agent/archive/refs/heads/{branch}.zip" + ) + print("→ Downloading latest version...") try: tmp_dir = tempfile.mkdtemp(prefix="hermes-update-") zip_path = os.path.join(tmp_dir, f"hermes-agent-{branch}.zip") urlretrieve(zip_url, zip_path) - + print("→ Extracting...") - with zipfile.ZipFile(zip_path, 'r') as zf: + with zipfile.ZipFile(zip_path, "r") as zf: # Validate paths to prevent zip-slip (path traversal) tmp_dir_real = os.path.realpath(tmp_dir) for member in zf.infolist(): member_path = os.path.realpath(os.path.join(tmp_dir, member.filename)) - if not member_path.startswith(tmp_dir_real + os.sep) and member_path != tmp_dir_real: - raise ValueError(f"Zip-slip detected: {member.filename} escapes extraction directory") + if ( + not member_path.startswith(tmp_dir_real + os.sep) + and member_path != tmp_dir_real + ): + raise ValueError( + f"Zip-slip detected: {member.filename} escapes extraction directory" + ) zf.extractall(tmp_dir) - + # GitHub ZIPs extract to hermes-agent-/ extracted = os.path.join(tmp_dir, f"hermes-agent-{branch}") if not os.path.isdir(extracted): @@ -3375,9 +3996,9 @@ def _update_via_zip(args): if os.path.isdir(candidate) and d != "__MACOSX": extracted = candidate break - + # Copy updated files over existing installation, preserving venv/node_modules/.git - preserve = {'venv', 'node_modules', '.git', '.env'} + preserve = {"venv", "node_modules", ".git", ".env"} update_count = 0 for item in os.listdir(extracted): if item in preserve: @@ -3391,12 +4012,12 @@ def _update_via_zip(args): else: shutil.copy2(src, dst) update_count += 1 - + print(f"✓ Updated {update_count} items from ZIP") - + # Cleanup shutil.rmtree(tmp_dir, ignore_errors=True) - + except Exception as e: print(f"✗ ZIP update failed: {e}") sys.exit(1) @@ -3404,13 +4025,16 @@ def _update_via_zip(args): # Clear stale bytecode after ZIP extraction removed = _clear_bytecode_cache(PROJECT_ROOT) if removed: - print(f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}") - + print( + f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}" + ) + # Reinstall Python dependencies. Prefer .[all], but if one optional extra # breaks on this machine, keep base deps and reinstall the remaining extras # individually so update does not silently strip working capabilities. print("→ Updating Python dependencies...") import subprocess + uv_bin = shutil.which("uv") if uv_bin: uv_env = {**os.environ, "VIRTUAL_ENV": str(PROJECT_ROOT / "venv")} @@ -3422,7 +4046,12 @@ def _update_via_zip(args): # ensurepip before trying the editable install. pip_cmd = [sys.executable, "-m", "pip"] try: - subprocess.run(pip_cmd + ["--version"], cwd=PROJECT_ROOT, check=True, capture_output=True) + subprocess.run( + pip_cmd + ["--version"], + cwd=PROJECT_ROOT, + check=True, + capture_output=True, + ) except subprocess.CalledProcessError: subprocess.run( [sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], @@ -3431,18 +4060,21 @@ def _update_via_zip(args): ) _install_python_dependencies_with_optional_fallback(pip_cmd) - # Build web UI frontend (optional — requires npm) + _update_node_dependencies() _build_web_ui(PROJECT_ROOT / "web") # Sync skills try: from tools.skills_sync import sync_skills + print("→ Syncing bundled skills...") result = sync_skills(quiet=True) if result["copied"]: print(f" + {len(result['copied'])} new: {', '.join(result['copied'])}") if result.get("updated"): - print(f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}") + print( + f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}" + ) if result.get("user_modified"): print(f" ~ {len(result['user_modified'])} user-modified (kept)") if result.get("cleaned"): @@ -3451,7 +4083,7 @@ def _update_via_zip(args): print(" ✓ Skills are up to date") except Exception: pass - + print() print("✓ Update complete!") @@ -3483,7 +4115,9 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st from datetime import datetime, timezone - stash_name = datetime.now(timezone.utc).strftime("hermes-update-autostash-%Y%m%d-%H%M%S") + stash_name = datetime.now(timezone.utc).strftime( + "hermes-update-autostash-%Y%m%d-%H%M%S" + ) print("→ Local changes detected — stashing before update...") subprocess.run( git_cmd + ["stash", "push", "--include-untracked", "-m", stash_name], @@ -3500,8 +4134,9 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path) -> Optional[st return stash_ref - -def _resolve_stash_selector(git_cmd: list[str], cwd: Path, stash_ref: str) -> Optional[str]: +def _resolve_stash_selector( + git_cmd: list[str], cwd: Path, stash_ref: str +) -> Optional[str]: stash_list = subprocess.run( git_cmd + ["stash", "list", "--format=%gd %H"], cwd=cwd, @@ -3516,15 +4151,19 @@ def _resolve_stash_selector(git_cmd: list[str], cwd: Path, stash_ref: str) -> Op return None - -def _print_stash_cleanup_guidance(stash_ref: str, stash_selector: Optional[str] = None) -> None: - print(" Check `git status` first so you don't accidentally reapply the same change twice.") +def _print_stash_cleanup_guidance( + stash_ref: str, stash_selector: Optional[str] = None +) -> None: + print( + " Check `git status` first so you don't accidentally reapply the same change twice." + ) print(" Find the saved entry with: git stash list --format='%gd %H %s'") if stash_selector: print(f" Remove it with: git stash drop {stash_selector}") else: - print(f" Look for commit {stash_ref}, then drop its selector with: git stash drop stash@{{N}}") - + print( + f" Look for commit {stash_ref}, then drop its selector with: git stash drop stash@{{N}}" + ) def _restore_stashed_changes( @@ -3537,7 +4176,9 @@ def _restore_stashed_changes( if prompt_user: print() print("⚠ Local changes were stashed before updating.") - print(" Restoring them may reapply local customizations onto the updated codebase.") + print( + " Restoring them may reapply local customizations onto the updated codebase." + ) print(" Review the result afterward if Hermes behaves unexpectedly.") print("Restore local changes now? [Y/n]") if input_fn is not None: @@ -3601,8 +4242,12 @@ def _restore_stashed_changes( stash_selector = _resolve_stash_selector(git_cmd, cwd, stash_ref) if stash_selector is None: - print("⚠ Local changes were restored, but Hermes couldn't find the stash entry to drop.") - print(" The stash was left in place. You can remove it manually after checking the result.") + print( + "⚠ Local changes were restored, but Hermes couldn't find the stash entry to drop." + ) + print( + " The stash was left in place. You can remove it manually after checking the result." + ) _print_stash_cleanup_guidance(stash_ref) else: drop = subprocess.run( @@ -3612,18 +4257,23 @@ def _restore_stashed_changes( text=True, ) if drop.returncode != 0: - print("⚠ Local changes were restored, but Hermes couldn't drop the saved stash entry.") + print( + "⚠ Local changes were restored, but Hermes couldn't drop the saved stash entry." + ) if drop.stdout.strip(): print(drop.stdout.strip()) if drop.stderr.strip(): print(drop.stderr.strip()) - print(" The stash was left in place. You can remove it manually after checking the result.") + print( + " The stash was left in place. You can remove it manually after checking the result." + ) _print_stash_cleanup_guidance(stash_ref, stash_selector) print("⚠ Local changes were restored on top of the updated codebase.") print(" Review `git diff` / `git status` if Hermes behaves unexpectedly.") return True + # ========================================================================= # Fork detection and upstream management for `hermes update` # ========================================================================= @@ -3718,6 +4368,7 @@ def _count_commits_between(git_cmd: list[str], cwd: Path, base: str, head: str) def _should_skip_upstream_prompt() -> bool: """Check if user previously declined to add upstream.""" from hermes_constants import get_hermes_home + return (get_hermes_home() / SKIP_UPSTREAM_PROMPT_FILE).exists() @@ -3725,6 +4376,7 @@ def _mark_skip_upstream_prompt(): """Create marker file to skip future upstream prompts.""" try: from hermes_constants import get_hermes_home + (get_hermes_home() / SKIP_UPSTREAM_PROMPT_FILE).touch() except Exception: pass @@ -3769,7 +4421,9 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path) -> None: print(" This means you may miss updates from NousResearch/hermes-agent.") print() try: - response = input("Add official repo as 'upstream' remote? [Y/n]: ").strip().lower() + response = ( + input("Add official repo as 'upstream' remote? [Y/n]: ").strip().lower() + ) except (EOFError, KeyboardInterrupt): print() response = "n" @@ -3777,13 +4431,17 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path) -> None: if response in ("", "y", "yes"): print("→ Adding upstream remote...") if _add_upstream_remote(git_cmd, cwd): - print(" ✓ Added upstream: https://github.com/NousResearch/hermes-agent.git") + print( + " ✓ Added upstream: https://github.com/NousResearch/hermes-agent.git" + ) has_upstream = True else: print(" ✗ Failed to add upstream remote. Skipping upstream sync.") return else: - print(" Skipped. Run 'git remote add upstream https://github.com/NousResearch/hermes-agent.git' to add later.") + print( + " Skipped. Run 'git remote add upstream https://github.com/NousResearch/hermes-agent.git' to add later." + ) _mark_skip_upstream_prompt() return @@ -3803,7 +4461,9 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path) -> None: # Compare origin/main with upstream/main origin_ahead = _count_commits_between(git_cmd, cwd, "upstream/main", "origin/main") - upstream_ahead = _count_commits_between(git_cmd, cwd, "origin/main", "upstream/main") + upstream_ahead = _count_commits_between( + git_cmd, cwd, "origin/main", "upstream/main" + ) if origin_ahead < 0 or upstream_ahead < 0: print(" ✗ Could not compare branches. Skipping upstream sync.") @@ -3835,7 +4495,9 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path) -> None: check=True, ) except subprocess.CalledProcessError: - print(" ✗ Failed to pull from upstream. You may need to resolve conflicts manually.") + print( + " ✗ Failed to pull from upstream. You may need to resolve conflicts manually." + ) return print(" ✓ Updated from upstream") @@ -3845,7 +4507,9 @@ def _sync_with_upstream_if_needed(git_cmd: list[str], cwd: Path) -> None: if _sync_fork_with_upstream(git_cmd, cwd): print(" ✓ Fork synced with upstream") else: - print(" ℹ Got updates from upstream but couldn't push to fork (no write access?)") + print( + " ℹ Got updates from upstream but couldn't push to fork (no write access?)" + ) print(" Your local repo is updated, but your fork on GitHub may be behind.") @@ -3859,6 +4523,7 @@ def _invalidate_update_cache(): homes = [] # Default profile home (Docker-aware — uses /opt/data in Docker) from hermes_constants import get_default_hermes_root + default_home = get_default_hermes_root() homes.append(default_home) # Named profiles under /profiles/ @@ -3886,6 +4551,7 @@ def _load_installable_optional_extras() -> list[str]: """ try: import tomllib + with (PROJECT_ROOT / "pyproject.toml").open("rb") as handle: project = tomllib.load(handle).get("project", {}) except Exception: @@ -3908,7 +4574,6 @@ def _load_installable_optional_extras() -> list[str]: return referenced - def _install_python_dependencies_with_optional_fallback( install_cmd_prefix: list[str], *, @@ -3924,7 +4589,9 @@ def _install_python_dependencies_with_optional_fallback( ) return except subprocess.CalledProcessError: - print(" ⚠ Optional extras failed, reinstalling base dependencies and retrying extras individually...") + print( + " ⚠ Optional extras failed, reinstalling base dependencies and retrying extras individually..." + ) subprocess.run( install_cmd_prefix + ["install", "-e", ".", "--quiet"], @@ -3948,14 +4615,51 @@ def _install_python_dependencies_with_optional_fallback( failed_extras.append(extra) if installed_extras: - print(f" ✓ Reinstalled optional extras individually: {', '.join(installed_extras)}") + print( + f" ✓ Reinstalled optional extras individually: {', '.join(installed_extras)}" + ) if failed_extras: - print(f" ⚠ Skipped optional extras that still failed: {', '.join(failed_extras)}") + print( + f" ⚠ Skipped optional extras that still failed: {', '.join(failed_extras)}" + ) + + +def _update_node_dependencies() -> None: + npm = shutil.which("npm") + if not npm: + return + + paths = ( + ("repo root", PROJECT_ROOT), + ("ui-tui", PROJECT_ROOT / "ui-tui"), + ) + if not any((path / "package.json").exists() for _, path in paths): + return + + print("→ Updating Node.js dependencies...") + for label, path in paths: + if not (path / "package.json").exists(): + continue + + result = subprocess.run( + [npm, "install", "--silent", "--no-fund", "--no-audit", "--progress=false"], + cwd=path, + capture_output=True, + text=True, + check=False, + ) + if result.returncode == 0: + print(f" ✓ {label}") + continue + + print(f" ⚠ npm install failed in {label}") + stderr = (result.stderr or "").strip() + if stderr: + print(f" {stderr.splitlines()[-1]}") def cmd_update(args): """Update Hermes Agent to the latest version.""" - import shutil from hermes_cli.config import is_managed, managed_error if is_managed(): @@ -3964,30 +4668,45 @@ def cmd_update(args): gateway_mode = getattr(args, "gateway", False) # In gateway mode, use file-based IPC for prompts instead of stdin - gw_input_fn = (lambda prompt, default="": _gateway_prompt(prompt, default)) if gateway_mode else None - + gw_input_fn = ( + (lambda prompt, default="": _gateway_prompt(prompt, default)) + if gateway_mode + else None + ) + print("⚕ Updating Hermes Agent...") print() - + # Try git-based update first, fall back to ZIP download on Windows # when git file I/O is broken (antivirus, NTFS filter drivers, etc.) use_zip_update = False - git_dir = PROJECT_ROOT / '.git' - + git_dir = PROJECT_ROOT / ".git" + if not git_dir.exists(): if sys.platform == "win32": use_zip_update = True else: print("✗ Not a git repository. Please reinstall:") - print(" curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash") + print( + " curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash" + ) sys.exit(1) - + # On Windows, git can fail with "unable to write loose object file: Invalid argument" # due to filesystem atomicity issues. Set the recommended workaround. if sys.platform == "win32" and git_dir.exists(): subprocess.run( - ["git", "-c", "windows.appendAtomically=false", "config", "windows.appendAtomically", "false"], - cwd=PROJECT_ROOT, check=False, capture_output=True + [ + "git", + "-c", + "windows.appendAtomically=false", + "config", + "windows.appendAtomically", + "false", + ], + cwd=PROJECT_ROOT, + check=False, + capture_output=True, ) # Build git command once — reused for fork detection and the update itself. @@ -4024,8 +4743,12 @@ def cmd_update(args): if "Could not resolve host" in stderr or "unable to access" in stderr: print("✗ Network error — cannot reach the remote repository.") print(f" {stderr.splitlines()[0]}" if stderr else "") - elif "Authentication failed" in stderr or "could not read Username" in stderr: - print("✗ Authentication failed — check your git credentials or SSH key.") + elif ( + "Authentication failed" in stderr or "could not read Username" in stderr + ): + print( + "✗ Authentication failed — check your git credentials or SSH key." + ) else: print(f"✗ Failed to fetch updates from origin.") if stderr: @@ -4047,7 +4770,11 @@ def cmd_update(args): # If user is on a non-main branch or detached HEAD, switch to main if current_branch != "main": - label = "detached HEAD" if current_branch == "HEAD" else f"branch '{current_branch}'" + label = ( + "detached HEAD" + if current_branch == "HEAD" + else f"branch '{current_branch}'" + ) print(f" ⚠ Currently on {label} — switching to main for update...") # Stash before checkout so uncommitted work isn't lost auto_stash_ref = _stash_local_changes_if_needed(git_cmd, PROJECT_ROOT) @@ -4080,14 +4807,19 @@ def cmd_update(args): # Restore stash and switch back to original branch if we moved if auto_stash_ref is not None: _restore_stashed_changes( - git_cmd, PROJECT_ROOT, auto_stash_ref, + git_cmd, + PROJECT_ROOT, + auto_stash_ref, prompt_user=prompt_for_restore, input_fn=gw_input_fn, ) if current_branch not in ("main", "HEAD"): subprocess.run( git_cmd + ["checkout", current_branch], - cwd=PROJECT_ROOT, capture_output=True, text=True, check=False, + cwd=PROJECT_ROOT, + capture_output=True, + text=True, + check=False, ) print("✓ Already up to date!") return @@ -4107,7 +4839,9 @@ def cmd_update(args): # ff-only failed — local and remote have diverged (e.g. upstream # force-pushed or rebase). Since local changes are already # stashed, reset to match the remote exactly. - print(" ⚠ Fast-forward not possible (history diverged), resetting to match remote...") + print( + " ⚠ Fast-forward not possible (history diverged), resetting to match remote..." + ) reset_result = subprocess.run( git_cmd + ["reset", "--hard", f"origin/{branch}"], cwd=PROJECT_ROOT, @@ -4118,7 +4852,9 @@ def cmd_update(args): print(f"✗ Failed to reset to origin/{branch}.") if reset_result.stderr.strip(): print(f" {reset_result.stderr.strip()}") - print(" Try manually: git fetch origin && git reset --hard origin/main") + print( + " Try manually: git fetch origin && git reset --hard origin/main" + ) sys.exit(1) update_succeeded = True finally: @@ -4126,7 +4862,9 @@ def cmd_update(args): # Don't attempt stash restore if the code update itself failed — # working tree is in an unknown state. if not update_succeeded: - print(f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})") + print( + f" ℹ️ Local changes preserved in stash (ref: {auto_stash_ref})" + ) print(f" Restore manually with: git stash apply") else: _restore_stashed_changes( @@ -4136,7 +4874,7 @@ def cmd_update(args): prompt_user=prompt_for_restore, input_fn=gw_input_fn, ) - + _invalidate_update_cache() # Clear stale .pyc bytecode cache — prevents ImportError on gateway @@ -4144,12 +4882,14 @@ def cmd_update(args): # the old bytecode (e.g. get_hermes_home added to hermes_constants). removed = _clear_bytecode_cache(PROJECT_ROOT) if removed: - print(f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}") + print( + f" ✓ Cleared {removed} stale __pycache__ director{'y' if removed == 1 else 'ies'}" + ) # Fork upstream sync logic (only for main branch on forks) if is_fork and branch == "main": _sync_with_upstream_if_needed(git_cmd, PROJECT_ROOT) - + # Reinstall Python dependencies. Prefer .[all], but if one optional extra # breaks on this machine, keep base deps and reinstall the remaining extras # individually so update does not silently strip working capabilities. @@ -4157,7 +4897,9 @@ def cmd_update(args): uv_bin = shutil.which("uv") if uv_bin: uv_env = {**os.environ, "VIRTUAL_ENV": str(PROJECT_ROOT / "venv")} - _install_python_dependencies_with_optional_fallback([uv_bin, "pip"], env=uv_env) + _install_python_dependencies_with_optional_fallback( + [uv_bin, "pip"], env=uv_env + ) else: # Use sys.executable to explicitly call the venv's pip module, # avoiding PEP 668 'externally-managed-environment' errors on Debian/Ubuntu. @@ -4165,7 +4907,12 @@ def cmd_update(args): # ensurepip before trying the editable install. pip_cmd = [sys.executable, "-m", "pip"] try: - subprocess.run(pip_cmd + ["--version"], cwd=PROJECT_ROOT, check=True, capture_output=True) + subprocess.run( + pip_cmd + ["--version"], + cwd=PROJECT_ROOT, + check=True, + capture_output=True, + ) except subprocess.CalledProcessError: subprocess.run( [sys.executable, "-m", "ensurepip", "--upgrade", "--default-pip"], @@ -4173,20 +4920,13 @@ def cmd_update(args): check=True, ) _install_python_dependencies_with_optional_fallback(pip_cmd) - - # Check for Node.js deps - if (PROJECT_ROOT / "package.json").exists(): - import shutil - if shutil.which("npm"): - print("→ Updating Node.js dependencies...") - subprocess.run(["npm", "install", "--silent"], cwd=PROJECT_ROOT, check=False) - # Build web UI frontend (optional — requires npm) + _update_node_dependencies() _build_web_ui(PROJECT_ROOT / "web") print() print("✓ Code updated!") - + # After git pull, source files on disk are newer than cached Python # modules in this process. Reload hermes_constants so that any lazy # import executed below (skills sync, gateway restart) sees new @@ -4194,20 +4934,24 @@ def cmd_update(args): try: import importlib import hermes_constants as _hc + importlib.reload(_hc) except Exception: pass # non-fatal — worst case a lazy import fails gracefully - + # Sync bundled skills (copies new, updates changed, respects user deletions) try: from tools.skills_sync import sync_skills + print() print("→ Syncing bundled skills...") result = sync_skills(quiet=True) if result["copied"]: print(f" + {len(result['copied'])} new: {', '.join(result['copied'])}") if result.get("updated"): - print(f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}") + print( + f" ↑ {len(result['updated'])} updated: {', '.join(result['updated'])}" + ) if result.get("user_modified"): print(f" ~ {len(result['user_modified'])} user-modified (kept)") if result.get("cleaned"): @@ -4219,7 +4963,12 @@ def cmd_update(args): # Sync bundled skills to all other profiles try: - from hermes_cli.profiles import list_profiles, get_active_profile_name, seed_profile_skills + from hermes_cli.profiles import ( + list_profiles, + get_active_profile_name, + seed_profile_skills, + ) + active = get_active_profile_name() other_profiles = [p for p in list_profiles() if p.name != active] if other_profiles: @@ -4233,9 +4982,12 @@ def cmd_update(args): updated = len(r.get("updated", [])) modified = len(r.get("user_modified", [])) parts = [] - if copied: parts.append(f"+{copied} new") - if updated: parts.append(f"↑{updated} updated") - if modified: parts.append(f"~{modified} user-modified") + if copied: + parts.append(f"+{copied} new") + if updated: + parts.append(f"↑{updated} updated") + if modified: + parts.append(f"~{modified} user-modified") status = ", ".join(parts) if parts else "up to date" else: status = "sync failed" @@ -4248,6 +5000,7 @@ def cmd_update(args): # Sync Honcho host blocks to all profiles try: from plugins.memory.honcho.cli import sync_honcho_profiles_quiet + synced = sync_honcho_profiles_quiet() if synced: print(f"\n-> Honcho: synced {synced} profile(s)") @@ -4257,46 +5010,60 @@ def cmd_update(args): # Check for config migrations print() print("→ Checking configuration for new options...") - + from hermes_cli.config import ( - get_missing_env_vars, get_missing_config_fields, - check_config_version, migrate_config + get_missing_env_vars, + get_missing_config_fields, + check_config_version, + migrate_config, ) - + missing_env = get_missing_env_vars(required_only=True) missing_config = get_missing_config_fields() current_ver, latest_ver = check_config_version() - + needs_migration = missing_env or missing_config or current_ver < latest_ver - + if needs_migration: print() if missing_env: - print(f" ⚠️ {len(missing_env)} new required setting(s) need configuration") + print( + f" ⚠️ {len(missing_env)} new required setting(s) need configuration" + ) if missing_config: print(f" ℹ️ {len(missing_config)} new config option(s) available") - + print() if gateway_mode: - response = _gateway_prompt( - "Would you like to configure new options now? [Y/n]", "n" - ).strip().lower() + response = ( + _gateway_prompt( + "Would you like to configure new options now? [Y/n]", "n" + ) + .strip() + .lower() + ) elif not (sys.stdin.isatty() and sys.stdout.isatty()): print(" ℹ Non-interactive session — skipping config migration prompt.") - print(" Run 'hermes config migrate' later to apply any new config/env options.") + print( + " Run 'hermes config migrate' later to apply any new config/env options." + ) response = "n" else: try: - response = input("Would you like to configure them now? [Y/n]: ").strip().lower() + response = ( + input("Would you like to configure them now? [Y/n]: ") + .strip() + .lower() + ) except EOFError: response = "n" - - if response in ('', 'y', 'yes'): + + if response in ("", "y", "yes"): print() # In gateway mode, run auto-migrations only (no input() prompts # for API keys which would hang the detached process). results = migrate_config(interactive=not gateway_mode, quiet=False) - + if results["env_added"] or results["config_added"]: print() print("✓ Configuration updated!") @@ -4307,10 +5074,10 @@ def cmd_update(args): print("Skipped. Run 'hermes config migrate' later to configure.") else: print(" ✓ Configuration is up to date") - + print() print("✓ Update complete!") - + # Write exit code *before* the gateway restart attempt. # When running as ``hermes update --gateway`` (spawned by the gateway's # /update command), this process lives inside the gateway's systemd @@ -4330,13 +5097,15 @@ def cmd_update(args): _exit_code_path.write_text("0") except OSError: pass - + # Auto-restart ALL gateways after update. # The code update (git pull) is shared across all profiles, so every # running gateway needs restarting to pick up the new code. try: from hermes_cli.gateway import ( - is_macos, supports_systemd_services, _ensure_user_systemd_env, + is_macos, + supports_systemd_services, + _ensure_user_systemd_env, find_gateway_pids, _get_service_pids, ) @@ -4353,39 +5122,60 @@ def cmd_update(args): except Exception: pass - for scope, scope_cmd in [("user", ["systemctl", "--user"]), ("system", ["systemctl"])]: + for scope, scope_cmd in [ + ("user", ["systemctl", "--user"]), + ("system", ["systemctl"]), + ]: try: result = subprocess.run( - scope_cmd + ["list-units", "hermes-gateway*", "--plain", "--no-legend", "--no-pager"], - capture_output=True, text=True, timeout=10, + scope_cmd + + [ + "list-units", + "hermes-gateway*", + "--plain", + "--no-legend", + "--no-pager", + ], + capture_output=True, + text=True, + timeout=10, ) for line in result.stdout.strip().splitlines(): parts = line.split() if not parts: continue - unit = parts[0] # e.g. hermes-gateway.service or hermes-gateway-coder.service + unit = parts[ + 0 + ] # e.g. hermes-gateway.service or hermes-gateway-coder.service if not unit.endswith(".service"): continue svc_name = unit.removesuffix(".service") # Check if active check = subprocess.run( scope_cmd + ["is-active", svc_name], - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, ) if check.stdout.strip() == "active": restart = subprocess.run( scope_cmd + ["restart", svc_name], - capture_output=True, text=True, timeout=15, + capture_output=True, + text=True, + timeout=15, ) if restart.returncode == 0: # Verify the service actually survived the # restart. systemctl restart returns 0 even # if the new process crashes immediately. import time as _time + _time.sleep(3) verify = subprocess.run( scope_cmd + ["is-active", svc_name], - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, ) if verify.stdout.strip() == "active": restarted_services.append(svc_name) @@ -4393,15 +5183,21 @@ def cmd_update(args): # Retry once — transient startup failures # (stale module cache, import race) often # resolve on the second attempt. - print(f" ⚠ {svc_name} died after restart, retrying...") + print( + f" ⚠ {svc_name} died after restart, retrying..." + ) retry = subprocess.run( scope_cmd + ["restart", svc_name], - capture_output=True, text=True, timeout=15, + capture_output=True, + text=True, + timeout=15, ) _time.sleep(3) verify2 = subprocess.run( scope_cmd + ["is-active", svc_name], - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, ) if verify2.stdout.strip() == "active": restarted_services.append(svc_name) @@ -4413,19 +5209,28 @@ def cmd_update(args): f" Restart manually: systemctl {'--user ' if scope == 'user' else ''}restart {svc_name}" ) else: - print(f" ⚠ Failed to restart {svc_name}: {restart.stderr.strip()}") + print( + f" ⚠ Failed to restart {svc_name}: {restart.stderr.strip()}" + ) except (FileNotFoundError, subprocess.TimeoutExpired): pass # --- Launchd services (macOS) --- if is_macos(): try: - from hermes_cli.gateway import launchd_restart, get_launchd_label, get_launchd_plist_path + from hermes_cli.gateway import ( + launchd_restart, + get_launchd_label, + get_launchd_plist_path, + ) + plist_path = get_launchd_plist_path() if plist_path.exists(): check = subprocess.run( ["launchctl", "list", get_launchd_label()], - capture_output=True, text=True, timeout=5, + capture_output=True, + text=True, + timeout=5, ) if check.returncode == 0: try: @@ -4442,7 +5247,9 @@ def cmd_update(args): # Exclude PIDs that belong to just-restarted services so we don't # immediately kill the process that systemd/launchd just spawned. service_pids = _get_service_pids() - manual_pids = find_gateway_pids(exclude_pids=service_pids, all_profiles=True) + manual_pids = find_gateway_pids( + exclude_pids=service_pids, all_profiles=True + ) for pid in manual_pids: try: os.kill(pid, _signal.SIGTERM) @@ -4459,7 +5266,9 @@ def cmd_update(args): print(" Restart manually: hermes gateway run") # Also restart for each profile if needed if len(killed_pids) > 1: - print(" (or: hermes -p gateway run for each profile)") + print( + " (or: hermes -p gateway run for each profile)" + ) if not restarted_services and not killed_pids: # No gateways were running — nothing to do @@ -4467,11 +5276,11 @@ def cmd_update(args): except Exception as e: logger.debug("Gateway restart during update failed: %s", e) - + print() print("Tip: You can now select a provider and model:") print(" hermes model # Select provider and model") - + except subprocess.CalledProcessError as e: if sys.platform == "win32": print(f"⚠ Git update failed: {e}") @@ -4495,12 +5304,41 @@ def _coalesce_session_name_args(argv: list) -> list: or a known top-level subcommand. """ _SUBCOMMANDS = { - "chat", "model", "gateway", "setup", "whatsapp", "login", "logout", "auth", - "status", "cron", "doctor", "config", "pairing", "skills", "tools", - "mcp", "sessions", "insights", "version", "update", "uninstall", - "profile", "dashboard", - "honcho", "claw", "plugins", "acp", - "webhook", "memory", "dump", "debug", "backup", "import", "completion", "logs", + "chat", + "model", + "gateway", + "setup", + "whatsapp", + "login", + "logout", + "auth", + "status", + "cron", + "doctor", + "config", + "pairing", + "skills", + "tools", + "mcp", + "sessions", + "insights", + "version", + "update", + "uninstall", + "profile", + "dashboard", + "honcho", + "claw", + "plugins", + "acp", + "webhook", + "memory", + "dump", + "debug", + "backup", + "import", + "completion", + "logs", } _SESSION_FLAGS = {"-c", "--continue", "-r", "--resume"} @@ -4513,7 +5351,11 @@ def _coalesce_session_name_args(argv: list) -> list: i += 1 # Collect subsequent non-flag, non-subcommand tokens as one name parts: list = [] - while i < len(argv) and not argv[i].startswith("-") and argv[i] not in _SUBCOMMANDS: + while ( + i < len(argv) + and not argv[i].startswith("-") + and argv[i] not in _SUBCOMMANDS + ): parts.append(argv[i]) i += 1 if parts: @@ -4527,10 +5369,17 @@ def _coalesce_session_name_args(argv: list) -> list: def cmd_profile(args): """Profile management — create, delete, list, switch, alias.""" from hermes_cli.profiles import ( - list_profiles, create_profile, delete_profile, seed_profile_skills, - set_active_profile, get_active_profile_name, - check_alias_collision, create_wrapper_script, remove_wrapper_script, - _is_wrapper_dir_in_path, _get_wrapper_dir, + list_profiles, + create_profile, + delete_profile, + seed_profile_skills, + set_active_profile, + get_active_profile_name, + check_alias_collision, + create_wrapper_script, + remove_wrapper_script, + _is_wrapper_dir_in_path, + _get_wrapper_dir, ) from hermes_constants import display_hermes_home @@ -4547,8 +5396,13 @@ def cmd_profile(args): for p in profiles: if p.name == profile_name or (profile_name == "default" and p.is_default): if p.model: - print(f"Model: {p.model}" + (f" ({p.provider})" if p.provider else "")) - print(f"Gateway: {'running' if p.gateway_running else 'stopped'}") + print( + f"Model: {p.model}" + + (f" ({p.provider})" if p.provider else "") + ) + print( + f"Gateway: {'running' if p.gateway_running else 'stopped'}" + ) print(f"Skills: {p.skill_count} installed") if p.alias_path: print(f"Alias: {p.name} → hermes -p {p.name}") @@ -4569,7 +5423,11 @@ def cmd_profile(args): print(f" {'─' * 15} {'─' * 27} {'─' * 11} {'─' * 12}") for p in profiles: - marker = " ◆" if (p.name == active or (active == "default" and p.is_default)) else " " + marker = ( + " ◆" + if (p.name == active or (active == "default" and p.is_default)) + else " " + ) name = p.name model = (p.model or "—")[:26] gw = "running" if p.gateway_running else "stopped" @@ -4610,7 +5468,9 @@ def cmd_profile(args): print(f"\nProfile '{name}' created at {profile_dir}") if clone or clone_all: - source_label = getattr(args, "clone_from", None) or get_active_profile_name() + source_label = ( + getattr(args, "clone_from", None) or get_active_profile_name() + ) if clone_all: print(f"Full copy from {source_label}.") else: @@ -4620,6 +5480,7 @@ def cmd_profile(args): if clone or clone_all: try: from plugins.memory.honcho.cli import clone_honcho_for_profile + if clone_honcho_for_profile(name): print(f"Honcho config cloned (peer: {name})") except Exception: @@ -4632,14 +5493,20 @@ def cmd_profile(args): copied = len(result.get("copied", [])) print(f"{copied} bundled skills synced.") else: - print("⚠ Skills could not be seeded. Run `{} update` to retry.".format(name)) + print( + "⚠ Skills could not be seeded. Run `{} update` to retry.".format( + name + ) + ) # Create wrapper alias if not no_alias: collision = check_alias_collision(name) if collision: print(f"\n⚠ Cannot create alias '{name}' — {collision}") - print(f" Choose a custom alias: hermes profile alias {name} --name ") + print( + f" Choose a custom alias: hermes profile alias {name} --name " + ) print(f" Or access via flag: hermes -p {name} chat") else: wrapper_path = create_wrapper_script(name) @@ -4647,7 +5514,9 @@ def cmd_profile(args): print(f"Wrapper created: {wrapper_path}") if not _is_wrapper_dir_in_path(): print(f"\n⚠ {_get_wrapper_dir()} is not in your PATH.") - print(f' Add to your shell config (~/.bashrc or ~/.zshrc):') + print( + f" Add to your shell config (~/.bashrc or ~/.zshrc):" + ) print(f' export PATH="$HOME/.local/bin:$PATH"') # Profile dir for display @@ -4665,7 +5534,9 @@ def cmd_profile(args): print(f"\n Edit {profile_dir_display}/.env for different API keys") print(f" Edit {profile_dir_display}/SOUL.md for different personality") else: - print(f"\n ⚠ This profile has no API keys yet. Run '{name} setup' first,") + print( + f"\n ⚠ This profile has no API keys yet. Run '{name} setup' first," + ) print(f" or it will inherit keys from your shell environment.") print(f" Edit {profile_dir_display}/SOUL.md to customize personality") print() @@ -4685,7 +5556,14 @@ def cmd_profile(args): elif action == "show": name = args.profile_name - from hermes_cli.profiles import get_profile_dir, profile_exists, _read_config_model, _check_gateway_running, _count_skills + from hermes_cli.profiles import ( + get_profile_dir, + profile_exists, + _read_config_model, + _check_gateway_running, + _count_skills, + ) + if not profile_exists(name): print(f"Error: Profile '{name}' does not exist.") sys.exit(1) @@ -4701,8 +5579,12 @@ def cmd_profile(args): print(f"Model: {model}" + (f" ({provider})" if provider else "")) print(f"Gateway: {'running' if gw else 'stopped'}") print(f"Skills: {skills}") - print(f".env: {'exists' if (profile_dir / '.env').exists() else 'not configured'}") - print(f"SOUL.md: {'exists' if (profile_dir / 'SOUL.md').exists() else 'not configured'}") + print( + f".env: {'exists' if (profile_dir / '.env').exists() else 'not configured'}" + ) + print( + f"SOUL.md: {'exists' if (profile_dir / 'SOUL.md').exists() else 'not configured'}" + ) if wrapper.exists(): print(f"Alias: {wrapper}") print() @@ -4713,6 +5595,7 @@ def cmd_profile(args): custom_name = getattr(args, "alias_name", None) from hermes_cli.profiles import profile_exists + if not profile_exists(name): print(f"Error: Profile '{name}' does not exist.") sys.exit(1) @@ -4740,6 +5623,7 @@ def cmd_profile(args): elif action == "rename": from hermes_cli.profiles import rename_profile + try: new_dir = rename_profile(args.old_name, args.new_name) print(f"\nProfile renamed: {args.old_name} → {args.new_name}") @@ -4750,6 +5634,7 @@ def cmd_profile(args): elif action == "export": from hermes_cli.profiles import export_profile + name = args.profile_name output = args.output or f"{name}.tar.gz" try: @@ -4761,8 +5646,11 @@ def cmd_profile(args): elif action == "import": from hermes_cli.profiles import import_profile + try: - profile_dir = import_profile(args.archive, name=getattr(args, "import_name", None)) + profile_dir = import_profile( + args.archive, name=getattr(args, "import_name", None) + ) name = profile_dir.name print(f"✓ Imported profile '{name}' at {profile_dir}") @@ -4792,6 +5680,7 @@ def cmd_dashboard(args): sys.exit(1) from hermes_cli.web_server import start_server + start_server( host=args.host, port=args.port, @@ -4803,6 +5692,7 @@ def cmd_dashboard(args): def cmd_completion(args, parser=None): """Print shell completion script.""" from hermes_cli.completion import generate_bash, generate_zsh, generate_fish + shell = getattr(args, "shell", "bash") if shell == "zsh": print(generate_zsh(parser)) @@ -4872,152 +5762,200 @@ Examples: For more help on a command: hermes --help -""" +""", ) - + parser.add_argument( - "--version", "-V", - action="store_true", - help="Show version and exit" + "--version", "-V", action="store_true", help="Show version and exit" ) parser.add_argument( - "--resume", "-r", + "--resume", + "-r", metavar="SESSION", default=None, - help="Resume a previous session by ID or title" + help="Resume a previous session by ID or title", ) parser.add_argument( - "--continue", "-c", + "--continue", + "-c", dest="continue_last", nargs="?", const=True, default=None, metavar="SESSION_NAME", - help="Resume a session by name, or the most recent if no name given" + help="Resume a session by name, or the most recent if no name given", ) parser.add_argument( - "--worktree", "-w", + "--worktree", + "-w", action="store_true", default=False, - help="Run in an isolated git worktree (for parallel agents)" + help="Run in an isolated git worktree (for parallel agents)", ) parser.add_argument( - "--skills", "-s", + "--skills", + "-s", action="append", default=None, - help="Preload one or more skills for the session (repeat flag or comma-separate)" + help="Preload one or more skills for the session (repeat flag or comma-separate)", ) parser.add_argument( "--yolo", action="store_true", default=False, - help="Bypass all dangerous command approval prompts (use at your own risk)" + help="Bypass all dangerous command approval prompts (use at your own risk)", ) parser.add_argument( "--pass-session-id", action="store_true", default=False, - help="Include the session ID in the agent's system prompt" + help="Include the session ID in the agent's system prompt", ) - + parser.add_argument( + "--tui", + action="store_true", + default=False, + help="Launch the modern TUI instead of the classic REPL", + ) + parser.add_argument( + "--dev", + dest="tui_dev", + action="store_true", + default=False, + help="With --tui: run TypeScript sources via tsx (skip dist build)", + ) + subparsers = parser.add_subparsers(dest="command", help="Command to run") - + # ========================================================================= # chat command # ========================================================================= chat_parser = subparsers.add_parser( "chat", help="Interactive chat with the agent", - description="Start an interactive chat session with Hermes Agent" + description="Start an interactive chat session with Hermes Agent", ) chat_parser.add_argument( - "-q", "--query", - help="Single query (non-interactive mode)" + "-q", "--query", help="Single query (non-interactive mode)" ) chat_parser.add_argument( - "--image", - help="Optional local image path to attach to a single query" + "--image", help="Optional local image path to attach to a single query" ) chat_parser.add_argument( - "-m", "--model", - help="Model to use (e.g., anthropic/claude-sonnet-4)" + "-m", "--model", help="Model to use (e.g., anthropic/claude-sonnet-4)" ) chat_parser.add_argument( - "-t", "--toolsets", - help="Comma-separated toolsets to enable" + "-t", "--toolsets", help="Comma-separated toolsets to enable" ) chat_parser.add_argument( - "-s", "--skills", + "-s", + "--skills", action="append", default=argparse.SUPPRESS, - help="Preload one or more skills for the session (repeat flag or comma-separate)" + help="Preload one or more skills for the session (repeat flag or comma-separate)", ) chat_parser.add_argument( "--provider", - choices=["auto", "openrouter", "nous", "openai-codex", "copilot-acp", "copilot", "anthropic", "gemini", "xai", "ollama-cloud", "huggingface", "zai", "kimi-coding", "kimi-coding-cn", "minimax", "minimax-cn", "kilocode", "xiaomi", "arcee", "nvidia"], + choices=[ + "auto", + "openrouter", + "nous", + "openai-codex", + "copilot-acp", + "copilot", + "anthropic", + "gemini", + "xai", + "ollama-cloud", + "huggingface", + "zai", + "kimi-coding", + "kimi-coding-cn", + "minimax", + "minimax-cn", + "kilocode", + "xiaomi", + "arcee", + "nvidia", + ], default=None, - help="Inference provider (default: auto)" + help="Inference provider (default: auto)", ) chat_parser.add_argument( - "-v", "--verbose", + "-v", "--verbose", action="store_true", help="Verbose output" + ) + chat_parser.add_argument( + "-Q", + "--quiet", action="store_true", - help="Verbose output" + help="Quiet mode for programmatic use: suppress banner, spinner, and tool previews. Only output the final response and session info.", ) chat_parser.add_argument( - "-Q", "--quiet", - action="store_true", - help="Quiet mode for programmatic use: suppress banner, spinner, and tool previews. Only output the final response and session info." - ) - chat_parser.add_argument( - "--resume", "-r", + "--resume", + "-r", metavar="SESSION_ID", default=argparse.SUPPRESS, - help="Resume a previous session by ID (shown on exit)" + help="Resume a previous session by ID (shown on exit)", ) chat_parser.add_argument( - "--continue", "-c", + "--continue", + "-c", dest="continue_last", nargs="?", const=True, default=argparse.SUPPRESS, metavar="SESSION_NAME", - help="Resume a session by name, or the most recent if no name given" + help="Resume a session by name, or the most recent if no name given", ) chat_parser.add_argument( - "--worktree", "-w", + "--worktree", + "-w", action="store_true", default=argparse.SUPPRESS, - help="Run in an isolated git worktree (for parallel agents on the same repo)" + help="Run in an isolated git worktree (for parallel agents on the same repo)", ) chat_parser.add_argument( "--checkpoints", action="store_true", default=False, - help="Enable filesystem checkpoints before destructive file operations (use /rollback to restore)" + help="Enable filesystem checkpoints before destructive file operations (use /rollback to restore)", ) chat_parser.add_argument( "--max-turns", type=int, default=None, metavar="N", - help="Maximum tool-calling iterations per conversation turn (default: 90, or agent.max_turns in config)" + help="Maximum tool-calling iterations per conversation turn (default: 90, or agent.max_turns in config)", ) chat_parser.add_argument( "--yolo", action="store_true", default=argparse.SUPPRESS, - help="Bypass all dangerous command approval prompts (use at your own risk)" + help="Bypass all dangerous command approval prompts (use at your own risk)", ) chat_parser.add_argument( "--pass-session-id", action="store_true", default=argparse.SUPPRESS, - help="Include the session ID in the agent's system prompt" + help="Include the session ID in the agent's system prompt", ) chat_parser.add_argument( "--source", default=None, - help="Session source tag for filtering (default: cli). Use 'tool' for third-party integrations that should not appear in user session lists." + help="Session source tag for filtering (default: cli). Use 'tool' for third-party integrations that should not appear in user session lists.", + ) + chat_parser.add_argument( + "--tui", + action="store_true", + default=False, + help="Launch the modern TUI instead of the classic REPL", + ) + chat_parser.add_argument( + "--dev", + dest="tui_dev", + action="store_true", + default=False, + help="With --tui: run TypeScript sources via tsx (skip dist build)", ) chat_parser.set_defaults(func=cmd_chat) @@ -5027,45 +5965,42 @@ For more help on a command: model_parser = subparsers.add_parser( "model", help="Select default model and provider", - description="Interactively select your inference provider and default model" + description="Interactively select your inference provider and default model", ) model_parser.add_argument( "--portal-url", - help="Portal base URL for Nous login (default: production portal)" + help="Portal base URL for Nous login (default: production portal)", ) model_parser.add_argument( "--inference-url", - help="Inference API base URL for Nous login (default: production inference API)" + help="Inference API base URL for Nous login (default: production inference API)", ) model_parser.add_argument( "--client-id", default=None, - help="OAuth client id to use for Nous login (default: hermes-cli)" + help="OAuth client id to use for Nous login (default: hermes-cli)", ) model_parser.add_argument( - "--scope", - default=None, - help="OAuth scope to request for Nous login" + "--scope", default=None, help="OAuth scope to request for Nous login" ) model_parser.add_argument( "--no-browser", action="store_true", - help="Do not attempt to open the browser automatically during Nous login" + help="Do not attempt to open the browser automatically during Nous login", ) model_parser.add_argument( "--timeout", type=float, default=15.0, - help="HTTP request timeout in seconds for Nous login (default: 15)" + help="HTTP request timeout in seconds for Nous login (default: 15)", ) model_parser.add_argument( - "--ca-bundle", - help="Path to CA bundle PEM file for Nous TLS verification" + "--ca-bundle", help="Path to CA bundle PEM file for Nous TLS verification" ) model_parser.add_argument( "--insecure", action="store_true", - help="Disable TLS verification for Nous login (testing only)" + help="Disable TLS verification for Nous login (testing only)", ) model_parser.set_defaults(func=cmd_model) @@ -5075,54 +6010,113 @@ For more help on a command: gateway_parser = subparsers.add_parser( "gateway", help="Messaging gateway management", - description="Manage the messaging gateway (Telegram, Discord, WhatsApp)" + description="Manage the messaging gateway (Telegram, Discord, WhatsApp)", ) gateway_subparsers = gateway_parser.add_subparsers(dest="gateway_command") - + # gateway run (default) - gateway_run = gateway_subparsers.add_parser("run", help="Run gateway in foreground (recommended for WSL, Docker, Termux)") - gateway_run.add_argument("-v", "--verbose", action="count", default=0, - help="Increase stderr log verbosity (-v=INFO, -vv=DEBUG)") - gateway_run.add_argument("-q", "--quiet", action="store_true", - help="Suppress all stderr log output") - gateway_run.add_argument("--replace", action="store_true", - help="Replace any existing gateway instance (useful for systemd)") - + gateway_run = gateway_subparsers.add_parser( + "run", help="Run gateway in foreground (recommended for WSL, Docker, Termux)" + ) + gateway_run.add_argument( + "-v", + "--verbose", + action="count", + default=0, + help="Increase stderr log verbosity (-v=INFO, -vv=DEBUG)", + ) + gateway_run.add_argument( + "-q", "--quiet", action="store_true", help="Suppress all stderr log output" + ) + gateway_run.add_argument( + "--replace", + action="store_true", + help="Replace any existing gateway instance (useful for systemd)", + ) + # gateway start - gateway_start = gateway_subparsers.add_parser("start", help="Start the installed systemd/launchd background service") - gateway_start.add_argument("--system", action="store_true", help="Target the Linux system-level gateway service") - gateway_start.add_argument("--all", action="store_true", help="Kill ALL stale gateway processes across all profiles before starting") - + gateway_start = gateway_subparsers.add_parser( + "start", help="Start the installed systemd/launchd background service" + ) + gateway_start.add_argument( + "--system", + action="store_true", + help="Target the Linux system-level gateway service", + ) + gateway_start.add_argument( + "--all", + action="store_true", + help="Kill ALL stale gateway processes across all profiles before starting", + ) + # gateway stop gateway_stop = gateway_subparsers.add_parser("stop", help="Stop gateway service") - gateway_stop.add_argument("--system", action="store_true", help="Target the Linux system-level gateway service") - gateway_stop.add_argument("--all", action="store_true", help="Stop ALL gateway processes across all profiles") - + gateway_stop.add_argument( + "--system", + action="store_true", + help="Target the Linux system-level gateway service", + ) + gateway_stop.add_argument( + "--all", + action="store_true", + help="Stop ALL gateway processes across all profiles", + ) + # gateway restart - gateway_restart = gateway_subparsers.add_parser("restart", help="Restart gateway service") - gateway_restart.add_argument("--system", action="store_true", help="Target the Linux system-level gateway service") - gateway_restart.add_argument("--all", action="store_true", help="Kill ALL gateway processes across all profiles before restarting") - + gateway_restart = gateway_subparsers.add_parser( + "restart", help="Restart gateway service" + ) + gateway_restart.add_argument( + "--system", + action="store_true", + help="Target the Linux system-level gateway service", + ) + gateway_restart.add_argument( + "--all", + action="store_true", + help="Kill ALL gateway processes across all profiles before restarting", + ) + # gateway status gateway_status = gateway_subparsers.add_parser("status", help="Show gateway status") gateway_status.add_argument("--deep", action="store_true", help="Deep status check") - gateway_status.add_argument("--system", action="store_true", help="Target the Linux system-level gateway service") - + gateway_status.add_argument( + "--system", + action="store_true", + help="Target the Linux system-level gateway service", + ) + # gateway install - gateway_install = gateway_subparsers.add_parser("install", help="Install gateway as a systemd/launchd background service") + gateway_install = gateway_subparsers.add_parser( + "install", help="Install gateway as a systemd/launchd background service" + ) gateway_install.add_argument("--force", action="store_true", help="Force reinstall") - gateway_install.add_argument("--system", action="store_true", help="Install as a Linux system-level service (starts at boot)") - gateway_install.add_argument("--run-as-user", dest="run_as_user", help="User account the Linux system service should run as") - + gateway_install.add_argument( + "--system", + action="store_true", + help="Install as a Linux system-level service (starts at boot)", + ) + gateway_install.add_argument( + "--run-as-user", + dest="run_as_user", + help="User account the Linux system service should run as", + ) + # gateway uninstall - gateway_uninstall = gateway_subparsers.add_parser("uninstall", help="Uninstall gateway service") - gateway_uninstall.add_argument("--system", action="store_true", help="Target the Linux system-level gateway service") + gateway_uninstall = gateway_subparsers.add_parser( + "uninstall", help="Uninstall gateway service" + ) + gateway_uninstall.add_argument( + "--system", + action="store_true", + help="Target the Linux system-level gateway service", + ) # gateway setup gateway_subparsers.add_parser("setup", help="Configure messaging platforms") gateway_parser.set_defaults(func=cmd_gateway) - + # ========================================================================= # setup command # ========================================================================= @@ -5130,24 +6124,22 @@ For more help on a command: "setup", help="Interactive setup wizard", description="Configure Hermes Agent with an interactive wizard. " - "Run a specific section: hermes setup model|tts|terminal|gateway|tools|agent" + "Run a specific section: hermes setup model|tts|terminal|gateway|tools|agent", ) setup_parser.add_argument( "section", nargs="?", choices=["model", "tts", "terminal", "gateway", "tools", "agent"], default=None, - help="Run a specific setup section instead of the full wizard" + help="Run a specific setup section instead of the full wizard", ) setup_parser.add_argument( "--non-interactive", action="store_true", - help="Non-interactive mode (use defaults/env vars)" + help="Non-interactive mode (use defaults/env vars)", ) setup_parser.add_argument( - "--reset", - action="store_true", - help="Reset configuration to defaults" + "--reset", action="store_true", help="Reset configuration to defaults" ) setup_parser.set_defaults(func=cmd_setup) @@ -5157,7 +6149,7 @@ For more help on a command: whatsapp_parser = subparsers.add_parser( "whatsapp", help="Set up WhatsApp integration", - description="Configure WhatsApp and pair via QR code" + description="Configure WhatsApp and pair via QR code", ) whatsapp_parser.set_defaults(func=cmd_whatsapp) @@ -5167,51 +6159,43 @@ For more help on a command: login_parser = subparsers.add_parser( "login", help="Authenticate with an inference provider", - description="Run OAuth device authorization flow for Hermes CLI" + description="Run OAuth device authorization flow for Hermes CLI", ) login_parser.add_argument( "--provider", choices=["nous", "openai-codex"], default=None, - help="Provider to authenticate with (default: nous)" + help="Provider to authenticate with (default: nous)", ) login_parser.add_argument( - "--portal-url", - help="Portal base URL (default: production portal)" + "--portal-url", help="Portal base URL (default: production portal)" ) login_parser.add_argument( "--inference-url", - help="Inference API base URL (default: production inference API)" + help="Inference API base URL (default: production inference API)", ) login_parser.add_argument( - "--client-id", - default=None, - help="OAuth client id to use (default: hermes-cli)" - ) - login_parser.add_argument( - "--scope", - default=None, - help="OAuth scope to request" + "--client-id", default=None, help="OAuth client id to use (default: hermes-cli)" ) + login_parser.add_argument("--scope", default=None, help="OAuth scope to request") login_parser.add_argument( "--no-browser", action="store_true", - help="Do not attempt to open the browser automatically" + help="Do not attempt to open the browser automatically", ) login_parser.add_argument( "--timeout", type=float, default=15.0, - help="HTTP request timeout in seconds (default: 15)" + help="HTTP request timeout in seconds (default: 15)", ) login_parser.add_argument( - "--ca-bundle", - help="Path to CA bundle PEM file for TLS verification" + "--ca-bundle", help="Path to CA bundle PEM file for TLS verification" ) login_parser.add_argument( "--insecure", action="store_true", - help="Disable TLS verification (testing only)" + help="Disable TLS verification (testing only)", ) login_parser.set_defaults(func=cmd_login) @@ -5221,13 +6205,13 @@ For more help on a command: logout_parser = subparsers.add_parser( "logout", help="Clear authentication for an inference provider", - description="Remove stored credentials and reset provider config" + description="Remove stored credentials and reset provider config", ) logout_parser.add_argument( "--provider", choices=["nous", "openai-codex"], default=None, - help="Provider to log out from (default: active provider)" + help="Provider to log out from (default: active provider)", ) logout_parser.set_defaults(func=cmd_logout) @@ -5237,24 +6221,50 @@ For more help on a command: ) auth_subparsers = auth_parser.add_subparsers(dest="auth_action") auth_add = auth_subparsers.add_parser("add", help="Add a pooled credential") - auth_add.add_argument("provider", help="Provider id (for example: anthropic, openai-codex, openrouter)") - auth_add.add_argument("--type", dest="auth_type", choices=["oauth", "api-key", "api_key"], help="Credential type to add") + auth_add.add_argument( + "provider", + help="Provider id (for example: anthropic, openai-codex, openrouter)", + ) + auth_add.add_argument( + "--type", + dest="auth_type", + choices=["oauth", "api-key", "api_key"], + help="Credential type to add", + ) auth_add.add_argument("--label", help="Optional display label") - auth_add.add_argument("--api-key", help="API key value (otherwise prompted securely)") + auth_add.add_argument( + "--api-key", help="API key value (otherwise prompted securely)" + ) auth_add.add_argument("--portal-url", help="Nous portal base URL") auth_add.add_argument("--inference-url", help="Nous inference base URL") auth_add.add_argument("--client-id", help="OAuth client id") auth_add.add_argument("--scope", help="OAuth scope override") - auth_add.add_argument("--no-browser", action="store_true", help="Do not auto-open a browser for OAuth login") - auth_add.add_argument("--timeout", type=float, help="OAuth/network timeout in seconds") - auth_add.add_argument("--insecure", action="store_true", help="Disable TLS verification for OAuth login") + auth_add.add_argument( + "--no-browser", + action="store_true", + help="Do not auto-open a browser for OAuth login", + ) + auth_add.add_argument( + "--timeout", type=float, help="OAuth/network timeout in seconds" + ) + auth_add.add_argument( + "--insecure", + action="store_true", + help="Disable TLS verification for OAuth login", + ) auth_add.add_argument("--ca-bundle", help="Custom CA bundle for OAuth login") auth_list = auth_subparsers.add_parser("list", help="List pooled credentials") auth_list.add_argument("provider", nargs="?", help="Optional provider filter") - auth_remove = auth_subparsers.add_parser("remove", help="Remove a pooled credential by index, id, or label") + auth_remove = auth_subparsers.add_parser( + "remove", help="Remove a pooled credential by index, id, or label" + ) auth_remove.add_argument("provider", help="Provider id") - auth_remove.add_argument("target", help="Credential index, entry id, or exact label") - auth_reset = auth_subparsers.add_parser("reset", help="Clear exhaustion status for all credentials for a provider") + auth_remove.add_argument( + "target", help="Credential index, entry id, or exact label" + ) + auth_reset = auth_subparsers.add_parser( + "reset", help="Clear exhaustion status for all credentials for a provider" + ) auth_reset.add_argument("provider", help="Provider id") auth_parser.set_defaults(func=cmd_auth) @@ -5264,57 +6274,92 @@ For more help on a command: status_parser = subparsers.add_parser( "status", help="Show status of all components", - description="Display status of Hermes Agent components" + description="Display status of Hermes Agent components", ) status_parser.add_argument( - "--all", - action="store_true", - help="Show all details (redacted for sharing)" + "--all", action="store_true", help="Show all details (redacted for sharing)" ) status_parser.add_argument( - "--deep", - action="store_true", - help="Run deep checks (may take longer)" + "--deep", action="store_true", help="Run deep checks (may take longer)" ) status_parser.set_defaults(func=cmd_status) - + # ========================================================================= # cron command # ========================================================================= cron_parser = subparsers.add_parser( - "cron", - help="Cron job management", - description="Manage scheduled tasks" + "cron", help="Cron job management", description="Manage scheduled tasks" ) cron_subparsers = cron_parser.add_subparsers(dest="cron_command") - + # cron list cron_list = cron_subparsers.add_parser("list", help="List scheduled jobs") cron_list.add_argument("--all", action="store_true", help="Include disabled jobs") # cron create/add - cron_create = cron_subparsers.add_parser("create", aliases=["add"], help="Create a scheduled job") - cron_create.add_argument("schedule", help="Schedule like '30m', 'every 2h', or '0 9 * * *'") - cron_create.add_argument("prompt", nargs="?", help="Optional self-contained prompt or task instruction") + cron_create = cron_subparsers.add_parser( + "create", aliases=["add"], help="Create a scheduled job" + ) + cron_create.add_argument( + "schedule", help="Schedule like '30m', 'every 2h', or '0 9 * * *'" + ) + cron_create.add_argument( + "prompt", nargs="?", help="Optional self-contained prompt or task instruction" + ) cron_create.add_argument("--name", help="Optional human-friendly job name") - cron_create.add_argument("--deliver", help="Delivery target: origin, local, telegram, discord, signal, or platform:chat_id") + cron_create.add_argument( + "--deliver", + help="Delivery target: origin, local, telegram, discord, signal, or platform:chat_id", + ) cron_create.add_argument("--repeat", type=int, help="Optional repeat count") - cron_create.add_argument("--skill", dest="skills", action="append", help="Attach a skill. Repeat to add multiple skills.") - cron_create.add_argument("--script", help="Path to a Python script whose stdout is injected into the prompt each run") + cron_create.add_argument( + "--skill", + dest="skills", + action="append", + help="Attach a skill. Repeat to add multiple skills.", + ) + cron_create.add_argument( + "--script", + help="Path to a Python script whose stdout is injected into the prompt each run", + ) # cron edit - cron_edit = cron_subparsers.add_parser("edit", help="Edit an existing scheduled job") + cron_edit = cron_subparsers.add_parser( + "edit", help="Edit an existing scheduled job" + ) cron_edit.add_argument("job_id", help="Job ID to edit") cron_edit.add_argument("--schedule", help="New schedule") cron_edit.add_argument("--prompt", help="New prompt/task instruction") cron_edit.add_argument("--name", help="New job name") cron_edit.add_argument("--deliver", help="New delivery target") cron_edit.add_argument("--repeat", type=int, help="New repeat count") - cron_edit.add_argument("--skill", dest="skills", action="append", help="Replace the job's skills with this set. Repeat to attach multiple skills.") - cron_edit.add_argument("--add-skill", dest="add_skills", action="append", help="Append a skill without replacing the existing list. Repeatable.") - cron_edit.add_argument("--remove-skill", dest="remove_skills", action="append", help="Remove a specific attached skill. Repeatable.") - cron_edit.add_argument("--clear-skills", action="store_true", help="Remove all attached skills from the job") - cron_edit.add_argument("--script", help="Path to a Python script whose stdout is injected into the prompt each run. Pass empty string to clear.") + cron_edit.add_argument( + "--skill", + dest="skills", + action="append", + help="Replace the job's skills with this set. Repeat to attach multiple skills.", + ) + cron_edit.add_argument( + "--add-skill", + dest="add_skills", + action="append", + help="Append a skill without replacing the existing list. Repeatable.", + ) + cron_edit.add_argument( + "--remove-skill", + dest="remove_skills", + action="append", + help="Remove a specific attached skill. Repeatable.", + ) + cron_edit.add_argument( + "--clear-skills", + action="store_true", + help="Remove all attached skills from the job", + ) + cron_edit.add_argument( + "--script", + help="Path to a Python script whose stdout is injected into the prompt each run. Pass empty string to clear.", + ) # lifecycle actions cron_pause = cron_subparsers.add_parser("pause", help="Pause a scheduled job") @@ -5323,10 +6368,14 @@ For more help on a command: cron_resume = cron_subparsers.add_parser("resume", help="Resume a paused job") cron_resume.add_argument("job_id", help="Job ID to resume") - cron_run = cron_subparsers.add_parser("run", help="Run a job on the next scheduler tick") + cron_run = cron_subparsers.add_parser( + "run", help="Run a job on the next scheduler tick" + ) cron_run.add_argument("job_id", help="Job ID to trigger") - cron_remove = cron_subparsers.add_parser("remove", aliases=["rm", "delete"], help="Remove a scheduled job") + cron_remove = cron_subparsers.add_parser( + "remove", aliases=["rm", "delete"], help="Remove a scheduled job" + ) cron_remove.add_argument("job_id", help="Job ID to remove") # cron status @@ -5347,24 +6396,50 @@ For more help on a command: ) webhook_subparsers = webhook_parser.add_subparsers(dest="webhook_action") - wh_sub = webhook_subparsers.add_parser("subscribe", aliases=["add"], help="Create a webhook subscription") + wh_sub = webhook_subparsers.add_parser( + "subscribe", aliases=["add"], help="Create a webhook subscription" + ) wh_sub.add_argument("name", help="Route name (used in URL: /webhooks/)") - wh_sub.add_argument("--prompt", default="", help="Prompt template with {dot.notation} payload refs") - wh_sub.add_argument("--events", default="", help="Comma-separated event types to accept") + wh_sub.add_argument( + "--prompt", default="", help="Prompt template with {dot.notation} payload refs" + ) + wh_sub.add_argument( + "--events", default="", help="Comma-separated event types to accept" + ) wh_sub.add_argument("--description", default="", help="What this subscription does") - wh_sub.add_argument("--skills", default="", help="Comma-separated skill names to load") - wh_sub.add_argument("--deliver", default="log", help="Delivery target: log, telegram, discord, slack, etc.") - wh_sub.add_argument("--deliver-chat-id", default="", help="Target chat ID for cross-platform delivery") - wh_sub.add_argument("--secret", default="", help="HMAC secret (auto-generated if omitted)") + wh_sub.add_argument( + "--skills", default="", help="Comma-separated skill names to load" + ) + wh_sub.add_argument( + "--deliver", + default="log", + help="Delivery target: log, telegram, discord, slack, etc.", + ) + wh_sub.add_argument( + "--deliver-chat-id", + default="", + help="Target chat ID for cross-platform delivery", + ) + wh_sub.add_argument( + "--secret", default="", help="HMAC secret (auto-generated if omitted)" + ) - webhook_subparsers.add_parser("list", aliases=["ls"], help="List all dynamic subscriptions") + webhook_subparsers.add_parser( + "list", aliases=["ls"], help="List all dynamic subscriptions" + ) - wh_rm = webhook_subparsers.add_parser("remove", aliases=["rm"], help="Remove a subscription") + wh_rm = webhook_subparsers.add_parser( + "remove", aliases=["rm"], help="Remove a subscription" + ) wh_rm.add_argument("name", help="Subscription name to remove") - wh_test = webhook_subparsers.add_parser("test", help="Send a test POST to a webhook route") + wh_test = webhook_subparsers.add_parser( + "test", help="Send a test POST to a webhook route" + ) wh_test.add_argument("name", help="Subscription name to test") - wh_test.add_argument("--payload", default="", help="JSON payload to send (default: test payload)") + wh_test.add_argument( + "--payload", default="", help="JSON payload to send (default: test payload)" + ) webhook_parser.set_defaults(func=cmd_webhook) @@ -5374,12 +6449,10 @@ For more help on a command: doctor_parser = subparsers.add_parser( "doctor", help="Check configuration and dependencies", - description="Diagnose issues with Hermes Agent setup" + description="Diagnose issues with Hermes Agent setup", ) doctor_parser.add_argument( - "--fix", - action="store_true", - help="Attempt to fix issues automatically" + "--fix", action="store_true", help="Attempt to fix issues automatically" ) doctor_parser.set_defaults(func=cmd_doctor) @@ -5390,12 +6463,12 @@ For more help on a command: "dump", help="Dump setup summary for support/debugging", description="Output a compact, plain-text summary of your Hermes setup " - "that can be copy-pasted into Discord/GitHub for support context" + "that can be copy-pasted into Discord/GitHub for support context", ) dump_parser.add_argument( "--show-keys", action="store_true", - help="Show redacted API key prefixes (first/last 4 chars) instead of just set/not set" + help="Show redacted API key prefixes (first/last 4 chars) instead of just set/not set", ) dump_parser.set_defaults(func=cmd_dump) @@ -5406,8 +6479,8 @@ For more help on a command: "debug", help="Debug tools — upload logs and system info for support", description="Debug utilities for Hermes Agent. Use 'hermes debug share' to " - "upload a debug report (system info + recent logs) to a paste " - "service and get a shareable URL.", + "upload a debug report (system info + recent logs) to a paste " + "service and get a shareable URL.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""\ Examples: @@ -5424,15 +6497,20 @@ Examples: help="Upload debug report to a paste service and print a shareable URL", ) share_parser.add_argument( - "--lines", type=int, default=200, + "--lines", + type=int, + default=200, help="Number of log lines to include per log file (default: 200)", ) share_parser.add_argument( - "--expire", type=int, default=7, + "--expire", + type=int, + default=7, help="Paste expiry in days (default: 7)", ) share_parser.add_argument( - "--local", action="store_true", + "--local", + action="store_true", help="Print the report locally instead of uploading", ) delete_parser = debug_sub.add_parser( @@ -5440,7 +6518,9 @@ Examples: help="Delete a paste uploaded by 'hermes debug share'", ) delete_parser.add_argument( - "urls", nargs="*", default=[], + "urls", + nargs="*", + default=[], help="One or more paste URLs to delete (e.g. https://paste.rs/abc123)", ) debug_parser.set_defaults(func=cmd_debug) @@ -5452,21 +6532,22 @@ Examples: "backup", help="Back up Hermes home directory to a zip file", description="Create a zip archive of your entire Hermes configuration, " - "skills, sessions, and data (excludes the hermes-agent codebase). " - "Use --quick for a fast snapshot of just critical state files." + "skills, sessions, and data (excludes the hermes-agent codebase). " + "Use --quick for a fast snapshot of just critical state files.", ) backup_parser.add_argument( - "-o", "--output", - help="Output path for the zip file (default: ~/hermes-backup-.zip)" + "-o", + "--output", + help="Output path for the zip file (default: ~/hermes-backup-.zip)", ) backup_parser.add_argument( - "-q", "--quick", + "-q", + "--quick", action="store_true", - help="Quick snapshot: only critical state files (config, state.db, .env, auth, cron)" + help="Quick snapshot: only critical state files (config, state.db, .env, auth, cron)", ) backup_parser.add_argument( - "-l", "--label", - help="Label for the snapshot (only used with --quick)" + "-l", "--label", help="Label for the snapshot (only used with --quick)" ) backup_parser.set_defaults(func=cmd_backup) @@ -5477,17 +6558,15 @@ Examples: "import", help="Restore a Hermes backup from a zip file", description="Extract a previously created Hermes backup into your " - "Hermes home directory, restoring configuration, skills, " - "sessions, and data" + "Hermes home directory, restoring configuration, skills, " + "sessions, and data", ) + import_parser.add_argument("zipfile", help="Path to the backup zip file") import_parser.add_argument( - "zipfile", - help="Path to the backup zip file" - ) - import_parser.add_argument( - "--force", "-f", + "--force", + "-f", action="store_true", - help="Overwrite existing files without confirmation" + help="Overwrite existing files without confirmation", ) import_parser.set_defaults(func=cmd_import) @@ -5497,49 +6576,55 @@ Examples: config_parser = subparsers.add_parser( "config", help="View and edit configuration", - description="Manage Hermes Agent configuration" + description="Manage Hermes Agent configuration", ) config_subparsers = config_parser.add_subparsers(dest="config_command") - + # config show (default) config_subparsers.add_parser("show", help="Show current configuration") - + # config edit config_subparsers.add_parser("edit", help="Open config file in editor") - + # config set config_set = config_subparsers.add_parser("set", help="Set a configuration value") - config_set.add_argument("key", nargs="?", help="Configuration key (e.g., model, terminal.backend)") + config_set.add_argument( + "key", nargs="?", help="Configuration key (e.g., model, terminal.backend)" + ) config_set.add_argument("value", nargs="?", help="Value to set") - + # config path config_subparsers.add_parser("path", help="Print config file path") - + # config env-path config_subparsers.add_parser("env-path", help="Print .env file path") - + # config check config_subparsers.add_parser("check", help="Check for missing/outdated config") - + # config migrate config_subparsers.add_parser("migrate", help="Update config with new options") - + config_parser.set_defaults(func=cmd_config) - + # ========================================================================= # pairing command # ========================================================================= pairing_parser = subparsers.add_parser( "pairing", help="Manage DM pairing codes for user authorization", - description="Approve or revoke user access via pairing codes" + description="Approve or revoke user access via pairing codes", ) pairing_sub = pairing_parser.add_subparsers(dest="pairing_action") pairing_sub.add_parser("list", help="Show pending + approved users") - pairing_approve_parser = pairing_sub.add_parser("approve", help="Approve a pairing code") - pairing_approve_parser.add_argument("platform", help="Platform name (telegram, discord, slack, whatsapp)") + pairing_approve_parser = pairing_sub.add_parser( + "approve", help="Approve a pairing code" + ) + pairing_approve_parser.add_argument( + "platform", help="Platform name (telegram, discord, slack, whatsapp)" + ) pairing_approve_parser.add_argument("code", help="Pairing code to approve") pairing_revoke_parser = pairing_sub.add_parser("revoke", help="Revoke user access") @@ -5550,6 +6635,7 @@ Examples: def cmd_pairing(args): from hermes_cli.pairing import pairing_command + pairing_command(args) pairing_parser.set_defaults(func=cmd_pairing) @@ -5560,44 +6646,106 @@ Examples: skills_parser = subparsers.add_parser( "skills", help="Search, install, configure, and manage skills", - description="Search, install, inspect, audit, configure, and manage skills from skills.sh, well-known agent skill endpoints, GitHub, ClawHub, and other registries." + description="Search, install, inspect, audit, configure, and manage skills from skills.sh, well-known agent skill endpoints, GitHub, ClawHub, and other registries.", ) skills_subparsers = skills_parser.add_subparsers(dest="skills_action") - skills_browse = skills_subparsers.add_parser("browse", help="Browse all available skills (paginated)") - skills_browse.add_argument("--page", type=int, default=1, help="Page number (default: 1)") - skills_browse.add_argument("--size", type=int, default=20, help="Results per page (default: 20)") - skills_browse.add_argument("--source", default="all", - choices=["all", "official", "skills-sh", "well-known", "github", "clawhub", "lobehub"], - help="Filter by source (default: all)") + skills_browse = skills_subparsers.add_parser( + "browse", help="Browse all available skills (paginated)" + ) + skills_browse.add_argument( + "--page", type=int, default=1, help="Page number (default: 1)" + ) + skills_browse.add_argument( + "--size", type=int, default=20, help="Results per page (default: 20)" + ) + skills_browse.add_argument( + "--source", + default="all", + choices=[ + "all", + "official", + "skills-sh", + "well-known", + "github", + "clawhub", + "lobehub", + ], + help="Filter by source (default: all)", + ) - skills_search = skills_subparsers.add_parser("search", help="Search skill registries") + skills_search = skills_subparsers.add_parser( + "search", help="Search skill registries" + ) skills_search.add_argument("query", help="Search query") - skills_search.add_argument("--source", default="all", choices=["all", "official", "skills-sh", "well-known", "github", "clawhub", "lobehub"]) + skills_search.add_argument( + "--source", + default="all", + choices=[ + "all", + "official", + "skills-sh", + "well-known", + "github", + "clawhub", + "lobehub", + ], + ) skills_search.add_argument("--limit", type=int, default=10, help="Max results") skills_install = skills_subparsers.add_parser("install", help="Install a skill") - skills_install.add_argument("identifier", help="Skill identifier (e.g. openai/skills/skill-creator)") - skills_install.add_argument("--category", default="", help="Category folder to install into") - skills_install.add_argument("--force", action="store_true", help="Install despite blocked scan verdict") - skills_install.add_argument("--yes", "-y", action="store_true", help="Skip confirmation prompt (needed in TUI mode)") + skills_install.add_argument( + "identifier", help="Skill identifier (e.g. openai/skills/skill-creator)" + ) + skills_install.add_argument( + "--category", default="", help="Category folder to install into" + ) + skills_install.add_argument( + "--force", action="store_true", help="Install despite blocked scan verdict" + ) + skills_install.add_argument( + "--yes", + "-y", + action="store_true", + help="Skip confirmation prompt (needed in TUI mode)", + ) - skills_inspect = skills_subparsers.add_parser("inspect", help="Preview a skill without installing") + skills_inspect = skills_subparsers.add_parser( + "inspect", help="Preview a skill without installing" + ) skills_inspect.add_argument("identifier", help="Skill identifier") skills_list = skills_subparsers.add_parser("list", help="List installed skills") - skills_list.add_argument("--source", default="all", choices=["all", "hub", "builtin", "local"]) + skills_list.add_argument( + "--source", default="all", choices=["all", "hub", "builtin", "local"] + ) - skills_check = skills_subparsers.add_parser("check", help="Check installed hub skills for updates") - skills_check.add_argument("name", nargs="?", help="Specific skill to check (default: all)") + skills_check = skills_subparsers.add_parser( + "check", help="Check installed hub skills for updates" + ) + skills_check.add_argument( + "name", nargs="?", help="Specific skill to check (default: all)" + ) - skills_update = skills_subparsers.add_parser("update", help="Update installed hub skills") - skills_update.add_argument("name", nargs="?", help="Specific skill to update (default: all outdated skills)") + skills_update = skills_subparsers.add_parser( + "update", help="Update installed hub skills" + ) + skills_update.add_argument( + "name", + nargs="?", + help="Specific skill to update (default: all outdated skills)", + ) - skills_audit = skills_subparsers.add_parser("audit", help="Re-scan installed hub skills") - skills_audit.add_argument("name", nargs="?", help="Specific skill to audit (default: all)") + skills_audit = skills_subparsers.add_parser( + "audit", help="Re-scan installed hub skills" + ) + skills_audit.add_argument( + "name", nargs="?", help="Specific skill to audit (default: all)" + ) - skills_uninstall = skills_subparsers.add_parser("uninstall", help="Remove a hub-installed skill") + skills_uninstall = skills_subparsers.add_parser( + "uninstall", help="Remove a hub-installed skill" + ) skills_uninstall.add_argument("name", help="Skill name to remove") skills_reset = skills_subparsers.add_parser( @@ -5609,28 +6757,47 @@ Examples: "replace the current copy with the bundled version." ), ) - skills_reset.add_argument("name", help="Skill name to reset (e.g. google-workspace)") skills_reset.add_argument( - "--restore", action="store_true", + "name", help="Skill name to reset (e.g. google-workspace)" + ) + skills_reset.add_argument( + "--restore", + action="store_true", help="Also delete the current copy and re-copy the bundled version", ) skills_reset.add_argument( - "--yes", "-y", action="store_true", + "--yes", + "-y", + action="store_true", help="Skip confirmation prompt when using --restore", ) - skills_publish = skills_subparsers.add_parser("publish", help="Publish a skill to a registry") + skills_publish = skills_subparsers.add_parser( + "publish", help="Publish a skill to a registry" + ) skills_publish.add_argument("skill_path", help="Path to skill directory") - skills_publish.add_argument("--to", default="github", choices=["github", "clawhub"], help="Target registry") - skills_publish.add_argument("--repo", default="", help="Target GitHub repo (e.g. openai/skills)") + skills_publish.add_argument( + "--to", default="github", choices=["github", "clawhub"], help="Target registry" + ) + skills_publish.add_argument( + "--repo", default="", help="Target GitHub repo (e.g. openai/skills)" + ) - skills_snapshot = skills_subparsers.add_parser("snapshot", help="Export/import skill configurations") + skills_snapshot = skills_subparsers.add_parser( + "snapshot", help="Export/import skill configurations" + ) snapshot_subparsers = skills_snapshot.add_subparsers(dest="snapshot_action") - snap_export = snapshot_subparsers.add_parser("export", help="Export installed skills to a file") + snap_export = snapshot_subparsers.add_parser( + "export", help="Export installed skills to a file" + ) snap_export.add_argument("output", help="Output JSON file path (use - for stdout)") - snap_import = snapshot_subparsers.add_parser("import", help="Import and install skills from a file") + snap_import = snapshot_subparsers.add_parser( + "import", help="Import and install skills from a file" + ) snap_import.add_argument("input", help="Input JSON file path") - snap_import.add_argument("--force", action="store_true", help="Force install despite caution verdict") + snap_import.add_argument( + "--force", action="store_true", help="Force install despite caution verdict" + ) skills_tap = skills_subparsers.add_parser("tap", help="Manage skill sources") tap_subparsers = skills_tap.add_subparsers(dest="tap_action") @@ -5641,16 +6808,21 @@ Examples: tap_rm.add_argument("name", help="Tap name to remove") # config sub-action: interactive enable/disable - skills_subparsers.add_parser("config", help="Interactive skill configuration — enable/disable individual skills") + skills_subparsers.add_parser( + "config", + help="Interactive skill configuration — enable/disable individual skills", + ) def cmd_skills(args): # Route 'config' action to skills_config module - if getattr(args, 'skills_action', None) == 'config': + if getattr(args, "skills_action", None) == "config": _require_tty("skills config") from hermes_cli.skills_config import skills_command as skills_config_command + skills_config_command(args) else: from hermes_cli.skills_hub import skills_command + skills_command(args) skills_parser.set_defaults(func=cmd_skills) @@ -5673,7 +6845,9 @@ Examples: help="Git URL or owner/repo shorthand (e.g. anpicasso/hermes-plugin-chrome-profiles)", ) plugins_install.add_argument( - "--force", "-f", action="store_true", + "--force", + "-f", + action="store_true", help="Remove existing plugin and reinstall", ) @@ -5701,6 +6875,7 @@ Examples: def cmd_plugins(args): from hermes_cli.plugins_cmd import plugins_command + plugins_command(args) plugins_parser.set_defaults(func=cmd_plugins) @@ -5712,6 +6887,7 @@ Examples: # ========================================================================= try: from plugins.memory import discover_plugin_cli_commands + for cmd_info in discover_plugin_cli_commands(): plugin_parser = subparsers.add_parser( cmd_info["name"], @@ -5722,6 +6898,7 @@ Examples: cmd_info["setup_fn"](plugin_parser) except Exception as _exc: import logging as _log + _log.getLogger(__name__).debug("Plugin CLI discovery failed: %s", _exc) # ========================================================================= @@ -5739,7 +6916,9 @@ Examples: ), ) memory_sub = memory_parser.add_subparsers(dest="memory_command") - memory_sub.add_parser("setup", help="Interactive provider selection and configuration") + memory_sub.add_parser( + "setup", help="Interactive provider selection and configuration" + ) memory_sub.add_parser("status", help="Show current memory provider config") memory_sub.add_parser("off", help="Disable external provider (built-in only)") _reset_parser = memory_sub.add_parser( @@ -5747,11 +6926,15 @@ Examples: help="Erase all built-in memory (MEMORY.md and USER.md)", ) _reset_parser.add_argument( - "--yes", "-y", action="store_true", + "--yes", + "-y", + action="store_true", help="Skip confirmation prompt", ) _reset_parser.add_argument( - "--target", choices=["all", "memory", "user"], default="all", + "--target", + choices=["all", "memory", "user"], + default="all", help="Which store to reset: 'all' (default), 'memory', or 'user'", ) @@ -5759,6 +6942,7 @@ Examples: sub = getattr(args, "memory_command", None) if sub == "off": from hermes_cli.config import load_config, save_config + config = load_config() if not isinstance(config.get("memory"), dict): config["memory"] = {} @@ -5768,6 +6952,7 @@ Examples: print(" Saved to config.yaml\n") elif sub == "reset": from hermes_constants import get_hermes_home, display_hermes_home + mem_dir = get_hermes_home() / "memories" target = getattr(args, "target", "all") files_to_reset = [] @@ -5777,9 +6962,13 @@ Examples: files_to_reset.append(("USER.md", "user profile")) # Check what exists - existing = [(f, desc) for f, desc in files_to_reset if (mem_dir / f).exists()] + existing = [ + (f, desc) for f, desc in files_to_reset if (mem_dir / f).exists() + ] if not existing: - print(f"\n Nothing to reset — no memory files found in {display_hermes_home()}/memories/\n") + print( + f"\n Nothing to reset — no memory files found in {display_hermes_home()}/memories/\n" + ) return print(f"\n This will permanently erase the following memory files:") @@ -5802,10 +6991,13 @@ Examples: (mem_dir / f).unlink() print(f" ✓ Deleted {f} ({desc})") - print(f"\n Memory reset complete. New sessions will start with a blank slate.") + print( + f"\n Memory reset complete. New sessions will start with a blank slate." + ) print(f" Files were in: {display_hermes_home()}/memories/\n") else: from hermes_cli.memory_setup import memory_command + memory_command(args) memory_parser.set_defaults(func=cmd_memory) @@ -5826,7 +7018,7 @@ Examples: tools_parser.add_argument( "--summary", action="store_true", - help="Print a summary of enabled tools per platform and exit" + help="Print a summary of enabled tools per platform and exit", ) tools_sub = tools_parser.add_subparsers(dest="tools_action") @@ -5836,7 +7028,8 @@ Examples: help="Show all tools and their enabled/disabled status", ) tools_list_p.add_argument( - "--platform", default="cli", + "--platform", + default="cli", help="Platform to show (default: cli)", ) @@ -5846,11 +7039,14 @@ Examples: help="Disable toolsets or MCP tools", ) tools_disable_p.add_argument( - "names", nargs="+", metavar="NAME", + "names", + nargs="+", + metavar="NAME", help="Toolset name (e.g. web) or MCP tool in server:tool form", ) tools_disable_p.add_argument( - "--platform", default="cli", + "--platform", + default="cli", help="Platform to apply to (default: cli)", ) @@ -5860,11 +7056,14 @@ Examples: help="Enable toolsets or MCP tools", ) tools_enable_p.add_argument( - "names", nargs="+", metavar="NAME", + "names", + nargs="+", + metavar="NAME", help="Toolset name or MCP tool in server:tool form", ) tools_enable_p.add_argument( - "--platform", default="cli", + "--platform", + default="cli", help="Platform to apply to (default: cli)", ) @@ -5872,10 +7071,12 @@ Examples: action = getattr(args, "tools_action", None) if action in ("list", "disable", "enable"): from hermes_cli.tools_config import tools_disable_enable_command + tools_disable_enable_command(args) else: _require_tty("tools") from hermes_cli.tools_config import tools_command + tools_command(args) tools_parser.set_defaults(func=cmd_tools) @@ -5899,18 +7100,29 @@ Examples: help="Run Hermes as an MCP server (expose conversations to other agents)", ) mcp_serve_p.add_argument( - "-v", "--verbose", action="store_true", + "-v", + "--verbose", + action="store_true", help="Enable verbose logging on stderr", ) - mcp_add_p = mcp_sub.add_parser("add", help="Add an MCP server (discovery-first install)") + mcp_add_p = mcp_sub.add_parser( + "add", help="Add an MCP server (discovery-first install)" + ) mcp_add_p.add_argument("name", help="Server name (used as config key)") mcp_add_p.add_argument("--url", help="HTTP/SSE endpoint URL") mcp_add_p.add_argument("--command", help="Stdio command (e.g. npx)") - mcp_add_p.add_argument("--args", nargs="*", default=[], help="Arguments for stdio command") + mcp_add_p.add_argument( + "--args", nargs="*", default=[], help="Arguments for stdio command" + ) mcp_add_p.add_argument("--auth", choices=["oauth", "header"], help="Auth method") mcp_add_p.add_argument("--preset", help="Known MCP preset name") - mcp_add_p.add_argument("--env", nargs="*", default=[], help="Environment variables for stdio servers (KEY=VALUE)") + mcp_add_p.add_argument( + "--env", + nargs="*", + default=[], + help="Environment variables for stdio servers (KEY=VALUE)", + ) mcp_rm_p = mcp_sub.add_parser("remove", aliases=["rm"], help="Remove an MCP server") mcp_rm_p.add_argument("name", help="Server name to remove") @@ -5920,7 +7132,9 @@ Examples: mcp_test_p = mcp_sub.add_parser("test", help="Test MCP server connection") mcp_test_p.add_argument("name", help="Server name to test") - mcp_cfg_p = mcp_sub.add_parser("configure", aliases=["config"], help="Toggle tool selection") + mcp_cfg_p = mcp_sub.add_parser( + "configure", aliases=["config"], help="Toggle tool selection" + ) mcp_cfg_p.add_argument("name", help="Server name to configure") mcp_login_p = mcp_sub.add_parser( @@ -5931,6 +7145,7 @@ Examples: def cmd_mcp(args): from hermes_cli.mcp_config import mcp_command + mcp_command(args) mcp_parser.set_defaults(func=cmd_mcp) @@ -5941,31 +7156,52 @@ Examples: sessions_parser = subparsers.add_parser( "sessions", help="Manage session history (list, rename, export, prune, delete)", - description="View and manage the SQLite session store" + description="View and manage the SQLite session store", ) sessions_subparsers = sessions_parser.add_subparsers(dest="sessions_action") sessions_list = sessions_subparsers.add_parser("list", help="List recent sessions") - sessions_list.add_argument("--source", help="Filter by source (cli, telegram, discord, etc.)") - sessions_list.add_argument("--limit", type=int, default=20, help="Max sessions to show") + sessions_list.add_argument( + "--source", help="Filter by source (cli, telegram, discord, etc.)" + ) + sessions_list.add_argument( + "--limit", type=int, default=20, help="Max sessions to show" + ) - sessions_export = sessions_subparsers.add_parser("export", help="Export sessions to a JSONL file") - sessions_export.add_argument("output", help="Output JSONL file path (use - for stdout)") + sessions_export = sessions_subparsers.add_parser( + "export", help="Export sessions to a JSONL file" + ) + sessions_export.add_argument( + "output", help="Output JSONL file path (use - for stdout)" + ) sessions_export.add_argument("--source", help="Filter by source") sessions_export.add_argument("--session-id", help="Export a specific session") - sessions_delete = sessions_subparsers.add_parser("delete", help="Delete a specific session") + sessions_delete = sessions_subparsers.add_parser( + "delete", help="Delete a specific session" + ) sessions_delete.add_argument("session_id", help="Session ID to delete") - sessions_delete.add_argument("--yes", "-y", action="store_true", help="Skip confirmation") + sessions_delete.add_argument( + "--yes", "-y", action="store_true", help="Skip confirmation" + ) sessions_prune = sessions_subparsers.add_parser("prune", help="Delete old sessions") - sessions_prune.add_argument("--older-than", type=int, default=90, help="Delete sessions older than N days (default: 90)") + sessions_prune.add_argument( + "--older-than", + type=int, + default=90, + help="Delete sessions older than N days (default: 90)", + ) sessions_prune.add_argument("--source", help="Only prune sessions from this source") - sessions_prune.add_argument("--yes", "-y", action="store_true", help="Skip confirmation") + sessions_prune.add_argument( + "--yes", "-y", action="store_true", help="Skip confirmation" + ) sessions_subparsers.add_parser("stats", help="Show session store statistics") - sessions_rename = sessions_subparsers.add_parser("rename", help="Set or change a session's title") + sessions_rename = sessions_subparsers.add_parser( + "rename", help="Set or change a session's title" + ) sessions_rename.add_argument("session_id", help="Session ID to rename") sessions_rename.add_argument("title", nargs="+", help="New title for the session") @@ -5973,8 +7209,12 @@ Examples: "browse", help="Interactive session picker — browse, search, and resume sessions", ) - sessions_browse.add_argument("--source", help="Filter by source (cli, telegram, discord, etc.)") - sessions_browse.add_argument("--limit", type=int, default=50, help="Max sessions to load (default: 50)") + sessions_browse.add_argument( + "--source", help="Filter by source (cli, telegram, discord, etc.)" + ) + sessions_browse.add_argument( + "--limit", type=int, default=50, help="Max sessions to load (default: 50)" + ) def _confirm_prompt(prompt: str) -> bool: """Prompt for y/N confirmation, safe against non-TTY environments.""" @@ -5985,8 +7225,10 @@ Examples: def cmd_sessions(args): import json as _json + try: from hermes_state import SessionDB + db = SessionDB() except Exception as e: print(f"Error: Could not open session database: {e}") @@ -5999,7 +7241,9 @@ Examples: _exclude = None if _source else ["tool"] if action == "list": - sessions = db.list_sessions_rich(source=args.source, exclude_sources=_exclude, limit=args.limit) + sessions = db.list_sessions_rich( + source=args.source, exclude_sources=_exclude, limit=args.limit + ) if not sessions: print("No sessions found.") return @@ -6012,7 +7256,11 @@ Examples: print("─" * 95) for s in sessions: last_active = _relative_time(s.get("last_active")) - preview = s.get("preview", "")[:38] if has_titles else s.get("preview", "")[:48] + preview = ( + s.get("preview", "")[:38] + if has_titles + else s.get("preview", "")[:48] + ) if has_titles: title = (s.get("title") or "—")[:30] sid = s["id"] @@ -6034,6 +7282,7 @@ Examples: line = _json.dumps(data, ensure_ascii=False) + "\n" if args.output == "-": import sys + sys.stdout.write(line) else: with open(args.output, "w", encoding="utf-8") as f: @@ -6043,6 +7292,7 @@ Examples: sessions = db.export_all(source=args.source) if args.output == "-": import sys + for s in sessions: sys.stdout.write(_json.dumps(s, ensure_ascii=False) + "\n") else: @@ -6057,7 +7307,9 @@ Examples: print(f"Session '{args.session_id}' not found.") return if not args.yes: - if not _confirm_prompt(f"Delete session '{resolved_session_id}' and all its messages? [y/N] "): + if not _confirm_prompt( + f"Delete session '{resolved_session_id}' and all its messages? [y/N] " + ): print("Cancelled.") return if db.delete_session(resolved_session_id): @@ -6069,7 +7321,9 @@ Examples: days = args.older_than source_msg = f" from '{args.source}'" if args.source else "" if not args.yes: - if not _confirm_prompt(f"Delete all ended sessions older than {days} days{source_msg}? [y/N] "): + if not _confirm_prompt( + f"Delete all ended sessions older than {days} days{source_msg}? [y/N] " + ): print("Cancelled.") return count = db.prune_sessions(older_than_days=days, source=args.source) @@ -6093,7 +7347,9 @@ Examples: limit = getattr(args, "limit", 50) or 50 source = getattr(args, "source", None) _browse_exclude = None if source else ["tool"] - sessions = db.list_sessions_rich(source=source, exclude_sources=_browse_exclude, limit=limit) + sessions = db.list_sessions_rich( + source=source, exclude_sources=_browse_exclude, limit=limit + ) db.close() if not sessions: print("No sessions found.") @@ -6107,6 +7363,7 @@ Examples: # Launch hermes --resume by replacing the current process print(f"Resuming session: {selected_id}") import shutil + hermes_bin = shutil.which("hermes") if hermes_bin: os.execvp(hermes_bin, ["hermes", "--resume", selected_id]) @@ -6145,10 +7402,14 @@ Examples: insights_parser = subparsers.add_parser( "insights", help="Show usage insights and analytics", - description="Analyze session history to show token usage, costs, tool patterns, and activity trends" + description="Analyze session history to show token usage, costs, tool patterns, and activity trends", + ) + insights_parser.add_argument( + "--days", type=int, default=30, help="Number of days to analyze (default: 30)" + ) + insights_parser.add_argument( + "--source", help="Filter by platform (cli, telegram, discord, etc.)" ) - insights_parser.add_argument("--days", type=int, default=30, help="Number of days to analyze (default: 30)") - insights_parser.add_argument("--source", help="Filter by platform (cli, telegram, discord, etc.)") def cmd_insights(args): try: @@ -6171,7 +7432,7 @@ Examples: claw_parser = subparsers.add_parser( "claw", help="OpenClaw migration tools", - description="Migrate settings, memories, skills, and API keys from OpenClaw to Hermes" + description="Migrate settings, memories, skills, and API keys from OpenClaw to Hermes", ) claw_subparsers = claw_parser.add_subparsers(dest="claw_action") @@ -6180,47 +7441,43 @@ Examples: "migrate", help="Migrate from OpenClaw to Hermes", description="Import settings, memories, skills, and API keys from an OpenClaw installation. " - "Always shows a preview before making changes." + "Always shows a preview before making changes.", ) claw_migrate.add_argument( - "--source", - help="Path to OpenClaw directory (default: ~/.openclaw)" + "--source", help="Path to OpenClaw directory (default: ~/.openclaw)" ) claw_migrate.add_argument( "--dry-run", action="store_true", - help="Preview only — stop after showing what would be migrated" + help="Preview only — stop after showing what would be migrated", ) claw_migrate.add_argument( "--preset", choices=["user-data", "full"], default="full", - help="Migration preset (default: full). 'user-data' excludes secrets" + help="Migration preset (default: full). 'user-data' excludes secrets", ) claw_migrate.add_argument( "--overwrite", action="store_true", - help="Overwrite existing files (default: skip conflicts)" + help="Overwrite existing files (default: skip conflicts)", ) claw_migrate.add_argument( "--migrate-secrets", action="store_true", - help="Include allowlisted secrets (TELEGRAM_BOT_TOKEN, API keys, etc.)" + help="Include allowlisted secrets (TELEGRAM_BOT_TOKEN, API keys, etc.)", ) claw_migrate.add_argument( - "--workspace-target", - help="Absolute path to copy workspace instructions into" + "--workspace-target", help="Absolute path to copy workspace instructions into" ) claw_migrate.add_argument( "--skill-conflict", choices=["skip", "overwrite", "rename"], default="skip", - help="How to handle skill name conflicts (default: skip)" + help="How to handle skill name conflicts (default: skip)", ) claw_migrate.add_argument( - "--yes", "-y", - action="store_true", - help="Skip confirmation prompts" + "--yes", "-y", action="store_true", help="Skip confirmation prompts" ) # claw cleanup @@ -6228,25 +7485,23 @@ Examples: "cleanup", aliases=["clean"], help="Archive leftover OpenClaw directories after migration", - description="Scan for and archive leftover OpenClaw directories to prevent state fragmentation" + description="Scan for and archive leftover OpenClaw directories to prevent state fragmentation", ) claw_cleanup.add_argument( - "--source", - help="Path to a specific OpenClaw directory to clean up" + "--source", help="Path to a specific OpenClaw directory to clean up" ) claw_cleanup.add_argument( "--dry-run", action="store_true", - help="Preview what would be archived without making changes" + help="Preview what would be archived without making changes", ) claw_cleanup.add_argument( - "--yes", "-y", - action="store_true", - help="Skip confirmation prompts" + "--yes", "-y", action="store_true", help="Skip confirmation prompts" ) def cmd_claw(args): from hermes_cli.claw import claw_command + claw_command(args) claw_parser.set_defaults(func=cmd_claw) @@ -6254,43 +7509,40 @@ Examples: # ========================================================================= # version command # ========================================================================= - version_parser = subparsers.add_parser( - "version", - help="Show version information" - ) + version_parser = subparsers.add_parser("version", help="Show version information") version_parser.set_defaults(func=cmd_version) - + # ========================================================================= # update command # ========================================================================= update_parser = subparsers.add_parser( "update", help="Update Hermes Agent to the latest version", - description="Pull the latest changes from git and reinstall dependencies" + description="Pull the latest changes from git and reinstall dependencies", ) update_parser.add_argument( - "--gateway", action="store_true", default=False, - help="Gateway mode: use file-based IPC for prompts instead of stdin (used internally by /update)" + "--gateway", + action="store_true", + default=False, + help="Gateway mode: use file-based IPC for prompts instead of stdin (used internally by /update)", ) update_parser.set_defaults(func=cmd_update) - + # ========================================================================= # uninstall command # ========================================================================= uninstall_parser = subparsers.add_parser( "uninstall", help="Uninstall Hermes Agent", - description="Remove Hermes Agent from your system. Can keep configs/data for reinstall." + description="Remove Hermes Agent from your system. Can keep configs/data for reinstall.", ) uninstall_parser.add_argument( "--full", action="store_true", - help="Full uninstall - remove everything including configs and data" + help="Full uninstall - remove everything including configs and data", ) uninstall_parser.add_argument( - "--yes", "-y", - action="store_true", - help="Skip confirmation prompts" + "--yes", "-y", action="store_true", help="Skip confirmation prompts" ) uninstall_parser.set_defaults(func=cmd_uninstall) @@ -6307,6 +7559,7 @@ Examples: """Launch Hermes Agent as an ACP server.""" try: from acp_adapter.entry import main as acp_main + acp_main() except ImportError: print("ACP dependencies not installed.") @@ -6325,48 +7578,81 @@ Examples: profile_subparsers = profile_parser.add_subparsers(dest="profile_action") profile_subparsers.add_parser("list", help="List all profiles") - profile_use = profile_subparsers.add_parser("use", help="Set sticky default profile") + profile_use = profile_subparsers.add_parser( + "use", help="Set sticky default profile" + ) profile_use.add_argument("profile_name", help="Profile name (or 'default')") - profile_create = profile_subparsers.add_parser("create", help="Create a new profile") - profile_create.add_argument("profile_name", help="Profile name (lowercase, alphanumeric)") - profile_create.add_argument("--clone", action="store_true", - help="Copy config.yaml, .env, SOUL.md from active profile") - profile_create.add_argument("--clone-all", action="store_true", - help="Full copy of active profile (all state)") - profile_create.add_argument("--clone-from", metavar="SOURCE", - help="Source profile to clone from (default: active)") - profile_create.add_argument("--no-alias", action="store_true", - help="Skip wrapper script creation") + profile_create = profile_subparsers.add_parser( + "create", help="Create a new profile" + ) + profile_create.add_argument( + "profile_name", help="Profile name (lowercase, alphanumeric)" + ) + profile_create.add_argument( + "--clone", + action="store_true", + help="Copy config.yaml, .env, SOUL.md from active profile", + ) + profile_create.add_argument( + "--clone-all", + action="store_true", + help="Full copy of active profile (all state)", + ) + profile_create.add_argument( + "--clone-from", + metavar="SOURCE", + help="Source profile to clone from (default: active)", + ) + profile_create.add_argument( + "--no-alias", action="store_true", help="Skip wrapper script creation" + ) profile_delete = profile_subparsers.add_parser("delete", help="Delete a profile") profile_delete.add_argument("profile_name", help="Profile to delete") - profile_delete.add_argument("-y", "--yes", action="store_true", - help="Skip confirmation prompt") + profile_delete.add_argument( + "-y", "--yes", action="store_true", help="Skip confirmation prompt" + ) profile_show = profile_subparsers.add_parser("show", help="Show profile details") profile_show.add_argument("profile_name", help="Profile to show") - profile_alias = profile_subparsers.add_parser("alias", help="Manage wrapper scripts") + profile_alias = profile_subparsers.add_parser( + "alias", help="Manage wrapper scripts" + ) profile_alias.add_argument("profile_name", help="Profile name") - profile_alias.add_argument("--remove", action="store_true", - help="Remove the wrapper script") - profile_alias.add_argument("--name", dest="alias_name", metavar="NAME", - help="Custom alias name (default: profile name)") + profile_alias.add_argument( + "--remove", action="store_true", help="Remove the wrapper script" + ) + profile_alias.add_argument( + "--name", + dest="alias_name", + metavar="NAME", + help="Custom alias name (default: profile name)", + ) profile_rename = profile_subparsers.add_parser("rename", help="Rename a profile") profile_rename.add_argument("old_name", help="Current profile name") profile_rename.add_argument("new_name", help="New profile name") - profile_export = profile_subparsers.add_parser("export", help="Export a profile to archive") + profile_export = profile_subparsers.add_parser( + "export", help="Export a profile to archive" + ) profile_export.add_argument("profile_name", help="Profile to export") - profile_export.add_argument("-o", "--output", default=None, - help="Output file (default: .tar.gz)") + profile_export.add_argument( + "-o", "--output", default=None, help="Output file (default: .tar.gz)" + ) - profile_import = profile_subparsers.add_parser("import", help="Import a profile from archive") + profile_import = profile_subparsers.add_parser( + "import", help="Import a profile from archive" + ) profile_import.add_argument("archive", help="Path to .tar.gz archive") - profile_import.add_argument("--name", dest="import_name", metavar="NAME", - help="Profile name (default: inferred from archive)") + profile_import.add_argument( + "--name", + dest="import_name", + metavar="NAME", + help="Profile name (default: inferred from archive)", + ) profile_parser.set_defaults(func=cmd_profile) @@ -6378,7 +7664,10 @@ Examples: help="Print shell completion script (bash, zsh, or fish)", ) completion_parser.add_argument( - "shell", nargs="?", default="bash", choices=["bash", "zsh", "fish"], + "shell", + nargs="?", + default="bash", + choices=["bash", "zsh", "fish"], help="Shell type (default: bash)", ) completion_parser.set_defaults(func=lambda args: cmd_completion(args, parser)) @@ -6391,11 +7680,18 @@ Examples: help="Start the web UI dashboard", description="Launch the Hermes Agent web dashboard for managing config, API keys, and sessions", ) - dashboard_parser.add_argument("--port", type=int, default=9119, help="Port (default 9119)") - dashboard_parser.add_argument("--host", default="127.0.0.1", help="Host (default 127.0.0.1)") - dashboard_parser.add_argument("--no-open", action="store_true", help="Don't open browser automatically") dashboard_parser.add_argument( - "--insecure", action="store_true", + "--port", type=int, default=9119, help="Port (default 9119)" + ) + dashboard_parser.add_argument( + "--host", default="127.0.0.1", help="Host (default 127.0.0.1)" + ) + dashboard_parser.add_argument( + "--no-open", action="store_true", help="Don't open browser automatically" + ) + dashboard_parser.add_argument( + "--insecure", + action="store_true", help="Allow binding to non-localhost (DANGEROUS: exposes API keys on the network)", ) dashboard_parser.set_defaults(func=cmd_dashboard) @@ -6423,31 +7719,42 @@ Examples: """, ) logs_parser.add_argument( - "log_name", nargs="?", default="agent", + "log_name", + nargs="?", + default="agent", help="Log to view: agent (default), errors, gateway, or 'list' to show available files", ) logs_parser.add_argument( - "-n", "--lines", type=int, default=50, + "-n", + "--lines", + type=int, + default=50, help="Number of lines to show (default: 50)", ) logs_parser.add_argument( - "-f", "--follow", action="store_true", + "-f", + "--follow", + action="store_true", help="Follow the log in real time (like tail -f)", ) logs_parser.add_argument( - "--level", metavar="LEVEL", + "--level", + metavar="LEVEL", help="Minimum log level to show (DEBUG, INFO, WARNING, ERROR)", ) logs_parser.add_argument( - "--session", metavar="ID", + "--session", + metavar="ID", help="Filter lines containing this session ID substring", ) logs_parser.add_argument( - "--since", metavar="TIME", + "--since", + metavar="TIME", help="Show lines since TIME ago (e.g. 1h, 30m, 2d)", ) logs_parser.add_argument( - "--component", metavar="NAME", + "--component", + metavar="NAME", help="Filter by component: gateway, agent, tools, cli, cron", ) logs_parser.set_defaults(func=cmd_logs) @@ -6464,6 +7771,7 @@ Examples: # --help, unrecognised flags, and every subcommand are forwarded # transparently instead of being intercepted by argparse on the host. from hermes_cli.config import get_container_exec_info + container_info = get_container_exec_info() if container_info: _exec_in_container(container_info, sys.argv[1:]) @@ -6484,8 +7792,13 @@ Examples: # fails (e.g. 'hermes -c model' where 'model' is consumed as the # session name for --continue), fall back to the default behaviour. import io as _io - _known_cmds = set(subparsers.choices.keys()) if hasattr(subparsers, "choices") else set() - _has_cmd_token = any(t in _known_cmds for t in _processed_argv if not t.startswith("-")) + + _known_cmds = ( + set(subparsers.choices.keys()) if hasattr(subparsers, "choices") else set() + ) + _has_cmd_token = any( + t in _known_cmds for t in _processed_argv if not t.startswith("-") + ) if _has_cmd_token: subparsers.required = True @@ -6513,36 +7826,42 @@ Examples: if args.version: cmd_version(args) return - + # Handle top-level --resume / --continue as shortcut to chat if (args.resume or args.continue_last) and args.command is None: args.command = "chat" - args.query = None - args.model = None - args.provider = None - args.toolsets = None - args.verbose = False - if not hasattr(args, "worktree"): - args.worktree = False + for attr, default in [ + ("query", None), + ("model", None), + ("provider", None), + ("toolsets", None), + ("verbose", False), + ("worktree", False), + ]: + if not hasattr(args, attr): + setattr(args, attr, default) cmd_chat(args) return - + # Default to chat if no command specified if args.command is None: - args.query = None - args.model = None - args.provider = None - args.toolsets = None - args.verbose = False - args.resume = None - args.continue_last = None - if not hasattr(args, "worktree"): - args.worktree = False + for attr, default in [ + ("query", None), + ("model", None), + ("provider", None), + ("toolsets", None), + ("verbose", False), + ("resume", None), + ("continue_last", None), + ("worktree", False), + ]: + if not hasattr(args, attr): + setattr(args, attr, default) cmd_chat(args) return - + # Execute the command - if hasattr(args, 'func'): + if hasattr(args, "func"): args.func(args) else: parser.print_help() diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py index 3d6c67c2d4..004582a574 100644 --- a/hermes_cli/model_switch.py +++ b/hermes_cli/model_switch.py @@ -692,12 +692,12 @@ def switch_model( api_key=api_key, base_url=base_url, ) - except Exception: + except Exception as e: validation = { - "accepted": True, - "persist": True, + "accepted": False, + "persist": False, "recognized": False, - "message": None, + "message": f"Could not validate `{new_model}`: {e}", } if not validation.get("accepted"): diff --git a/hermes_cli/models.py b/hermes_cli/models.py index d2859e01c5..cbbeef62d4 100644 --- a/hermes_cli/models.py +++ b/hermes_cli/models.py @@ -2050,8 +2050,8 @@ def validate_requested_model( ) return { - "accepted": True, - "persist": True, + "accepted": False, + "persist": False, "recognized": False, "message": message, } @@ -2064,8 +2064,8 @@ def validate_requested_model( message += f"\n If this server expects `/v1`, try base URL: `{probe.get('suggested_base_url')}`" return { - "accepted": True, - "persist": True, + "accepted": False, + "persist": False, "recognized": False, "message": message, } @@ -2099,12 +2099,11 @@ def validate_requested_model( if suggestions: suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions) return { - "accepted": True, - "persist": True, + "accepted": False, + "persist": False, "recognized": False, "message": ( - f"Note: `{requested}` was not found in the OpenAI Codex model listing. " - f"It may still work if your account has access to it." + f"Model `{requested}` was not found in the OpenAI Codex model listing." f"{suggestion_text}" ), } @@ -2143,16 +2142,15 @@ def validate_requested_model( if suggestions: suggestion_text = "\n Similar models: " + ", ".join(f"`{s}`" for s in suggestions) - return { - "accepted": True, - "persist": True, - "recognized": False, - "message": ( - f"Note: `{requested}` was not found in this provider's model listing. " - f"It may still work if your plan supports it." - f"{suggestion_text}" - ), - } + return { + "accepted": False, + "persist": False, + "recognized": False, + "message": ( + f"Model `{requested}` was not found in this provider's model listing." + f"{suggestion_text}" + ), + } # api_models is None — couldn't reach API. Accept and persist, # but warn so typos don't silently break things. @@ -2194,8 +2192,8 @@ def validate_requested_model( provider_label = _PROVIDER_LABELS.get(normalized, normalized) return { - "accepted": True, - "persist": True, + "accepted": False, + "persist": False, "recognized": False, "message": ( f"Could not reach the {provider_label} API to validate `{requested}`. " diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py index c27ca25eaa..bf92fafe10 100644 --- a/hermes_cli/skills_hub.py +++ b/hermes_cli/skills_hub.py @@ -515,6 +515,90 @@ def do_inspect(identifier: str, console: Optional[Console] = None) -> None: c.print() +def browse_skills(page: int = 1, page_size: int = 20, source: str = "all") -> dict: + """Paginated hub browse for programmatic callers (e.g. TUI gateway). + + Returns ``{"items": [...], "page": int, "total_pages": int, "total": int}``. + """ + from tools.skills_hub import GitHubAuth, create_source_router + + page_size = max(1, min(page_size, 100)) + _TRUST_RANK = {"builtin": 3, "trusted": 2, "community": 1} + _PER_SOURCE_LIMIT = {"official": 100, "skills-sh": 100, "well-known": 25, "github": 100, "clawhub": 50, + "claude-marketplace": 50, "lobehub": 50} + auth = GitHubAuth() + sources = create_source_router(auth) + all_results: list = [] + for src in sources: + sid = src.source_id() + if source != "all" and sid != source and sid != "official": + continue + try: + limit = _PER_SOURCE_LIMIT.get(sid, 50) + all_results.extend(src.search("", limit=limit)) + except Exception: + continue + if not all_results: + return {"items": [], "page": 1, "total_pages": 1, "total": 0} + seen: dict = {} + for r in all_results: + rank = _TRUST_RANK.get(r.trust_level, 0) + if r.name not in seen or rank > _TRUST_RANK.get(seen[r.name].trust_level, 0): + seen[r.name] = r + deduped = list(seen.values()) + deduped.sort(key=lambda r: (-_TRUST_RANK.get(r.trust_level, 0), r.source != "official", r.name.lower())) + total = len(deduped) + total_pages = max(1, (total + page_size - 1) // page_size) + page = max(1, min(page, total_pages)) + start = (page - 1) * page_size + page_items = deduped[start : min(start + page_size, total)] + return { + "items": [{"name": r.name, "description": r.description, "source": r.source, + "trust": r.trust_level} for r in page_items], + "page": page, + "total_pages": total_pages, + "total": total, + } + + +def inspect_skill(identifier: str) -> Optional[dict]: + """Skill metadata (+ SKILL.md preview) for programmatic callers.""" + from tools.skills_hub import GitHubAuth, create_source_router + + class _Q: + def print(self, *a, **k): + pass + + c = _Q() + auth = GitHubAuth() + sources = create_source_router(auth) + ident = identifier + if "/" not in ident: + ident = _resolve_short_name(ident, sources, c) + if not ident: + return None + meta, bundle, _ = _resolve_source_meta_and_bundle(ident, sources) + if not meta: + return None + out: dict = { + "name": meta.name, + "description": meta.description, + "source": meta.source, + "identifier": meta.identifier, + "tags": list(meta.tags) if meta.tags else [], + } + if bundle and "SKILL.md" in bundle.files: + content = bundle.files["SKILL.md"] + if isinstance(content, bytes): + content = content.decode("utf-8", errors="replace") + lines = content.split("\n") + preview = "\n".join(lines[:50]) + if len(lines) > 50: + preview += f"\n\n... ({len(lines) - 50} more lines)" + out["skill_md_preview"] = preview + return out + + def do_list(source_filter: str = "all", console: Optional[Console] = None) -> None: """List installed skills, distinguishing hub, builtin, and local skills.""" from tools.skills_hub import HubLockFile, ensure_hub_dirs diff --git a/hermes_cli/skin_engine.py b/hermes_cli/skin_engine.py index 160e7c119c..4222a966ef 100644 --- a/hermes_cli/skin_engine.py +++ b/hermes_cli/skin_engine.py @@ -23,7 +23,7 @@ All fields are optional. Missing values inherit from the ``default`` skin. banner_dim: "#B8860B" # Dim/muted text (separators, labels) banner_text: "#FFF8DC" # Body text (tool names, skill names) ui_accent: "#FFBF00" # General UI accent - ui_label: "#4dd0e1" # UI labels + ui_label: "#DAA520" # UI labels (warm gold; teal clashed w/ default banner gold) ui_ok: "#4caf50" # Success indicators ui_error: "#ef5350" # Error indicators ui_warn: "#ffa726" # Warning indicators @@ -163,7 +163,7 @@ _BUILTIN_SKINS: Dict[str, Dict[str, Any]] = { "banner_dim": "#B8860B", "banner_text": "#FFF8DC", "ui_accent": "#FFBF00", - "ui_label": "#4dd0e1", + "ui_label": "#DAA520", "ui_ok": "#4caf50", "ui_error": "#ef5350", "ui_warn": "#ffa726", diff --git a/hermes_constants.py b/hermes_constants.py index 3bc56d4f78..35dbf86ab2 100644 --- a/hermes_constants.py +++ b/hermes_constants.py @@ -14,7 +14,8 @@ def get_hermes_home() -> Path: Reads HERMES_HOME env var, falls back to ~/.hermes. This is the single source of truth — all other copies should import this. """ - return Path(os.getenv("HERMES_HOME", Path.home() / ".hermes")) + val = os.environ.get("HERMES_HOME", "").strip() + return Path(val) if val else Path.home() / ".hermes" def get_default_hermes_root() -> Path: diff --git a/nix/checks.nix b/nix/checks.nix index 6dd5115c93..55068a94f1 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -103,6 +103,28 @@ json.dump(sorted(leaf_paths(DEFAULT_CONFIG)), sys.stdout, indent=2) echo "ok" > $out/result ''; + # Verify bundled TUI is present and compiled + bundled-tui = pkgs.runCommand "hermes-bundled-tui" { } '' + set -e + echo "=== Checking bundled TUI ===" + test -d ${hermes-agent}/ui-tui || (echo "FAIL: ui-tui directory missing"; exit 1) + echo "PASS: ui-tui directory exists" + + test -f ${hermes-agent}/ui-tui/dist/entry.js || (echo "FAIL: compiled entry.js missing"; exit 1) + echo "PASS: compiled entry.js present" + + test -d ${hermes-agent}/ui-tui/node_modules || (echo "FAIL: node_modules missing"; exit 1) + echo "PASS: node_modules present" + + grep -q "HERMES_TUI_DIR" ${hermes-agent}/bin/hermes || \ + (echo "FAIL: HERMES_TUI_DIR not in wrapper"; exit 1) + echo "PASS: HERMES_TUI_DIR set in wrapper" + + echo "=== All bundled TUI checks passed ===" + mkdir -p $out + echo "ok" > $out/result + ''; + # Verify HERMES_MANAGED guard works on all mutation commands managed-guard = pkgs.runCommand "hermes-managed-guard" { } '' set -e diff --git a/nix/devShell.nix b/nix/devShell.nix index 7f8b5a1b03..db39c9d955 100644 --- a/nix/devShell.nix +++ b/nix/devShell.nix @@ -1,49 +1,26 @@ -# nix/devShell.nix — Fast dev shell with stamp-file optimization +# nix/devShell.nix — Dev shell that delegates setup to each package +# +# Each package in inputsFrom exposes passthru.devShellHook — a bash snippet +# with stamp-checked setup logic. This file collects and runs them all. { inputs, ... }: { - perSystem = { pkgs, ... }: + perSystem = { pkgs, system, ... }: let - python = pkgs.python311; + hermes-agent = inputs.self.packages.${system}.default; + hermes-tui = inputs.self.packages.${system}.tui; + packages = [ hermes-agent hermes-tui ]; in { devShells.default = pkgs.mkShell { + inputsFrom = packages; packages = with pkgs; [ - python uv nodejs_20 ripgrep git openssh ffmpeg + python311 uv nodejs_22 ripgrep git openssh ffmpeg ]; - shellHook = '' + shellHook = let + hooks = map (p: p.passthru.devShellHook or "") packages; + combined = pkgs.lib.concatStringsSep "\n" (builtins.filter (h: h != "") hooks); + in '' echo "Hermes Agent dev shell" - - # Composite stamp: changes when nix python or uv change - STAMP_VALUE="${python}:${pkgs.uv}" - STAMP_FILE=".venv/.nix-stamp" - - # Create venv if missing - if [ ! -d .venv ]; then - echo "Creating Python 3.11 venv..." - uv venv .venv --python ${python}/bin/python3 - fi - - source .venv/bin/activate - - # Only install if stamp is stale or missing - if [ ! -f "$STAMP_FILE" ] || [ "$(cat "$STAMP_FILE")" != "$STAMP_VALUE" ]; then - echo "Installing Python dependencies..." - uv pip install -e ".[all]" - if [ -d mini-swe-agent ]; then - uv pip install -e ./mini-swe-agent 2>/dev/null || true - fi - if [ -d tinker-atropos ]; then - uv pip install -e ./tinker-atropos 2>/dev/null || true - fi - - # Install npm deps - if [ -f package.json ] && [ ! -d node_modules ]; then - echo "Installing npm dependencies..." - npm install - fi - - echo "$STAMP_VALUE" > "$STAMP_FILE" - fi - + ${combined} echo "Ready. Run 'hermes' to start." ''; }; diff --git a/nix/packages.nix b/nix/packages.nix index eb50d4a17b..f39d9d0b2b 100644 --- a/nix/packages.nix +++ b/nix/packages.nix @@ -1,54 +1,108 @@ # nix/packages.nix — Hermes Agent package built with uv2nix -{ inputs, ... }: { - perSystem = { pkgs, system, ... }: +{ inputs, ... }: +{ + perSystem = + { pkgs, inputs', ... }: let hermesVenv = pkgs.callPackage ./python.nix { inherit (inputs) uv2nix pyproject-nix pyproject-build-systems; }; + hermesTui = pkgs.callPackage ./tui.nix { + npm-lockfile-fix = inputs'.npm-lockfile-fix.packages.default; + }; + # Import bundled skills, excluding runtime caches bundledSkills = pkgs.lib.cleanSourceWith { src = ../skills; - filter = path: _type: - !(pkgs.lib.hasInfix "/index-cache/" path); + filter = path: _type: !(pkgs.lib.hasInfix "/index-cache/" path); }; runtimeDeps = with pkgs; [ - nodejs_20 ripgrep git openssh ffmpeg tirith + nodejs_22 + ripgrep + git + openssh + ffmpeg + tirith ]; runtimePath = pkgs.lib.makeBinPath runtimeDeps; - in { - packages.default = pkgs.stdenv.mkDerivation { - pname = "hermes-agent"; - version = (builtins.fromTOML (builtins.readFile ../pyproject.toml)).project.version; - dontUnpack = true; - dontBuild = true; - nativeBuildInputs = [ pkgs.makeWrapper ]; + # Lockfile hashes for dev shell stamps + pyprojectHash = builtins.hashString "sha256" (builtins.readFile ../pyproject.toml); + uvLockHash = + if builtins.pathExists ../uv.lock then + builtins.hashString "sha256" (builtins.readFile ../uv.lock) + else + "none"; + in + { + packages = { + default = pkgs.stdenv.mkDerivation { + pname = "hermes-agent"; + version = (fromTOML (builtins.readFile ../pyproject.toml)).project.version; - installPhase = '' - runHook preInstall + dontUnpack = true; + dontBuild = true; + nativeBuildInputs = [ pkgs.makeWrapper ]; - mkdir -p $out/share/hermes-agent $out/bin - cp -r ${bundledSkills} $out/share/hermes-agent/skills + installPhase = '' + runHook preInstall - ${pkgs.lib.concatMapStringsSep "\n" (name: '' - makeWrapper ${hermesVenv}/bin/${name} $out/bin/${name} \ - --suffix PATH : "${runtimePath}" \ - --set HERMES_BUNDLED_SKILLS $out/share/hermes-agent/skills - '') [ "hermes" "hermes-agent" "hermes-acp" ]} + mkdir -p $out/share/hermes-agent $out/bin + cp -r ${bundledSkills} $out/share/hermes-agent/skills - runHook postInstall - ''; + # copy pre-built TUI (same layout as dev: ui-tui/dist/ + node_modules/) + mkdir -p $out/ui-tui + cp -r ${hermesTui}/lib/hermes-tui/* $out/ui-tui/ - meta = with pkgs.lib; { - description = "AI agent with advanced tool-calling capabilities"; - homepage = "https://github.com/NousResearch/hermes-agent"; - mainProgram = "hermes"; - license = licenses.mit; - platforms = platforms.unix; + ${pkgs.lib.concatMapStringsSep "\n" + (name: '' + makeWrapper ${hermesVenv}/bin/${name} $out/bin/${name} \ + --suffix PATH : "${runtimePath}" \ + --set HERMES_BUNDLED_SKILLS $out/share/hermes-agent/skills \ + --set HERMES_TUI_DIR $out/ui-tui \ + --set HERMES_PYTHON ${hermesVenv}/bin/python3 + '') + [ + "hermes" + "hermes-agent" + "hermes-acp" + ] + } + + runHook postInstall + ''; + + passthru.devShellHook = '' + STAMP=".nix-stamps/hermes-agent" + STAMP_VALUE="${pyprojectHash}:${uvLockHash}" + if [ ! -f "$STAMP" ] || [ "$(cat "$STAMP")" != "$STAMP_VALUE" ]; then + echo "hermes-agent: installing Python dependencies..." + uv venv .venv --python ${pkgs.python311}/bin/python3 2>/dev/null || true + source .venv/bin/activate + uv pip install -e ".[all]" + [ -d mini-swe-agent ] && uv pip install -e ./mini-swe-agent 2>/dev/null || true + [ -d tinker-atropos ] && uv pip install -e ./tinker-atropos 2>/dev/null || true + mkdir -p .nix-stamps + echo "$STAMP_VALUE" > "$STAMP" + else + source .venv/bin/activate + export HERMES_PYTHON=${hermesVenv}/bin/python3 + fi + ''; + + meta = with pkgs.lib; { + description = "AI agent with advanced tool-calling capabilities"; + homepage = "https://github.com/NousResearch/hermes-agent"; + mainProgram = "hermes"; + license = licenses.mit; + platforms = platforms.unix; + }; }; + + tui = hermesTui; }; }; } diff --git a/nix/tui.nix b/nix/tui.nix new file mode 100644 index 0000000000..70eb67f949 --- /dev/null +++ b/nix/tui.nix @@ -0,0 +1,82 @@ +# nix/tui.nix — Hermes TUI (Ink/React) compiled with tsc and bundled +{ pkgs, npm-lockfile-fix, ... }: +let + src = ../ui-tui; + npmDeps = pkgs.fetchNpmDeps { + inherit src; + hash = "sha256-zsUPmbC6oMUO10EhS3ptvDjwlfpCSEmrkjyeORw7fac="; + }; + + packageJson = builtins.fromJSON (builtins.readFile (src + "/package.json")); + version = packageJson.version; + + npmLockHash = builtins.hashString "sha256" (builtins.readFile ../ui-tui/package-lock.json); +in +pkgs.buildNpmPackage { + pname = "hermes-tui"; + inherit src npmDeps version; + + doCheck = false; + + postPatch = '' + # fetchNpmDeps strips the trailing newline; match it so the diff passes + sed -i -z 's/\n$//' package-lock.json + ''; + + installPhase = '' + runHook preInstall + + mkdir -p $out/lib/hermes-tui + + cp -r dist $out/lib/hermes-tui/dist + + # runtime node_modules + cp -r node_modules $out/lib/hermes-tui/node_modules + + # @hermes/ink is a file: dependency, we need to copy it in fr + rm -f $out/lib/hermes-tui/node_modules/@hermes/ink + cp -r packages/hermes-ink $out/lib/hermes-tui/node_modules/@hermes/ink + + # package.json needed for "type": "module" resolution + cp package.json $out/lib/hermes-tui/ + + runHook postInstall + ''; + + nativeBuildInputs = [ + (pkgs.writeShellScriptBin "update_tui_lockfile" '' + set -euox pipefail + + # get root of repo + REPO_ROOT=$(git rev-parse --show-toplevel) + + # cd into ui-tui and reinstall + cd "$REPO_ROOT/ui-tui" + rm -rf node_modules/ + npm cache clean --force + CI=true npm install # ci env var to suppress annoying unicode install banner lag + ${pkgs.lib.getExe npm-lockfile-fix} ./package-lock.json + + NIX_FILE="$REPO_ROOT/nix/tui.nix" + # compute the new hash + sed -i "s/hash = \"[^\"]*\";/hash = \"\";/" $NIX_FILE + NIX_OUTPUT=$(nix build .#tui 2>&1 || true) + NEW_HASH=$(echo "$NIX_OUTPUT" | grep 'got:' | awk '{print $2}') + echo got new hash $NEW_HASH + sed -i "s|hash = \"[^\"]*\";|hash = \"$NEW_HASH\";|" $NIX_FILE + nix build .#tui + echo "Updated npm hash in $NIX_FILE to $NEW_HASH" + '') + ]; + + passthru.devShellHook = '' + STAMP=".nix-stamps/hermes-tui" + STAMP_VALUE="${npmLockHash}" + if [ ! -f "$STAMP" ] || [ "$(cat "$STAMP")" != "$STAMP_VALUE" ]; then + echo "hermes-tui: installing npm dependencies..." + cd ui-tui && CI=true npm install --silent --no-fund --no-audit 2>/dev/null && cd .. + mkdir -p .nix-stamps + echo "$STAMP_VALUE" > "$STAMP" + fi + ''; +} diff --git a/pyproject.toml b/pyproject.toml index 0cac0b6b7c..b73bef9379 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -126,7 +126,7 @@ py-modules = ["run_agent", "model_tools", "toolsets", "batch_runner", "trajector hermes_cli = ["web_dist/**/*"] [tool.setuptools.packages.find] -include = ["agent", "tools", "tools.*", "hermes_cli", "gateway", "gateway.*", "cron", "acp_adapter", "plugins", "plugins.*"] +include = ["agent", "tools", "tools.*", "hermes_cli", "gateway", "gateway.*", "tui_gateway", "tui_gateway.*", "cron", "acp_adapter", "plugins", "plugins.*"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/run_agent.py b/run_agent.py index 34f7518a2b..bb8cfa459d 100644 --- a/run_agent.py +++ b/run_agent.py @@ -5894,6 +5894,7 @@ class AIAgent: ) except Exception: pass + self._emit_status("🔄 Reconnected — resuming…") continue self._emit_status( "❌ Connection to provider failed after " @@ -7002,7 +7003,7 @@ class AIAgent: # (gateway, batch, quiet) still get reasoning. # Any reasoning that wasn't shown during streaming is caught by the # CLI post-response display fallback (cli.py _reasoning_shown_this_turn). - if not self.stream_delta_callback: + if not self.stream_delta_callback and not self._stream_callback: try: self.reasoning_callback(reasoning_text) except Exception: @@ -10443,9 +10444,9 @@ class AIAgent: pass wait_time = _retry_after if _retry_after else jittered_backoff(retry_count, base_delay=2.0, max_delay=60.0) if is_rate_limited: - self._emit_status(f"⏱️ Rate limit reached. Waiting {wait_time}s before retry (attempt {retry_count + 1}/{max_retries})...") + self._emit_status(f"⏱️ Rate limited. Waiting {wait_time:.1f}s (attempt {retry_count + 1}/{max_retries})...") else: - self._emit_status(f"⏳ Retrying in {wait_time}s (attempt {retry_count}/{max_retries})...") + self._emit_status(f"⏳ Retrying in {wait_time:.1f}s (attempt {retry_count}/{max_retries})...") logger.warning( "Retrying API call in %ss (attempt %s/%s) %s error=%s", wait_time, @@ -10861,7 +10862,14 @@ class AIAgent: elif self.quiet_mode: clean = self._strip_think_blocks(turn_content).strip() if clean: - self._vprint(f" ┊ 💬 {clean}") + relayed = False + if ( + self.tool_progress_callback + and getattr(self, "platform", "") == "tui" + ): + relayed = True + if not relayed: + self._vprint(f" ┊ 💬 {clean}") # Pop thinking-only prefill message(s) before appending # (tool-call path — same rationale as the final-response path). diff --git a/scripts/install.ps1 b/scripts/install.ps1 index d644c6221f..80ed53cce8 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -721,6 +721,20 @@ function Install-NodeDeps { } } + # Install TUI dependencies + $tuiDir = "$InstallDir\ui-tui" + if (Test-Path "$tuiDir\package.json") { + Write-Info "Installing TUI dependencies..." + Push-Location $tuiDir + try { + npm install --silent 2>&1 | Out-Null + Write-Success "TUI dependencies installed" + } catch { + Write-Warn "TUI npm install failed (hermes --tui may not work)" + } + Pop-Location + } + # Install WhatsApp bridge dependencies $bridgeDir = "$InstallDir\scripts\whatsapp-bridge" if (Test-Path "$bridgeDir\package.json") { diff --git a/scripts/install.sh b/scripts/install.sh index 0de5da908f..c6524cefcb 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1194,6 +1194,16 @@ install_node_deps() { log_success "Browser engine setup complete" fi + # Install TUI dependencies + if [ -f "$INSTALL_DIR/ui-tui/package.json" ]; then + log_info "Installing TUI dependencies..." + cd "$INSTALL_DIR/ui-tui" + npm install --silent 2>/dev/null || { + log_warn "TUI npm install failed (hermes --tui may not work)" + } + log_success "TUI dependencies installed" + fi + # Install WhatsApp bridge dependencies if [ -f "$INSTALL_DIR/scripts/whatsapp-bridge/package.json" ]; then log_info "Installing WhatsApp bridge dependencies..." diff --git a/scripts/lib/node-bootstrap.sh b/scripts/lib/node-bootstrap.sh new file mode 100644 index 0000000000..9eadc479dd --- /dev/null +++ b/scripts/lib/node-bootstrap.sh @@ -0,0 +1,238 @@ +#!/usr/bin/env bash +# ============================================================================ +# scripts/lib/node-bootstrap.sh +# ---------------------------------------------------------------------------- +# Sourceable helper: ensure Node.js >= MIN_VERSION is available for the TUI +# (React + Ink), browser tools, and the WhatsApp bridge. +# +# Strategy (first hit wins — respects the user's existing tooling): +# 1. modern `node` already on PATH +# 2. ~/.hermes/node/ from a prior Hermes-managed install +# 3. fnm, proto, nvm (in that order) if the user already uses a version manager +# 4. Termux `pkg`, macOS Homebrew +# 5. pinned nodejs.org tarball into ~/.hermes/node/ (always works, zero shell rc edits) +# +# Usage: +# source scripts/lib/node-bootstrap.sh +# ensure_node # returns 0 on success, non-zero on failure +# if [ "$HERMES_NODE_AVAILABLE" = true ]; then ...; fi +# +# Env inputs (set before sourcing to override defaults): +# HERMES_NODE_MIN_VERSION (default: 20) — accepted on PATH +# HERMES_NODE_TARGET_MAJOR (default: 22) — installed when we install +# HERMES_HOME (default: $HOME/.hermes) +# ============================================================================ + +HERMES_NODE_MIN_VERSION="${HERMES_NODE_MIN_VERSION:-20}" +HERMES_NODE_TARGET_MAJOR="${HERMES_NODE_TARGET_MAJOR:-22}" +HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}" +HERMES_NODE_AVAILABLE=false + +# --------------------------------------------------------------------------- +# Logging — prefer the host script's log_* helpers when present +# --------------------------------------------------------------------------- + +_nb_log() { declare -F log_info >/dev/null 2>&1 && log_info "$*" || printf '→ %s\n' "$*" >&2; } +_nb_ok() { declare -F log_success >/dev/null 2>&1 && log_success "$*" || printf '✓ %s\n' "$*" >&2; } +_nb_warn() { declare -F log_warn >/dev/null 2>&1 && log_warn "$*" || printf '⚠ %s\n' "$*" >&2; } + +# --------------------------------------------------------------------------- +# Platform + version helpers +# --------------------------------------------------------------------------- + +_nb_is_termux() { + [ -n "${TERMUX_VERSION:-}" ] || [[ "${PREFIX:-}" == *"com.termux/files/usr"* ]] +} + +_nb_node_major() { + local v + v=$(node --version 2>/dev/null | sed 's/^v//' | cut -d. -f1) + [[ "$v" =~ ^[0-9]+$ ]] && echo "$v" || echo 0 +} + +_nb_have_modern_node() { + command -v node >/dev/null 2>&1 || return 1 + [ "$(_nb_node_major)" -ge "$HERMES_NODE_MIN_VERSION" ] +} + +# --------------------------------------------------------------------------- +# Version-manager paths — respect what the user already uses +# --------------------------------------------------------------------------- + +_nb_try_fnm() { + command -v fnm >/dev/null 2>&1 || return 1 + _nb_log "fnm detected — installing Node $HERMES_NODE_TARGET_MAJOR..." + eval "$(fnm env 2>/dev/null)" || true + fnm install "$HERMES_NODE_TARGET_MAJOR" >/dev/null 2>&1 || return 1 + fnm use "$HERMES_NODE_TARGET_MAJOR" >/dev/null 2>&1 || return 1 + _nb_have_modern_node || return 1 + _nb_ok "Node $(node --version) activated via fnm" + return 0 +} + +_nb_try_proto() { + command -v proto >/dev/null 2>&1 || return 1 + _nb_log "proto detected — installing Node $HERMES_NODE_TARGET_MAJOR..." + proto install node "$HERMES_NODE_TARGET_MAJOR" >/dev/null 2>&1 || return 1 + _nb_have_modern_node || return 1 + _nb_ok "Node $(node --version) activated via proto" + return 0 +} + +_nb_try_nvm() { + local nvm_sh="${NVM_DIR:-$HOME/.nvm}/nvm.sh" + [ -s "$nvm_sh" ] || return 1 + # shellcheck source=/dev/null + \. "$nvm_sh" >/dev/null 2>&1 || return 1 + _nb_log "nvm detected — installing Node $HERMES_NODE_TARGET_MAJOR..." + nvm install "$HERMES_NODE_TARGET_MAJOR" >/dev/null 2>&1 || return 1 + nvm use "$HERMES_NODE_TARGET_MAJOR" >/dev/null 2>&1 || return 1 + _nb_have_modern_node || return 1 + _nb_ok "Node $(node --version) activated via nvm" + return 0 +} + +# --------------------------------------------------------------------------- +# Platform package managers +# --------------------------------------------------------------------------- + +_nb_try_termux_pkg() { + _nb_is_termux || return 1 + _nb_log "Installing Node.js via pkg..." + pkg install -y nodejs >/dev/null 2>&1 || return 1 + _nb_have_modern_node || return 1 + _nb_ok "Node $(node --version) installed via pkg" + return 0 +} + +_nb_try_brew() { + [ "$(uname -s)" = "Darwin" ] || return 1 + command -v brew >/dev/null 2>&1 || return 1 + _nb_log "Installing Node via Homebrew..." + brew install "node@${HERMES_NODE_TARGET_MAJOR}" >/dev/null 2>&1 \ + || brew install node >/dev/null 2>&1 \ + || return 1 + brew link --overwrite --force "node@${HERMES_NODE_TARGET_MAJOR}" >/dev/null 2>&1 || true + _nb_have_modern_node || return 1 + _nb_ok "Node $(node --version) installed via Homebrew" + return 0 +} + +# --------------------------------------------------------------------------- +# Bundled binary fallback — always works, no shell rc edits +# --------------------------------------------------------------------------- + +_nb_install_bundled_node() { + local arch node_arch os_name node_os + arch=$(uname -m) + case "$arch" in + x86_64) node_arch="x64" ;; + aarch64|arm64) node_arch="arm64" ;; + armv7l) node_arch="armv7l" ;; + *) + _nb_warn "Unsupported arch ($arch) — install Node.js manually: https://nodejs.org/" + return 1 + ;; + esac + + os_name=$(uname -s) + case "$os_name" in + Linux*) node_os="linux" ;; + Darwin*) node_os="darwin" ;; + *) + _nb_warn "Unsupported OS ($os_name) — install Node.js manually: https://nodejs.org/" + return 1 + ;; + esac + + local index_url="https://nodejs.org/dist/latest-v${HERMES_NODE_TARGET_MAJOR}.x/" + local tarball + tarball=$(curl -fsSL "$index_url" \ + | grep -oE "node-v${HERMES_NODE_TARGET_MAJOR}\.[0-9]+\.[0-9]+-${node_os}-${node_arch}\.tar\.xz" \ + | head -1) + if [ -z "$tarball" ]; then + tarball=$(curl -fsSL "$index_url" \ + | grep -oE "node-v${HERMES_NODE_TARGET_MAJOR}\.[0-9]+\.[0-9]+-${node_os}-${node_arch}\.tar\.gz" \ + | head -1) + fi + if [ -z "$tarball" ]; then + _nb_warn "Could not resolve Node $HERMES_NODE_TARGET_MAJOR binary for $node_os-$node_arch" + return 1 + fi + + local tmp + tmp=$(mktemp -d) + _nb_log "Downloading $tarball..." + curl -fsSL "${index_url}${tarball}" -o "$tmp/$tarball" || { + _nb_warn "Download failed"; rm -rf "$tmp"; return 1 + } + + _nb_log "Extracting to $HERMES_HOME/node/..." + if [[ "$tarball" == *.tar.xz ]]; then + tar xf "$tmp/$tarball" -C "$tmp" || { rm -rf "$tmp"; return 1; } + else + tar xzf "$tmp/$tarball" -C "$tmp" || { rm -rf "$tmp"; return 1; } + fi + + local extracted + extracted=$(find "$tmp" -maxdepth 1 -type d -name 'node-v*' 2>/dev/null | head -1) + if [ ! -d "$extracted" ]; then + _nb_warn "Extraction produced no node-v* directory" + rm -rf "$tmp" + return 1 + fi + + mkdir -p "$HERMES_HOME" + rm -rf "$HERMES_HOME/node" + mv "$extracted" "$HERMES_HOME/node" + rm -rf "$tmp" + + mkdir -p "$HOME/.local/bin" + ln -sf "$HERMES_HOME/node/bin/node" "$HOME/.local/bin/node" + ln -sf "$HERMES_HOME/node/bin/npm" "$HOME/.local/bin/npm" + ln -sf "$HERMES_HOME/node/bin/npx" "$HOME/.local/bin/npx" + export PATH="$HERMES_HOME/node/bin:$PATH" + + _nb_have_modern_node || return 1 + _nb_ok "Node $(node --version) installed to $HERMES_HOME/node/" + return 0 +} + +# --------------------------------------------------------------------------- +# Public entry point +# --------------------------------------------------------------------------- + +ensure_node() { + HERMES_NODE_AVAILABLE=false + + if _nb_have_modern_node; then + _nb_ok "Node $(node --version) found" + HERMES_NODE_AVAILABLE=true + return 0 + fi + + if [ -x "$HERMES_HOME/node/bin/node" ]; then + export PATH="$HERMES_HOME/node/bin:$PATH" + if _nb_have_modern_node; then + _nb_ok "Node $(node --version) found (Hermes-managed)" + HERMES_NODE_AVAILABLE=true + return 0 + fi + fi + + # Version managers first — respect the user's existing setup. + _nb_try_fnm && { HERMES_NODE_AVAILABLE=true; return 0; } + _nb_try_proto && { HERMES_NODE_AVAILABLE=true; return 0; } + _nb_try_nvm && { HERMES_NODE_AVAILABLE=true; return 0; } + + # Platform package managers. + _nb_try_termux_pkg && { HERMES_NODE_AVAILABLE=true; return 0; } + _nb_try_brew && { HERMES_NODE_AVAILABLE=true; return 0; } + + # Last resort: pinned nodejs.org tarball. + _nb_install_bundled_node && { HERMES_NODE_AVAILABLE=true; return 0; } + + _nb_warn "Node.js install failed — TUI and browser tools will be unavailable." + _nb_warn "Install manually: https://nodejs.org/en/download/ (or: \`brew install node\`, \`fnm install $HERMES_NODE_TARGET_MAJOR\`, etc.)" + return 1 +} diff --git a/tests/cli/test_cli_copy_command.py b/tests/cli/test_cli_copy_command.py new file mode 100644 index 0000000000..6cd010df37 --- /dev/null +++ b/tests/cli/test_cli_copy_command.py @@ -0,0 +1,71 @@ +"""Tests for CLI /copy command.""" + +from unittest.mock import MagicMock, patch + +from cli import HermesCLI + + +def _make_cli() -> HermesCLI: + cli_obj = HermesCLI.__new__(HermesCLI) + cli_obj.config = {} + cli_obj.console = MagicMock() + cli_obj.agent = None + cli_obj.conversation_history = [] + cli_obj.session_id = "sess-copy-test" + cli_obj._pending_input = MagicMock() + cli_obj._app = None + return cli_obj + + +def test_copy_copies_latest_assistant_message(): + cli_obj = _make_cli() + cli_obj.conversation_history = [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": "first"}, + {"role": "assistant", "content": "latest"}, + ] + + with patch.object(cli_obj, "_write_osc52_clipboard") as mock_copy: + result = cli_obj.process_command("/copy") + + assert result is True + mock_copy.assert_called_once_with("latest") + + +def test_copy_with_index_uses_requested_assistant_message(): + cli_obj = _make_cli() + cli_obj.conversation_history = [ + {"role": "assistant", "content": "one"}, + {"role": "assistant", "content": "two"}, + ] + + with patch.object(cli_obj, "_write_osc52_clipboard") as mock_copy: + cli_obj.process_command("/copy 1") + + mock_copy.assert_called_once_with("one") + + +def test_copy_strips_reasoning_blocks_before_copy(): + cli_obj = _make_cli() + cli_obj.conversation_history = [ + { + "role": "assistant", + "content": "internal\nVisible answer", + } + ] + + with patch.object(cli_obj, "_write_osc52_clipboard") as mock_copy: + cli_obj.process_command("/copy") + + mock_copy.assert_called_once_with("Visible answer") + + +def test_copy_invalid_index_does_not_copy(): + cli_obj = _make_cli() + cli_obj.conversation_history = [{"role": "assistant", "content": "only"}] + + with patch.object(cli_obj, "_write_osc52_clipboard") as mock_copy, patch("cli._cprint") as mock_print: + cli_obj.process_command("/copy 99") + + mock_copy.assert_not_called() + assert any("Invalid response number" in str(call) for call in mock_print.call_args_list) diff --git a/tests/gateway/test_command_bypass_active_session.py b/tests/gateway/test_command_bypass_active_session.py index 180c15f711..d8098005c4 100644 --- a/tests/gateway/test_command_bypass_active_session.py +++ b/tests/gateway/test_command_bypass_active_session.py @@ -160,6 +160,30 @@ class TestCommandBypassActiveSession: assert sk not in adapter._pending_messages assert any("handled:status" in r for r in adapter.sent_responses) + @pytest.mark.asyncio + async def test_agents_bypasses_guard(self): + """/agents must bypass so active-task queries don't interrupt runs.""" + adapter = _make_adapter() + sk = _session_key() + adapter._active_sessions[sk] = asyncio.Event() + + await adapter.handle_message(_make_event("/agents")) + + assert sk not in adapter._pending_messages + assert any("handled:agents" in r for r in adapter.sent_responses) + + @pytest.mark.asyncio + async def test_tasks_alias_bypasses_guard(self): + """/tasks alias must bypass active-session guard too.""" + adapter = _make_adapter() + sk = _session_key() + adapter._active_sessions[sk] = asyncio.Event() + + await adapter.handle_message(_make_event("/tasks")) + + assert sk not in adapter._pending_messages + assert any("handled:tasks" in r for r in adapter.sent_responses) + @pytest.mark.asyncio async def test_background_bypasses_guard(self): """/background must bypass so it spawns a parallel task, not an interrupt.""" diff --git a/tests/gateway/test_status_command.py b/tests/gateway/test_status_command.py index 5544800871..c4a64f30ab 100644 --- a/tests/gateway/test_status_command.py +++ b/tests/gateway/test_status_command.py @@ -1,6 +1,7 @@ """Tests for gateway /status behavior and token persistence.""" from datetime import datetime +import time from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock @@ -111,6 +112,75 @@ async def test_status_command_includes_session_title_when_present(): assert "**Title:** My titled session" in result +@pytest.mark.asyncio +async def test_agents_command_reports_active_agents_and_processes(monkeypatch): + session_key = build_session_key(_make_source()) + session_entry = SessionEntry( + session_key=session_key, + session_id="sess-1", + created_at=datetime.now(), + updated_at=datetime.now(), + platform=Platform.TELEGRAM, + chat_type="dm", + total_tokens=0, + ) + runner = _make_runner(session_entry) + running_agent = SimpleNamespace( + session_id="sess-running", + model="openrouter/test-model", + interrupt=MagicMock(), + get_activity_summary=lambda: {"seconds_since_activity": 0}, + ) + runner._running_agents[session_key] = running_agent + runner._running_agents_ts = {session_key: time.time() - 8} + runner._background_tasks = set() + + class _FakeRegistry: + def list_sessions(self): + return [ + { + "session_id": "proc-1", + "status": "running", + "uptime_seconds": 17, + "command": "sleep 30", + } + ] + + monkeypatch.setattr("tools.process_registry.process_registry", _FakeRegistry()) + + result = await runner._handle_message(_make_event("/agents")) + + assert "**Active agents:** 1" in result + assert "**Running background processes:** 1" in result + assert "proc-1" in result + running_agent.interrupt.assert_not_called() + + +@pytest.mark.asyncio +async def test_tasks_alias_routes_to_agents_command(monkeypatch): + session_entry = SessionEntry( + session_key=build_session_key(_make_source()), + session_id="sess-1", + created_at=datetime.now(), + updated_at=datetime.now(), + platform=Platform.TELEGRAM, + chat_type="dm", + total_tokens=0, + ) + runner = _make_runner(session_entry) + runner._background_tasks = set() + + class _FakeRegistry: + def list_sessions(self): + return [] + + monkeypatch.setattr("tools.process_registry.process_registry", _FakeRegistry()) + + result = await runner._handle_message(_make_event("/tasks")) + + assert "Active Agents & Tasks" in result + + @pytest.mark.asyncio async def test_handle_message_persists_agent_token_counts(monkeypatch): import gateway.run as gateway_run diff --git a/tests/hermes_cli/test_cmd_update.py b/tests/hermes_cli/test_cmd_update.py index 9ffa809a5e..c8f284228b 100644 --- a/tests/hermes_cli/test_cmd_update.py +++ b/tests/hermes_cli/test_cmd_update.py @@ -106,6 +106,49 @@ class TestCmdUpdateBranchFallback: pull_cmds = [c for c in commands if "pull" in c] assert len(pull_cmds) == 0 + @patch("shutil.which") + @patch("subprocess.run") + def test_update_refreshes_repo_and_tui_node_dependencies( + self, mock_run, mock_which, mock_args + ): + mock_which.side_effect = {"uv": "/usr/bin/uv", "npm": "/usr/bin/npm"}.get + mock_run.side_effect = _make_run_side_effect( + branch="main", verify_ok=True, commit_count="1" + ) + + cmd_update(mock_args) + + npm_calls = [ + (call.args[0], call.kwargs.get("cwd")) + for call in mock_run.call_args_list + if call.args and call.args[0][0] == "/usr/bin/npm" + ] + + assert npm_calls == [ + ( + [ + "/usr/bin/npm", + "install", + "--silent", + "--no-fund", + "--no-audit", + "--progress=false", + ], + PROJECT_ROOT, + ), + ( + [ + "/usr/bin/npm", + "install", + "--silent", + "--no-fund", + "--no-audit", + "--progress=false", + ], + PROJECT_ROOT / "ui-tui", + ), + ] + def test_update_non_interactive_skips_migration_prompt(self, mock_args, capsys): """When stdin/stdout aren't TTYs, config migration prompt is skipped.""" with patch("shutil.which", return_value=None), patch( diff --git a/tests/hermes_cli/test_commands.py b/tests/hermes_cli/test_commands.py index 8b35970969..c14e60224f 100644 --- a/tests/hermes_cli/test_commands.py +++ b/tests/hermes_cli/test_commands.py @@ -93,6 +93,8 @@ class TestResolveCommand: def test_canonical_name_resolves(self): assert resolve_command("help").name == "help" assert resolve_command("background").name == "background" + assert resolve_command("copy").name == "copy" + assert resolve_command("agents").name == "agents" def test_alias_resolves_to_canonical(self): assert resolve_command("bg").name == "background" @@ -102,6 +104,7 @@ class TestResolveCommand: assert resolve_command("gateway").name == "platforms" assert resolve_command("set-home").name == "sethome" assert resolve_command("reload_mcp").name == "reload-mcp" + assert resolve_command("tasks").name == "agents" def test_leading_slash_stripped(self): assert resolve_command("/help").name == "help" diff --git a/tests/hermes_cli/test_model_validation.py b/tests/hermes_cli/test_model_validation.py index d07cb62dfa..cbd4121662 100644 --- a/tests/hermes_cli/test_model_validation.py +++ b/tests/hermes_cli/test_model_validation.py @@ -403,7 +403,8 @@ class TestValidateFormatChecks: def test_no_slash_model_rejected_if_not_in_api(self): result = _validate("gpt-5.4", api_models=["openai/gpt-5.4"]) - assert result["accepted"] is True + assert result["accepted"] is False + assert result["persist"] is False assert "not found" in result["message"] @@ -429,10 +430,10 @@ class TestValidateApiFound: # -- validate — API not found ------------------------------------------------ class TestValidateApiNotFound: - def test_model_not_in_api_accepted_with_warning(self): + def test_model_not_in_api_rejected_with_guidance(self): result = _validate("anthropic/claude-nonexistent") - assert result["accepted"] is True - assert result["persist"] is True + assert result["accepted"] is False + assert result["persist"] is False assert "not found" in result["message"] def test_warning_includes_suggestions(self): @@ -456,30 +457,29 @@ class TestValidateApiNotFound: assert "not found" in result["message"] -# -- validate — API unreachable — accept and persist everything ---------------- +# -- validate — API unreachable — reject with guidance ---------------- class TestValidateApiFallback: - def test_any_model_accepted_when_api_down(self): + def test_any_model_rejected_when_api_down(self): result = _validate("anthropic/claude-opus-4.6", api_models=None) - assert result["accepted"] is True - assert result["persist"] is True + assert result["accepted"] is False + assert result["persist"] is False - def test_unknown_model_also_accepted_when_api_down(self): - """No hardcoded catalog gatekeeping — accept, persist, and warn.""" + def test_unknown_model_also_rejected_when_api_down(self): result = _validate("anthropic/claude-next-gen", api_models=None) - assert result["accepted"] is True - assert result["persist"] is True + assert result["accepted"] is False + assert result["persist"] is False assert "could not reach" in result["message"].lower() - def test_zai_model_accepted_when_api_down(self): + def test_zai_model_rejected_when_api_down(self): result = _validate("glm-5", provider="zai", api_models=None) - assert result["accepted"] is True - assert result["persist"] is True + assert result["accepted"] is False + assert result["persist"] is False - def test_unknown_provider_accepted_when_api_down(self): + def test_unknown_provider_rejected_when_api_down(self): result = _validate("some-model", provider="totally-unknown", api_models=None) - assert result["accepted"] is True - assert result["persist"] is True + assert result["accepted"] is False + assert result["persist"] is False def test_custom_endpoint_warns_with_probed_url_and_v1_hint(self): with patch( @@ -499,8 +499,8 @@ class TestValidateApiFallback: base_url="http://localhost:8000", ) - assert result["accepted"] is True - assert result["persist"] is True + assert result["accepted"] is False + assert result["persist"] is False assert "http://localhost:8000/v1/models" in result["message"] assert "http://localhost:8000/v1" in result["message"] diff --git a/tests/hermes_cli/test_tui_npm_install.py b/tests/hermes_cli/test_tui_npm_install.py new file mode 100644 index 0000000000..3f3191ccf3 --- /dev/null +++ b/tests/hermes_cli/test_tui_npm_install.py @@ -0,0 +1,53 @@ +"""_tui_need_npm_install: auto npm when lockfile ahead of node_modules.""" + +import os +from pathlib import Path + +import pytest + + +@pytest.fixture +def main_mod(): + import hermes_cli.main as m + + return m + + +def _touch_ink(root: Path) -> None: + ink = root / "node_modules" / "@hermes" / "ink" / "package.json" + ink.parent.mkdir(parents=True, exist_ok=True) + ink.write_text("{}") + + +def test_need_install_when_ink_missing(tmp_path: Path, main_mod) -> None: + (tmp_path / "package-lock.json").write_text("{}") + assert main_mod._tui_need_npm_install(tmp_path) is True + + +def test_need_install_when_lock_newer_than_marker(tmp_path: Path, main_mod) -> None: + _touch_ink(tmp_path) + (tmp_path / "package-lock.json").write_text("{}") + (tmp_path / "node_modules" / ".package-lock.json").write_text("{}") + os.utime(tmp_path / "package-lock.json", (200, 200)) + os.utime(tmp_path / "node_modules" / ".package-lock.json", (100, 100)) + assert main_mod._tui_need_npm_install(tmp_path) is True + + +def test_no_install_when_lock_older_than_marker(tmp_path: Path, main_mod) -> None: + _touch_ink(tmp_path) + (tmp_path / "package-lock.json").write_text("{}") + (tmp_path / "node_modules" / ".package-lock.json").write_text("{}") + os.utime(tmp_path / "package-lock.json", (100, 100)) + os.utime(tmp_path / "node_modules" / ".package-lock.json", (200, 200)) + assert main_mod._tui_need_npm_install(tmp_path) is False + + +def test_need_install_when_marker_missing(tmp_path: Path, main_mod) -> None: + _touch_ink(tmp_path) + (tmp_path / "package-lock.json").write_text("{}") + assert main_mod._tui_need_npm_install(tmp_path) is True + + +def test_no_install_without_lockfile_when_ink_present(tmp_path: Path, main_mod) -> None: + _touch_ink(tmp_path) + assert main_mod._tui_need_npm_install(tmp_path) is False diff --git a/tests/hermes_cli/test_tui_resume_flow.py b/tests/hermes_cli/test_tui_resume_flow.py new file mode 100644 index 0000000000..c7e551ea1c --- /dev/null +++ b/tests/hermes_cli/test_tui_resume_flow.py @@ -0,0 +1,121 @@ +from argparse import Namespace +import sys +import types + +import pytest + + +def _args(**overrides): + base = { + "continue_last": None, + "resume": None, + "tui": True, + } + base.update(overrides) + return Namespace(**base) + + +@pytest.fixture +def main_mod(monkeypatch): + import hermes_cli.main as mod + + monkeypatch.setattr(mod, "_has_any_provider_configured", lambda: True) + return mod + + +def test_cmd_chat_tui_continue_uses_latest_tui_session(monkeypatch, main_mod): + calls = [] + captured = {} + + def fake_resolve_last(source="cli"): + calls.append(source) + return "20260408_235959_a1b2c3" if source == "tui" else None + + def fake_launch(resume_session_id=None, tui_dev=False): + captured["resume"] = resume_session_id + raise SystemExit(0) + + monkeypatch.setattr(main_mod, "_resolve_last_session", fake_resolve_last) + monkeypatch.setattr(main_mod, "_resolve_session_by_name_or_id", lambda val: val) + monkeypatch.setattr(main_mod, "_launch_tui", fake_launch) + + with pytest.raises(SystemExit): + main_mod.cmd_chat(_args(continue_last=True)) + + assert calls == ["tui"] + assert captured["resume"] == "20260408_235959_a1b2c3" + + +def test_cmd_chat_tui_continue_falls_back_to_latest_cli_session(monkeypatch, main_mod): + calls = [] + captured = {} + + def fake_resolve_last(source="cli"): + calls.append(source) + if source == "tui": + return None + if source == "cli": + return "20260408_235959_d4e5f6" + return None + + def fake_launch(resume_session_id=None, tui_dev=False): + captured["resume"] = resume_session_id + raise SystemExit(0) + + monkeypatch.setattr(main_mod, "_resolve_last_session", fake_resolve_last) + monkeypatch.setattr(main_mod, "_resolve_session_by_name_or_id", lambda val: val) + monkeypatch.setattr(main_mod, "_launch_tui", fake_launch) + + with pytest.raises(SystemExit): + main_mod.cmd_chat(_args(continue_last=True)) + + assert calls == ["tui", "cli"] + assert captured["resume"] == "20260408_235959_d4e5f6" + + +def test_cmd_chat_tui_resume_resolves_title_before_launch(monkeypatch, main_mod): + captured = {} + + def fake_launch(resume_session_id=None, tui_dev=False): + captured["resume"] = resume_session_id + raise SystemExit(0) + + monkeypatch.setattr(main_mod, "_resolve_session_by_name_or_id", lambda val: "20260409_000000_aa11bb") + monkeypatch.setattr(main_mod, "_launch_tui", fake_launch) + + with pytest.raises(SystemExit): + main_mod.cmd_chat(_args(resume="my t0p session")) + + assert captured["resume"] == "20260409_000000_aa11bb" + + +def test_print_tui_exit_summary_includes_resume_and_token_totals(monkeypatch, capsys): + import hermes_cli.main as main_mod + + class _FakeDB: + def get_session(self, session_id): + assert session_id == "20260409_000001_abc123" + return { + "message_count": 2, + "input_tokens": 10, + "output_tokens": 6, + "cache_read_tokens": 2, + "cache_write_tokens": 2, + "reasoning_tokens": 1, + } + + def get_session_title(self, _session_id): + return "demo title" + + def close(self): + return None + + monkeypatch.setitem(sys.modules, "hermes_state", types.SimpleNamespace(SessionDB=lambda: _FakeDB())) + + main_mod._print_tui_exit_summary("20260409_000001_abc123") + out = capsys.readouterr().out + + assert "Resume this session with:" in out + assert "hermes --tui --resume 20260409_000001_abc123" in out + assert 'hermes --tui -c "demo title"' in out + assert "Tokens: 21 (in 10, out 6, cache 4, reasoning 1)" in out diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py new file mode 100644 index 0000000000..e7681b784c --- /dev/null +++ b/tests/test_tui_gateway_server.py @@ -0,0 +1,440 @@ +import json +import sys +import threading +import time +import types +from pathlib import Path +from unittest.mock import patch + +from tui_gateway import server + + +class _ChunkyStdout: + def __init__(self): + self.parts: list[str] = [] + + def write(self, text: str) -> int: + for ch in text: + self.parts.append(ch) + time.sleep(0.0001) + return len(text) + + def flush(self) -> None: + return None + + +class _BrokenStdout: + def write(self, text: str) -> int: + raise BrokenPipeError + + def flush(self) -> None: + return None + + +def test_write_json_serializes_concurrent_writes(monkeypatch): + out = _ChunkyStdout() + monkeypatch.setattr(server, "_real_stdout", out) + + threads = [ + threading.Thread(target=server.write_json, args=({"seq": i, "text": "x" * 24},)) + for i in range(8) + ] + + for t in threads: + t.start() + + for t in threads: + t.join() + + lines = "".join(out.parts).splitlines() + + assert len(lines) == 8 + assert {json.loads(line)["seq"] for line in lines} == set(range(8)) + + +def test_write_json_returns_false_on_broken_pipe(monkeypatch): + monkeypatch.setattr(server, "_real_stdout", _BrokenStdout()) + + assert server.write_json({"ok": True}) is False + + +def test_status_callback_emits_kind_and_text(): + with patch("tui_gateway.server._emit") as emit: + cb = server._agent_cbs("sid")["status_callback"] + cb("context_pressure", "85% to compaction") + + emit.assert_called_once_with( + "status.update", + "sid", + {"kind": "context_pressure", "text": "85% to compaction"}, + ) + + +def test_status_callback_accepts_single_message_argument(): + with patch("tui_gateway.server._emit") as emit: + cb = server._agent_cbs("sid")["status_callback"] + cb("thinking...") + + emit.assert_called_once_with( + "status.update", + "sid", + {"kind": "status", "text": "thinking..."}, + ) + + +def _session(agent=None, **extra): + return { + "agent": agent if agent is not None else types.SimpleNamespace(), + "session_key": "session-key", + "history": [], + "history_lock": threading.Lock(), + "history_version": 0, + "running": False, + "attached_images": [], + "image_counter": 0, + "cols": 80, + "slash_worker": None, + "show_reasoning": False, + "tool_progress_mode": "all", + **extra, + } + + +def test_config_set_yolo_toggles_session_scope(): + from tools.approval import clear_session, is_session_yolo_enabled + + server._sessions["sid"] = _session() + try: + resp_on = server.handle_request({"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "yolo"}}) + assert resp_on["result"]["value"] == "1" + assert is_session_yolo_enabled("session-key") is True + + resp_off = server.handle_request({"id": "2", "method": "config.set", "params": {"session_id": "sid", "key": "yolo"}}) + assert resp_off["result"]["value"] == "0" + assert is_session_yolo_enabled("session-key") is False + finally: + clear_session("session-key") + server._sessions.clear() + + +def test_enable_gateway_prompts_sets_gateway_env(monkeypatch): + monkeypatch.delenv("HERMES_EXEC_ASK", raising=False) + monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False) + monkeypatch.delenv("HERMES_INTERACTIVE", raising=False) + + server._enable_gateway_prompts() + + assert server.os.environ["HERMES_GATEWAY_SESSION"] == "1" + assert server.os.environ["HERMES_EXEC_ASK"] == "1" + assert server.os.environ["HERMES_INTERACTIVE"] == "1" + + +def test_setup_status_reports_provider_config(monkeypatch): + monkeypatch.setattr("hermes_cli.main._has_any_provider_configured", lambda: False) + + resp = server.handle_request({"id": "1", "method": "setup.status", "params": {}}) + + assert resp["result"]["provider_configured"] is False + + +def test_config_set_reasoning_updates_live_session_and_agent(tmp_path, monkeypatch): + monkeypatch.setattr(server, "_hermes_home", tmp_path) + agent = types.SimpleNamespace(reasoning_config=None) + server._sessions["sid"] = _session(agent=agent) + + resp_effort = server.handle_request( + {"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "reasoning", "value": "low"}} + ) + assert resp_effort["result"]["value"] == "low" + assert agent.reasoning_config == {"enabled": True, "effort": "low"} + + resp_show = server.handle_request( + {"id": "2", "method": "config.set", "params": {"session_id": "sid", "key": "reasoning", "value": "show"}} + ) + assert resp_show["result"]["value"] == "show" + assert server._sessions["sid"]["show_reasoning"] is True + + +def test_config_set_verbose_updates_session_mode_and_agent(tmp_path, monkeypatch): + monkeypatch.setattr(server, "_hermes_home", tmp_path) + agent = types.SimpleNamespace(verbose_logging=False) + server._sessions["sid"] = _session(agent=agent) + + resp = server.handle_request( + {"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "verbose", "value": "cycle"}} + ) + + assert resp["result"]["value"] == "verbose" + assert server._sessions["sid"]["tool_progress_mode"] == "verbose" + assert agent.verbose_logging is True + + +def test_config_set_model_uses_live_switch_path(monkeypatch): + server._sessions["sid"] = _session() + seen = {} + + def _fake_apply(sid, session, raw): + seen["args"] = (sid, session["session_key"], raw) + return {"value": "new/model", "warning": "catalog unreachable"} + + monkeypatch.setattr(server, "_apply_model_switch", _fake_apply) + resp = server.handle_request( + {"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "model", "value": "new/model"}} + ) + + assert resp["result"]["value"] == "new/model" + assert resp["result"]["warning"] == "catalog unreachable" + assert seen["args"] == ("sid", "session-key", "new/model") + + +def test_config_set_model_global_persists(monkeypatch): + class _Agent: + provider = "openrouter" + model = "old/model" + base_url = "" + api_key = "sk-old" + + def switch_model(self, **kwargs): + return None + + result = types.SimpleNamespace( + success=True, + new_model="anthropic/claude-sonnet-4.6", + target_provider="anthropic", + api_key="sk-new", + base_url="https://api.anthropic.com", + api_mode="anthropic_messages", + warning_message="", + ) + seen = {} + saved = {} + + def _switch_model(**kwargs): + seen.update(kwargs) + return result + + server._sessions["sid"] = _session(agent=_Agent()) + monkeypatch.setattr("hermes_cli.model_switch.switch_model", _switch_model) + monkeypatch.setattr(server, "_restart_slash_worker", lambda session: None) + monkeypatch.setattr(server, "_emit", lambda *args, **kwargs: None) + monkeypatch.setattr("hermes_cli.config.save_config", lambda cfg: saved.update(cfg)) + + resp = server.handle_request( + {"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "model", "value": "anthropic/claude-sonnet-4.6 --global"}} + ) + + assert resp["result"]["value"] == "anthropic/claude-sonnet-4.6" + assert seen["is_global"] is True + assert saved["model"]["default"] == "anthropic/claude-sonnet-4.6" + assert saved["model"]["provider"] == "anthropic" + assert saved["model"]["base_url"] == "https://api.anthropic.com" + + +def test_config_set_personality_rejects_unknown_name(monkeypatch): + monkeypatch.setattr(server, "_available_personalities", lambda cfg=None: {"helpful": "You are helpful."}) + resp = server.handle_request( + {"id": "1", "method": "config.set", "params": {"key": "personality", "value": "bogus"}} + ) + + assert "error" in resp + assert "Unknown personality" in resp["error"]["message"] + + +def test_config_set_personality_resets_history_and_returns_info(monkeypatch): + session = _session(agent=types.SimpleNamespace(), history=[{"role": "user", "text": "hi"}], history_version=4) + new_agent = types.SimpleNamespace(model="x") + emits = [] + + server._sessions["sid"] = session + monkeypatch.setattr(server, "_available_personalities", lambda cfg=None: {"helpful": "You are helpful."}) + monkeypatch.setattr(server, "_make_agent", lambda sid, key, session_id=None: new_agent) + monkeypatch.setattr(server, "_session_info", lambda agent: {"model": getattr(agent, "model", "?")}) + monkeypatch.setattr(server, "_restart_slash_worker", lambda session: None) + monkeypatch.setattr(server, "_emit", lambda *args: emits.append(args)) + monkeypatch.setattr(server, "_write_config_key", lambda path, value: None) + + resp = server.handle_request( + {"id": "1", "method": "config.set", "params": {"session_id": "sid", "key": "personality", "value": "helpful"}} + ) + + assert resp["result"]["history_reset"] is True + assert resp["result"]["info"] == {"model": "x"} + assert session["history"] == [] + assert session["history_version"] == 5 + assert ("session.info", "sid", {"model": "x"}) in emits + + +def test_session_compress_uses_compress_helper(monkeypatch): + agent = types.SimpleNamespace() + server._sessions["sid"] = _session(agent=agent) + + monkeypatch.setattr(server, "_compress_session_history", lambda session, focus_topic=None: (2, {"total": 42})) + monkeypatch.setattr(server, "_session_info", lambda _agent: {"model": "x"}) + + with patch("tui_gateway.server._emit") as emit: + resp = server.handle_request({"id": "1", "method": "session.compress", "params": {"session_id": "sid"}}) + + assert resp["result"]["removed"] == 2 + assert resp["result"]["usage"]["total"] == 42 + emit.assert_called_once_with("session.info", "sid", {"model": "x"}) + + +def test_prompt_submit_sets_approval_session_key(monkeypatch): + from tools.approval import get_current_session_key + + captured = {} + + class _Agent: + def run_conversation(self, prompt, conversation_history=None, stream_callback=None): + captured["session_key"] = get_current_session_key(default="") + return {"final_response": "ok", "messages": [{"role": "assistant", "content": "ok"}]} + + class _ImmediateThread: + def __init__(self, target=None, daemon=None): + self._target = target + + def start(self): + self._target() + + server._sessions["sid"] = _session(agent=_Agent()) + monkeypatch.setattr(server.threading, "Thread", _ImmediateThread) + monkeypatch.setattr(server, "_emit", lambda *args, **kwargs: None) + monkeypatch.setattr(server, "make_stream_renderer", lambda cols: None) + monkeypatch.setattr(server, "render_message", lambda raw, cols: None) + + resp = server.handle_request({"id": "1", "method": "prompt.submit", "params": {"session_id": "sid", "text": "ping"}}) + + assert resp["result"]["status"] == "streaming" + assert captured["session_key"] == "session-key" + + +def test_prompt_submit_expands_context_refs(monkeypatch): + captured = {} + + class _Agent: + model = "test/model" + base_url = "" + api_key = "" + + def run_conversation(self, prompt, conversation_history=None, stream_callback=None): + captured["prompt"] = prompt + return {"final_response": "ok", "messages": [{"role": "assistant", "content": "ok"}]} + + class _ImmediateThread: + def __init__(self, target=None, daemon=None): + self._target = target + + def start(self): + self._target() + + fake_ctx = types.ModuleType("agent.context_references") + fake_ctx.preprocess_context_references = lambda message, **kwargs: types.SimpleNamespace( + blocked=False, message="expanded prompt", warnings=[], references=[], injected_tokens=0 + ) + fake_meta = types.ModuleType("agent.model_metadata") + fake_meta.get_model_context_length = lambda *args, **kwargs: 100000 + + server._sessions["sid"] = _session(agent=_Agent()) + monkeypatch.setattr(server.threading, "Thread", _ImmediateThread) + monkeypatch.setattr(server, "_emit", lambda *args, **kwargs: None) + monkeypatch.setattr(server, "make_stream_renderer", lambda cols: None) + monkeypatch.setattr(server, "render_message", lambda raw, cols: None) + monkeypatch.setitem(sys.modules, "agent.context_references", fake_ctx) + monkeypatch.setitem(sys.modules, "agent.model_metadata", fake_meta) + + server.handle_request({"id": "1", "method": "prompt.submit", "params": {"session_id": "sid", "text": "@diff"}}) + + assert captured["prompt"] == "expanded prompt" + + +def test_image_attach_appends_local_image(monkeypatch): + fake_cli = types.ModuleType("cli") + fake_cli._IMAGE_EXTENSIONS = {".png"} + fake_cli._split_path_input = lambda raw: (raw, "") + fake_cli._resolve_attachment_path = lambda raw: Path("/tmp/cat.png") + + server._sessions["sid"] = _session() + monkeypatch.setitem(sys.modules, "cli", fake_cli) + + resp = server.handle_request({"id": "1", "method": "image.attach", "params": {"session_id": "sid", "path": "/tmp/cat.png"}}) + + assert resp["result"]["attached"] is True + assert resp["result"]["name"] == "cat.png" + assert len(server._sessions["sid"]["attached_images"]) == 1 + + +def test_command_dispatch_exec_nonzero_surfaces_error(monkeypatch): + monkeypatch.setattr(server, "_load_cfg", lambda: {"quick_commands": {"boom": {"type": "exec", "command": "boom"}}}) + monkeypatch.setattr( + server.subprocess, + "run", + lambda *args, **kwargs: types.SimpleNamespace(returncode=1, stdout="", stderr="failed"), + ) + + resp = server.handle_request({"id": "1", "method": "command.dispatch", "params": {"name": "boom"}}) + + assert "error" in resp + assert "failed" in resp["error"]["message"] + + +def test_plugins_list_surfaces_loader_error(monkeypatch): + with patch("hermes_cli.plugins.get_plugin_manager", side_effect=Exception("boom")): + resp = server.handle_request({"id": "1", "method": "plugins.list", "params": {}}) + + assert "error" in resp + assert "boom" in resp["error"]["message"] + + +def test_complete_slash_surfaces_completer_error(monkeypatch): + with patch("hermes_cli.commands.SlashCommandCompleter", side_effect=Exception("no completer")): + resp = server.handle_request({"id": "1", "method": "complete.slash", "params": {"text": "/mo"}}) + + assert "error" in resp + assert "no completer" in resp["error"]["message"] + + +def test_input_detect_drop_attaches_image(monkeypatch): + fake_cli = types.ModuleType("cli") + fake_cli._detect_file_drop = lambda raw: { + "path": Path("/tmp/cat.png"), + "is_image": True, + "remainder": "", + } + + server._sessions["sid"] = _session() + monkeypatch.setitem(sys.modules, "cli", fake_cli) + + resp = server.handle_request( + {"id": "1", "method": "input.detect_drop", "params": {"session_id": "sid", "text": "/tmp/cat.png"}} + ) + + assert resp["result"]["matched"] is True + assert resp["result"]["is_image"] is True + assert resp["result"]["text"] == "[User attached image: cat.png]" + + +def test_rollback_restore_resolves_number_and_file_path(): + calls = {} + + class _Mgr: + enabled = True + + def list_checkpoints(self, cwd): + return [{"hash": "aaa111"}, {"hash": "bbb222"}] + + def restore(self, cwd, target, file_path=None): + calls["args"] = (cwd, target, file_path) + return {"success": True, "message": "done"} + + server._sessions["sid"] = _session(agent=types.SimpleNamespace(_checkpoint_mgr=_Mgr()), history=[]) + resp = server.handle_request( + { + "id": "1", + "method": "rollback.restore", + "params": {"session_id": "sid", "hash": "2", "file_path": "src/app.tsx"}, + } + ) + + assert resp["result"]["success"] is True + assert calls["args"][1] == "bbb222" + assert calls["args"][2] == "src/app.tsx" diff --git a/tests/tools/test_clipboard.py b/tests/tools/test_clipboard.py index fab80b4bc3..17f929eb9c 100644 --- a/tests/tools/test_clipboard.py +++ b/tests/tools/test_clipboard.py @@ -250,6 +250,15 @@ class TestWslHasImage: mock_run.return_value = MagicMock(stdout="False\n", returncode=0) assert _wsl_has_image() is False + def test_falls_back_to_get_clipboard_image(self): + with patch("hermes_cli.clipboard.subprocess.run") as mock_run: + mock_run.side_effect = [ + MagicMock(stdout="False\n", returncode=0), + MagicMock(stdout="True\n", returncode=0), + ] + assert _wsl_has_image() is True + assert mock_run.call_count == 2 + def test_powershell_not_found(self): with patch("hermes_cli.clipboard.subprocess.run", side_effect=FileNotFoundError): assert _wsl_has_image() is False @@ -269,6 +278,18 @@ class TestWslSave: assert _wsl_save(dest) is True assert dest.read_bytes() == FAKE_PNG + def test_falls_back_to_get_clipboard_extraction(self, tmp_path): + dest = tmp_path / "out.png" + b64_png = base64.b64encode(FAKE_PNG).decode() + with patch("hermes_cli.clipboard.subprocess.run") as mock_run: + mock_run.side_effect = [ + MagicMock(stdout="", returncode=1), + MagicMock(stdout=b64_png + "\n", returncode=0), + ] + assert _wsl_save(dest) is True + assert mock_run.call_count == 2 + assert dest.read_bytes() == FAKE_PNG + def test_no_image_returns_false(self, tmp_path): dest = tmp_path / "out.png" with patch("hermes_cli.clipboard.subprocess.run") as mock_run: @@ -528,6 +549,16 @@ class TestWindowsHasImage: mock_run.return_value = MagicMock(stdout="False\n", returncode=0) assert _windows_has_image() is False + def test_falls_back_to_get_clipboard_image(self): + with patch("hermes_cli.clipboard._get_ps_exe", return_value="powershell"): + with patch("hermes_cli.clipboard.subprocess.run") as mock_run: + mock_run.side_effect = [ + MagicMock(stdout="False\n", returncode=0), + MagicMock(stdout="True\n", returncode=0), + ] + assert _windows_has_image() is True + assert mock_run.call_count == 2 + def test_no_powershell_available(self): with patch("hermes_cli.clipboard._get_ps_exe", return_value=None): assert _windows_has_image() is False @@ -559,6 +590,20 @@ class TestWindowsSave: assert _windows_save(dest) is True assert dest.read_bytes() == FAKE_PNG + def test_falls_back_to_filedrop_image(self, tmp_path): + dest = tmp_path / "out.png" + b64_png = base64.b64encode(FAKE_PNG).decode() + with patch("hermes_cli.clipboard._get_ps_exe", return_value="powershell"): + with patch("hermes_cli.clipboard.subprocess.run") as mock_run: + mock_run.side_effect = [ + MagicMock(stdout="", returncode=1), + MagicMock(stdout="", returncode=1), + MagicMock(stdout=b64_png + "\n", returncode=0), + ] + assert _windows_save(dest) is True + assert mock_run.call_count == 3 + assert dest.read_bytes() == FAKE_PNG + def test_no_image_returns_false(self, tmp_path): dest = tmp_path / "out.png" with patch("hermes_cli.clipboard._get_ps_exe", return_value="powershell"): @@ -734,6 +779,18 @@ class TestHasClipboardImage: assert has_clipboard_image() is True m.assert_called_once() + def test_wsl_falls_through_to_wayland_when_windows_path_empty(self): + """WSLg often bridges images to wl-paste even when powershell.exe check fails.""" + with patch("hermes_cli.clipboard.sys") as mock_sys: + mock_sys.platform = "linux" + with patch("hermes_cli.clipboard._is_wsl", return_value=True): + with patch("hermes_cli.clipboard._wsl_has_image", return_value=False) as wsl: + with patch.dict(os.environ, {"WAYLAND_DISPLAY": "wayland-0"}): + with patch("hermes_cli.clipboard._wayland_has_image", return_value=True) as wl: + assert has_clipboard_image() is True + wsl.assert_called_once() + wl.assert_called_once() + def test_linux_wayland_dispatch(self): with patch("hermes_cli.clipboard.sys") as mock_sys: mock_sys.platform = "linux" diff --git a/tests/tui_gateway/__init__.py b/tests/tui_gateway/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py new file mode 100644 index 0000000000..6ee5fe65b6 --- /dev/null +++ b/tests/tui_gateway/test_protocol.py @@ -0,0 +1,233 @@ +"""Tests for tui_gateway JSON-RPC protocol plumbing.""" + +import io +import json +import sys +import threading +from unittest.mock import MagicMock, patch + +import pytest + +_original_stdout = sys.stdout + + +@pytest.fixture(autouse=True) +def _restore_stdout(): + yield + sys.stdout = _original_stdout + + +@pytest.fixture() +def server(): + with patch.dict("sys.modules", { + "hermes_constants": MagicMock(get_hermes_home=MagicMock(return_value="/tmp/hermes_test")), + "hermes_cli.env_loader": MagicMock(), + "hermes_cli.banner": MagicMock(), + "hermes_state": MagicMock(), + }): + import importlib + mod = importlib.import_module("tui_gateway.server") + yield mod + mod._sessions.clear() + mod._pending.clear() + mod._answers.clear() + mod._methods.clear() + importlib.reload(mod) + + +@pytest.fixture() +def capture(server): + """Redirect server's real stdout to a StringIO and return (server, buf).""" + buf = io.StringIO() + server._real_stdout = buf + return server, buf + + +# ── JSON-RPC envelope ──────────────────────────────────────────────── + + +def test_unknown_method(server): + resp = server.handle_request({"id": "1", "method": "bogus"}) + assert resp["error"]["code"] == -32601 + + +def test_ok_envelope(server): + assert server._ok("r1", {"x": 1}) == { + "jsonrpc": "2.0", "id": "r1", "result": {"x": 1}, + } + + +def test_err_envelope(server): + assert server._err("r2", 4001, "nope") == { + "jsonrpc": "2.0", "id": "r2", "error": {"code": 4001, "message": "nope"}, + } + + +# ── write_json ─────────────────────────────────────────────────────── + + +def test_write_json(capture): + server, buf = capture + assert server.write_json({"test": True}) + assert json.loads(buf.getvalue()) == {"test": True} + + +def test_write_json_broken_pipe(server): + class _Broken: + def write(self, _): raise BrokenPipeError + def flush(self): raise BrokenPipeError + + server._real_stdout = _Broken() + assert server.write_json({"x": 1}) is False + + +# ── _emit ──────────────────────────────────────────────────────────── + + +def test_emit_with_payload(capture): + server, buf = capture + server._emit("test.event", "s1", {"key": "val"}) + msg = json.loads(buf.getvalue()) + + assert msg["method"] == "event" + assert msg["params"]["type"] == "test.event" + assert msg["params"]["session_id"] == "s1" + assert msg["params"]["payload"]["key"] == "val" + + +def test_emit_without_payload(capture): + server, buf = capture + server._emit("ping", "s2") + + assert "payload" not in json.loads(buf.getvalue())["params"] + + +# ── Blocking prompt round-trip ─────────────────────────────────────── + + +def test_block_and_respond(capture): + server, _ = capture + result = [None] + + threading.Thread( + target=lambda: result.__setitem__(0, server._block("test.prompt", "s1", {"q": "?"}, timeout=5)), + ).start() + + for _ in range(100): + if server._pending: + break + threading.Event().wait(0.01) + + rid = next(iter(server._pending)) + server._answers[rid] = "my_answer" + server._pending[rid].set() + + threading.Event().wait(0.1) + assert result[0] == "my_answer" + + +def test_clear_pending(server): + ev = threading.Event() + server._pending["r1"] = ev + server._clear_pending() + + assert ev.is_set() + assert server._answers["r1"] == "" + + +# ── Session lookup ─────────────────────────────────────────────────── + + +def test_sess_missing(server): + _, err = server._sess({"session_id": "nope"}, "r1") + assert err["error"]["code"] == 4001 + + +def test_sess_found(server): + server._sessions["abc"] = {"agent": MagicMock()} + s, err = server._sess({"session_id": "abc"}, "r1") + + assert s is not None + assert err is None + + +# ── session.resume payload ──────────────────────────────────────────── + + +def test_session_resume_returns_hydrated_messages(server, monkeypatch): + class _DB: + def get_session(self, _sid): + return {"id": "20260409_010101_abc123"} + + def get_session_by_title(self, _title): + return None + + def reopen_session(self, _sid): + return None + + def get_messages_as_conversation(self, _sid): + return [ + {"role": "user", "content": "hello"}, + {"role": "assistant", "content": "yo"}, + {"role": "tool", "content": "searched"}, + {"role": "assistant", "content": " "}, + {"role": "assistant", "content": None}, + {"role": "narrator", "content": "skip"}, + ] + + monkeypatch.setattr(server, "_get_db", lambda: _DB()) + monkeypatch.setattr(server, "_make_agent", lambda sid, key, session_id=None: object()) + monkeypatch.setattr(server, "_init_session", lambda sid, key, agent, history, cols=80: None) + monkeypatch.setattr(server, "_session_info", lambda _agent: {"model": "test/model"}) + + resp = server.handle_request( + { + "id": "r1", + "method": "session.resume", + "params": {"session_id": "20260409_010101_abc123", "cols": 100}, + } + ) + + assert "error" not in resp + assert resp["result"]["message_count"] == 3 + assert resp["result"]["messages"] == [ + {"role": "user", "text": "hello"}, + {"role": "assistant", "text": "yo"}, + {"role": "tool", "name": "tool", "context": ""}, + ] + + +# ── Config I/O ─────────────────────────────────────────────────────── + + +def test_config_load_missing(server, tmp_path): + server._hermes_home = tmp_path + assert server._load_cfg() == {} + + +def test_config_roundtrip(server, tmp_path): + server._hermes_home = tmp_path + server._save_cfg({"model": "test/model"}) + assert server._load_cfg()["model"] == "test/model" + + +# ── _cli_exec_blocked ──────────────────────────────────────────────── + + +@pytest.mark.parametrize("argv", [ + [], + ["setup"], + ["gateway"], + ["sessions", "browse"], + ["config", "edit"], +]) +def test_cli_exec_blocked(server, argv): + assert server._cli_exec_blocked(argv) is not None + + +@pytest.mark.parametrize("argv", [ + ["version"], + ["sessions", "list"], +]) +def test_cli_exec_allowed(server, argv): + assert server._cli_exec_blocked(argv) is None diff --git a/tests/tui_gateway/test_render.py b/tests/tui_gateway/test_render.py new file mode 100644 index 0000000000..3054846b88 --- /dev/null +++ b/tests/tui_gateway/test_render.py @@ -0,0 +1,67 @@ +"""Tests for tui_gateway.render — rendering bridge fallback behavior.""" + +from unittest.mock import MagicMock, patch + +from tui_gateway.render import make_stream_renderer, render_diff, render_message + + +def _stub_rich(mock_mod): + return patch.dict("sys.modules", {"agent.rich_output": mock_mod}) + + +def _no_rich(): + return patch.dict("sys.modules", {"agent.rich_output": None}) + + +# ── render_message ─────────────────────────────────────────────────── + + +def test_render_message_none_without_module(): + with _no_rich(): + assert render_message("hello") is None + + +def test_render_message_formatted(): + mod = MagicMock() + mod.format_response.return_value = "hi" + + with _stub_rich(mod): + assert render_message("hi", 100) == "hi" + + +def test_render_message_type_error_fallback(): + mod = MagicMock() + mod.format_response.side_effect = [TypeError, "fallback"] + + with _stub_rich(mod): + assert render_message("hi") == "fallback" + + +def test_render_message_exception_returns_none(): + mod = MagicMock() + mod.format_response.side_effect = RuntimeError + + with _stub_rich(mod): + assert render_message("hi") is None + + +# ── render_diff / make_stream_renderer ─────────────────────────────── + + +def test_render_diff_none_without_module(): + with _no_rich(): + assert render_diff("+line") is None + + +def test_stream_renderer_none_without_module(): + with _no_rich(): + assert make_stream_renderer() is None + + +def test_stream_renderer_returns_instance(): + renderer = MagicMock() + mod = MagicMock() + mod.StreamingRenderer.return_value = renderer + + with _stub_rich(mod): + assert make_stream_renderer(120) is renderer diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py index 1b29150fba..22b132f2c4 100644 --- a/tools/delegate_tool.py +++ b/tools/delegate_tool.py @@ -155,7 +155,7 @@ def _strip_blocked_tools(toolsets: List[str]) -> List[str]: return [t for t in toolsets if t not in blocked_toolset_names] -def _build_child_progress_callback(task_index: int, parent_agent, task_count: int = 1) -> Optional[callable]: +def _build_child_progress_callback(task_index: int, goal: str, parent_agent, task_count: int = 1) -> Optional[callable]: """Build a callback that relays child agent tool calls to the parent display. Two display paths: @@ -173,14 +173,46 @@ def _build_child_progress_callback(task_index: int, parent_agent, task_count: in # Show 1-indexed prefix only in batch mode (multiple tasks) prefix = f"[{task_index + 1}] " if task_count > 1 else "" + goal_label = (goal or "").strip() # Gateway: batch tool names, flush periodically _BATCH_SIZE = 5 _batch: List[str] = [] + def _relay(event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs): + if not parent_cb: + return + try: + parent_cb( + event_type, + tool_name, + preview, + args, + task_index=task_index, + task_count=task_count, + goal=goal_label, + **kwargs, + ) + except Exception as e: + logger.debug("Parent callback failed: %s", e) + def _callback(event_type: str, tool_name: str = None, preview: str = None, args=None, **kwargs): # event_type is one of: "tool.started", "tool.completed", - # "reasoning.available", "_thinking", "subagent_progress" + # "reasoning.available", "_thinking", "subagent.*" + + if event_type == "subagent.start": + if spinner and goal_label: + short = (goal_label[:55] + "...") if len(goal_label) > 55 else goal_label + try: + spinner.print_above(f" {prefix}├─ 🔀 {short}") + except Exception as e: + logger.debug("Spinner print_above failed: %s", e) + _relay("subagent.start", preview=preview or goal_label or "", **kwargs) + return + + if event_type == "subagent.complete": + _relay("subagent.complete", preview=preview, **kwargs) + return # "_thinking" / reasoning events if event_type in ("_thinking", "reasoning.available"): @@ -191,7 +223,7 @@ def _build_child_progress_callback(task_index: int, parent_agent, task_count: in spinner.print_above(f" {prefix}├─ 💭 \"{short}\"") except Exception as e: logger.debug("Spinner print_above failed: %s", e) - # Don't relay thinking to gateway (too noisy for chat) + _relay("subagent.thinking", preview=text) return # tool.completed — no display needed here (spinner shows on started) @@ -212,23 +244,18 @@ def _build_child_progress_callback(task_index: int, parent_agent, task_count: in logger.debug("Spinner print_above failed: %s", e) if parent_cb: + _relay("subagent.tool", tool_name, preview, args) _batch.append(tool_name or "") if len(_batch) >= _BATCH_SIZE: summary = ", ".join(_batch) - try: - parent_cb("subagent_progress", f"🔀 {prefix}{summary}") - except Exception as e: - logger.debug("Parent callback failed: %s", e) + _relay("subagent.progress", preview=f"🔀 {prefix}{summary}") _batch.clear() def _flush(): """Flush remaining batched tool names to gateway on completion.""" if parent_cb and _batch: summary = ", ".join(_batch) - try: - parent_cb("subagent_progress", f"🔀 {prefix}{summary}") - except Exception as e: - logger.debug("Parent callback flush failed: %s", e) + _relay("subagent.progress", preview=f"🔀 {prefix}{summary}") _batch.clear() _callback._flush = _flush @@ -242,6 +269,7 @@ def _build_child_agent( toolsets: Optional[List[str]], model: Optional[str], max_iterations: int, + task_count: int, parent_agent, # Credential overrides from delegation config (provider:model resolution) override_provider: Optional[str] = None, @@ -298,7 +326,7 @@ def _build_child_agent( parent_api_key = parent_agent._client_kwargs.get("api_key") # Build progress callback to relay tool calls to parent display - child_progress_cb = _build_child_progress_callback(task_index, parent_agent) + child_progress_cb = _build_child_progress_callback(task_index, goal, parent_agent, task_count) # Each subagent gets its own iteration budget capped at max_iterations # (configurable via delegation.max_iterations, default 50). This means @@ -469,6 +497,12 @@ def _run_single_child( _heartbeat_thread.start() try: + if child_progress_cb: + try: + child_progress_cb("subagent.start", preview=goal) + except Exception as e: + logger.debug("Progress callback start failed: %s", e) + result = child.run_conversation(user_message=goal) # Flush any remaining batched progress to gateway @@ -563,11 +597,34 @@ def _run_single_child( if status == "failed": entry["error"] = result.get("error", "Subagent did not produce a response.") + if child_progress_cb: + try: + child_progress_cb( + "subagent.complete", + preview=summary[:160] if summary else entry.get("error", ""), + status=status, + duration_seconds=duration, + summary=summary[:500] if summary else entry.get("error", ""), + ) + except Exception as e: + logger.debug("Progress callback completion failed: %s", e) + return entry except Exception as exc: duration = round(time.monotonic() - child_start, 2) logging.exception(f"[subagent-{task_index}] failed") + if child_progress_cb: + try: + child_progress_cb( + "subagent.complete", + preview=str(exc), + status="failed", + duration_seconds=duration, + summary=str(exc), + ) + except Exception as e: + logger.debug("Progress callback failure relay failed: %s", e) return { "task_index": task_index, "status": "error", @@ -714,7 +771,7 @@ def delegate_task( child = _build_child_agent( task_index=i, goal=t["goal"], context=t.get("context"), toolsets=t.get("toolsets") or toolsets, model=creds["model"], - max_iterations=effective_max_iter, parent_agent=parent_agent, + max_iterations=effective_max_iter, task_count=n_tasks, parent_agent=parent_agent, override_provider=creds["provider"], override_base_url=creds["base_url"], override_api_key=creds["api_key"], override_api_mode=creds["api_mode"], diff --git a/tools/process_registry.py b/tools/process_registry.py index d2cc566396..92f3db2a10 100644 --- a/tools/process_registry.py +++ b/tools/process_registry.py @@ -64,6 +64,17 @@ WATCH_WINDOW_SECONDS = 10 # Rolling window length WATCH_OVERLOAD_KILL_SECONDS = 45 # Sustained overload duration before disabling watch +def format_uptime_short(seconds: int) -> str: + s = max(0, int(seconds)) + if s < 60: + return f"{s}s" + mins, secs = divmod(s, 60) + if mins < 60: + return f"{mins}m {secs}s" + hours, mins = divmod(mins, 60) + return f"{hours}h {mins}m" + + @dataclass class ProcessSession: """A tracked background process with output buffering.""" diff --git a/tui_gateway/__init__.py b/tui_gateway/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tui_gateway/entry.py b/tui_gateway/entry.py new file mode 100644 index 0000000000..a9667528de --- /dev/null +++ b/tui_gateway/entry.py @@ -0,0 +1,38 @@ +import json +import signal +import sys + +from tui_gateway.server import handle_request, resolve_skin, write_json + +signal.signal(signal.SIGPIPE, signal.SIG_DFL) +signal.signal(signal.SIGINT, signal.SIG_IGN) + + +def main(): + if not write_json({ + "jsonrpc": "2.0", + "method": "event", + "params": {"type": "gateway.ready", "payload": {"skin": resolve_skin()}}, + }): + sys.exit(0) + + for raw in sys.stdin: + line = raw.strip() + if not line: + continue + + try: + req = json.loads(line) + except json.JSONDecodeError: + if not write_json({"jsonrpc": "2.0", "error": {"code": -32700, "message": "parse error"}, "id": None}): + sys.exit(0) + continue + + resp = handle_request(req) + if resp is not None: + if not write_json(resp): + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/tui_gateway/render.py b/tui_gateway/render.py new file mode 100644 index 0000000000..c15ddef7c0 --- /dev/null +++ b/tui_gateway/render.py @@ -0,0 +1,49 @@ +"""Rendering bridge — routes TUI content through Python-side renderers. + +When agent.rich_output exists, its functions are used. When it doesn't, +everything returns None and the TUI falls back to its own markdown.tsx. +""" + +from __future__ import annotations + + +def render_message(text: str, cols: int = 80) -> str | None: + try: + from agent.rich_output import format_response + except ImportError: + return None + + try: + return format_response(text, cols=cols) + except TypeError: + return format_response(text) + except Exception: + return None + + +def render_diff(text: str, cols: int = 80) -> str | None: + try: + from agent.rich_output import render_diff as _rd + except ImportError: + return None + + try: + return _rd(text, cols=cols) + except TypeError: + return _rd(text) + except Exception: + return None + + +def make_stream_renderer(cols: int = 80): + try: + from agent.rich_output import StreamingRenderer + except ImportError: + return None + + try: + return StreamingRenderer(cols=cols) + except TypeError: + return StreamingRenderer() + except Exception: + return None diff --git a/tui_gateway/server.py b/tui_gateway/server.py new file mode 100644 index 0000000000..3ef76a0f02 --- /dev/null +++ b/tui_gateway/server.py @@ -0,0 +1,2778 @@ +import atexit +import copy +import json +import os +import queue +import subprocess +import sys +import threading +import time +import uuid +from datetime import datetime +from pathlib import Path + +from hermes_constants import get_hermes_home +from hermes_cli.env_loader import load_hermes_dotenv + +_hermes_home = get_hermes_home() +load_hermes_dotenv(hermes_home=_hermes_home, project_env=Path(__file__).parent.parent / ".env") + +try: + from hermes_cli.banner import prefetch_update_check + prefetch_update_check() +except Exception: + pass + +from tui_gateway.render import make_stream_renderer, render_diff, render_message + +_sessions: dict[str, dict] = {} +_methods: dict[str, callable] = {} +_pending: dict[str, threading.Event] = {} +_answers: dict[str, str] = {} +_db = None +_stdout_lock = threading.Lock() +_cfg_lock = threading.Lock() +_cfg_cache: dict | None = None +_cfg_mtime: float | None = None +_SLASH_WORKER_TIMEOUT_S = max(5.0, float(os.environ.get("HERMES_TUI_SLASH_TIMEOUT_S", "45") or 45)) + +# Reserve real stdout for JSON-RPC only; redirect Python's stdout to stderr +# so stray print() from libraries/tools becomes harmless gateway.stderr instead +# of corrupting the JSON protocol. +_real_stdout = sys.stdout +sys.stdout = sys.stderr + + +class _SlashWorker: + """Persistent HermesCLI subprocess for slash commands.""" + + def __init__(self, session_key: str, model: str): + self._lock = threading.Lock() + self._seq = 0 + self.stderr_tail: list[str] = [] + self.stdout_queue: queue.Queue[dict | None] = queue.Queue() + + argv = [sys.executable, "-m", "tui_gateway.slash_worker", "--session-key", session_key] + if model: + argv += ["--model", model] + + self.proc = subprocess.Popen( + argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, bufsize=1, cwd=os.getcwd(), env=os.environ.copy(), + ) + threading.Thread(target=self._drain_stdout, daemon=True).start() + threading.Thread(target=self._drain_stderr, daemon=True).start() + + def _drain_stdout(self): + for line in (self.proc.stdout or []): + try: + self.stdout_queue.put(json.loads(line)) + except json.JSONDecodeError: + continue + self.stdout_queue.put(None) + + def _drain_stderr(self): + for line in (self.proc.stderr or []): + if text := line.rstrip("\n"): + self.stderr_tail = (self.stderr_tail + [text])[-80:] + + def run(self, command: str) -> str: + if self.proc.poll() is not None: + raise RuntimeError("slash worker exited") + + with self._lock: + self._seq += 1 + rid = self._seq + self.proc.stdin.write(json.dumps({"id": rid, "command": command}) + "\n") + self.proc.stdin.flush() + + while True: + try: + msg = self.stdout_queue.get(timeout=_SLASH_WORKER_TIMEOUT_S) + except queue.Empty: + raise RuntimeError("slash worker timed out") + if msg is None: + break + if msg.get("id") != rid: + continue + if not msg.get("ok"): + raise RuntimeError(msg.get("error", "slash worker failed")) + return str(msg.get("output", "")).rstrip() + + raise RuntimeError(f"slash worker closed pipe{': ' + chr(10).join(self.stderr_tail[-8:]) if self.stderr_tail else ''}") + + def close(self): + try: + if self.proc.poll() is None: + self.proc.terminate() + self.proc.wait(timeout=1) + except Exception: + try: self.proc.kill() + except Exception: pass + + +atexit.register(lambda: [ + s.get("slash_worker") and s["slash_worker"].close() + for s in _sessions.values() +]) + + +# ── Plumbing ────────────────────────────────────────────────────────── + +def _get_db(): + global _db + if _db is None: + from hermes_state import SessionDB + _db = SessionDB() + return _db + + +def write_json(obj: dict) -> bool: + line = json.dumps(obj, ensure_ascii=False) + "\n" + try: + with _stdout_lock: + _real_stdout.write(line) + _real_stdout.flush() + return True + except BrokenPipeError: + return False + + +def _emit(event: str, sid: str, payload: dict | None = None): + params = {"type": event, "session_id": sid} + if payload is not None: + params["payload"] = payload + write_json({"jsonrpc": "2.0", "method": "event", "params": params}) + + +def _status_update(sid: str, kind: str, text: str | None = None): + body = (text if text is not None else kind).strip() + if not body: + return + _emit("status.update", sid, {"kind": kind if text is not None else "status", "text": body}) + + +def _estimate_image_tokens(width: int, height: int) -> int: + """Very rough UI estimate for image prompt cost. + + Uses 512px tiles at ~85 tokens/tile as a lightweight cross-provider hint. + This is intentionally approximate and only used for attachment display. + """ + if width <= 0 or height <= 0: + return 0 + return max(1, (width + 511) // 512) * max(1, (height + 511) // 512) * 85 + + +def _image_meta(path: Path) -> dict: + meta = {"name": path.name} + try: + from PIL import Image + + with Image.open(path) as img: + width, height = img.size + meta["width"] = int(width) + meta["height"] = int(height) + meta["token_estimate"] = _estimate_image_tokens(int(width), int(height)) + except Exception: + pass + return meta + + +def _ok(rid, result: dict) -> dict: + return {"jsonrpc": "2.0", "id": rid, "result": result} + + +def _err(rid, code: int, msg: str) -> dict: + return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": msg}} + + +def method(name: str): + def dec(fn): + _methods[name] = fn + return fn + return dec + + +def handle_request(req: dict) -> dict | None: + fn = _methods.get(req.get("method", "")) + if not fn: + return _err(req.get("id"), -32601, f"unknown method: {req.get('method')}") + return fn(req.get("id"), req.get("params", {})) + + +def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None: + ready = session.get("agent_ready") + if ready is not None and not ready.wait(timeout=timeout): + return _err(rid, 5032, "agent initialization timed out") + err = session.get("agent_error") + return _err(rid, 5032, err) if err else None + + +def _sess_nowait(params, rid): + s = _sessions.get(params.get("session_id") or "") + return (s, None) if s else (None, _err(rid, 4001, "session not found")) + + +def _sess(params, rid): + s, err = _sess_nowait(params, rid) + return (None, err) if err else (s, _wait_agent(s, rid)) + + +def _normalize_completion_path(path_part: str) -> str: + expanded = os.path.expanduser(path_part) + if os.name != "nt": + normalized = expanded.replace("\\", "/") + if len(normalized) >= 3 and normalized[1] == ":" and normalized[2] == "/" and normalized[0].isalpha(): + return f"/mnt/{normalized[0].lower()}/{normalized[3:]}" + return expanded + + +# ── Config I/O ──────────────────────────────────────────────────────── + +def _load_cfg() -> dict: + global _cfg_cache, _cfg_mtime + try: + import yaml + p = _hermes_home / "config.yaml" + mtime = p.stat().st_mtime if p.exists() else None + with _cfg_lock: + if _cfg_cache is not None and _cfg_mtime == mtime: + return copy.deepcopy(_cfg_cache) + if p.exists(): + with open(p) as f: + data = yaml.safe_load(f) or {} + else: + data = {} + with _cfg_lock: + _cfg_cache = copy.deepcopy(data) + _cfg_mtime = mtime + return data + except Exception: + pass + return {} + + +def _save_cfg(cfg: dict): + global _cfg_cache, _cfg_mtime + import yaml + path = _hermes_home / "config.yaml" + with open(path, "w") as f: + yaml.safe_dump(cfg, f) + with _cfg_lock: + _cfg_cache = copy.deepcopy(cfg) + try: + _cfg_mtime = path.stat().st_mtime + except Exception: + _cfg_mtime = None + + +def _set_session_context(session_key: str) -> list: + try: + from gateway.session_context import set_session_vars + return set_session_vars(session_key=session_key) + except Exception: + return [] + + +def _clear_session_context(tokens: list) -> None: + if not tokens: + return + try: + from gateway.session_context import clear_session_vars + clear_session_vars(tokens) + except Exception: + pass + + +def _enable_gateway_prompts() -> None: + """Route approvals through gateway callbacks instead of CLI input().""" + os.environ["HERMES_GATEWAY_SESSION"] = "1" + os.environ["HERMES_EXEC_ASK"] = "1" + os.environ["HERMES_INTERACTIVE"] = "1" + + +# ── Blocking prompt factory ────────────────────────────────────────── + +def _block(event: str, sid: str, payload: dict, timeout: int = 300) -> str: + rid = uuid.uuid4().hex[:8] + ev = threading.Event() + _pending[rid] = ev + payload["request_id"] = rid + _emit(event, sid, payload) + ev.wait(timeout=timeout) + _pending.pop(rid, None) + return _answers.pop(rid, "") + + +def _clear_pending(): + for rid, ev in list(_pending.items()): + _answers[rid] = "" + ev.set() + + +# ── Agent factory ──────────────────────────────────────────────────── + +def resolve_skin() -> dict: + try: + from hermes_cli.skin_engine import init_skin_from_config, get_active_skin + init_skin_from_config(_load_cfg()) + skin = get_active_skin() + return { + "name": skin.name, + "colors": skin.colors, + "branding": skin.branding, + "banner_logo": skin.banner_logo, + "banner_hero": skin.banner_hero, + "tool_prefix": skin.tool_prefix, + "help_header": (skin.branding or {}).get("help_header", ""), + } + except Exception: + return {} + + +def _resolve_model() -> str: + env = os.environ.get("HERMES_MODEL", "") + if env: + return env + m = _load_cfg().get("model", "") + if isinstance(m, dict): + return m.get("default", "") + if isinstance(m, str) and m: + return m + return "anthropic/claude-sonnet-4" + + +def _write_config_key(key_path: str, value): + cfg = _load_cfg() + current = cfg + keys = key_path.split(".") + for key in keys[:-1]: + if key not in current or not isinstance(current.get(key), dict): + current[key] = {} + current = current[key] + current[keys[-1]] = value + _save_cfg(cfg) + + +def _load_reasoning_config() -> dict | None: + from hermes_constants import parse_reasoning_effort + + effort = str(_load_cfg().get("agent", {}).get("reasoning_effort", "") or "").strip() + return parse_reasoning_effort(effort) + + +def _load_service_tier() -> str | None: + raw = str(_load_cfg().get("agent", {}).get("service_tier", "") or "").strip().lower() + if not raw or raw in {"normal", "default", "standard", "off", "none"}: + return None + if raw in {"fast", "priority", "on"}: + return "priority" + return None + + +def _load_show_reasoning() -> bool: + return bool(_load_cfg().get("display", {}).get("show_reasoning", False)) + + +def _load_tool_progress_mode() -> str: + raw = _load_cfg().get("display", {}).get("tool_progress", "all") + if raw is False: + return "off" + if raw is True: + return "all" + mode = str(raw or "all").strip().lower() + return mode if mode in {"off", "new", "all", "verbose"} else "all" + + +def _load_enabled_toolsets() -> list[str] | None: + try: + from hermes_cli.config import load_config + from hermes_cli.tools_config import _get_platform_tools + + enabled = sorted(_get_platform_tools(load_config(), "cli", include_default_mcp_servers=False)) + return enabled or None + except Exception: + return None + + +def _session_tool_progress_mode(sid: str) -> str: + return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all") + + +def _tool_progress_enabled(sid: str) -> bool: + return _session_tool_progress_mode(sid) != "off" + + +def _restart_slash_worker(session: dict): + worker = session.get("slash_worker") + if worker: + try: + worker.close() + except Exception: + pass + try: + session["slash_worker"] = _SlashWorker(session["session_key"], getattr(session.get("agent"), "model", _resolve_model())) + except Exception: + session["slash_worker"] = None + + +def _persist_model_switch(result) -> None: + from hermes_cli.config import save_config + + cfg = _load_cfg() + model_cfg = cfg.get("model") + if not isinstance(model_cfg, dict): + model_cfg = {} + cfg["model"] = model_cfg + + model_cfg["default"] = result.new_model + model_cfg["provider"] = result.target_provider + if result.base_url: + model_cfg["base_url"] = result.base_url + else: + model_cfg.pop("base_url", None) + save_config(cfg) + + +def _apply_model_switch(sid: str, session: dict, raw_input: str) -> dict: + from hermes_cli.model_switch import parse_model_flags, switch_model + from hermes_cli.runtime_provider import resolve_runtime_provider + + model_input, explicit_provider, persist_global = parse_model_flags(raw_input) + if not model_input: + raise ValueError("model value required") + + agent = session.get("agent") + if agent: + current_provider = getattr(agent, "provider", "") or "" + current_model = getattr(agent, "model", "") or "" + current_base_url = getattr(agent, "base_url", "") or "" + current_api_key = getattr(agent, "api_key", "") or "" + else: + runtime = resolve_runtime_provider(requested=None) + current_provider = str(runtime.get("provider", "") or "") + current_model = _resolve_model() + current_base_url = str(runtime.get("base_url", "") or "") + current_api_key = str(runtime.get("api_key", "") or "") + + result = switch_model( + raw_input=model_input, + current_provider=current_provider, + current_model=current_model, + current_base_url=current_base_url, + current_api_key=current_api_key, + is_global=persist_global, + explicit_provider=explicit_provider, + ) + if not result.success: + raise ValueError(result.error_message or "model switch failed") + + if agent: + agent.switch_model( + new_model=result.new_model, + new_provider=result.target_provider, + api_key=result.api_key, + base_url=result.base_url, + api_mode=result.api_mode, + ) + _restart_slash_worker(session) + _emit("session.info", sid, _session_info(agent)) + + os.environ["HERMES_MODEL"] = result.new_model + if persist_global: + _persist_model_switch(result) + return {"value": result.new_model, "warning": result.warning_message or ""} + + +def _compress_session_history(session: dict, focus_topic: str | None = None) -> tuple[int, dict]: + from agent.model_metadata import estimate_messages_tokens_rough + + agent = session["agent"] + history = list(session.get("history", [])) + if len(history) < 4: + return 0, _get_usage(agent) + approx_tokens = estimate_messages_tokens_rough(history) + compressed, _ = agent._compress_context( + history, + getattr(agent, "_cached_system_prompt", "") or "", + approx_tokens=approx_tokens, + focus_topic=focus_topic or None, + ) + session["history"] = compressed + session["history_version"] = int(session.get("history_version", 0)) + 1 + return len(history) - len(compressed), _get_usage(agent) + + +def _get_usage(agent) -> dict: + g = lambda k, fb=None: getattr(agent, k, 0) or (getattr(agent, fb, 0) if fb else 0) + usage = { + "model": getattr(agent, "model", "") or "", + "input": g("session_input_tokens", "session_prompt_tokens"), + "output": g("session_output_tokens", "session_completion_tokens"), + "cache_read": g("session_cache_read_tokens"), + "cache_write": g("session_cache_write_tokens"), + "prompt": g("session_prompt_tokens"), + "completion": g("session_completion_tokens"), + "total": g("session_total_tokens"), + "calls": g("session_api_calls"), + } + comp = getattr(agent, "context_compressor", None) + if comp: + ctx_used = getattr(comp, "last_prompt_tokens", 0) or usage["total"] or 0 + ctx_max = getattr(comp, "context_length", 0) or 0 + if ctx_max: + usage["context_used"] = ctx_used + usage["context_max"] = ctx_max + usage["context_percent"] = max(0, min(100, round(ctx_used / ctx_max * 100))) + usage["compressions"] = getattr(comp, "compression_count", 0) or 0 + try: + from agent.usage_pricing import CanonicalUsage, estimate_usage_cost + cost = estimate_usage_cost( + usage["model"], + CanonicalUsage( + input_tokens=usage["input"], + output_tokens=usage["output"], + cache_read_tokens=usage["cache_read"], + cache_write_tokens=usage["cache_write"], + ), + provider=getattr(agent, "provider", None), + base_url=getattr(agent, "base_url", None), + ) + usage["cost_status"] = cost.status + if cost.amount_usd is not None: + usage["cost_usd"] = float(cost.amount_usd) + except Exception: + pass + return usage + + +def _probe_credentials(agent) -> str: + """Light credential check at session creation — returns warning or ''.""" + try: + key = getattr(agent, "api_key", "") or "" + provider = getattr(agent, "provider", "") or "" + if not key or key == "no-key-required": + return f"No API key configured for provider '{provider}'. First message will fail." + except Exception: + pass + return "" + + +def _session_info(agent) -> dict: + info: dict = { + "model": getattr(agent, "model", ""), + "tools": {}, + "skills": {}, + "cwd": os.getcwd(), + "version": "", + "release_date": "", + "update_behind": None, + "update_command": "", + "usage": _get_usage(agent), + } + try: + from hermes_cli import __version__, __release_date__ + info["version"] = __version__ + info["release_date"] = __release_date__ + except Exception: + pass + try: + from model_tools import get_toolset_for_tool + for t in getattr(agent, "tools", []) or []: + name = t["function"]["name"] + info["tools"].setdefault(get_toolset_for_tool(name) or "other", []).append(name) + except Exception: + pass + try: + from hermes_cli.banner import get_available_skills + info["skills"] = get_available_skills() + except Exception: + pass + try: + from hermes_cli.banner import get_update_result + from hermes_cli.config import recommended_update_command + info["update_behind"] = get_update_result(timeout=0.5) + info["update_command"] = recommended_update_command() + except Exception: + pass + return info + + +def _tool_ctx(name: str, args: dict) -> str: + try: + from agent.display import build_tool_preview + return build_tool_preview(name, args, max_len=80) or "" + except Exception: + return "" + + +def _fmt_tool_duration(seconds: float | None) -> str: + if seconds is None: + return "" + if seconds < 10: + return f"{seconds:.1f}s" + if seconds < 60: + return f"{round(seconds)}s" + mins, secs = divmod(int(round(seconds)), 60) + return f"{mins}m {secs}s" if secs else f"{mins}m" + + +def _count_list(obj: object, *path: str) -> int | None: + cur = obj + for key in path: + if not isinstance(cur, dict): + return None + cur = cur.get(key) + return len(cur) if isinstance(cur, list) else None + + +def _tool_summary(name: str, result: str, duration_s: float | None) -> str | None: + try: + data = json.loads(result) + except Exception: + data = None + + dur = _fmt_tool_duration(duration_s) + suffix = f" in {dur}" if dur else "" + text = None + + if name == "web_search" and isinstance(data, dict): + n = _count_list(data, "data", "web") + if n is not None: + text = f"Did {n} {'search' if n == 1 else 'searches'}" + + elif name == "web_extract" and isinstance(data, dict): + n = _count_list(data, "results") or _count_list(data, "data", "results") + if n is not None: + text = f"Extracted {n} {'page' if n == 1 else 'pages'}" + + return f"{text or 'Completed'}{suffix}" if (text or dur) else None + + +def _on_tool_start(sid: str, tool_call_id: str, name: str, args: dict): + session = _sessions.get(sid) + if session is not None: + try: + from agent.display import capture_local_edit_snapshot + + snapshot = capture_local_edit_snapshot(name, args) + if snapshot is not None: + session.setdefault("edit_snapshots", {})[tool_call_id] = snapshot + except Exception: + pass + session.setdefault("tool_started_at", {})[tool_call_id] = time.time() + if _tool_progress_enabled(sid): + _emit("tool.start", sid, {"tool_id": tool_call_id, "name": name, "context": _tool_ctx(name, args)}) + + +def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result: str): + payload = {"tool_id": tool_call_id, "name": name} + session = _sessions.get(sid) + snapshot = None + started_at = None + if session is not None: + snapshot = session.setdefault("edit_snapshots", {}).pop(tool_call_id, None) + started_at = session.setdefault("tool_started_at", {}).pop(tool_call_id, None) + duration_s = time.time() - started_at if started_at else None + if duration_s is not None: + payload["duration_s"] = duration_s + summary = _tool_summary(name, result, duration_s) + if summary: + payload["summary"] = summary + try: + from agent.display import render_edit_diff_with_delta + + rendered: list[str] = [] + if render_edit_diff_with_delta(name, result, function_args=args, snapshot=snapshot, print_fn=rendered.append): + payload["inline_diff"] = "\n".join(rendered) + except Exception: + pass + if _tool_progress_enabled(sid) or payload.get("inline_diff"): + _emit("tool.complete", sid, payload) + + +def _on_tool_progress( + sid: str, + event_type: str, + name: str | None = None, + preview: str | None = None, + _args: dict | None = None, + **_kwargs, +): + if not _tool_progress_enabled(sid): + return + if event_type == "tool.started" and name: + _emit("tool.progress", sid, {"name": name, "preview": preview or ""}) + return + if event_type == "reasoning.available" and preview: + _emit("reasoning.available", sid, {"text": str(preview)}) + return + if event_type.startswith("subagent."): + payload = { + "goal": str(_kwargs.get("goal") or ""), + "task_count": int(_kwargs.get("task_count") or 1), + "task_index": int(_kwargs.get("task_index") or 0), + } + if name: + payload["tool_name"] = str(name) + if preview: + payload["text"] = str(preview) + if _kwargs.get("status"): + payload["status"] = str(_kwargs["status"]) + if _kwargs.get("summary"): + payload["summary"] = str(_kwargs["summary"]) + if _kwargs.get("duration_seconds") is not None: + payload["duration_seconds"] = float(_kwargs["duration_seconds"]) + if preview and event_type == "subagent.tool": + payload["tool_preview"] = str(preview) + payload["text"] = str(preview) + _emit(event_type, sid, payload) + + +def _agent_cbs(sid: str) -> dict: + return dict( + tool_start_callback=lambda tc_id, name, args: _on_tool_start(sid, tc_id, name, args), + tool_complete_callback=lambda tc_id, name, args, result: _on_tool_complete(sid, tc_id, name, args, result), + tool_progress_callback=lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress( + sid, event_type, name, preview, args, **kwargs + ), + tool_gen_callback=lambda name: _tool_progress_enabled(sid) and _emit("tool.generating", sid, {"name": name}), + thinking_callback=lambda text: _emit("thinking.delta", sid, {"text": text}), + reasoning_callback=lambda text: _emit("reasoning.delta", sid, {"text": text}), + status_callback=lambda kind, text=None: _status_update(sid, str(kind), None if text is None else str(text)), + clarify_callback=lambda q, c: _block("clarify.request", sid, {"question": q, "choices": c}), + ) + + +def _wire_callbacks(sid: str): + from tools.terminal_tool import set_sudo_password_callback + from tools.skills_tool import set_secret_capture_callback + + set_sudo_password_callback(lambda: _block("sudo.request", sid, {}, timeout=120)) + + def secret_cb(env_var, prompt, metadata=None): + pl = {"prompt": prompt, "env_var": env_var} + if metadata: + pl["metadata"] = metadata + val = _block("secret.request", sid, pl) + if not val: + return {"success": True, "stored_as": env_var, "validated": False, "skipped": True, "message": "skipped"} + from hermes_cli.config import save_env_value_secure + return {**save_env_value_secure(env_var, val), "skipped": False, "message": "ok"} + + set_secret_capture_callback(secret_cb) + + +def _resolve_personality_prompt(cfg: dict) -> str: + """Resolve the active personality into a system prompt string.""" + name = (cfg.get("display", {}).get("personality", "") or "").strip().lower() + if not name or name in ("default", "none", "neutral"): + return "" + try: + from cli import load_cli_config + + personalities = load_cli_config().get("agent", {}).get("personalities", {}) + except Exception: + try: + from hermes_cli.config import load_config as _load_full_cfg + + personalities = _load_full_cfg().get("agent", {}).get("personalities", {}) + except Exception: + personalities = cfg.get("agent", {}).get("personalities", {}) + pval = personalities.get(name) + if pval is None: + return "" + return _render_personality_prompt(pval) + + +def _render_personality_prompt(value) -> str: + if isinstance(value, dict): + parts = [value.get("system_prompt", "")] + if value.get("tone"): + parts.append(f'Tone: {value["tone"]}') + if value.get("style"): + parts.append(f'Style: {value["style"]}') + return "\n".join(p for p in parts if p) + return str(value) + + +def _available_personalities(cfg: dict | None = None) -> dict: + try: + from cli import load_cli_config + + return load_cli_config().get("agent", {}).get("personalities", {}) or {} + except Exception: + try: + from hermes_cli.config import load_config as _load_full_cfg + + return _load_full_cfg().get("agent", {}).get("personalities", {}) or {} + except Exception: + cfg = cfg or _load_cfg() + return cfg.get("agent", {}).get("personalities", {}) or {} + + +def _validate_personality(value: str, cfg: dict | None = None) -> tuple[str, str]: + raw = str(value or "").strip() + name = raw.lower() + if not name or name in ("none", "default", "neutral"): + return "", "" + + personalities = _available_personalities(cfg) + if name not in personalities: + names = sorted(personalities) + available = ", ".join(f"`{n}`" for n in names) + base = f"Unknown personality: `{raw}`." + if available: + base += f"\n\nAvailable: `none`, {available}" + else: + base += "\n\nNo personalities configured." + raise ValueError(base) + + return name, _render_personality_prompt(personalities[name]) + + +def _apply_personality_to_session(sid: str, session: dict, new_prompt: str) -> tuple[bool, dict | None]: + if not session: + return False, None + + try: + info = _reset_session_agent(sid, session) + return True, info + except Exception: + if session.get("agent"): + agent = session["agent"] + agent.ephemeral_system_prompt = new_prompt or None + agent._cached_system_prompt = None + info = _session_info(agent) + _emit("session.info", sid, info) + return False, info + return False, None + + +def _background_agent_kwargs(agent, task_id: str) -> dict: + cfg = _load_cfg() + + return { + "base_url": getattr(agent, "base_url", None) or None, + "api_key": getattr(agent, "api_key", None) or None, + "provider": getattr(agent, "provider", None) or None, + "api_mode": getattr(agent, "api_mode", None) or None, + "acp_command": getattr(agent, "acp_command", None) or None, + "acp_args": getattr(agent, "acp_args", None) or None, + "model": getattr(agent, "model", None) or _resolve_model(), + "max_iterations": int(cfg.get("max_turns", 25) or 25), + "enabled_toolsets": getattr(agent, "enabled_toolsets", None) or _load_enabled_toolsets(), + "quiet_mode": True, + "verbose_logging": False, + "ephemeral_system_prompt": getattr(agent, "ephemeral_system_prompt", None) or None, + "providers_allowed": getattr(agent, "providers_allowed", None), + "providers_ignored": getattr(agent, "providers_ignored", None), + "providers_order": getattr(agent, "providers_order", None), + "provider_sort": getattr(agent, "provider_sort", None), + "provider_require_parameters": getattr(agent, "provider_require_parameters", False), + "provider_data_collection": getattr(agent, "provider_data_collection", None), + "session_id": task_id, + "reasoning_config": getattr(agent, "reasoning_config", None) or _load_reasoning_config(), + "service_tier": getattr(agent, "service_tier", None) or _load_service_tier(), + "request_overrides": dict(getattr(agent, "request_overrides", {}) or {}), + "platform": "tui", + "session_db": _get_db(), + "fallback_model": getattr(agent, "_fallback_model", None), + } + + +def _reset_session_agent(sid: str, session: dict) -> dict: + tokens = _set_session_context(session["session_key"]) + try: + new_agent = _make_agent(sid, session["session_key"], session_id=session["session_key"]) + finally: + _clear_session_context(tokens) + session["agent"] = new_agent + session["attached_images"] = [] + session["edit_snapshots"] = {} + session["image_counter"] = 0 + session["running"] = False + session["show_reasoning"] = _load_show_reasoning() + session["tool_progress_mode"] = _load_tool_progress_mode() + session["tool_started_at"] = {} + with session["history_lock"]: + session["history"] = [] + session["history_version"] = int(session.get("history_version", 0)) + 1 + info = _session_info(new_agent) + _emit("session.info", sid, info) + _restart_slash_worker(session) + return info + + +def _make_agent(sid: str, key: str, session_id: str | None = None): + from run_agent import AIAgent + cfg = _load_cfg() + system_prompt = cfg.get("agent", {}).get("system_prompt", "") or "" + if not system_prompt: + system_prompt = _resolve_personality_prompt(cfg) + return AIAgent( + model=_resolve_model(), + quiet_mode=True, + verbose_logging=_load_tool_progress_mode() == "verbose", + reasoning_config=_load_reasoning_config(), + service_tier=_load_service_tier(), + enabled_toolsets=_load_enabled_toolsets(), + platform="tui", + session_id=session_id or key, session_db=_get_db(), + ephemeral_system_prompt=system_prompt or None, + **_agent_cbs(sid), + ) + + +def _init_session(sid: str, key: str, agent, history: list, cols: int = 80): + _sessions[sid] = { + "agent": agent, + "session_key": key, + "history": history, + "history_lock": threading.Lock(), + "history_version": 0, + "running": False, + "attached_images": [], + "image_counter": 0, + "cols": cols, + "slash_worker": None, + "show_reasoning": _load_show_reasoning(), + "tool_progress_mode": _load_tool_progress_mode(), + "edit_snapshots": {}, + "tool_started_at": {}, + } + try: + _sessions[sid]["slash_worker"] = _SlashWorker(key, getattr(agent, "model", _resolve_model())) + except Exception: + # Defer hard-failure to slash.exec; chat still works without slash worker. + _sessions[sid]["slash_worker"] = None + try: + from tools.approval import register_gateway_notify, load_permanent_allowlist + register_gateway_notify(key, lambda data: _emit("approval.request", sid, data)) + load_permanent_allowlist() + except Exception: + pass + _wire_callbacks(sid) + _emit("session.info", sid, _session_info(agent)) + + +def _new_session_key() -> str: + return f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" + + +def _with_checkpoints(session, fn): + return fn(session["agent"]._checkpoint_mgr, os.getenv("TERMINAL_CWD", os.getcwd())) + + +def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str: + try: + checkpoints = mgr.list_checkpoints(cwd) + idx = int(ref) - 1 + except ValueError: + return ref + if 0 <= idx < len(checkpoints): + return checkpoints[idx].get("hash", ref) + raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.") + + +def _enrich_with_attached_images(user_text: str, image_paths: list[str]) -> str: + """Pre-analyze attached images via vision and prepend descriptions to user text.""" + import asyncio, json as _json + from tools.vision_tools import vision_analyze_tool + + prompt = ( + "Describe everything visible in this image in thorough detail. " + "Include any text, code, data, objects, people, layout, colors, " + "and any other notable visual information." + ) + + parts: list[str] = [] + for path in image_paths: + p = Path(path) + if not p.exists(): + continue + hint = f"[You can examine it with vision_analyze using image_url: {p}]" + try: + r = _json.loads(asyncio.run(vision_analyze_tool(image_url=str(p), user_prompt=prompt))) + desc = r.get("analysis", "") if r.get("success") else None + parts.append(f"[The user attached an image:\n{desc}]\n{hint}" if desc + else f"[The user attached an image but analysis failed.]\n{hint}") + except Exception: + parts.append(f"[The user attached an image but analysis failed.]\n{hint}") + + text = user_text or "" + prefix = "\n\n".join(parts) + if prefix: + return f"{prefix}\n\n{text}" if text else prefix + return text or "What do you see in this image?" + + +def _history_to_messages(history: list[dict]) -> list[dict]: + messages = [] + tool_call_args = {} + + for m in history: + if not isinstance(m, dict): + continue + role = m.get("role") + if role not in ("user", "assistant", "tool", "system"): + continue + if role == "assistant" and m.get("tool_calls"): + for tc in m["tool_calls"]: + fn = tc.get("function", {}) + tc_id = tc.get("id", "") + if tc_id and fn.get("name"): + try: + args = json.loads(fn.get("arguments", "{}")) + except (json.JSONDecodeError, TypeError): + args = {} + tool_call_args[tc_id] = (fn["name"], args) + if not (m.get("content") or "").strip(): + continue + if role == "tool": + tc_id = m.get("tool_call_id", "") + tc_info = tool_call_args.get(tc_id) if tc_id else None + name = (tc_info[0] if tc_info else None) or m.get("tool_name") or "tool" + args = (tc_info[1] if tc_info else None) or {} + messages.append({"role": "tool", "name": name, "context": _tool_ctx(name, args)}) + continue + if not (m.get("content") or "").strip(): + continue + messages.append({"role": role, "text": m.get("content") or ""}) + + return messages + + +# ── Methods: session ───────────────────────────────────────────────── + +@method("session.create") +def _(rid, params: dict) -> dict: + sid = uuid.uuid4().hex[:8] + key = _new_session_key() + cols = int(params.get("cols", 80)) + _enable_gateway_prompts() + + ready = threading.Event() + + _sessions[sid] = { + "agent": None, + "agent_error": None, + "agent_ready": ready, + "attached_images": [], + "cols": cols, + "edit_snapshots": {}, + "history": [], + "history_lock": threading.Lock(), + "history_version": 0, + "image_counter": 0, + "running": False, + "session_key": key, + "show_reasoning": _load_show_reasoning(), + "slash_worker": None, + "tool_progress_mode": _load_tool_progress_mode(), + "tool_started_at": {}, + } + + def _build() -> None: + session = _sessions[sid] + try: + tokens = _set_session_context(key) + try: + agent = _make_agent(sid, key) + finally: + _clear_session_context(tokens) + + _get_db().create_session(key, source="tui", model=_resolve_model()) + session["agent"] = agent + + try: + session["slash_worker"] = _SlashWorker(key, getattr(agent, "model", _resolve_model())) + except Exception: + pass + + try: + from tools.approval import register_gateway_notify, load_permanent_allowlist + register_gateway_notify(key, lambda data: _emit("approval.request", sid, data)) + load_permanent_allowlist() + except Exception: + pass + + _wire_callbacks(sid) + + info = _session_info(agent) + warn = _probe_credentials(agent) + if warn: + info["credential_warning"] = warn + _emit("session.info", sid, info) + except Exception as e: + session["agent_error"] = str(e) + _emit("error", sid, {"message": f"agent init failed: {e}"}) + finally: + ready.set() + + threading.Thread(target=_build, daemon=True).start() + + return _ok(rid, { + "session_id": sid, + "info": { + "model": _resolve_model(), + "tools": {}, + "skills": {}, + "cwd": os.getenv("TERMINAL_CWD", os.getcwd()), + }, + }) + + +@method("session.list") +def _(rid, params: dict) -> dict: + try: + db = _get_db() + # Show both TUI and CLI sessions — TUI is the successor to the CLI, + # so users expect to resume their old CLI sessions here too. + tui = db.list_sessions_rich(source="tui", limit=params.get("limit", 20)) + cli = db.list_sessions_rich(source="cli", limit=params.get("limit", 20)) + rows = sorted(tui + cli, key=lambda s: s.get("started_at") or 0, reverse=True)[:params.get("limit", 20)] + return _ok(rid, {"sessions": [ + {"id": s["id"], "title": s.get("title") or "", "preview": s.get("preview") or "", + "started_at": s.get("started_at") or 0, "message_count": s.get("message_count") or 0, + "source": s.get("source") or ""} + for s in rows + ]}) + except Exception as e: + return _err(rid, 5006, str(e)) + + +@method("session.resume") +def _(rid, params: dict) -> dict: + target = params.get("session_id", "") + if not target: + return _err(rid, 4006, "session_id required") + db = _get_db() + found = db.get_session(target) + if not found: + found = db.get_session_by_title(target) + if found: + target = found["id"] + else: + return _err(rid, 4007, "session not found") + sid = uuid.uuid4().hex[:8] + _enable_gateway_prompts() + try: + db.reopen_session(target) + history = db.get_messages_as_conversation(target) + messages = _history_to_messages(history) + tokens = _set_session_context(target) + try: + agent = _make_agent(sid, target, session_id=target) + finally: + _clear_session_context(tokens) + _init_session(sid, target, agent, history, cols=int(params.get("cols", 80))) + except Exception as e: + return _err(rid, 5000, f"resume failed: {e}") + return _ok( + rid, + { + "session_id": sid, + "resumed": target, + "message_count": len(messages), + "messages": messages, + "info": _session_info(agent), + }, + ) + + +@method("session.title") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + title, key = params.get("title", ""), session["session_key"] + if not title: + return _ok(rid, {"title": _get_db().get_session_title(key) or "", "session_key": key}) + try: + _get_db().set_session_title(key, title) + return _ok(rid, {"title": title}) + except Exception as e: + return _err(rid, 5007, str(e)) + + +@method("session.usage") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + return err or _ok(rid, _get_usage(session["agent"])) + + +@method("session.history") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + return err or _ok( + rid, + { + "count": len(session.get("history", [])), + "messages": _history_to_messages(list(session.get("history", []))), + }, + ) + + +@method("session.undo") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + removed = 0 + with session["history_lock"]: + history = session.get("history", []) + while history and history[-1].get("role") in ("assistant", "tool"): + history.pop() + removed += 1 + if history and history[-1].get("role") == "user": + history.pop() + removed += 1 + if removed: + session["history_version"] = int(session.get("history_version", 0)) + 1 + return _ok(rid, {"removed": removed}) + + +@method("session.compress") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + try: + with session["history_lock"]: + removed, usage = _compress_session_history(session, str(params.get("focus_topic", "") or "").strip()) + messages = list(session.get("history", [])) + info = _session_info(session["agent"]) + _emit("session.info", params.get("session_id", ""), info) + return _ok(rid, {"status": "compressed", "removed": removed, "usage": usage, "info": info, "messages": messages}) + except Exception as e: + return _err(rid, 5005, str(e)) + + +@method("session.save") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + import time as _time + filename = os.path.abspath(f"hermes_conversation_{_time.strftime('%Y%m%d_%H%M%S')}.json") + try: + with open(filename, "w") as f: + json.dump({"model": getattr(session["agent"], "model", ""), "messages": session.get("history", [])}, + f, indent=2, ensure_ascii=False) + return _ok(rid, {"file": filename}) + except Exception as e: + return _err(rid, 5011, str(e)) + + +@method("session.close") +def _(rid, params: dict) -> dict: + sid = params.get("session_id", "") + session = _sessions.pop(sid, None) + if not session: + return _ok(rid, {"closed": False}) + try: + from tools.approval import unregister_gateway_notify + + unregister_gateway_notify(session["session_key"]) + except Exception: + pass + try: + worker = session.get("slash_worker") + if worker: + worker.close() + except Exception: + pass + return _ok(rid, {"closed": True}) + + +@method("session.branch") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + db = _get_db() + old_key = session["session_key"] + with session["history_lock"]: + history = [dict(msg) for msg in session.get("history", [])] + if not history: + return _err(rid, 4008, "nothing to branch — send a message first") + new_key = _new_session_key() + branch_name = params.get("name", "") + try: + if branch_name: + title = branch_name + else: + current = db.get_session_title(old_key) or "branch" + title = db.get_next_title_in_lineage(current) if hasattr(db, "get_next_title_in_lineage") else f"{current} (branch)" + db.create_session(new_key, source="tui", model=_resolve_model(), parent_session_id=old_key) + for msg in history: + db.append_message(session_id=new_key, role=msg.get("role", "user"), content=msg.get("content")) + db.set_session_title(new_key, title) + except Exception as e: + return _err(rid, 5008, f"branch failed: {e}") + new_sid = uuid.uuid4().hex[:8] + try: + tokens = _set_session_context(new_key) + try: + agent = _make_agent(new_sid, new_key, session_id=new_key) + finally: + _clear_session_context(tokens) + _init_session(new_sid, new_key, agent, list(history), cols=session.get("cols", 80)) + except Exception as e: + return _err(rid, 5000, f"agent init failed on branch: {e}") + return _ok(rid, {"session_id": new_sid, "title": title, "parent": old_key}) + + +@method("session.interrupt") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + if hasattr(session["agent"], "interrupt"): + session["agent"].interrupt() + _clear_pending() + try: + from tools.approval import resolve_gateway_approval + resolve_gateway_approval(session["session_key"], "deny", resolve_all=True) + except Exception: + pass + return _ok(rid, {"status": "interrupted"}) + + +@method("terminal.resize") +def _(rid, params: dict) -> dict: + session, err = _sess_nowait(params, rid) + if err: + return err + session["cols"] = int(params.get("cols", 80)) + return _ok(rid, {"cols": session["cols"]}) + + +# ── Methods: prompt ────────────────────────────────────────────────── + +@method("prompt.submit") +def _(rid, params: dict) -> dict: + sid, text = params.get("session_id", ""), params.get("text", "") + session, err = _sess(params, rid) + if err: + return err + with session["history_lock"]: + if session.get("running"): + return _err(rid, 4009, "session busy") + session["running"] = True + history = list(session["history"]) + history_version = int(session.get("history_version", 0)) + images = list(session.get("attached_images", [])) + session["attached_images"] = [] + agent = session["agent"] + _emit("message.start", sid) + + def run(): + approval_token = None + session_tokens = [] + try: + from tools.approval import reset_current_session_key, set_current_session_key + approval_token = set_current_session_key(session["session_key"]) + session_tokens = _set_session_context(session["session_key"]) + cols = session.get("cols", 80) + streamer = make_stream_renderer(cols) + prompt = text + + if isinstance(prompt, str) and "@" in prompt: + from agent.context_references import preprocess_context_references + from agent.model_metadata import get_model_context_length + + ctx_len = get_model_context_length( + getattr(agent, "model", "") or _resolve_model(), + base_url=getattr(agent, "base_url", "") or "", + api_key=getattr(agent, "api_key", "") or "", + ) + ctx = preprocess_context_references( + prompt, + cwd=os.environ.get("TERMINAL_CWD", os.getcwd()), + allowed_root=os.environ.get("TERMINAL_CWD", os.getcwd()), + context_length=ctx_len, + ) + if ctx.blocked: + _emit("error", sid, {"message": "\n".join(ctx.warnings) or "Context injection refused."}) + return + prompt = ctx.message + + prompt = _enrich_with_attached_images(prompt, images) if images else prompt + + def _stream(delta): + payload = {"text": delta} + if streamer and (r := streamer.feed(delta)) is not None: + payload["rendered"] = r + _emit("message.delta", sid, payload) + + result = agent.run_conversation( + prompt, conversation_history=list(history), + stream_callback=_stream, + ) + + last_reasoning = None + if isinstance(result, dict): + if isinstance(result.get("messages"), list): + with session["history_lock"]: + if int(session.get("history_version", 0)) == history_version: + session["history"] = result["messages"] + session["history_version"] = history_version + 1 + raw = result.get("final_response", "") + status = "interrupted" if result.get("interrupted") else "error" if result.get("error") else "complete" + lr = result.get("last_reasoning") + if isinstance(lr, str) and lr.strip(): + last_reasoning = lr.strip() + else: + raw = str(result) + status = "complete" + + payload = {"text": raw, "usage": _get_usage(agent), "status": status} + if last_reasoning: + payload["reasoning"] = last_reasoning + rendered = render_message(raw, cols) + if rendered: + payload["rendered"] = rendered + _emit("message.complete", sid, payload) + except Exception as e: + _emit("error", sid, {"message": str(e)}) + finally: + try: + if approval_token is not None: + reset_current_session_key(approval_token) + except Exception: + pass + _clear_session_context(session_tokens) + with session["history_lock"]: + session["running"] = False + + threading.Thread(target=run, daemon=True).start() + return _ok(rid, {"status": "streaming"}) + + +@method("clipboard.paste") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + try: + from datetime import datetime + from hermes_cli.clipboard import has_clipboard_image, save_clipboard_image + except Exception as e: + return _err(rid, 5027, f"clipboard unavailable: {e}") + + session["image_counter"] = session.get("image_counter", 0) + 1 + img_dir = _hermes_home / "images" + img_dir.mkdir(parents=True, exist_ok=True) + img_path = img_dir / f"clip_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{session['image_counter']}.png" + + # Save-first: mirrors CLI keybinding path; more robust than has_image() precheck + if not save_clipboard_image(img_path): + session["image_counter"] = max(0, session["image_counter"] - 1) + msg = "Clipboard has image but extraction failed" if has_clipboard_image() else "No image found in clipboard" + return _ok(rid, {"attached": False, "message": msg}) + + session.setdefault("attached_images", []).append(str(img_path)) + return _ok( + rid, + { + "attached": True, + "path": str(img_path), + "count": len(session["attached_images"]), + **_image_meta(img_path), + }, + ) + + +@method("image.attach") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + raw = str(params.get("path", "") or "").strip() + if not raw: + return _err(rid, 4015, "path required") + try: + from cli import _IMAGE_EXTENSIONS, _resolve_attachment_path, _split_path_input + + path_token, remainder = _split_path_input(raw) + image_path = _resolve_attachment_path(path_token) + if image_path is None: + return _err(rid, 4016, f"image not found: {path_token}") + if image_path.suffix.lower() not in _IMAGE_EXTENSIONS: + return _err(rid, 4016, f"unsupported image: {image_path.name}") + session.setdefault("attached_images", []).append(str(image_path)) + return _ok( + rid, + { + "attached": True, + "path": str(image_path), + "count": len(session["attached_images"]), + "remainder": remainder, + "text": remainder or f"[User attached image: {image_path.name}]", + **_image_meta(image_path), + }, + ) + except Exception as e: + return _err(rid, 5027, str(e)) + + +@method("input.detect_drop") +def _(rid, params: dict) -> dict: + session, err = _sess_nowait(params, rid) + if err: + return err + try: + from cli import _detect_file_drop + + raw = str(params.get("text", "") or "") + dropped = _detect_file_drop(raw) + if not dropped: + return _ok(rid, {"matched": False}) + + drop_path = dropped["path"] + remainder = dropped["remainder"] + if dropped["is_image"]: + session.setdefault("attached_images", []).append(str(drop_path)) + text = remainder or f"[User attached image: {drop_path.name}]" + return _ok( + rid, + { + "matched": True, + "is_image": True, + "path": str(drop_path), + "count": len(session["attached_images"]), + "text": text, + **_image_meta(drop_path), + }, + ) + + text = f"[User attached file: {drop_path}]" + (f"\n{remainder}" if remainder else "") + return _ok( + rid, + { + "matched": True, + "is_image": False, + "path": str(drop_path), + "name": drop_path.name, + "text": text, + }, + ) + except Exception as e: + return _err(rid, 5027, str(e)) + + +@method("prompt.background") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + text, parent = params.get("text", ""), params.get("session_id", "") + if not text: + return _err(rid, 4012, "text required") + task_id = f"bg_{uuid.uuid4().hex[:6]}" + + def run(): + session_tokens = _set_session_context(task_id) + try: + from run_agent import AIAgent + result = AIAgent(**_background_agent_kwargs(session["agent"], task_id)).run_conversation( + user_message=text, + task_id=task_id, + ) + _emit("background.complete", parent, {"task_id": task_id, + "text": result.get("final_response", str(result)) if isinstance(result, dict) else str(result)}) + except Exception as e: + _emit("background.complete", parent, {"task_id": task_id, "text": f"error: {e}"}) + finally: + _clear_session_context(session_tokens) + + threading.Thread(target=run, daemon=True).start() + return _ok(rid, {"task_id": task_id}) + + +@method("prompt.btw") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + text, sid = params.get("text", ""), params.get("session_id", "") + if not text: + return _err(rid, 4012, "text required") + snapshot = list(session.get("history", [])) + + def run(): + session_tokens = _set_session_context(session["session_key"]) + try: + from run_agent import AIAgent + result = AIAgent(model=_resolve_model(), quiet_mode=True, platform="tui", + max_iterations=8, enabled_toolsets=[]).run_conversation(text, conversation_history=snapshot) + _emit("btw.complete", sid, {"text": result.get("final_response", str(result)) if isinstance(result, dict) else str(result)}) + except Exception as e: + _emit("btw.complete", sid, {"text": f"error: {e}"}) + finally: + _clear_session_context(session_tokens) + + threading.Thread(target=run, daemon=True).start() + return _ok(rid, {"status": "running"}) + + +# ── Methods: respond ───────────────────────────────────────────────── + +def _respond(rid, params, key): + r = params.get("request_id", "") + ev = _pending.get(r) + if not ev: + return _err(rid, 4009, f"no pending {key} request") + _answers[r] = params.get(key, "") + ev.set() + return _ok(rid, {"status": "ok"}) + + +@method("clarify.respond") +def _(rid, params: dict) -> dict: + return _respond(rid, params, "answer") + +@method("sudo.respond") +def _(rid, params: dict) -> dict: + return _respond(rid, params, "password") + +@method("secret.respond") +def _(rid, params: dict) -> dict: + return _respond(rid, params, "value") + +@method("approval.respond") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + try: + from tools.approval import resolve_gateway_approval + return _ok(rid, {"resolved": resolve_gateway_approval( + session["session_key"], params.get("choice", "deny"), resolve_all=params.get("all", False))}) + except Exception as e: + return _err(rid, 5004, str(e)) + + +# ── Methods: config ────────────────────────────────────────────────── + +@method("config.set") +def _(rid, params: dict) -> dict: + key, value = params.get("key", ""), params.get("value", "") + session = _sessions.get(params.get("session_id", "")) + + if key == "model": + try: + if not value: + return _err(rid, 4002, "model value required") + if session: + result = _apply_model_switch(params.get("session_id", ""), session, value) + else: + result = _apply_model_switch("", {"agent": None}, value) + return _ok(rid, {"key": key, "value": result["value"], "warning": result["warning"]}) + except Exception as e: + return _err(rid, 5001, str(e)) + + if key == "verbose": + cycle = ["off", "new", "all", "verbose"] + cur = session.get("tool_progress_mode", _load_tool_progress_mode()) if session else _load_tool_progress_mode() + if value and value != "cycle": + nv = str(value).strip().lower() + if nv not in cycle: + return _err(rid, 4002, f"unknown verbose mode: {value}") + else: + try: + idx = cycle.index(cur) + except ValueError: + idx = 2 + nv = cycle[(idx + 1) % len(cycle)] + _write_config_key("display.tool_progress", nv) + if session: + session["tool_progress_mode"] = nv + agent = session.get("agent") + if agent is not None: + agent.verbose_logging = nv == "verbose" + return _ok(rid, {"key": key, "value": nv}) + + if key == "yolo": + try: + if session: + from tools.approval import ( + disable_session_yolo, + enable_session_yolo, + is_session_yolo_enabled, + ) + + current = is_session_yolo_enabled(session["session_key"]) + if current: + disable_session_yolo(session["session_key"]) + nv = "0" + else: + enable_session_yolo(session["session_key"]) + nv = "1" + else: + current = bool(os.environ.get("HERMES_YOLO_MODE")) + if current: + os.environ.pop("HERMES_YOLO_MODE", None) + nv = "0" + else: + os.environ["HERMES_YOLO_MODE"] = "1" + nv = "1" + return _ok(rid, {"key": key, "value": nv}) + except Exception as e: + return _err(rid, 5001, str(e)) + + if key == "reasoning": + try: + from hermes_constants import parse_reasoning_effort + + arg = str(value or "").strip().lower() + if arg in ("show", "on"): + _write_config_key("display.show_reasoning", True) + if session: + session["show_reasoning"] = True + return _ok(rid, {"key": key, "value": "show"}) + if arg in ("hide", "off"): + _write_config_key("display.show_reasoning", False) + if session: + session["show_reasoning"] = False + return _ok(rid, {"key": key, "value": "hide"}) + + parsed = parse_reasoning_effort(arg) + if parsed is None: + return _err(rid, 4002, f"unknown reasoning value: {value}") + _write_config_key("agent.reasoning_effort", arg) + if session and session.get("agent") is not None: + session["agent"].reasoning_config = parsed + return _ok(rid, {"key": key, "value": arg}) + except Exception as e: + return _err(rid, 5001, str(e)) + + if key == "details_mode": + nv = str(value or "").strip().lower() + allowed_dm = frozenset({"hidden", "collapsed", "expanded"}) + if nv not in allowed_dm: + return _err(rid, 4002, f"unknown details_mode: {value}") + _write_config_key("display.details_mode", nv) + return _ok(rid, {"key": key, "value": nv}) + + if key == "thinking_mode": + nv = str(value or "").strip().lower() + allowed_tm = frozenset({"collapsed", "truncated", "full"}) + if nv not in allowed_tm: + return _err(rid, 4002, f"unknown thinking_mode: {value}") + _write_config_key("display.thinking_mode", nv) + # Backward compatibility bridge: keep details_mode aligned. + _write_config_key("display.details_mode", "expanded" if nv == "full" else "collapsed") + return _ok(rid, {"key": key, "value": nv}) + + if key in ("compact", "statusbar"): + raw = str(value or "").strip().lower() + cfg0 = _load_cfg() + d0 = cfg0.get("display") if isinstance(cfg0.get("display"), dict) else {} + def_key = "tui_compact" if key == "compact" else "tui_statusbar" + cur_b = bool(d0.get(def_key, False if key == "compact" else True)) + if raw in ("", "toggle"): + nv_b = not cur_b + elif raw == "on": + nv_b = True + elif raw == "off": + nv_b = False + else: + return _err(rid, 4002, f"unknown {key} value: {value}") + _write_config_key(f"display.{def_key}", nv_b) + out = "on" if nv_b else "off" + return _ok(rid, {"key": key, "value": out}) + + if key in ("prompt", "personality", "skin"): + try: + cfg = _load_cfg() + if key == "prompt": + if value == "clear": + cfg.pop("custom_prompt", None) + nv = "" + else: + cfg["custom_prompt"] = value + nv = value + _save_cfg(cfg) + elif key == "personality": + sid_key = params.get("session_id", "") + pname, new_prompt = _validate_personality(str(value or ""), cfg) + _write_config_key("display.personality", pname) + _write_config_key("agent.system_prompt", new_prompt) + nv = str(value or "default") + history_reset, info = _apply_personality_to_session(sid_key, session, new_prompt) + else: + _write_config_key(f"display.{key}", value) + nv = value + if key == "skin": + _emit("skin.changed", "", resolve_skin()) + resp = {"key": key, "value": nv} + if key == "personality": + resp["history_reset"] = history_reset + if info is not None: + resp["info"] = info + return _ok(rid, resp) + except Exception as e: + return _err(rid, 5001, str(e)) + + return _err(rid, 4002, f"unknown config key: {key}") + + +@method("config.get") +def _(rid, params: dict) -> dict: + key = params.get("key", "") + if key == "provider": + try: + from hermes_cli.models import list_available_providers, normalize_provider + model = _resolve_model() + parts = model.split("/", 1) + return _ok(rid, {"model": model, "provider": normalize_provider(parts[0]) if len(parts) > 1 else "unknown", + "providers": list_available_providers()}) + except Exception as e: + return _err(rid, 5013, str(e)) + if key == "profile": + from hermes_constants import display_hermes_home + return _ok(rid, {"home": str(_hermes_home), "display": display_hermes_home()}) + if key == "full": + return _ok(rid, {"config": _load_cfg()}) + if key == "prompt": + return _ok(rid, {"prompt": _load_cfg().get("custom_prompt", "")}) + if key == "skin": + return _ok(rid, {"value": _load_cfg().get("display", {}).get("skin", "default")}) + if key == "personality": + return _ok(rid, {"value": _load_cfg().get("display", {}).get("personality", "default")}) + if key == "reasoning": + cfg = _load_cfg() + effort = str(cfg.get("agent", {}).get("reasoning_effort", "medium") or "medium") + display = "show" if bool(cfg.get("display", {}).get("show_reasoning", False)) else "hide" + return _ok(rid, {"value": effort, "display": display}) + if key == "details_mode": + allowed_dm = frozenset({"hidden", "collapsed", "expanded"}) + raw = str(_load_cfg().get("display", {}).get("details_mode", "collapsed") or "collapsed").strip().lower() + nv = raw if raw in allowed_dm else "collapsed" + return _ok(rid, {"value": nv}) + if key == "thinking_mode": + allowed_tm = frozenset({"collapsed", "truncated", "full"}) + cfg = _load_cfg() + raw = str(cfg.get("display", {}).get("thinking_mode", "") or "").strip().lower() + if raw in allowed_tm: + nv = raw + else: + dm = str(cfg.get("display", {}).get("details_mode", "collapsed") or "collapsed").strip().lower() + nv = "full" if dm == "expanded" else "collapsed" + return _ok(rid, {"value": nv}) + if key == "compact": + on = bool(_load_cfg().get("display", {}).get("tui_compact", False)) + return _ok(rid, {"value": "on" if on else "off"}) + if key == "statusbar": + on = bool(_load_cfg().get("display", {}).get("tui_statusbar", True)) + return _ok(rid, {"value": "on" if on else "off"}) + if key == "mtime": + cfg_path = _hermes_home / "config.yaml" + try: + return _ok(rid, {"mtime": cfg_path.stat().st_mtime if cfg_path.exists() else 0}) + except Exception: + return _ok(rid, {"mtime": 0}) + return _err(rid, 4002, f"unknown config key: {key}") + + +@method("setup.status") +def _(rid, params: dict) -> dict: + try: + from hermes_cli.main import _has_any_provider_configured + return _ok(rid, {"provider_configured": bool(_has_any_provider_configured())}) + except Exception as e: + return _err(rid, 5016, str(e)) + + +# ── Methods: tools & system ────────────────────────────────────────── + +@method("process.stop") +def _(rid, params: dict) -> dict: + try: + from tools.process_registry import process_registry + return _ok(rid, {"killed": process_registry.kill_all()}) + except Exception as e: + return _err(rid, 5010, str(e)) + + +@method("reload.mcp") +def _(rid, params: dict) -> dict: + session = _sessions.get(params.get("session_id", "")) + try: + from tools.mcp_tool import shutdown_mcp_servers, discover_mcp_tools + shutdown_mcp_servers() + discover_mcp_tools() + if session: + agent = session["agent"] + if hasattr(agent, "refresh_tools"): + agent.refresh_tools() + _emit("session.info", params.get("session_id", ""), _session_info(agent)) + return _ok(rid, {"status": "reloaded"}) + except Exception as e: + return _err(rid, 5015, str(e)) + + +_TUI_HIDDEN: frozenset[str] = frozenset({ + "sethome", "set-home", "update", "commands", "status", "approve", "deny", +}) + +_TUI_EXTRA: list[tuple[str, str, str]] = [ + ("/compact", "Toggle compact display mode", "TUI"), + ("/logs", "Show recent gateway log lines", "TUI"), +] + + +@method("commands.catalog") +def _(rid, params: dict) -> dict: + """Registry-backed slash metadata for the TUI — categorized, no aliases.""" + try: + from hermes_cli.commands import COMMAND_REGISTRY, SUBCOMMANDS, _build_description + + all_pairs: list[list[str]] = [] + canon: dict[str, str] = {} + categories: list[dict] = [] + cat_map: dict[str, list[list[str]]] = {} + cat_order: list[str] = [] + + for cmd in COMMAND_REGISTRY: + c = f"/{cmd.name}" + canon[c.lower()] = c + for a in cmd.aliases: + canon[f"/{a}".lower()] = c + + if cmd.name in _TUI_HIDDEN: + continue + + desc = _build_description(cmd) + all_pairs.append([c, desc]) + + cat = cmd.category + if cat not in cat_map: + cat_map[cat] = [] + cat_order.append(cat) + cat_map[cat].append([c, desc]) + + for name, desc, cat in _TUI_EXTRA: + all_pairs.append([name, desc]) + if cat not in cat_map: + cat_map[cat] = [] + cat_order.append(cat) + cat_map[cat].append([name, desc]) + + skill_count = 0 + warning = "" + try: + from agent.skill_commands import scan_skill_commands + for k, info in sorted(scan_skill_commands().items()): + d = str(info.get("description", "Skill")) + all_pairs.append([k, d[:120] + ("…" if len(d) > 120 else "")]) + skill_count += 1 + except Exception as e: + warning = f"skill discovery unavailable: {e}" + + for cat in cat_order: + categories.append({"name": cat, "pairs": cat_map[cat]}) + + sub = {k: v[:] for k, v in SUBCOMMANDS.items()} + return _ok(rid, { + "pairs": all_pairs, + "sub": sub, + "canon": canon, + "categories": categories, + "skill_count": skill_count, + "warning": warning, + }) + except Exception as e: + return _err(rid, 5020, str(e)) + + +def _cli_exec_blocked(argv: list[str]) -> str | None: + """Return user hint if this argv must not run headless in the gateway process.""" + if not argv: + return "bare `hermes` is interactive — use `/hermes chat -q …` or run `hermes` in another terminal" + a0 = argv[0].lower() + if a0 == "setup": + return "`hermes setup` needs a full terminal — run it outside the TUI" + if a0 == "gateway": + return "`hermes gateway` is long-running — run it in another terminal" + if a0 == "sessions" and len(argv) > 1 and argv[1].lower() == "browse": + return "`hermes sessions browse` is interactive — use /resume here, or run browse in another terminal" + if a0 == "config" and len(argv) > 1 and argv[1].lower() == "edit": + return "`hermes config edit` needs $EDITOR in a real terminal" + return None + + +@method("cli.exec") +def _(rid, params: dict) -> dict: + """Run `python -m hermes_cli.main` with argv; capture stdout/stderr (non-interactive only).""" + argv = params.get("argv", []) + if not isinstance(argv, list) or not all(isinstance(x, str) for x in argv): + return _err(rid, 4003, "argv must be list[str]") + hint = _cli_exec_blocked(argv) + if hint: + return _ok(rid, {"blocked": True, "hint": hint, "code": -1, "output": ""}) + try: + r = subprocess.run( + [sys.executable, "-m", "hermes_cli.main", *argv], + capture_output=True, + text=True, + timeout=min(int(params.get("timeout", 240)), 600), + cwd=os.getcwd(), + env=os.environ.copy(), + ) + parts = [r.stdout or "", r.stderr or ""] + out = "\n".join(p for p in parts if p).strip() or "(no output)" + return _ok(rid, {"blocked": False, "code": r.returncode, "output": out[:48_000]}) + except subprocess.TimeoutExpired: + return _err(rid, 5016, "cli.exec: timeout") + except Exception as e: + return _err(rid, 5017, str(e)) + + +@method("command.resolve") +def _(rid, params: dict) -> dict: + try: + from hermes_cli.commands import resolve_command + r = resolve_command(params.get("name", "")) + if r: + return _ok(rid, {"canonical": r.name, "description": r.description, "category": r.category}) + return _err(rid, 4011, f"unknown command: {params.get('name')}") + except Exception as e: + return _err(rid, 5012, str(e)) + + +def _resolve_name(name: str) -> str: + try: + from hermes_cli.commands import resolve_command + r = resolve_command(name) + return r.name if r else name + except Exception: + return name + + +@method("command.dispatch") +def _(rid, params: dict) -> dict: + name, arg = params.get("name", "").lstrip("/"), params.get("arg", "") + resolved = _resolve_name(name) + if resolved != name: + name = resolved + session = _sessions.get(params.get("session_id", "")) + + qcmds = _load_cfg().get("quick_commands", {}) + if name in qcmds: + qc = qcmds[name] + if qc.get("type") == "exec": + r = subprocess.run(qc.get("command", ""), shell=True, capture_output=True, text=True, timeout=30) + output = ((r.stdout or "") + ("\n" if r.stdout and r.stderr else "") + (r.stderr or "")).strip()[:4000] + if r.returncode != 0: + return _err(rid, 4018, output or f"quick command failed with exit code {r.returncode}") + return _ok(rid, {"type": "exec", "output": output}) + if qc.get("type") == "alias": + return _ok(rid, {"type": "alias", "target": qc.get("target", "")}) + + try: + from hermes_cli.plugins import get_plugin_command_handler + handler = get_plugin_command_handler(name) + if handler: + return _ok(rid, {"type": "plugin", "output": str(handler(arg) or "")}) + except Exception: + pass + + try: + from agent.skill_commands import scan_skill_commands, build_skill_invocation_message + cmds = scan_skill_commands() + key = f"/{name}" + if key in cmds: + msg = build_skill_invocation_message(key, arg, task_id=session.get("session_key", "") if session else "") + if msg: + return _ok(rid, {"type": "skill", "message": msg, "name": cmds[key].get("name", name)}) + except Exception: + pass + + return _err(rid, 4018, f"not a quick/plugin/skill command: {name}") + + +# ── Methods: paste ──────────────────────────────────────────────────── + +_paste_counter = 0 + +@method("paste.collapse") +def _(rid, params: dict) -> dict: + global _paste_counter + text = params.get("text", "") + if not text: + return _err(rid, 4004, "empty paste") + + _paste_counter += 1 + line_count = text.count('\n') + 1 + paste_dir = _hermes_home / "pastes" + paste_dir.mkdir(parents=True, exist_ok=True) + + from datetime import datetime + paste_file = paste_dir / f"paste_{_paste_counter}_{datetime.now().strftime('%H%M%S')}.txt" + paste_file.write_text(text, encoding="utf-8") + + placeholder = f"[Pasted text #{_paste_counter}: {line_count} lines \u2192 {paste_file}]" + return _ok(rid, {"placeholder": placeholder, "path": str(paste_file), "lines": line_count}) + + +# ── Methods: complete ───────────────────────────────────────────────── + +@method("complete.path") +def _(rid, params: dict) -> dict: + word = params.get("word", "") + if not word: + return _ok(rid, {"items": []}) + + items: list[dict] = [] + try: + is_context = word.startswith("@") + query = word[1:] if is_context else word + + if is_context and not query: + items = [ + {"text": "@diff", "display": "@diff", "meta": "git diff"}, + {"text": "@staged", "display": "@staged", "meta": "staged diff"}, + {"text": "@file:", "display": "@file:", "meta": "attach file"}, + {"text": "@folder:", "display": "@folder:", "meta": "attach folder"}, + {"text": "@url:", "display": "@url:", "meta": "fetch url"}, + {"text": "@git:", "display": "@git:", "meta": "git log"}, + ] + return _ok(rid, {"items": items}) + + if is_context and query.startswith(("file:", "folder:")): + prefix_tag = query.split(":", 1)[0] + path_part = query.split(":", 1)[1] or "." + else: + prefix_tag = "" + path_part = query if not is_context else query + + expanded = _normalize_completion_path(path_part) + if expanded.endswith("/"): + search_dir, match = expanded, "" + else: + search_dir = os.path.dirname(expanded) or "." + match = os.path.basename(expanded) + + if not os.path.isdir(search_dir): + return _ok(rid, {"items": []}) + + match_lower = match.lower() + for entry in sorted(os.listdir(search_dir)): + if match and not entry.lower().startswith(match_lower): + continue + if is_context and not prefix_tag and entry.startswith("."): + continue + full = os.path.join(search_dir, entry) + is_dir = os.path.isdir(full) + rel = os.path.relpath(full) + suffix = "/" if is_dir else "" + + if is_context and prefix_tag: + text = f"@{prefix_tag}:{rel}{suffix}" + elif is_context: + kind = "folder" if is_dir else "file" + text = f"@{kind}:{rel}{suffix}" + elif word.startswith("~"): + text = "~/" + os.path.relpath(full, os.path.expanduser("~")) + suffix + elif word.startswith("./"): + text = "./" + rel + suffix + else: + text = rel + suffix + + items.append({"text": text, "display": entry + suffix, "meta": "dir" if is_dir else ""}) + if len(items) >= 30: + break + except Exception as e: + return _err(rid, 5021, str(e)) + + return _ok(rid, {"items": items}) + + +@method("complete.slash") +def _(rid, params: dict) -> dict: + text = params.get("text", "") + if not text.startswith("/"): + return _ok(rid, {"items": []}) + + try: + from hermes_cli.commands import SlashCommandCompleter + from prompt_toolkit.document import Document + from prompt_toolkit.formatted_text import to_plain_text + + from agent.skill_commands import get_skill_commands + + completer = SlashCommandCompleter(skill_commands_provider=lambda: get_skill_commands()) + doc = Document(text, len(text)) + items = [ + {"text": c.text, "display": c.display or c.text, + "meta": to_plain_text(c.display_meta) if c.display_meta else ""} + for c in completer.get_completions(doc, None) + ][:30] + text_lower = text.lower() + extras = [ + {"text": "/compact", "display": "/compact", "meta": "Toggle compact display mode"}, + {"text": "/logs", "display": "/logs", "meta": "Show recent gateway log lines"}, + ] + for extra in extras: + if extra["text"].startswith(text_lower) and not any(item["text"] == extra["text"] for item in items): + items.append(extra) + return _ok(rid, {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1}) + except Exception as e: + return _err(rid, 5020, str(e)) + + +@method("model.options") +def _(rid, params: dict) -> dict: + try: + from hermes_cli.model_switch import list_authenticated_providers + from hermes_cli.models import provider_model_ids + + session = _sessions.get(params.get("session_id", "")) + agent = session.get("agent") if session else None + cfg = _load_cfg() + current_provider = getattr(agent, "provider", "") or "" + current_model = getattr(agent, "model", "") or _resolve_model() + providers = list_authenticated_providers( + current_provider=current_provider, + user_providers=cfg.get("providers") if isinstance(cfg.get("providers"), dict) else {}, + custom_providers=cfg.get("custom_providers") if isinstance(cfg.get("custom_providers"), list) else [], + max_models=50, + ) + for provider in providers: + try: + models = provider_model_ids(provider.get("slug")) + if models: + provider["models"] = models + provider["total_models"] = len(models) + except Exception as e: + provider["warning"] = f"model catalog unavailable: {e}" + return _ok(rid, {"providers": providers, "model": current_model, "provider": current_provider}) + except Exception as e: + return _err(rid, 5033, str(e)) + + +# ── Methods: slash.exec ────────────────────────────────────────────── + + +def _mirror_slash_side_effects(sid: str, session: dict, command: str) -> str: + """Apply side effects that must also hit the gateway's live agent.""" + parts = command.lstrip("/").split(None, 1) + if not parts: + return "" + name, arg, agent = parts[0], (parts[1].strip() if len(parts) > 1 else ""), session.get("agent") + + try: + if name == "model" and arg and agent: + result = _apply_model_switch(sid, session, arg) + return result.get("warning", "") + elif name == "personality" and arg and agent: + _, new_prompt = _validate_personality(arg, _load_cfg()) + _apply_personality_to_session(sid, session, new_prompt) + elif name == "prompt" and agent: + cfg = _load_cfg() + new_prompt = cfg.get("agent", {}).get("system_prompt", "") or "" + agent.ephemeral_system_prompt = new_prompt or None + agent._cached_system_prompt = None + elif name == "compress" and agent: + with session["history_lock"]: + _compress_session_history(session, arg) + _emit("session.info", sid, _session_info(agent)) + elif name == "fast" and agent: + mode = arg.lower() + if mode in {"fast", "on"}: + agent.service_tier = "priority" + elif mode in {"normal", "off"}: + agent.service_tier = None + _emit("session.info", sid, _session_info(agent)) + elif name == "reload-mcp" and agent and hasattr(agent, "reload_mcp_tools"): + agent.reload_mcp_tools() + elif name == "stop": + from tools.process_registry import process_registry + process_registry.kill_all() + except Exception as e: + return f"live session sync failed: {e}" + return "" + + +@method("slash.exec") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + + cmd = params.get("command", "").strip() + if not cmd: + return _err(rid, 4004, "empty command") + + worker = session.get("slash_worker") + if not worker: + try: + worker = _SlashWorker(session["session_key"], getattr(session.get("agent"), "model", _resolve_model())) + session["slash_worker"] = worker + except Exception as e: + return _err(rid, 5030, f"slash worker start failed: {e}") + + try: + output = worker.run(cmd) + warning = _mirror_slash_side_effects(params.get("session_id", ""), session, cmd) + payload = {"output": output or "(no output)"} + if warning: + payload["warning"] = warning + return _ok(rid, payload) + except Exception as e: + try: + worker.close() + except Exception: + pass + session["slash_worker"] = None + return _err(rid, 5030, str(e)) + + +# ── Methods: voice ─────────────────────────────────────────────────── + +@method("voice.toggle") +def _(rid, params: dict) -> dict: + action = params.get("action", "status") + if action == "status": + env = os.environ.get("HERMES_VOICE", "").strip() + if env in {"0", "1"}: + return _ok(rid, {"enabled": env == "1"}) + return _ok(rid, {"enabled": bool(_load_cfg().get("display", {}).get("voice_enabled", False))}) + if action in ("on", "off"): + enabled = action == "on" + os.environ["HERMES_VOICE"] = "1" if enabled else "0" + _write_config_key("display.voice_enabled", enabled) + return _ok(rid, {"enabled": action == "on"}) + return _err(rid, 4013, f"unknown voice action: {action}") + + +@method("voice.record") +def _(rid, params: dict) -> dict: + action = params.get("action", "start") + try: + if action == "start": + from hermes_cli.voice import start_recording + start_recording() + return _ok(rid, {"status": "recording"}) + if action == "stop": + from hermes_cli.voice import stop_and_transcribe + return _ok(rid, {"text": stop_and_transcribe() or ""}) + return _err(rid, 4019, f"unknown voice action: {action}") + except ImportError: + return _err(rid, 5025, "voice module not available — install audio dependencies") + except Exception as e: + return _err(rid, 5025, str(e)) + + +@method("voice.tts") +def _(rid, params: dict) -> dict: + text = params.get("text", "") + if not text: + return _err(rid, 4020, "text required") + try: + from hermes_cli.voice import speak_text + threading.Thread(target=speak_text, args=(text,), daemon=True).start() + return _ok(rid, {"status": "speaking"}) + except ImportError: + return _err(rid, 5026, "voice module not available") + except Exception as e: + return _err(rid, 5026, str(e)) + + +# ── Methods: insights ──────────────────────────────────────────────── + +@method("insights.get") +def _(rid, params: dict) -> dict: + days = params.get("days", 30) + try: + import time + cutoff = time.time() - days * 86400 + rows = [s for s in _get_db().list_sessions_rich(limit=500) if (s.get("started_at") or 0) >= cutoff] + return _ok(rid, {"days": days, "sessions": len(rows), "messages": sum(s.get("message_count", 0) for s in rows)}) + except Exception as e: + return _err(rid, 5017, str(e)) + + +# ── Methods: rollback ──────────────────────────────────────────────── + +@method("rollback.list") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + try: + def go(mgr, cwd): + if not mgr.enabled: + return _ok(rid, {"enabled": False, "checkpoints": []}) + return _ok(rid, {"enabled": True, "checkpoints": [ + {"hash": c.get("hash", ""), "timestamp": c.get("timestamp", ""), "message": c.get("message", "")} + for c in mgr.list_checkpoints(cwd)]}) + return _with_checkpoints(session, go) + except Exception as e: + return _err(rid, 5020, str(e)) + + +@method("rollback.restore") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + target = params.get("hash", "") + file_path = params.get("file_path", "") + if not target: + return _err(rid, 4014, "hash required") + try: + def go(mgr, cwd): + resolved = _resolve_checkpoint_hash(mgr, cwd, target) + result = mgr.restore(cwd, resolved, file_path=file_path or None) + if result.get("success") and not file_path: + removed = 0 + with session["history_lock"]: + history = session.get("history", []) + while history and history[-1].get("role") in ("assistant", "tool"): + history.pop() + removed += 1 + if history and history[-1].get("role") == "user": + history.pop() + removed += 1 + if removed: + session["history_version"] = int(session.get("history_version", 0)) + 1 + result["history_removed"] = removed + return result + + return _ok(rid, _with_checkpoints(session, go)) + except Exception as e: + return _err(rid, 5021, str(e)) + + +@method("rollback.diff") +def _(rid, params: dict) -> dict: + session, err = _sess(params, rid) + if err: + return err + target = params.get("hash", "") + if not target: + return _err(rid, 4014, "hash required") + try: + r = _with_checkpoints(session, lambda mgr, cwd: mgr.diff(cwd, _resolve_checkpoint_hash(mgr, cwd, target))) + raw = r.get("diff", "")[:4000] + payload = {"stat": r.get("stat", ""), "diff": raw} + rendered = render_diff(raw, session.get("cols", 80)) + if rendered: + payload["rendered"] = rendered + return _ok(rid, payload) + except Exception as e: + return _err(rid, 5022, str(e)) + + +# ── Methods: browser / plugins / cron / skills ─────────────────────── + +@method("browser.manage") +def _(rid, params: dict) -> dict: + action = params.get("action", "status") + if action == "status": + url = os.environ.get("BROWSER_CDP_URL", "") + return _ok(rid, {"connected": bool(url), "url": url}) + if action == "connect": + url = params.get("url", "http://localhost:9222") + try: + import urllib.request + from urllib.parse import urlparse + from tools.browser_tool import cleanup_all_browsers + + parsed = urlparse(url if "://" in url else f"http://{url}") + if parsed.scheme not in {"http", "https", "ws", "wss"}: + return _err(rid, 4015, f"unsupported browser url: {url}") + probe_root = ( + f"{'https' if parsed.scheme == 'wss' else 'http' if parsed.scheme == 'ws' else parsed.scheme}://{parsed.netloc}" + ) + probe_urls = [f"{probe_root.rstrip('/')}/json/version", f"{probe_root.rstrip('/')}/json"] + ok = False + for probe in probe_urls: + try: + with urllib.request.urlopen(probe, timeout=2.0) as resp: + if 200 <= getattr(resp, "status", 200) < 300: + ok = True + break + except Exception: + continue + if not ok: + return _err(rid, 5031, f"could not reach browser CDP at {url}") + + os.environ["BROWSER_CDP_URL"] = url + cleanup_all_browsers() + except Exception as e: + return _err(rid, 5031, str(e)) + return _ok(rid, {"connected": True, "url": url}) + if action == "disconnect": + os.environ.pop("BROWSER_CDP_URL", None) + try: + from tools.browser_tool import cleanup_all_browsers + cleanup_all_browsers() + except Exception: + pass + return _ok(rid, {"connected": False}) + return _err(rid, 4015, f"unknown action: {action}") + + +@method("plugins.list") +def _(rid, params: dict) -> dict: + try: + from hermes_cli.plugins import get_plugin_manager + return _ok(rid, {"plugins": [ + {"name": n, "version": getattr(i, "version", "?"), "enabled": getattr(i, "enabled", True)} + for n, i in get_plugin_manager()._plugins.items()]}) + except Exception as e: + return _err(rid, 5032, str(e)) + + +@method("config.show") +def _(rid, params: dict) -> dict: + try: + cfg = _load_cfg() + model = _resolve_model() + api_key = os.environ.get("HERMES_API_KEY", "") or cfg.get("api_key", "") + masked = f"****{api_key[-4:]}" if len(api_key) > 4 else "(not set)" + base_url = os.environ.get("HERMES_BASE_URL", "") or cfg.get("base_url", "") + + sections = [{ + "title": "Model", + "rows": [ + ["Model", model], + ["Base URL", base_url or "(default)"], + ["API Key", masked], + ] + }, { + "title": "Agent", + "rows": [ + ["Max Turns", str(cfg.get("max_turns", 25))], + ["Toolsets", ", ".join(cfg.get("enabled_toolsets", [])) or "all"], + ["Verbose", str(cfg.get("verbose", False))], + ] + }, { + "title": "Environment", + "rows": [ + ["Working Dir", os.getcwd()], + ["Config File", str(_hermes_home / "config.yaml")], + ] + }] + return _ok(rid, {"sections": sections}) + except Exception as e: + return _err(rid, 5030, str(e)) + + +@method("tools.list") +def _(rid, params: dict) -> dict: + try: + from toolsets import get_all_toolsets, get_toolset_info + session = _sessions.get(params.get("session_id", "")) + enabled = set(getattr(session["agent"], "enabled_toolsets", []) or []) if session else set(_load_enabled_toolsets() or []) + + items = [] + for name in sorted(get_all_toolsets().keys()): + info = get_toolset_info(name) + if not info: + continue + items.append({ + "name": name, + "description": info["description"], + "tool_count": info["tool_count"], + "enabled": name in enabled if enabled else True, + "tools": info["resolved_tools"], + }) + return _ok(rid, {"toolsets": items}) + except Exception as e: + return _err(rid, 5031, str(e)) + + +@method("tools.show") +def _(rid, params: dict) -> dict: + try: + from model_tools import get_toolset_for_tool, get_tool_definitions + + session = _sessions.get(params.get("session_id", "")) + enabled = getattr(session["agent"], "enabled_toolsets", None) if session else _load_enabled_toolsets() + tools = get_tool_definitions(enabled_toolsets=enabled, quiet_mode=True) + sections = {} + + for tool in sorted(tools, key=lambda t: t["function"]["name"]): + name = tool["function"]["name"] + desc = str(tool["function"].get("description", "") or "").split("\n")[0] + if ". " in desc: + desc = desc[:desc.index(". ") + 1] + sections.setdefault(get_toolset_for_tool(name) or "unknown", []).append({ + "name": name, + "description": desc, + }) + + return _ok(rid, { + "sections": [{"name": name, "tools": rows} for name, rows in sorted(sections.items())], + "total": len(tools), + }) + except Exception as e: + return _err(rid, 5034, str(e)) + + +@method("tools.configure") +def _(rid, params: dict) -> dict: + action = str(params.get("action", "") or "").strip().lower() + targets = [str(name).strip() for name in params.get("names", []) or [] if str(name).strip()] + if action not in {"disable", "enable"}: + return _err(rid, 4017, f"unknown tools action: {action}") + if not targets: + return _err(rid, 4018, "names required") + + try: + from hermes_cli.config import load_config, save_config + from hermes_cli.tools_config import ( + CONFIGURABLE_TOOLSETS, + _apply_mcp_change, + _apply_toolset_change, + _get_platform_tools, + _get_plugin_toolset_keys, + ) + + cfg = load_config() + valid_toolsets = {ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS} | _get_plugin_toolset_keys() + toolset_targets = [name for name in targets if ":" not in name] + mcp_targets = [name for name in targets if ":" in name] + unknown = [name for name in toolset_targets if name not in valid_toolsets] + toolset_targets = [name for name in toolset_targets if name in valid_toolsets] + + if toolset_targets: + _apply_toolset_change(cfg, "cli", toolset_targets, action) + + missing_servers = _apply_mcp_change(cfg, mcp_targets, action) if mcp_targets else set() + save_config(cfg) + + session = _sessions.get(params.get("session_id", "")) + info = _reset_session_agent(params.get("session_id", ""), session) if session else None + enabled = sorted(_get_platform_tools(load_config(), "cli", include_default_mcp_servers=False)) + changed = [ + name for name in targets + if name not in unknown and (":" not in name or name.split(":", 1)[0] not in missing_servers) + ] + + return _ok(rid, { + "changed": changed, + "enabled_toolsets": enabled, + "info": info, + "missing_servers": sorted(missing_servers), + "reset": bool(session), + "unknown": unknown, + }) + except Exception as e: + return _err(rid, 5035, str(e)) + + +@method("toolsets.list") +def _(rid, params: dict) -> dict: + try: + from toolsets import get_all_toolsets, get_toolset_info + session = _sessions.get(params.get("session_id", "")) + enabled = set(getattr(session["agent"], "enabled_toolsets", []) or []) if session else set(_load_enabled_toolsets() or []) + + items = [] + for name in sorted(get_all_toolsets().keys()): + info = get_toolset_info(name) + if not info: + continue + items.append({ + "name": name, + "description": info["description"], + "tool_count": info["tool_count"], + "enabled": name in enabled if enabled else True, + }) + return _ok(rid, {"toolsets": items}) + except Exception as e: + return _err(rid, 5032, str(e)) + + +@method("agents.list") +def _(rid, params: dict) -> dict: + try: + from tools.process_registry import process_registry + procs = process_registry.list_sessions() + return _ok(rid, { + "processes": [{ + "session_id": p["session_id"], + "command": p["command"][:80], + "status": p["status"], + "uptime": p["uptime_seconds"], + } for p in procs] + }) + except Exception as e: + return _err(rid, 5033, str(e)) + + +@method("cron.manage") +def _(rid, params: dict) -> dict: + action, jid = params.get("action", "list"), params.get("name", "") + try: + from tools.cronjob_tools import cronjob + if action == "list": + return _ok(rid, json.loads(cronjob(action="list"))) + if action == "add": + return _ok(rid, json.loads(cronjob(action="create", name=jid, + schedule=params.get("schedule", ""), prompt=params.get("prompt", "")))) + if action in ("remove", "pause", "resume"): + return _ok(rid, json.loads(cronjob(action=action, job_id=jid))) + return _err(rid, 4016, f"unknown cron action: {action}") + except Exception as e: + return _err(rid, 5023, str(e)) + + +@method("skills.manage") +def _(rid, params: dict) -> dict: + action, query = params.get("action", "list"), params.get("query", "") + try: + if action == "list": + from hermes_cli.banner import get_available_skills + return _ok(rid, {"skills": get_available_skills()}) + if action == "search": + from hermes_cli.skills_hub import unified_search, GitHubAuth, create_source_router + raw = unified_search(query, create_source_router(GitHubAuth()), source_filter="all", limit=20) or [] + return _ok(rid, {"results": [{"name": r.name, "description": r.description} for r in raw]}) + if action == "install": + from hermes_cli.skills_hub import do_install + class _Q: + def print(self, *a, **k): pass + do_install(query, skip_confirm=True, console=_Q()) + return _ok(rid, {"installed": True, "name": query}) + if action == "browse": + from hermes_cli.skills_hub import browse_skills + pg = int(params.get("page", 0) or 0) or (int(query) if query.isdigit() else 1) + return _ok(rid, browse_skills(page=pg, page_size=int(params.get("page_size", 20)))) + if action == "inspect": + from hermes_cli.skills_hub import inspect_skill + return _ok(rid, {"info": inspect_skill(query) or {}}) + return _err(rid, 4017, f"unknown skills action: {action}") + except Exception as e: + return _err(rid, 5024, str(e)) + + +# ── Methods: shell ─────────────────────────────────────────────────── + +@method("shell.exec") +def _(rid, params: dict) -> dict: + cmd = params.get("command", "") + if not cmd: + return _err(rid, 4004, "empty command") + try: + from tools.approval import detect_dangerous_command + is_dangerous, _, desc = detect_dangerous_command(cmd) + if is_dangerous: + return _err(rid, 4005, f"blocked: {desc}. Use the agent for dangerous commands.") + except ImportError: + pass + try: + r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30, cwd=os.getcwd()) + return _ok(rid, {"stdout": r.stdout[-4000:], "stderr": r.stderr[-2000:], "code": r.returncode}) + except subprocess.TimeoutExpired: + return _err(rid, 5002, "command timed out (30s)") + except Exception as e: + return _err(rid, 5003, str(e)) diff --git a/tui_gateway/slash_worker.py b/tui_gateway/slash_worker.py new file mode 100644 index 0000000000..631b0c7045 --- /dev/null +++ b/tui_gateway/slash_worker.py @@ -0,0 +1,76 @@ +"""Persistent slash-command worker — one HermesCLI per TUI session. + +Protocol: reads JSON lines from stdin {id, command}, writes {id, ok, output|error} to stdout. +""" + +import argparse +import contextlib +import io +import json +import os +import sys + +import cli as cli_mod +from cli import HermesCLI +from rich.console import Console + + +def _run(cli: HermesCLI, command: str) -> str: + cmd = (command or "").strip() + if not cmd: + return "" + if not cmd.startswith("/"): + cmd = f"/{cmd}" + + buf = io.StringIO() + + # Rich Console captures its file handle at construction time, so + # contextlib.redirect_stdout won't affect it. Swap the console's + # underlying file to our buffer so self.console.print() is captured. + cli.console = Console(file=buf, force_terminal=True, width=120) + + old = getattr(cli_mod, "_cprint", None) + if old is not None: + cli_mod._cprint = lambda text: print(text) + + try: + with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): + cli.process_command(cmd) + finally: + if old is not None: + cli_mod._cprint = old + + return buf.getvalue().rstrip() + + +def main(): + p = argparse.ArgumentParser(add_help=False) + p.add_argument("--session-key", required=True) + p.add_argument("--model", default="") + args = p.parse_args() + + os.environ["HERMES_SESSION_KEY"] = args.session_key + os.environ["HERMES_INTERACTIVE"] = "1" + + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + cli = HermesCLI(model=args.model or None, compact=True, resume=args.session_key, verbose=False) + + for raw in sys.stdin: + line = raw.strip() + if not line: + continue + + rid = None + try: + req = json.loads(line) + rid = req.get("id") + out = _run(cli, req.get("command", "")) + sys.stdout.write(json.dumps({"id": rid, "ok": True, "output": out}) + "\n") + sys.stdout.flush() + except Exception as e: + sys.stdout.write(json.dumps({"id": rid, "ok": False, "error": str(e)}) + "\n") + sys.stdout.flush() + + +if __name__ == "__main__": + main() diff --git a/ui-tui/.gitignore b/ui-tui/.gitignore new file mode 100644 index 0000000000..c5323f8723 --- /dev/null +++ b/ui-tui/.gitignore @@ -0,0 +1,4 @@ +dist/ +node_modules/ +src/*.js +docs/ \ No newline at end of file diff --git a/ui-tui/.prettierrc b/ui-tui/.prettierrc new file mode 100644 index 0000000000..12ec3ed7db --- /dev/null +++ b/ui-tui/.prettierrc @@ -0,0 +1,11 @@ +{ + "arrowParens": "avoid", + "bracketSpacing": true, + "endOfLine": "auto", + "printWidth": 120, + "semi": false, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none", + "useTabs": false +} diff --git a/ui-tui/README.md b/ui-tui/README.md new file mode 100644 index 0000000000..38d206baf4 --- /dev/null +++ b/ui-tui/README.md @@ -0,0 +1,347 @@ +# Hermes TUI + +React + Ink terminal UI for Hermes. TypeScript owns the screen. Python owns sessions, tools, model calls, and most command logic. + +```bash +hermes --tui +``` + +## What runs + +The client entrypoint is `src/entry.tsx`. It exits early if `stdin` is not a TTY, starts `GatewayClient`, then renders `App`. + +`GatewayClient` spawns: + +```text +python -m tui_gateway.entry +``` + +Interpreter resolution order is: `HERMES_PYTHON` → `PYTHON` → `$VIRTUAL_ENV/bin/python` → `./.venv/bin/python` → `./venv/bin/python` → `python3` (or `python` on Windows). + +The transport is newline-delimited JSON-RPC over stdio: + +```text +ui-tui/src tui_gateway/ +----------- ------------- +entry.tsx entry.py + -> GatewayClient -> request loop + -> App -> server.py RPC handlers + +stdin/stdout: JSON-RPC requests, responses, events +stderr: captured into an in-memory log ring +``` + +Malformed stdout lines are treated as protocol noise and surfaced as `gateway.protocol_error`. Stderr lines become `gateway.stderr`. Neither writes directly into the terminal. + +## Running it + +From the repo root, the normal path is: + +```bash +hermes --tui +``` + +The CLI expects `ui-tui/node_modules` to exist. If the TUI deps are missing: + +```bash +cd ui-tui +npm install +``` + +Local package commands: + +```bash +npm run dev +npm start +npm run build +npm run lint +npm run fmt +npm run fix +``` + +Tests use vitest: + +```bash +npm test # single run +npm run test:watch +``` + +## App model + +`src/app.tsx` is the center of the UI. Heavy logic is split into `src/app/`: + +- `createGatewayEventHandler.ts` — maps gateway events to state updates +- `createSlashHandler.ts` — local slash command dispatch +- `useComposerState.ts` — draft, multiline buffer, queue editing +- `useInputHandlers.ts` — keypress routing +- `useTurnState.ts` — agent turn lifecycle +- `overlayStore.ts` / `uiStore.ts` — nanostores for overlay and UI state +- `gatewayContext.tsx` — React context for the gateway client +- `constants.ts`, `helpers.ts`, `interfaces.ts` + +The top-level `app.tsx` composes these into the Ink tree with `Static` transcript output, a live streaming assistant row, prompt overlays, queue preview, status rule, input line, and completion list. + +State managed at the top level includes: + +- transcript and streaming state +- queued messages and input history +- session lifecycle +- tool progress and reasoning text +- prompt flows for approval, clarify, sudo, and secret input +- slash command routing +- tab completion and path completion +- theme state from gateway skin data + +The UI renders as a normal Ink tree with `Static` transcript output, a live streaming assistant row, prompt overlays, queue preview, status rule, input line, and completion list. + +The intro panel is driven by `session.info` and rendered through `branding.tsx`. + +## Hotkeys and interactions + +Current input behavior is split across `app.tsx`, `components/textInput.tsx`, and the prompt/picker components. + +### Main chat input + +| Key | Behavior | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Enter` | Submit the current draft | +| empty `Enter` twice | If queued messages exist and the agent is busy, interrupt the current run. If queued messages exist and the agent is idle, send the next queued message | +| `Shift+Enter` / `Alt+Enter` | Insert a newline in the current draft | +| `\` + `Enter` | Append the line to the multiline buffer (fallback for terminals without modifier support) | +| `Ctrl+C` | Interrupt active run, or clear the current draft, or exit if nothing is pending | +| `Ctrl+D` | Exit | +| `Ctrl+G` | Open `$EDITOR` with the current draft | +| `Ctrl+L` | New session (same as `/clear`) | +| `Ctrl+V` / `Alt+V` | Paste clipboard image (same as `/paste`) | +| `Tab` | Apply the active completion | +| `Up/Down` | Cycle completions if the completion list is open; otherwise edit queued messages first, then walk input history | +| `Left/Right` | Move the cursor | +| modified `Left/Right` | Move by word when the terminal sends `Ctrl` or `Meta` with the arrow key | +| `Home` / `Ctrl+A` | Start of line | +| `End` / `Ctrl+E` | End of line | +| `Backspace` | Delete the character to the left of the cursor | +| `Delete` | Delete the character to the right of the cursor | +| modified `Backspace` | Delete the previous word | +| modified `Delete` | Delete the next word | +| `Ctrl+W` | Delete the previous word | +| `Ctrl+U` | Delete from the cursor back to the start of the line | +| `Ctrl+K` | Delete from the cursor to the end of the line | +| `Meta+B` / `Meta+F` | Move by word | +| `!cmd` | Run a shell command through the gateway | +| `{!cmd}` | Inline shell interpolation before send; queued drafts keep the raw text until they are sent | + +Notes: + +- `Tab` only applies completions when completions are present and you are not in multiline mode. +- Queue/history navigation only applies when you are not in multiline mode. +- `PgUp` / `PgDn` are left to the terminal emulator; the TUI does not handle them. + +### Prompt and picker modes + +| Context | Keys | Behavior | +| --------------------------- | ------------------- | ------------------------------------------------- | +| approval prompt | `Up/Down`, `Enter` | Move and confirm the selected approval choice | +| approval prompt | `o`, `s`, `a`, `d` | Quick-pick `once`, `session`, `always`, `deny` | +| approval prompt | `Esc`, `Ctrl+C` | Deny | +| clarify prompt with choices | `Up/Down`, `Enter` | Move and confirm the selected choice | +| clarify prompt with choices | single-digit number | Quick-pick the matching numbered choice | +| clarify prompt with choices | `Enter` on "Other" | Switch into free-text entry | +| clarify free-text mode | `Enter` | Submit typed answer | +| sudo / secret prompt | `Enter` | Submit typed value | +| sudo / secret prompt | `Ctrl+C` | Cancel by sending an empty response | +| resume picker | `Up/Down`, `Enter` | Move and resume the selected session | +| resume picker | `1-9` | Quick-pick one of the first nine visible sessions | +| resume picker | `Esc`, `Ctrl+C` | Close the picker | + +Notes: + +- Clarify free-text mode and masked prompts use `ink-text-input`, so text editing there follows the library's default bindings rather than `components/textInput.tsx`. +- When a blocking prompt is open, the main chat input hotkeys are suspended. +- Clarify mode has no dedicated cancel shortcut in the current client. Sudo and secret prompts only expose `Ctrl+C` cancellation from the app-level blocked handler. + +### Interaction rules + +- Plain text entered while the agent is busy is queued instead of sent immediately. +- Slash commands and `!cmd` do not queue; they execute immediately even while a run is active. +- Queue auto-drains after each assistant response, unless a queued item is currently being edited. +- `Up/Down` prioritizes queued-message editing over history. History only activates when there is no queue to edit. +- Queued drafts keep their original `!cmd` and `{!cmd}` text while you edit them. Shell commands and interpolation run when the queued item is actually sent. +- If you load a queued item into the input and resubmit plain text, that queue item is replaced, removed from the queue preview, and promoted to send next. If the agent is still busy, the edited item is moved to the front of the queue and sent after the current run completes. +- Completion requests are debounced by 60 ms. Input starting with `/` uses `complete.slash`. A trailing token that starts with `./`, `../`, `~/`, `/`, or `@` uses `complete.path`. +- Text pastes are inserted inline directly into the draft. Nothing is newline-flattened. +- `Ctrl+G` writes the current draft, including any multiline buffer, to a temp file, temporarily swaps screen buffers, launches `$EDITOR`, then restores the TUI and submits the saved text if the editor exits cleanly. +- Input history is stored in `~/.hermes/.hermes_history` or under `HERMES_HOME`. + +## Rendering + +Assistant output is rendered in one of two ways: + +- if the payload already contains ANSI, `messageLine.tsx` prints it directly +- otherwise `components/markdown.tsx` renders a small Markdown subset into Ink components + +The Markdown renderer handles headings, lists, block quotes, tables, fenced code blocks, diff coloring, inline code, emphasis, links, and plain URLs. + +Tool/status activity is shown in a live activity lane. Transcript rows stay focused on user/assistant turns. + +## Prompt flows + +The Python gateway can pause the main loop and request structured input: + +- `approval.request`: allow once, allow for session, allow always, or deny +- `clarify.request`: pick from choices or type a custom answer +- `sudo.request`: masked password entry +- `secret.request`: masked value entry for a named env var +- `session.list`: used by `SessionPicker` for `/resume` + +These are stateful UI branches in `app.tsx`, not separate screens. + +## Commands + +The local slash handler covers the built-ins that need direct client behavior: + +- `/help` +- `/quit`, `/exit`, `/q` +- `/clear` +- `/new` +- `/compact` +- `/resume` +- `/copy` +- `/paste` +- `/details` +- `/logs` +- `/statusbar`, `/sb` +- `/queue` +- `/undo` +- `/retry` + +Notes: + +- `/copy` sends the selected assistant response through OSC 52. +- `/paste` with no args asks the gateway for clipboard image attachment state. +- `/paste` does not manage text paste entries; text paste is inline-only. +- `/details [hidden|collapsed|expanded|cycle]` controls thinking/tool-detail visibility. +- `/statusbar` toggles the status rule on/off. + +Anything else falls through to: + +1. `slash.exec` +2. `command.dispatch` + +That lets Python own aliases, plugins, skills, and registry-backed commands without duplicating the logic in the TUI. + +## Event surface + +Primary event types the client handles today: + +| Event | Payload | +| ------------------------ | ----------------------------------------------- | +| `gateway.ready` | `{ skin? }` | +| `session.info` | session metadata for banner + tool/skill panels | +| `message.start` | start assistant streaming | +| `message.delta` | `{ text, rendered? }` | +| `message.complete` | `{ text, rendered?, usage, status }` | +| `thinking.delta` | `{ text }` | +| `reasoning.delta` | `{ text }` | +| `reasoning.available` | `{ text }` | +| `status.update` | `{ kind, text }` | +| `tool.start` | `{ tool_id, name, context? }` | +| `tool.progress` | `{ name, preview }` | +| `tool.complete` | `{ tool_id, name }` | +| `clarify.request` | `{ question, choices?, request_id }` | +| `approval.request` | `{ command, description }` | +| `sudo.request` | `{ request_id }` | +| `secret.request` | `{ prompt, env_var, request_id }` | +| `background.complete` | `{ task_id, text }` | +| `btw.complete` | `{ text }` | +| `error` | `{ message }` | +| `gateway.stderr` | synthesized from child stderr | +| `gateway.protocol_error` | synthesized from malformed stdout | + +## Theme model + +The client starts with `DEFAULT_THEME` from `theme.ts`, then merges in gateway skin data from `gateway.ready`. + +Current branding overrides: + +- agent name +- prompt symbol +- welcome text +- goodbye text + +Current color overrides: + +- banner title, accent, border, body, dim +- label, ok, error, warn + +`branding.tsx` uses those values for the logo, session panel, and update notice. + +## File map + +```text +ui-tui/ + packages/hermes-ink/ forked Ink renderer (local dep) + src/ + entry.tsx TTY gate + render() + app.tsx top-level Ink tree, composes src/app/* + gatewayClient.ts child process + JSON-RPC bridge + theme.ts default palette + skin merge + constants.ts display constants, hotkeys, tool labels + types.ts shared client-side types + banner.ts ASCII art data + + app/ + createGatewayEventHandler.ts event → state mapping + createSlashHandler.ts local slash dispatch + useComposerState.ts draft + multiline + queue editing + useInputHandlers.ts keypress routing + useTurnState.ts agent turn lifecycle + overlayStore.ts nanostores for overlays + uiStore.ts nanostores for UI flags + gatewayContext.tsx React context for gateway client + constants.ts app-level constants + helpers.ts pure helpers + interfaces.ts internal interfaces + + components/ + appChrome.tsx status bar, input row, completions + appLayout.tsx top-level layout composition + appOverlays.tsx overlay routing (pickers, prompts) + branding.tsx banner + session summary + markdown.tsx Markdown-to-Ink renderer + maskedPrompt.tsx masked input for sudo / secrets + messageLine.tsx transcript rows + modelPicker.tsx model switch picker + prompts.tsx approval + clarify flows + queuedMessages.tsx queued input preview + sessionPicker.tsx session resume picker + textInput.tsx custom line editor + thinking.tsx spinner, reasoning, tool activity + + hooks/ + useCompletion.ts tab completion (slash + path) + useInputHistory.ts persistent history navigation + useQueue.ts queued message management + useVirtualHistory.ts in-memory history for pickers + + lib/ + history.ts persistent input history + messages.ts message formatting helpers + osc52.ts OSC 52 clipboard copy + rpc.ts JSON-RPC type helpers + text.ts text helpers, ANSI detection, previews + + types/ + hermes-ink.d.ts type declarations for @hermes/ink + + __tests__/ vitest suite +``` + +Related Python side: + +```text +tui_gateway/ + entry.py stdio entrypoint + server.py RPC handlers and session logic + render.py optional rich/ANSI bridge + slash_worker.py persistent HermesCLI subprocess for slash commands +``` diff --git a/ui-tui/eslint.config.mjs b/ui-tui/eslint.config.mjs new file mode 100644 index 0000000000..1b20c3244f --- /dev/null +++ b/ui-tui/eslint.config.mjs @@ -0,0 +1,107 @@ +import js from '@eslint/js' +import typescriptEslint from '@typescript-eslint/eslint-plugin' +import typescriptParser from '@typescript-eslint/parser' +import perfectionist from 'eslint-plugin-perfectionist' +import reactPlugin from 'eslint-plugin-react' +import hooksPlugin from 'eslint-plugin-react-hooks' +import unusedImports from 'eslint-plugin-unused-imports' +import globals from 'globals' + +const noopRule = { + meta: { schema: [], type: 'problem' }, + create: () => ({}) +} + +const customRules = { + rules: { + 'no-process-cwd': noopRule, + 'no-process-env-top-level': noopRule, + 'no-sync-fs': noopRule, + 'no-top-level-dynamic-import': noopRule, + 'no-top-level-side-effects': noopRule + } +} + +export default [ + { + ignores: ['**/node_modules/**', '**/dist/**', 'src/**/*.js'] + }, + js.configs.recommended, + { + files: ['**/*.{ts,tsx}'], + languageOptions: { + globals: { ...globals.node }, + parser: typescriptParser, + parserOptions: { + ecmaFeatures: { jsx: true }, + ecmaVersion: 'latest', + sourceType: 'module' + } + }, + plugins: { + '@typescript-eslint': typescriptEslint, + 'custom-rules': customRules, + perfectionist, + react: reactPlugin, + 'react-hooks': hooksPlugin, + 'unused-imports': unusedImports + }, + rules: { + 'no-fallthrough': ['error', { allowEmptyCase: true }], + curly: ['error', 'all'], + '@typescript-eslint/consistent-type-imports': ['error', { prefer: 'type-imports' }], + '@typescript-eslint/no-unused-vars': 'off', + 'no-undef': 'off', + 'no-unused-vars': 'off', + 'padding-line-between-statements': [ + 1, + { blankLine: 'always', next: ['block-like', 'block', 'return', 'if', 'class', 'continue', 'debugger', 'break', 'multiline-const', 'multiline-let'], prev: '*' }, + { blankLine: 'always', next: '*', prev: ['case', 'default', 'multiline-const', 'multiline-let', 'multiline-block-like'] }, + { blankLine: 'never', next: ['block', 'block-like'], prev: ['case', 'default'] }, + { blankLine: 'always', next: ['block', 'block-like'], prev: ['block', 'block-like'] }, + { blankLine: 'always', next: ['empty'], prev: 'export' }, + { blankLine: 'never', next: 'iife', prev: ['block', 'block-like', 'empty'] } + ], + 'perfectionist/sort-exports': ['error', { order: 'asc', type: 'natural' }], + 'perfectionist/sort-imports': [ + 'error', + { + groups: ['side-effect', 'builtin', 'external', 'internal', 'parent', 'sibling', 'index'], + order: 'asc', + type: 'natural' + } + ], + 'perfectionist/sort-jsx-props': ['error', { order: 'asc', type: 'natural' }], + 'perfectionist/sort-named-exports': ['error', { order: 'asc', type: 'natural' }], + 'perfectionist/sort-named-imports': ['error', { order: 'asc', type: 'natural' }], + 'react-hooks/exhaustive-deps': 'warn', + 'react-hooks/rules-of-hooks': 'error', + 'unused-imports/no-unused-imports': 'error' + }, + settings: { + react: { version: 'detect' } + } + }, + { + files: ['packages/hermes-ink/**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/consistent-type-imports': 'off', + 'no-constant-condition': 'off', + 'no-empty': 'off', + 'no-redeclare': 'off', + 'react-hooks/exhaustive-deps': 'off' + } + }, + { + files: ['**/*.js'], + ignores: ['**/node_modules/**', '**/dist/**'], + languageOptions: { + globals: { ...globals.node }, + ecmaVersion: 'latest', + sourceType: 'module' + } + }, + { + ignores: ['*.config.*'] + } +] diff --git a/ui-tui/package-lock.json b/ui-tui/package-lock.json new file mode 100644 index 0000000000..0b33e6e334 --- /dev/null +++ b/ui-tui/package-lock.json @@ -0,0 +1,7246 @@ +{ + "name": "hermes-tui", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "hermes-tui", + "version": "0.0.1", + "dependencies": { + "@hermes/ink": "file:./packages/hermes-ink", + "@nanostores/react": "^1.1.0", + "ink": "^6.8.0", + "ink-text-input": "^6.0.0", + "react": "^19.2.4", + "unicode-animations": "^1.0.3" + }, + "devDependencies": { + "@eslint/js": "^9", + "@types/node": "^25.5.0", + "@types/react": "^19.2.14", + "@typescript-eslint/eslint-plugin": "^8", + "@typescript-eslint/parser": "^8", + "eslint": "^9", + "eslint-plugin-perfectionist": "^5", + "eslint-plugin-react": "^7", + "eslint-plugin-react-hooks": "^7", + "eslint-plugin-unused-imports": "^4", + "globals": "^16", + "prettier": "^3", + "tsx": "^4.19.0", + "typescript": "^5.7.0", + "vitest": "^4.1.3" + } + }, + "node_modules/@alcalzone/ansi-tokenize": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.5.tgz", + "integrity": "sha512-3NX/MpTdroi0aKz134A6RC2Gb2iXVECN4QaAXnvCIxxIm3C3AVB1mkUe8NaaiyvOpDfsrqWhYtj+Q6a62RrTsw==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/core/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.28.6", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", + "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.2", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.2.tgz", + "integrity": "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.0" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/template": { + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.2.tgz", + "integrity": "sha512-UC+ZhH3XtczQYfOlu3lNEkdW/p4dsJ1r/bP7H8+rhao3TTTMO1ATq/4DdIi23XuGoFY+Cz0JmCbdVl0hz9jZcA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz", + "integrity": "sha512-3U4+MIWHImeyu1wnmVygh5WlgfYDtyf0k8AbLhMFxOipihf6nrWC4syIm/SwEeec0mNSafiiNnMJwbza/Is6Lw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.5.tgz", + "integrity": "sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/eslintrc/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.4.tgz", + "integrity": "sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@hermes/ink": { + "resolved": "packages/hermes-ink", + "link": true + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nanostores/react": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@nanostores/react/-/react-1.1.0.tgz", + "integrity": "sha512-MbH35fjhcf7LAubYX5vhOChYUfTLzNLqH/mBGLVsHkcvjy0F8crO1WQwdmQ2xKbAmtpalDa2zBt3Hlg5kqr8iw==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "engines": { + "node": "^20.0.0 || >=22.0.0" + }, + "peerDependencies": { + "nanostores": "^1.2.0", + "react": ">=18.0.0" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.3.tgz", + "integrity": "sha512-xK9sGVbJWYb08+mTJt3/YV24WxvxpXcXtP6B172paPZ+Ts69Re9dAr7lKwJoeIx8OoeuimEiRZ7umkiUVClmmQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.124.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.124.0.tgz", + "integrity": "sha512-VBFWMTBvHxS11Z5Lvlr3IWgrwhMTXV+Md+EQF0Xf60+wAdsGFTBx7X7K/hP4pi8N7dcm1RvcHwDxZ16Qx8keUg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.15.tgz", + "integrity": "sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.0-rc.15.tgz", + "integrity": "sha512-oArR/ig8wNTPYsXL+Mzhs0oxhxfuHRfG7Ikw7jXsw8mYOtk71W0OkF2VEVh699pdmzjPQsTjlD1JIOoHkLP1Fg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.0-rc.15.tgz", + "integrity": "sha512-YzeVqOqjPYvUbJSWJ4EDL8ahbmsIXQpgL3JVipmN+MX0XnXMeWomLN3Fb+nwCmP/jfyqte5I3XRSm7OfQrbyxw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.0-rc.15.tgz", + "integrity": "sha512-9Erhx956jeQ0nNTyif1+QWAXDRD38ZNjr//bSHrt6wDwB+QkAfl2q6Mn1k6OBPerznjRmbM10lgRb1Pli4xZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.0-rc.15.tgz", + "integrity": "sha512-cVwk0w8QbZJGTnP/AHQBs5yNwmpgGYStL88t4UIaqcvYJWBfS0s3oqVLZPwsPU6M0zlW4GqjP0Zq5MnAGwFeGA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-eBZ/u8iAK9SoHGanqe/jrPnY0JvBN6iXbVOsbO38mbz+ZJsaobExAm1Iu+rxa4S1l2FjG0qEZn4Rc6X8n+9M+w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.0-rc.15.tgz", + "integrity": "sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.0-rc.15.tgz", + "integrity": "sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.0-rc.15.tgz", + "integrity": "sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.0-rc.15.tgz", + "integrity": "sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.0-rc.15.tgz", + "integrity": "sha512-ApLruZq/ig+nhaE7OJm4lDjayUnOHVUa77zGeqnqZ9pn0ovdVbbNPerVibLXDmWeUZXjIYIT8V3xkT58Rm9u5Q==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.9.2", + "@emnapi/runtime": "1.9.2", + "@napi-rs/wasm-runtime": "^1.1.3" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.0-rc.15.tgz", + "integrity": "sha512-KmoUoU7HnN+Si5YWJigfTws1jz1bKBYDQKdbLspz0UaqjjFkddHsqorgiW1mxcAj88lYUE6NC/zJNwT+SloqtA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.0-rc.15.tgz", + "integrity": "sha512-3P2A8L+x75qavWLe/Dll3EYBJLQmtkJN8rfh+U/eR3MqMgL/h98PhYI+JFfXuDPgPeCB7iZAKiqii5vqOvnA0g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.15.tgz", + "integrity": "sha512-UromN0peaE53IaBRe9W7CjrZgXl90fqGpK+mIZbA3qSTeYqg3pqpROBdIPvOG3F5ereDHNwoHBI2e50n1BDr1g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "25.6.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz", + "integrity": "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.19.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.14", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz", + "integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.58.1.tgz", + "integrity": "sha512-eSkwoemjo76bdXl2MYqtxg51HNwUSkWfODUOQ3PaTLZGh9uIWWFZIjyjaJnex7wXDu+TRx+ATsnSxdN9YWfRTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.58.1", + "@typescript-eslint/type-utils": "8.58.1", + "@typescript-eslint/utils": "8.58.1", + "@typescript-eslint/visitor-keys": "8.58.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.58.1", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.58.1.tgz", + "integrity": "sha512-gGkiNMPqerb2cJSVcruigx9eHBlLG14fSdPdqMoOcBfh+vvn4iCq2C8MzUB89PrxOXk0y3GZ1yIWb9aOzL93bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.58.1", + "@typescript-eslint/types": "8.58.1", + "@typescript-eslint/typescript-estree": "8.58.1", + "@typescript-eslint/visitor-keys": "8.58.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.58.1.tgz", + "integrity": "sha512-gfQ8fk6cxhtptek+/8ZIqw8YrRW5048Gug8Ts5IYcMLCw18iUgrZAEY/D7s4hkI0FxEfGakKuPK/XUMPzPxi5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.58.1", + "@typescript-eslint/types": "^8.58.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.58.1.tgz", + "integrity": "sha512-TPYUEqJK6avLcEjumWsIuTpuYODTTDAtoMdt8ZZa93uWMTX13Nb8L5leSje1NluammvU+oI3QRr5lLXPgihX3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.1", + "@typescript-eslint/visitor-keys": "8.58.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.58.1.tgz", + "integrity": "sha512-JAr2hOIct2Q+qk3G+8YFfqkqi7sC86uNryT+2i5HzMa2MPjw4qNFvtjnw1IiA1rP7QhNKVe21mSSLaSjwA1Olw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.58.1.tgz", + "integrity": "sha512-HUFxvTJVroT+0rXVJC7eD5zol6ID+Sn5npVPWoFuHGg9Ncq5Q4EYstqR+UOqaNRFXi5TYkpXXkLhoCHe3G0+7w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.1", + "@typescript-eslint/typescript-estree": "8.58.1", + "@typescript-eslint/utils": "8.58.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.58.1.tgz", + "integrity": "sha512-io/dV5Aw5ezwzfPBBWLoT+5QfVtP8O7q4Kftjn5azJ88bYyp/ZMCsyW1lpKK46EXJcaYMZ1JtYj+s/7TdzmQMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.58.1.tgz", + "integrity": "sha512-w4w7WR7GHOjqqPnvAYbazq+Y5oS68b9CzasGtnd6jIeOIeKUzYzupGTB2T4LTPSv4d+WPeccbxuneTFHYgAAWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.58.1", + "@typescript-eslint/tsconfig-utils": "8.58.1", + "@typescript-eslint/types": "8.58.1", + "@typescript-eslint/visitor-keys": "8.58.1", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.58.1.tgz", + "integrity": "sha512-Ln8R0tmWC7pTtLOzgJzYTXSCjJ9rDNHAqTaVONF4FEi2qwce8mD9iSOxOpLFFvWp/wBFlew0mjM1L1ihYWfBdQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.58.1", + "@typescript-eslint/types": "8.58.1", + "@typescript-eslint/typescript-estree": "8.58.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.58.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.58.1.tgz", + "integrity": "sha512-y+vH7QE8ycjoa0bWciFg7OpFcipUuem1ujhrdLtq1gByKwfbC7bPeKsiny9e0urg93DqwGcHey+bGRKCnF1nZQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.58.1", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.4.tgz", + "integrity": "sha512-iPBpra+VDuXmBFI3FMKHSFXp3Gx5HfmSCE8X67Dn+bwephCnQCaB7qWK2ldHa+8ncN8hJU8VTMcxjPpyMkUjww==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.4", + "@vitest/utils": "4.1.4", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.4.tgz", + "integrity": "sha512-R9HTZBhW6yCSGbGQnDnH3QHfJxokKN4KB+Yvk9Q1le7eQNYwiCyKxmLmurSpFy6BzJanSLuEUDrD+j97Q+ZLPg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.4", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.4.tgz", + "integrity": "sha512-ddmDHU0gjEUyEVLxtZa7xamrpIefdEETu3nZjWtHeZX4QxqJ7tRxSteHVXJOcr8jhiLoGAhkK4WJ3WqBpjx42A==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.4.tgz", + "integrity": "sha512-xTp7VZ5aXP5ZJrn15UtJUWlx6qXLnGtF6jNxHepdPHpMfz/aVPx+htHtgcAL2mDXJgKhpoo2e9/hVJsIeFbytQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.4", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.4.tgz", + "integrity": "sha512-MCjCFgaS8aZz+m5nTcEcgk/xhWv0rEH4Yl53PPlMXOZ1/Ka2VcZU6CJ+MgYCZbcJvzGhQRjVrGQNZqkGPttIKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.4", + "@vitest/utils": "4.1.4", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.4.tgz", + "integrity": "sha512-XxNdAsKW7C+FLydqFJLb5KhJtl3PGCMmYwFRfhvIgxJvLSXhhVI1zM8f1qD3Zg7RCjTSzDVyct6sghs9UEgBEQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.4.tgz", + "integrity": "sha512-13QMT+eysM5uVGa1rG4kegGYNp6cnQcsTc67ELFbhNLQO+vgsygtYJx2khvdt4gVQqSSpC/KT5FZZxUpP3Oatw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.4", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/acorn": { + "version": "8.16.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", + "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.14.0.tgz", + "integrity": "sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz", + "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.0", + "es-object-atoms": "^1.1.1", + "get-intrinsic": "^1.3.0", + "is-string": "^1.1.1", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlast": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz", + "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz", + "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", + "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.tosorted": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz", + "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3", + "es-errors": "^1.3.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/auto-bind": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz", + "integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.17", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.17.tgz", + "integrity": "sha512-HdrkN8eVG2CXxeifv/VdJ4A4RSra1DTW8dc/hdxzhGHN8QePs6gKaWM9pHPcpCoxYZJuOZ8drHmbdpLHjCYjLA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", + "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/browserslist": { + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001787", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001787.tgz", + "integrity": "sha512-mNcrMN9KeI68u7muanUpEejSLghOKlVhRqS/Za2IeyGllJ9I9otGpR9g3nsw7n4W378TE/LyIteA0+/FOZm4Kg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cli-boxes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz", + "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.2.0.tgz", + "integrity": "sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw==", + "license": "MIT", + "dependencies": { + "slice-ansi": "^8.0.0", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/code-excerpt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz", + "integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==", + "license": "MIT", + "dependencies": { + "convert-to-spaces": "^2.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-to-spaces": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz", + "integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.334", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.334.tgz", + "integrity": "sha512-mgjZAz7Jyx1SRCwEpy9wefDS7GvNPazLthHg8eQMJ76wBdGQQDW33TCrUTvQ4wzpmOrv2zrFoD3oNufMdyMpog==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-abstract": { + "version": "1.24.2", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz", + "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-iterator-helpers": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.3.2.tgz", + "integrity": "sha512-HVLACW1TppGYjJ8H6/jqH/pqOtKRw6wMlrB23xfExmFWxFquAIWCmwoLsOyN96K4a5KbmOf5At9ZUO3GZbetAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-errors": "^1.3.0", + "es-set-tostringtag": "^2.1.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.3.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "iterator.prototype": "^1.1.5", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-module-lexer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", + "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz", + "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7", + "is-date-object": "^1.0.5", + "is-symbol": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-toolkit": { + "version": "1.45.1", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.45.1.tgz", + "integrity": "sha512-/jhoOj/Fx+A+IIyDNOvO3TItGmlMKhtX8ISAHKE90c4b/k1tqaqEZ+uUqfpU8DMnW5cgNJv606zS55jGvza0Xw==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.4", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.4.tgz", + "integrity": "sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.5", + "@eslint/js": "9.39.4", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-perfectionist": { + "version": "5.8.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-perfectionist/-/eslint-plugin-perfectionist-5.8.0.tgz", + "integrity": "sha512-k8uIptWIxkUclonCFGyDzgYs9NI+Qh0a7cUXS3L7IYZDEsjXuimFBVbxXPQQngWqMiaxJRwbtYB4smMGMqF+cw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/utils": "^8.58.0", + "natural-orderby": "^5.0.0" + }, + "engines": { + "node": "^20.0.0 || >=22.0.0" + }, + "peerDependencies": { + "eslint": "^8.45.0 || ^9.0.0 || ^10.0.0" + } + }, + "node_modules/eslint-plugin-react": { + "version": "7.37.5", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz", + "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.8", + "array.prototype.findlast": "^1.2.5", + "array.prototype.flatmap": "^1.3.3", + "array.prototype.tosorted": "^1.1.4", + "doctrine": "^2.1.0", + "es-iterator-helpers": "^1.2.1", + "estraverse": "^5.3.0", + "hasown": "^2.0.2", + "jsx-ast-utils": "^2.4.1 || ^3.0.0", + "minimatch": "^3.1.2", + "object.entries": "^1.1.9", + "object.fromentries": "^2.0.8", + "object.values": "^1.2.1", + "prop-types": "^15.8.1", + "resolve": "^2.0.0-next.5", + "semver": "^6.3.1", + "string.prototype.matchall": "^4.0.12", + "string.prototype.repeat": "^1.0.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz", + "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint-plugin-react/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint-plugin-react/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/eslint-plugin-react/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/eslint-plugin-unused-imports": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-unused-imports/-/eslint-plugin-unused-imports-4.4.1.tgz", + "integrity": "sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@typescript-eslint/eslint-plugin": "^8.0.0-0 || ^7.0.0 || ^6.0.0 || ^5.0.0", + "eslint": "^10.0.0 || ^9.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/eslint-plugin": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "dev": true, + "license": "ISC" + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz", + "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz", + "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.7", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.7.tgz", + "integrity": "sha512-7tN6rFgBlMgpBML5j8typ92BKFi2sFQvIdpAqLA2beia5avZDrMs0FLZiM5etShWq5irVyGcGMEA1jcDaK7A/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/indent-string": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", + "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/ink/-/ink-6.8.0.tgz", + "integrity": "sha512-sbl1RdLOgkO9isK42WCZlJCFN9hb++sX9dsklOvfd1YQ3bQ2AiFu12Q6tFlr0HvEUvzraJntQCCpfEoUe9DSzA==", + "license": "MIT", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.2.4", + "ansi-escapes": "^7.3.0", + "ansi-styles": "^6.2.1", + "auto-bind": "^5.0.1", + "chalk": "^5.6.0", + "cli-boxes": "^3.0.0", + "cli-cursor": "^4.0.0", + "cli-truncate": "^5.1.1", + "code-excerpt": "^4.0.0", + "es-toolkit": "^1.39.10", + "indent-string": "^5.0.0", + "is-in-ci": "^2.0.0", + "patch-console": "^2.0.0", + "react-reconciler": "^0.33.0", + "scheduler": "^0.27.0", + "signal-exit": "^3.0.7", + "slice-ansi": "^8.0.0", + "stack-utils": "^2.0.6", + "string-width": "^8.1.1", + "terminal-size": "^4.0.1", + "type-fest": "^5.4.1", + "widest-line": "^6.0.0", + "wrap-ansi": "^9.0.0", + "ws": "^8.18.0", + "yoga-layout": "~3.2.1" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@types/react": ">=19.0.0", + "react": ">=19.0.0", + "react-devtools-core": ">=6.1.2" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-devtools-core": { + "optional": true + } + } + }, + "node_modules/ink-text-input": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ink-text-input/-/ink-text-input-6.0.0.tgz", + "integrity": "sha512-Fw64n7Yha5deb1rHY137zHTAbSTNelUKuB5Kkk2HACXEtwIHBCf9OH2tP/LQ9fRYTl1F0dZgbW0zPnZk6FA9Lw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "type-fest": "^4.18.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "ink": ">=5", + "react": ">=18" + } + }, + "node_modules/ink-text-input/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink-text-input/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ink/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-in-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-2.0.0.tgz", + "integrity": "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w==", + "license": "MIT", + "bin": { + "is-in-ci": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/iterator.prototype": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz", + "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "get-proto": "^1.0.0", + "has-symbols": "^1.1.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsx-ast-utils": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", + "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.6", + "array.prototype.flat": "^1.3.1", + "object.assign": "^4.1.4", + "object.values": "^1.1.6" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/nanostores": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/nanostores/-/nanostores-1.2.0.tgz", + "integrity": "sha512-F0wCzbsH80G7XXo0Jd9/AVQC7ouWY6idUCTnMwW5t/Rv9W8qmO6endavDwg7TNp5GbugwSukFMVZqzPSrSMndg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "engines": { + "node": "^20.0.0 || >=22.0.0" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/natural-orderby": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/natural-orderby/-/natural-orderby-5.0.0.tgz", + "integrity": "sha512-kKHJhxwpR/Okycz4HhQKKlhWe4ASEfPgkSWNmKFHd7+ezuQlxkA5cM3+XkBPvm1gmHen3w53qsYAv+8GwRrBlg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/node-exports-info": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/node-exports-info/-/node-exports-info-1.6.0.tgz", + "integrity": "sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "array.prototype.flatmap": "^1.3.3", + "es-errors": "^1.3.0", + "object.entries": "^1.1.9", + "semver": "^6.3.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/node-exports-info/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/node-releases": { + "version": "2.0.37", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz", + "integrity": "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==", + "dev": true, + "license": "MIT" + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz", + "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.values": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz", + "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/own-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz", + "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/patch-console": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz", + "integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.5.9", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.9.tgz", + "integrity": "sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prettier": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.2.tgz", + "integrity": "sha512-8c3mgTe0ASwWAJK+78dpviD+A8EqhndQPUBpNUIPt6+xWlIigCwfN01lWr9MAede4uqXGTEKeQWTvzb3vjia0Q==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.2.5", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz", + "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/react-reconciler": { + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz", + "integrity": "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^19.2.0" + } + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "2.0.0-next.6", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.6.tgz", + "integrity": "sha512-3JmVl5hMGtJ3kMmB3zi3DL25KfkCEyy3Tw7Gmw7z5w8M9WlwoPFnIvwChzu1+cF3iaK3sp18hhPz8ANeimdJfA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.16.1", + "node-exports-info": "^1.6.0", + "object-keys": "^1.1.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/rolldown": { + "version": "1.0.0-rc.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.15.tgz", + "integrity": "sha512-Ff31guA5zT6WjnGp0SXw76X6hzGRk/OQq2hE+1lcDe+lJdHSgnSX6nK3erbONHyCbpSj9a9E+uX/OvytZoWp2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.124.0", + "@rolldown/pluginutils": "1.0.0-rc.15" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.0-rc.15", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.15", + "@rolldown/binding-darwin-x64": "1.0.0-rc.15", + "@rolldown/binding-freebsd-x64": "1.0.0-rc.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.15", + "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.15", + "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.15", + "@rolldown/binding-linux-x64-musl": "1.0.0-rc.15", + "@rolldown/binding-openharmony-arm64": "1.0.0-rc.15", + "@rolldown/binding-wasm32-wasi": "1.0.0-rc.15", + "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.15", + "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.15" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz", + "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/slice-ansi": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-8.0.0.tgz", + "integrity": "sha512-stxByr12oeeOyY2BlviTNQlYV5xOj47GirPr4yA1hE9JCtxfQN0+tVbkxwCtYDQWhEKWFHsEK48ORg5jrouCAg==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "is-fullwidth-code-point": "^5.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.0.0.tgz", + "integrity": "sha512-zUMPtQ/HBY3/50VbpkupYHbRroTRZJPRLvreamgErJVys0ceuzMkD44J/QjqhHjOzK42GQ3QZIeFG1OYfOtKqQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/string-width": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.0.tgz", + "integrity": "sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/string.prototype.matchall": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz", + "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.6", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "regexp.prototype.flags": "^1.5.3", + "set-function-name": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.repeat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz", + "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", + "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz", + "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-hyperlinks": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.2.0.tgz", + "integrity": "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0", + "supports-color": "^7.0.0" + }, + "engines": { + "node": ">=14.18" + }, + "funding": { + "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/terminal-size": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/terminal-size/-/terminal-size-4.0.1.tgz", + "integrity": "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.1.1.tgz", + "integrity": "sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.16", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz", + "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", + "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/tsx": { + "version": "4.21.0", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz", + "integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "~0.27.0", + "get-tsconfig": "^4.7.5" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/type-fest": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.5.0.tgz", + "integrity": "sha512-PlBfpQwiUvGViBNX84Yxwjsdhd1TUlXr6zjX7eoirtCPIr08NAmxwa+fcYBTeRQxHo9YC9wwF3m9i700sHma8g==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", + "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz", + "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0", + "reflect.getprototypeof": "^1.0.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici-types": { + "version": "7.19.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz", + "integrity": "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==", + "dev": true, + "license": "MIT" + }, + "node_modules/unicode-animations": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/unicode-animations/-/unicode-animations-1.0.3.tgz", + "integrity": "sha512-+klB2oWwcYZjYWhwP4Pr8UZffWDFVx6jKeIahE6z0QYyM2dwDeDPyn5nevCYbyotxvtT9lh21cVURO1RX0+YMg==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "unicode-animations": "^1.0.1" + }, + "bin": { + "unicode-animations": "scripts/demo.cjs" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/usehooks-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/usehooks-ts/-/usehooks-ts-3.1.1.tgz", + "integrity": "sha512-I4diPp9Cq6ieSUH2wu+fDAVQO43xwtulo+fKEidHUwZPnYImbtkTjzIJYcDcJqxgmX31GVqNFURodvcgHcW0pA==", + "license": "MIT", + "dependencies": { + "lodash.debounce": "^4.0.8" + }, + "engines": { + "node": ">=16.15.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17 || ^18 || ^19 || ^19.0.0-rc" + } + }, + "node_modules/vite": { + "version": "8.0.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.8.tgz", + "integrity": "sha512-dbU7/iLVa8KZALJyLOBOQ88nOXtNG8vxKuOT4I2mD+Ya70KPceF4IAmDsmU0h1Qsn5bPrvsY9HJstCRh3hG6Uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.8", + "rolldown": "1.0.0-rc.15", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.1.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.4.tgz", + "integrity": "sha512-tFuJqTxKb8AvfyqMfnavXdzfy3h3sWZRWwfluGbkeR7n0HUev+FmNgZ8SDrRBTVrVCjgH5cA21qGbCffMNtWvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.4", + "@vitest/mocker": "4.1.4", + "@vitest/pretty-format": "4.1.4", + "@vitest/runner": "4.1.4", + "@vitest/snapshot": "4.1.4", + "@vitest/spy": "4.1.4", + "@vitest/utils": "4.1.4", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.4", + "@vitest/browser-preview": "4.1.4", + "@vitest/browser-webdriverio": "4.1.4", + "@vitest/coverage-istanbul": "4.1.4", + "@vitest/coverage-v8": "4.1.4", + "@vitest/ui": "4.1.4", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.20", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.20.tgz", + "integrity": "sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/widest-line": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-6.0.0.tgz", + "integrity": "sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA==", + "license": "MIT", + "dependencies": { + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ws": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoga-layout": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", + "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", + "license": "MIT" + }, + "node_modules/zod": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", + "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + }, + "packages/hermes-ink": { + "name": "@hermes/ink", + "version": "0.0.1", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.1.0", + "auto-bind": "^5.0.0", + "bidi-js": "^1.0.0", + "chalk": "^5.4.0", + "cli-boxes": "^3.0.0", + "code-excerpt": "^4.0.0", + "emoji-regex": "^10.4.0", + "get-east-asian-width": "^1.3.0", + "indent-string": "^5.0.0", + "lodash-es": "^4.17.0", + "react": ">=19.0.0", + "react-reconciler": "0.33.0", + "semver": "^7.6.0", + "signal-exit": "^4.1.0", + "stack-utils": "^2.0.0", + "strip-ansi": "^7.1.0", + "supports-hyperlinks": "^3.1.0", + "type-fest": "^4.30.0", + "usehooks-ts": "^3.1.0", + "wrap-ansi": "^9.0.0" + }, + "devDependencies": { + "esbuild": "^0.25.0" + }, + "peerDependencies": { + "ink-text-input": ">=6.0.0", + "react": ">=19.0.0" + } + }, + "packages/hermes-ink/node_modules/@alcalzone/ansi-tokenize": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz", + "integrity": "sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=14.13.1" + } + }, + "packages/hermes-ink/node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "packages/hermes-ink/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "packages/hermes-ink/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "packages/hermes-ink/node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "packages/hermes-ink/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "packages/hermes-ink/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "packages/hermes-ink/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/ui-tui/package.json b/ui-tui/package.json new file mode 100644 index 0000000000..4776f0830d --- /dev/null +++ b/ui-tui/package.json @@ -0,0 +1,43 @@ +{ + "name": "hermes-tui", + "version": "0.0.1", + "private": true, + "type": "module", + "scripts": { + "dev": "npm run build --prefix packages/hermes-ink && tsx --watch src/entry.tsx", + "start": "tsx src/entry.tsx", + "build": "npm run build --prefix packages/hermes-ink && tsc -p tsconfig.build.json && chmod +x dist/entry.js", + "type-check": "tsc --noEmit -p tsconfig.json", + "lint": "eslint src/ packages/", + "lint:fix": "eslint src/ packages/ --fix", + "fmt": "prettier --write 'src/**/*.{ts,tsx}' 'packages/**/*.{ts,tsx}'", + "fix": "npm run lint:fix && npm run fmt", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@hermes/ink": "file:./packages/hermes-ink", + "@nanostores/react": "^1.1.0", + "ink": "^6.8.0", + "ink-text-input": "^6.0.0", + "react": "^19.2.4", + "unicode-animations": "^1.0.3" + }, + "devDependencies": { + "@eslint/js": "^9", + "@types/node": "^25.5.0", + "@types/react": "^19.2.14", + "@typescript-eslint/eslint-plugin": "^8", + "@typescript-eslint/parser": "^8", + "eslint": "^9", + "eslint-plugin-perfectionist": "^5", + "eslint-plugin-react": "^7", + "eslint-plugin-react-hooks": "^7", + "eslint-plugin-unused-imports": "^4", + "globals": "^16", + "prettier": "^3", + "tsx": "^4.19.0", + "typescript": "^5.7.0", + "vitest": "^4.1.3" + } +} diff --git a/ui-tui/packages/hermes-ink/ambient.d.ts b/ui-tui/packages/hermes-ink/ambient.d.ts new file mode 100644 index 0000000000..943ff76bc0 --- /dev/null +++ b/ui-tui/packages/hermes-ink/ambient.d.ts @@ -0,0 +1,83 @@ +/// + +declare module 'react/compiler-runtime' { + export function c(size: number): any[] +} + +declare module 'bidi-js' { + const bidiFactory: () => Record + export default bidiFactory +} + +declare module 'stack-utils' { + class StackUtils { + static nodeInternals(): RegExp[] + constructor(opts?: { cwd?: string; internals?: RegExp[] }) + clean(stack: string | undefined): string | undefined + parseLine(line: string): { file?: string; line?: number; column?: number; function?: string } | undefined + } + export default StackUtils +} + +declare module 'react-reconciler' { + export type FiberRoot = unknown + const createReconciler: any + export default createReconciler +} + +declare module 'react-reconciler/constants.js' { + export const ConcurrentRoot: number + export const LegacyRoot: number + export const DiscreteEventPriority: symbol | number + export const ContinuousEventPriority: symbol | number + export const DefaultEventPriority: symbol | number + export const NoEventPriority: symbol | number +} + +declare module 'lodash-es/noop.js' { + const noop: (...args: unknown[]) => void + export default noop +} + +declare module 'lodash-es/throttle.js' { + function throttle unknown>( + fn: T, + wait?: number, + opts?: { leading?: boolean; trailing?: boolean } + ): T & { cancel(): void; flush(): void } + export default throttle +} + +declare module 'semver' { + export function coerce(version: string | number | null | undefined): { version: string } | null + export function gt(a: string, b: string, opts?: { loose?: boolean }): boolean + export function gte(a: string, b: string, opts?: { loose?: boolean }): boolean + export function lt(a: string, b: string, opts?: { loose?: boolean }): boolean + export function lte(a: string, b: string, opts?: { loose?: boolean }): boolean + export function satisfies(version: string, range: string, opts?: { loose?: boolean }): boolean + export function compare(a: string, b: string, opts?: { loose?: boolean }): number +} + +interface BunSemver { + order(a: string, b: string): -1 | 0 | 1 + satisfies(version: string, range: string): boolean +} + +interface BunRuntime { + stringWidth(s: string, opts?: { ambiguousIsNarrow?: boolean }): number + semver: BunSemver + wrapAnsi?(input: string, columns: number, options?: { hard?: boolean; wordWrap?: boolean; trim?: boolean }): string +} + +declare var Bun: BunRuntime | undefined + +declare namespace React { + namespace JSX { + interface IntrinsicElements { + 'ink-box': Record + 'ink-text': Record + 'ink-link': Record + 'ink-raw-ansi': Record + } + } +} diff --git a/ui-tui/packages/hermes-ink/index.d.ts b/ui-tui/packages/hermes-ink/index.d.ts new file mode 100644 index 0000000000..6536bddb02 --- /dev/null +++ b/ui-tui/packages/hermes-ink/index.d.ts @@ -0,0 +1,35 @@ +/// +export { default as useStderr } from './src/hooks/use-stderr.ts' +export type { StderrHandle } from './src/hooks/use-stderr.ts' +export { default as useStdout } from './src/hooks/use-stdout.ts' +export type { StdoutHandle } from './src/hooks/use-stdout.ts' +export { Ansi } from './src/ink/Ansi.tsx' +export { AlternateScreen } from './src/ink/components/AlternateScreen.tsx' +export { default as Box } from './src/ink/components/Box.tsx' +export type { Props as BoxProps } from './src/ink/components/Box.tsx' +export { default as Link } from './src/ink/components/Link.tsx' +export { default as Newline } from './src/ink/components/Newline.tsx' +export { NoSelect } from './src/ink/components/NoSelect.tsx' +export { RawAnsi } from './src/ink/components/RawAnsi.tsx' +export { default as ScrollBox } from './src/ink/components/ScrollBox.tsx' +export type { ScrollBoxHandle, ScrollBoxProps } from './src/ink/components/ScrollBox.tsx' +export { default as Spacer } from './src/ink/components/Spacer.tsx' +export type { Props as StdinProps } from './src/ink/components/StdinContext.ts' +export { default as Text } from './src/ink/components/Text.tsx' +export type { Props as TextProps } from './src/ink/components/Text.tsx' +export type { Key } from './src/ink/events/input-event.ts' +export { default as useApp } from './src/ink/hooks/use-app.ts' +export { useDeclaredCursor } from './src/ink/hooks/use-declared-cursor.ts' +export { default as useInput } from './src/ink/hooks/use-input.ts' +export { useHasSelection, useSelection } from './src/ink/hooks/use-selection.ts' +export { default as useStdin } from './src/ink/hooks/use-stdin.ts' +export { useTabStatus } from './src/ink/hooks/use-tab-status.ts' +export { useTerminalFocus } from './src/ink/hooks/use-terminal-focus.ts' +export { useTerminalTitle } from './src/ink/hooks/use-terminal-title.ts' +export { useTerminalViewport } from './src/ink/hooks/use-terminal-viewport.ts' +export { default as measureElement } from './src/ink/measure-element.ts' +export { createRoot, default as render, renderSync } from './src/ink/root.ts' +export type { Instance, RenderOptions, Root } from './src/ink/root.ts' +export { stringWidth } from './src/ink/stringWidth.ts' +export { default as TextInput, UncontrolledTextInput } from 'ink-text-input' +export type { Props as TextInputProps } from 'ink-text-input' diff --git a/ui-tui/packages/hermes-ink/index.js b/ui-tui/packages/hermes-ink/index.js new file mode 100644 index 0000000000..758fef3073 --- /dev/null +++ b/ui-tui/packages/hermes-ink/index.js @@ -0,0 +1 @@ +export * from './dist/ink-bundle.js' diff --git a/ui-tui/packages/hermes-ink/package-lock.json b/ui-tui/packages/hermes-ink/package-lock.json new file mode 100644 index 0000000000..4fb5866d14 --- /dev/null +++ b/ui-tui/packages/hermes-ink/package-lock.json @@ -0,0 +1,819 @@ +{ + "name": "@hermes/ink", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@hermes/ink", + "version": "0.0.1", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.1.0", + "auto-bind": "^5.0.0", + "bidi-js": "^1.0.0", + "chalk": "^5.4.0", + "cli-boxes": "^3.0.0", + "code-excerpt": "^4.0.0", + "emoji-regex": "^10.4.0", + "get-east-asian-width": "^1.3.0", + "indent-string": "^5.0.0", + "lodash-es": "^4.17.0", + "react": ">=19.0.0", + "react-reconciler": "0.33.0", + "semver": "^7.6.0", + "signal-exit": "^4.1.0", + "stack-utils": "^2.0.0", + "strip-ansi": "^7.1.0", + "supports-hyperlinks": "^3.1.0", + "type-fest": "^4.30.0", + "usehooks-ts": "^3.1.0", + "wrap-ansi": "^9.0.0" + }, + "devDependencies": { + "typescript": "~5.7.0" + }, + "peerDependencies": { + "ink-text-input": ">=6.0.0", + "react": ">=19.0.0" + } + }, + "node_modules/@alcalzone/ansi-tokenize": { + "version": "0.1.3", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=14.13.1" + } + }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "license": "MIT", + "peer": true, + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/auto-bind": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz", + "integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/cli-boxes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz", + "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", + "license": "MIT", + "peer": true, + "dependencies": { + "restore-cursor": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-6.0.0.tgz", + "integrity": "sha512-3+YKIUFsohD9MIoOFPFBldjAlnfCmCDcqe6aYGFqlDTRKg80p4wg35L+j83QQ63iOlKRccEkbn8IuM++HsgEjA==", + "license": "MIT", + "peer": true, + "dependencies": { + "slice-ansi": "^9.0.0", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/code-excerpt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz", + "integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==", + "license": "MIT", + "dependencies": { + "convert-to-spaces": "^2.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/convert-to-spaces": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz", + "integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-toolkit": { + "version": "1.45.1", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.45.1.tgz", + "integrity": "sha512-/jhoOj/Fx+A+IIyDNOvO3TItGmlMKhtX8ISAHKE90c4b/k1tqaqEZ+uUqfpU8DMnW5cgNJv606zS55jGvza0Xw==", + "license": "MIT", + "peer": true, + "workspaces": [ + "docs", + "benchmarks" + ] + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz", + "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/indent-string": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", + "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/ink/-/ink-7.0.0.tgz", + "integrity": "sha512-fMie5/VwIYXofMyND0s+fOVhwVBBPYx+uuqJ6V6rUBGjui+2UYp+0fWtvhSeKT4z+X1uH98a4ge5Vj3aTlL6mg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.3.0", + "ansi-escapes": "^7.3.0", + "ansi-styles": "^6.2.3", + "auto-bind": "^5.0.1", + "chalk": "^5.6.2", + "cli-boxes": "^4.0.1", + "cli-cursor": "^4.0.0", + "cli-truncate": "^6.0.0", + "code-excerpt": "^4.0.0", + "es-toolkit": "^1.45.1", + "indent-string": "^5.0.0", + "is-in-ci": "^2.0.0", + "patch-console": "^2.0.0", + "react-reconciler": "^0.33.0", + "scheduler": "^0.27.0", + "signal-exit": "^3.0.7", + "slice-ansi": "^9.0.0", + "stack-utils": "^2.0.6", + "string-width": "^8.2.0", + "terminal-size": "^4.0.1", + "type-fest": "^5.5.0", + "widest-line": "^6.0.0", + "wrap-ansi": "^10.0.0", + "ws": "^8.20.0", + "yoga-layout": "~3.2.1" + }, + "engines": { + "node": ">=22" + }, + "peerDependencies": { + "@types/react": ">=19.2.0", + "react": ">=19.2.0", + "react-devtools-core": ">=6.1.2" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-devtools-core": { + "optional": true + } + } + }, + "node_modules/ink-text-input": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ink-text-input/-/ink-text-input-6.0.0.tgz", + "integrity": "sha512-Fw64n7Yha5deb1rHY137zHTAbSTNelUKuB5Kkk2HACXEtwIHBCf9OH2tP/LQ9fRYTl1F0dZgbW0zPnZk6FA9Lw==", + "license": "MIT", + "peer": true, + "dependencies": { + "chalk": "^5.3.0", + "type-fest": "^4.18.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "ink": ">=5", + "react": ">=18" + } + }, + "node_modules/ink/node_modules/@alcalzone/ansi-tokenize": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.3.0.tgz", + "integrity": "sha512-p+CMKJ93HFmLkjXKlXiVGlMQEuRb6H0MokBSwUsX+S6BRX8eV5naFZpQJFfJHjRZY0Hmnqy1/r6UWl3x+19zYA==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/ink/node_modules/cli-boxes": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-4.0.1.tgz", + "integrity": "sha512-5IOn+jcCEHEraYolBPs/sT4BxYCe2nHg374OPiItB1O96KZFseS2gthU4twyYzeDcFew4DaUM/xwc5BQf08JJw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18.20 <19 || >=20.10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC", + "peer": true + }, + "node_modules/ink/node_modules/type-fest": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.5.0.tgz", + "integrity": "sha512-PlBfpQwiUvGViBNX84Yxwjsdhd1TUlXr6zjX7eoirtCPIr08NAmxwa+fcYBTeRQxHo9YC9wwF3m9i700sHma8g==", + "license": "(MIT OR CC0-1.0)", + "peer": true, + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ink/node_modules/wrap-ansi": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-10.0.0.tgz", + "integrity": "sha512-SGcvg80f0wUy2/fXES19feHMz8E0JoXv2uNgHOu4Dgi2OrCy1lqwFYEJz1BLbDI0exjPMe/ZdzZ/YpGECBG/aQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.2.3", + "string-width": "^8.2.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-in-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-2.0.0.tgz", + "integrity": "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w==", + "license": "MIT", + "peer": true, + "bin": { + "is-in-ci": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash-es": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", + "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", + "license": "MIT" + }, + "node_modules/lodash.debounce": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz", + "integrity": "sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==", + "license": "MIT" + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "peer": true, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/patch-console": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz", + "integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==", + "license": "MIT", + "peer": true, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/react": { + "version": "19.2.5", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.5.tgz", + "integrity": "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-reconciler": { + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz", + "integrity": "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^19.2.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "license": "MIT", + "peer": true, + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC", + "peer": true + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slice-ansi": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-9.0.0.tgz", + "integrity": "sha512-SO/3iYL5S3W57LLEniscOGPZgOqZUPCx6d3dB+52B80yJ0XstzsC/eV8gnA4tM3MHDrKz+OCFSLNjswdSC+/bA==", + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-styles": "^6.2.3", + "is-fullwidth-code-point": "^5.1.0" + }, + "engines": { + "node": ">=22" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-width": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.0.tgz", + "integrity": "sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw==", + "license": "MIT", + "peer": true, + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-hyperlinks": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.2.0.tgz", + "integrity": "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0", + "supports-color": "^7.0.0" + }, + "engines": { + "node": ">=14.18" + }, + "funding": { + "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" + } + }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/terminal-size": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/terminal-size/-/terminal-size-4.0.1.tgz", + "integrity": "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/type-fest": { + "version": "4.41.0", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.7.3.tgz", + "integrity": "sha512-84MVSjMEHP+FQRPy3pX9sTVV/INIex71s9TL2Gm5FG/WG1SqXeKyZ0k7/blY/4FdOzI12CBy1vGc4og/eus0fw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/usehooks-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/usehooks-ts/-/usehooks-ts-3.1.1.tgz", + "integrity": "sha512-I4diPp9Cq6ieSUH2wu+fDAVQO43xwtulo+fKEidHUwZPnYImbtkTjzIJYcDcJqxgmX31GVqNFURodvcgHcW0pA==", + "license": "MIT", + "dependencies": { + "lodash.debounce": "^4.0.8" + }, + "engines": { + "node": ">=16.15.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17 || ^18 || ^19 || ^19.0.0-rc" + } + }, + "node_modules/widest-line": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-6.0.0.tgz", + "integrity": "sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA==", + "license": "MIT", + "peer": true, + "dependencies": { + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ws": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", + "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/yoga-layout": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", + "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", + "license": "MIT", + "peer": true + } + } +} diff --git a/ui-tui/packages/hermes-ink/package.json b/ui-tui/packages/hermes-ink/package.json new file mode 100644 index 0000000000..8e23491310 --- /dev/null +++ b/ui-tui/packages/hermes-ink/package.json @@ -0,0 +1,54 @@ +{ + "name": "@hermes/ink", + "version": "0.0.1", + "private": true, + "type": "module", + "scripts": { + "build": "esbuild src/entry-exports.ts --bundle --platform=node --format=esm --packages=external --outfile=dist/ink-bundle.js" + }, + "sideEffects": true, + "main": "./index.js", + "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.js", + "default": "./index.js" + }, + "./text-input": { + "types": "./text-input.d.ts", + "import": "./text-input.js", + "default": "./text-input.js" + }, + "./package.json": "./package.json" + }, + "peerDependencies": { + "ink-text-input": ">=6.0.0", + "react": ">=19.0.0" + }, + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.1.0", + "auto-bind": "^5.0.0", + "bidi-js": "^1.0.0", + "chalk": "^5.4.0", + "cli-boxes": "^3.0.0", + "code-excerpt": "^4.0.0", + "emoji-regex": "^10.4.0", + "get-east-asian-width": "^1.3.0", + "indent-string": "^5.0.0", + "lodash-es": "^4.17.0", + "react": ">=19.0.0", + "react-reconciler": "0.33.0", + "semver": "^7.6.0", + "signal-exit": "^4.1.0", + "stack-utils": "^2.0.0", + "strip-ansi": "^7.1.0", + "supports-hyperlinks": "^3.1.0", + "type-fest": "^4.30.0", + "usehooks-ts": "^3.1.0", + "wrap-ansi": "^9.0.0" + }, + "devDependencies": { + "esbuild": "^0.25.0" + } +} diff --git a/ui-tui/packages/hermes-ink/src/bootstrap/state.ts b/ui-tui/packages/hermes-ink/src/bootstrap/state.ts new file mode 100644 index 0000000000..dcbae499fc --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/bootstrap/state.ts @@ -0,0 +1,9 @@ +export function flushInteractionTime(): void {} + +export function updateLastInteractionTime(): void {} + +export function markScrollActivity(): void {} + +export function getIsInteractive(): boolean { + return !!process.stdin.isTTY && !!process.stdout.isTTY +} diff --git a/ui-tui/packages/hermes-ink/src/entry-exports.ts b/ui-tui/packages/hermes-ink/src/entry-exports.ts new file mode 100644 index 0000000000..6ef1fc5fbd --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/entry-exports.ts @@ -0,0 +1,26 @@ +export { default as useStderr } from './hooks/use-stderr.js' +export { default as useStdout } from './hooks/use-stdout.js' +export { Ansi } from './ink/Ansi.js' +export { AlternateScreen } from './ink/components/AlternateScreen.js' +export { default as Box } from './ink/components/Box.js' +export { default as Link } from './ink/components/Link.js' +export { default as Newline } from './ink/components/Newline.js' +export { NoSelect } from './ink/components/NoSelect.js' +export { RawAnsi } from './ink/components/RawAnsi.js' +export { default as ScrollBox } from './ink/components/ScrollBox.js' +export { default as Spacer } from './ink/components/Spacer.js' +export { default as Text } from './ink/components/Text.js' +export { default as useApp } from './ink/hooks/use-app.js' +export { useDeclaredCursor } from './ink/hooks/use-declared-cursor.js' +export { type RunExternalProcess, useExternalProcess, withInkSuspended } from './ink/hooks/use-external-process.js' +export { default as useInput } from './ink/hooks/use-input.js' +export { useHasSelection, useSelection } from './ink/hooks/use-selection.js' +export { default as useStdin } from './ink/hooks/use-stdin.js' +export { useTabStatus } from './ink/hooks/use-tab-status.js' +export { useTerminalFocus } from './ink/hooks/use-terminal-focus.js' +export { useTerminalTitle } from './ink/hooks/use-terminal-title.js' +export { useTerminalViewport } from './ink/hooks/use-terminal-viewport.js' +export { default as measureElement } from './ink/measure-element.js' +export { createRoot, default as render, renderSync } from './ink/root.js' +export { stringWidth } from './ink/stringWidth.js' +export { default as TextInput, UncontrolledTextInput } from 'ink-text-input' diff --git a/ui-tui/packages/hermes-ink/src/hooks/use-stderr.ts b/ui-tui/packages/hermes-ink/src/hooks/use-stderr.ts new file mode 100644 index 0000000000..0aa7e1f20a --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/hooks/use-stderr.ts @@ -0,0 +1,15 @@ +import { useMemo } from 'react' +export type StderrHandle = { + stderr: NodeJS.WriteStream + write: (data: string) => boolean +} + +export default function useStderr(): StderrHandle { + return useMemo( + () => ({ + stderr: process.stderr, + write: data => process.stderr.write(data) + }), + [] + ) +} diff --git a/ui-tui/packages/hermes-ink/src/hooks/use-stdout.ts b/ui-tui/packages/hermes-ink/src/hooks/use-stdout.ts new file mode 100644 index 0000000000..fde397af2b --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/hooks/use-stdout.ts @@ -0,0 +1,15 @@ +import { useMemo } from 'react' +export type StdoutHandle = { + stdout: NodeJS.WriteStream + write: (data: string) => boolean +} + +export default function useStdout(): StdoutHandle { + return useMemo( + () => ({ + stdout: process.stdout, + write: data => process.stdout.write(data) + }), + [] + ) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/Ansi.tsx b/ui-tui/packages/hermes-ink/src/ink/Ansi.tsx new file mode 100644 index 0000000000..de0d750c35 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/Ansi.tsx @@ -0,0 +1,435 @@ +import React, { type ReactNode } from 'react' +import { c as _c } from 'react/compiler-runtime' + +import Link from './components/Link.js' +import Text from './components/Text.js' +import type { Color } from './styles.js' +import { type NamedColor, Parser, type Color as TermioColor, type TextStyle } from './termio.js' +type Props = { + children?: ReactNode + /** When true, force all text to be rendered with dim styling */ + dimColor?: boolean +} +type SpanProps = { + color?: Color + backgroundColor?: Color + dim?: boolean + bold?: boolean + italic?: boolean + underline?: boolean + strikethrough?: boolean + inverse?: boolean + hyperlink?: string +} + +type Span = { + text: string + props: SpanProps +} + +/** + * Component that parses ANSI escape codes and renders them using Text components. + * + * Use this as an escape hatch when you have pre-formatted ANSI strings from + * external tools (like cli-highlight) that need to be rendered in Ink. + * + * Memoized to prevent re-renders when parent changes but children string is the same. + */ +export const Ansi = React.memo(function Ansi(t0: Props) { + const $ = _c(12) + + const { children, dimColor } = t0 + + if (typeof children !== 'string') { + let t1 + + if ($[0] !== children || $[1] !== dimColor) { + t1 = dimColor ? {String(children)} : {String(children)} + $[0] = children + $[1] = dimColor + $[2] = t1 + } else { + t1 = $[2] + } + + return t1 + } + + if (children === '') { + return null + } + + let t1 + let t2 + + if ($[3] !== children || $[4] !== dimColor) { + t2 = Symbol.for('react.early_return_sentinel') + + bb0: { + const spans = parseToSpans(children) + + if (spans.length === 0) { + t2 = null + + break bb0 + } + + if (spans.length === 1 && !hasAnyProps(spans[0].props)) { + t2 = dimColor ? {spans[0].text} : {spans[0].text} + + break bb0 + } + + let t3 + + if ($[7] !== dimColor) { + t3 = (span: Span, i: number) => { + const hyperlink = span.props.hyperlink + + if (dimColor) { + span.props.dim = true + } + + const hasTextProps = hasAnyTextProps(span.props) + + if (hyperlink) { + return hasTextProps ? ( + + + {span.text} + + + ) : ( + + {span.text} + + ) + } + + return hasTextProps ? ( + + {span.text} + + ) : ( + span.text + ) + } + + $[7] = dimColor + $[8] = t3 + } else { + t3 = $[8] + } + + t1 = spans.map(t3) + } + + $[3] = children + $[4] = dimColor + $[5] = t1 + $[6] = t2 + } else { + t1 = $[5] + t2 = $[6] + } + + if (t2 !== Symbol.for('react.early_return_sentinel')) { + return t2 + } + + const content = t1 + let t3 + + if ($[9] !== content || $[10] !== dimColor) { + t3 = dimColor ? {content} : {content} + $[9] = content + $[10] = dimColor + $[11] = t3 + } else { + t3 = $[11] + } + + return t3 +}) + +/** + * Parse an ANSI string into spans using the termio parser. + */ +function parseToSpans(input: string): Span[] { + const parser = new Parser() + const actions = parser.feed(input) + const spans: Span[] = [] + let currentHyperlink: string | undefined + + for (const action of actions) { + if (action.type === 'link') { + if (action.action.type === 'start') { + currentHyperlink = action.action.url + } else { + currentHyperlink = undefined + } + + continue + } + + if (action.type === 'text') { + const text = action.graphemes.map(g => g.value).join('') + + if (!text) { + continue + } + + const props = textStyleToSpanProps(action.style) + + if (currentHyperlink) { + props.hyperlink = currentHyperlink + } + + // Try to merge with previous span if props match + const lastSpan = spans[spans.length - 1] + + if (lastSpan && propsEqual(lastSpan.props, props)) { + lastSpan.text += text + } else { + spans.push({ + text, + props + }) + } + } + } + + return spans +} + +/** + * Convert termio's TextStyle to SpanProps. + */ +function textStyleToSpanProps(style: TextStyle): SpanProps { + const props: SpanProps = {} + + if (style.bold) { + props.bold = true + } + + if (style.dim) { + props.dim = true + } + + if (style.italic) { + props.italic = true + } + + if (style.underline !== 'none') { + props.underline = true + } + + if (style.strikethrough) { + props.strikethrough = true + } + + if (style.inverse) { + props.inverse = true + } + + const fgColor = colorToString(style.fg) + + if (fgColor) { + props.color = fgColor + } + + const bgColor = colorToString(style.bg) + + if (bgColor) { + props.backgroundColor = bgColor + } + + return props +} + +// Map termio named colors to the ansi: format +const NAMED_COLOR_MAP: Record = { + black: 'ansi:black', + red: 'ansi:red', + green: 'ansi:green', + yellow: 'ansi:yellow', + blue: 'ansi:blue', + magenta: 'ansi:magenta', + cyan: 'ansi:cyan', + white: 'ansi:white', + brightBlack: 'ansi:blackBright', + brightRed: 'ansi:redBright', + brightGreen: 'ansi:greenBright', + brightYellow: 'ansi:yellowBright', + brightBlue: 'ansi:blueBright', + brightMagenta: 'ansi:magentaBright', + brightCyan: 'ansi:cyanBright', + brightWhite: 'ansi:whiteBright' +} + +/** + * Convert termio's Color to the string format used by Ink. + */ +function colorToString(color: TermioColor): Color | undefined { + switch (color.type) { + case 'named': + return NAMED_COLOR_MAP[color.name] as Color + + case 'indexed': + return `ansi256(${color.index})` as Color + + case 'rgb': + return `rgb(${color.r},${color.g},${color.b})` as Color + + case 'default': + return undefined + } +} + +/** + * Check if two SpanProps are equal for merging. + */ +function propsEqual(a: SpanProps, b: SpanProps): boolean { + return ( + a.color === b.color && + a.backgroundColor === b.backgroundColor && + a.bold === b.bold && + a.dim === b.dim && + a.italic === b.italic && + a.underline === b.underline && + a.strikethrough === b.strikethrough && + a.inverse === b.inverse && + a.hyperlink === b.hyperlink + ) +} + +function hasAnyProps(props: SpanProps): boolean { + return ( + props.color !== undefined || + props.backgroundColor !== undefined || + props.dim === true || + props.bold === true || + props.italic === true || + props.underline === true || + props.strikethrough === true || + props.inverse === true || + props.hyperlink !== undefined + ) +} + +function hasAnyTextProps(props: SpanProps): boolean { + return ( + props.color !== undefined || + props.backgroundColor !== undefined || + props.dim === true || + props.bold === true || + props.italic === true || + props.underline === true || + props.strikethrough === true || + props.inverse === true + ) +} + +// Text style props without weight (bold/dim) - these are handled separately +type BaseTextStyleProps = { + color?: Color + backgroundColor?: Color + italic?: boolean + underline?: boolean + strikethrough?: boolean + inverse?: boolean +} + +// Wrapper component that handles bold/dim mutual exclusivity for Text +function StyledText(t0: BaseTextStyleProps & { bold?: boolean; dim?: boolean; children?: ReactNode }) { + const $ = _c(14) + let bold + let children + let dim + let rest + + if ($[0] !== t0) { + ;({ bold, dim, children, ...rest } = t0) + $[0] = t0 + $[1] = bold + $[2] = children + $[3] = dim + $[4] = rest + } else { + bold = $[1] + children = $[2] + dim = $[3] + rest = $[4] + } + + if (dim) { + let t1 + + if ($[5] !== children || $[6] !== rest) { + t1 = ( + + {children} + + ) + $[5] = children + $[6] = rest + $[7] = t1 + } else { + t1 = $[7] + } + + return t1 + } + + if (bold) { + let t1 + + if ($[8] !== children || $[9] !== rest) { + t1 = ( + + {children} + + ) + $[8] = children + $[9] = rest + $[10] = t1 + } else { + t1 = $[10] + } + + return t1 + } + + let t1 + + if ($[11] !== children || $[12] !== rest) { + t1 = {children} + $[11] = children + $[12] = rest + $[13] = t1 + } else { + t1 = $[13] + } + + return t1 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIkxpbmsiLCJUZXh0IiwiQ29sb3IiLCJOYW1lZENvbG9yIiwiUGFyc2VyIiwiVGVybWlvQ29sb3IiLCJUZXh0U3R5bGUiLCJQcm9wcyIsImNoaWxkcmVuIiwiZGltQ29sb3IiLCJTcGFuUHJvcHMiLCJjb2xvciIsImJhY2tncm91bmRDb2x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msgPSBzcGFuLnByb3BzLmh5cGVybGlua1xuICAgIC8vIFdoZW4gZGltQ29sb3IgaXMgZm9yY2VkLCBvdmVycmlkZSB0aGUgc3BhbidzIGRpbSBwcm9wXG4gICAgaWYgKGRpbUNvbG9yKSB7XG4gICAgICBzcGFuLnByb3BzLmRpbSA9IHRydWVcbiAgICB9XG4gICAgY29uc3QgaGFzVGV4dFByb3BzID0gaGFzQW55VGV4dFByb3BzKHNwYW4ucHJvcHMpXG5cbiAgICBpZiAoaHlwZXJsaW5rKSB7XG4gICAgICByZXR1cm4gaGFzVGV4dFByb3BzID8gKFxuICAgICAgICA8TGluayBrZXk9e2l9IHVybD17aHlwZXJsaW5rfT5cbiAgICAgICAgICA8U3R5bGVkVGV4dFxuICAgICAgICAgICAgY29sb3I9e3NwYW4ucHJvcHMuY29sb3J9XG4gICAgICAgICAgICBiYWNrZ3JvdW5kQ29sb3I9e3NwYW4ucHJvcHMuYmFja2dyb3VuZENvbG9yfVxuICAgICAgICAgICAgZGltPXtzcGFuLnByb3BzLmRpbX1cbiAgICAgICAgICAgIGJvbGQ9e3NwYW4ucHJvcHMuYm9sZH1cbiAgICAgICAgICAgIGl0YWxpYz17c3Bhbi5wcm9wcy5pdGFsaWN9XG4gICAgICAgICAgICB1bmRlcmxpbmU9e3NwYW4ucHJvcHMudW5kZXJsaW5lfVxuICAgICAgICAgICAgc3RyaWtldGhyb3VnaD17c3Bhbi5wcm9wcy5zdHJpa2V0aHJvdWdofVxuICAgICAgICAgICAgaW52ZXJzZT17c3Bhbi5wcm9wcy5pbnZlcnNlfVxuICAgICAgICAgID5cbiAgICAgICAgICAgIHtzcGFuLnRleHR9XG4gICAgICAgICAgPC9TdHlsZWRUZXh0PlxuICAgICAgICA8L0xpbms+XG4gICAgICApIDogKFxuICAgICAgICA8TGluayBrZXk9e2l9IHVybD17aHlwZXJsaW5rfT5cbiAgICAgICAgICB7c3Bhbi50ZXh0fVxuICAgICAgICA8L0xpbms+XG4gICAgICApXG4g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XNFLElBQUE7TUFBQXRFLENBQUEsTUFBQUUsRUFBQTtJQUFBO01BQUFBLEVBQUEsR0FBQUYsQ0FBQTtJQUFBO0lBQUEsT0FGUEUsRUFFTztFQUFBO0VBR1gsSUFBSVgsSUFBSTtJQUFBLElBQUFXLEVBQUE7SUFBQSxJQUFBRixDQUFBLFFBQUFmLFFBQUEsSUFBQWUsQ0FBQSxRQUFBc0UsSUFBQTtNQUVKcEUsRUFBQSxJQUFDLElBQUksS0FBS29FLElBQUksRUFBRSxJQUFJLENBQUosS0FBRyxDQUFDLENBQ2pCckYsU0FBTyxDQUNWLEVBRkMsSUFBSSxDQUVFO01BQUFlLENBQUEsTUFBQWYsUUFBQTtNQUFBZSxDQUFBLE1BQUFzRSxJQUFBO01BQUF0RSxDQUFBLE9BQUFFLEVBQUE7SUFBQTtNQUFBQSxFQUFBLEdBQUFGLENBQUE7SUFBQTtJQUFBLE9BRlBFLEVBRU87RUFBQTtFQUVWLElBQUFBLEVBQUE7RUFBQSxJQUFBRixDQUFBLFNBQUFmLFFBQUEsSUFBQWUsQ0FBQSxTQUFBc0UsSUFBQTtJQUNNcEUsRUFBQSxJQUFDLElBQUksS0FBS29FLElBQUksRUFBR3JGLFNBQU8sQ0FBRSxFQUF6QixJQUFJLENBQTRCO0lBQUFlLENBQUEsT0FBQWYsUUFBQTtJQUFBZSxDQUFBLE9BQUFzRSxJQUFBO0lBQUF0RSxDQUFBLE9BQUFFLEVBQUE7RUFBQTtJQUFBQSxFQUFBLEdBQUFGLENBQUE7RUFBQTtFQUFBLE9BQWpDRSxFQUFpQztBQUFBIiwiaWdub3JlTGlzdCI6W119 diff --git a/ui-tui/packages/hermes-ink/src/ink/bidi.ts b/ui-tui/packages/hermes-ink/src/ink/bidi.ts new file mode 100644 index 0000000000..28edace8a9 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/bidi.ts @@ -0,0 +1,145 @@ +/** + * Bidirectional text reordering for terminal rendering. + * + * Terminals on Windows do not implement the Unicode Bidi Algorithm, + * so RTL text (Hebrew, Arabic, etc.) appears reversed. This module + * applies the bidi algorithm to reorder ClusteredChar arrays from + * logical order to visual order before Ink's LTR cell placement loop. + * + * On macOS terminals (Terminal.app, iTerm2) bidi works natively. + * Windows Terminal (including WSL) does not implement bidi + * (https://github.com/microsoft/terminal/issues/538). + * + * Detection: Windows Terminal sets WT_SESSION; native Windows cmd/conhost + * also lacks bidi. We enable bidi reordering when running on Windows or + * inside Windows Terminal (covers WSL). + */ +import bidiFactory from 'bidi-js' + +type ClusteredChar = { + value: string + width: number + styleId: number + hyperlink: string | undefined +} + +let bidiInstance: ReturnType | undefined +let needsSoftwareBidi: boolean | undefined + +function needsBidi(): boolean { + if (needsSoftwareBidi === undefined) { + needsSoftwareBidi = + process.platform === 'win32' || + typeof process.env['WT_SESSION'] === 'string' || // WSL in Windows Terminal + process.env['TERM_PROGRAM'] === 'vscode' // VS Code integrated terminal (xterm.js) + } + + return needsSoftwareBidi +} + +function getBidi() { + if (!bidiInstance) { + bidiInstance = bidiFactory() + } + + return bidiInstance +} + +/** + * Reorder an array of ClusteredChars from logical order to visual order + * using the Unicode Bidi Algorithm. Active on terminals that lack native + * bidi support (Windows Terminal, conhost, WSL). + * + * Returns the same array on bidi-capable terminals (no-op). + */ +export function reorderBidi(characters: ClusteredChar[]): ClusteredChar[] { + if (!needsBidi() || characters.length === 0) { + return characters + } + + // Build a plain string from the clustered chars to run through bidi + const plainText = characters.map(c => c.value).join('') + + // Check if there are any RTL characters — skip bidi if pure LTR + if (!hasRTLCharacters(plainText)) { + return characters + } + + const bidi = getBidi() + const { levels } = bidi.getEmbeddingLevels(plainText, 'auto') + + // Map bidi levels back to ClusteredChar indices. + // Each ClusteredChar may be multiple code units in the joined string. + const charLevels: number[] = [] + let offset = 0 + + for (let i = 0; i < characters.length; i++) { + charLevels.push(levels[offset]!) + offset += characters[i]!.value.length + } + + // Get reorder segments from bidi-js, but we need to work at the + // ClusteredChar level, not the string level. We'll implement the + // standard bidi reordering: find the max level, then for each level + // from max down to 1, reverse all contiguous runs >= that level. + const reordered = [...characters] + const maxLevel = Math.max(...charLevels) + + for (let level = maxLevel; level >= 1; level--) { + let i = 0 + + while (i < reordered.length) { + if (charLevels[i]! >= level) { + // Find the end of this run + let j = i + 1 + + while (j < reordered.length && charLevels[j]! >= level) { + j++ + } + + // Reverse the run in both arrays + reverseRange(reordered, i, j - 1) + reverseRangeNumbers(charLevels, i, j - 1) + i = j + } else { + i++ + } + } + } + + return reordered +} + +function reverseRange(arr: T[], start: number, end: number): void { + while (start < end) { + const temp = arr[start]! + arr[start] = arr[end]! + arr[end] = temp + start++ + end-- + } +} + +function reverseRangeNumbers(arr: number[], start: number, end: number): void { + while (start < end) { + const temp = arr[start]! + arr[start] = arr[end]! + arr[end] = temp + start++ + end-- + } +} + +/** + * Quick check for RTL characters (Hebrew, Arabic, and related scripts). + * Avoids running the full bidi algorithm on pure-LTR text. + */ +function hasRTLCharacters(text: string): boolean { + // Hebrew: U+0590-U+05FF, U+FB1D-U+FB4F + // Arabic: U+0600-U+06FF, U+0750-U+077F, U+08A0-U+08FF, U+FB50-U+FDFF, U+FE70-U+FEFF + // Thaana: U+0780-U+07BF + // Syriac: U+0700-U+074F + return /[\u0590-\u05FF\uFB1D-\uFB4F\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF\u0780-\u07BF\u0700-\u074F]/u.test( + text + ) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/clearTerminal.ts b/ui-tui/packages/hermes-ink/src/ink/clearTerminal.ts new file mode 100644 index 0000000000..4ccaeeace0 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/clearTerminal.ts @@ -0,0 +1,68 @@ +/** + * Cross-platform terminal clearing with scrollback support. + * Detects modern terminals that support ESC[3J for clearing scrollback. + */ + +import { csi, CURSOR_HOME, ERASE_SCREEN, ERASE_SCROLLBACK } from './termio/csi.js' + +// HVP (Horizontal Vertical Position) - legacy Windows cursor home +const CURSOR_HOME_WINDOWS = csi(0, 'f') + +function isWindowsTerminal(): boolean { + return process.platform === 'win32' && !!process.env.WT_SESSION +} + +function isMintty(): boolean { + // mintty 3.1.5+ sets TERM_PROGRAM to 'mintty' + if (process.env.TERM_PROGRAM === 'mintty') { + return true + } + + // GitBash/MSYS2/MINGW use mintty and set MSYSTEM + if (process.platform === 'win32' && process.env.MSYSTEM) { + return true + } + + return false +} + +function isModernWindowsTerminal(): boolean { + // Windows Terminal sets WT_SESSION environment variable + if (isWindowsTerminal()) { + return true + } + + // VS Code integrated terminal on Windows with ConPTY support + if (process.platform === 'win32' && process.env.TERM_PROGRAM === 'vscode' && process.env.TERM_PROGRAM_VERSION) { + return true + } + + // mintty (GitBash/MSYS2/Cygwin) supports modern escape sequences + if (isMintty()) { + return true + } + + return false +} + +/** + * Returns the ANSI escape sequence to clear the terminal including scrollback. + * Automatically detects terminal capabilities. + */ +export function getClearTerminalSequence(): string { + if (process.platform === 'win32') { + if (isModernWindowsTerminal()) { + return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME + } else { + // Legacy Windows console - can't clear scrollback + return ERASE_SCREEN + CURSOR_HOME_WINDOWS + } + } + + return ERASE_SCREEN + ERASE_SCROLLBACK + CURSOR_HOME +} + +/** + * Clears the terminal screen. On supported terminals, also clears scrollback. + */ +export const clearTerminal = getClearTerminalSequence() diff --git a/ui-tui/packages/hermes-ink/src/ink/colorize.ts b/ui-tui/packages/hermes-ink/src/ink/colorize.ts new file mode 100644 index 0000000000..2229f70a97 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/colorize.ts @@ -0,0 +1,226 @@ +import chalk from 'chalk' + +import type { Color, TextStyles } from './styles.js' + +/** + * xterm.js (VS Code, Cursor, code-server, Coder) has supported truecolor + * since 2017, but code-server/Coder containers often don't set + * COLORTERM=truecolor. chalk's supports-color doesn't recognize + * TERM_PROGRAM=vscode (it only knows iTerm.app/Apple_Terminal), so it falls + * through to the -256color regex → level 2. At level 2, chalk.rgb() + * downgrades to the nearest 6×6×6 cube color: rgb(215,119,87) → idx 174 + * rgb(215,135,135) — washed-out salmon. + * + * Gated on level === 2 (not < 3) to respect NO_COLOR / FORCE_COLOR=0 — + * those yield level 0 and are an explicit "no colors" request. Desktop VS + * Code sets COLORTERM=truecolor itself, so this is a no-op there (already 3). + * + * Must run BEFORE the tmux clamp — if tmux is running inside a VS Code + * terminal, tmux's passthrough limitation wins and we want level 2. + */ +function boostChalkLevelForXtermJs(): boolean { + if (process.env.TERM_PROGRAM === 'vscode' && chalk.level === 2) { + chalk.level = 3 + + return true + } + + return false +} + +/** + * tmux parses truecolor SGR (\e[48;2;r;g;bm) into its cell buffer correctly, + * but its client-side emitter only re-emits truecolor to the outer terminal if + * the outer terminal advertises Tc/RGB capability (via terminal-overrides). + * Default tmux config doesn't set this, so tmux emits the cell to iTerm2/etc + * WITHOUT the bg sequence — outer terminal's buffer has bg=default → black on + * dark profiles. Clamping to level 2 makes chalk emit 256-color (\e[48;5;Nm), + * which tmux passes through cleanly. grey93 (255) is visually identical to + * rgb(240,240,240). + * + * Users who HAVE set `terminal-overrides ,*:Tc` get a technically-unnecessary + * downgrade, but the visual difference is imperceptible. Querying + * `tmux show -gv terminal-overrides` to detect this would add a subprocess on + * startup — not worth it. + * + * $TMUX is a pty-lifecycle env var set by tmux itself; it never comes from + * globalSettings.env, so reading it here is correct. chalk is a singleton, so + * this clamps ALL truecolor output (fg+bg+hex) across the entire app. + */ +function clampChalkLevelForTmux(): boolean { + if (process.env.TMUX && chalk.level > 2) { + chalk.level = 2 + + return true + } + + return false +} + +// Computed once at module load — terminal/tmux environment doesn't change mid-session. +// Order matters: boost first so the tmux clamp can re-clamp if tmux is running +// inside a VS Code terminal. Exported for debugging — tree-shaken if unused. +export const CHALK_BOOSTED_FOR_XTERMJS = boostChalkLevelForXtermJs() +export const CHALK_CLAMPED_FOR_TMUX = clampChalkLevelForTmux() + +export type ColorType = 'foreground' | 'background' + +const RGB_REGEX = /^rgb\(\s?(\d+),\s?(\d+),\s?(\d+)\s?\)$/ +const ANSI_REGEX = /^ansi256\(\s?(\d+)\s?\)$/ + +export const colorize = (str: string, color: string | undefined, type: ColorType): string => { + if (!color) { + return str + } + + if (color.startsWith('ansi:')) { + const value = color.substring('ansi:'.length) + + switch (value) { + case 'black': + return type === 'foreground' ? chalk.black(str) : chalk.bgBlack(str) + + case 'red': + return type === 'foreground' ? chalk.red(str) : chalk.bgRed(str) + + case 'green': + return type === 'foreground' ? chalk.green(str) : chalk.bgGreen(str) + + case 'yellow': + return type === 'foreground' ? chalk.yellow(str) : chalk.bgYellow(str) + + case 'blue': + return type === 'foreground' ? chalk.blue(str) : chalk.bgBlue(str) + + case 'magenta': + return type === 'foreground' ? chalk.magenta(str) : chalk.bgMagenta(str) + + case 'cyan': + return type === 'foreground' ? chalk.cyan(str) : chalk.bgCyan(str) + + case 'white': + return type === 'foreground' ? chalk.white(str) : chalk.bgWhite(str) + + case 'blackBright': + return type === 'foreground' ? chalk.blackBright(str) : chalk.bgBlackBright(str) + + case 'redBright': + return type === 'foreground' ? chalk.redBright(str) : chalk.bgRedBright(str) + + case 'greenBright': + return type === 'foreground' ? chalk.greenBright(str) : chalk.bgGreenBright(str) + + case 'yellowBright': + return type === 'foreground' ? chalk.yellowBright(str) : chalk.bgYellowBright(str) + + case 'blueBright': + return type === 'foreground' ? chalk.blueBright(str) : chalk.bgBlueBright(str) + + case 'magentaBright': + return type === 'foreground' ? chalk.magentaBright(str) : chalk.bgMagentaBright(str) + + case 'cyanBright': + return type === 'foreground' ? chalk.cyanBright(str) : chalk.bgCyanBright(str) + + case 'whiteBright': + return type === 'foreground' ? chalk.whiteBright(str) : chalk.bgWhiteBright(str) + } + } + + if (color.startsWith('#')) { + return type === 'foreground' ? chalk.hex(color)(str) : chalk.bgHex(color)(str) + } + + if (color.startsWith('ansi256')) { + const matches = ANSI_REGEX.exec(color) + + if (!matches) { + return str + } + + const value = Number(matches[1]) + + return type === 'foreground' ? chalk.ansi256(value)(str) : chalk.bgAnsi256(value)(str) + } + + if (color.startsWith('rgb')) { + const matches = RGB_REGEX.exec(color) + + if (!matches) { + return str + } + + const firstValue = Number(matches[1]) + const secondValue = Number(matches[2]) + const thirdValue = Number(matches[3]) + + return type === 'foreground' + ? chalk.rgb(firstValue, secondValue, thirdValue)(str) + : chalk.bgRgb(firstValue, secondValue, thirdValue)(str) + } + + return str +} + +/** + * Apply TextStyles to a string using chalk. + * This is the inverse of parsing ANSI codes - we generate them from structured styles. + * Theme resolution happens at component layer, not here. + */ +export function applyTextStyles(text: string, styles: TextStyles): string { + let result = text + + // Apply styles in reverse order of desired nesting. + // chalk wraps text so later calls become outer wrappers. + // Desired order (outermost to innermost): + // background > foreground > text modifiers + // So we apply: text modifiers first, then foreground, then background last. + + if (styles.inverse) { + result = chalk.inverse(result) + } + + if (styles.strikethrough) { + result = chalk.strikethrough(result) + } + + if (styles.underline) { + result = chalk.underline(result) + } + + if (styles.italic) { + result = chalk.italic(result) + } + + if (styles.bold) { + result = chalk.bold(result) + } + + if (styles.dim) { + result = chalk.dim(result) + } + + if (styles.color) { + // Color is now always a raw color value (theme resolution happens at component layer) + result = colorize(result, styles.color, 'foreground') + } + + if (styles.backgroundColor) { + // backgroundColor is now always a raw color value + result = colorize(result, styles.backgroundColor, 'background') + } + + return result +} + +/** + * Apply a raw color value to text. + * Theme resolution should happen at component layer, not here. + */ +export function applyColor(text: string, color: Color | undefined): string { + if (!color) { + return text + } + + return colorize(text, color, 'foreground') +} diff --git a/ui-tui/packages/hermes-ink/src/ink/components/AlternateScreen.tsx b/ui-tui/packages/hermes-ink/src/ink/components/AlternateScreen.tsx new file mode 100644 index 0000000000..bb18608172 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/AlternateScreen.tsx @@ -0,0 +1,93 @@ +import React, { type PropsWithChildren, useContext, useInsertionEffect } from 'react' +import { c as _c } from 'react/compiler-runtime' + +import instances from '../instances.js' +import { DISABLE_MOUSE_TRACKING, ENABLE_MOUSE_TRACKING, ENTER_ALT_SCREEN, EXIT_ALT_SCREEN } from '../termio/dec.js' +import { TerminalWriteContext } from '../useTerminalNotification.js' + +import Box from './Box.js' +import { TerminalSizeContext } from './TerminalSizeContext.js' +type Props = PropsWithChildren<{ + /** Enable SGR mouse tracking (wheel + click/drag). Default true. */ + mouseTracking?: boolean +}> + +/** + * Run children in the terminal's alternate screen buffer, constrained to + * the viewport height. While mounted: + * + * - Enters the alt screen (DEC 1049), clears it, homes the cursor + * - Constrains its own height to the terminal row count, so overflow must + * be handled via `overflow: scroll` / flexbox (no native scrollback) + * - Optionally enables SGR mouse tracking (wheel + click/drag) — events + * surface as `ParsedKey` (wheel) and update the Ink instance's + * selection state (click/drag) + * + * On unmount, disables mouse tracking and exits the alt screen, restoring + * the main screen's content. Safe for use in ctrl-o transcript overlays + * and similar temporary fullscreen views — the main screen is preserved. + * + * Notifies the Ink instance via `setAltScreenActive()` so the renderer + * keeps the cursor inside the viewport (preventing the cursor-restore LF + * from scrolling content) and so signal-exit cleanup can exit the alt + * screen if the component's own unmount doesn't run. + */ +export function AlternateScreen(t0: Props) { + const $ = _c(7) + + const { children, mouseTracking: t1 } = t0 + + const mouseTracking = t1 === undefined ? true : t1 + const size = useContext(TerminalSizeContext) + const writeRaw = useContext(TerminalWriteContext) + let t2 + let t3 + + if ($[0] !== mouseTracking || $[1] !== writeRaw) { + t2 = () => { + const ink = instances.get(process.stdout) + + if (!writeRaw) { + return + } + + writeRaw(ENTER_ALT_SCREEN + '\x1B[2J\x1B[H' + (mouseTracking ? ENABLE_MOUSE_TRACKING : '')) + ink?.setAltScreenActive(true, mouseTracking) + + return () => { + ink?.setAltScreenActive(false) + ink?.clearTextSelection() + writeRaw((mouseTracking ? DISABLE_MOUSE_TRACKING : '') + EXIT_ALT_SCREEN) + } + } + + t3 = [writeRaw, mouseTracking] + $[0] = mouseTracking + $[1] = writeRaw + $[2] = t2 + $[3] = t3 + } else { + t2 = $[2] + t3 = $[3] + } + + useInsertionEffect(t2, t3) + const t4 = size?.rows ?? 24 + let t5 + + if ($[4] !== children || $[5] !== t4) { + t5 = ( + + {children} + + ) + $[4] = children + $[5] = t4 + $[6] = t5 + } else { + t5 = $[6] + } + + return t5 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlByb3BzV2l0aENoaWxkcmVuIiwidXNlQ29udGV4dCIsInVzZUluc2VydGlvbkVmZmVjdCIsImluc3RhbmNlcyIsIkRJU0FCTEVfTU9VU0VfVFJBQ0tJTkciLCJFTkFCTEVfTU9VU0VfVFJBQ0tJTkciLCJFTlRFUl9BTFRfU0NSRUVOIiwiRVhJVF9BTFRfU0NSRUVOIiwiVGVybWluYWxXcml0ZUNvbnRleHQiLCJCb3giLCJUZXJtaW5hbFNpemVDb250ZXh0IiwiUHJvcHMiLCJtb3VzZVRyYWNraW5nIiwiQWx0ZXJuYXRlU2NyZWVuIiwidDAiLCIkIiwiX2MiLCJjaGlsZHJlbiIsInQxIiwidW5kZWZpbmVkIiwic2l6ZSIsIndyaXRlUmF3IiwidDIiLCJ0MyIsImluayIsImdldCIsInByb2Nlc3MiLCJzdGRvdXQiLCJzZXRBbHRTY3JlZW5BY3RpdmUiLCJjbGVhclRleHRTZWxlY3Rpb24iLCJ0NCIsInJvd3MiLCJ0NSJdLCJzb3VyY2VzIjpbIkFsdGVybmF0ZVNjcmVlbi50c3giXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFJlYWN0LCB7XG4gIHR5cGUgUHJvcHNXaXRoQ2hpbGRyZW4sXG4gIHVzZUNvbnRleHQsXG4gIHVzZUluc2VydGlvbkVmZmVjdCxcbn0gZnJvbSAncmVhY3QnXG5pbXBvcnQgaW5zdGFuY2VzIGZyb20gJy4uL2luc3RhbmNlcy5qcydcbmltcG9ydCB7XG4gIERJU0FCTEVfTU9VU0VfVFJBQ0tJTkcsXG4gIEVOQUJMRV9NT1V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UFBQUYsQ0FBQSxNQUFBZSxFQUFBO0lBQUFmLENBQUEsTUFBQWlCLEVBQUE7RUFBQTtJQUFBQSxFQUFBLEdBQUFqQixDQUFBO0VBQUE7RUFBQSxPQVBOaUIsRUFPTTtBQUFBIiwiaWdub3JlTGlzdCI6W119 diff --git a/ui-tui/packages/hermes-ink/src/ink/components/App.tsx b/ui-tui/packages/hermes-ink/src/ink/components/App.tsx new file mode 100644 index 0000000000..3a0381a729 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/App.tsx @@ -0,0 +1,780 @@ +import React, { PureComponent, type ReactNode } from 'react' + +import { updateLastInteractionTime } from '../../bootstrap/state.js' +import { logForDebugging } from '../../utils/debug.js' +import { stopCapturingEarlyInput } from '../../utils/earlyInput.js' +import { isMouseClicksDisabled } from '../../utils/fullscreen.js' +import { logError } from '../../utils/log.js' +import type { DOMElement } from '../dom.js' +import { EventEmitter } from '../events/emitter.js' +import { InputEvent } from '../events/input-event.js' +import { TerminalFocusEvent } from '../events/terminal-focus-event.js' +import { + INITIAL_STATE, + type ParsedInput, + type ParsedKey, + type ParsedMouse, + parseMultipleKeypresses +} from '../parse-keypress.js' +import reconciler from '../reconciler.js' +import { finishSelection, hasSelection, type SelectionState, startSelection } from '../selection.js' +import { getTerminalFocused, setTerminalFocused } from '../terminal-focus-state.js' +import { TerminalQuerier, xtversion } from '../terminal-querier.js' +import { isXtermJs, setXtversionName, supportsExtendedKeys } from '../terminal.js' +import { + DISABLE_KITTY_KEYBOARD, + DISABLE_MODIFY_OTHER_KEYS, + ENABLE_KITTY_KEYBOARD, + ENABLE_MODIFY_OTHER_KEYS, + FOCUS_IN, + FOCUS_OUT +} from '../termio/csi.js' +import { DBP, DFE, DISABLE_MOUSE_TRACKING, EBP, EFE, HIDE_CURSOR, SHOW_CURSOR } from '../termio/dec.js' + +import AppContext from './AppContext.js' +import { ClockProvider } from './ClockContext.js' +import CursorDeclarationContext, { type CursorDeclarationSetter } from './CursorDeclarationContext.js' +import ErrorOverview from './ErrorOverview.js' +import StdinContext from './StdinContext.js' +import { TerminalFocusProvider } from './TerminalFocusContext.js' +import { TerminalSizeContext } from './TerminalSizeContext.js' + +// Platforms that support Unix-style process suspension (SIGSTOP/SIGCONT) +const SUPPORTS_SUSPEND = false + +// After this many milliseconds of stdin silence, the next chunk triggers +// a terminal mode re-assert (mouse tracking). Catches tmux detach→attach, +// ssh reconnect, and laptop wake — the terminal resets DEC private modes +// but no signal reaches us. 5s is well above normal inter-keystroke gaps +// but short enough that the first scroll after reattach works. +const STDIN_RESUME_GAP_MS = 5000 +type Props = { + readonly children: ReactNode + readonly stdin: NodeJS.ReadStream + readonly stdout: NodeJS.WriteStream + readonly stderr: NodeJS.WriteStream + readonly exitOnCtrlC: boolean + readonly onExit: (error?: Error) => void + readonly terminalColumns: number + readonly terminalRows: number + // Text selection state. App mutates this directly from mouse events + // and calls onSelectionChange to trigger a repaint. Mouse events only + // arrive when (or similar) enables mouse tracking, + // so the handler is always wired but dormant until tracking is on. + readonly selection: SelectionState + readonly onSelectionChange: () => void + // Dispatch a click at (col, row) — hit-tests the DOM tree and bubbles + // onClick handlers. Returns true if a DOM handler consumed the click. + // No-op (returns false) outside fullscreen mode (Ink.dispatchClick + // gates on altScreenActive). + readonly onClickAt: (col: number, row: number) => boolean + readonly onMouseDownAt: (col: number, row: number, button: number) => DOMElement | undefined + readonly onMouseUpAt: (target: DOMElement, col: number, row: number, button: number) => void + readonly onMouseDragAt: (target: DOMElement, col: number, row: number, button: number) => void + // Dispatch hover (onMouseEnter/onMouseLeave) as the pointer moves over + // DOM elements. Called for mode-1003 motion events with no button held. + // No-op outside fullscreen (Ink.dispatchHover gates on altScreenActive). + readonly onHoverAt: (col: number, row: number) => void + // Look up the OSC 8 hyperlink at (col, row) synchronously at click + // time. Returns the URL or undefined. The browser-open is deferred by + // MULTI_CLICK_TIMEOUT_MS so double-click can cancel it. + readonly getHyperlinkAt: (col: number, row: number) => string | undefined + // Open a hyperlink URL in the browser. Called after the timer fires. + readonly onOpenHyperlink: (url: string) => void + // Called on double/triple-click PRESS at (col, row). count=2 selects + // the word under the cursor; count=3 selects the line. Ink reads the + // screen buffer to find word/line boundaries and mutates selection, + // setting isDragging=true so a subsequent drag extends by word/line. + readonly onMultiClick: (col: number, row: number, count: 2 | 3) => void + // Called on drag-motion. Mode-aware: char mode updates focus to the + // exact cell; word/line mode snaps to word/line boundaries. Needs + // screen-buffer access (word boundaries) so lives on Ink, not here. + readonly onSelectionDrag: (col: number, row: number) => void + // Called when stdin data arrives after a >STDIN_RESUME_GAP_MS gap. + // Ink re-asserts terminal modes: extended key reporting, and (when in + // fullscreen) re-enters alt-screen + mouse tracking. Idempotent on the + // terminal side. Optional so testing.tsx doesn't need to stub it. + readonly onStdinResume?: () => void + // Receives the declared native-cursor position from useDeclaredCursor + // so ink.tsx can park the terminal cursor there after each frame. + // Enables IME composition at the input caret and lets screen readers / + // magnifiers track the input. Optional so testing.tsx doesn't stub it. + readonly onCursorDeclaration?: CursorDeclarationSetter + // Dispatch a keyboard event through the DOM tree. Called for each + // parsed key alongside the legacy EventEmitter path. + readonly dispatchKeyboardEvent: (parsedKey: ParsedKey) => void +} + +// Multi-click detection thresholds. 500ms is the macOS default; a small +// position tolerance allows for trackpad jitter between clicks. +const MULTI_CLICK_TIMEOUT_MS = 500 +const MULTI_CLICK_DISTANCE = 1 +type State = { + readonly error?: Error +} + +// Root component for all Ink apps +// It renders stdin and stdout contexts, so that children can access them if needed +// It also handles Ctrl+C exiting and cursor visibility +export default class App extends PureComponent { + static displayName = 'InternalApp' + static getDerivedStateFromError(error: Error) { + return { + error + } + } + override state = { + error: undefined + } + + // Count how many components enabled raw mode to avoid disabling + // raw mode until all components don't need it anymore + rawModeEnabledCount = 0 + inputEmitter = new EventEmitter() + keyParseState = INITIAL_STATE + // Timer for flushing incomplete escape sequences + incompleteEscapeTimer: NodeJS.Timeout | null = null + // Timeout durations for incomplete sequences (ms) + readonly NORMAL_TIMEOUT = 50 // Short timeout for regular esc sequences + readonly PASTE_TIMEOUT = 500 // Longer timeout for paste operations + + // Terminal query/response dispatch. Responses arrive on stdin (parsed + // out by parse-keypress) and are routed to pending promise resolvers. + querier = new TerminalQuerier(this.props.stdout) + + // Multi-click tracking for double/triple-click text selection. A click + // within MULTI_CLICK_TIMEOUT_MS and MULTI_CLICK_DISTANCE of the previous + // click increments clickCount; otherwise it resets to 1. + lastClickTime = 0 + lastClickCol = -1 + lastClickRow = -1 + clickCount = 0 + // Deferred hyperlink-open timer — cancelled if a second click arrives + // within MULTI_CLICK_TIMEOUT_MS (so double-clicking a hyperlink selects + // the word without also opening the browser). DOM onClick dispatch is + // NOT deferred — it returns true from onClickAt and skips this timer. + pendingHyperlinkTimer: ReturnType | null = null + // Last mode-1003 motion position. Terminals already dedupe to cell + // granularity but this also lets us skip dispatchHover entirely on + // repeat events (drag-then-release at same cell, etc.). + lastHoverCol = -1 + lastHoverRow = -1 + mouseCaptureTarget: DOMElement | undefined + + // Timestamp of last stdin chunk. Used to detect long gaps (tmux attach, + // ssh reconnect, laptop wake) and trigger terminal mode re-assert. + // Initialized to now so startup doesn't false-trigger. + lastStdinTime = Date.now() + + // Determines if TTY is supported on the provided stdin + isRawModeSupported(): boolean { + return this.props.stdin.isTTY + } + override render() { + return ( + + + + + + {})}> + {this.state.error ? : this.props.children} + + + + + + + ) + } + override componentDidMount() { + // In accessibility mode, keep the native cursor visible for screen magnifiers and other tools + if (this.props.stdout.isTTY) { + this.props.stdout.write(HIDE_CURSOR) + } + } + override componentWillUnmount() { + if (this.props.stdout.isTTY) { + this.props.stdout.write(SHOW_CURSOR) + } + + // Clear any pending timers + if (this.incompleteEscapeTimer) { + clearTimeout(this.incompleteEscapeTimer) + this.incompleteEscapeTimer = null + } + + if (this.pendingHyperlinkTimer) { + clearTimeout(this.pendingHyperlinkTimer) + this.pendingHyperlinkTimer = null + } + + // ignore calling setRawMode on an handle stdin it cannot be called + if (this.isRawModeSupported()) { + this.handleSetRawMode(false) + } + } + override componentDidCatch(error: Error) { + this.handleExit(error) + } + handleSetRawMode = (isEnabled: boolean): void => { + const { stdin } = this.props + + if (!this.isRawModeSupported()) { + if (stdin === process.stdin) { + throw new Error( + 'Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported' + ) + } else { + throw new Error( + 'Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported' + ) + } + } + + stdin.setEncoding('utf8') + + if (isEnabled) { + // Ensure raw mode is enabled only once + if (this.rawModeEnabledCount === 0) { + // Stop early input capture right before we add our own readable handler. + // Both use the same stdin 'readable' + read() pattern, so they can't + // coexist -- our handler would drain stdin before Ink's can see it. + // The buffered text is preserved for REPL.tsx via consumeEarlyInput(). + stopCapturingEarlyInput() + stdin.ref() + stdin.setRawMode(true) + stdin.addListener('readable', this.handleReadable) + // Enable bracketed paste mode + this.props.stdout.write(EBP) + // Enable terminal focus reporting (DECSET 1004) + this.props.stdout.write(EFE) + + // Enable extended key reporting so ctrl+shift+ is + // distinguishable from ctrl+. We write both the kitty stack + // push (CSI >1u) and xterm modifyOtherKeys level 2 (CSI >4;2m) — + // terminals honor whichever they implement (tmux only accepts the + // latter). + if (supportsExtendedKeys()) { + this.props.stdout.write(ENABLE_KITTY_KEYBOARD) + this.props.stdout.write(ENABLE_MODIFY_OTHER_KEYS) + } + + // Probe terminal identity. XTVERSION survives SSH (query/reply goes + // through the pty), unlike TERM_PROGRAM. Used for wheel-scroll base + // detection when env vars are absent. Fire-and-forget: the DA1 + // sentinel bounds the round-trip, and if the terminal ignores the + // query, flush() still resolves and name stays undefined. + // Deferred to next tick so it fires AFTER the current synchronous + // init sequence completes — avoids interleaving with alt-screen/mouse + // tracking enable writes that may happen in the same render cycle. + setImmediate(() => { + void Promise.all([this.querier.send(xtversion()), this.querier.flush()]).then(([r]) => { + if (r) { + setXtversionName(r.name) + logForDebugging(`XTVERSION: terminal identified as "${r.name}"`) + } else { + logForDebugging('XTVERSION: no reply (terminal ignored query)') + } + }) + }) + } + + this.rawModeEnabledCount++ + + return + } + + // Disable raw mode only when no components left that are using it + if (--this.rawModeEnabledCount === 0) { + this.props.stdout.write(DISABLE_MODIFY_OTHER_KEYS) + this.props.stdout.write(DISABLE_KITTY_KEYBOARD) + // Disable terminal focus reporting (DECSET 1004) + this.props.stdout.write(DFE) + // Disable bracketed paste mode + this.props.stdout.write(DBP) + stdin.setRawMode(false) + stdin.removeListener('readable', this.handleReadable) + stdin.unref() + } + } + + // Helper to flush incomplete escape sequences + flushIncomplete = (): void => { + // Clear the timer reference + this.incompleteEscapeTimer = null + + // Only proceed if we have incomplete sequences + if (!this.keyParseState.incomplete) { + return + } + + // Fullscreen: if stdin has data waiting, it's almost certainly the + // continuation of the buffered sequence (e.g. `[<64;74;16M` after a + // lone ESC). Node's event loop runs the timers phase before the poll + // phase, so when a heavy render blocks the loop past 50ms, this timer + // fires before the queued readable event even though the bytes are + // already buffered. Re-arm instead of flushing: handleReadable will + // drain stdin next and clear this timer. Prevents both the spurious + // Escape key and the lost scroll event. + if (this.props.stdin.readableLength > 0) { + this.incompleteEscapeTimer = setTimeout(this.flushIncomplete, this.NORMAL_TIMEOUT) + + return + } + + // Process incomplete as a flush operation (input=null) + // This reuses all existing parsing logic + this.processInput(null) + } + + // Process input through the parser and handle the results + processInput = (input: string | Buffer | null): void => { + // Parse input using our state machine + const [keys, newState] = parseMultipleKeypresses(this.keyParseState, input) + this.keyParseState = newState + + // Process ALL keys in a SINGLE discreteUpdates call to prevent + // "Maximum update depth exceeded" error when many keys arrive at once + // (e.g., from paste operations or holding keys rapidly). + // This batches all state updates from handleInput and all useInput + // listeners together within one high-priority update context. + if (keys.length > 0) { + reconciler.discreteUpdates(processKeysInBatch, this, keys, undefined, undefined) + } + + // If we have incomplete escape sequences, set a timer to flush them + if (this.keyParseState.incomplete) { + // Cancel any existing timer first + if (this.incompleteEscapeTimer) { + clearTimeout(this.incompleteEscapeTimer) + } + + this.incompleteEscapeTimer = setTimeout( + this.flushIncomplete, + this.keyParseState.mode === 'IN_PASTE' ? this.PASTE_TIMEOUT : this.NORMAL_TIMEOUT + ) + } + } + handleReadable = (): void => { + // Detect long stdin gaps (tmux attach, ssh reconnect, laptop wake). + // The terminal may have reset DEC private modes; re-assert mouse + // tracking. Checked before the read loop so one Date.now() covers + // all chunks in this readable event. + const now = Date.now() + + if (now - this.lastStdinTime > STDIN_RESUME_GAP_MS) { + this.props.onStdinResume?.() + } + + this.lastStdinTime = now + + try { + let chunk + + while ((chunk = this.props.stdin.read() as string | null) !== null) { + // Process the input chunk + this.processInput(chunk) + } + } catch (error) { + // In Bun, an uncaught throw inside a stream 'readable' handler can + // permanently wedge the stream: data stays buffered and 'readable' + // never re-emits. Catching here ensures the stream stays healthy so + // subsequent keystrokes are still delivered. + logError(error) + + // Re-attach the listener in case the exception detached it. + // Bun may remove the listener after an error; without this, + // the session freezes permanently (stdin reader dead, event loop alive). + const { stdin } = this.props + + if (this.rawModeEnabledCount > 0 && !stdin.listeners('readable').includes(this.handleReadable)) { + logForDebugging('handleReadable: re-attaching stdin readable listener after error recovery', { + level: 'warn' + }) + stdin.addListener('readable', this.handleReadable) + } + } + } + handleInput = (input: string | undefined): void => { + // Exit on Ctrl+C + if (input === '\x03' && this.props.exitOnCtrlC) { + this.handleExit() + } + + // Note: Ctrl+Z (suspend) is now handled in processKeysInBatch using the + // parsed key to support both raw (\x1a) and CSI u format from Kitty + // keyboard protocol terminals (Ghostty, iTerm2, kitty, WezTerm) + } + handleExit = (error?: Error): void => { + if (this.isRawModeSupported()) { + this.handleSetRawMode(false) + } + + this.props.onExit(error) + } + handleTerminalFocus = (isFocused: boolean): void => { + // setTerminalFocused notifies subscribers: TerminalFocusProvider (context) + // and Clock (interval speed) — no App setState needed. + setTerminalFocused(isFocused) + } + handleSuspend = (): void => { + if (!this.isRawModeSupported()) { + return + } + + // Store the exact raw mode count to restore it properly + const rawModeCountBeforeSuspend = this.rawModeEnabledCount + + // Completely disable raw mode before suspending + while (this.rawModeEnabledCount > 0) { + this.handleSetRawMode(false) + } + + // Show cursor, disable focus reporting, and disable mouse tracking + // before suspending. DISABLE_MOUSE_TRACKING is a no-op if tracking + // wasn't enabled, so it's safe to emit unconditionally — without + // it, SGR mouse sequences would appear as garbled text at the + // shell prompt while suspended. + if (this.props.stdout.isTTY) { + this.props.stdout.write(SHOW_CURSOR + DFE + DISABLE_MOUSE_TRACKING) + } + + this.inputEmitter.emit('suspend') + + // Set up resume handler + const resumeHandler = () => { + // Restore raw mode to exact previous state + for (let i = 0; i < rawModeCountBeforeSuspend; i++) { + if (this.isRawModeSupported()) { + this.handleSetRawMode(true) + } + } + + if (this.props.stdout.isTTY) { + this.props.stdout.write(HIDE_CURSOR + EFE) + } + + this.inputEmitter.emit('resume') + process.removeListener('SIGCONT', resumeHandler) + } + + process.on('SIGCONT', resumeHandler) + process.kill(process.pid, 'SIGSTOP') + } +} + +// Helper to process all keys within a single discrete update context. +// discreteUpdates expects (fn, a, b, c, d) -> fn(a, b, c, d) +function processKeysInBatch(app: App, items: ParsedInput[], _unused1: undefined, _unused2: undefined): void { + // Update interaction time for notification timeout tracking. + // This is called from the central input handler to avoid having multiple + // stdin listeners that can cause race conditions and dropped input. + // Terminal responses (kind: 'response') are automated, not user input. + // Mode-1003 no-button motion is also excluded — passive cursor drift is + // not engagement (would suppress idle notifications + defer housekeeping). + if ( + items.some(i => i.kind === 'key' || (i.kind === 'mouse' && !((i.button & 0x20) !== 0 && (i.button & 0x03) === 3))) + ) { + updateLastInteractionTime() + } + + for (const item of items) { + // Terminal responses (DECRPM, DA1, OSC replies, etc.) are not user + // input — route them to the querier to resolve pending promises. + if (item.kind === 'response') { + app.querier.onResponse(item.response) + + continue + } + + // Mouse click/drag events update selection state (fullscreen only). + // Terminal sends 1-indexed col/row; convert to 0-indexed for the + // screen buffer. Button bit 0x20 = drag (motion while button held). + if (item.kind === 'mouse') { + handleMouseEvent(app, item) + + continue + } + + const sequence = item.sequence + + // Handle terminal focus events (DECSET 1004) + if (sequence === FOCUS_IN) { + app.handleTerminalFocus(true) + const event = new TerminalFocusEvent('terminalfocus') + app.inputEmitter.emit('terminalfocus', event) + + continue + } + + if (sequence === FOCUS_OUT) { + app.handleTerminalFocus(false) + + // Defensive: if we lost the release event (mouse released outside + // terminal window — some emulators drop it rather than capturing the + // pointer), focus-out is the next observable signal that the drag is + // over. Without this, drag-to-scroll's timer runs until the scroll + // boundary is hit. + if (app.props.selection.isDragging) { + finishSelection(app.props.selection) + app.props.onSelectionChange() + } + + const event = new TerminalFocusEvent('terminalblur') + app.inputEmitter.emit('terminalblur', event) + + continue + } + + // Failsafe: if we receive input, the terminal must be focused + if (!getTerminalFocused()) { + setTerminalFocused(true) + } + + // Handle Ctrl+Z (suspend) using parsed key to support both raw (\x1a) and + // CSI u format (\x1b[122;5u) from Kitty keyboard protocol terminals + if (item.name === 'z' && item.ctrl && SUPPORTS_SUSPEND) { + app.handleSuspend() + + continue + } + + app.handleInput(sequence) + const event = new InputEvent(item) + app.inputEmitter.emit('input', event) + + // Also dispatch through the DOM tree so onKeyDown handlers fire. + app.props.dispatchKeyboardEvent(item) + } +} + +/** Exported for testing. Mutates app.props.selection and click/hover state. */ +export function handleMouseEvent(app: App, m: ParsedMouse): void { + // Allow disabling click handling while keeping wheel scroll (which goes + // through the keybinding system as 'wheelup'/'wheeldown', not here). + if (isMouseClicksDisabled()) { + return + } + + const sel = app.props.selection + // Terminal coords are 1-indexed; screen buffer is 0-indexed + const col = m.col - 1 + const row = m.row - 1 + const baseButton = m.button & 0x03 + + if (m.action === 'press') { + if ((m.button & 0x20) !== 0 && baseButton === 3) { + if (app.mouseCaptureTarget) { + app.props.onMouseUpAt(app.mouseCaptureTarget, col, row, baseButton) + app.mouseCaptureTarget = undefined + } + + // Mode-1003 motion with no button held. Dispatch hover; skip the + // rest of this handler (no selection, no click-count side effects). + // Lost-release recovery: no-button motion while isDragging=true means + // the release happened outside the terminal window (iTerm2 doesn't + // capture the pointer past window bounds, so the SGR 'm' never + // arrives). Finish the selection here so copy-on-select fires. The + // FOCUS_OUT handler covers the "switched apps" case but not "released + // past the edge, came back" — and tmux drops focus events unless + // `focus-events on` is set, so this is the more reliable signal. + if (sel.isDragging) { + finishSelection(sel) + app.props.onSelectionChange() + } + + if (col === app.lastHoverCol && row === app.lastHoverRow) { + return + } + + app.lastHoverCol = col + app.lastHoverRow = row + app.props.onHoverAt(col, row) + + return + } + + if (baseButton !== 0) { + // Non-left press breaks the multi-click chain. + app.clickCount = 0 + + return + } + + if ((m.button & 0x20) !== 0) { + if (app.mouseCaptureTarget) { + app.props.onMouseDragAt(app.mouseCaptureTarget, col, row, baseButton) + + return + } + + // Drag motion: mode-aware extension (char/word/line). onSelectionDrag + // calls notifySelectionChange internally — no extra onSelectionChange. + app.props.onSelectionDrag(col, row) + + return + } + + // Lost-release fallback for mode-1002-only terminals: a fresh press + // while isDragging=true means the previous release was dropped (cursor + // left the window). Finish that selection so copy-on-select fires + // before startSelection/onMultiClick clobbers it. Mode-1003 terminals + // hit the no-button-motion recovery above instead, so this is rare. + if (sel.isDragging) { + finishSelection(sel) + app.props.onSelectionChange() + } + + const capture = app.props.onMouseDownAt(col, row, baseButton) + + if (capture) { + app.mouseCaptureTarget = capture + app.clickCount = 0 + + return + } + + // Fresh left press. Detect multi-click HERE (not on release) so the + // word/line highlight appears immediately and a subsequent drag can + // extend by word/line like native macOS. Previously detected on + // release, which meant (a) visible latency before the word highlights + // and (b) double-click+drag fell through to char-mode selection. + const now = Date.now() + + const nearLast = + now - app.lastClickTime < MULTI_CLICK_TIMEOUT_MS && + Math.abs(col - app.lastClickCol) <= MULTI_CLICK_DISTANCE && + Math.abs(row - app.lastClickRow) <= MULTI_CLICK_DISTANCE + + app.clickCount = nearLast ? app.clickCount + 1 : 1 + app.lastClickTime = now + app.lastClickCol = col + app.lastClickRow = row + + if (app.clickCount >= 2) { + // Cancel any pending hyperlink-open from the first click — this is + // a double-click, not a single-click on a link. + if (app.pendingHyperlinkTimer) { + clearTimeout(app.pendingHyperlinkTimer) + app.pendingHyperlinkTimer = null + } + + // Cap at 3 (line select) for quadruple+ clicks. + const count = app.clickCount === 2 ? 2 : 3 + app.props.onMultiClick(col, row, count) + + return + } + + startSelection(sel, col, row) + // SGR bit 0x08 = alt (xterm.js wires altKey here, not metaKey — see + // comment at the hyperlink-open guard below). On macOS xterm.js, + // receiving alt means macOptionClickForcesSelection is OFF (otherwise + // xterm.js would have consumed the event for native selection). + sel.lastPressHadAlt = (m.button & 0x08) !== 0 + app.props.onSelectionChange() + + return + } + + // Release: end the drag even for non-zero button codes. Some terminals + // encode release with the motion bit or button=3 "no button" (carried + // over from pre-SGR X10 encoding) — filtering those would orphan + // isDragging=true and leave drag-to-scroll's timer running until the + // scroll boundary. Only act on non-left releases when we ARE dragging + // (so an unrelated middle/right click-release doesn't touch selection). + if (app.mouseCaptureTarget) { + app.props.onMouseUpAt(app.mouseCaptureTarget, col, row, baseButton) + app.mouseCaptureTarget = undefined + + return + } + + if (baseButton !== 0) { + if (!sel.isDragging) { + return + } + + finishSelection(sel) + app.props.onSelectionChange() + + return + } + + finishSelection(sel) + + // NOTE: unlike the old release-based detection we do NOT reset clickCount + // on release-after-drag. This aligns with NSEvent.clickCount semantics: + // an intervening drag doesn't break the click chain. Practical upside: + // trackpad jitter during an intended double-click (press→wobble→release + // →press) now correctly resolves to word-select instead of breaking to a + // fresh single click. The nearLast window (500ms, 1 cell) bounds the + // effect — a deliberate drag past that just starts a fresh chain. + // A press+release with no drag in char mode is a click: anchor set, + // focus null → hasSelection false. In word/line mode the press already + // set anchor+focus (hasSelection true), so release just keeps the + // highlight. The anchor check guards against an orphaned release (no + // prior press — e.g. button was held when mouse tracking was enabled). + if (!hasSelection(sel) && sel.anchor) { + // Single click: dispatch DOM click immediately (cursor repositioning + // etc. are latency-sensitive). If no DOM handler consumed it, defer + // the hyperlink check so a second click can cancel it. + if (!app.props.onClickAt(col, row)) { + // Resolve the hyperlink URL synchronously while the screen buffer + // still reflects what the user clicked — deferring only the + // browser-open so double-click can cancel it. + const url = app.props.getHyperlinkAt(col, row) + + // xterm.js (VS Code, Cursor, Windsurf, etc.) has its own OSC 8 link + // handler that fires on Cmd+click *without consuming the mouse event* + // (Linkifier._handleMouseUp calls link.activate() but never + // preventDefault/stopPropagation). The click is also forwarded to the + // pty as SGR, so both VS Code's terminalLinkManager AND our handler + // here would open the URL — twice. We can't filter on Cmd: xterm.js + // drops metaKey before SGR encoding (ICoreMouseEvent has no meta + // field; the SGR bit we call 'meta' is wired to alt). Let xterm.js + // own link-opening; Cmd+click is the native UX there anyway. + // TERM_PROGRAM is the sync fast-path; isXtermJs() is the XTVERSION + // probe result (catches SSH + non-VS Code embedders like Hyper). + if (url && process.env.TERM_PROGRAM !== 'vscode' && !isXtermJs()) { + // Clear any prior pending timer — clicking a second link + // supersedes the first (only the latest click opens). + if (app.pendingHyperlinkTimer) { + clearTimeout(app.pendingHyperlinkTimer) + } + + app.pendingHyperlinkTimer = setTimeout( + (app, url) => { + app.pendingHyperlinkTimer = null + app.props.onOpenHyperlink(url) + }, + MULTI_CLICK_TIMEOUT_MS, + app, + url + ) + } + } + } + + app.props.onSelectionChange() +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlB1cmVDb21wb25lbnQiLCJSZWFjdE5vZGUiLCJ1cGRhdGVMYXN0SW50ZXJhY3Rpb25UaW1lIiwibG9nRm9yRGVidWdnaW5nIiwic3RvcENhcHR1cmluZ0Vhcmx5SW5wdXQiLCJpc0VudlRydXRoeSIsImlzTW91c2VDbGlja3NEaXNhYmxlZCIsImxvZ0Vycm9yIiwiRXZlbnRFbWl0dGVyIiwiSW5wdXRFdmVudCIsIlRlcm1pbmFsRm9jdXNFdmVudCIsIklOSVRJQUxfU1RBVEUiLCJQYXJzZWRJbnB1dCIsIlBhcnNlZ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ICAgICAgICAgdmFsdWU9e3tcbiAgICAgICAgICAgICAgc3RkaW46IHRoaXMucHJvcHMuc3RkaW4sXG4gICAgICAgICAgICAgIHNldFJhd01vZGU6IHRoaXMuaGFuZGxlU2V0UmF3TW9kZSxcbiAgICAgICAgICAgICAgaXNSYXdNb2RlU3VwcG9ydGVkOiB0aGlzLmlzUmF3TW9kZVN1cHBvcnRlZCgpLFxuXG4gICAgICAgICAgICAgIGludGVybmFsX2V4aXRPbkN0cmxDOiB0aGlzLnByb3BzLmV4aXRPbkN0cmxDLFxuXG4gICAgICAgICAgICAgIGludGVybmFsX2V2ZW50RW1pdHRlcjogdGhpcy5pbnRlcm5hbF9ldmVudEVtaXR0ZXIsXG4gICAgICAgICAgICAgIGludGVybmFsX3F1ZXJpZXI6IHRoaXMucXVlcmllcixcbiAgICAgICAgICAgIH19XG4gICAgICAgICAgPlxuICAgICAgICAgICAgPFRlcm1pbmFsRm9jdXNQcm92aWRlcj5cbiAgICAgICAgICAgICAgPENsb2NrUHJvdmlkZXI+XG4gICAgICAgICAgICAgICAgPEN1cnNvckRlY2xhcmF0aW9uQ29udGV4dC5Qcm92aWRlclxuICAgICAgICAgICAgICAgICAgdmFsdWU9e3RoaXMucHJvcHMub25DdXJzb3JEZWNsYXJhdGlvbiA/PyAoKCkgPT4ge30pfVxuICAgICAgICAgICAgICAgID5cbiAgICAgICAgICAgICAgICAgIHt0aGlzLnN0YXRlLmVycm9yID8gKFxuICAgICAgICAgICAgICAgICAgICA8RXJyb3JPdmVydmlldyBlcnJvcj17dGhpcy5zdGF0ZS5lcnJvciBhcyBFcnJvcn0gLz5cbiAgICAgICAgICAgICAgICAgICkgOiAoXG4gICAgICAgICAgICAgICAgICAgIHRoaXMucHJvcHMuY2hpbGRyZW5cbiAgICAgICAgICAgICAgICAgICl9XG4gICAgICAgICAgICAgICAgPC9DdXJzb3JEZWNsYXJhdGlvbkNvbnRleHQuUHJvdmlkZXI+XG4gICAgICAgICAgICAgIDwvQ2xvY2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sRUFDdEIwRixHQUFHLEVBQ0hsRyxHQUNGLENBQUM7TUFDSDtJQUNGO0VBQ0Y7RUFDQWtHLEdBQUcsQ0FBQzFFLEtBQUssQ0FBQy9CLGlCQUFpQixDQUFDLENBQUM7QUFDL0IiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/AppContext.ts b/ui-tui/packages/hermes-ink/src/ink/components/AppContext.ts new file mode 100644 index 0000000000..3d13e779cc --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/AppContext.ts @@ -0,0 +1,20 @@ +import { createContext } from 'react' + +export type Props = { + /** + * Exit (unmount) the whole Ink app. + */ + readonly exit: (error?: Error) => void +} + +/** + * `AppContext` is a React context, which exposes a method to manually exit the app (unmount). + */ + +const AppContext = createContext({ + exit() {} +}) + +AppContext.displayName = 'InternalAppContext' + +export default AppContext diff --git a/ui-tui/packages/hermes-ink/src/ink/components/Box.tsx b/ui-tui/packages/hermes-ink/src/ink/components/Box.tsx new file mode 100644 index 0000000000..408d23c227 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/Box.tsx @@ -0,0 +1,294 @@ +import '../global.d.ts' + +import React, { type ReactNode, type Ref } from 'react' +import { c as _c } from 'react/compiler-runtime' +import type { Except } from 'type-fest' + +import type { DOMElement } from '../dom.js' +import type { ClickEvent } from '../events/click-event.js' +import type { FocusEvent } from '../events/focus-event.js' +import type { KeyboardEvent } from '../events/keyboard-event.js' +import type { MouseEvent } from '../events/mouse-event.js' +import type { Styles } from '../styles.js' +import * as warn from '../warn.js' +export type Props = Except & { + children?: ReactNode + ref?: Ref + /** + * Tab order index. Nodes with `tabIndex >= 0` participate in + * Tab/Shift+Tab cycling; `-1` means programmatically focusable only. + */ + tabIndex?: number + /** + * Focus this element when it mounts. Like the HTML `autofocus` + * attribute — the FocusManager calls `focus(node)` during the + * reconciler's `commitMount` phase. + */ + autoFocus?: boolean + /** + * Fired on left-button click (press + release without drag). Only works + * inside `` where mouse tracking is enabled — no-op + * otherwise. The event bubbles from the deepest hit Box up through + * ancestors; call `event.stopImmediatePropagation()` to stop bubbling. + */ + onClick?: (event: ClickEvent) => void + onMouseDown?: (event: MouseEvent) => void + onMouseUp?: (event: MouseEvent) => void + onMouseDrag?: (event: MouseEvent) => void + onFocus?: (event: FocusEvent) => void + onFocusCapture?: (event: FocusEvent) => void + onBlur?: (event: FocusEvent) => void + onBlurCapture?: (event: FocusEvent) => void + onKeyDown?: (event: KeyboardEvent) => void + onKeyDownCapture?: (event: KeyboardEvent) => void + /** + * Fired when the mouse moves into this Box's rendered rect. Like DOM + * `mouseenter`, does NOT bubble — moving between children does not + * re-fire on the parent. Only works inside `` where + * mode-1003 mouse tracking is enabled. + */ + onMouseEnter?: () => void + /** Fired when the mouse moves out of this Box's rendered rect. */ + onMouseLeave?: () => void +} + +/** + * `` is an essential Ink component to build your layout. It's like `
` in the browser. + */ +function Box(t0: Props) { + const $ = _c(48) + let autoFocus + let children + let flexDirection + let flexGrow + let flexShrink + let flexWrap + let onBlur + let onBlurCapture + let onClick + let onFocus + let onFocusCapture + let onKeyDown + let onKeyDownCapture + let onMouseDown + let onMouseDrag + let onMouseEnter + let onMouseLeave + let onMouseUp + let ref + let style + let tabIndex + + if ($[0] !== t0) { + const { + children: t1, + flexWrap: t2, + flexDirection: t3, + flexGrow: t4, + flexShrink: t5, + ref: t6, + tabIndex: t7, + autoFocus: t8, + onClick: t9, + onFocus: t10, + onFocusCapture: t11, + onBlur: t12, + onBlurCapture: t13, + onMouseDown: t14, + onMouseUp: t15, + onMouseDrag: t16, + onMouseEnter: t17, + onMouseLeave: t18, + onKeyDown: t19, + onKeyDownCapture: t20, + ...t21 + } = t0 + + children = t1 + ref = t6 + tabIndex = t7 + autoFocus = t8 + onClick = t9 + onFocus = t10 + onFocusCapture = t11 + onBlur = t12 + onBlurCapture = t13 + onMouseDown = t14 + onMouseUp = t15 + onMouseDrag = t16 + onMouseEnter = t17 + onMouseLeave = t18 + onKeyDown = t19 + onKeyDownCapture = t20 + style = t21 + flexWrap = t2 === undefined ? 'nowrap' : t2 + flexDirection = t3 === undefined ? 'row' : t3 + flexGrow = t4 === undefined ? 0 : t4 + flexShrink = t5 === undefined ? 1 : t5 + warn.ifNotInteger(style.margin, 'margin') + warn.ifNotInteger(style.marginX, 'marginX') + warn.ifNotInteger(style.marginY, 'marginY') + warn.ifNotInteger(style.marginTop, 'marginTop') + warn.ifNotInteger(style.marginBottom, 'marginBottom') + warn.ifNotInteger(style.marginLeft, 'marginLeft') + warn.ifNotInteger(style.marginRight, 'marginRight') + warn.ifNotInteger(style.padding, 'padding') + warn.ifNotInteger(style.paddingX, 'paddingX') + warn.ifNotInteger(style.paddingY, 'paddingY') + warn.ifNotInteger(style.paddingTop, 'paddingTop') + warn.ifNotInteger(style.paddingBottom, 'paddingBottom') + warn.ifNotInteger(style.paddingLeft, 'paddingLeft') + warn.ifNotInteger(style.paddingRight, 'paddingRight') + warn.ifNotInteger(style.gap, 'gap') + warn.ifNotInteger(style.columnGap, 'columnGap') + warn.ifNotInteger(style.rowGap, 'rowGap') + $[0] = t0 + $[1] = autoFocus + $[2] = children + $[3] = flexDirection + $[4] = flexGrow + $[5] = flexShrink + $[6] = flexWrap + $[7] = onBlur + $[8] = onBlurCapture + $[9] = onClick + $[10] = onFocus + $[11] = onFocusCapture + $[12] = onKeyDown + $[13] = onKeyDownCapture + $[14] = onMouseDown + $[15] = onMouseUp + $[16] = onMouseDrag + $[17] = onMouseEnter + $[18] = onMouseLeave + $[19] = ref + $[20] = style + $[21] = tabIndex + } else { + autoFocus = $[1] + children = $[2] + flexDirection = $[3] + flexGrow = $[4] + flexShrink = $[5] + flexWrap = $[6] + onBlur = $[7] + onBlurCapture = $[8] + onClick = $[9] + onFocus = $[10] + onFocusCapture = $[11] + onKeyDown = $[12] + onKeyDownCapture = $[13] + onMouseDown = $[14] + onMouseUp = $[15] + onMouseDrag = $[16] + onMouseEnter = $[17] + onMouseLeave = $[18] + ref = $[19] + style = $[20] + tabIndex = $[21] + } + + const t1 = style.overflowX ?? style.overflow ?? 'visible' + const t2 = style.overflowY ?? style.overflow ?? 'visible' + let t3 + + if ( + $[22] !== flexDirection || + $[23] !== flexGrow || + $[24] !== flexShrink || + $[25] !== flexWrap || + $[26] !== style || + $[27] !== t1 || + $[28] !== t2 + ) { + t3 = { + flexWrap, + flexDirection, + flexGrow, + flexShrink, + ...style, + overflowX: t1, + overflowY: t2 + } + $[22] = flexDirection + $[23] = flexGrow + $[24] = flexShrink + $[25] = flexWrap + $[26] = style + $[27] = t1 + $[28] = t2 + $[29] = t3 + } else { + t3 = $[29] + } + + let t4 + + if ( + $[30] !== autoFocus || + $[31] !== children || + $[32] !== onBlur || + $[33] !== onBlurCapture || + $[34] !== onClick || + $[35] !== onFocus || + $[36] !== onFocusCapture || + $[37] !== onKeyDown || + $[38] !== onKeyDownCapture || + $[39] !== onMouseDown || + $[40] !== onMouseUp || + $[41] !== onMouseDrag || + $[42] !== onMouseEnter || + $[43] !== onMouseLeave || + $[44] !== ref || + $[45] !== t3 || + $[46] !== tabIndex + ) { + t4 = ( + + {children} + + ) + $[30] = autoFocus + $[31] = children + $[32] = onBlur + $[33] = onBlurCapture + $[34] = onClick + $[35] = onFocus + $[36] = onFocusCapture + $[37] = onKeyDown + $[38] = onKeyDownCapture + $[39] = onMouseDown + $[40] = onMouseUp + $[41] = onMouseDrag + $[42] = onMouseEnter + $[43] = onMouseLeave + $[44] = ref + $[45] = t3 + $[46] = tabIndex + $[47] = t4 + } else { + t4 = $[47] + } + + return t4 +} + +export default Box +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlByb3BzV2l0aENoaWxkcmVuIiwiUmVmIiwiRXhjZXB0IiwiRE9NRWxlbWVudCIsIkNsaWNrRXZlbnQiLCJGb2N1c0V2ZW50IiwiS2V5Ym9hcmRFdmVudCIsIlN0eWxlcyIsIndhcm4iLCJ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E9BQUssQ0FBQyxDQUNDQyxhQUFhLENBQWJBLGNBQVksQ0FBQyxDQUNkRyxZQUFZLENBQVpBLGFBQVcsQ0FBQyxDQUNaQyxZQUFZLENBQVpBLGFBQVcsQ0FBQyxDQUNmSCxTQUFTLENBQVRBLFVBQVEsQ0FBQyxDQUNGQyxnQkFBZ0IsQ0FBaEJBLGlCQUFlLENBQUMsQ0FDM0IsS0FRTixDQVJNLENBQUFlLEVBUVAsQ0FBQyxDQUVBUixTQUFPLENBQ1YsRUF4QkEsT0F3QlU7SUFBQUYsQ0FBQSxPQUFBYixTQUFBO0lBQUFhLENBQUEsT0FBQUUsUUFBQTtJQUFBRixDQUFBLE9BQUFSLE1BQUE7SUFBQVEsQ0FBQSxPQUFBUCxhQUFBO0lBQUFPLENBQUEsT0FBQVosT0FBQTtJQUFBWSxDQUFBLE9BQUFWLE9BQUE7SUFBQVUsQ0FBQSxPQUFBVCxjQUFBO0lBQUFTLENBQUEsT0FBQU4sU0FBQTtJQUFBTSxDQUFBLE9BQUFMLGdCQUFBO0lBQUFLLENBQUEsT0FBQUosWUFBQTtJQUFBSSxDQUFBLE9BQUFILFlBQUE7SUFBQUcsQ0FBQSxPQUFBZixHQUFBO0lBQUFlLENBQUEsT0FBQVUsRUFBQTtJQUFBVixDQUFBLE9BQUFkLFFBQUE7SUFBQWMsQ0FBQSxPQUFBVyxFQUFBO0VBQUE7SUFBQUEsRUFBQSxHQUFBWCxDQUFBO0VBQUE7RUFBQSxPQXhCVlcsRUF3QlU7QUFBQTtBQUlkLGVBQWViLEdBQUciLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/Button.tsx b/ui-tui/packages/hermes-ink/src/ink/components/Button.tsx new file mode 100644 index 0000000000..e99034c6db --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/Button.tsx @@ -0,0 +1,236 @@ +import React, { type Ref, useEffect, useRef, useState } from 'react' +import { c as _c } from 'react/compiler-runtime' +import type { Except } from 'type-fest' + +import type { DOMElement } from '../dom.js' +import type { Styles } from '../styles.js' + +import Box from './Box.js' +type ButtonState = { + focused: boolean + hovered: boolean + active: boolean +} +export type Props = Except & { + ref?: Ref + /** + * Called when the button is activated via Enter, Space, or click. + */ + onAction: () => void + /** + * Tab order index. Defaults to 0 (in tab order). + * Set to -1 for programmatically focusable only. + */ + tabIndex?: number + /** + * Focus this button when it mounts. + */ + autoFocus?: boolean + /** + * Render prop receiving the interactive state. Use this to + * style children based on focus/hover/active — Button itself + * is intentionally unstyled. + * + * If not provided, children render as-is (no state-dependent styling). + */ + children: ((state: ButtonState) => React.ReactNode) | React.ReactNode +} + +function Button(t0) { + const $ = _c(30) + let autoFocus + let children + let onAction + let ref + let style + let t1 + + if ($[0] !== t0) { + ;({ onAction, tabIndex: t1, autoFocus, children, ref, ...style } = t0) + $[0] = t0 + $[1] = autoFocus + $[2] = children + $[3] = onAction + $[4] = ref + $[5] = style + $[6] = t1 + } else { + autoFocus = $[1] + children = $[2] + onAction = $[3] + ref = $[4] + style = $[5] + t1 = $[6] + } + + const tabIndex = t1 === undefined ? 0 : t1 + const [isFocused, setIsFocused] = useState(false) + const [isHovered, setIsHovered] = useState(false) + const [isActive, setIsActive] = useState(false) + const activeTimer = useRef(null) + let t2 + let t3 + + if ($[7] === Symbol.for('react.memo_cache_sentinel')) { + t2 = () => () => { + if (activeTimer.current) { + clearTimeout(activeTimer.current) + } + } + + t3 = [] + $[7] = t2 + $[8] = t3 + } else { + t2 = $[7] + t3 = $[8] + } + + useEffect(t2, t3) + let t4 + + if ($[9] !== onAction) { + t4 = e => { + if (e.key === 'return' || e.key === ' ') { + e.preventDefault() + setIsActive(true) + onAction() + + if (activeTimer.current) { + clearTimeout(activeTimer.current) + } + + activeTimer.current = setTimeout(_temp, 100, setIsActive) + } + } + + $[9] = onAction + $[10] = t4 + } else { + t4 = $[10] + } + + const handleKeyDown = t4 + let t5 + + if ($[11] !== onAction) { + t5 = _e => { + onAction() + } + + $[11] = onAction + $[12] = t5 + } else { + t5 = $[12] + } + + const handleClick = t5 + let t6 + + if ($[13] === Symbol.for('react.memo_cache_sentinel')) { + t6 = _e_0 => setIsFocused(true) + $[13] = t6 + } else { + t6 = $[13] + } + + const handleFocus = t6 + let t7 + + if ($[14] === Symbol.for('react.memo_cache_sentinel')) { + t7 = _e_1 => setIsFocused(false) + $[14] = t7 + } else { + t7 = $[14] + } + + const handleBlur = t7 + let t8 + + if ($[15] === Symbol.for('react.memo_cache_sentinel')) { + t8 = () => setIsHovered(true) + $[15] = t8 + } else { + t8 = $[15] + } + + const handleMouseEnter = t8 + let t9 + + if ($[16] === Symbol.for('react.memo_cache_sentinel')) { + t9 = () => setIsHovered(false) + $[16] = t9 + } else { + t9 = $[16] + } + + const handleMouseLeave = t9 + let t10 + + if ($[17] !== children || $[18] !== isActive || $[19] !== isFocused || $[20] !== isHovered) { + const state = { + focused: isFocused, + hovered: isHovered, + active: isActive + } + + t10 = typeof children === 'function' ? children(state) : children + $[17] = children + $[18] = isActive + $[19] = isFocused + $[20] = isHovered + $[21] = t10 + } else { + t10 = $[21] + } + + const content = t10 + let t11 + + if ( + $[22] !== autoFocus || + $[23] !== content || + $[24] !== handleClick || + $[25] !== handleKeyDown || + $[26] !== ref || + $[27] !== style || + $[28] !== tabIndex + ) { + t11 = ( + + {content} + + ) + $[22] = autoFocus + $[23] = content + $[24] = handleClick + $[25] = handleKeyDown + $[26] = ref + $[27] = style + $[28] = tabIndex + $[29] = t11 + } else { + t11 = $[29] + } + + return t11 +} + +function _temp(setter) { + return setter(false) +} + +export default Button +export type { ButtonState } +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlJlZiIsInVzZUNhbGxiYWNrIiwidXNlRWZmZWN0IiwidXNlUmVmIiwidXNlU3RhdGUiLCJFeGNlcHQiLCJET01FbGVtZW50IiwiQ2xpY2tFdmVudCIsIkZvY3VzRXZlbnQiLCJ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VJBLFNBQU8sQ0FBQyxDQUNQQyxTQUFTLENBQVRBLFVBQVEsQ0FBQyxDQUNUOEIsU0FBYSxDQUFiQSxjQUFZLENBQUMsQ0FDZkcsT0FBVyxDQUFYQSxZQUFVLENBQUMsQ0FDWEcsT0FBVyxDQUFYQSxZQUFVLENBQUMsQ0FDWkcsTUFBVSxDQUFWQSxXQUFTLENBQUMsQ0FDSkUsWUFBZ0IsQ0FBaEJBLGlCQUFlLENBQUMsQ0FDaEJFLFlBQWdCLENBQWhCQSxpQkFBZSxDQUFDLEtBQzFCbkMsS0FBSyxFQUVScUMsUUFBTSxDQUNULEVBYkMsR0FBRyxDQWFFO0lBQUF2QyxDQUFBLE9BQUFOLFNBQUE7SUFBQU0sQ0FBQSxPQUFBdUMsT0FBQTtJQUFBdkMsQ0FBQSxPQUFBMkIsV0FBQTtJQUFBM0IsQ0FBQSxPQUFBd0IsYUFBQTtJQUFBeEIsQ0FBQSxPQUFBVCxHQUFBO0lBQUFTLENBQUEsT0FBQUUsS0FBQTtJQUFBRixDQUFBLE9BQUFQLFFBQUE7SUFBQU8sQ0FBQSxPQUFBd0MsR0FBQTtFQUFBO0lBQUFBLEdBQUEsR0FBQXhDLENBQUE7RUFBQTtFQUFBLE9BYk53QyxHQWFNO0FBQUE7QUF0RVYsU0FBQWpCLE1BQUFrQixNQUFBO0VBQUEsT0E0Qm9CQSxNQUFNLENBQUMsS0FBSyxDQUFDO0FBQUE7QUE4Q2pDLGVBQWUzQyxNQUFNO0FBQ3JCLGNBQWNaLFdBQVciLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/ClockContext.tsx b/ui-tui/packages/hermes-ink/src/ink/components/ClockContext.tsx new file mode 100644 index 0000000000..99dfc2d883 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/ClockContext.tsx @@ -0,0 +1,133 @@ +import React, { createContext, type ReactNode, useEffect, useState } from 'react' +import { c as _c } from 'react/compiler-runtime' + +import { BLURRED_FRAME_INTERVAL_MS, FRAME_INTERVAL_MS } from '../constants.js' +import { useTerminalFocus } from '../hooks/use-terminal-focus.js' +export type Clock = { + subscribe: (onChange: () => void, keepAlive: boolean) => () => void + now: () => number + setTickInterval: (ms: number) => void +} + +export function createClock(tickIntervalMs: number): Clock { + const subscribers = new Map<() => void, boolean>() + let interval: ReturnType | null = null + let currentTickIntervalMs = tickIntervalMs + let startTime = 0 + // Snapshot of the current tick's time, ensuring all subscribers in the same + // tick see the same value (keeps animations synchronized) + let tickTime = 0 + + function tick(): void { + tickTime = Date.now() - startTime + + for (const onChange of subscribers.keys()) { + onChange() + } + } + + function updateInterval(): void { + const anyKeepAlive = [...subscribers.values()].some(Boolean) + + if (anyKeepAlive) { + if (interval) { + clearInterval(interval) + interval = null + } + + if (startTime === 0) { + startTime = Date.now() + } + + interval = setInterval(tick, currentTickIntervalMs) + } else if (interval) { + clearInterval(interval) + interval = null + } + } + + return { + subscribe(onChange, keepAlive) { + subscribers.set(onChange, keepAlive) + updateInterval() + + return () => { + subscribers.delete(onChange) + updateInterval() + } + }, + now() { + if (startTime === 0) { + startTime = Date.now() + } + + // When the clock interval is running, return the synchronized tickTime + // so all subscribers in the same tick see the same value. + // When paused (no keepAlive subscribers), return real-time to avoid + // returning a stale tickTime from the last tick before the pause. + if (interval && tickTime) { + return tickTime + } + + return Date.now() - startTime + }, + setTickInterval(ms) { + if (ms === currentTickIntervalMs) { + return + } + + currentTickIntervalMs = ms + updateInterval() + } + } +} + +export const ClockContext = createContext(null) + +// Own component so App.tsx doesn't re-render when the clock is created. +// The clock value is stable (created once via useState), so the provider +// never causes consumer re-renders on its own. +export function ClockProvider(t0: { readonly children: ReactNode }) { + const $ = _c(7) + + const { children } = t0 + + const [clock] = useState(_temp) + const focused = useTerminalFocus() + let t1 + let t2 + + if ($[0] !== clock || $[1] !== focused) { + t1 = () => { + clock.setTickInterval(focused ? FRAME_INTERVAL_MS : BLURRED_FRAME_INTERVAL_MS) + } + + t2 = [clock, focused] + $[0] = clock + $[1] = focused + $[2] = t1 + $[3] = t2 + } else { + t1 = $[2] + t2 = $[3] + } + + useEffect(t1, t2) + let t3 + + if ($[4] !== children || $[5] !== clock) { + t3 = {children} + $[4] = children + $[5] = clock + $[6] = t3 + } else { + t3 = $[6] + } + + return t3 +} + +function _temp() { + return createClock(FRAME_INTERVAL_MS) +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsImNyZWF0ZUNvbnRleHQiLCJ1c2VFZmZlY3QiLCJ1c2VTdGF0ZSIsIkZSQU1FX0lOVEVSVkFMX01TIiwidXNlVGVybWluYWxGb2N1cyIsIkNsb2NrIiwic3Vic2NyaWJlIiwib25DaGFuZ2UiLCJrZWVwQWxpdmUiLCJub3ciLCJzZXRUaWNrSW50ZXJ2YWwiLCJtcyIsImNyZWF0ZUNsb2NrIiwidGlja0ludGVydmFsTXMiLCJzdWJzY3JpYmVycyIsIk1hcCIsImludGVydmFsIiwiUmV0dXJuVHlwZSIsInNldEludGVydmFsIiwiY3VycmVudFRpY2tJbnRlcnZhbE1zIiwic3RhcnRUaW1lIiwidGlja1RpbWUiLCJ0aWNrIiwiRGF0ZSIsImtleXMiLCJ1cGRhdGVJbnRlcnZhbCIsImFueUtlZXBBbGl2ZSIsInZhbHVlcyIsInNvbWUiLCJCb29sZWFuIiwiY2xlYXJJbnRlcnZhbCIsInNldCIsImRlbGV0ZSIsIkNsb2NrQ29udGV4dCIsIkJMVVJSRURfVElDS19JTlRFUlZBTF9NUyIsIkNsb2NrUHJvdmlkZXIiLCJ0MCIsIiQiLCJfYyIsImNoaWxkcmVuIiwiY2xvY2siLCJfdGVtcCIsImZvY3VzZWQiLCJ0MSIsInQyIiwidDMiXSwic291cmNlcyI6WyJDbG9ja0NvbnRleHQudHN4Il0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBSZWFjdCwgeyBjcmVhdGVDb250ZXh0LCB1c2V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UFBQSxJQUFBRixDQUFBLFFBQUFHLEtBQUE7SUFFYkssRUFBQSwwQkFBOEJMLEtBQUssQ0FBTEEsTUFBSSxDQUFDLENBQUdELFNBQU8sQ0FBRSx3QkFBd0I7SUFBQUYsQ0FBQSxNQUFBRSxRQUFBO0lBQUFGLENBQUEsTUFBQUcsS0FBQTtJQUFBSCxDQUFBLE1BQUFRLEVBQUE7RUFBQTtJQUFBQSxFQUFBLEdBQUFSLENBQUE7RUFBQTtFQUFBLE9BQXZFUSxFQUF1RTtBQUFBO0FBZHpFLFNBQUFKLE1BQUE7RUFBQSxPQUswQjdCLFdBQVcsQ0FBQ1QsaUJBQWlCLENBQUM7QUFBQSIsImlnbm9yZUxpc3QiOltdfQ== diff --git a/ui-tui/packages/hermes-ink/src/ink/components/CursorDeclarationContext.ts b/ui-tui/packages/hermes-ink/src/ink/components/CursorDeclarationContext.ts new file mode 100644 index 0000000000..37356afa17 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/CursorDeclarationContext.ts @@ -0,0 +1,28 @@ +import { createContext } from 'react' + +import type { DOMElement } from '../dom.js' + +export type CursorDeclaration = { + /** Display column (terminal cell width) within the declared node */ + readonly relativeX: number + /** Line number within the declared node */ + readonly relativeY: number + /** The ink-box DOMElement whose yoga layout provides the absolute origin */ + readonly node: DOMElement +} + +/** + * Setter for the declared cursor position. + * + * The optional second argument makes `null` a conditional clear: the + * declaration is only cleared if the currently-declared node matches + * `clearIfNode`. This makes the hook safe for sibling components + * (e.g. list items) that transfer focus among themselves — without the + * node check, a newly-unfocused item's clear could clobber a + * newly-focused sibling's set depending on layout-effect order. + */ +export type CursorDeclarationSetter = (declaration: CursorDeclaration | null, clearIfNode?: DOMElement | null) => void + +const CursorDeclarationContext = createContext(() => {}) + +export default CursorDeclarationContext diff --git a/ui-tui/packages/hermes-ink/src/ink/components/ErrorOverview.tsx b/ui-tui/packages/hermes-ink/src/ink/components/ErrorOverview.tsx new file mode 100644 index 0000000000..9e87788e6c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/ErrorOverview.tsx @@ -0,0 +1,130 @@ +import { readFileSync } from 'fs' + +import codeExcerpt, { type CodeExcerpt } from 'code-excerpt' +import React from 'react' +import StackUtils from 'stack-utils' + +import Box from './Box.js' +import Text from './Text.js' + +// Error's source file is reported as file:///home/user/file.js +// This function removes the file://[cwd] part +const cleanupPath = (path: string | undefined): string | undefined => { + return path?.replace(`file://${process.cwd()}/`, '') +} + +let stackUtils: StackUtils | undefined + +function getStackUtils(): StackUtils { + return (stackUtils ??= new StackUtils({ + cwd: process.cwd(), + internals: StackUtils.nodeInternals() + })) +} + +type Props = { + readonly error: Error +} + +export default function ErrorOverview({ error }: Props) { + const stack = error.stack ? error.stack.split('\n').slice(1) : undefined + const origin = stack ? getStackUtils().parseLine(stack[0]!) : undefined + const filePath = cleanupPath(origin?.file) + let excerpt: CodeExcerpt[] | undefined + let lineWidth = 0 + + if (filePath && origin?.line) { + try { + const sourceCode = readFileSync(filePath, 'utf8') + excerpt = codeExcerpt(sourceCode, origin.line) + + if (excerpt) { + for (const { line } of excerpt) { + lineWidth = Math.max(lineWidth, String(line).length) + } + } + } catch { + // file not readable — skip source context + } + } + + return ( + + + + {' '} + ERROR{' '} + + + {error.message} + + + {origin && filePath && ( + + + {filePath}:{origin.line}:{origin.column} + + + )} + + {origin && excerpt && ( + + {excerpt.map(({ line: line_0, value }) => ( + + + + {String(line_0).padStart(lineWidth, ' ')}: + + + + + {' ' + value} + + + ))} + + )} + + {error.stack && ( + + {error.stack + .split('\n') + .slice(1) + .map(line_1 => { + const parsedLine = getStackUtils().parseLine(line_1) + + // If the line from the stack cannot be parsed, we print out the unparsed line. + if (!parsedLine) { + return ( + + - + {line_1} + + ) + } + + return ( + + - + {parsedLine.function} + + {' '} + ({cleanupPath(parsedLine.file) ?? ''}:{parsedLine.line}:{parsedLine.column}) + + + ) + })} + + )} + + ) +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZX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PUnsnICd9XG4gICAgICAgIDwvVGV4dD5cblxuICAgICAgICA8VGV4dD4ge2Vycm9yLm1lc3NhZ2V9PC9UZXh0PlxuICAgICAgPC9Cb3g+XG5cbiAgICAgIHtvcmlnaW4gJiYgZmlsZVBhdGggJiYgKFxuICAgICAgICA8Qm94IG1hcmdpblRvcD17MX0+XG4gICAgICAgICAgPFRleHQgZGltPlxuICAgICAgICAgICAge2ZpbGVQYXRofTp7b3JpZ2luLmxpbmV9OntvcmlnaW4uY29sdW1ufVxuICAgICAgICAgIDwvVGV4dD5cbiAgICAgICAgPC9Cb3g+XG4gICAgICApfVxuXG4gICAgICB7b3JpZ2luICYmIGV4Y2VycHQgJiYgKFxuICAgICAgICA8Qm94IG1hcmdpblRvcD17MX0gZmxleERpcmVjdGlvbj1cImNvbHVtblwiPlxuICAgICAgICAgIHtleGNlcnB0Lm1hcCgoeyBsaW5lLCB2YWx1ZSB9KSA9PiAoXG4gICAgICAgICAgICA8Qm94IGtleT17bGluZX0+XG4gICAgICAgICAgICAgIDxCb3ggd2lkdGg9e2xpbmVXaWR0aCArIDF9PlxuICAgICAgICAgICAgICAgIDxUZXh0XG4gICAgICAgICAgICAgICAgICBkaW09e2xpbmUgIT09IG9yaWdpbi5saW5lfVxuICAgICAgICAgICAgICAgICAgYmFja2dyb3VuZENvbG9yPXtcbiAgICAgICAgICAgICAgICAgICAgbGluZSA9PT0gb3JpZ2luLmxpbmUgPyAnYW5zaTpyZWQnIDogdW5kZWZpbmVkXG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICBjb2xvcj17bGluZSA9PT0gb3JpZ2luLmxpbmUgPyAnYW5zaTp3aGl0ZScgOiB1bmRlZmluZWR9XG4gICAgICAgICAgICAgICAgPlxuICAgICAgICAgICAgICAgICAge1N0cmluZyhsaW5lKS5wYWRTdGFydChsaW5lV2lkdGgsICcgJyl9OlxuICAgICAgICAgICAgICAgIDwvVGV4dD5cbiAgICAgICAgICAgICAgPC9Cb3g+XG5cbiAgICAgICAgICAgICAgPFRleHRcbiAgICAgICAgICAgICAgICBrZXk9e2xpbmV9XG4gICAgICAgICAgICAgICAgYmFja2dyb3VuZENvbG9yPXtsaW5lID09PSBvcmlnaW4ubGluZSA/ICdhbnNpOnJlZCcgOiB1bmRlZmluZWR9XG4gICAgICAgICAgICAgICAgY29sb3I9e2xpbmUgPT09IG9yaWdpbi5saW5lID8gJ2Fuc2k6d2hpdGUnIDogdW5kZWZpbmVkfVxuICAgICAgICAgICAgICA+XG4gICAgICAgICAgICAgICAgeycgJyArIHZhbHVlfVxuICAgICAgICAgICAgICA8L1RleHQ+XG4gICAgICAgICAgICA8L0JveD5cbiAgICAgICAgICApKX1cbiAgICAgICAgPC9Cb3g+XG4gICAgICApfVxuXG4gICAgICB7ZXJyb3Iuc3RhY2sgJiYgKFxuICAgICAgICA8Qm94IG1hcmdpblRvcD17MX0gZmxleERpcmVjdGlvbj1cImNvbHVtblwiPlxuICAgICAgICAgIHtlcnJvci5zdGFja1xuICAgICAgICAgICAgLnNwbGl0KCdcXG4nKVxuICAgICAgICAgICAgLnNsaWNlKDEpXG4gICAgICAgICAgICAubWFwKGxpbmUgPT4ge1xuICAgICAgICAgICAgICBjb25zdCBwYXJzZWRMaW5lID0gZ2V0U3RhY2tVdGlscygpLnBhcnNlTGluZShsaW5lKVxuXG4gICAgICAgICAgICAgIC8vIElmIHRoZSBsaW5lIGZyb20gdGhlIHN0YWNrIGNhbm5vdCBiZSBwYXJzZWQsIHdlIHByaW50IG91dCB0aGUgdW5wYXJzZWQgbGluZS5cbiAgICAgICAgICAgICAgaWYgKCFwYXJzZWRMaW5lKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIChcbiAgICAgICAgICAgICAgICAgIDxCb3gga2V5PXtsaW5lfT5cbiAgICAgICAgICAgICAgICAgICAgPFRleHQgZGltPi0gPC9UZXh0PlxuICAgICAgICAgICAgICAgICAgICA8VGV4dCBib2xkPntsaW5lfTwvVGV4dD5cbiAgICAgICAgICAgICAgICAgIDwvQm94PlxuICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICAgIHJldHVybiAoXG4gICAgICAgICAgICAgICAgPEJveCBrZXk9e2xpbmV9PlxuICAgICAgICAgICAgICAgICAgPFRleHQgZGltPi0gPC9UZXh0PlxuICAgICAgICAgICAgICAgICAgPFRleHQgYm9sZD57cGFyc2VkTGluZS5mdW5jdGlvbn08L1RleHQ+XG4gICAgICAgICAgICAgICAgICA8VGV4dCBkaW0+XG4gICAgICAgICAgICAgICAgICAgIHsnICd9XG4gICAgICAgICAgICAgICAgICAgICh7Y2xlYW51cFBhdGgocGFyc2VkTGluZS5maWxlKSA/PyAnJ306e3BhcnNlZExpbmUubGluZX06XG4gICAgICAgICAgICAgICAgICAgIHtwYXJzZWRMaW5lLmNvbHVtbn0pXG4gICAgICAgICAgICAgICAgICA8L1RleHQ+XG4gICAgICAgICAgICAgICAgPC9Cb3g+XG4gICAgICAgICAgICAgIClcbiAgICAgICAgICAgIH0pfVxuICAgICAgICA8L0JveD5cbiAgICAgICl9XG4gICAgPC9Cb3g+XG4gIClcbn1cbiJdLCJtYXBwaW5ncyI6IkFBQUEsT0FBT0EsV0FBVyxJQUFJLEtBQUtDLFdBQVcsUUFBUSxjQUFjO0FBQzVELFNBQVNDLFlBQVksUUFBUSxJQUFJO0FBQ2pDLE9BQU9DLEtBQUssTUFBTSxPQUFPO0FBQ3pCLE9BQU9DLFVBQVUsTUFBTSxhQUFhO0FBQ3BDLE9BQU9DLEdBQUcsTUFBTSxVQUFVO0FBQzFCLE9BQU9DLElBQUksTUFBTSxXQUFXOztBQUU1Qjs7QUFFQTtBQUNBO0FBQ0EsTUFBTUMsV0FBVyxHQUFHQSxDQUFDQyxJQUFJLEVBQUUsTUFBTSxHQUFHLFNBQVMsQ0FBQyxFQUFFLE1BQU0sR0FBRyxTQUFTLElBQUk7RUFDcEUsT0FBT0EsSUFBSSxFQUFFQyxPQUFPLENBQ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ElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQ0EsTUFBSSxDQUFDLEVBQUUsSUFBSTtBQUMzQyxrQkFBa0IsRUFBRSxHQUFHLENBQUM7UUFFVjtRQUVBLE9BQ0UsQ0FBQyxHQUFHLENBQUMsR0FBRyxDQUFDLENBQUNBLE1BQUksQ0FBQztBQUMvQixrQkFBa0IsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsRUFBRSxJQUFJO0FBQ3BDLGtCQUFrQixDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQ1csVUFBVSxDQUFDQyxRQUFRLENBQUMsRUFBRSxJQUFJO0FBQ3hELGtCQUFrQixDQUFDLElBQUksQ0FBQyxHQUFHO0FBQzNCLG9CQUFvQixDQUFDLEdBQUc7QUFDeEIscUJBQXFCLENBQUNuQyxXQUFXLENBQUNrQyxVQUFVLENBQUNkLElBQUksQ0FBQyxJQUFJLEVBQUUsQ0FBQyxDQUFDLENBQUNjLFVBQVUsQ0FBQ1gsSUFBSSxDQUFDO0FBQzNFLG9CQUFvQixDQUFDVyxVQUFVLENBQUNKLE1BQU0sQ0FBQztBQUN2QyxrQkFBa0IsRUFBRSxJQUFJO0FBQ3hCLGdCQUFnQixFQUFFLEdBQUcsQ0FBQztNQUVWLENBQUMsQ0FBQztBQUNkLFFBQVEsRUFBRSxHQUFHLENBQ047QUFDUCxJQUFJLEVBQUUsR0FBRyxDQUFDO0FBRVYiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/Link.tsx b/ui-tui/packages/hermes-ink/src/ink/components/Link.tsx new file mode 100644 index 0000000000..71c4914558 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/Link.tsx @@ -0,0 +1,53 @@ +import type { ReactNode } from 'react' +import React from 'react' +import { c as _c } from 'react/compiler-runtime' + +import { supportsHyperlinks } from '../supports-hyperlinks.js' + +import Text from './Text.js' +export type Props = { + readonly children?: ReactNode + readonly url: string + readonly fallback?: ReactNode +} + +export default function Link(t0: Props) { + const $ = _c(5) + + const { children, url, fallback } = t0 + + const content = children ?? url + + if (supportsHyperlinks()) { + let t1 + + if ($[0] !== content || $[1] !== url) { + t1 = ( + + {content} + + ) + $[0] = content + $[1] = url + $[2] = t1 + } else { + t1 = $[2] + } + + return t1 + } + + const t1 = fallback ?? content + let t2 + + if ($[3] !== t1) { + t2 = {t1} + $[3] = t1 + $[4] = t2 + } else { + t2 = $[4] + } + + return t2 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdE5vZGUiLCJSZWFjdCIsInN1cHBvcnRzSHlwZXJsaW5rcyIsIlRleHQiLCJQcm9wcyIsImNoaWxkcmVuIiwidXJsIiwiZmFsbGJhY2siLCJMaW5rIiwidDAiLCIkIiwiX2MiLCJjb250ZW50IiwidDEiLCJ0MiJdLCJzb3VyY2VzIjpbIkxpbmsudHN4Il0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB0eXBlIHsgUmVhY3ROb2RlIH0gZnJvbSAncmVhY3QnXG5pbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnXG5pbXBvcnQgeyBzdXBwb3J0c0h5cGVybGlua3MgfSBmcm9tICcuLi9zdXBwb3J0cy1oeXBlcmxpbmtzLmpzJ1xuaW1wb3J0IFRleHQgZnJvbSAnLi9UZXh0LmpzJ1xuXG5leHBvcnQgdHlwZSBQcm9wcyA9IHtcbiAgcmVhZG9ubHkgY2hpbGRyZW4/OiBSZWFjdE5vZGVcbiAgcmVhZG9ubHkgdXJsOiBzdHJpbmdcbiAgcmVhZG9ubHkgZmFsbGJhY2s/OiBSZWFjdE5vZGVcbn1cblxuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gTGluayh7XG4gIGNoaWxkcmVuLFxuICB1cmwsXG4gIGZhbGxiYWNrLFxufTogUHJvcHMpOiBSZWFjdC5SZWFjdE5vZGUge1xuICAvL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MsQ0FBQztJQUFBLElBQUFXLEVBQUE7SUFBQSxJQUFBSCxDQUFBLFFBQUFFLE9BQUEsSUFBQUYsQ0FBQSxRQUFBSixHQUFBO01BSXBCTyxFQUFBLElBQUMsSUFBSSxDQUNILFNBQXlDLENBQXpCUCxJQUFHLENBQUhBLElBQUUsQ0FBQyxDQUFHTSxRQUFNLENBQUUsRUFBOUIsUUFBeUMsQ0FDM0MsRUFGQyxJQUFJLENBRUU7TUFBQUYsQ0FBQSxNQUFBRSxPQUFBO01BQUFGLENBQUEsTUFBQUosR0FBQTtNQUFBSSxDQUFBLE1BQUFHLEVBQUE7SUFBQTtNQUFBQSxFQUFBLEdBQUFILENBQUE7SUFBQTtJQUFBLE9BRlBHLEVBRU87RUFBQTtFQUlHLE1BQUFBLEVBQUEsR0FBQU4sUUFBbUIsSUFBbkJLLE9BQW1CO0VBQUEsSUFBQUUsRUFBQTtFQUFBLElBQUFKLENBQUEsUUFBQUcsRUFBQTtJQUExQkMsRUFBQSxJQUFDLElBQUksQ0FBRSxDQUFBRCxFQUFrQixDQUFFLEVBQTFCLElBQUksQ0FBNkI7SUFBQUgsQ0FBQSxNQUFBRyxFQUFBO0lBQUFILENBQUEsTUFBQUksRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQUosQ0FBQTtFQUFBO0VBQUEsT0FBbENJLEVBQWtDO0FBQUEiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/Newline.tsx b/ui-tui/packages/hermes-ink/src/ink/components/Newline.tsx new file mode 100644 index 0000000000..4010dc9ffd --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/Newline.tsx @@ -0,0 +1,43 @@ +import React from 'react' +import { c as _c } from 'react/compiler-runtime' +export type Props = { + /** + * Number of newlines to insert. + * + * @default 1 + */ + readonly count?: number +} + +/** + * Adds one or more newline (\n) characters. Must be used within components. + */ +export default function Newline(t0: Props) { + const $ = _c(4) + + const { count: t1 } = t0 + + const count = t1 === undefined ? 1 : t1 + let t2 + + if ($[0] !== count) { + t2 = '\n'.repeat(count) + $[0] = count + $[1] = t2 + } else { + t2 = $[1] + } + + let t3 + + if ($[2] !== t2) { + t3 = {t2} + $[2] = t2 + $[3] = t3 + } else { + t3 = $[3] + } + + return t3 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlByb3BzIiwiY291bnQiLCJOZXdsaW5lIiwidDAiLCIkIiwiX2MiLCJ0MSIsInVuZGVmaW5lZCIsInQyIiwicmVwZWF0IiwidDMiXSwic291cmNlcyI6WyJOZXdsaW5lLnRzeCJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnXG5cbmV4cG9ydCB0eXBlIFByb3BzID0ge1xuICAvKipcbiAgICogTnVtYmVyIG9mIG5ld2xpbmVzIHRvIGluc2VydC5cbiAgICpcbiAgICogQGRlZmF1bHQgMVxuICAgKi9cbiAgcmVhZG9ubHkgY291bnQ/OiBudW1iZXJcbn1cblxuLyoqXG4gKiBBZGRzIG9uZSBvciBtb3JlIG5ld2xpbmUgKFxcbikgY2hhcmFjdGVycy4gTXVzdCBiZSB1c2VkIHdpdGhpbiA8VGV4dD4gY29tcG9uZW50cy5cbiAqL1xuZXhwb3J0IGRlZmF1bHQgZnVuY3Rpb24gTmV3bGluZSh7IGNvdW50ID0gMSB9OiBQcm9wcykge1xuICByZXR1cm4gPGluay10ZXh0PnsnXFxuJy5yZXBlYXQoY291bnQpfTwvaW5rLXRleHQ+XG59XG4iXSwibWFwcGluZ3MiOiI7QUFBQSxPQUFPQSxLQUFLLE1BQU0sT0FBTztBQUV6QixPQUFPLEtBQUtDLEtBQUssR0FBRztFQUNsQjtBQUNGO0FBQ0E7QUFDQTtBQUNBO0VBQ0UsU0FBU0MsS0FBSyxDQUFDLEVBQUUsTUFBTTtBQUN6QixDQUFDOztBQUVEO0FBQ0E7QUFDQTtBQUNBLGVBQWUsU0FBQUMsUUFBQUMsRUFBQTtFQUFBLE1BQUFDLENBQUEsR0FBQUMsRUFBQTtFQUFpQjtJQUFBSixLQUFBLEVBQUFLO0VBQUEsSUFBQUgsRUFBb0I7RUFBbEIsTUFBQUYsS0FBQSxHQUFBSyxFQUFTLEtBQVRDLFNBQVMsR0FBVCxDQUFTLEdBQVRELEVBQVM7RUFBQSxJQUFBRSxFQUFBO0VBQUEsSUFBQUosQ0FBQSxRQUFBSCxLQUFBO0lBQ3ZCTyxFQUFBLE9BQUksQ0FBQUMsTUFBTyxDQUFDUixLQUFLLENBQUM7SUFBQUcsQ0FBQSxNQUFBSCxLQUFBO0lBQUFHLENBQUEsTUFBQUksRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQUosQ0FBQTtFQUFBO0VBQUEsSUFBQU0sRUFBQTtFQUFBLElBQUFOLENBQUEsUUFBQUksRUFBQTtJQUE3QkUsRUFBQSxZQUF5QyxDQUE5QixDQUFBRixFQUFpQixDQUFFLEVBQTlCLFFBQXlDO0lBQUFKLENBQUEsTUFBQUksRUFBQTtJQUFBSixDQUFBLE1BQUFNLEVBQUE7RUFBQTtJQUFBQSxFQUFBLEdBQUFOLENBQUE7RUFBQTtFQUFBLE9BQXpDTSxFQUF5QztBQUFBIiwiaWdub3JlTGlzdCI6W119 diff --git a/ui-tui/packages/hermes-ink/src/ink/components/NoSelect.tsx b/ui-tui/packages/hermes-ink/src/ink/components/NoSelect.tsx new file mode 100644 index 0000000000..79078189e4 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/NoSelect.tsx @@ -0,0 +1,73 @@ +import React from 'react' +import { c as _c } from 'react/compiler-runtime' + +import Box, { type Props as BoxProps } from './Box.js' +type Props = Omit & { + /** + * Extend the exclusion zone from column 0 to this box's right edge, + * for every row this box occupies. Use for gutters rendered inside a + * wider indented container (e.g. a diff inside a tool message row): + * without this, a multi-row drag picks up the container's leading + * indent on rows below the prefix. + * + * @default false + */ + fromLeftEdge?: boolean +} + +/** + * Marks its contents as non-selectable in fullscreen text selection. + * Cells inside this box are skipped by both the selection highlight and + * the copied text — the gutter stays visually unchanged while the user + * drags, making it clear what will be copied. + * + * Use to fence off gutters (line numbers, diff +/- sigils, list bullets) + * so click-drag over rendered code yields clean pasteable content: + * + * + * 42 + + * const x = 1 + * + * + * Only affects alt-screen text selection ( with mouse + * tracking). No-op in the main-screen scrollback render where the + * terminal's native selection is used instead. + */ +export function NoSelect(t0: Props) { + const $ = _c(8) + let boxProps + let children + let fromLeftEdge + + if ($[0] !== t0) { + ;({ children, fromLeftEdge, ...boxProps } = t0) + $[0] = t0 + $[1] = boxProps + $[2] = children + $[3] = fromLeftEdge + } else { + boxProps = $[1] + children = $[2] + fromLeftEdge = $[3] + } + + const t1 = fromLeftEdge ? 'from-left-edge' : true + let t2 + + if ($[4] !== boxProps || $[5] !== children || $[6] !== t1) { + t2 = ( + + {children} + + ) + $[4] = boxProps + $[5] = children + $[6] = t1 + $[7] = t2 + } else { + t2 = $[7] + } + + return t2 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlByb3BzV2l0aENoaWxkcmVuIiwiQm94IiwiUHJvcHMiLCJCb3hQcm9wcyIsIk9taXQiLCJmcm9tTGVmdEVkZ2UiLCJOb1NlbGVjdCIsInQwIiwiJCIsIl9jIiwiYm94UHJvcHMiLCJjaGlsZHJlbiIsInQxIiwidDIiXSwic291cmNlcyI6WyJOb1NlbGVjdC50c3giXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFJlYWN0LCB7IHR5cGUgUHJvcHNXaXRoQ2hpbGRyZW4gfSBmcm9tICdyZWFjdCdcbmltcG9ydCBCb3gsIHsgdHlwZSBQcm9wcyBhcyBCb3hQcm9wcyB9IGZyb20gJy4vQm94LmpzJ1xuXG50eXBlIFByb3BzID0gT21pdDxCb3hQcm9wcywgJ25vU2VsZWN0Jz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FBQUUsUUFBQTtJQUFBRixDQUFBLE1BQUFHLFFBQUE7SUFBQUgsQ0FBQSxNQUFBSSxFQUFBO0lBQUFKLENBQUEsTUFBQUssRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQUwsQ0FBQTtFQUFBO0VBQUEsT0FGTkssRUFFTTtBQUFBIiwiaWdub3JlTGlzdCI6W119 diff --git a/ui-tui/packages/hermes-ink/src/ink/components/RawAnsi.tsx b/ui-tui/packages/hermes-ink/src/ink/components/RawAnsi.tsx new file mode 100644 index 0000000000..b5bd8f2536 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/RawAnsi.tsx @@ -0,0 +1,61 @@ +import React from 'react' +import { c as _c } from 'react/compiler-runtime' +type Props = { + /** + * Pre-rendered ANSI lines. Each element must be exactly one terminal row + * (already wrapped to `width` by the producer) with ANSI escape codes inline. + */ + lines: string[] + /** Column width the producer wrapped to. Sent to Yoga as the fixed leaf width. */ + width: number +} + +/** + * Bypass the → React tree → Yoga → squash → re-serialize roundtrip for + * content that is already terminal-ready. + * + * Use this when an external renderer (e.g. the ColorDiff NAPI module) has + * already produced ANSI-escaped, width-wrapped output. A normal mount + * reparses that output into one React per style span, lays out each + * span as a Yoga flex child, then walks the tree to re-emit the same escape + * codes it was given. For a long transcript full of syntax-highlighted diffs + * that roundtrip is the dominant cost of the render. + * + * This component emits a single Yoga leaf with a constant-time measure func + * (width × lines.length) and hands the joined string straight to output.write(), + * which already splits on '\n' and parses ANSI into the screen buffer. + */ +export function RawAnsi(t0: Props) { + const $ = _c(6) + + const { lines, width } = t0 + + if (lines.length === 0) { + return null + } + + let t1 + + if ($[0] !== lines) { + t1 = lines.join('\n') + $[0] = lines + $[1] = t1 + } else { + t1 = $[1] + } + + let t2 + + if ($[2] !== lines.length || $[3] !== t1 || $[4] !== width) { + t2 = + $[2] = lines.length + $[3] = t1 + $[4] = width + $[5] = t2 + } else { + t2 = $[5] + } + + return t2 +} +//# sourceMappingURL=data:application/json;charset=utf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QUFBLE1BQUFHLEVBQUE7SUFBQUgsQ0FBQSxNQUFBSCxLQUFBO0lBQUFHLENBQUEsTUFBQUssRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQUwsQ0FBQTtFQUFBO0VBQUEsT0FKRkssRUFJRTtBQUFBIiwiaWdub3JlTGlzdCI6W119 diff --git a/ui-tui/packages/hermes-ink/src/ink/components/ScrollBox.tsx b/ui-tui/packages/hermes-ink/src/ink/components/ScrollBox.tsx new file mode 100644 index 0000000000..aac8f2b334 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/ScrollBox.tsx @@ -0,0 +1,285 @@ +import '../global.d.ts' + +import React, { type PropsWithChildren, type Ref, useImperativeHandle, useRef, useState } from 'react' +import type { Except } from 'type-fest' + +import { markScrollActivity } from '../../bootstrap/state.js' +import type { DOMElement } from '../dom.js' +import { markDirty, scheduleRenderFrom } from '../dom.js' +import { markCommitStart } from '../reconciler.js' +import type { Styles } from '../styles.js' + +import Box from './Box.js' +export type ScrollBoxHandle = { + scrollTo: (y: number) => void + scrollBy: (dy: number) => void + /** + * Scroll so `el`'s top is at the viewport top (plus `offset`). Unlike + * scrollTo which bakes a number that's stale by the time the throttled + * render fires, this defers the position read to render time — + * render-node-to-output reads `el.yogaNode.getComputedTop()` in the + * SAME Yoga pass that computes scrollHeight. Deterministic. One-shot. + */ + scrollToElement: (el: DOMElement, offset?: number) => void + scrollToBottom: () => void + getScrollTop: () => number + getPendingDelta: () => number + getScrollHeight: () => number + /** + * Like getScrollHeight, but reads Yoga directly instead of the cached + * value written by render-node-to-output (throttled, up to 16ms stale). + * Use when you need a fresh value in useLayoutEffect after a React commit + * that grew content. Slightly more expensive (native Yoga call). + */ + getFreshScrollHeight: () => number + getViewportHeight: () => number + /** + * Absolute screen-buffer row of the first visible content line (inside + * padding). Used for drag-to-scroll edge detection. + */ + getViewportTop: () => number + /** + * True when scroll is pinned to the bottom. Set by scrollToBottom, the + * initial stickyScroll attribute, and by the renderer when positional + * follow fires (scrollTop at prevMax, content grows). Cleared by + * scrollTo/scrollBy. Stable signal for "at bottom" that doesn't depend on + * layout values (unlike scrollTop+viewportH >= scrollHeight). + */ + isSticky: () => boolean + /** + * Subscribe to imperative scroll changes (scrollTo/scrollBy/scrollToBottom). + * Does NOT fire for stickyScroll updates done by the Ink renderer — those + * happen during Ink's render phase after React has committed. Callers that + * care about the sticky case should treat "at bottom" as a fallback. + */ + subscribe: (listener: () => void) => () => void + /** + * Set the render-time scrollTop clamp to the currently-mounted children's + * coverage span. Called by useVirtualScroll after computing its range; + * render-node-to-output clamps scrollTop to [min, max] so burst scrollTo + * calls that race past React's async re-render show the edge of mounted + * content instead of blank spacer. Pass undefined to disable (sticky, + * cold start). + */ + setClampBounds: (min: number | undefined, max: number | undefined) => void +} +export type ScrollBoxProps = Except & { + ref?: Ref + /** + * When true, automatically pins scroll position to the bottom when content + * grows. Unset manually via scrollTo/scrollBy to break the stickiness. + */ + stickyScroll?: boolean +} + +/** + * A Box with `overflow: scroll` and an imperative scroll API. + * + * Children are laid out at their full Yoga-computed height inside a + * constrained container. At render time, only children intersecting the + * visible window (scrollTop..scrollTop+height) are rendered (viewport + * culling). Content is translated by -scrollTop and clipped to the box bounds. + * + * Works best inside a fullscreen (constrained-height root) Ink tree. + */ +function ScrollBox({ children, ref, stickyScroll, ...style }: PropsWithChildren): React.ReactNode { + const domRef = useRef(null) + // scrollTo/scrollBy bypass React: they mutate scrollTop on the DOM node, + // mark it dirty, and call the root's throttled scheduleRender directly. + // The Ink renderer reads scrollTop from the node — no React state needed, + // no reconciler overhead per wheel event. The microtask defer coalesces + // multiple scrollBy calls in one input batch (discreteUpdates) into one + // render — otherwise scheduleRender's leading edge fires on the FIRST + // event before subsequent events mutate scrollTop. scrollToBottom still + // forces a React render: sticky is attribute-observed, no DOM-only path. + const [, forceRender] = useState(0) + const listenersRef = useRef(new Set<() => void>()) + const renderQueuedRef = useRef(false) + + const notify = () => { + for (const l of listenersRef.current) { + l() + } + } + + function scrollMutated(el: DOMElement): void { + // Signal background intervals (IDE poll, LSP poll, GCS fetch, orphan + // check) to skip their next tick — they compete for the event loop and + // contributed to 1402ms max frame gaps during scroll drain. + markScrollActivity() + markDirty(el) + markCommitStart() + notify() + + if (renderQueuedRef.current) { + return + } + + renderQueuedRef.current = true + queueMicrotask(() => { + renderQueuedRef.current = false + scheduleRenderFrom(el) + }) + } + + useImperativeHandle( + ref, + (): ScrollBoxHandle => ({ + scrollTo(y: number) { + const el = domRef.current + + if (!el) { + return + } + + // Explicit false overrides the DOM attribute so manual scroll + // breaks stickiness. Render code checks ?? precedence. + el.stickyScroll = false + el.pendingScrollDelta = undefined + el.scrollAnchor = undefined + el.scrollTop = Math.max(0, Math.floor(y)) + scrollMutated(el) + }, + scrollToElement(el: DOMElement, offset = 0) { + const box = domRef.current + + if (!box) { + return + } + + box.stickyScroll = false + box.pendingScrollDelta = undefined + box.scrollAnchor = { + el, + offset + } + scrollMutated(box) + }, + scrollBy(dy: number) { + const el = domRef.current + + if (!el) { + return + } + + el.stickyScroll = false + // Wheel input cancels any in-flight anchor seek — user override. + el.scrollAnchor = undefined + // Accumulate in pendingScrollDelta; renderer drains it at a capped + // rate so fast flicks show intermediate frames. Pure accumulator: + // scroll-up followed by scroll-down naturally cancels. + el.pendingScrollDelta = (el.pendingScrollDelta ?? 0) + Math.floor(dy) + scrollMutated(el) + }, + scrollToBottom() { + const el = domRef.current + + if (!el) { + return + } + + el.pendingScrollDelta = undefined + el.stickyScroll = true + markDirty(el) + notify() + forceRender(n => n + 1) + }, + getScrollTop() { + return domRef.current?.scrollTop ?? 0 + }, + getPendingDelta() { + // Accumulated-but-not-yet-drained delta. useVirtualScroll needs + // this to mount the union [committed, committed+pending] range — + // otherwise intermediate drain frames find no children (blank). + return domRef.current?.pendingScrollDelta ?? 0 + }, + getScrollHeight() { + return domRef.current?.scrollHeight ?? 0 + }, + getFreshScrollHeight() { + const content = domRef.current?.childNodes[0] as DOMElement | undefined + + return content?.yogaNode?.getComputedHeight() ?? domRef.current?.scrollHeight ?? 0 + }, + getViewportHeight() { + return domRef.current?.scrollViewportHeight ?? 0 + }, + getViewportTop() { + return domRef.current?.scrollViewportTop ?? 0 + }, + isSticky() { + const el = domRef.current + + if (!el) { + return false + } + + return el.stickyScroll ?? Boolean(el.attributes['stickyScroll']) + }, + subscribe(listener: () => void) { + listenersRef.current.add(listener) + + return () => listenersRef.current.delete(listener) + }, + setClampBounds(min, max) { + const el = domRef.current + + if (!el) { + return + } + + el.scrollClampMin = min + el.scrollClampMax = max + } + }), + // notify/scrollMutated are inline (no useCallback) but only close over + // refs + imports — stable. Empty deps avoids rebuilding the handle on + // every render (which re-registers the ref = churn). + + [] + ) + + // Structure: outer viewport (overflow:scroll, constrained height) > + // inner content (flexGrow:1, flexShrink:0 — fills at least the viewport + // but grows beyond it for tall content). flexGrow:1 lets children use + // spacers to pin elements to the bottom of the scroll area. Yoga's + // Overflow.Scroll prevents the viewport from growing to fit the content. + // The renderer computes scrollHeight from the content box and culls + // content's children based on scrollTop. + // + // stickyScroll is passed as a DOM attribute (via ink-box directly) so it's + // available on the first render — ref callbacks fire after the initial + // commit, which is too late for the first frame. + return ( + { + domRef.current = el + + if (el) { + el.scrollTop ??= 0 + } + }} + style={{ + flexWrap: 'nowrap', + flexDirection: style.flexDirection ?? 'row', + flexGrow: style.flexGrow ?? 0, + flexShrink: style.flexShrink ?? 1, + ...style, + overflowX: 'scroll', + overflowY: 'scroll' + }} + {...(stickyScroll + ? { + stickyScroll: true + } + : {})} + > + + {children} + + + ) +} + +export default ScrollBox +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIlByb3BzV2l0aENoaWxkcmVuIiwiUmVmIiwidXNlSW1wZXJhdGl2ZUhhbmRsZSIsInVzZVJlZiIsInVzZVN0YXRlIiwiRXhjZXB0IiwibWFya1Njcm9sbEFjdGl2aXR5IiwiRE9NRWxlbWVudCIsIm1hc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BQUlBLEVBQUUsRUFBRUEsRUFBRSxDQUFDbUMsU0FBUyxLQUFLLENBQUM7RUFDNUIsQ0FBQyxDQUFDLENBQ0YsS0FBSyxDQUFDLENBQUM7SUFDTGtCLFFBQVEsRUFBRSxRQUFRO0lBQ2xCQyxhQUFhLEVBQUVsQyxLQUFLLENBQUNrQyxhQUFhLElBQUksS0FBSztJQUMzQ0MsUUFBUSxFQUFFbkMsS0FBSyxDQUFDbUMsUUFBUSxJQUFJLENBQUM7SUFDN0JDLFVBQVUsRUFBRXBDLEtBQUssQ0FBQ29DLFVBQVUsSUFBSSxDQUFDO0lBQ2pDLEdBQUdwQyxLQUFLO0lBQ1JxQyxTQUFTLEVBQUUsUUFBUTtJQUNuQkMsU0FBUyxFQUFFO0VBQ2IsQ0FBQyxDQUFDLENBQ0YsSUFBS3pDLFlBQVksR0FBRztJQUFFQSxZQUFZLEVBQUU7RUFBSyxDQUFDLEdBQUcsQ0FBQyxDQUFFLENBQUM7QUFFdkQsTUFBTSxDQUFDLEdBQUcsQ0FBQyxhQUFhLENBQUMsUUFBUSxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLFVBQVUsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEtBQUssQ0FBQyxNQUFNO0FBQzFFLFFBQVEsQ0FBQ0UsUUFBUTtBQUNqQixNQUFNLEVBQUUsR0FBRztBQUNYLElBQUksRUFBRSxPQUFPLENBQUM7QUFFZDtBQUVBLGVBQWVELFNBQVMiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/Spacer.tsx b/ui-tui/packages/hermes-ink/src/ink/components/Spacer.tsx new file mode 100644 index 0000000000..3ed7609b84 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/Spacer.tsx @@ -0,0 +1,23 @@ +import React from 'react' +import { c as _c } from 'react/compiler-runtime' + +import Box from './Box.js' + +/** + * A flexible space that expands along the major axis of its containing layout. + * It's useful as a shortcut for filling all the available spaces between elements. + */ +export default function Spacer() { + const $ = _c(1) + let t0 + + if ($[0] === Symbol.for('react.memo_cache_sentinel')) { + t0 = + $[0] = t0 + } else { + t0 = $[0] + } + + return t0 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsIkJveCIsIlNwYWNlciIsIiQiLCJfYyIsInQwIiwiU3ltYm9sIiwiZm9yIl0sInNvdXJjZXMiOlsiU3BhY2VyLnRzeCJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnXG5pbXBvcnQgQm94IGZyb20gJy4vQm94LmpzJ1xuXG4vKipcbiAqIEEgZmxleGlibGUgc3BhY2UgdGhhdCBleHBhbmRzIGFsb25nIHRoZSBtYWpvciBheGlzIG9mIGl0cyBjb250YWluaW5nIGxheW91dC5cbiAqIEl0J3MgdXNlZnVsIGFzIGEgc2hvcnRjdXQgZm9yIGZpbGxpbmcgYWxsIHRoZSBhdmFpbGFibGUgc3BhY2VzIGJldHdlZW4gZWxlbWVudHMuXG4gKi9cbmV4cG9ydCBkZWZhdWx0IGZ1bmN0aW9uIFNwYWNlcigpIHtcbiAgcmV0dXJuIDxCb3ggZmxleEdyb3c9ezF9IC8+XG59XG4iXSwibWFwcGluZ3MiOiI7QUFBQSxPQUFPQSxLQUFLLE1BQU0sT0FBTztBQUN6QixPQUFPQyxHQUFHLE1BQU0sVUFBVTs7QUFFMUI7QUFDQTtBQUNBO0FBQ0E7QUFDQSxlQUFlLFNBQUFDLE9BQUE7RUFBQSxNQUFBQyxDQUFBLEdBQUFDLEVBQUE7RUFBQSxJQUFBQyxFQUFBO0VBQUEsSUFBQUYsQ0FBQSxRQUFBRyxNQUFBLENBQUFDLEdBQUE7SUFDTkYsRUFBQSxJQUFDLEdBQUcsQ0FBVyxRQUFDLENBQUQsR0FBQyxHQUFJO0lBQUFGLENBQUEsTUFBQUUsRUFBQTtFQUFBO0lBQUFBLEVBQUEsR0FBQUYsQ0FBQTtFQUFBO0VBQUEsT0FBcEJFLEVBQW9CO0FBQUEiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/StdinContext.ts b/ui-tui/packages/hermes-ink/src/ink/components/StdinContext.ts new file mode 100644 index 0000000000..c6e9334dfa --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/StdinContext.ts @@ -0,0 +1,25 @@ +import { createContext } from 'react' + +import { EventEmitter } from '../events/emitter.js' +import type { TerminalQuerier } from '../terminal-querier.js' + +export type Props = { + readonly stdin: NodeJS.ReadStream + readonly setRawMode: (value: boolean) => void + readonly isRawModeSupported: boolean + readonly exitOnCtrlC: boolean + readonly inputEmitter: EventEmitter + readonly querier: TerminalQuerier | null +} + +const StdinContext = createContext({ + stdin: process.stdin, + inputEmitter: new EventEmitter(), + setRawMode() {}, + isRawModeSupported: false, + exitOnCtrlC: true, + querier: null +}) + +StdinContext.displayName = 'StdinContext' +export default StdinContext diff --git a/ui-tui/packages/hermes-ink/src/ink/components/TerminalFocusContext.tsx b/ui-tui/packages/hermes-ink/src/ink/components/TerminalFocusContext.tsx new file mode 100644 index 0000000000..e5f1acdd68 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/TerminalFocusContext.tsx @@ -0,0 +1,63 @@ +import React, { createContext, type ReactNode, useSyncExternalStore } from 'react' +import { c as _c } from 'react/compiler-runtime' + +import { + getTerminalFocused, + getTerminalFocusState, + subscribeTerminalFocus, + type TerminalFocusState +} from '../terminal-focus-state.js' +export type { TerminalFocusState } +export type TerminalFocusContextProps = { + readonly isTerminalFocused: boolean + readonly terminalFocusState: TerminalFocusState +} + +const TerminalFocusContext = createContext({ + isTerminalFocused: true, + terminalFocusState: 'unknown' +}) + +TerminalFocusContext.displayName = 'TerminalFocusContext' + +// Separate component so App.tsx doesn't re-render on focus changes. +// Children are a stable prop reference, so they don't re-render either — +// only components that consume the context will re-render. +export function TerminalFocusProvider(t0: { readonly children: ReactNode }) { + const $ = _c(6) + + const { children } = t0 + + const isTerminalFocused = useSyncExternalStore(subscribeTerminalFocus, getTerminalFocused) + const terminalFocusState = useSyncExternalStore(subscribeTerminalFocus, getTerminalFocusState) + let t1 + + if ($[0] !== isTerminalFocused || $[1] !== terminalFocusState) { + t1 = { + isTerminalFocused, + terminalFocusState + } + $[0] = isTerminalFocused + $[1] = terminalFocusState + $[2] = t1 + } else { + t1 = $[2] + } + + const value = t1 + let t2 + + if ($[3] !== children || $[4] !== value) { + t2 = {children} + $[3] = children + $[4] = value + $[5] = t2 + } else { + t2 = $[5] + } + + return t2 +} + +export default TerminalFocusContext +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdCIsImNyZWF0ZUNvbnRleHQiLCJ1c2VNZW1vIiwidXNlU3luY0V4dGVybmFsU3RvcmUiLCJnZXRUZXJtaW5hbEZvY3VzZWQiLCJnZXRUZXJtaW5hbEZvY3VzU3RhdGUiLCJzdWJzY3JpYmVUZXJtaW5hbEZvY3VzIiwiVGVybWluYWxGb2N1c1N0YXRlIiwiVGVybWluYWxGb2N1c0NvbnRleHRQcm9wcyIsImlzVGVybWluYWxGb2N1c2VkIiwidGVybWluYWxGb2N1c1N0YXRlIiwiVGVybWluYWxGb2N1c0NvbnRleHQiLCJkaXNwbGF5TmFtZSIsIlRlcm1pbmFsRm9jdXNQcm92aWRlciIsInQwIiwiJCIsIl9jIiwiY2hpbGRyZW4iLCJ0MSIsInZhbHVlIiwidDIiXSwic291cmNlcyI6WyJUZXJtaW5hbEZvY3VzQ29udGV4dC50c3giXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IFJlYWN0LCB7IGNyZWF0ZUNvbnRleHQsIHVzZU1lbW8sIHVzZVN5bmNFeHRlcm5hbFN0b3JlIH0gZnJvbSAncmVhY3QnXG5pbXBvcnQge1xuICBnZXRUZXJ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BQUE7SUFHQ0MsRUFBQSxrQ0FBc0NELEtBQUssQ0FBTEEsTUFBSSxDQUFDLENBQ3hDRixTQUFPLENBQ1YsZ0NBQWdDO0lBQUFGLENBQUEsTUFBQUUsUUFBQTtJQUFBRixDQUFBLE1BQUFJLEtBQUE7SUFBQUosQ0FBQSxNQUFBSyxFQUFBO0VBQUE7SUFBQUEsRUFBQSxHQUFBTCxDQUFBO0VBQUE7RUFBQSxPQUZoQ0ssRUFFZ0M7QUFBQTtBQUlwQyxlQUFlVCxvQkFBb0IiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/TerminalSizeContext.tsx b/ui-tui/packages/hermes-ink/src/ink/components/TerminalSizeContext.tsx new file mode 100644 index 0000000000..ec743b3a0e --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/TerminalSizeContext.tsx @@ -0,0 +1,7 @@ +import { createContext } from 'react' +export type TerminalSize = { + columns: number + rows: number +} +export const TerminalSizeContext = createContext(null) +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJjcmVhdGVDb250ZXh0IiwiVGVybWluYWxTaXplIiwiY29sdW1ucyIsInJvd3MiLCJUZXJtaW5hbFNpemVDb250ZXh0Il0sInNvdXJjZXMiOlsiVGVybWluYWxTaXplQ29udGV4dC50c3giXSwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHsgY3JlYXRlQ29udGV4dCB9IGZyb20gJ3JlYWN0J1xuXG5leHBvcnQgdHlwZSBUZXJtaW5hbFNpemUgPSB7XG4gIGNvbHVtbnM6IG51bWJlclxuICByb3dzOiBudW1iZXJcbn1cblxuZXhwb3J0IGNvbnN0IFRlcm1pbmFsU2l6ZUNvbnRleHQgPSBjcmVhdGVDb250ZXh0PFRlcm1pbmFsU2l6ZSB8IG51bGw+KG51bGwpXG4iXSwibWFwcGluZ3MiOiJBQUFBLFNBQVNBLGFBQWEsUUFBUSxPQUFPO0FBRXJDLE9BQU8sS0FBS0MsWUFBWSxHQUFHO0VBQ3pCQyxPQUFPLEVBQUUsTUFBTTtFQUNmQyxJQUFJLEVBQUUsTUFBTTtBQUNkLENBQUM7QUFFRCxPQUFPLE1BQU1DLG1CQUFtQixHQUFHSixhQUFhLENBQUNDLFlBQVksR0FBRyxJQUFJLENBQUMsQ0FBQyxJQUFJLENBQUMiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/components/Text.tsx b/ui-tui/packages/hermes-ink/src/ink/components/Text.tsx new file mode 100644 index 0000000000..ea2a74c9a6 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/components/Text.tsx @@ -0,0 +1,296 @@ +import type { ReactNode } from 'react' +import React from 'react' +import { c as _c } from 'react/compiler-runtime' + +import type { Color, Styles } from '../styles.js' +type BaseProps = { + /** + * Change text color. Accepts a raw color value (rgb, hex, ansi). + */ + readonly color?: Color + + /** + * Same as `color`, but for background. + */ + readonly backgroundColor?: Color + + /** + * Make the text italic. + */ + readonly italic?: boolean + + /** + * Make the text underlined. + */ + readonly underline?: boolean + + /** + * Make the text crossed with a line. + */ + readonly strikethrough?: boolean + + /** + * Inverse background and foreground colors. + */ + readonly inverse?: boolean + + /** + * This property tells Ink to wrap or truncate text if its width is larger than container. + * If `wrap` is passed (by default), Ink will wrap text and split it into multiple lines. + * If `truncate-*` is passed, Ink will truncate text instead, which will result in one line of text with the rest cut off. + */ + readonly wrap?: Styles['textWrap'] + readonly children?: ReactNode +} + +/** + * Bold and dim are mutually exclusive in terminals. + * This type ensures you can use one or the other, but not both. + */ +type WeightProps = + | { + bold?: never + dim?: never + } + | { + bold: boolean + dim?: never + } + | { + dim: boolean + bold?: never + } +export type Props = BaseProps & WeightProps + +const memoizedStylesForWrap: Record, Styles> = { + wrap: { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'wrap' + }, + 'wrap-trim': { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'wrap-trim' + }, + end: { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'end' + }, + middle: { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'middle' + }, + 'truncate-end': { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'truncate-end' + }, + truncate: { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'truncate' + }, + 'truncate-middle': { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'truncate-middle' + }, + 'truncate-start': { + flexGrow: 0, + flexShrink: 1, + flexDirection: 'row', + textWrap: 'truncate-start' + } +} as const + +/** + * This component can display text, and change its style to make it colorful, bold, underline, italic or strikethrough. + */ +export default function Text(t0: Props) { + const $ = _c(29) + + const { + color, + backgroundColor, + bold, + dim, + italic: t1, + underline: t2, + strikethrough: t3, + inverse: t4, + wrap: t5, + children + } = t0 + + const italic = t1 === undefined ? false : t1 + const underline = t2 === undefined ? false : t2 + const strikethrough = t3 === undefined ? false : t3 + const inverse = t4 === undefined ? false : t4 + const wrap = t5 === undefined ? 'wrap' : t5 + + if (children === undefined || children === null) { + return null + } + + let t6 + + if ($[0] !== color) { + t6 = color && { + color + } + $[0] = color + $[1] = t6 + } else { + t6 = $[1] + } + + let t7 + + if ($[2] !== backgroundColor) { + t7 = backgroundColor && { + backgroundColor + } + $[2] = backgroundColor + $[3] = t7 + } else { + t7 = $[3] + } + + let t8 + + if ($[4] !== dim) { + t8 = dim && { + dim + } + $[4] = dim + $[5] = t8 + } else { + t8 = $[5] + } + + let t9 + + if ($[6] !== bold) { + t9 = bold && { + bold + } + $[6] = bold + $[7] = t9 + } else { + t9 = $[7] + } + + let t10 + + if ($[8] !== italic) { + t10 = italic && { + italic + } + $[8] = italic + $[9] = t10 + } else { + t10 = $[9] + } + + let t11 + + if ($[10] !== underline) { + t11 = underline && { + underline + } + $[10] = underline + $[11] = t11 + } else { + t11 = $[11] + } + + let t12 + + if ($[12] !== strikethrough) { + t12 = strikethrough && { + strikethrough + } + $[12] = strikethrough + $[13] = t12 + } else { + t12 = $[13] + } + + let t13 + + if ($[14] !== inverse) { + t13 = inverse && { + inverse + } + $[14] = inverse + $[15] = t13 + } else { + t13 = $[15] + } + + let t14 + + if ( + $[16] !== t10 || + $[17] !== t11 || + $[18] !== t12 || + $[19] !== t13 || + $[20] !== t6 || + $[21] !== t7 || + $[22] !== t8 || + $[23] !== t9 + ) { + t14 = { + ...t6, + ...t7, + ...t8, + ...t9, + ...t10, + ...t11, + ...t12, + ...t13 + } + $[16] = t10 + $[17] = t11 + $[18] = t12 + $[19] = t13 + $[20] = t6 + $[21] = t7 + $[22] = t8 + $[23] = t9 + $[24] = t14 + } else { + t14 = $[24] + } + + const textStyles = t14 + const t15 = memoizedStylesForWrap[wrap] + let t16 + + if ($[25] !== children || $[26] !== t15 || $[27] !== textStyles) { + t16 = ( + + {children} + + ) + $[25] = children + $[26] = t15 + $[27] = textStyles + $[28] = t16 + } else { + t16 = $[28] + } + + return t16 +} +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJSZWFjdE5vZGUiLCJSZWFjdCIsIkNvbG9yIiwiU3R5bGVzIiwiVGV4dFN0eWxlcyIsIkJhc2VQcm9wcyIsImNvbG9yIiwiYmFja2dyb3VuZENvbG9yIiwiaXRhbGljIiwidW5kZXJsaW5lIiwic3RyaWtldGhyb3VnaCIsImludmVyc2UiLCJ3cmFwIiwiY2hpbGRyZW4iLCJXZWlnaHRQcm9wcyIsImJvbGQiLCJkaW0iLCJQcm9wcyIsIm1lbW9pemVkU3R5bGVzRm9yV3JhcCIsIlJlY29yZCIsIk5vbk51bGxhYmxlIiwiZmxleEdyb3ciLCJmbGV4U2hyaW5rIiwiZmxleERpcmVjdGlvbiIsInRleHRXcmFwIiwiZW5kIiwibWlkZGxlIiwidHJ1bmNhdGUiLCJjb25zdCIsIlRleHQi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BQWhCLENBQUE7RUFBQTtFQVRELE1BQUFpQixVQUFBLEdBQStCRCxHQVM5QjtFQUdrQixNQUFBRSxHQUFBLEdBQUEvQixxQkFBcUIsQ0FBQ04sSUFBSSxDQUFDO0VBQUEsSUFBQXNDLEdBQUE7RUFBQSxJQUFBbkIsQ0FBQSxTQUFBbEIsUUFBQSxJQUFBa0IsQ0FBQSxTQUFBa0IsR0FBQSxJQUFBbEIsQ0FBQSxTQUFBaUIsVUFBQTtJQUE1Q0UsR0FBQSxZQUVXLENBRk0sS0FBMkIsQ0FBM0IsQ0FBQUQsR0FBMEIsQ0FBQyxDQUFjRCxVQUFVLENBQVZBLFdBQVMsQ0FBQyxDQUNqRW5DLFNBQU8sQ0FDVixFQUZBLFFBRVc7SUFBQWtCLENBQUEsT0FBQWxCLFFBQUE7SUFBQWtCLENBQUEsT0FBQWtCLEdBQUE7SUFBQWxCLENBQUEsT0FBQWlCLFVBQUE7SUFBQWpCLENBQUEsT0FBQW1CLEdBQUE7RUFBQTtJQUFBQSxHQUFBLEdBQUFuQixDQUFBO0VBQUE7RUFBQSxPQUZYbUIsR0FFVztBQUFBIiwiaWdub3JlTGlzdCI6W119 diff --git a/ui-tui/packages/hermes-ink/src/ink/constants.ts b/ui-tui/packages/hermes-ink/src/ink/constants.ts new file mode 100644 index 0000000000..1846997c0c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/constants.ts @@ -0,0 +1,6 @@ +// Shared frame interval for render throttling and animations (~60fps). +export const FRAME_INTERVAL_MS = 16 + +// Keep clock-driven animations at full speed when terminal focus changes. +// We still pause entirely when there are no keepAlive subscribers. +export const BLURRED_FRAME_INTERVAL_MS = FRAME_INTERVAL_MS diff --git a/ui-tui/packages/hermes-ink/src/ink/cursor.ts b/ui-tui/packages/hermes-ink/src/ink/cursor.ts new file mode 100644 index 0000000000..fd37816712 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/cursor.ts @@ -0,0 +1,5 @@ +export type Cursor = { + x: number + y: number + visible: boolean +} diff --git a/ui-tui/packages/hermes-ink/src/ink/devtools.ts b/ui-tui/packages/hermes-ink/src/ink/devtools.ts new file mode 100644 index 0000000000..73b0c9448d --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/devtools.ts @@ -0,0 +1,2 @@ +/** Optional react-devtools hook; package may be absent. */ +export {} diff --git a/ui-tui/packages/hermes-ink/src/ink/dom.ts b/ui-tui/packages/hermes-ink/src/ink/dom.ts new file mode 100644 index 0000000000..6c4b198304 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/dom.ts @@ -0,0 +1,438 @@ +import type { FocusManager } from './focus.js' +import { createLayoutNode } from './layout/engine.js' +import type { LayoutNode } from './layout/node.js' +import { LayoutMeasureMode } from './layout/node.js' +import measureText from './measure-text.js' +import { addPendingClear, nodeCache } from './node-cache.js' +import squashTextNodes from './squash-text-nodes.js' +import type { Styles, TextStyles } from './styles.js' +import { expandTabs } from './tabstops.js' +import wrapText from './wrap-text.js' + +type InkNode = { + parentNode: DOMElement | undefined + yogaNode?: LayoutNode + style: Styles +} + +export type TextName = '#text' +export type ElementNames = + | 'ink-root' + | 'ink-box' + | 'ink-text' + | 'ink-virtual-text' + | 'ink-link' + | 'ink-progress' + | 'ink-raw-ansi' + +export type NodeNames = ElementNames | TextName + +export type DOMElement = { + nodeName: ElementNames + attributes: Record + childNodes: DOMNode[] + textStyles?: TextStyles + + // Internal properties + onComputeLayout?: () => void + onRender?: () => void + onImmediateRender?: () => void + // Used to skip empty renders during React 19's effect double-invoke in test mode + hasRenderedContent?: boolean + + // When true, this node needs re-rendering + dirty: boolean + // Set by the reconciler's hideInstance/unhideInstance; survives style updates. + isHidden?: boolean + // Event handlers set by the reconciler for the capture/bubble dispatcher. + // Stored separately from attributes so handler identity changes don't + // mark dirty and defeat the blit optimization. + _eventHandlers?: Record + + // Scroll state for overflow: 'scroll' boxes. scrollTop is the number of + // rows the content is scrolled down by. scrollHeight/scrollViewportHeight + // are computed at render time and stored for imperative access. stickyScroll + // auto-pins scrollTop to the bottom when content grows. + scrollTop?: number + // Accumulated scroll delta not yet applied to scrollTop. The renderer + // drains this at SCROLL_MAX_PER_FRAME rows/frame so fast flicks show + // intermediate frames instead of one big jump. Direction reversal + // naturally cancels (pure accumulator, no target tracking). + pendingScrollDelta?: number + // Render-time clamp bounds for virtual scroll. useVirtualScroll writes + // the currently-mounted children's coverage span; render-node-to-output + // clamps scrollTop to stay within it. Prevents blank screen when + // scrollTo's direct write races past React's async re-render — instead + // of painting spacer (blank), the renderer holds at the edge of mounted + // content until React catches up (next commit updates these bounds and + // the clamp releases). Undefined = no clamp (sticky-scroll, cold start). + scrollClampMin?: number + scrollClampMax?: number + scrollHeight?: number + scrollViewportHeight?: number + scrollViewportTop?: number + stickyScroll?: boolean + // Set by ScrollBox.scrollToElement; render-node-to-output reads + // el.yogaNode.getComputedTop() (FRESH — same Yoga pass as scrollHeight) + // and sets scrollTop = top + offset, then clears this. Unlike an + // imperative scrollTo(N) which bakes in a number that's stale by the + // time the throttled render fires, the element ref defers the position + // read to paint time. One-shot. + scrollAnchor?: { el: DOMElement; offset: number } + // Only set on ink-root. The document owns focus — any node can + // reach it by walking parentNode, like browser getRootNode(). + focusManager?: FocusManager +} & InkNode + +export type TextNode = { + nodeName: TextName + nodeValue: string +} & InkNode + +export type DOMNode = T extends { + nodeName: infer U +} + ? U extends '#text' + ? TextNode + : DOMElement + : never + +export type DOMNodeAttribute = boolean | string | number + +export const createNode = (nodeName: ElementNames): DOMElement => { + const needsYogaNode = nodeName !== 'ink-virtual-text' && nodeName !== 'ink-link' && nodeName !== 'ink-progress' + + const node: DOMElement = { + nodeName, + style: {}, + attributes: {}, + childNodes: [], + parentNode: undefined, + yogaNode: needsYogaNode ? createLayoutNode() : undefined, + dirty: false + } + + if (nodeName === 'ink-text') { + node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node)) + } else if (nodeName === 'ink-raw-ansi') { + node.yogaNode?.setMeasureFunc(measureRawAnsiNode.bind(null, node)) + } + + return node +} + +export const appendChildNode = (node: DOMElement, childNode: DOMElement): void => { + if (childNode.parentNode) { + removeChildNode(childNode.parentNode, childNode) + } + + childNode.parentNode = node + node.childNodes.push(childNode) + + if (childNode.yogaNode) { + node.yogaNode?.insertChild(childNode.yogaNode, node.yogaNode.getChildCount()) + } + + markDirty(node) +} + +export const insertBeforeNode = (node: DOMElement, newChildNode: DOMNode, beforeChildNode: DOMNode): void => { + if (newChildNode.parentNode) { + removeChildNode(newChildNode.parentNode, newChildNode) + } + + newChildNode.parentNode = node + + const index = node.childNodes.indexOf(beforeChildNode) + + if (index >= 0) { + // Calculate yoga index BEFORE modifying childNodes. + // We can't use DOM index directly because some children (like ink-progress, + // ink-link, ink-virtual-text) don't have yogaNodes, so DOM indices don't + // match yoga indices. + let yogaIndex = 0 + + if (newChildNode.yogaNode && node.yogaNode) { + for (let i = 0; i < index; i++) { + if (node.childNodes[i]?.yogaNode) { + yogaIndex++ + } + } + } + + node.childNodes.splice(index, 0, newChildNode) + + if (newChildNode.yogaNode && node.yogaNode) { + node.yogaNode.insertChild(newChildNode.yogaNode, yogaIndex) + } + + markDirty(node) + + return + } + + node.childNodes.push(newChildNode) + + if (newChildNode.yogaNode) { + node.yogaNode?.insertChild(newChildNode.yogaNode, node.yogaNode.getChildCount()) + } + + markDirty(node) +} + +export const removeChildNode = (node: DOMElement, removeNode: DOMNode): void => { + if (removeNode.yogaNode) { + removeNode.parentNode?.yogaNode?.removeChild(removeNode.yogaNode) + } + + // Collect cached rects from the removed subtree so they can be cleared + collectRemovedRects(node, removeNode) + + removeNode.parentNode = undefined + + const index = node.childNodes.indexOf(removeNode) + + if (index >= 0) { + node.childNodes.splice(index, 1) + } + + markDirty(node) +} + +function collectRemovedRects(parent: DOMElement, removed: DOMNode, underAbsolute = false): void { + if (removed.nodeName === '#text') { + return + } + + const elem = removed as DOMElement + // If this node or any ancestor in the removed subtree was absolute, + // its painted pixels may overlap non-siblings — flag for global blit + // disable. Normal-flow removals only affect direct siblings, which + // hasRemovedChild already handles. + const isAbsolute = underAbsolute || elem.style.position === 'absolute' + const cached = nodeCache.get(elem) + + if (cached) { + addPendingClear(parent, cached, isAbsolute) + nodeCache.delete(elem) + } + + for (const child of elem.childNodes) { + collectRemovedRects(parent, child, isAbsolute) + } +} + +export const setAttribute = (node: DOMElement, key: string, value: DOMNodeAttribute): void => { + // Skip 'children' - React handles children via appendChild/removeChild, + // not attributes. React always passes a new children reference, so + // tracking it as an attribute would mark everything dirty every render. + if (key === 'children') { + return + } + + // Skip if unchanged + if (node.attributes[key] === value) { + return + } + + node.attributes[key] = value + markDirty(node) +} + +export const setStyle = (node: DOMNode, style: Styles): void => { + // Compare style properties to avoid marking dirty unnecessarily. + // React creates new style objects on every render even when unchanged. + if (stylesEqual(node.style, style)) { + return + } + + node.style = style + markDirty(node) +} + +export const setTextStyles = (node: DOMElement, textStyles: TextStyles): void => { + // Same dirty-check guard as setStyle: React (and buildTextStyles in Text.tsx) + // allocate a new textStyles object on every render even when values are + // unchanged, so compare by value to avoid markDirty -> yoga re-measurement + // on every Text re-render. + if (shallowEqual(node.textStyles, textStyles)) { + return + } + + node.textStyles = textStyles + markDirty(node) +} + +function stylesEqual(a: Styles, b: Styles): boolean { + return shallowEqual(a, b) +} + +function shallowEqual(a: T | undefined, b: T | undefined): boolean { + // Fast path: same object reference (or both undefined) + if (a === b) { + return true + } + + if (a === undefined || b === undefined) { + return false + } + + // Get all keys from both objects + const aKeys = Object.keys(a) as (keyof T)[] + const bKeys = Object.keys(b) as (keyof T)[] + + // Different number of properties + if (aKeys.length !== bKeys.length) { + return false + } + + // Compare each property + for (const key of aKeys) { + if (a[key] !== b[key]) { + return false + } + } + + return true +} + +export const createTextNode = (text: string): TextNode => { + const node: TextNode = { + nodeName: '#text', + nodeValue: text, + yogaNode: undefined, + parentNode: undefined, + style: {} + } + + setTextNodeValue(node, text) + + return node +} + +const measureTextNode = function ( + node: DOMNode, + width: number, + widthMode: LayoutMeasureMode +): { width: number; height: number } { + const rawText = node.nodeName === '#text' ? node.nodeValue : squashTextNodes(node) + + // Expand tabs for measurement (worst case: 8 spaces each). + // Actual tab expansion happens in output.ts based on screen position. + const text = expandTabs(rawText) + + const dimensions = measureText(text, width) + + // Text fits into container, no need to wrap + if (dimensions.width <= width) { + return dimensions + } + + // This is happening when is shrinking child nodes and layout asks + // if we can fit this text node in a <1px space, so we just say "no" + if (dimensions.width >= 1 && width > 0 && width < 1) { + return dimensions + } + + // For text with embedded newlines (pre-wrapped content), avoid re-wrapping + // at measurement width when layout is asking for intrinsic size (Undefined mode). + // This prevents height inflation during min/max size checks. + // + // However, when layout provides an actual constraint (Exactly or AtMost mode), + // we must respect it and measure at that width. Otherwise, if the actual + // rendering width is smaller than the natural width, the text will wrap to + // more lines than layout expects, causing content to be truncated. + if (text.includes('\n') && widthMode === LayoutMeasureMode.Undefined) { + const effectiveWidth = Math.max(width, dimensions.width) + + return measureText(text, effectiveWidth) + } + + const textWrap = node.style?.textWrap ?? 'wrap' + const wrappedText = wrapText(text, width, textWrap) + + return measureText(wrappedText, width) +} + +// ink-raw-ansi nodes hold pre-rendered ANSI strings with known dimensions. +// No stringWidth, no wrapping, no tab expansion — the producer (e.g. ColorDiff) +// already wrapped to the target width and each line is exactly one terminal row. +const measureRawAnsiNode = function (node: DOMElement): { + width: number + height: number +} { + return { + width: node.attributes['rawWidth'] as number, + height: node.attributes['rawHeight'] as number + } +} + +/** + * Mark a node and all its ancestors as dirty for re-rendering. + * Also marks yoga dirty for text remeasurement if this is a text node. + */ +export const markDirty = (node?: DOMNode): void => { + let current: DOMNode | undefined = node + let markedYoga = false + + while (current) { + if (current.nodeName !== '#text') { + ;(current as DOMElement).dirty = true + + // Only mark yoga dirty on leaf nodes that have measure functions + if (!markedYoga && (current.nodeName === 'ink-text' || current.nodeName === 'ink-raw-ansi') && current.yogaNode) { + current.yogaNode.markDirty() + markedYoga = true + } + } + + current = current.parentNode + } +} + +// Walk to root and call its onRender (the throttled scheduleRender). Use for +// DOM-level mutations (scrollTop changes) that should trigger an Ink frame +// without going through React's reconciler. Pair with markDirty() so the +// renderer knows which subtree to re-evaluate. +export const scheduleRenderFrom = (node?: DOMNode): void => { + let cur: DOMNode | undefined = node + + while (cur?.parentNode) { + cur = cur.parentNode + } + + if (cur && cur.nodeName !== '#text') { + ;(cur as DOMElement).onRender?.() + } +} + +export const setTextNodeValue = (node: TextNode, text: string): void => { + if (typeof text !== 'string') { + text = String(text) + } + + // Skip if unchanged + if (node.nodeValue === text) { + return + } + + node.nodeValue = text + markDirty(node) +} + +function isDOMElement(node: DOMElement | TextNode): node is DOMElement { + return node.nodeName !== '#text' +} + +// Clear yogaNode references recursively before freeing. +// freeRecursive() frees the node and ALL its children, so we must clear +// all yogaNode references to prevent dangling pointers. +export const clearYogaNodeReferences = (node: DOMElement | TextNode): void => { + if ('childNodes' in node) { + for (const child of node.childNodes) { + clearYogaNodeReferences(child) + } + } + + node.yogaNode = undefined +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/click-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/click-event.ts new file mode 100644 index 0000000000..1f58659a89 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/click-event.ts @@ -0,0 +1,38 @@ +import { Event } from './event.js' + +/** + * Mouse click event. Fired on left-button release without drag, only when + * mouse tracking is enabled (i.e. inside ). + * + * Bubbles from the deepest hit node up through parentNode. Call + * stopImmediatePropagation() to prevent ancestors' onClick from firing. + */ +export class ClickEvent extends Event { + /** 0-indexed screen column of the click */ + readonly col: number + /** 0-indexed screen row of the click */ + readonly row: number + /** + * Click column relative to the current handler's Box (col - box.x). + * Recomputed by dispatchClick before each handler fires, so an onClick + * on a container sees coords relative to that container, not to any + * child the click landed on. + */ + localCol = 0 + /** Click row relative to the current handler's Box (row - box.y). */ + localRow = 0 + /** + * True if the clicked cell has no visible content (unwritten in the + * screen buffer — both packed words are 0). Handlers can check this to + * ignore clicks on blank space to the right of text, so accidental + * clicks on empty terminal space don't toggle state. + */ + readonly cellIsBlank: boolean + + constructor(col: number, row: number, cellIsBlank: boolean) { + super() + this.col = col + this.row = row + this.cellIsBlank = cellIsBlank + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/dispatcher.ts b/ui-tui/packages/hermes-ink/src/ink/events/dispatcher.ts new file mode 100644 index 0000000000..1357da1dda --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/dispatcher.ts @@ -0,0 +1,242 @@ +import { + ContinuousEventPriority, + DefaultEventPriority, + DiscreteEventPriority, + NoEventPriority +} from 'react-reconciler/constants.js' + +import { logError } from '../../utils/log.js' + +import { HANDLER_FOR_EVENT } from './event-handlers.js' +import type { EventTarget, TerminalEvent } from './terminal-event.js' + +// -- + +type DispatchListener = { + node: EventTarget + handler: (event: TerminalEvent) => void + phase: 'capturing' | 'at_target' | 'bubbling' +} + +function getHandler( + node: EventTarget, + eventType: string, + capture: boolean +): ((event: TerminalEvent) => void) | undefined { + const handlers = node._eventHandlers + + if (!handlers) { + return undefined + } + + const mapping = HANDLER_FOR_EVENT[eventType] + + if (!mapping) { + return undefined + } + + const propName = capture ? mapping.capture : mapping.bubble + + if (!propName) { + return undefined + } + + return handlers[propName] as ((event: TerminalEvent) => void) | undefined +} + +/** + * Collect all listeners for an event in dispatch order. + * + * Uses react-dom's two-phase accumulation pattern: + * - Walk from target to root + * - Capture handlers are prepended (unshift) → root-first + * - Bubble handlers are appended (push) → target-first + * + * Result: [root-cap, ..., parent-cap, target-cap, target-bub, parent-bub, ..., root-bub] + */ +function collectListeners(target: EventTarget, event: TerminalEvent): DispatchListener[] { + const listeners: DispatchListener[] = [] + + let node: EventTarget | undefined = target + + while (node) { + const isTarget = node === target + + const captureHandler = getHandler(node, event.type, true) + const bubbleHandler = getHandler(node, event.type, false) + + if (captureHandler) { + listeners.unshift({ + node, + handler: captureHandler, + phase: isTarget ? 'at_target' : 'capturing' + }) + } + + if (bubbleHandler && (event.bubbles || isTarget)) { + listeners.push({ + node, + handler: bubbleHandler, + phase: isTarget ? 'at_target' : 'bubbling' + }) + } + + node = node.parentNode + } + + return listeners +} + +/** + * Execute collected listeners with propagation control. + * + * Before each handler, calls event._prepareForTarget(node) so event + * subclasses can do per-node setup. + */ +function processDispatchQueue(listeners: DispatchListener[], event: TerminalEvent): void { + let previousNode: EventTarget | undefined + + for (const { node, handler, phase } of listeners) { + if (event._isImmediatePropagationStopped()) { + break + } + + if (event._isPropagationStopped() && node !== previousNode) { + break + } + + event._setEventPhase(phase) + event._setCurrentTarget(node) + event._prepareForTarget(node) + + try { + handler(event) + } catch (error) { + logError(error) + } + + previousNode = node + } +} + +// -- + +/** + * Map terminal event types to React scheduling priorities. + * Mirrors react-dom's getEventPriority() switch. + */ +function getEventPriority(eventType: string): number { + switch (eventType) { + case 'keydown': + + case 'keyup': + + case 'click': + + case 'focus': + + case 'blur': + + case 'paste': + return DiscreteEventPriority as number + + case 'resize': + + case 'scroll': + + case 'mousemove': + return ContinuousEventPriority as number + + default: + return DefaultEventPriority as number + } +} + +// -- + +type DiscreteUpdates = (fn: (a: A, b: B) => boolean, a: A, b: B, c: undefined, d: undefined) => boolean + +/** + * Owns event dispatch state and the capture/bubble dispatch loop. + * + * The reconciler host config reads currentEvent and currentUpdatePriority + * to implement resolveUpdatePriority, resolveEventType, and + * resolveEventTimeStamp — mirroring how react-dom's host config reads + * ReactDOMSharedInternals and window.event. + * + * discreteUpdates is injected after construction (by InkReconciler) + * to break the import cycle. + */ +export class Dispatcher { + currentEvent: TerminalEvent | null = null + currentUpdatePriority: number = DefaultEventPriority as number + discreteUpdates: DiscreteUpdates | null = null + + /** + * Infer event priority from the currently-dispatching event. + * Called by the reconciler host config's resolveUpdatePriority + * when no explicit priority has been set. + */ + resolveEventPriority(): number { + if (this.currentUpdatePriority !== (NoEventPriority as number)) { + return this.currentUpdatePriority + } + + if (this.currentEvent) { + return getEventPriority(this.currentEvent.type) + } + + return DefaultEventPriority as number + } + + /** + * Dispatch an event through capture and bubble phases. + * Returns true if preventDefault() was NOT called. + */ + dispatch(target: EventTarget, event: TerminalEvent): boolean { + const previousEvent = this.currentEvent + this.currentEvent = event + + try { + event._setTarget(target) + + const listeners = collectListeners(target, event) + processDispatchQueue(listeners, event) + + event._setEventPhase('none') + event._setCurrentTarget(null) + + return !event.defaultPrevented + } finally { + this.currentEvent = previousEvent + } + } + + /** + * Dispatch with discrete (sync) priority. + * For user-initiated events: keyboard, click, focus, paste. + */ + dispatchDiscrete(target: EventTarget, event: TerminalEvent): boolean { + if (!this.discreteUpdates) { + return this.dispatch(target, event) + } + + return this.discreteUpdates((t, e) => this.dispatch(t, e), target, event, undefined, undefined) + } + + /** + * Dispatch with continuous priority. + * For high-frequency events: resize, scroll, mouse move. + */ + dispatchContinuous(target: EventTarget, event: TerminalEvent): boolean { + const previousPriority = this.currentUpdatePriority + + try { + this.currentUpdatePriority = ContinuousEventPriority as number + + return this.dispatch(target, event) + } finally { + this.currentUpdatePriority = previousPriority + } + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/emitter.ts b/ui-tui/packages/hermes-ink/src/ink/events/emitter.ts new file mode 100644 index 0000000000..d00c4d9e3c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/emitter.ts @@ -0,0 +1,40 @@ +import { EventEmitter as NodeEventEmitter } from 'events' + +import { Event } from './event.js' + +// Similar to node's builtin EventEmitter, but is also aware of our `Event` +// class, and so `emit` respects `stopImmediatePropagation()`. +export class EventEmitter extends NodeEventEmitter { + constructor() { + super() + // Disable the default maxListeners warning. In React, many components + // can legitimately listen to the same event (e.g., useInput hooks). + // The default limit of 10 causes spurious warnings. + this.setMaxListeners(0) + } + + override emit(type: string | symbol, ...args: unknown[]): boolean { + // Delegate to node for `error`, since it's not treated like a normal event + if (type === 'error') { + return super.emit(type, ...args) + } + + const listeners = this.rawListeners(type) + + if (listeners.length === 0) { + return false + } + + const ccEvent = args[0] instanceof Event ? args[0] : null + + for (const listener of listeners) { + listener.apply(this, args) + + if (ccEvent?.didStopImmediatePropagation()) { + break + } + } + + return true + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/event-handlers.ts b/ui-tui/packages/hermes-ink/src/ink/events/event-handlers.ts new file mode 100644 index 0000000000..1750dbeee5 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/event-handlers.ts @@ -0,0 +1,84 @@ +import type { ClickEvent } from './click-event.js' +import type { FocusEvent } from './focus-event.js' +import type { KeyboardEvent } from './keyboard-event.js' +import type { MouseEvent } from './mouse-event.js' +import type { PasteEvent } from './paste-event.js' +import type { ResizeEvent } from './resize-event.js' + +type KeyboardEventHandler = (event: KeyboardEvent) => void +type FocusEventHandler = (event: FocusEvent) => void +type PasteEventHandler = (event: PasteEvent) => void +type ResizeEventHandler = (event: ResizeEvent) => void +type ClickEventHandler = (event: ClickEvent) => void +type MouseEventHandler = (event: MouseEvent) => void +type HoverEventHandler = () => void + +/** + * Props for event handlers on Box and other host components. + * + * Follows the React/DOM naming convention: + * - onEventName: handler for bubble phase + * - onEventNameCapture: handler for capture phase + */ +export type EventHandlerProps = { + onKeyDown?: KeyboardEventHandler + onKeyDownCapture?: KeyboardEventHandler + + onFocus?: FocusEventHandler + onFocusCapture?: FocusEventHandler + onBlur?: FocusEventHandler + onBlurCapture?: FocusEventHandler + + onPaste?: PasteEventHandler + onPasteCapture?: PasteEventHandler + + onResize?: ResizeEventHandler + + onClick?: ClickEventHandler + onMouseDown?: MouseEventHandler + onMouseUp?: MouseEventHandler + onMouseDrag?: MouseEventHandler + onMouseEnter?: HoverEventHandler + onMouseLeave?: HoverEventHandler +} + +/** + * Reverse lookup: event type string → handler prop names. + * Used by the dispatcher for O(1) handler lookup per node. + */ +export const HANDLER_FOR_EVENT: Record< + string, + { bubble?: keyof EventHandlerProps; capture?: keyof EventHandlerProps } +> = { + keydown: { bubble: 'onKeyDown', capture: 'onKeyDownCapture' }, + focus: { bubble: 'onFocus', capture: 'onFocusCapture' }, + blur: { bubble: 'onBlur', capture: 'onBlurCapture' }, + paste: { bubble: 'onPaste', capture: 'onPasteCapture' }, + resize: { bubble: 'onResize' }, + click: { bubble: 'onClick' }, + mousedown: { bubble: 'onMouseDown' }, + mouseup: { bubble: 'onMouseUp' }, + mousedrag: { bubble: 'onMouseDrag' } +} + +/** + * Set of all event handler prop names, for the reconciler to detect + * event props and store them in _eventHandlers instead of attributes. + */ +export const EVENT_HANDLER_PROPS = new Set([ + 'onKeyDown', + 'onKeyDownCapture', + 'onFocus', + 'onFocusCapture', + 'onBlur', + 'onBlurCapture', + 'onPaste', + 'onPasteCapture', + 'onResize', + 'onClick', + 'onMouseDown', + 'onMouseUp', + 'onMouseDrag', + 'onMouseEnter', + 'onMouseLeave' +]) diff --git a/ui-tui/packages/hermes-ink/src/ink/events/event.ts b/ui-tui/packages/hermes-ink/src/ink/events/event.ts new file mode 100644 index 0000000000..61874002eb --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/event.ts @@ -0,0 +1,11 @@ +export class Event { + private _didStopImmediatePropagation = false + + didStopImmediatePropagation(): boolean { + return this._didStopImmediatePropagation + } + + stopImmediatePropagation(): void { + this._didStopImmediatePropagation = true + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/focus-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/focus-event.ts new file mode 100644 index 0000000000..527fd26d22 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/focus-event.ts @@ -0,0 +1,18 @@ +import { type EventTarget, TerminalEvent } from './terminal-event.js' + +/** + * Focus event for component focus changes. + * + * Dispatched when focus moves between elements. 'focus' fires on the + * newly focused element, 'blur' fires on the previously focused one. + * Both bubble, matching react-dom's use of focusin/focusout semantics + * so parent components can observe descendant focus changes. + */ +export class FocusEvent extends TerminalEvent { + readonly relatedTarget: EventTarget | null + + constructor(type: 'focus' | 'blur', relatedTarget: EventTarget | null = null) { + super(type, { bubbles: true, cancelable: false }) + this.relatedTarget = relatedTarget + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/input-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/input-event.ts new file mode 100644 index 0000000000..293ecdbeec --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/input-event.ts @@ -0,0 +1,184 @@ +import { nonAlphanumericKeys, type ParsedKey } from '../parse-keypress.js' + +import { Event } from './event.js' + +export type Key = { + upArrow: boolean + downArrow: boolean + leftArrow: boolean + rightArrow: boolean + pageDown: boolean + pageUp: boolean + wheelUp: boolean + wheelDown: boolean + home: boolean + end: boolean + return: boolean + escape: boolean + ctrl: boolean + shift: boolean + fn: boolean + tab: boolean + backspace: boolean + delete: boolean + meta: boolean + super: boolean +} + +function parseKey(keypress: ParsedKey): [Key, string] { + const key: Key = { + upArrow: keypress.name === 'up', + downArrow: keypress.name === 'down', + leftArrow: keypress.name === 'left', + rightArrow: keypress.name === 'right', + pageDown: keypress.name === 'pagedown', + pageUp: keypress.name === 'pageup', + wheelUp: keypress.name === 'wheelup', + wheelDown: keypress.name === 'wheeldown', + home: keypress.name === 'home', + end: keypress.name === 'end', + return: keypress.name === 'return', + escape: keypress.name === 'escape', + fn: keypress.fn, + ctrl: keypress.ctrl, + shift: keypress.shift, + tab: keypress.name === 'tab', + backspace: keypress.name === 'backspace', + delete: keypress.name === 'delete', + // `parseKeypress` parses \u001B\u001B[A (meta + up arrow) as meta = false + // but with option = true, so we need to take this into account here + // to avoid breaking changes in Ink. + // TODO(vadimdemedes): consider removing this in the next major version. + meta: keypress.meta || keypress.name === 'escape' || keypress.option, + // Super (Cmd on macOS / Win key) — only arrives via kitty keyboard + // protocol CSI u sequences. Distinct from meta (Alt/Option) so + // bindings like cmd+c can be expressed separately from opt+c. + super: keypress.super + } + + let input = keypress.ctrl ? keypress.name : keypress.sequence + + // Handle undefined input case + if (input === undefined) { + input = '' + } + + // When ctrl is set, keypress.name for space is the literal word "space". + // Convert to actual space character for consistency with the CSI u branch + // (which maps 'space' → ' '). Without this, ctrl+space leaks the literal + // word "space" into text input. + if (keypress.ctrl && input === 'space') { + input = ' ' + } + + // Suppress unrecognized escape sequences that were parsed as function keys + // (matched by FN_KEY_RE) but have no name in the keyName map. + // Examples: ESC[25~ (F13/Right Alt on Windows), ESC[26~ (F14), etc. + // Without this, the ESC prefix is stripped below and the remainder (e.g., + // "[25~") leaks into the input as literal text. + if (keypress.code && !keypress.name) { + input = '' + } + + // Suppress ESC-less SGR mouse fragments. When a heavy React commit blocks + // the event loop past App's 50ms NORMAL_TIMEOUT flush, a CSI split across + // stdin chunks gets its buffered ESC flushed as a lone Escape key, and the + // continuation arrives as a text token with name='' — which falls through + // all of parseKeypress's ESC-anchored regexes and the nonAlphanumericKeys + // clear below (name is falsy). The fragment then leaks into the prompt as + // literal `[<64;74;16M`. This is the same defensive sink as the F13 guard + // above; the underlying tokenizer-flush race is upstream of this layer. + if (!keypress.name && /^\[<\d+;\d+;\d+[Mm]/.test(input)) { + input = '' + } + + // Strip meta if it's still remaining after `parseKeypress` + // TODO(vadimdemedes): remove this in the next major version. + if (input.startsWith('\u001B')) { + input = input.slice(1) + } + + // Track whether we've already processed this as a special sequence + // that converted input to the key name (CSI u or application keypad mode). + // For these, we don't want to clear input with nonAlphanumericKeys check. + let processedAsSpecialSequence = false + + // Handle CSI u sequences (Kitty keyboard protocol): after stripping ESC, + // we're left with "[codepoint;modifieru" (e.g., "[98;3u" for Alt+b). + // Use the parsed key name instead for input handling. Require a digit + // after [ — real CSI u is always […u, and a bare startsWith('[') + // false-matches X10 mouse at row 85 (Cy = 85+32 = 'u'), leaking the + // literal text "mouse" into the prompt via processedAsSpecialSequence. + if (/^\[\d/.test(input) && input.endsWith('u')) { + if (!keypress.name) { + // Unmapped Kitty functional key (Caps Lock 57358, F13–F35, KP nav, + // bare modifiers, etc.) — keycodeToName() returned undefined. Swallow + // so the raw "[57358u" doesn't leak into the prompt. See #38781. + input = '' + } else { + // 'space' → ' '; 'escape' → '' (key.escape carries it; + // processedAsSpecialSequence bypasses the nonAlphanumericKeys + // clear below, so we must handle it explicitly here); + // otherwise use key name. + input = keypress.name === 'space' ? ' ' : keypress.name === 'escape' ? '' : keypress.name + } + + processedAsSpecialSequence = true + } + + // Handle xterm modifyOtherKeys sequences: after stripping ESC, we're left + // with "[27;modifier;keycode~" (e.g., "[27;3;98~" for Alt+b). Same + // extraction as CSI u — without this, printable-char keycodes (single-letter + // names) skip the nonAlphanumericKeys clear and leak "[27;..." as input. + if (input.startsWith('[27;') && input.endsWith('~')) { + if (!keypress.name) { + // Unmapped modifyOtherKeys keycode — swallow for consistency with + // the CSI u handler above. Practically untriggerable today (xterm + // modifyOtherKeys only sends ASCII keycodes, all mapped), but + // guards against future terminal behavior. + input = '' + } else { + input = keypress.name === 'space' ? ' ' : keypress.name === 'escape' ? '' : keypress.name + } + + processedAsSpecialSequence = true + } + + // Handle application keypad mode sequences: after stripping ESC, + // we're left with "O" (e.g., "Op" for numpad 0, "Oy" for numpad 9). + // Use the parsed key name (the digit character) for input handling. + if (input.startsWith('O') && input.length === 2 && keypress.name && keypress.name.length === 1) { + input = keypress.name + processedAsSpecialSequence = true + } + + // Clear input for non-alphanumeric keys (arrows, function keys, etc.) + // Skip this for CSI u and application keypad mode sequences since + // those were already converted to their proper input characters. + if (!processedAsSpecialSequence && keypress.name && nonAlphanumericKeys.includes(keypress.name)) { + input = '' + } + + // Set shift=true for uppercase letters (A-Z) + // Must check it's actually a letter, not just any char unchanged by toUpperCase + if (input.length === 1 && typeof input[0] === 'string' && input[0] >= 'A' && input[0] <= 'Z') { + key.shift = true + } + + return [key, input] +} + +export class InputEvent extends Event { + readonly keypress: ParsedKey + readonly key: Key + readonly input: string + + constructor(keypress: ParsedKey) { + super() + const [key, input] = parseKey(keypress) + + this.keypress = keypress + this.key = key + this.input = input + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/keyboard-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/keyboard-event.ts new file mode 100644 index 0000000000..6d441dadbd --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/keyboard-event.ts @@ -0,0 +1,57 @@ +import type { ParsedKey } from '../parse-keypress.js' + +import { TerminalEvent } from './terminal-event.js' + +/** + * Keyboard event dispatched through the DOM tree via capture/bubble. + * + * Follows browser KeyboardEvent semantics: `key` is the literal character + * for printable keys ('a', '3', ' ', '/') and a multi-char name for + * special keys ('down', 'return', 'escape', 'f1'). The idiomatic + * printable-char check is `e.key.length === 1`. + */ +export class KeyboardEvent extends TerminalEvent { + readonly key: string + readonly ctrl: boolean + readonly shift: boolean + readonly meta: boolean + readonly superKey: boolean + readonly fn: boolean + + constructor(parsedKey: ParsedKey) { + super('keydown', { bubbles: true, cancelable: true }) + + this.key = keyFromParsed(parsedKey) + this.ctrl = parsedKey.ctrl + this.shift = parsedKey.shift + this.meta = parsedKey.meta || parsedKey.option + this.superKey = parsedKey.super + this.fn = parsedKey.fn + } +} + +function keyFromParsed(parsed: ParsedKey): string { + const seq = parsed.sequence ?? '' + const name = parsed.name ?? '' + + // Ctrl combos: sequence is a control byte (\x03 for ctrl+c), name is the + // letter. Browsers report e.key === 'c' with e.ctrlKey === true. + if (parsed.ctrl) { + return name + } + + // Single printable char (space through ~, plus anything above ASCII): + // use the literal char. Browsers report e.key === '3', not 'Digit3'. + if (seq.length === 1) { + const code = seq.charCodeAt(0) + + if (code >= 0x20 && code !== 0x7f) { + return seq + } + } + + // Special keys (arrows, F-keys, return, tab, escape, etc.): sequence is + // either an escape sequence (\x1b[B) or a control byte (\r, \t), so use + // the parsed name. Browsers report e.key === 'ArrowDown'. + return name || seq +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/mouse-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/mouse-event.ts new file mode 100644 index 0000000000..d42839b5fb --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/mouse-event.ts @@ -0,0 +1,18 @@ +import { Event } from './event.js' + +export class MouseEvent extends Event { + readonly col: number + readonly row: number + localCol = 0 + localRow = 0 + readonly cellIsBlank: boolean + readonly button: number + + constructor(col: number, row: number, cellIsBlank: boolean, button: number) { + super() + this.col = col + this.row = row + this.cellIsBlank = cellIsBlank + this.button = button + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/paste-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/paste-event.ts new file mode 100644 index 0000000000..38a88f3171 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/paste-event.ts @@ -0,0 +1,10 @@ +import { TerminalEvent } from './terminal-event.js' + +export class PasteEvent extends TerminalEvent { + readonly text: string + + constructor(text: string) { + super('paste', { bubbles: true, cancelable: true }) + this.text = text + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/resize-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/resize-event.ts new file mode 100644 index 0000000000..b2627bb290 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/resize-event.ts @@ -0,0 +1,12 @@ +import { TerminalEvent } from './terminal-event.js' + +export class ResizeEvent extends TerminalEvent { + readonly columns: number + readonly rows: number + + constructor(columns: number, rows: number) { + super('resize', { bubbles: true, cancelable: true }) + this.columns = columns + this.rows = rows + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/terminal-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/terminal-event.ts new file mode 100644 index 0000000000..9a86bf8b29 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/terminal-event.ts @@ -0,0 +1,107 @@ +import { Event } from './event.js' + +type EventPhase = 'none' | 'capturing' | 'at_target' | 'bubbling' + +type TerminalEventInit = { + bubbles?: boolean + cancelable?: boolean +} + +/** + * Base class for all terminal events with DOM-style propagation. + * + * Extends Event so existing event types (ClickEvent, InputEvent, + * TerminalFocusEvent) share a common ancestor and can migrate later. + * + * Mirrors the browser's Event API: target, currentTarget, eventPhase, + * stopPropagation(), preventDefault(), timeStamp. + */ +export class TerminalEvent extends Event { + readonly type: string + readonly timeStamp: number + readonly bubbles: boolean + readonly cancelable: boolean + + private _target: EventTarget | null = null + private _currentTarget: EventTarget | null = null + private _eventPhase: EventPhase = 'none' + private _propagationStopped = false + private _defaultPrevented = false + + constructor(type: string, init?: TerminalEventInit) { + super() + this.type = type + this.timeStamp = performance.now() + this.bubbles = init?.bubbles ?? true + this.cancelable = init?.cancelable ?? true + } + + get target(): EventTarget | null { + return this._target + } + + get currentTarget(): EventTarget | null { + return this._currentTarget + } + + get eventPhase(): EventPhase { + return this._eventPhase + } + + get defaultPrevented(): boolean { + return this._defaultPrevented + } + + stopPropagation(): void { + this._propagationStopped = true + } + + override stopImmediatePropagation(): void { + super.stopImmediatePropagation() + this._propagationStopped = true + } + + preventDefault(): void { + if (this.cancelable) { + this._defaultPrevented = true + } + } + + // -- Internal setters used by the Dispatcher + + /** @internal */ + _setTarget(target: EventTarget): void { + this._target = target + } + + /** @internal */ + _setCurrentTarget(target: EventTarget | null): void { + this._currentTarget = target + } + + /** @internal */ + _setEventPhase(phase: EventPhase): void { + this._eventPhase = phase + } + + /** @internal */ + _isPropagationStopped(): boolean { + return this._propagationStopped + } + + /** @internal */ + _isImmediatePropagationStopped(): boolean { + return this.didStopImmediatePropagation() + } + + /** + * Hook for subclasses to do per-node setup before each handler fires. + * Default is a no-op. + */ + _prepareForTarget(_target: EventTarget): void {} +} + +export type EventTarget = { + parentNode: EventTarget | undefined + _eventHandlers?: Record +} diff --git a/ui-tui/packages/hermes-ink/src/ink/events/terminal-focus-event.ts b/ui-tui/packages/hermes-ink/src/ink/events/terminal-focus-event.ts new file mode 100644 index 0000000000..6d0303fdb4 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/events/terminal-focus-event.ts @@ -0,0 +1,19 @@ +import { Event } from './event.js' + +export type TerminalFocusEventType = 'terminalfocus' | 'terminalblur' + +/** + * Event fired when the terminal window gains or loses focus. + * + * Uses DECSET 1004 focus reporting - the terminal sends: + * - CSI I (\x1b[I) when the terminal gains focus + * - CSI O (\x1b[O) when the terminal loses focus + */ +export class TerminalFocusEvent extends Event { + readonly type: TerminalFocusEventType + + constructor(type: TerminalFocusEventType) { + super() + this.type = type + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/focus.ts b/ui-tui/packages/hermes-ink/src/ink/focus.ts new file mode 100644 index 0000000000..0317ed9d7e --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/focus.ts @@ -0,0 +1,219 @@ +import type { DOMElement } from './dom.js' +import { FocusEvent } from './events/focus-event.js' + +const MAX_FOCUS_STACK = 32 + +/** + * DOM-like focus manager for the Ink terminal UI. + * + * Pure state — tracks activeElement and a focus stack. Has no reference + * to the tree; callers pass the root when tree walks are needed. + * + * Stored on the root DOMElement so any node can reach it by walking + * parentNode (like browser's `node.ownerDocument`). + */ +export class FocusManager { + activeElement: DOMElement | null = null + private dispatchFocusEvent: (target: DOMElement, event: FocusEvent) => boolean + private enabled = true + private focusStack: DOMElement[] = [] + + constructor(dispatchFocusEvent: (target: DOMElement, event: FocusEvent) => boolean) { + this.dispatchFocusEvent = dispatchFocusEvent + } + + focus(node: DOMElement): void { + if (node === this.activeElement) { + return + } + + if (!this.enabled) { + return + } + + const previous = this.activeElement + + if (previous) { + // Deduplicate before pushing to prevent unbounded growth from Tab cycling + const idx = this.focusStack.indexOf(previous) + + if (idx !== -1) { + this.focusStack.splice(idx, 1) + } + + this.focusStack.push(previous) + + if (this.focusStack.length > MAX_FOCUS_STACK) { + this.focusStack.shift() + } + + this.dispatchFocusEvent(previous, new FocusEvent('blur', node)) + } + + this.activeElement = node + this.dispatchFocusEvent(node, new FocusEvent('focus', previous)) + } + + blur(): void { + if (!this.activeElement) { + return + } + + const previous = this.activeElement + this.activeElement = null + this.dispatchFocusEvent(previous, new FocusEvent('blur', null)) + } + + /** + * Called by the reconciler when a node is removed from the tree. + * Handles both the exact node and any focused descendant within + * the removed subtree. Dispatches blur and restores focus from stack. + */ + handleNodeRemoved(node: DOMElement, root: DOMElement): void { + // Remove the node and any descendants from the stack + this.focusStack = this.focusStack.filter(n => n !== node && isInTree(n, root)) + + // Check if activeElement is the removed node OR a descendant + if (!this.activeElement) { + return + } + + if (this.activeElement !== node && isInTree(this.activeElement, root)) { + return + } + + const removed = this.activeElement + this.activeElement = null + this.dispatchFocusEvent(removed, new FocusEvent('blur', null)) + + // Restore focus to the most recent still-mounted element + while (this.focusStack.length > 0) { + const candidate = this.focusStack.pop()! + + if (isInTree(candidate, root)) { + this.activeElement = candidate + this.dispatchFocusEvent(candidate, new FocusEvent('focus', removed)) + + return + } + } + } + + handleAutoFocus(node: DOMElement): void { + this.focus(node) + } + + handleClickFocus(node: DOMElement): void { + const tabIndex = node.attributes['tabIndex'] + + if (typeof tabIndex !== 'number') { + return + } + + this.focus(node) + } + + enable(): void { + this.enabled = true + } + + disable(): void { + this.enabled = false + } + + focusNext(root: DOMElement): void { + this.moveFocus(1, root) + } + + focusPrevious(root: DOMElement): void { + this.moveFocus(-1, root) + } + + private moveFocus(direction: 1 | -1, root: DOMElement): void { + if (!this.enabled) { + return + } + + const tabbable = collectTabbable(root) + + if (tabbable.length === 0) { + return + } + + const currentIndex = this.activeElement ? tabbable.indexOf(this.activeElement) : -1 + + const nextIndex = + currentIndex === -1 + ? direction === 1 + ? 0 + : tabbable.length - 1 + : (currentIndex + direction + tabbable.length) % tabbable.length + + const next = tabbable[nextIndex] + + if (next) { + this.focus(next) + } + } +} + +function collectTabbable(root: DOMElement): DOMElement[] { + const result: DOMElement[] = [] + walkTree(root, result) + + return result +} + +function walkTree(node: DOMElement, result: DOMElement[]): void { + const tabIndex = node.attributes['tabIndex'] + + if (typeof tabIndex === 'number' && tabIndex >= 0) { + result.push(node) + } + + for (const child of node.childNodes) { + if (child.nodeName !== '#text') { + walkTree(child, result) + } + } +} + +function isInTree(node: DOMElement, root: DOMElement): boolean { + let current: DOMElement | undefined = node + + while (current) { + if (current === root) { + return true + } + + current = current.parentNode + } + + return false +} + +/** + * Walk up to root and return it. The root is the node that holds + * the FocusManager — like browser's `node.getRootNode()`. + */ +export function getRootNode(node: DOMElement): DOMElement { + let current: DOMElement | undefined = node + + while (current) { + if (current.focusManager) { + return current + } + + current = current.parentNode + } + + throw new Error('Node is not in a tree with a FocusManager') +} + +/** + * Walk up to root and return its FocusManager. + * Like browser's `node.ownerDocument` — focus belongs to the root. + */ +export function getFocusManager(node: DOMElement): FocusManager { + return getRootNode(node).focusManager! +} diff --git a/ui-tui/packages/hermes-ink/src/ink/frame.ts b/ui-tui/packages/hermes-ink/src/ink/frame.ts new file mode 100644 index 0000000000..b85c0ad944 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/frame.ts @@ -0,0 +1,116 @@ +import type { Cursor } from './cursor.js' +import type { Size } from './layout/geometry.js' +import type { ScrollHint } from './render-node-to-output.js' +import { type CharPool, createScreen, type HyperlinkPool, type Screen, type StylePool } from './screen.js' + +export type Frame = { + readonly screen: Screen + readonly viewport: Size + readonly cursor: Cursor + /** DECSTBM scroll optimization hint (alt-screen only, null otherwise). */ + readonly scrollHint?: ScrollHint | null + /** A ScrollBox has remaining pendingScrollDelta — schedule another frame. */ + readonly scrollDrainPending?: boolean + /** Absolute overlay moved/resized — schedule corrective frame without prevScreen. */ + readonly absoluteOverlayMoved?: boolean +} + +export function emptyFrame( + rows: number, + columns: number, + stylePool: StylePool, + charPool: CharPool, + hyperlinkPool: HyperlinkPool +): Frame { + return { + screen: createScreen(0, 0, stylePool, charPool, hyperlinkPool), + viewport: { width: columns, height: rows }, + cursor: { x: 0, y: 0, visible: true } + } +} + +export type FlickerReason = 'resize' | 'offscreen' | 'clear' + +export type FrameEvent = { + durationMs: number + /** Phase breakdown in ms + patch count. Populated when the ink instance + * has frame-timing instrumentation enabled (via onFrame wiring). */ + phases?: { + /** createRenderer output: DOM → yoga layout → screen buffer */ + renderer: number + /** LogUpdate.render(): screen diff → Patch[] (the hot path this PR optimizes) */ + diff: number + /** optimize(): patch merge/dedupe */ + optimize: number + /** writeDiffToTerminal(): serialize patches → ANSI → stdout */ + write: number + /** Pre-optimize patch count (proxy for how much changed this frame) */ + patches: number + /** yoga calculateLayout() time (runs in resetAfterCommit, before onRender) */ + yoga: number + /** React reconcile time: scrollMutated → resetAfterCommit. 0 if no commit. */ + commit: number + /** layoutNode() calls this frame (recursive, includes cache-hit returns) */ + yogaVisited: number + /** measureFunc (text wrap/width) calls — the expensive part */ + yogaMeasured: number + /** early returns via _hasL single-slot cache */ + yogaCacheHits: number + /** total yoga Node instances alive (create - free). Growth = leak. */ + yogaLive: number + } + flickers: Array<{ + desiredHeight: number + availableHeight: number + reason: FlickerReason + }> +} + +export type Patch = + | { type: 'stdout'; content: string } + | { type: 'clear'; count: number } + | { + type: 'clearTerminal' + reason: FlickerReason + // Populated by log-update when a scrollback diff triggers the reset. + debug?: { triggerY: number; prevLine: string; nextLine: string } + } + | { type: 'cursorHide' } + | { type: 'cursorShow' } + | { type: 'cursorMove'; x: number; y: number } + | { type: 'cursorTo'; col: number } + | { type: 'carriageReturn' } + | { type: 'hyperlink'; uri: string } + // Pre-serialized style transition string from StylePool.transition() — + // cached by (fromId, toId), zero allocations after warmup. + | { type: 'styleStr'; str: string } + +export type Diff = Patch[] + +/** + * Determines whether the screen should be cleared based on the current and previous frame. + * Returns the reason for clearing, or undefined if no clear is needed. + * + * Screen clearing is triggered when: + * 1. Terminal has been resized (viewport dimensions changed) → 'resize' + * 2. Current frame screen height exceeds available terminal rows → 'offscreen' + * 3. Previous frame screen height exceeded available terminal rows → 'offscreen' + */ +export function shouldClearScreen(prevFrame: Frame, frame: Frame): FlickerReason | undefined { + const didResize = + frame.viewport.height !== prevFrame.viewport.height || frame.viewport.width !== prevFrame.viewport.width + + if (didResize) { + return 'resize' + } + + const currentFrameOverflows = frame.screen.height >= frame.viewport.height + + const previousFrameOverflowed = prevFrame.screen.height >= prevFrame.viewport.height + + if (currentFrameOverflows || previousFrameOverflowed) { + return 'offscreen' + } + + return undefined +} diff --git a/ui-tui/packages/hermes-ink/src/ink/get-max-width.ts b/ui-tui/packages/hermes-ink/src/ink/get-max-width.ts new file mode 100644 index 0000000000..e079463748 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/get-max-width.ts @@ -0,0 +1,27 @@ +import { LayoutEdge, type LayoutNode } from './layout/node.js' + +/** + * Returns the yoga node's content width (computed width minus padding and + * border). + * + * Warning: can return a value WIDER than the parent container. In a + * column-direction flex parent, width is the cross axis — align-items: + * stretch never shrinks children below their intrinsic size, so the text + * node overflows (standard CSS behavior). Yoga measures leaf nodes in two + * passes: the AtMost pass determines width, the Exactly pass determines + * height. getComputedWidth() reflects the wider AtMost result while + * getComputedHeight() reflects the narrower Exactly result. Callers that + * use this for wrapping should clamp to actual available screen space so + * the rendered line count stays consistent with the layout height. + */ +const getMaxWidth = (yogaNode: LayoutNode): number => { + return ( + yogaNode.getComputedWidth() - + yogaNode.getComputedPadding(LayoutEdge.Left) - + yogaNode.getComputedPadding(LayoutEdge.Right) - + yogaNode.getComputedBorder(LayoutEdge.Left) - + yogaNode.getComputedBorder(LayoutEdge.Right) + ) +} + +export default getMaxWidth diff --git a/ui-tui/packages/hermes-ink/src/ink/global.d.ts b/ui-tui/packages/hermes-ink/src/ink/global.d.ts new file mode 100644 index 0000000000..336ce12bb9 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/global.d.ts @@ -0,0 +1 @@ +export {} diff --git a/ui-tui/packages/hermes-ink/src/ink/hit-test.ts b/ui-tui/packages/hermes-ink/src/ink/hit-test.ts new file mode 100644 index 0000000000..c23ce34fe0 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hit-test.ts @@ -0,0 +1,192 @@ +import type { DOMElement } from './dom.js' +import { ClickEvent } from './events/click-event.js' +import type { EventHandlerProps } from './events/event-handlers.js' +import { MouseEvent } from './events/mouse-event.js' +import { nodeCache } from './node-cache.js' + +/** + * Find the deepest DOM element whose rendered rect contains (col, row). + * + * Uses the nodeCache populated by renderNodeToOutput — rects are in screen + * coordinates with all offsets (including scrollTop translation) already + * applied. Children are traversed in reverse so later siblings (painted on + * top) win. Nodes not in nodeCache (not rendered this frame, or lacking a + * yogaNode) are skipped along with their subtrees. + * + * Returns the hit node even if it has no onClick — dispatchClick walks up + * via parentNode to find handlers. + */ +export function hitTest(node: DOMElement, col: number, row: number): DOMElement | null { + const rect = nodeCache.get(node) + + if (!rect) { + return null + } + + if (col < rect.x || col >= rect.x + rect.width || row < rect.y || row >= rect.y + rect.height) { + return null + } + + // Later siblings paint on top; reversed traversal returns topmost hit. + for (let i = node.childNodes.length - 1; i >= 0; i--) { + const child = node.childNodes[i]! + + if (child.nodeName === '#text') { + continue + } + + const hit = hitTest(child, col, row) + + if (hit) { + return hit + } + } + + return node +} + +/** + * Hit-test the root at (col, row) and bubble a ClickEvent from the deepest + * containing node up through parentNode. Only nodes with an onClick handler + * fire. Stops when a handler calls stopImmediatePropagation(). Returns + * true if at least one onClick handler fired. + */ +export function dispatchClick(root: DOMElement, col: number, row: number, cellIsBlank = false): boolean { + let target: DOMElement | undefined = hitTest(root, col, row) ?? undefined + + if (!target) { + return false + } + + // Click-to-focus: find the closest focusable ancestor and focus it. + // root is always ink-root, which owns the FocusManager. + if (root.focusManager) { + let focusTarget: DOMElement | undefined = target + + while (focusTarget) { + if (typeof focusTarget.attributes['tabIndex'] === 'number') { + root.focusManager.handleClickFocus(focusTarget) + + break + } + + focusTarget = focusTarget.parentNode + } + } + + const event = new ClickEvent(col, row, cellIsBlank) + let handled = false + + while (target) { + const handler = target._eventHandlers?.onClick as ((event: ClickEvent) => void) | undefined + + if (handler) { + handled = true + const rect = nodeCache.get(target) + + if (rect) { + event.localCol = col - rect.x + event.localRow = row - rect.y + } + + handler(event) + + if (event.didStopImmediatePropagation()) { + return true + } + } + + target = target.parentNode + } + + return handled +} + +type MouseHandler = 'onMouseDown' | 'onMouseUp' | 'onMouseDrag' + +export function dispatchMouse( + root: DOMElement, + col: number, + row: number, + handlerName: MouseHandler, + button: number, + cellIsBlank = false, + target?: DOMElement +): DOMElement | undefined { + let node: DOMElement | undefined = target ?? hitTest(root, col, row) ?? undefined + + if (!node) { + return undefined + } + + const event = new MouseEvent(col, row, cellIsBlank, button) + let handled: DOMElement | undefined + + while (node) { + const handler = node._eventHandlers?.[handlerName] as ((event: MouseEvent) => void) | undefined + + if (handler) { + handled ??= node + const rect = nodeCache.get(node) + + if (rect) { + event.localCol = col - rect.x + event.localRow = row - rect.y + } + + handler(event) + + if (event.didStopImmediatePropagation()) { + return handled + } + } + + node = node.parentNode + } + + return handled +} + +/** + * Fire onMouseEnter/onMouseLeave as the pointer moves. Like DOM + * mouseenter/mouseleave: does NOT bubble — moving between children does + * not re-fire on the parent. Walks up from the hit node collecting every + * ancestor with a hover handler; diffs against the previous hovered set; + * fires leave on the nodes exited, enter on the nodes entered. + * + * Mutates `hovered` in place so the caller (App instance) can hold it + * across calls. Clears the set when the hit is null (cursor moved into a + * non-rendered gap or off the root rect). + */ +export function dispatchHover(root: DOMElement, col: number, row: number, hovered: Set): void { + const next = new Set() + let node: DOMElement | undefined = hitTest(root, col, row) ?? undefined + + while (node) { + const h = node._eventHandlers as EventHandlerProps | undefined + + if (h?.onMouseEnter || h?.onMouseLeave) { + next.add(node) + } + + node = node.parentNode + } + + for (const old of hovered) { + if (!next.has(old)) { + hovered.delete(old) + + // Skip handlers on detached nodes (removed between mouse events) + if (old.parentNode) { + ;(old._eventHandlers as EventHandlerProps | undefined)?.onMouseLeave?.() + } + } + } + + for (const n of next) { + if (!hovered.has(n)) { + hovered.add(n) + ;(n._eventHandlers as EventHandlerProps | undefined)?.onMouseEnter?.() + } + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-animation-frame.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-animation-frame.ts new file mode 100644 index 0000000000..0eef9e1aba --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-animation-frame.ts @@ -0,0 +1,62 @@ +import { useContext, useEffect, useState } from 'react' + +import { ClockContext } from '../components/ClockContext.js' +import type { DOMElement } from '../dom.js' + +import { useTerminalViewport } from './use-terminal-viewport.js' + +/** + * Hook for synchronized animations that pause when offscreen. + * + * Returns a ref to attach to the animated element and the current animation time. + * All instances share the same clock, so animations stay in sync. + * The clock only runs when at least one keepAlive subscriber exists. + * + * Pass `null` to pause — unsubscribes from the clock so no ticks fire. + * Time freezes at the last value and resumes from the current clock time + * when a number is passed again. + * + * @param intervalMs - How often to update, or null to pause + * @returns [ref, time] - Ref to attach to element, elapsed time in ms + * + * @example + * function Spinner() { + * const [ref, time] = useAnimationFrame(120) + * const frame = Math.floor(time / 120) % FRAMES.length + * return {FRAMES[frame]} + * } + * + * The clock automatically slows when the terminal is blurred, + * so consumers don't need to handle focus state. + */ +export function useAnimationFrame( + intervalMs: number | null = 16 +): [ref: (element: DOMElement | null) => void, time: number] { + const clock = useContext(ClockContext) + const [viewportRef, { isVisible }] = useTerminalViewport() + const [time, setTime] = useState(() => clock?.now() ?? 0) + + const active = isVisible && intervalMs !== null + + useEffect(() => { + if (!clock || !active) { + return + } + + let lastUpdate = clock.now() + + const onChange = (): void => { + const now = clock.now() + + if (now - lastUpdate >= intervalMs!) { + lastUpdate = now + setTime(now) + } + } + + // keepAlive: true — visible animations drive the clock + return clock.subscribe(onChange, true) + }, [clock, intervalMs, active]) + + return [viewportRef, time] +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-app.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-app.ts new file mode 100644 index 0000000000..9c06032448 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-app.ts @@ -0,0 +1,9 @@ +import { useContext } from 'react' + +import AppContext from '../components/AppContext.js' + +/** + * `useApp` is a React hook, which exposes a method to manually exit the app (unmount). + */ +const useApp = () => useContext(AppContext) +export default useApp diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-declared-cursor.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-declared-cursor.ts new file mode 100644 index 0000000000..288a92eda3 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-declared-cursor.ts @@ -0,0 +1,75 @@ +import { useCallback, useContext, useLayoutEffect, useRef } from 'react' + +import CursorDeclarationContext from '../components/CursorDeclarationContext.js' +import type { DOMElement } from '../dom.js' + +/** + * Declares where the terminal cursor should be parked after each frame. + * + * Terminal emulators render IME preedit text at the physical cursor + * position, and screen readers / screen magnifiers track the native + * cursor — so parking it at the text input's caret makes CJK input + * appear inline and lets accessibility tools follow the input. + * + * Returns a ref callback to attach to the Box that contains the input. + * The declared (line, column) is interpreted relative to that Box's + * nodeCache rect (populated by renderNodeToOutput). + * + * Timing: Both ref attach and useLayoutEffect fire in React's layout + * phase — after resetAfterCommit calls scheduleRender. scheduleRender + * defers onRender via queueMicrotask, so onRender runs AFTER layout + * effects commit and reads the fresh declaration on the first frame + * (no one-keystroke lag). Test env uses onImmediateRender (synchronous, + * no microtask), so tests compensate by calling ink.onRender() + * explicitly after render. + */ +export function useDeclaredCursor({ + line, + column, + active +}: { + line: number + column: number + active: boolean +}): (element: DOMElement | null) => void { + const setCursorDeclaration = useContext(CursorDeclarationContext) + const nodeRef = useRef(null) + + const setNode = useCallback((node: DOMElement | null) => { + nodeRef.current = node + }, []) + + // When active, set unconditionally. When inactive, clear conditionally + // (only if the currently-declared node is ours). The node-identity check + // handles two hazards: + // 1. A memo()ized active instance elsewhere (e.g. the search input in + // a memo'd Footer) doesn't re-render this commit — an inactive + // instance re-rendering here must not clobber it. + // 2. Sibling handoff (menu focus moving between list items) — when + // focus moves opposite to sibling order, the newly-inactive item's + // effect runs AFTER the newly-active item's set. Without the node + // check it would clobber. + // No dep array: must re-declare every commit so the active instance + // re-claims the declaration after another instance's unmount-cleanup or + // sibling handoff nulls it. + useLayoutEffect(() => { + const node = nodeRef.current + + if (active && node) { + setCursorDeclaration({ relativeX: column, relativeY: line, node }) + } else { + setCursorDeclaration(null, node) + } + }) + + // Clear on unmount (conditionally — another instance may own by then). + // Separate effect with empty deps so cleanup only fires once — not on + // every line/column change, which would transiently null between commits. + useLayoutEffect(() => { + return () => { + setCursorDeclaration(null, nodeRef.current) + } + }, [setCursorDeclaration]) + + return setNode +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-external-process.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-external-process.ts new file mode 100644 index 0000000000..c895edeb21 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-external-process.ts @@ -0,0 +1,27 @@ +import { useCallback } from 'react' + +import instances from '../instances.js' + +export type RunExternalProcess = () => Promise + +export async function withInkSuspended(run: RunExternalProcess): Promise { + const ink = instances.get(process.stdout) + + if (!ink) { + await run() + + return + } + + ink.enterAlternateScreen() + + try { + await run() + } finally { + ink.exitAlternateScreen() + } +} + +export function useExternalProcess(): (run: RunExternalProcess) => Promise { + return useCallback((run: RunExternalProcess) => withInkSuspended(run), []) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-input.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-input.ts new file mode 100644 index 0000000000..edda48a4a7 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-input.ts @@ -0,0 +1,95 @@ +import { useEffect, useLayoutEffect } from 'react' +import { useEventCallback } from 'usehooks-ts' + +import type { InputEvent, Key } from '../events/input-event.js' + +import useStdin from './use-stdin.js' + +type Handler = (input: string, key: Key, event: InputEvent) => void + +type Options = { + /** + * Enable or disable capturing of user input. + * Useful when there are multiple useInput hooks used at once to avoid handling the same input several times. + * + * @default true + */ + isActive?: boolean +} + +/** + * This hook is used for handling user input. + * It's a more convenient alternative to using `StdinContext` and listening to `data` events. + * The callback you pass to `useInput` is called for each character when user enters any input. + * However, if user pastes text and it's more than one character, the callback will be called only once and the whole string will be passed as `input`. + * + * ``` + * import {useInput} from 'ink'; + * + * const UserInput = () => { + * useInput((input, key) => { + * if (input === 'q') { + * // Exit program + * } + * + * if (key.leftArrow) { + * // Left arrow key pressed + * } + * }); + * + * return … + * }; + * ``` + */ +const useInput = (inputHandler: Handler, options: Options = {}) => { + const { setRawMode, exitOnCtrlC, inputEmitter } = useStdin() + + // useLayoutEffect (not useEffect) so that raw mode is enabled synchronously + // during React's commit phase, before render() returns. With useEffect, raw + // mode setup is deferred to the next event loop tick via React's scheduler, + // leaving the terminal in cooked mode — keystrokes echo and the cursor is + // visible until the effect fires. + useLayoutEffect(() => { + if (options.isActive === false) { + return + } + + setRawMode(true) + + return () => { + setRawMode(false) + } + }, [options.isActive, setRawMode]) + + // Register the listener once on mount so its slot in the EventEmitter's + // listener array is stable. If isActive were in the effect's deps, the + // listener would re-append on false→true, moving it behind listeners + // that registered while it was inactive — breaking + // stopImmediatePropagation() ordering. useEventCallback keeps the + // reference stable while reading latest isActive/inputHandler from + // closure (it syncs via useLayoutEffect, so it's compiler-safe). + const handleData = useEventCallback((event: InputEvent) => { + if (options.isActive === false) { + return + } + + const { input, key } = event + + // If app is not supposed to exit on Ctrl+C, then let input listener handle it + // Note: discreteUpdates is called at the App level when emitting events, + // so all listeners are already within a high-priority update context. + if (!(input === 'c' && key.ctrl) || !exitOnCtrlC) { + inputHandler(input, key, event) + } + }) + + useEffect(() => { + inputEmitter?.on('input', handleData) + + return () => { + inputEmitter?.removeListener('input', handleData) + } + }, [inputEmitter, handleData]) +} + +export default useInput diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-interval.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-interval.ts new file mode 100644 index 0000000000..af568457bf --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-interval.ts @@ -0,0 +1,71 @@ +import { useContext, useEffect, useRef, useState } from 'react' + +import { ClockContext } from '../components/ClockContext.js' + +/** + * Returns the clock time, updating at the given interval. + * Subscribes as non-keepAlive — won't keep the clock alive on its own, + * but updates whenever a keepAlive subscriber (e.g. the spinner) + * is driving the clock. + * + * Use this to drive pure time-based computations (shimmer position, + * frame index) from the shared clock. + */ +export function useAnimationTimer(intervalMs: number): number { + const clock = useContext(ClockContext) + const [time, setTime] = useState(() => clock?.now() ?? 0) + + useEffect(() => { + if (!clock) { + return + } + + let lastUpdate = clock.now() + + const onChange = (): void => { + const now = clock.now() + + if (now - lastUpdate >= intervalMs) { + lastUpdate = now + setTime(now) + } + } + + return clock.subscribe(onChange, false) + }, [clock, intervalMs]) + + return time +} + +/** + * Interval hook backed by the shared Clock. + * + * Unlike `useInterval` from `usehooks-ts` (which creates its own setInterval), + * this piggybacks on the single shared clock so all timers consolidate into + * one wake-up. Pass `null` for intervalMs to pause. + */ +export function useInterval(callback: () => void, intervalMs: number | null): void { + const callbackRef = useRef(callback) + callbackRef.current = callback + + const clock = useContext(ClockContext) + + useEffect(() => { + if (!clock || intervalMs === null) { + return + } + + let lastUpdate = clock.now() + + const onChange = (): void => { + const now = clock.now() + + if (now - lastUpdate >= intervalMs) { + lastUpdate = now + callbackRef.current() + } + } + + return clock.subscribe(onChange, false) + }, [clock, intervalMs]) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-search-highlight.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-search-highlight.ts new file mode 100644 index 0000000000..f43379a5e6 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-search-highlight.ts @@ -0,0 +1,56 @@ +import { useContext, useMemo } from 'react' + +import StdinContext from '../components/StdinContext.js' +import type { DOMElement } from '../dom.js' +import instances from '../instances.js' +import type { MatchPosition } from '../render-to-screen.js' + +/** + * Set the search highlight query on the Ink instance. Non-empty → all + * visible occurrences are inverted on the next frame (SGR 7, screen-buffer + * overlay, same damage machinery as selection). Empty → clears. + * + * This is a screen-space highlight — it matches the RENDERED text, not the + * source message text. Works for anything visible (bash output, file paths, + * error messages) regardless of where it came from in the message tree. A + * query that matched in source but got truncated/ellipsized in rendering + * won't highlight; that's acceptable — we highlight what you see. + */ +export function useSearchHighlight(): { + setQuery: (query: string) => void + /** Paint an existing DOM subtree (from the MAIN tree) to a fresh + * Screen at its natural height, scan. Element-relative positions + * (row 0 = element top). Zero context duplication — the element + * IS the one built with all real providers. */ + scanElement: (el: DOMElement) => MatchPosition[] + /** Position-based CURRENT highlight. Every frame writes yellow at + * positions[currentIdx] + rowOffset. The scan-highlight (inverse on + * all matches) still runs — this overlays on top. rowOffset tracks + * scroll; positions stay stable (message-relative). null clears. */ + setPositions: ( + state: { + positions: MatchPosition[] + rowOffset: number + currentIdx: number + } | null + ) => void +} { + useContext(StdinContext) // anchor to App subtree for hook rules + const ink = instances.get(process.stdout) + + return useMemo(() => { + if (!ink) { + return { + setQuery: () => {}, + scanElement: () => [], + setPositions: () => {} + } + } + + return { + setQuery: (query: string) => ink.setSearchHighlight(query), + scanElement: (el: DOMElement) => ink.scanElementSubtree(el), + setPositions: state => ink.setSearchPositions(state) + } + }, [ink]) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-selection.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-selection.ts new file mode 100644 index 0000000000..58761fe241 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-selection.ts @@ -0,0 +1,97 @@ +import { useContext, useMemo, useSyncExternalStore } from 'react' + +import StdinContext from '../components/StdinContext.js' +import instances from '../instances.js' +import { type FocusMove, type SelectionState, shiftAnchor } from '../selection.js' + +/** + * Access to text selection operations on the Ink instance (fullscreen only). + * Returns no-op functions when fullscreen mode is disabled. + */ +export function useSelection(): { + copySelection: () => string + /** Copy without clearing the highlight (for copy-on-select). */ + copySelectionNoClear: () => string + clearSelection: () => void + hasSelection: () => boolean + /** Read the raw mutable selection state (for drag-to-scroll). */ + getState: () => SelectionState | null + /** Subscribe to selection mutations (start/update/finish/clear). */ + subscribe: (cb: () => void) => () => void + /** Shift the anchor row by dRow, clamped to [minRow, maxRow]. */ + shiftAnchor: (dRow: number, minRow: number, maxRow: number) => void + /** Shift anchor AND focus by dRow (keyboard scroll: whole selection + * tracks content). Clamped points get col reset to the full-width edge + * since their content was captured by captureScrolledRows. Reads + * screen.width from the ink instance for the col-reset boundary. */ + shiftSelection: (dRow: number, minRow: number, maxRow: number) => void + /** Keyboard selection extension (shift+arrow): move focus, anchor fixed. + * Left/right wrap across rows; up/down clamp at viewport edges. */ + moveFocus: (move: FocusMove) => void + /** Capture text from rows about to scroll out of the viewport (call + * BEFORE scrollBy so the screen buffer still has the outgoing rows). */ + captureScrolledRows: (firstRow: number, lastRow: number, side: 'above' | 'below') => void + /** Set the selection highlight bg color (theme-piping; solid bg + * replaces the old SGR-7 inverse so syntax highlighting stays readable + * under selection). Call once on mount + whenever theme changes. */ + setSelectionBgColor: (color: string) => void +} { + // Look up the Ink instance via stdout — same pattern as instances map. + // StdinContext is available (it's always provided), and the Ink instance + // is keyed by stdout which we can get from process.stdout since there's + // only one Ink instance per process in practice. + useContext(StdinContext) // anchor to App subtree for hook rules + const ink = instances.get(process.stdout) + + // Memoize so callers can safely use the return value in dependency arrays. + // ink is a singleton per stdout — stable across renders. + return useMemo(() => { + if (!ink) { + return { + copySelection: () => '', + copySelectionNoClear: () => '', + clearSelection: () => {}, + hasSelection: () => false, + getState: () => null, + subscribe: () => () => {}, + shiftAnchor: () => {}, + shiftSelection: () => {}, + moveFocus: () => {}, + captureScrolledRows: () => {}, + setSelectionBgColor: () => {} + } + } + + return { + copySelection: () => ink.copySelection(), + copySelectionNoClear: () => ink.copySelectionNoClear(), + clearSelection: () => ink.clearTextSelection(), + hasSelection: () => ink.hasTextSelection(), + getState: () => ink.selection, + subscribe: (cb: () => void) => ink.subscribeToSelectionChange(cb), + shiftAnchor: (dRow: number, minRow: number, maxRow: number) => shiftAnchor(ink.selection, dRow, minRow, maxRow), + shiftSelection: (dRow, minRow, maxRow) => ink.shiftSelectionForScroll(dRow, minRow, maxRow), + moveFocus: (move: FocusMove) => ink.moveSelectionFocus(move), + captureScrolledRows: (firstRow, lastRow, side) => ink.captureScrolledRows(firstRow, lastRow, side), + setSelectionBgColor: (color: string) => ink.setSelectionBgColor(color) + } + }, [ink]) +} + +const NO_SUBSCRIBE = () => () => {} +const ALWAYS_FALSE = () => false + +/** + * Reactive selection-exists state. Re-renders the caller when a text + * selection is created or cleared. Always returns false outside + * fullscreen mode (selection is only available in alt-screen). + */ +export function useHasSelection(): boolean { + useContext(StdinContext) + const ink = instances.get(process.stdout) + + return useSyncExternalStore( + ink ? ink.subscribeToSelectionChange : NO_SUBSCRIBE, + ink ? ink.hasTextSelection : ALWAYS_FALSE + ) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-stdin.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-stdin.ts new file mode 100644 index 0000000000..58cf746f57 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-stdin.ts @@ -0,0 +1,9 @@ +import { useContext } from 'react' + +import StdinContext from '../components/StdinContext.js' + +/** + * `useStdin` is a React hook, which exposes stdin stream. + */ +const useStdin = () => useContext(StdinContext) +export default useStdin diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-tab-status.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-tab-status.ts new file mode 100644 index 0000000000..a3cdf17bc2 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-tab-status.ts @@ -0,0 +1,71 @@ +import { useContext, useEffect, useRef } from 'react' + +import { CLEAR_TAB_STATUS, supportsTabStatus, tabStatus, wrapForMultiplexer } from '../termio/osc.js' +import type { Color } from '../termio/types.js' +import { TerminalWriteContext } from '../useTerminalNotification.js' + +export type TabStatusKind = 'idle' | 'busy' | 'waiting' + +const rgb = (r: number, g: number, b: number): Color => ({ + type: 'rgb', + r, + g, + b +}) + +// Per the OSC 21337 usage guide's suggested mapping. +const TAB_STATUS_PRESETS: Record = { + idle: { + indicator: rgb(0, 215, 95), + status: 'Idle', + statusColor: rgb(136, 136, 136) + }, + busy: { + indicator: rgb(255, 149, 0), + status: 'Working…', + statusColor: rgb(255, 149, 0) + }, + waiting: { + indicator: rgb(95, 135, 255), + status: 'Waiting', + statusColor: rgb(95, 135, 255) + } +} + +/** + * Declaratively set the tab-status indicator (OSC 21337). + * + * Emits a colored dot + short status text to the tab sidebar. Terminals + * that don't support OSC 21337 discard the sequence silently, so this is + * safe to call unconditionally. Wrapped for tmux/screen passthrough. + * + * Pass `null` to opt out. If a status was previously set, transitioning to + * `null` emits CLEAR_TAB_STATUS so toggling off mid-session doesn't leave + * a stale dot. Process-exit cleanup is handled by ink.tsx's unmount path. + */ +export function useTabStatus(kind: TabStatusKind | null): void { + const writeRaw = useContext(TerminalWriteContext) + const prevKindRef = useRef(null) + + useEffect(() => { + // When kind transitions from non-null to null (e.g. user toggles off + // showStatusInTerminalTab mid-session), clear the stale dot. + if (kind === null) { + if (prevKindRef.current !== null && writeRaw && supportsTabStatus()) { + writeRaw(wrapForMultiplexer(CLEAR_TAB_STATUS)) + } + + prevKindRef.current = null + + return + } + + prevKindRef.current = kind + + if (!writeRaw || !supportsTabStatus()) { + return + } + + writeRaw(wrapForMultiplexer(tabStatus(TAB_STATUS_PRESETS[kind]))) + }, [kind, writeRaw]) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-focus.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-focus.ts new file mode 100644 index 0000000000..230d87a39f --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-focus.ts @@ -0,0 +1,18 @@ +import { useContext } from 'react' + +import TerminalFocusContext from '../components/TerminalFocusContext.js' + +/** + * Hook to check if the terminal has focus. + * + * Uses DECSET 1004 focus reporting - the terminal sends escape sequences + * when it gains or loses focus. These are handled automatically + * by Ink and filtered from useInput. + * + * @returns true if the terminal is focused (or focus state is unknown) + */ +export function useTerminalFocus(): boolean { + const { isTerminalFocused } = useContext(TerminalFocusContext) + + return isTerminalFocused +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-title.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-title.ts new file mode 100644 index 0000000000..6b5b28f5c3 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-title.ts @@ -0,0 +1,34 @@ +import { useContext, useEffect } from 'react' +import stripAnsi from 'strip-ansi' + +import { OSC, osc } from '../termio/osc.js' +import { TerminalWriteContext } from '../useTerminalNotification.js' + +/** + * Declaratively set the terminal tab/window title. + * + * Pass a string to set the title. ANSI escape sequences are stripped + * automatically so callers don't need to know about terminal encoding. + * Pass `null` to opt out — the hook becomes a no-op and leaves the + * terminal title untouched. + * + * On Windows, uses `process.title` (classic conhost doesn't support OSC). + * Elsewhere, writes OSC 0 (set title+icon) via Ink's stdout. + */ +export function useTerminalTitle(title: string | null): void { + const writeRaw = useContext(TerminalWriteContext) + + useEffect(() => { + if (title === null || !writeRaw) { + return + } + + const clean = stripAnsi(title) + + if (process.platform === 'win32') { + process.title = clean + } else { + writeRaw(osc(OSC.SET_TITLE_AND_ICON, clean)) + } + }, [title, writeRaw]) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-viewport.ts b/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-viewport.ts new file mode 100644 index 0000000000..ada3059d91 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/hooks/use-terminal-viewport.ts @@ -0,0 +1,100 @@ +import { useCallback, useContext, useLayoutEffect, useRef } from 'react' + +import { TerminalSizeContext } from '../components/TerminalSizeContext.js' +import type { DOMElement } from '../dom.js' + +type ViewportEntry = { + /** + * Whether the element is currently within the terminal viewport + */ + isVisible: boolean +} + +/** + * Hook to detect if a component is within the terminal viewport. + * + * Returns a callback ref and a viewport entry object. + * Attach the ref to the component you want to track. + * + * The entry is updated during the layout phase (useLayoutEffect) so callers + * always read fresh values during render. Visibility changes do NOT trigger + * re-renders on their own — callers that re-render for other reasons (e.g. + * animation ticks, state changes) will pick up the latest value naturally. + * This avoids infinite update loops when combined with other layout effects + * that also call setState. + * + * @example + * const [ref, entry] = useTerminalViewport() + * return ... + */ +export function useTerminalViewport(): [ref: (element: DOMElement | null) => void, entry: ViewportEntry] { + const terminalSize = useContext(TerminalSizeContext) + const elementRef = useRef(null) + const entryRef = useRef({ isVisible: true }) + + const setElement = useCallback((el: DOMElement | null) => { + elementRef.current = el + }, []) + + // Runs on every render because yoga layout values can change + // without React being aware. Only updates the ref — no setState + // to avoid cascading re-renders during the commit phase. + // Walks the DOM ancestor chain fresh each time to avoid holding stale + // references after yoga tree rebuilds. + useLayoutEffect(() => { + const element = elementRef.current + + if (!element?.yogaNode || !terminalSize) { + return + } + + const height = element.yogaNode.getComputedHeight() + const rows = terminalSize.rows + + // Walk the DOM parent chain (not yoga.getParent()) so we can detect + // scroll containers and subtract their scrollTop. Yoga computes layout + // positions without scroll offset — scrollTop is applied at render time. + // Without this, an element inside a ScrollBox whose yoga position exceeds + // terminalRows would be considered offscreen even when scrolled into view + // (e.g., the spinner in fullscreen mode after enough messages accumulate). + let absoluteTop = element.yogaNode.getComputedTop() + let parent: DOMElement | undefined = element.parentNode + let root = element.yogaNode + + while (parent) { + if (parent.yogaNode) { + absoluteTop += parent.yogaNode.getComputedTop() + root = parent.yogaNode + } + + // scrollTop is only ever set on scroll containers (by ScrollBox + renderer). + // Non-scroll nodes have undefined scrollTop → falsy fast-path. + if (parent.scrollTop) { + absoluteTop -= parent.scrollTop + } + + parent = parent.parentNode + } + + // Only the root's height matters + const screenHeight = root.getComputedHeight() + + const bottom = absoluteTop + height + // When content overflows the viewport (screenHeight > rows), the + // cursor-restore at frame end scrolls one extra row into scrollback. + // log-update.ts accounts for this with scrollbackRows = viewportY + 1. + // We must match, otherwise an element at the boundary is considered + // "visible" here (animation keeps ticking) but its row is treated as + // scrollback by log-update (content change → full reset → flicker). + const cursorRestoreScroll = screenHeight > rows ? 1 : 0 + const viewportY = Math.max(0, screenHeight - rows) + cursorRestoreScroll + const viewportBottom = viewportY + rows + const visible = bottom > viewportY && absoluteTop < viewportBottom + + if (visible !== entryRef.current.isVisible) { + entryRef.current = { isVisible: visible } + } + }) + + return [setElement, entryRef.current] +} diff --git a/ui-tui/packages/hermes-ink/src/ink/ink.tsx b/ui-tui/packages/hermes-ink/src/ink/ink.tsx new file mode 100644 index 0000000000..1543dc7fce --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/ink.tsx @@ -0,0 +1,2201 @@ +import { closeSync, constants as fsConstants, openSync, readSync, writeSync } from 'fs' +import { format } from 'util' + +import autoBind from 'auto-bind' +import noop from 'lodash-es/noop.js' +import throttle from 'lodash-es/throttle.js' +import React, { type ReactNode } from 'react' +import type { FiberRoot } from 'react-reconciler' +import { ConcurrentRoot } from 'react-reconciler/constants.js' +import { onExit } from 'signal-exit' + +import { flushInteractionTime } from '../bootstrap/state.js' +import { getYogaCounters } from '../native-ts/yoga-layout/index.js' +import { logForDebugging } from '../utils/debug.js' +import { logError } from '../utils/log.js' + +import { colorize } from './colorize.js' +import App from './components/App.js' +import type { CursorDeclaration, CursorDeclarationSetter } from './components/CursorDeclarationContext.js' +import { FRAME_INTERVAL_MS } from './constants.js' +import * as dom from './dom.js' +import { KeyboardEvent } from './events/keyboard-event.js' +import { FocusManager } from './focus.js' +import { emptyFrame, type Frame, type FrameEvent } from './frame.js' +import { dispatchClick, dispatchHover, dispatchMouse } from './hit-test.js' +import instances from './instances.js' +import { LogUpdate } from './log-update.js' +import { nodeCache } from './node-cache.js' +import { optimize } from './optimizer.js' +import Output from './output.js' +import type { ParsedKey } from './parse-keypress.js' +import reconciler, { + dispatcher, + getLastCommitMs, + getLastYogaMs, + recordYogaMs, + resetProfileCounters +} from './reconciler.js' +import renderNodeToOutput, { consumeFollowScroll, didLayoutShift } from './render-node-to-output.js' +import { applyPositionedHighlight, type MatchPosition, scanPositions } from './render-to-screen.js' +import createRenderer, { type Renderer } from './renderer.js' +import { + cellAt, + CellWidth, + CharPool, + createScreen, + HyperlinkPool, + isEmptyCellAt, + migrateScreenPools, + StylePool +} from './screen.js' +import { applySearchHighlight } from './searchHighlight.js' +import { + applySelectionOverlay, + captureScrolledRows, + clearSelection, + createSelectionState, + extendSelection, + findPlainTextUrlAt, + type FocusMove, + getSelectedText, + hasSelection, + moveFocus, + type SelectionState, + selectLineAt, + selectWordAt, + shiftAnchor, + shiftSelection, + shiftSelectionForFollow, + startSelection, + updateSelection +} from './selection.js' +import { supportsExtendedKeys, SYNC_OUTPUT_SUPPORTED, type Terminal, writeDiffToTerminal } from './terminal.js' +import { + CURSOR_HOME, + cursorMove, + cursorPosition, + DISABLE_KITTY_KEYBOARD, + DISABLE_MODIFY_OTHER_KEYS, + ENABLE_KITTY_KEYBOARD, + ENABLE_MODIFY_OTHER_KEYS, + ERASE_SCREEN +} from './termio/csi.js' +import { + DBP, + DFE, + DISABLE_MOUSE_TRACKING, + ENABLE_MOUSE_TRACKING, + ENTER_ALT_SCREEN, + EXIT_ALT_SCREEN, + SHOW_CURSOR +} from './termio/dec.js' +import { + CLEAR_ITERM2_PROGRESS, + CLEAR_TAB_STATUS, + setClipboard, + supportsTabStatus, + wrapForMultiplexer +} from './termio/osc.js' +import { TerminalWriteProvider } from './useTerminalNotification.js' + +// Alt-screen: renderer.ts sets cursor.visible = !isTTY || screen.height===0, +// which is always false in alt-screen (TTY + content fills screen). +// Reusing a frozen object saves 1 allocation per frame. +const ALT_SCREEN_ANCHOR_CURSOR = Object.freeze({ + x: 0, + y: 0, + visible: false +}) + +const CURSOR_HOME_PATCH = Object.freeze({ + type: 'stdout' as const, + content: CURSOR_HOME +}) + +const ERASE_THEN_HOME_PATCH = Object.freeze({ + type: 'stdout' as const, + content: ERASE_SCREEN + CURSOR_HOME +}) + +// Cached per-Ink-instance, invalidated on resize. frame.cursor.y for +// alt-screen is always terminalRows - 1 (renderer.ts). +function makeAltScreenParkPatch(terminalRows: number) { + return Object.freeze({ + type: 'stdout' as const, + content: cursorPosition(terminalRows, 1) + }) +} + +export type Options = { + stdout: NodeJS.WriteStream + stdin: NodeJS.ReadStream + stderr: NodeJS.WriteStream + exitOnCtrlC: boolean + patchConsole: boolean + waitUntilExit?: () => Promise + onFrame?: (event: FrameEvent) => void +} +export default class Ink { + private readonly log: LogUpdate + private readonly terminal: Terminal + private scheduleRender: (() => void) & { + cancel?: () => void + } + // Ignore last render after unmounting a tree to prevent empty output before exit + private isUnmounted = false + private isPaused = false + private readonly container: FiberRoot + private rootNode: dom.DOMElement + readonly focusManager: FocusManager + private renderer: Renderer + private readonly stylePool: StylePool + private charPool: CharPool + private hyperlinkPool: HyperlinkPool + private exitPromise?: Promise + private restoreConsole?: () => void + private restoreStderr?: () => void + private readonly unsubscribeTTYHandlers?: () => void + private terminalColumns: number + private terminalRows: number + private currentNode: ReactNode = null + private frontFrame: Frame + private backFrame: Frame + private lastPoolResetTime = performance.now() + private drainTimer: ReturnType | null = null + private lastYogaCounters: { + ms: number + visited: number + measured: number + cacheHits: number + live: number + } = { + ms: 0, + visited: 0, + measured: 0, + cacheHits: 0, + live: 0 + } + private altScreenParkPatch: Readonly<{ + type: 'stdout' + content: string + }> + // Text selection state (alt-screen only). Owned here so the overlay + // pass in onRender can read it and App.tsx can update it from mouse + // events. Public so instances.get() callers can access. + readonly selection: SelectionState = createSelectionState() + // Search highlight query (alt-screen only). Setter below triggers + // scheduleRender; applySearchHighlight in onRender inverts matching cells. + private searchHighlightQuery = '' + // Position-based highlight. VML scans positions ONCE (via + // scanElementSubtree, when the target message is mounted), stores them + // message-relative, sets this for every-frame apply. rowOffset = + // message's current screen-top. currentIdx = which position is + // "current" (yellow). null clears. Positions are known upfront — + // navigation is index arithmetic, no scan-feedback loop. + private searchPositions: { + positions: MatchPosition[] + rowOffset: number + currentIdx: number + } | null = null + // React-land subscribers for selection state changes (useHasSelection). + // Fired alongside the terminal repaint whenever the selection mutates + // so UI (e.g. footer hints) can react to selection appearing/clearing. + private readonly selectionListeners = new Set<() => void>() + private selectionWasActive = false + // DOM nodes currently under the pointer (mode-1003 motion). Held here + // so App.tsx's handleMouseEvent is stateless — dispatchHover diffs + // against this set and mutates it in place. + private readonly hoveredNodes = new Set() + // Set by via setAltScreenActive(). Controls the + // renderer's cursor.y clamping (keeps cursor in-viewport to avoid + // LF-induced scroll when screen.height === terminalRows) and gates + // alt-screen-aware SIGCONT/resize/unmount handling. + private altScreenActive = false + // Set alongside altScreenActive so SIGCONT resume knows whether to + // re-enable mouse tracking (not all uses want it). + private altScreenMouseTracking = false + // True when the previous frame's screen buffer cannot be trusted for + // blit — selection overlay mutated it, resetFramesForAltScreen() + // replaced it with blanks, or forceRedraw() reset it to 0×0. Forces + // one full-render frame; steady-state frames after clear it and regain + // the blit + narrow-damage fast path. + private prevFrameContaminated = false + // Set by handleResize: prepend ERASE_SCREEN to the next onRender's patches + // INSIDE the BSU/ESU block so clear+paint is atomic. Writing ERASE_SCREEN + // synchronously in handleResize would leave the screen blank for the ~80ms + // render() takes; deferring into the atomic block means old content stays + // visible until the new frame is fully ready. + private needsEraseBeforePaint = false + // Native cursor positioning: a component (via useDeclaredCursor) declares + // where the terminal cursor should be parked after each frame. Terminal + // emulators render IME preedit text at the physical cursor position, and + // screen readers / screen magnifiers track it — so parking at the text + // input's caret makes CJK input appear inline and lets a11y tools follow. + private cursorDeclaration: CursorDeclaration | null = null + // Main-screen: physical cursor position after the declared-cursor move, + // tracked separately from frame.cursor (which must stay at content-bottom + // for log-update's relative-move invariants). Alt-screen doesn't need + // this — every frame begins with CSI H. null = no move emitted last frame. + private displayCursor: { + x: number + y: number + } | null = null + // Burst of SIGWINCH (vscode panel drag) → one React commit per + // microtask. Dims are captured sync in handleResize; only the + // expensive tree rebuild defers. + private pendingResizeRender = false + + // Fold synchronous re-entry (selection fanout, onFrame callback) + // into one follow-up microtask instead of stacking renders. + private isRendering = false + private immediateRerenderRequested = false + constructor(private readonly options: Options) { + autoBind(this) + + if (this.options.patchConsole) { + this.restoreConsole = this.patchConsole() + this.restoreStderr = this.patchStderr() + } + + this.terminal = { + stdout: options.stdout, + stderr: options.stderr + } + this.terminalColumns = options.stdout.columns || 80 + this.terminalRows = options.stdout.rows || 24 + this.altScreenParkPatch = makeAltScreenParkPatch(this.terminalRows) + this.stylePool = new StylePool() + this.charPool = new CharPool() + this.hyperlinkPool = new HyperlinkPool() + this.frontFrame = emptyFrame( + this.terminalRows, + this.terminalColumns, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.backFrame = emptyFrame( + this.terminalRows, + this.terminalColumns, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.log = new LogUpdate({ + isTTY: (options.stdout.isTTY as boolean | undefined) || false, + stylePool: this.stylePool + }) + + // scheduleRender is called from the reconciler's resetAfterCommit, which + // runs BEFORE React's layout phase (ref attach + useLayoutEffect). Any + // state set in layout effects — notably the cursorDeclaration from + // useDeclaredCursor — would lag one commit behind if we rendered + // synchronously. Deferring to a microtask runs onRender after layout + // effects have committed, so the native cursor tracks the caret without + // a one-keystroke lag. Same event-loop tick, so throughput is unchanged. + // Test env uses onImmediateRender (direct onRender, no throttle) so + // existing synchronous lastFrame() tests are unaffected. + const deferredRender = (): void => queueMicrotask(this.onRender) + this.scheduleRender = throttle(deferredRender, FRAME_INTERVAL_MS, { + leading: true, + trailing: true + }) + + // Ignore last render after unmounting a tree to prevent empty output before exit + this.isUnmounted = false + + // Unmount when process exits + this.unsubscribeExit = onExit(this.unmount, { + alwaysLast: false + }) + + if (options.stdout.isTTY) { + options.stdout.on('resize', this.handleResize) + process.on('SIGCONT', this.handleResume) + + this.unsubscribeTTYHandlers = () => { + options.stdout.off('resize', this.handleResize) + process.off('SIGCONT', this.handleResume) + } + } + + this.rootNode = dom.createNode('ink-root') + this.focusManager = new FocusManager((target, event) => dispatcher.dispatchDiscrete(target, event)) + this.rootNode.focusManager = this.focusManager + this.renderer = createRenderer(this.rootNode, this.stylePool) + this.rootNode.onRender = this.scheduleRender + this.rootNode.onImmediateRender = this.onRender + + this.rootNode.onComputeLayout = () => { + // Calculate layout during React's commit phase so useLayoutEffect hooks + // have access to fresh layout data + // Guard against accessing freed Yoga nodes after unmount + if (this.isUnmounted) { + return + } + + if (this.rootNode.yogaNode) { + const t0 = performance.now() + this.rootNode.yogaNode.setWidth(this.terminalColumns) + this.rootNode.yogaNode.calculateLayout(this.terminalColumns) + const ms = performance.now() - t0 + recordYogaMs(ms) + const c = getYogaCounters() + this.lastYogaCounters = { + ms, + ...c + } + } + } + + this.container = reconciler.createContainer( + this.rootNode, + ConcurrentRoot, + null, + false, + null, + 'id', + noop, + // onUncaughtError + noop, + // onCaughtError + noop, + // onRecoverableError + noop // onDefaultTransitionIndicator + ) + + if (process.env.NODE_ENV === 'development') { + reconciler.injectIntoDevTools({ + bundleType: 0, + // Reporting React DOM's version, not Ink's + // See https://github.com/facebook/react/issues/16666#issuecomment-532639905 + version: '16.13.1', + rendererPackageName: 'ink' + }) + } + } + private handleResume = () => { + if (!this.options.stdout.isTTY) { + return + } + + // Alt screen: after SIGCONT, content is stale (shell may have written + // to main screen, switching focus away) and mouse tracking was + // disabled by handleSuspend. + if (this.altScreenActive) { + this.reenterAltScreen() + + return + } + + // Main screen: start fresh to prevent clobbering terminal content + this.frontFrame = emptyFrame( + this.frontFrame.viewport.height, + this.frontFrame.viewport.width, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.backFrame = emptyFrame( + this.backFrame.viewport.height, + this.backFrame.viewport.width, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.log.reset() + // Physical cursor position is unknown after the shell took over during + // suspend. Clear displayCursor so the next frame's cursor preamble + // doesn't emit a relative move from a stale park position. + this.displayCursor = null + } + + // Dims captured sync — closes the stale-dim window the original + // debounce rejection warned about. Expensive React commit defers to + // one microtask per burst: vscode fires many SIGWINCHes per panel + // drag, each ~80ms uncoalesced = event loop visibly locks up. + private handleResize = () => { + const cols = this.options.stdout.columns || 80 + const rows = this.options.stdout.rows || 24 + + // Terminals often emit 2+ resize events for one user action (window + // settling). Same-dimension events are no-ops; skip to avoid redundant + // frame resets and renders. + if (cols === this.terminalColumns && rows === this.terminalRows) { + return + } + + this.terminalColumns = cols + this.terminalRows = rows + this.altScreenParkPatch = makeAltScreenParkPatch(this.terminalRows) + + // Pending throttled/drain work captured stale dims — cancel so + // the upcoming microtask owns the next frame. + this.scheduleRender.cancel?.() + + if (this.drainTimer !== null) { + clearTimeout(this.drainTimer) + this.drainTimer = null + } + + // Alt screen: reset frame buffers so the next render repaints from + // scratch (prevFrameContaminated → every cell written, wrapped in + // BSU/ESU — old content stays visible until the new frame swaps + // atomically). Re-assert mouse tracking (some emulators reset it on + // resize). Do NOT write ENTER_ALT_SCREEN: iTerm2 treats ?1049h as a + // buffer clear even when already in alt — that's the blank flicker. + // Self-healing re-entry (if something kicked us out of alt) is handled + // by handleResume (SIGCONT) and the sleep-wake detector; resize itself + // doesn't exit alt-screen. Do NOT write ERASE_SCREEN: render() below + // can take ~80ms; erasing first leaves the screen blank that whole time. + if (this.altScreenActive && !this.isPaused && this.options.stdout.isTTY) { + if (this.altScreenMouseTracking) { + this.options.stdout.write(ENABLE_MOUSE_TRACKING) + } + + this.resetFramesForAltScreen() + this.needsEraseBeforePaint = true + } + + // Already queued: later events in this burst updated dims/alt-screen + // prep above; the queued render picks up the latest values when it + // fires (React commit → onComputeLayout → scheduleRender → onRender). + if (this.pendingResizeRender) { + return + } + + this.pendingResizeRender = true + + queueMicrotask(() => { + this.pendingResizeRender = false + + if (this.isUnmounted || this.currentNode === null) { + return + } + + this.render(this.currentNode) + }) + } + resolveExitPromise: () => void = () => {} + rejectExitPromise: (reason?: Error) => void = () => {} + unsubscribeExit: () => void = () => {} + + /** + * Pause Ink and hand the terminal over to an external TUI (e.g. git + * commit editor). In non-fullscreen mode this enters the alt screen; + * in fullscreen mode we're already in alt so we just clear it. + * Call `exitAlternateScreen()` when done to restore Ink. + */ + enterAlternateScreen(): void { + this.pause() + this.suspendStdin() + this.options.stdout.write( + // Disable extended key reporting first — editors that don't speak + // CSI-u (e.g. nano) show "Unknown sequence" for every Ctrl- if + // kitty/modifyOtherKeys stays active. exitAlternateScreen re-enables. + DISABLE_KITTY_KEYBOARD + + DISABLE_MODIFY_OTHER_KEYS + + (this.altScreenMouseTracking ? DISABLE_MOUSE_TRACKING : '') + + // disable mouse (no-op if off) + (this.altScreenActive ? '' : '\x1b[?1049h') + + // enter alt (already in alt if fullscreen) + '\x1b[?1004l' + + // disable focus reporting + '\x1b[0m' + + // reset attributes + '\x1b[?25h' + + // show cursor + '\x1b[2J' + + // clear screen + '\x1b[H' // cursor home + ) + } + + /** + * Resume Ink after an external TUI handoff with a full repaint. + * In non-fullscreen mode this exits the alt screen back to main; + * in fullscreen mode we re-enter alt and clear + repaint. + * + * The re-enter matters: terminal editors (vim, nano, less) write + * smcup/rmcup (?1049h/?1049l), so even though we started in alt, + * the editor's rmcup on exit drops us to main screen. Without + * re-entering, the 2J below wipes the user's main-screen scrollback + * and subsequent renders land in main — native terminal scroll + * returns, fullscreen scroll is dead. + */ + exitAlternateScreen(): void { + this.options.stdout.write( + (this.altScreenActive ? ENTER_ALT_SCREEN : '') + + // re-enter alt — vim's rmcup dropped us to main + '\x1b[2J' + + // clear screen (now alt if fullscreen) + '\x1b[H' + + // cursor home + (this.altScreenMouseTracking ? ENABLE_MOUSE_TRACKING : '') + + (this.altScreenActive ? '' : '\x1b[?1049l') + + // exit alt (non-fullscreen only) + '\x1b[?25l' // hide cursor (Ink manages) + ) + this.resumeStdin() + + if (this.altScreenActive) { + this.resetFramesForAltScreen() + } else { + this.repaint() + } + + this.resume() + // Re-enable focus reporting and extended key reporting — terminal + // editors (vim, nano, etc.) write their own modifyOtherKeys level on + // entry and reset it on exit, leaving us unable to distinguish + // ctrl+shift+ from ctrl+. Pop-before-push keeps the + // Kitty stack balanced (a well-behaved editor restores our entry, so + // without the pop we'd accumulate depth on each editor round-trip). + this.options.stdout.write( + '\x1b[?1004h' + + (supportsExtendedKeys() ? DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS : '') + ) + } + onRender() { + if (this.isUnmounted || this.isPaused) { + return + } + + // Fold synchronous re-entry (selection fanout, onFrame callback) + // into one follow-up microtask — back-to-back renders within one + // macrotask were the freeze multiplier. + if (this.isRendering) { + this.immediateRerenderRequested = true + + return + } + + this.isRendering = true + + // Entering a render cancels any pending drain tick — this render will + // handle the drain (and re-schedule below if needed). Prevents a + // wheel-event-triggered render AND a drain-timer render both firing. + if (this.drainTimer !== null) { + clearTimeout(this.drainTimer) + this.drainTimer = null + } + + // Flush deferred interaction-time update before rendering so we call + // Date.now() at most once per frame instead of once per keypress. + // Done before the render to avoid dirtying state that would trigger + // an extra React re-render cycle. + flushInteractionTime() + const renderStart = performance.now() + const terminalWidth = this.options.stdout.columns || 80 + const terminalRows = this.options.stdout.rows || 24 + + const frame = this.renderer({ + frontFrame: this.frontFrame, + backFrame: this.backFrame, + isTTY: this.options.stdout.isTTY, + terminalWidth, + terminalRows, + altScreen: this.altScreenActive, + prevFrameContaminated: this.prevFrameContaminated + }) + + const rendererMs = performance.now() - renderStart + + // Sticky/auto-follow scrolled the ScrollBox this frame. Translate the + // selection by the same delta so the highlight stays anchored to the + // TEXT (native terminal behavior — the selection walks up the screen + // as content scrolls, eventually clipping at the top). frontFrame + // still holds the PREVIOUS frame's screen (swap is at ~500 below), so + // captureScrolledRows reads the rows that are about to scroll out + // before they're overwritten — the text stays copyable until the + // selection scrolls entirely off. During drag, focus tracks the mouse + // (screen-local) so only anchor shifts — selection grows toward the + // mouse as the anchor walks up. After release, both ends are text- + // anchored and move as a block. + const follow = consumeFollowScroll() + + if ( + follow && + this.selection.anchor && + // Only translate if the selection is ON scrollbox content. Selections + // in the footer/prompt/StickyPromptHeader are on static text — the + // scroll doesn't move what's under them. Without this guard, a + // footer selection would be shifted by -delta then clamped to + // viewportBottom, teleporting it into the scrollbox. Mirror the + // bounds check the deleted check() in ScrollKeybindingHandler had. + this.selection.anchor.row >= follow.viewportTop && + this.selection.anchor.row <= follow.viewportBottom + ) { + const { delta, viewportTop, viewportBottom } = follow + + // captureScrolledRows and shift* are a pair: capture grabs rows about + // to scroll off, shift moves the selection endpoint so the same rows + // won't intersect again next frame. Capturing without shifting leaves + // the endpoint in place, so the SAME viewport rows re-intersect every + // frame and scrolledOffAbove grows without bound — getSelectedText + // then returns ever-growing text on each re-copy. Keep capture inside + // each shift branch so the pairing can't be broken by a new guard. + if (this.selection.isDragging) { + if (hasSelection(this.selection)) { + captureScrolledRows(this.selection, this.frontFrame.screen, viewportTop, viewportTop + delta - 1, 'above') + } + + shiftAnchor(this.selection, -delta, viewportTop, viewportBottom) + } else if ( + // Flag-3 guard: the anchor check above only proves ONE endpoint is + // on scrollbox content. A drag from row 3 (scrollbox) into the + // footer at row 6, then release, leaves focus outside the viewport + // — shiftSelectionForFollow would clamp it to viewportBottom, + // teleporting the highlight from static footer into the scrollbox. + // Symmetric check: require BOTH ends inside to translate. A + // straddling selection falls through to NEITHER shift NOR capture: + // the footer endpoint pins the selection, text scrolls away under + // the highlight, and getSelectedText reads the CURRENT screen + // contents — no accumulation. Dragging branch doesn't need this: + // shiftAnchor ignores focus, and the anchor DOES shift (so capture + // is correct there even when focus is in the footer). + !this.selection.focus || + (this.selection.focus.row >= viewportTop && this.selection.focus.row <= viewportBottom) + ) { + if (hasSelection(this.selection)) { + captureScrolledRows(this.selection, this.frontFrame.screen, viewportTop, viewportTop + delta - 1, 'above') + } + + const cleared = shiftSelectionForFollow(this.selection, -delta, viewportTop, viewportBottom) + + // Auto-clear (both ends overshot minRow) must notify React-land + // so useHasSelection re-renders and the footer copy/escape hint + // disappears. notifySelectionChange() would recurse into onRender; + // fire the listeners directly — they schedule a React update for + // LATER, they don't re-enter this frame. + if (cleared) { + for (const cb of this.selectionListeners) { + cb() + } + } + } + } + + // Selection overlay: invert cell styles in the screen buffer itself, + // so the diff picks up selection as ordinary cell changes and + // LogUpdate remains a pure diff engine. + // + // Full-screen damage (PR #20120) is a correctness backstop for the + // sibling-resize bleed: when flexbox siblings resize between frames + // (spinner appears → bottom grows → scrollbox shrinks), the + // cached-clear + clip-and-cull + setCellAt damage union can miss + // transition cells at the boundary. But that only happens when layout + // actually SHIFTS — didLayoutShift() tracks exactly this (any node's + // cached yoga position/size differs from current, or a child was + // removed). Steady-state frames (spinner rotate, clock tick, text + // stream into fixed-height box) don't shift layout, so normal damage + // bounds are correct and diffEach only compares the damaged region. + // + // Selection also requires full damage: overlay writes via setCellStyleId + // which doesn't track damage, and prev-frame overlay cells need to be + // compared when selection moves/clears. prevFrameContaminated covers + // the frame-after-selection-clears case. + let selActive = false + let hlActive = false + + if (this.altScreenActive) { + selActive = hasSelection(this.selection) + + if (selActive) { + applySelectionOverlay(frame.screen, this.selection, this.stylePool) + } + + // Scan-highlight: inverse on ALL visible matches (less/vim style). + // Position-highlight (below) overlays CURRENT (yellow) on top. + hlActive = applySearchHighlight(frame.screen, this.searchHighlightQuery, this.stylePool) + + // Position-based CURRENT: write yellow at positions[currentIdx] + + // rowOffset. No scanning — positions came from a prior scan when + // the message first mounted. Message-relative + rowOffset = screen. + if (this.searchPositions) { + const sp = this.searchPositions + + const posApplied = applyPositionedHighlight( + frame.screen, + this.stylePool, + sp.positions, + sp.rowOffset, + sp.currentIdx + ) + + hlActive = hlActive || posApplied + } + } + + // Full-damage backstop: applies on BOTH alt-screen and main-screen. + // Layout shifts (spinner appears, status line resizes) can leave stale + // cells at sibling boundaries that per-node damage tracking misses. + // Selection/highlight overlays write via setCellStyleId which doesn't + // track damage. prevFrameContaminated covers the cleanup frame. + if (didLayoutShift() || selActive || hlActive || this.prevFrameContaminated) { + frame.screen.damage = { + x: 0, + y: 0, + width: frame.screen.width, + height: frame.screen.height + } + } + + // Alt-screen: anchor the physical cursor to (0,0) before every diff. + // All cursor moves in log-update are RELATIVE to prev.cursor; if tmux + // (or any emulator) perturbs the physical cursor out-of-band (status + // bar refresh, pane redraw, Cmd+K wipe), the relative moves drift and + // content creeps up 1 row/frame. CSI H resets the physical cursor; + // passing prev.cursor=(0,0) makes the diff compute from the same spot. + // Self-healing against any external cursor manipulation. Main-screen + // can't do this — cursor.y tracks scrollback rows CSI H can't reach. + // The CSI H write is deferred until after the diff is computed so we + // can skip it for empty diffs (no writes → physical cursor unused). + let prevFrame = this.frontFrame + + if (this.altScreenActive) { + prevFrame = { + ...this.frontFrame, + cursor: ALT_SCREEN_ANCHOR_CURSOR + } + } + + const tDiff = performance.now() + + const diff = this.log.render( + prevFrame, + frame, + this.altScreenActive, + // DECSTBM needs BSU/ESU atomicity — without it the outer terminal + // renders the scrolled-but-not-yet-repainted intermediate state. + // tmux is the main case (re-emits DECSTBM with its own timing and + // doesn't implement DEC 2026, so SYNC_OUTPUT_SUPPORTED is false). + SYNC_OUTPUT_SUPPORTED + ) + + const diffMs = performance.now() - tDiff + // Swap buffers + this.backFrame = this.frontFrame + this.frontFrame = frame + + // Periodically reset char/hyperlink pools to prevent unbounded growth + // during long sessions. 5 minutes is infrequent enough that the O(cells) + // migration cost is negligible. Reuses renderStart to avoid extra clock call. + if (renderStart - this.lastPoolResetTime > 5 * 60 * 1000) { + this.resetPools() + this.lastPoolResetTime = renderStart + } + + const flickers: FrameEvent['flickers'] = [] + + for (const patch of diff) { + if (patch.type === 'clearTerminal') { + flickers.push({ + desiredHeight: frame.screen.height, + availableHeight: frame.viewport.height, + reason: patch.reason + }) + } + } + + const tOptimize = performance.now() + const optimized = optimize(diff) + const optimizeMs = performance.now() - tOptimize + const hasDiff = optimized.length > 0 + + if (this.altScreenActive && hasDiff) { + // Prepend CSI H to anchor the physical cursor to (0,0) so + // log-update's relative moves compute from a known spot (self-healing + // against out-of-band cursor drift, see the ALT_SCREEN_ANCHOR_CURSOR + // comment above). Append CSI row;1 H to park the cursor at the bottom + // row (where the prompt input is) — without this, the cursor ends + // wherever the last diff write landed (a different row every frame), + // making iTerm2's cursor guide flicker as it chases the cursor. + // BSU/ESU protects content atomicity but iTerm2's guide tracks cursor + // position independently. Parking at bottom (not 0,0) keeps the guide + // where the user's attention is. + // + // After resize, prepend ERASE_SCREEN too. The diff only writes cells + // that changed; cells where new=blank and prev-buffer=blank get skipped + // — but the physical terminal still has stale content there (shorter + // lines at new width leave old-width text tails visible). ERASE inside + // BSU/ESU is atomic: old content stays visible until the whole + // erase+paint lands, then swaps in one go. Writing ERASE_SCREEN + // synchronously in handleResize would blank the screen for the ~80ms + // render() takes. + if (this.needsEraseBeforePaint) { + this.needsEraseBeforePaint = false + optimized.unshift(ERASE_THEN_HOME_PATCH) + } else { + optimized.unshift(CURSOR_HOME_PATCH) + } + + optimized.push(this.altScreenParkPatch) + } + + // Native cursor positioning: park the terminal cursor at the declared + // position so IME preedit text renders inline and screen readers / + // magnifiers can follow the input. nodeCache holds the absolute screen + // rect populated by renderNodeToOutput this frame (including scrollTop + // translation) — if the declared node didn't render (stale declaration + // after remount, or scrolled out of view), it won't be in the cache + // and no move is emitted. + const decl = this.cursorDeclaration + const rect = decl !== null ? nodeCache.get(decl.node) : undefined + + const target = + decl !== null && rect !== undefined + ? { + x: rect.x + decl.relativeX, + y: rect.y + decl.relativeY + } + : null + + const parked = this.displayCursor + + // Preserve the empty-diff zero-write fast path: skip all cursor writes + // when nothing rendered AND the park target is unchanged. + const targetMoved = target !== null && (parked === null || parked.x !== target.x || parked.y !== target.y) + + if (hasDiff || targetMoved || (target === null && parked !== null)) { + // Main-screen preamble: log-update's relative moves assume the + // physical cursor is at prevFrame.cursor. If last frame parked it + // elsewhere, move back before the diff runs. Alt-screen's CSI H + // already resets to (0,0) so no preamble needed. + if (parked !== null && !this.altScreenActive && hasDiff) { + const pdx = prevFrame.cursor.x - parked.x + const pdy = prevFrame.cursor.y - parked.y + + if (pdx !== 0 || pdy !== 0) { + optimized.unshift({ + type: 'stdout', + content: cursorMove(pdx, pdy) + }) + } + } + + if (target !== null) { + if (this.altScreenActive) { + // Absolute CUP (1-indexed); next frame's CSI H resets regardless. + // Emitted after altScreenParkPatch so the declared position wins. + const row = Math.min(Math.max(target.y + 1, 1), terminalRows) + const col = Math.min(Math.max(target.x + 1, 1), terminalWidth) + optimized.push({ + type: 'stdout', + content: cursorPosition(row, col) + }) + } else { + // After the diff (or preamble), cursor is at frame.cursor. If no + // diff AND previously parked, it's still at the old park position + // (log-update wrote nothing). Otherwise it's at frame.cursor. + const from = + !hasDiff && parked !== null + ? parked + : { + x: frame.cursor.x, + y: frame.cursor.y + } + + const dx = target.x - from.x + const dy = target.y - from.y + + if (dx !== 0 || dy !== 0) { + optimized.push({ + type: 'stdout', + content: cursorMove(dx, dy) + }) + } + } + + this.displayCursor = target + } else { + // Declaration cleared (input blur, unmount). Restore physical cursor + // to frame.cursor before forgetting the park position — otherwise + // displayCursor=null lies about where the cursor is, and the NEXT + // frame's preamble (or log-update's relative moves) computes from a + // wrong spot. The preamble above handles hasDiff; this handles + // !hasDiff (e.g. accessibility mode where blur doesn't change + // renderedValue since invert is identity). + if (parked !== null && !this.altScreenActive && !hasDiff) { + const rdx = frame.cursor.x - parked.x + const rdy = frame.cursor.y - parked.y + + if (rdx !== 0 || rdy !== 0) { + optimized.push({ + type: 'stdout', + content: cursorMove(rdx, rdy) + }) + } + } + + this.displayCursor = null + } + } + + const tWrite = performance.now() + writeDiffToTerminal(this.terminal, optimized, this.altScreenActive && !SYNC_OUTPUT_SUPPORTED) + const writeMs = performance.now() - tWrite + + // Update blit safety for the NEXT frame. The frame just rendered + // becomes frontFrame (= next frame's prevScreen). If we applied the + // selection overlay, that buffer has inverted cells. selActive/hlActive + // are only ever true in alt-screen; in main-screen this is false→false. + this.prevFrameContaminated = selActive || hlActive || !!frame.absoluteOverlayMoved + + // Plain setTimeout (not scheduleRender) — lodash throttle's leading + // edge would fire inside this trailing invocation and double-render. + // Scroll drain only; absolute-overlay movement rides prevFrameContaminated + // into the next natural render. Routing it here made caret re-layout a + // 250fps self-oscillator that locked the event loop after resize. + if (frame.scrollDrainPending) { + this.drainTimer = setTimeout(() => this.onRender(), FRAME_INTERVAL_MS >> 2) + } + + const yogaMs = getLastYogaMs() + const commitMs = getLastCommitMs() + const yc = this.lastYogaCounters + // Reset so drain-only frames (no React commit) don't repeat stale values. + resetProfileCounters() + this.lastYogaCounters = { + ms: 0, + visited: 0, + measured: 0, + cacheHits: 0, + live: 0 + } + this.options.onFrame?.({ + durationMs: performance.now() - renderStart, + phases: { + renderer: rendererMs, + diff: diffMs, + optimize: optimizeMs, + write: writeMs, + patches: diff.length, + yoga: yogaMs, + commit: commitMs, + yogaVisited: yc.visited, + yogaMeasured: yc.measured, + yogaCacheHits: yc.cacheHits, + yogaLive: yc.live + }, + flickers + }) + + this.isRendering = false + + if (this.immediateRerenderRequested) { + this.immediateRerenderRequested = false + queueMicrotask(() => this.onRender()) + } + } + pause(): void { + // Flush pending React updates and render before pausing. + reconciler.flushSyncFromReconciler() + this.onRender() + this.isPaused = true + } + resume(): void { + this.isPaused = false + this.onRender() + } + + /** + * Reset frame buffers so the next render writes the full screen from scratch. + * Call this before resume() when the terminal content has been corrupted by + * an external process (e.g. tmux, shell, full-screen TUI). + */ + repaint(): void { + this.frontFrame = emptyFrame( + this.frontFrame.viewport.height, + this.frontFrame.viewport.width, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.backFrame = emptyFrame( + this.backFrame.viewport.height, + this.backFrame.viewport.width, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.log.reset() + // Physical cursor position is unknown after external terminal corruption. + // Clear displayCursor so the cursor preamble doesn't emit a stale + // relative move from where we last parked it. + this.displayCursor = null + } + + /** + * Clear the physical terminal and force a full redraw. + * + * The traditional readline ctrl+l — clears the visible screen and + * redraws the current content. Also the recovery path when the terminal + * was cleared externally (macOS Cmd+K) and Ink's diff engine thinks + * unchanged cells don't need repainting. Scrollback is preserved. + */ + forceRedraw(): void { + if (!this.options.stdout.isTTY || this.isUnmounted || this.isPaused) { + return + } + + this.options.stdout.write(ERASE_SCREEN + CURSOR_HOME) + + if (this.altScreenActive) { + this.resetFramesForAltScreen() + } else { + this.repaint() + // repaint() resets frontFrame to 0×0. Without this flag the next + // frame's blit optimization copies from that empty screen and the + // diff sees no content. onRender resets the flag at frame end. + this.prevFrameContaminated = true + } + + this.onRender() + } + + /** + * Mark the previous frame as untrustworthy for blit, forcing the next + * render to do a full-damage diff instead of the per-node fast path. + * + * Lighter than forceRedraw() — no screen clear, no extra write. Call + * from a useLayoutEffect cleanup when unmounting a tall overlay: the + * blit fast path can copy stale cells from the overlay frame into rows + * the shrunken layout no longer reaches, leaving a ghost title/divider. + * onRender resets the flag at frame end so it's one-shot. + */ + invalidatePrevFrame(): void { + this.prevFrameContaminated = true + } + + /** + * Called by the component on mount/unmount. + * Controls cursor.y clamping in the renderer and gates alt-screen-aware + * behavior in SIGCONT/resize/unmount handlers. Repaints on change so + * the first alt-screen frame (and first main-screen frame on exit) is + * a full redraw with no stale diff state. + */ + setAltScreenActive(active: boolean, mouseTracking = false): void { + if (this.altScreenActive === active) { + return + } + + this.altScreenActive = active + this.altScreenMouseTracking = active && mouseTracking + + if (active) { + this.resetFramesForAltScreen() + } else { + this.repaint() + } + } + get isAltScreenActive(): boolean { + return this.altScreenActive + } + + /** + * Re-assert terminal modes after a gap (>5s stdin silence or event-loop + * stall). Catches tmux detach→attach, ssh reconnect, and laptop + * sleep/wake — none of which send SIGCONT. The terminal may reset DEC + * private modes on reconnect; this method restores them. + * + * Always re-asserts extended key reporting and mouse tracking. Mouse + * tracking is idempotent (DEC private mode set-when-set is a no-op). The + * Kitty keyboard protocol is NOT — CSI >1u is a stack push, so we pop + * first to keep depth balanced (pop on empty stack is a no-op per spec, + * so after a terminal reset this still restores depth 0→1). Without the + * pop, each >5s idle gap adds a stack entry, and the single pop on exit + * or suspend can't drain them — the shell is left in CSI u mode where + * Ctrl+C/Ctrl+D leak as escape sequences. The alt-screen + * re-entry (ERASE_SCREEN + frame reset) is NOT idempotent — it blanks the + * screen — so it's opt-in via includeAltScreen. The stdin-gap caller fires + * on ordinary >5s idle + keypress and must not erase; the event-loop stall + * detector fires on genuine sleep/wake and opts in. tmux attach / ssh + * reconnect typically send a resize, which already covers alt-screen via + * handleResize. + */ + reassertTerminalModes = (includeAltScreen = false): void => { + if (!this.options.stdout.isTTY) { + return + } + + // Don't touch the terminal during an editor handoff — re-enabling kitty + // keyboard here would undo enterAlternateScreen's disable and nano would + // start seeing CSI-u sequences again. + if (this.isPaused) { + return + } + + // Extended keys — re-assert if enabled (App.tsx enables these on + // allowlisted terminals at raw-mode entry; a terminal reset clears them). + // Pop-before-push keeps Kitty stack depth at 1 instead of accumulating + // on each call. + if (supportsExtendedKeys()) { + this.options.stdout.write(DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS) + } + + if (!this.altScreenActive) { + return + } + + // Mouse tracking — idempotent, safe to re-assert on every stdin gap. + if (this.altScreenMouseTracking) { + this.options.stdout.write(ENABLE_MOUSE_TRACKING) + } + + // Alt-screen re-entry — destructive (ERASE_SCREEN). Only for callers that + // have a strong signal the terminal actually dropped mode 1049. + if (includeAltScreen) { + this.reenterAltScreen() + } + } + + /** + * Mark this instance as unmounted so future unmount() calls early-return. + * Called by gracefulShutdown's cleanupTerminalModes() after it has sent + * EXIT_ALT_SCREEN but before the remaining terminal-reset sequences. + * Without this, signal-exit's deferred ink.unmount() (triggered by + * process.exit()) runs the full unmount path: onRender() + writeSync + * cleanup block + updateContainerSync → AlternateScreen unmount cleanup. + * The result is 2-3 redundant EXIT_ALT_SCREEN sequences landing on the + * main screen AFTER printResumeHint(), which tmux (at least) interprets + * as restoring the saved cursor position — clobbering the resume hint. + */ + detachForShutdown(): void { + this.isUnmounted = true + // Cancel any pending throttled render so it doesn't fire between + // cleanupTerminalModes() and process.exit() and write to main screen. + this.scheduleRender.cancel?.() + + // Restore stdin from raw mode. unmount() used to do this via React + // unmount (App.componentWillUnmount → handleSetRawMode(false)) but we're + // short-circuiting that path. Must use this.options.stdin — NOT + // process.stdin — because getStdinOverride() may have opened /dev/tty + // when stdin is piped. + const stdin = this.options.stdin as NodeJS.ReadStream & { + isRaw?: boolean + setRawMode?: (m: boolean) => void + } + + this.drainStdin() + + if (stdin.isTTY && stdin.isRaw && stdin.setRawMode) { + stdin.setRawMode(false) + } + } + + /** @see drainStdin */ + drainStdin(): void { + drainStdin(this.options.stdin) + } + + /** + * Re-enter alt-screen, clear, home, re-enable mouse tracking, and reset + * frame buffers so the next render repaints from scratch. Self-heal for + * SIGCONT, resize, and stdin-gap/event-loop-stall (sleep/wake) — any of + * which can leave the terminal in main-screen mode while altScreenActive + * stays true. ENTER_ALT_SCREEN is a terminal-side no-op if already in alt. + */ + private reenterAltScreen(): void { + this.options.stdout.write( + ENTER_ALT_SCREEN + ERASE_SCREEN + CURSOR_HOME + (this.altScreenMouseTracking ? ENABLE_MOUSE_TRACKING : '') + ) + this.resetFramesForAltScreen() + } + + /** + * Seed prev/back frames with full-size BLANK screens (rows×cols of empty + * cells, not 0×0). In alt-screen mode, next.screen.height is always + * terminalRows; if prev.screen.height is 0 (emptyFrame's default), + * log-update sees heightDelta > 0 ('growing') and calls renderFrameSlice, + * whose trailing per-row CR+LF at the last row scrolls the alt screen, + * permanently desyncing the virtual and physical cursors by 1 row. + * + * With a rows×cols blank prev, heightDelta === 0 → standard diffEach + * → moveCursorTo (CSI cursorMove, no LF, no scroll). + * + * viewport.height = rows + 1 matches the renderer's alt-screen output, + * preventing a spurious resize trigger on the first frame. cursor.y = 0 + * matches the physical cursor after ENTER_ALT_SCREEN + CSI H (home). + */ + private resetFramesForAltScreen(): void { + const rows = this.terminalRows + const cols = this.terminalColumns + + const blank = (): Frame => ({ + screen: createScreen(cols, rows, this.stylePool, this.charPool, this.hyperlinkPool), + viewport: { + width: cols, + height: rows + 1 + }, + cursor: { + x: 0, + y: 0, + visible: true + } + }) + + this.frontFrame = blank() + this.backFrame = blank() + this.log.reset() + // Defense-in-depth: alt-screen skips the cursor preamble anyway (CSI H + // resets), but a stale displayCursor would be misleading if we later + // exit to main-screen without an intervening render. + this.displayCursor = null + // Fresh frontFrame is blank rows×cols — blitting from it would copy + // blanks over content. Next alt-screen frame must full-render. + this.prevFrameContaminated = true + } + + /** + * Copy the current selection to the clipboard without clearing the + * highlight. Matches iTerm2's copy-on-select behavior where the selected + * region stays visible after the automatic copy. + */ + copySelectionNoClear(): string { + if (!hasSelection(this.selection)) { + return '' + } + + const text = getSelectedText(this.selection, this.frontFrame.screen) + + if (text) { + // Raw OSC 52, or DCS-passthrough-wrapped OSC 52 inside tmux (tmux + // drops it silently unless allow-passthrough is on — no regression). + void setClipboard(text).then(raw => { + if (raw) { + this.options.stdout.write(raw) + } + }) + } + + return text + } + + /** + * Copy the current text selection to the system clipboard via OSC 52 + * and clear the selection. Returns the copied text (empty if no selection). + */ + copySelection(): string { + if (!hasSelection(this.selection)) { + return '' + } + + const text = this.copySelectionNoClear() + clearSelection(this.selection) + this.notifySelectionChange() + + return text + } + + /** Clear the current text selection without copying. */ + clearTextSelection(): void { + if (!hasSelection(this.selection)) { + return + } + + clearSelection(this.selection) + this.notifySelectionChange() + } + + /** + * Set the search highlight query. Non-empty → all visible occurrences + * are inverted (SGR 7) on the next frame; first one also underlined. + * Empty → clears (prevFrameContaminated handles the frame after). Same + * damage-tracking machinery as selection — setCellStyleId doesn't track + * damage, so the overlay forces full-frame damage while active. + */ + setSearchHighlight(query: string): void { + if (this.searchHighlightQuery === query) { + return + } + + this.searchHighlightQuery = query + this.scheduleRender() + } + + /** Paint an EXISTING DOM subtree to a fresh Screen at its natural + * height, scan for query. Returns positions relative to the element's + * bounding box (row 0 = element top). + * + * The element comes from the MAIN tree — built with all real + * providers, yoga already computed. We paint it to a fresh buffer + * with offsets so it lands at (0,0). Same paint path as the main + * render. Zero drift. No second React root, no context bridge. + * + * ~1-2ms (paint only, no reconcile — the DOM is already built). */ + scanElementSubtree(el: dom.DOMElement): MatchPosition[] { + if (!this.searchHighlightQuery || !el.yogaNode) { + return [] + } + + const width = Math.ceil(el.yogaNode.getComputedWidth()) + const height = Math.ceil(el.yogaNode.getComputedHeight()) + + if (width <= 0 || height <= 0) { + return [] + } + + // renderNodeToOutput adds el's OWN computedLeft/Top to offsetX/Y. + // Passing -elLeft/-elTop nets to 0 → paints at (0,0) in our buffer. + const elLeft = el.yogaNode.getComputedLeft() + const elTop = el.yogaNode.getComputedTop() + const screen = createScreen(width, height, this.stylePool, this.charPool, this.hyperlinkPool) + + const output = new Output({ + width, + height, + stylePool: this.stylePool, + screen + }) + + renderNodeToOutput(el, output, { + offsetX: -elLeft, + offsetY: -elTop, + prevScreen: undefined + }) + const rendered = output.get() + // renderNodeToOutput wrote our offset positions to nodeCache — + // corrupts the main render (it'd blit from wrong coords). Mark the + // subtree dirty so the next main render repaints + re-caches + // correctly. One extra paint of this message, but correct > fast. + dom.markDirty(el) + const positions = scanPositions(rendered, this.searchHighlightQuery) + logForDebugging( + `scanElementSubtree: q='${this.searchHighlightQuery}' ` + + `el=${width}x${height}@(${elLeft},${elTop}) n=${positions.length} ` + + `[${positions + .slice(0, 10) + .map(p => `${p.row}:${p.col}`) + .join(',')}` + + `${positions.length > 10 ? ',…' : ''}]` + ) + + return positions + } + + /** Set the position-based highlight state. Every frame, writes CURRENT + * style at positions[currentIdx] + rowOffset. null clears. The scan- + * highlight (inverse on all matches) still runs — this overlays yellow + * on top. rowOffset changes as the user scrolls (= message's current + * screen-top); positions stay stable (message-relative). */ + setSearchPositions( + state: { + positions: MatchPosition[] + rowOffset: number + currentIdx: number + } | null + ): void { + this.searchPositions = state + this.scheduleRender() + } + + /** + * Set the selection highlight background color. Replaces the per-cell + * SGR-7 inverse with a solid theme-aware bg (matches native terminal + * selection). Accepts the same color formats as Text backgroundColor + * (rgb(), ansi:name, #hex, ansi256()) — colorize() routes through + * chalk so the tmux/xterm.js level clamps in colorize.ts apply and + * the emitted SGR is correct for the current terminal. + * + * Called by React-land once theme is known (ScrollKeybindingHandler's + * useEffect watching useTheme). Before that call, withSelectionBg + * falls back to withInverse so selection still renders on the first + * frame; the effect fires before any mouse input so the fallback is + * unobservable in practice. + */ + setSelectionBgColor(color: string): void { + // Wrap a NUL marker, then split on it to extract the open/close SGR. + // colorize returns the input unchanged if the color string is bad — + // no NUL-split then, so fall through to null (inverse fallback). + const wrapped = colorize('\0', color, 'background') + const nul = wrapped.indexOf('\0') + + if (nul <= 0 || nul === wrapped.length - 1) { + this.stylePool.setSelectionBg(null) + + return + } + + this.stylePool.setSelectionBg({ + type: 'ansi', + code: wrapped.slice(0, nul), + endCode: wrapped.slice(nul + 1) // always \x1b[49m for bg + }) + // No scheduleRender: this is called from a React effect that already + // runs inside the render cycle, and the bg only matters once a + // selection exists (which itself triggers a full-damage frame). + } + + /** + * Capture text from rows about to scroll out of the viewport during + * drag-to-scroll. Must be called BEFORE the ScrollBox scrolls so the + * screen buffer still holds the outgoing content. Accumulated into + * the selection state and joined back in by getSelectedText. + */ + captureScrolledRows(firstRow: number, lastRow: number, side: 'above' | 'below'): void { + captureScrolledRows(this.selection, this.frontFrame.screen, firstRow, lastRow, side) + } + + /** + * Shift anchor AND focus by dRow, clamped to [minRow, maxRow]. Used by + * keyboard scroll handlers (PgUp/PgDn etc.) so the highlight tracks the + * content instead of disappearing. Unlike shiftAnchor (drag-to-scroll), + * this moves BOTH endpoints — the user isn't holding the mouse at one + * edge. Supplies screen.width for the col-reset-on-clamp boundary. + */ + shiftSelectionForScroll(dRow: number, minRow: number, maxRow: number): void { + const hadSel = hasSelection(this.selection) + shiftSelection(this.selection, dRow, minRow, maxRow, this.frontFrame.screen.width) + + // shiftSelection clears when both endpoints overshoot the same edge + // (Home/g/End/G page-jump past the selection). Notify subscribers so + // useHasSelection updates. Safe to call notifySelectionChange here — + // this runs from keyboard handlers, not inside onRender(). + if (hadSel && !hasSelection(this.selection)) { + this.notifySelectionChange() + } + } + + /** + * Keyboard selection extension (shift+arrow/home/end). Moves focus; + * anchor stays fixed so the highlight grows or shrinks relative to it. + * Left/right wrap across row boundaries — native macOS text-edit + * behavior: shift+left at col 0 wraps to end of the previous row. + * Up/down clamp at viewport edges (no scroll-to-extend yet). Drops to + * char mode. No-op outside alt-screen or without an active selection. + */ + moveSelectionFocus(move: FocusMove): void { + if (!this.altScreenActive) { + return + } + + const { focus } = this.selection + + if (!focus) { + return + } + + const { width, height } = this.frontFrame.screen + + const maxCol = width - 1 + const maxRow = height - 1 + + let { col, row } = focus + + switch (move) { + case 'left': + if (col > 0) { + col-- + } else if (row > 0) { + col = maxCol + row-- + } + + break + + case 'right': + if (col < maxCol) { + col++ + } else if (row < maxRow) { + col = 0 + row++ + } + + break + + case 'up': + if (row > 0) { + row-- + } + + break + + case 'down': + if (row < maxRow) { + row++ + } + + break + + case 'lineStart': + col = 0 + + break + + case 'lineEnd': + col = maxCol + + break + } + + if (col === focus.col && row === focus.row) { + return + } + + moveFocus(this.selection, col, row) + this.notifySelectionChange() + } + + /** Whether there is an active text selection. */ + hasTextSelection(): boolean { + return hasSelection(this.selection) + } + + /** + * Subscribe to selection state changes. Fires whenever the selection + * is started, updated, cleared, or copied. Returns an unsubscribe fn. + */ + subscribeToSelectionChange(cb: () => void): () => void { + this.selectionListeners.add(cb) + + return () => this.selectionListeners.delete(cb) + } + private notifySelectionChange(): void { + this.scheduleRender() + + const active = hasSelection(this.selection) + + if (active !== this.selectionWasActive) { + this.selectionWasActive = active + + for (const cb of this.selectionListeners) { + cb() + } + } + } + + /** + * Hit-test the rendered DOM tree at (col, row) and bubble a ClickEvent + * from the deepest hit node up through ancestors with onClick handlers. + * Returns true if a DOM handler consumed the click. Gated on + * altScreenActive — clicks only make sense with a fixed viewport where + * nodeCache rects map 1:1 to terminal cells (no scrollback offset). + */ + dispatchClick(col: number, row: number): boolean { + if (!this.altScreenActive) { + return false + } + + const blank = isEmptyCellAt(this.frontFrame.screen, col, row) + + return dispatchClick(this.rootNode, col, row, blank) + } + dispatchMouseDown(col: number, row: number, button: number): dom.DOMElement | undefined { + if (!this.altScreenActive) { + return undefined + } + + return dispatchMouse( + this.rootNode, + col, + row, + 'onMouseDown', + button, + isEmptyCellAt(this.frontFrame.screen, col, row) + ) + } + dispatchMouseUp(target: dom.DOMElement, col: number, row: number, button: number): void { + if (!this.altScreenActive) { + return + } + + dispatchMouse(this.rootNode, col, row, 'onMouseUp', button, isEmptyCellAt(this.frontFrame.screen, col, row), target) + } + dispatchMouseDrag(target: dom.DOMElement, col: number, row: number, button: number): void { + if (!this.altScreenActive) { + return + } + + dispatchMouse( + this.rootNode, + col, + row, + 'onMouseDrag', + button, + isEmptyCellAt(this.frontFrame.screen, col, row), + target + ) + } + dispatchHover(col: number, row: number): void { + if (!this.altScreenActive) { + return + } + + dispatchHover(this.rootNode, col, row, this.hoveredNodes) + } + dispatchKeyboardEvent(parsedKey: ParsedKey): void { + const target = this.focusManager.activeElement ?? this.rootNode + const event = new KeyboardEvent(parsedKey) + dispatcher.dispatchDiscrete(target, event) + + // Tab cycling is the default action — only fires if no handler + // called preventDefault(). Mirrors browser behavior. + if (!event.defaultPrevented && parsedKey.name === 'tab' && !parsedKey.ctrl && !parsedKey.meta) { + if (parsedKey.shift) { + this.focusManager.focusPrevious(this.rootNode) + } else { + this.focusManager.focusNext(this.rootNode) + } + } + } + /** + * Look up the URL at (col, row) in the current front frame. Checks for + * an OSC 8 hyperlink first, then falls back to scanning the row for a + * plain-text URL (mouse tracking intercepts the terminal's native + * Cmd+Click URL detection, so we replicate it). This is a pure lookup + * with no side effects — call it synchronously at click time so the + * result reflects the screen the user actually clicked on, then defer + * the browser-open action via a timer. + */ + getHyperlinkAt(col: number, row: number): string | undefined { + if (!this.altScreenActive) { + return undefined + } + + const screen = this.frontFrame.screen + const cell = cellAt(screen, col, row) + let url = cell?.hyperlink + + // SpacerTail cells (right half of wide/CJK/emoji chars) store the + // hyperlink on the head cell at col-1. + if (!url && cell?.width === CellWidth.SpacerTail && col > 0) { + url = cellAt(screen, col - 1, row)?.hyperlink + } + + return url ?? findPlainTextUrlAt(screen, col, row) + } + + /** + * Optional callback fired when clicking an OSC 8 hyperlink in fullscreen + * mode. Set by FullscreenLayout via useLayoutEffect. + */ + onHyperlinkClick: ((url: string) => void) | undefined + + /** + * Stable prototype wrapper for onHyperlinkClick. Passed to as + * onOpenHyperlink so the prop is a bound method (autoBind'd) that reads + * the mutable field at call time — not the undefined-at-render value. + */ + openHyperlink(url: string): void { + this.onHyperlinkClick?.(url) + } + + /** + * Handle a double- or triple-click at (col, row): select the word or + * line under the cursor by reading the current screen buffer. Called on + * PRESS (not release) so the highlight appears immediately and drag can + * extend the selection word-by-word / line-by-line. Falls back to + * char-mode startSelection if the click lands on a noSelect cell. + */ + handleMultiClick(col: number, row: number, count: 2 | 3): void { + if (!this.altScreenActive) { + return + } + + const screen = this.frontFrame.screen + // selectWordAt/selectLineAt no-op on noSelect/out-of-bounds. Seed with + // a char-mode selection so the press still starts a drag even if the + // word/line scan finds nothing selectable. + startSelection(this.selection, col, row) + + if (count === 2) { + selectWordAt(this.selection, screen, col, row) + } else { + selectLineAt(this.selection, screen, row) + } + + // Ensure hasSelection is true so release doesn't re-dispatch onClickAt. + // selectWordAt no-ops on noSelect; selectLineAt no-ops out-of-bounds. + if (!this.selection.focus) { + this.selection.focus = this.selection.anchor + } + + this.notifySelectionChange() + } + + /** + * Handle a drag-motion at (col, row). In char mode updates focus to the + * exact cell. In word/line mode snaps to word/line boundaries so the + * selection extends by word/line like native macOS. Gated on + * altScreenActive for the same reason as dispatchClick. + */ + handleSelectionDrag(col: number, row: number): void { + if (!this.altScreenActive) { + return + } + + const sel = this.selection + + if (sel.anchorSpan) { + extendSelection(sel, this.frontFrame.screen, col, row) + } else { + updateSelection(sel, col, row) + } + + this.notifySelectionChange() + } + + // Methods to properly suspend stdin for external editor usage + // This is needed to prevent Ink from swallowing keystrokes when an external editor is active + private stdinListeners: Array<{ + event: string + listener: (...args: unknown[]) => void + }> = [] + private wasRawMode = false + suspendStdin(): void { + const stdin = this.options.stdin + + if (!stdin.isTTY) { + return + } + + // Store and remove all 'readable' event listeners temporarily + // This prevents Ink from consuming stdin while the editor is active + const readableListeners = stdin.listeners('readable') + logForDebugging( + `[stdin] suspendStdin: removing ${readableListeners.length} readable listener(s), wasRawMode=${ + ( + stdin as NodeJS.ReadStream & { + isRaw?: boolean + } + ).isRaw ?? false + }` + ) + readableListeners.forEach(listener => { + this.stdinListeners.push({ + event: 'readable', + listener: listener as (...args: unknown[]) => void + }) + stdin.removeListener('readable', listener as (...args: unknown[]) => void) + }) + + // If raw mode is enabled, disable it temporarily + const stdinWithRaw = stdin as NodeJS.ReadStream & { + isRaw?: boolean + setRawMode?: (mode: boolean) => void + } + + if (stdinWithRaw.isRaw && stdinWithRaw.setRawMode) { + stdinWithRaw.setRawMode(false) + this.wasRawMode = true + } + } + resumeStdin(): void { + const stdin = this.options.stdin + + if (!stdin.isTTY) { + return + } + + // Re-attach all the stored listeners + if (this.stdinListeners.length === 0 && !this.wasRawMode) { + logForDebugging('[stdin] resumeStdin: called with no stored listeners and wasRawMode=false (possible desync)', { + level: 'warn' + }) + } + + logForDebugging( + `[stdin] resumeStdin: re-attaching ${this.stdinListeners.length} listener(s), wasRawMode=${this.wasRawMode}` + ) + this.stdinListeners.forEach(({ event, listener }) => { + stdin.addListener(event, listener) + }) + this.stdinListeners = [] + + // Re-enable raw mode if it was enabled before + if (this.wasRawMode) { + const stdinWithRaw = stdin as NodeJS.ReadStream & { + setRawMode?: (mode: boolean) => void + } + + if (stdinWithRaw.setRawMode) { + stdinWithRaw.setRawMode(true) + } + + this.wasRawMode = false + } + } + + // Stable identity for TerminalWriteContext. An inline arrow here would + // change on every render() call (initial mount + each resize), which + // cascades through useContext → 's useLayoutEffect dep + // array → spurious exit+re-enter of the alt screen on every SIGWINCH. + private writeRaw(data: string): void { + this.options.stdout.write(data) + } + private setCursorDeclaration: CursorDeclarationSetter = (decl, clearIfNode) => { + if (decl === null && clearIfNode !== undefined && this.cursorDeclaration?.node !== clearIfNode) { + return + } + + this.cursorDeclaration = decl + } + render(node: ReactNode): void { + this.currentNode = node + + const tree = ( + + {node} + + ) + + reconciler.updateContainerSync(tree, this.container, null, noop) + reconciler.flushSyncWork() + } + unmount(error?: Error | number | null): void { + if (this.isUnmounted) { + return + } + + this.onRender() + this.unsubscribeExit() + + if (typeof this.restoreConsole === 'function') { + this.restoreConsole() + } + + this.restoreStderr?.() + this.unsubscribeTTYHandlers?.() + + // Non-TTY environments don't handle erasing ansi escapes well, so it's better to + // only render last frame of non-static output + const diff = this.log.renderPreviousOutput_DEPRECATED(this.frontFrame) + writeDiffToTerminal(this.terminal, optimize(diff)) + + // Clean up terminal modes synchronously before process exit. + // React's componentWillUnmount won't run in time when process.exit() is called, + // so we must reset terminal modes here to prevent escape sequence leakage. + // Use writeSync to stdout (fd 1) to ensure writes complete before exit. + // We unconditionally send all disable sequences because terminal detection + // may not work correctly (e.g., in tmux, screen) and these are no-ops on + // terminals that don't support them. + + if (this.options.stdout.isTTY) { + if (this.altScreenActive) { + // 's unmount effect won't run during signal-exit. + // Exit alt screen FIRST so other cleanup sequences go to the main screen. + writeSync(1, EXIT_ALT_SCREEN) + } + + // Disable mouse tracking — unconditional because altScreenActive can be + // stale if AlternateScreen's unmount (which flips the flag) raced a + // blocked event loop + SIGINT. No-op if tracking was never enabled. + writeSync(1, DISABLE_MOUSE_TRACKING) + // Drain stdin so in-flight mouse events don't leak to the shell + this.drainStdin() + // Disable extended key reporting (both kitty and modifyOtherKeys) + writeSync(1, DISABLE_MODIFY_OTHER_KEYS) + writeSync(1, DISABLE_KITTY_KEYBOARD) + // Disable focus events (DECSET 1004) + writeSync(1, DFE) + // Disable bracketed paste mode + writeSync(1, DBP) + // Show cursor + writeSync(1, SHOW_CURSOR) + // Clear iTerm2 progress bar + writeSync(1, CLEAR_ITERM2_PROGRESS) + + // Clear tab status (OSC 21337) so a stale dot doesn't linger + if (supportsTabStatus()) { + writeSync(1, wrapForMultiplexer(CLEAR_TAB_STATUS)) + } + } + + this.isUnmounted = true + + // Cancel any pending throttled renders to prevent accessing freed Yoga nodes + this.scheduleRender.cancel?.() + + if (this.drainTimer !== null) { + clearTimeout(this.drainTimer) + this.drainTimer = null + } + + reconciler.updateContainerSync(null, this.container, null, noop) + reconciler.flushSyncWork() + instances.delete(this.options.stdout) + + // Free the root yoga node, then clear its reference. Children are already + // freed by the reconciler's removeChildFromContainer; using .free() (not + // .freeRecursive()) avoids double-freeing them. + this.rootNode.yogaNode?.free() + this.rootNode.yogaNode = undefined + + if (error instanceof Error) { + this.rejectExitPromise(error) + } else { + this.resolveExitPromise() + } + } + async waitUntilExit(): Promise { + this.exitPromise ||= new Promise((resolve, reject) => { + this.resolveExitPromise = resolve + this.rejectExitPromise = reject + }) + + return this.exitPromise + } + resetLineCount(): void { + if (this.options.stdout.isTTY) { + // Swap so old front becomes back (for screen reuse), then reset front + this.backFrame = this.frontFrame + this.frontFrame = emptyFrame( + this.frontFrame.viewport.height, + this.frontFrame.viewport.width, + this.stylePool, + this.charPool, + this.hyperlinkPool + ) + this.log.reset() + // frontFrame is reset, so frame.cursor on the next render is (0,0). + // Clear displayCursor so the preamble doesn't compute a stale delta. + this.displayCursor = null + } + } + + /** + * Replace char/hyperlink pools with fresh instances to prevent unbounded + * growth during long sessions. Migrates the front frame's screen IDs into + * the new pools so diffing remains correct. The back frame doesn't need + * migration — resetScreen zeros it before any reads. + * + * Call between conversation turns or periodically. + */ + resetPools(): void { + this.charPool = new CharPool() + this.hyperlinkPool = new HyperlinkPool() + migrateScreenPools(this.frontFrame.screen, this.charPool, this.hyperlinkPool) + // Back frame's data is zeroed by resetScreen before reads, but its pool + // references are used by the renderer to intern new characters. Point + // them at the new pools so the next frame's IDs are comparable. + this.backFrame.screen.charPool = this.charPool + this.backFrame.screen.hyperlinkPool = this.hyperlinkPool + } + patchConsole(): () => void { + // biome-ignore lint/suspicious/noConsole: intentionally patching global console + const con = console + const originals: Partial> = {} + const toDebug = (...args: unknown[]) => logForDebugging(`console.log: ${format(...args)}`) + const toError = (...args: unknown[]) => logError(new Error(`console.error: ${format(...args)}`)) + + for (const m of CONSOLE_STDOUT_METHODS) { + originals[m] = con[m] + con[m] = toDebug + } + + for (const m of CONSOLE_STDERR_METHODS) { + originals[m] = con[m] + con[m] = toError + } + + originals.assert = con.assert + + con.assert = (condition: unknown, ...args: unknown[]) => { + if (!condition) { + toError(...args) + } + } + + return () => Object.assign(con, originals) + } + + /** + * Intercept process.stderr.write so stray writes (config.ts, hooks.ts, + * third-party deps) don't corrupt the alt-screen buffer. patchConsole only + * hooks console.* methods — direct stderr writes bypass it, land at the + * parked cursor, scroll the alt-screen, and desync frontFrame from the + * physical terminal. Next diff writes only changed-in-React cells at + * absolute coords → interleaved garbage. + * + * Swallows the write (routes text to the debug log) and, in alt-screen, + * forces a full-damage repaint as a defensive recovery. Not patching + * process.stdout — Ink itself writes there. + */ + private patchStderr(): () => void { + const stderr = process.stderr + const originalWrite = stderr.write + let reentered = false + + const intercept = ( + chunk: Uint8Array | string, + encodingOrCb?: BufferEncoding | ((err?: Error | null) => void), + cb?: (err?: Error | null) => void + ): boolean => { + const callback = typeof encodingOrCb === 'function' ? encodingOrCb : cb + + // Reentrancy guard: logForDebugging → writeToStderr → here. Pass + // through to the original so --debug-to-stderr still works and we + // don't stack-overflow. + if (reentered) { + const encoding = typeof encodingOrCb === 'string' ? encodingOrCb : undefined + + return originalWrite.call(stderr, chunk, encoding, callback) + } + + reentered = true + + try { + const text = typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8') + logForDebugging(`[stderr] ${text}`, { + level: 'warn' + }) + + if (this.altScreenActive && !this.isUnmounted && !this.isPaused) { + this.prevFrameContaminated = true + this.scheduleRender() + } + } finally { + reentered = false + callback?.() + } + + return true + } + + stderr.write = intercept + + return () => { + if (stderr.write === intercept) { + stderr.write = originalWrite + } + } + } +} + +/** + * Discard pending stdin bytes so in-flight escape sequences (mouse tracking + * reports, bracketed-paste markers) don't leak to the shell after exit. + * + * Two layers of trickiness: + * + * 1. setRawMode is termios, not fcntl — the stdin fd stays blocking, so + * readSync on it would hang forever. Node doesn't expose fcntl, so we + * open /dev/tty fresh with O_NONBLOCK (all fds to the controlling + * terminal share one line-discipline input queue). + * + * 2. By the time forceExit calls this, detachForShutdown has already put + * the TTY back in cooked (canonical) mode. Canonical mode line-buffers + * input until newline, so O_NONBLOCK reads return EAGAIN even when + * mouse bytes are sitting in the buffer. We briefly re-enter raw mode + * so reads return any available bytes, then restore cooked mode. + * + * Safe to call multiple times. Call as LATE as possible in the exit path: + * DISABLE_MOUSE_TRACKING has terminal round-trip latency, so events can + * arrive for a few ms after it's written. + */ + +export function drainStdin(stdin: NodeJS.ReadStream = process.stdin): void { + if (!stdin.isTTY) { + return + } + + // Drain Node's stream buffer (bytes libuv already pulled in). read() + // returns null when empty — never blocks. + try { + while (stdin.read() !== null) { + /* discard */ + } + } catch { + /* stream may be destroyed */ + } + + // No /dev/tty on Windows; CONIN$ doesn't support O_NONBLOCK semantics. + // Windows Terminal also doesn't buffer mouse reports the same way. + if (process.platform === 'win32') { + return + } + + // termios is per-device: flip stdin to raw so canonical-mode line + // buffering doesn't hide partial input from the non-blocking read. + // Restored in the finally block. + const tty = stdin as NodeJS.ReadStream & { + isRaw?: boolean + setRawMode?: (raw: boolean) => void + } + + const wasRaw = tty.isRaw === true + // Drain the kernel TTY buffer via a fresh O_NONBLOCK fd. Bounded at 64 + // reads (64KB) — a real mouse burst is a few hundred bytes; the cap + // guards against a terminal that ignores O_NONBLOCK. + let fd = -1 + + try { + // setRawMode inside try: on revoked TTY (SIGHUP/SSH disconnect) the + // ioctl throws EBADF — same recovery path as openSync/readSync below. + if (!wasRaw) { + tty.setRawMode?.(true) + } + + fd = openSync('/dev/tty', fsConstants.O_RDONLY | fsConstants.O_NONBLOCK) + const buf = Buffer.alloc(1024) + + for (let i = 0; i < 64; i++) { + if (readSync(fd, buf, 0, buf.length, null) <= 0) { + break + } + } + } catch { + // EAGAIN (buffer empty — expected), ENXIO/ENOENT (no controlling tty), + // EBADF/EIO (TTY revoked — SIGHUP, SSH disconnect) + } finally { + if (fd >= 0) { + try { + closeSync(fd) + } catch { + /* ignore */ + } + } + + if (!wasRaw) { + try { + tty.setRawMode?.(false) + } catch { + /* TTY may be gone */ + } + } + } +} + +const CONSOLE_STDOUT_METHODS = [ + 'log', + 'info', + 'debug', + 'dir', + 'dirxml', + 'count', + 'countReset', + 'group', + 'groupCollapsed', + 'groupEnd', + 'table', + 'time', + 'timeEnd', + 'timeLog' +] as const + +const CONSOLE_STDERR_METHODS = ['warn', 'error', 'trace'] as const +//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJhdXRvQmluZCIsImNsb3NlU3luYyIsImNvbnN0YW50cyIsImZzQ29uc3RhbnRzIiwib3BlblN5bmMiLCJyZWFkU3luYyIsIndyaXRlU3luYyIsIm5vb3AiLCJ0aHJvdHRsZSIsIlJlYWN0IiwiUmVhY3ROb2RlIiwiRmliZXJSb290IiwiQ29uY3VycmVudFJvb3QiLCJvbkV4aXQiLCJmbHVzaEludGVyYWN0aW9uVGltZSIsImdldFlvZ2FDb3VudGVycyIsImxvZ0ZvckRlYnVnZ2luZyIsImxvZ0Vycm9yIiwiZm9ybWF0IiwiY29sb3JpemUiLCJBcHAiLCJDdXJzb3JEZWNsYXJhdGlvbiIsIkN1cnNvckRlY2xhcmF0aW9uU2V0dGVyIiwiRlJBTUVfSU5URVJWQUxfTVMiLCJkb20iLCJLZXlib2FyZEV2ZW50IiwiRm9jdXNNYW5hZ2VyIiwiZW1wdHlGcmFtZSIsIkZyYW1lIiwiRnJhbWVFdmVudCIsImRpc3BhdGNoQ2xpY2siLCJkaXNwYXRjaEhvdmVyIiwiaW5zdGFuY2VzIiwiTG9nVXBkYXRlIiwibm9kZUNhY2hlIiwib3B0aW1pemUiLCJPdXRwdXQiLCJQYXJzZWRLZXkiLCJyZWNvbmNpbGVyIiwiZGlzcGF0Y2hlciIsImdldExhc3RDb21taXRNcyIsImdldExhc3RZb2dhTXMiLCJpc0RlYnVnUmVwYWludHNFbmFibGVkIiwicmVjb3JkWW9nYU1zIiwicmVzZXRQcm9maWxlQ291bnRlcnMiLCJyZW5kZXJOb2RlVG9PdXRwdXQiLCJjb25zdW1lRm9sbG93U2Nyb2xsIiwiZGl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pZiAoIWZvY3VzKSByZXR1cm5cbiAgICBjb25zdCB7IHdpZHRoLCBoZWlnaHQgfSA9IHRoaXMuZnJvbnRGcmFtZS5zY3JlZW5cbiAgICBjb25zdCBtYXhDb2wgPSB3aWR0aCAtIDFcbiAgICBjb25zdCBtYXhSb3cgPSBoZWlnaHQgLSAxXG4gICAgbGV0IHsgY29sLCByb3cgfSA9IGZvY3VzXG4gICAgc3dpdGNoIChtb3ZlKSB7XG4gICAgICBjYXNlICdsZWZ0JzpcbiAgICAgICAgaWYgKGNvbCA+IDApIGNvbC0tXG4gICAgICAgIGVsc2UgaWYgKHJvdyA+IDApIHtcbiAgICAgICAgICBjb2wgPSBtYXhDb2xcbiAgICAgICAgICByb3ctLVxuICAgICAgICB9XG4gICAgICAgIGJyZWFrXG4gICAgICBjYXNlICdyaWdodCc6XG4gICAgICAgIGlmIChjb2wgPCBtYXhDb2wpIGNvbCsrXG4gICAgICAgIGVsc2UgaWYgKHJvdyA8IG1heFJvdykge1xuICAgICAgICAgIGNvbCA9IDBcbiAgICAgICAgICByb3crK1xuICAgICAgICB9XG4gICAgICAgIGJyZWFrXG4gICAgICBjYXNlICd1cCc6XG4gICAgICAgIGlmIChyb3cgPiAwKSByb3ctLVxuICAgICAgICBicmVha1xuICAgICAgY2FzZSAnZG93bic6XG4gICAgICAgIGlmIChyb3cgPCBtYXhSb3cpIHJvdysrXG4gICAgICAgIGJyZWFrXG4gICAgICBjYXNlICdsaW5lU3RhcnQnOlxuICAgICAgICBjb2wgPSAwXG4gICAgICAgIGJyZWFrXG4gICAgICBjYXNlICdsaW5lRW5kJzpcbiAgICAgICAgY29sID0gbWF4Q29sXG4gICAgICAgIGJyZWFrXG4gICAgfVxuICAgIGlmIChjb2wgPT09IGZvY3VzLmNvbCAmJiByb3cgPT09IGZvY3VzLnJvdykgcmV0dXJuXG4gICAgbW92ZUZvY3VzKHRoaXMuc2VsZWN0aW9uLCBjb2wsIHJvdylcbiAgICB0aGlzLm5vdGlmeVNl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QUM5TCxNQUFNLEVBQUUsSUFBSSxDQUFDLElBQUksQ0FBQyxFQUFFO0lBQ25EO0VBQ0YsQ0FBQyxDQUFDLE1BQU07SUFDTjtJQUNBO0VBQUEsQ0FDRCxTQUFTO0lBQ1IsSUFBSTJMLEVBQUUsSUFBSSxDQUFDLEVBQUU7TUFDWCxJQUFJO1FBQ0Y5YyxTQUFTLENBQUM4YyxFQUFFLENBQUM7TUFDZixDQUFDLENBQUMsTUFBTTtRQUNOO01BQUE7SUFFSjtJQUNBLElBQUksQ0FBQ0QsTUFBTSxFQUFFO01BQ1gsSUFBSTtRQUNGRCxHQUFHLENBQUNuSSxVQUFVLEdBQUcsS0FBSyxDQUFDO01BQ3pCLENBQUMsQ0FBQyxNQUFNO1FBQ047TUFBQTtJQUVKO0VBQ0Y7QUFDRjtBQUNBOztBQUVBLE1BQU0rRyxzQkFBc0IsR0FBRyxDQUM3QixLQUFLLEVBQ0wsTUFBTSxFQUNOLE9BQU8sRUFDUCxLQUFLLEVBQ0wsUUFBUSxFQUNSLE9BQU8sRUFDUCxZQUFZLEVBQ1osT0FBTyxFQUNQLGdCQUFnQixFQUNoQixVQUFVLEVBQ1YsT0FBTyxFQUNQLE1BQU0sRUFDTixTQUFTLEVBQ1QsU0FBUyxDQUNWLElBQUl4VSxLQUFLO0FBQ1YsTUFBTXlVLHNCQUFzQixHQUFHLENBQUMsTUFBTSxFQUFFLE9BQU8sRUFBRSxPQUFPLENBQUMsSUFBSXpVLEtBQUsiLCJpZ25vcmVMaXN0IjpbXX0= diff --git a/ui-tui/packages/hermes-ink/src/ink/instances.ts b/ui-tui/packages/hermes-ink/src/ink/instances.ts new file mode 100644 index 0000000000..389384a8d4 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/instances.ts @@ -0,0 +1,10 @@ +// Store all instances of Ink (instance.js) to ensure that consecutive render() calls +// use the same instance of Ink and don't create a new one +// +// This map has to be stored in a separate file, because render.js creates instances, +// but instance.js should delete itself from the map on unmount + +import type Ink from './ink.js' + +const instances = new Map() +export default instances diff --git a/ui-tui/packages/hermes-ink/src/ink/layout/engine.ts b/ui-tui/packages/hermes-ink/src/ink/layout/engine.ts new file mode 100644 index 0000000000..38f6dcb0fb --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/layout/engine.ts @@ -0,0 +1,6 @@ +import type { LayoutNode } from './node.js' +import { createYogaLayoutNode } from './yoga.js' + +export function createLayoutNode(): LayoutNode { + return createYogaLayoutNode() +} diff --git a/ui-tui/packages/hermes-ink/src/ink/layout/geometry.ts b/ui-tui/packages/hermes-ink/src/ink/layout/geometry.ts new file mode 100644 index 0000000000..871db1bc27 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/layout/geometry.ts @@ -0,0 +1,98 @@ +export type Point = { + x: number + y: number +} + +export type Size = { + width: number + height: number +} + +export type Rectangle = Point & Size + +/** Edge insets (padding, margin, border) */ +export type Edges = { + top: number + right: number + bottom: number + left: number +} + +/** Create uniform edges */ +export function edges(all: number): Edges +export function edges(vertical: number, horizontal: number): Edges +export function edges(top: number, right: number, bottom: number, left: number): Edges + +export function edges(a: number, b?: number, c?: number, d?: number): Edges { + if (b === undefined) { + return { top: a, right: a, bottom: a, left: a } + } + + if (c === undefined) { + return { top: a, right: b, bottom: a, left: b } + } + + return { top: a, right: b, bottom: c, left: d! } +} + +/** Add two edge values */ +export function addEdges(a: Edges, b: Edges): Edges { + return { + top: a.top + b.top, + right: a.right + b.right, + bottom: a.bottom + b.bottom, + left: a.left + b.left + } +} + +/** Zero edges constant */ +export const ZERO_EDGES: Edges = { top: 0, right: 0, bottom: 0, left: 0 } + +/** Convert partial edges to full edges with defaults */ +export function resolveEdges(partial?: Partial): Edges { + return { + top: partial?.top ?? 0, + right: partial?.right ?? 0, + bottom: partial?.bottom ?? 0, + left: partial?.left ?? 0 + } +} + +export function unionRect(a: Rectangle, b: Rectangle): Rectangle { + const minX = Math.min(a.x, b.x) + const minY = Math.min(a.y, b.y) + const maxX = Math.max(a.x + a.width, b.x + b.width) + const maxY = Math.max(a.y + a.height, b.y + b.height) + + return { x: minX, y: minY, width: maxX - minX, height: maxY - minY } +} + +export function clampRect(rect: Rectangle, size: Size): Rectangle { + const minX = Math.max(0, rect.x) + const minY = Math.max(0, rect.y) + const maxX = Math.min(size.width - 1, rect.x + rect.width - 1) + const maxY = Math.min(size.height - 1, rect.y + rect.height - 1) + + return { + x: minX, + y: minY, + width: Math.max(0, maxX - minX + 1), + height: Math.max(0, maxY - minY + 1) + } +} + +export function withinBounds(size: Size, point: Point): boolean { + return point.x >= 0 && point.y >= 0 && point.x < size.width && point.y < size.height +} + +export function clamp(value: number, min?: number, max?: number): number { + if (min !== undefined && value < min) { + return min + } + + if (max !== undefined && value > max) { + return max + } + + return value +} diff --git a/ui-tui/packages/hermes-ink/src/ink/layout/node.ts b/ui-tui/packages/hermes-ink/src/ink/layout/node.ts new file mode 100644 index 0000000000..fa84a4f810 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/layout/node.ts @@ -0,0 +1,145 @@ +// -- +// Adapter interface for the layout engine (Yoga) + +export const LayoutEdge = { + All: 'all', + Horizontal: 'horizontal', + Vertical: 'vertical', + Left: 'left', + Right: 'right', + Top: 'top', + Bottom: 'bottom', + Start: 'start', + End: 'end' +} as const +export type LayoutEdge = (typeof LayoutEdge)[keyof typeof LayoutEdge] + +export const LayoutGutter = { + All: 'all', + Column: 'column', + Row: 'row' +} as const +export type LayoutGutter = (typeof LayoutGutter)[keyof typeof LayoutGutter] + +export const LayoutDisplay = { + Flex: 'flex', + None: 'none' +} as const +export type LayoutDisplay = (typeof LayoutDisplay)[keyof typeof LayoutDisplay] + +export const LayoutFlexDirection = { + Row: 'row', + RowReverse: 'row-reverse', + Column: 'column', + ColumnReverse: 'column-reverse' +} as const +export type LayoutFlexDirection = (typeof LayoutFlexDirection)[keyof typeof LayoutFlexDirection] + +export const LayoutAlign = { + Auto: 'auto', + Stretch: 'stretch', + FlexStart: 'flex-start', + Center: 'center', + FlexEnd: 'flex-end' +} as const +export type LayoutAlign = (typeof LayoutAlign)[keyof typeof LayoutAlign] + +export const LayoutJustify = { + FlexStart: 'flex-start', + Center: 'center', + FlexEnd: 'flex-end', + SpaceBetween: 'space-between', + SpaceAround: 'space-around', + SpaceEvenly: 'space-evenly' +} as const +export type LayoutJustify = (typeof LayoutJustify)[keyof typeof LayoutJustify] + +export const LayoutWrap = { + NoWrap: 'nowrap', + Wrap: 'wrap', + WrapReverse: 'wrap-reverse' +} as const +export type LayoutWrap = (typeof LayoutWrap)[keyof typeof LayoutWrap] + +export const LayoutPositionType = { + Relative: 'relative', + Absolute: 'absolute' +} as const +export type LayoutPositionType = (typeof LayoutPositionType)[keyof typeof LayoutPositionType] + +export const LayoutOverflow = { + Visible: 'visible', + Hidden: 'hidden', + Scroll: 'scroll' +} as const +export type LayoutOverflow = (typeof LayoutOverflow)[keyof typeof LayoutOverflow] + +export type LayoutMeasureFunc = (width: number, widthMode: LayoutMeasureMode) => { width: number; height: number } + +export const LayoutMeasureMode = { + Undefined: 'undefined', + Exactly: 'exactly', + AtMost: 'at-most' +} as const +export type LayoutMeasureMode = (typeof LayoutMeasureMode)[keyof typeof LayoutMeasureMode] + +export type LayoutNode = { + // Tree + insertChild(child: LayoutNode, index: number): void + removeChild(child: LayoutNode): void + getChildCount(): number + getParent(): LayoutNode | null + + // Layout computation + calculateLayout(width?: number, height?: number): void + setMeasureFunc(fn: LayoutMeasureFunc): void + unsetMeasureFunc(): void + markDirty(): void + + // Layout reading (post-layout) + getComputedLeft(): number + getComputedTop(): number + getComputedWidth(): number + getComputedHeight(): number + getComputedBorder(edge: LayoutEdge): number + getComputedPadding(edge: LayoutEdge): number + + // Style setters + setWidth(value: number): void + setWidthPercent(value: number): void + setWidthAuto(): void + setHeight(value: number): void + setHeightPercent(value: number): void + setHeightAuto(): void + setMinWidth(value: number): void + setMinWidthPercent(value: number): void + setMinHeight(value: number): void + setMinHeightPercent(value: number): void + setMaxWidth(value: number): void + setMaxWidthPercent(value: number): void + setMaxHeight(value: number): void + setMaxHeightPercent(value: number): void + setFlexDirection(dir: LayoutFlexDirection): void + setFlexGrow(value: number): void + setFlexShrink(value: number): void + setFlexBasis(value: number): void + setFlexBasisPercent(value: number): void + setFlexWrap(wrap: LayoutWrap): void + setAlignItems(align: LayoutAlign): void + setAlignSelf(align: LayoutAlign): void + setJustifyContent(justify: LayoutJustify): void + setDisplay(display: LayoutDisplay): void + getDisplay(): LayoutDisplay + setPositionType(type: LayoutPositionType): void + setPosition(edge: LayoutEdge, value: number): void + setPositionPercent(edge: LayoutEdge, value: number): void + setOverflow(overflow: LayoutOverflow): void + setMargin(edge: LayoutEdge, value: number): void + setPadding(edge: LayoutEdge, value: number): void + setBorder(edge: LayoutEdge, value: number): void + setGap(gutter: LayoutGutter, value: number): void + + // Lifecycle + free(): void + freeRecursive(): void +} diff --git a/ui-tui/packages/hermes-ink/src/ink/layout/yoga.ts b/ui-tui/packages/hermes-ink/src/ink/layout/yoga.ts new file mode 100644 index 0000000000..e18c7f848c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/layout/yoga.ts @@ -0,0 +1,313 @@ +import Yoga, { + Align, + Direction, + Display, + Edge, + FlexDirection, + Gutter, + Justify, + MeasureMode, + Overflow, + PositionType, + Wrap, + type Node as YogaNode +} from '../../native-ts/yoga-layout/index.js' + +import { + type LayoutAlign, + LayoutDisplay, + type LayoutEdge, + type LayoutFlexDirection, + type LayoutGutter, + type LayoutJustify, + type LayoutMeasureFunc, + LayoutMeasureMode, + type LayoutNode, + type LayoutOverflow, + type LayoutPositionType, + type LayoutWrap +} from './node.js' + +// -- +// Edge/Gutter mapping + +const EDGE_MAP: Record = { + all: Edge.All, + horizontal: Edge.Horizontal, + vertical: Edge.Vertical, + left: Edge.Left, + right: Edge.Right, + top: Edge.Top, + bottom: Edge.Bottom, + start: Edge.Start, + end: Edge.End +} + +const GUTTER_MAP: Record = { + all: Gutter.All, + column: Gutter.Column, + row: Gutter.Row +} + +// -- +// Yoga adapter + +export class YogaLayoutNode implements LayoutNode { + readonly yoga: YogaNode + + constructor(yoga: YogaNode) { + this.yoga = yoga + } + + // Tree + + insertChild(child: LayoutNode, index: number): void { + this.yoga.insertChild((child as YogaLayoutNode).yoga, index) + } + + removeChild(child: LayoutNode): void { + this.yoga.removeChild((child as YogaLayoutNode).yoga) + } + + getChildCount(): number { + return this.yoga.getChildCount() + } + + getParent(): LayoutNode | null { + const p = this.yoga.getParent() + + return p ? new YogaLayoutNode(p) : null + } + + // Layout + + calculateLayout(width?: number, _height?: number): void { + this.yoga.calculateLayout(width, undefined, Direction.LTR) + } + + setMeasureFunc(fn: LayoutMeasureFunc): void { + this.yoga.setMeasureFunc((w, wMode) => { + const mode = + wMode === MeasureMode.Exactly + ? LayoutMeasureMode.Exactly + : wMode === MeasureMode.AtMost + ? LayoutMeasureMode.AtMost + : LayoutMeasureMode.Undefined + + return fn(w, mode) + }) + } + + unsetMeasureFunc(): void { + this.yoga.unsetMeasureFunc() + } + + markDirty(): void { + this.yoga.markDirty() + } + + // Computed layout + + getComputedLeft(): number { + return this.yoga.getComputedLeft() + } + + getComputedTop(): number { + return this.yoga.getComputedTop() + } + + getComputedWidth(): number { + return this.yoga.getComputedWidth() + } + + getComputedHeight(): number { + return this.yoga.getComputedHeight() + } + + getComputedBorder(edge: LayoutEdge): number { + return this.yoga.getComputedBorder(EDGE_MAP[edge]!) + } + + getComputedPadding(edge: LayoutEdge): number { + return this.yoga.getComputedPadding(EDGE_MAP[edge]!) + } + + // Style setters + + setWidth(value: number): void { + this.yoga.setWidth(value) + } + setWidthPercent(value: number): void { + this.yoga.setWidthPercent(value) + } + setWidthAuto(): void { + this.yoga.setWidthAuto() + } + setHeight(value: number): void { + this.yoga.setHeight(value) + } + setHeightPercent(value: number): void { + this.yoga.setHeightPercent(value) + } + setHeightAuto(): void { + this.yoga.setHeightAuto() + } + setMinWidth(value: number): void { + this.yoga.setMinWidth(value) + } + setMinWidthPercent(value: number): void { + this.yoga.setMinWidthPercent(value) + } + setMinHeight(value: number): void { + this.yoga.setMinHeight(value) + } + setMinHeightPercent(value: number): void { + this.yoga.setMinHeightPercent(value) + } + setMaxWidth(value: number): void { + this.yoga.setMaxWidth(value) + } + setMaxWidthPercent(value: number): void { + this.yoga.setMaxWidthPercent(value) + } + setMaxHeight(value: number): void { + this.yoga.setMaxHeight(value) + } + setMaxHeightPercent(value: number): void { + this.yoga.setMaxHeightPercent(value) + } + + setFlexDirection(dir: LayoutFlexDirection): void { + const map: Record = { + row: FlexDirection.Row, + 'row-reverse': FlexDirection.RowReverse, + column: FlexDirection.Column, + 'column-reverse': FlexDirection.ColumnReverse + } + + this.yoga.setFlexDirection(map[dir]!) + } + + setFlexGrow(value: number): void { + this.yoga.setFlexGrow(value) + } + setFlexShrink(value: number): void { + this.yoga.setFlexShrink(value) + } + setFlexBasis(value: number): void { + this.yoga.setFlexBasis(value) + } + setFlexBasisPercent(value: number): void { + this.yoga.setFlexBasisPercent(value) + } + + setFlexWrap(wrap: LayoutWrap): void { + const map: Record = { + nowrap: Wrap.NoWrap, + wrap: Wrap.Wrap, + 'wrap-reverse': Wrap.WrapReverse + } + + this.yoga.setFlexWrap(map[wrap]!) + } + + setAlignItems(align: LayoutAlign): void { + const map: Record = { + auto: Align.Auto, + stretch: Align.Stretch, + 'flex-start': Align.FlexStart, + center: Align.Center, + 'flex-end': Align.FlexEnd + } + + this.yoga.setAlignItems(map[align]!) + } + + setAlignSelf(align: LayoutAlign): void { + const map: Record = { + auto: Align.Auto, + stretch: Align.Stretch, + 'flex-start': Align.FlexStart, + center: Align.Center, + 'flex-end': Align.FlexEnd + } + + this.yoga.setAlignSelf(map[align]!) + } + + setJustifyContent(justify: LayoutJustify): void { + const map: Record = { + 'flex-start': Justify.FlexStart, + center: Justify.Center, + 'flex-end': Justify.FlexEnd, + 'space-between': Justify.SpaceBetween, + 'space-around': Justify.SpaceAround, + 'space-evenly': Justify.SpaceEvenly + } + + this.yoga.setJustifyContent(map[justify]!) + } + + setDisplay(display: LayoutDisplay): void { + this.yoga.setDisplay(display === 'flex' ? Display.Flex : Display.None) + } + + getDisplay(): LayoutDisplay { + return this.yoga.getDisplay() === Display.None ? LayoutDisplay.None : LayoutDisplay.Flex + } + + setPositionType(type: LayoutPositionType): void { + this.yoga.setPositionType(type === 'absolute' ? PositionType.Absolute : PositionType.Relative) + } + + setPosition(edge: LayoutEdge, value: number): void { + this.yoga.setPosition(EDGE_MAP[edge]!, value) + } + + setPositionPercent(edge: LayoutEdge, value: number): void { + this.yoga.setPositionPercent(EDGE_MAP[edge]!, value) + } + + setOverflow(overflow: LayoutOverflow): void { + const map: Record = { + visible: Overflow.Visible, + hidden: Overflow.Hidden, + scroll: Overflow.Scroll + } + + this.yoga.setOverflow(map[overflow]!) + } + + setMargin(edge: LayoutEdge, value: number): void { + this.yoga.setMargin(EDGE_MAP[edge]!, value) + } + setPadding(edge: LayoutEdge, value: number): void { + this.yoga.setPadding(EDGE_MAP[edge]!, value) + } + setBorder(edge: LayoutEdge, value: number): void { + this.yoga.setBorder(EDGE_MAP[edge]!, value) + } + setGap(gutter: LayoutGutter, value: number): void { + this.yoga.setGap(GUTTER_MAP[gutter]!, value) + } + + // Lifecycle + + free(): void { + this.yoga.free() + } + freeRecursive(): void { + this.yoga.freeRecursive() + } +} + +// -- +// Instance management +// +// The TS yoga-layout port is synchronous — no WASM loading, no linear memory +// growth, so no preload/swap/reset machinery is needed. The Yoga instance is +// just a plain JS object available at import time. + +export function createYogaLayoutNode(): LayoutNode { + return new YogaLayoutNode(Yoga.Node.create()) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/line-width-cache.ts b/ui-tui/packages/hermes-ink/src/ink/line-width-cache.ts new file mode 100644 index 0000000000..0791fbb8a6 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/line-width-cache.ts @@ -0,0 +1,28 @@ +import { stringWidth } from './stringWidth.js' + +// During streaming, text grows but completed lines are immutable. +// Caching stringWidth per-line avoids re-measuring hundreds of +// unchanged lines on every token (~50x reduction in stringWidth calls). +const cache = new Map() + +const MAX_CACHE_SIZE = 4096 + +export function lineWidth(line: string): number { + const cached = cache.get(line) + + if (cached !== undefined) { + return cached + } + + const width = stringWidth(line) + + // Evict when cache grows too large (e.g. after many different responses). + // Simple full-clear is fine — the cache repopulates in one frame. + if (cache.size >= MAX_CACHE_SIZE) { + cache.clear() + } + + cache.set(line, width) + + return width +} diff --git a/ui-tui/packages/hermes-ink/src/ink/log-update.ts b/ui-tui/packages/hermes-ink/src/ink/log-update.ts new file mode 100644 index 0000000000..e4dc3dc7a4 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/log-update.ts @@ -0,0 +1,738 @@ +import { type AnsiCode, ansiCodesToString, diffAnsiCodes } from '@alcalzone/ansi-tokenize' + +import { logForDebugging } from '../utils/debug.js' + +import type { Diff, FlickerReason, Frame } from './frame.js' +import type { Point } from './layout/geometry.js' +import { + type Cell, + cellAt, + CellWidth, + charInCellAt, + diffEach, + type Hyperlink, + isEmptyCellAt, + type Screen, + shiftRows, + type StylePool, + visibleCellAtIndex +} from './screen.js' +import { + scrollDown as csiScrollDown, + scrollUp as csiScrollUp, + CURSOR_HOME, + RESET_SCROLL_REGION, + setScrollRegion +} from './termio/csi.js' +import { LINK_END, link as oscLink } from './termio/osc.js' + +type State = { + previousOutput: string +} + +type Options = { + isTTY: boolean + stylePool: StylePool +} + +const CARRIAGE_RETURN = { type: 'carriageReturn' } as const +const NEWLINE = { type: 'stdout', content: '\n' } as const + +export class LogUpdate { + private state: State + + constructor(private readonly options: Options) { + this.state = { + previousOutput: '' + } + } + + renderPreviousOutput_DEPRECATED(prevFrame: Frame): Diff { + if (!this.options.isTTY) { + // Non-TTY output is no longer supported (string output was removed) + return [NEWLINE] + } + + return this.getRenderOpsForDone(prevFrame) + } + + // Called when process resumes from suspension (SIGCONT) to prevent clobbering terminal content + reset(): void { + this.state.previousOutput = '' + } + + private renderFullFrame(frame: Frame): Diff { + const { screen } = frame + const lines: string[] = [] + let currentStyles: AnsiCode[] = [] + let currentHyperlink: Hyperlink = undefined + + for (let y = 0; y < screen.height; y++) { + let line = '' + + for (let x = 0; x < screen.width; x++) { + const cell = cellAt(screen, x, y) + + if (cell && cell.width !== CellWidth.SpacerTail) { + // Handle hyperlink transitions + if (cell.hyperlink !== currentHyperlink) { + if (currentHyperlink !== undefined) { + line += LINK_END + } + + if (cell.hyperlink !== undefined) { + line += oscLink(cell.hyperlink) + } + + currentHyperlink = cell.hyperlink + } + + const cellStyles = this.options.stylePool.get(cell.styleId) + const styleDiff = diffAnsiCodes(currentStyles, cellStyles) + + if (styleDiff.length > 0) { + line += ansiCodesToString(styleDiff) + currentStyles = cellStyles + } + + line += cell.char + } + } + + // Close any open hyperlink before resetting styles + if (currentHyperlink !== undefined) { + line += LINK_END + currentHyperlink = undefined + } + + // Reset styles at end of line so trimEnd doesn't leave dangling codes + const resetCodes = diffAnsiCodes(currentStyles, []) + + if (resetCodes.length > 0) { + line += ansiCodesToString(resetCodes) + currentStyles = [] + } + + lines.push(line.trimEnd()) + } + + if (lines.length === 0) { + return [] + } + + return [{ type: 'stdout', content: lines.join('\n') }] + } + + private getRenderOpsForDone(prev: Frame): Diff { + this.state.previousOutput = '' + + if (!prev.cursor.visible) { + return [{ type: 'cursorShow' }] + } + + return [] + } + + render(prev: Frame, next: Frame, altScreen = false, decstbmSafe = true): Diff { + if (!this.options.isTTY) { + return this.renderFullFrame(next) + } + + const startTime = performance.now() + const stylePool = this.options.stylePool + + // Since we assume the cursor is at the bottom on the screen, we only need + // to clear when the viewport gets shorter (i.e. the cursor position drifts) + // or when it gets thinner (and text wraps). We _could_ figure out how to + // not reset here but that would involve predicting the current layout + // _after_ the viewport change which means calcuating text wrapping. + // Resizing is a rare enough event that it's not practically a big issue. + if ( + next.viewport.height < prev.viewport.height || + (prev.viewport.width !== 0 && next.viewport.width !== prev.viewport.width) + ) { + return fullResetSequence_CAUSES_FLICKER(next, 'resize', stylePool) + } + + // DECSTBM scroll optimization: when a ScrollBox's scrollTop changed, + // shift content with a hardware scroll (CSI top;bot r + CSI n S/T) + // instead of rewriting the whole scroll region. The shiftRows on + // prev.screen simulates the shift so the diff loop below naturally + // finds only the rows that scrolled IN as diffs. prev.screen is + // about to become backFrame (reused next render) so mutation is safe. + // CURSOR_HOME after RESET_SCROLL_REGION is defensive — DECSTBM reset + // homes cursor per spec but terminal implementations vary. + // + // decstbmSafe: caller passes false when the DECSTBM→diff sequence + // can't be made atomic (no DEC 2026 / BSU/ESU). Without atomicity the + // outer terminal renders the intermediate state — region scrolled, + // edge rows not yet painted — a visible vertical jump on every frame + // where scrollTop moves. Falling through to the diff loop writes all + // shifted rows: more bytes, no intermediate state. next.screen from + // render-node-to-output's blit+shift is correct either way. + let scrollPatch: Diff = [] + + if (altScreen && next.scrollHint && decstbmSafe) { + const { top, bottom, delta } = next.scrollHint + + if (top >= 0 && bottom < prev.screen.height && bottom < next.screen.height) { + shiftRows(prev.screen, top, bottom, delta) + scrollPatch = [ + { + type: 'stdout', + content: + setScrollRegion(top + 1, bottom + 1) + + (delta > 0 ? csiScrollUp(delta) : csiScrollDown(-delta)) + + RESET_SCROLL_REGION + + CURSOR_HOME + } + ] + } + } + + // We have to use purely relative operations to manipulate the cursor since + // we don't know its starting point. + // + // When content height >= viewport height AND cursor is at the bottom, + // the cursor restore at the end of the previous frame caused terminal scroll. + // viewportY tells us how many rows are in scrollback from content overflow. + // Additionally, the cursor-restore scroll pushes 1 more row into scrollback. + // We need fullReset if any changes are to rows that are now in scrollback. + // + // This early full-reset check only applies in "steady state" (not growing). + // For growing, the viewportY calculation below (with cursorRestoreScroll) + // catches unreachable scrollback rows in the diff loop instead. + const cursorAtBottom = prev.cursor.y >= prev.screen.height + const isGrowing = next.screen.height > prev.screen.height + + // When content fills the viewport exactly (height == viewport) and the + // cursor is at the bottom, the cursor-restore LF at the end of the + // previous frame scrolled 1 row into scrollback. Use >= to catch this. + const prevHadScrollback = cursorAtBottom && prev.screen.height >= prev.viewport.height + + const isShrinking = next.screen.height < prev.screen.height + const nextFitsViewport = next.screen.height <= prev.viewport.height + + // When shrinking from above-viewport to at-or-below-viewport, content that + // was in scrollback should now be visible. Terminal clear operations can't + // bring scrollback content into view, so we need a full reset. + // Use <= (not <) because even when next height equals viewport height, the + // scrollback depth from the previous render differs from a fresh render. + if (prevHadScrollback && nextFitsViewport && isShrinking) { + logForDebugging( + `Full reset (shrink->below): prevHeight=${prev.screen.height}, nextHeight=${next.screen.height}, viewport=${prev.viewport.height}` + ) + + return fullResetSequence_CAUSES_FLICKER(next, 'offscreen', stylePool) + } + + if (prev.screen.height >= prev.viewport.height && prev.screen.height > 0 && cursorAtBottom && !isGrowing) { + // viewportY = rows in scrollback from content overflow + // +1 for the row pushed by cursor-restore scroll + const viewportY = prev.screen.height - prev.viewport.height + const scrollbackRows = viewportY + 1 + + let scrollbackChangeY = -1 + diffEach(prev.screen, next.screen, (_x, y) => { + if (y < scrollbackRows) { + scrollbackChangeY = y + + return true // early exit + } + }) + + if (scrollbackChangeY >= 0) { + const prevLine = readLine(prev.screen, scrollbackChangeY) + const nextLine = readLine(next.screen, scrollbackChangeY) + + return fullResetSequence_CAUSES_FLICKER(next, 'offscreen', stylePool, { + triggerY: scrollbackChangeY, + prevLine, + nextLine + }) + } + } + + const screen = new VirtualScreen(prev.cursor, next.viewport.width) + + // Treat empty screen as height 1 to avoid spurious adjustments on first render + const heightDelta = Math.max(next.screen.height, 1) - Math.max(prev.screen.height, 1) + + const shrinking = heightDelta < 0 + const growing = heightDelta > 0 + + // Handle shrinking: clear lines from the bottom + if (shrinking) { + const linesToClear = prev.screen.height - next.screen.height + + // eraseLines only works within the viewport - it can't clear scrollback. + // If we need to clear more lines than fit in the viewport, some are in + // scrollback, so we need a full reset. + if (linesToClear > prev.viewport.height) { + return fullResetSequence_CAUSES_FLICKER(next, 'offscreen', this.options.stylePool) + } + + // clear(N) moves cursor UP by N-1 lines and to column 0 + // This puts us at line prev.screen.height - N = next.screen.height + // But we want to be at next.screen.height - 1 (bottom of new screen) + screen.txn(prev => [ + [ + { type: 'clear', count: linesToClear }, + { type: 'cursorMove', x: 0, y: -1 } + ], + { dx: -prev.x, dy: -linesToClear } + ]) + } + + // viewportY = number of rows in scrollback (not visible on terminal). + // For shrinking: use max(prev, next) because terminal clears don't scroll. + // For growing: use prev state because new rows haven't scrolled old ones yet. + // When prevHadScrollback, add 1 for the cursor-restore LF that scrolled + // an additional row out of view at the end of the previous frame. Without + // this, the diff loop treats that row as reachable — but the cursor clamps + // at viewport top, causing writes to land 1 row off and garbling the output. + const cursorRestoreScroll = prevHadScrollback ? 1 : 0 + + const viewportY = growing + ? Math.max(0, prev.screen.height - prev.viewport.height + cursorRestoreScroll) + : Math.max(prev.screen.height, next.screen.height) - next.viewport.height + cursorRestoreScroll + + let currentStyleId = stylePool.none + let currentHyperlink: Hyperlink = undefined + + // First pass: render changes to existing rows (rows < prev.screen.height) + let needsFullReset = false + let resetTriggerY = -1 + diffEach(prev.screen, next.screen, (x, y, removed, added) => { + // Skip new rows - we'll render them directly after + if (growing && y >= prev.screen.height) { + return + } + + // Skip spacers during rendering because the terminal will automatically + // advance 2 columns when we write the wide character itself. + // SpacerTail: Second cell of a wide character + // SpacerHead: Marks line-end position where wide char wraps to next line + if (added && (added.width === CellWidth.SpacerTail || added.width === CellWidth.SpacerHead)) { + return + } + + if (removed && (removed.width === CellWidth.SpacerTail || removed.width === CellWidth.SpacerHead) && !added) { + return + } + + // Skip empty cells that don't need to overwrite existing content. + // This prevents writing trailing spaces that would cause unnecessary + // line wrapping at the edge of the screen. + // Uses isEmptyCellAt to check if both packed words are zero (empty cell). + if (added && isEmptyCellAt(next.screen, x, y) && !removed) { + return + } + + // If the cell outside the viewport range has changed, we need to reset + // because we can't move the cursor there to draw. + if (y < viewportY) { + needsFullReset = true + resetTriggerY = y + + return true // early exit + } + + moveCursorTo(screen, x, y) + + if (added) { + const targetHyperlink = added.hyperlink + currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, targetHyperlink) + const styleStr = stylePool.transition(currentStyleId, added.styleId) + + if (writeCellWithStyleStr(screen, added, styleStr)) { + currentStyleId = added.styleId + } + } else if (removed) { + // Cell was removed - clear it with a space + // (This handles shrinking content) + // Reset any active styles/hyperlinks first to avoid leaking into cleared cells + const styleIdToReset = currentStyleId + const hyperlinkToReset = currentHyperlink + currentStyleId = stylePool.none + currentHyperlink = undefined + + screen.txn(() => { + const patches: Diff = [] + transitionStyle(patches, stylePool, styleIdToReset, stylePool.none) + transitionHyperlink(patches, hyperlinkToReset, undefined) + patches.push({ type: 'stdout', content: ' ' }) + + return [patches, { dx: 1, dy: 0 }] + }) + } + }) + + if (needsFullReset) { + return fullResetSequence_CAUSES_FLICKER(next, 'offscreen', stylePool, { + triggerY: resetTriggerY, + prevLine: readLine(prev.screen, resetTriggerY), + nextLine: readLine(next.screen, resetTriggerY) + }) + } + + // Reset styles before rendering new rows (they'll set their own styles) + currentStyleId = transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none) + currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, undefined) + + // Handle growth: render new rows directly (they naturally scroll the terminal) + if (growing) { + renderFrameSlice(screen, next, prev.screen.height, next.screen.height, stylePool) + } + + // Restore cursor. Skipped in alt-screen: the cursor is hidden, its + // position only matters as the starting point for the NEXT frame's + // relative moves, and in alt-screen the next frame always begins with + // CSI H (see ink.tsx onRender) which resets to (0,0) regardless. This + // saves a CR + cursorMove round-trip (~6-10 bytes) every frame. + // + // Main screen: if cursor needs to be past the last line of content + // (typical: cursor.y = screen.height), emit \n to create that line + // since cursor movement can't create new lines. + if (altScreen) { + // no-op; next frame's CSI H anchors cursor + } else if (next.cursor.y >= next.screen.height) { + // Move to column 0 of current line, then emit newlines to reach target row + screen.txn(prev => { + const rowsToCreate = next.cursor.y - prev.y + + if (rowsToCreate > 0) { + // Use CR to resolve pending wrap (if any) without advancing + // to the next line, then LF to create each new row. + const patches: Diff = new Array(1 + rowsToCreate) + patches[0] = CARRIAGE_RETURN + + for (let i = 0; i < rowsToCreate; i++) { + patches[1 + i] = NEWLINE + } + + return [patches, { dx: -prev.x, dy: rowsToCreate }] + } + + // At or past target row - need to move cursor to correct position + const dy = next.cursor.y - prev.y + + if (dy !== 0 || prev.x !== next.cursor.x) { + // Use CR to clear pending wrap (if any), then cursor move + const patches: Diff = [CARRIAGE_RETURN] + patches.push({ type: 'cursorMove', x: next.cursor.x, y: dy }) + + return [patches, { dx: next.cursor.x - prev.x, dy }] + } + + return [[], { dx: 0, dy: 0 }] + }) + } else { + moveCursorTo(screen, next.cursor.x, next.cursor.y) + } + + const elapsed = performance.now() - startTime + + if (elapsed > 50) { + const damage = next.screen.damage + + const damageInfo = damage ? `${damage.width}x${damage.height} at (${damage.x},${damage.y})` : 'none' + + logForDebugging( + `Slow render: ${elapsed.toFixed(1)}ms, screen: ${next.screen.height}x${next.screen.width}, damage: ${damageInfo}, changes: ${screen.diff.length}` + ) + } + + return scrollPatch.length > 0 ? [...scrollPatch, ...screen.diff] : screen.diff + } +} + +function transitionHyperlink(diff: Diff, current: Hyperlink, target: Hyperlink): Hyperlink { + if (current !== target) { + diff.push({ type: 'hyperlink', uri: target ?? '' }) + + return target + } + + return current +} + +function transitionStyle(diff: Diff, stylePool: StylePool, currentId: number, targetId: number): number { + const str = stylePool.transition(currentId, targetId) + + if (str.length > 0) { + diff.push({ type: 'styleStr', str }) + } + + return targetId +} + +function readLine(screen: Screen, y: number): string { + let line = '' + + for (let x = 0; x < screen.width; x++) { + line += charInCellAt(screen, x, y) ?? ' ' + } + + return line.trimEnd() +} + +function fullResetSequence_CAUSES_FLICKER( + frame: Frame, + reason: FlickerReason, + stylePool: StylePool, + debug?: { triggerY: number; prevLine: string; nextLine: string } +): Diff { + // After clearTerminal, cursor is at (0, 0) + const screen = new VirtualScreen({ x: 0, y: 0 }, frame.viewport.width) + renderFrame(screen, frame, stylePool) + + return [{ type: 'clearTerminal', reason, debug }, ...screen.diff] +} + +function renderFrame(screen: VirtualScreen, frame: Frame, stylePool: StylePool): void { + renderFrameSlice(screen, frame, 0, frame.screen.height, stylePool) +} + +/** + * Render a slice of rows from the frame's screen. + * Each row is rendered followed by a newline. Cursor ends at (0, endY). + */ +function renderFrameSlice( + screen: VirtualScreen, + frame: Frame, + startY: number, + endY: number, + stylePool: StylePool +): VirtualScreen { + let currentStyleId = stylePool.none + let currentHyperlink: Hyperlink = undefined + // Track the styleId of the last rendered cell on this line (-1 if none). + // Passed to visibleCellAtIndex to enable fg-only space optimization. + let lastRenderedStyleId = -1 + + const { width: screenWidth, cells, charPool, hyperlinkPool } = frame.screen + + let index = startY * screenWidth + + for (let y = startY; y < endY; y += 1) { + // Advance cursor to this row using LF (not CSI CUD / cursor-down). + // CSI CUD stops at the viewport bottom margin and cannot scroll, + // but LF scrolls the viewport to create new lines. Without this, + // when the cursor is at the viewport bottom, moveCursorTo's + // cursor-down silently fails, creating a permanent off-by-one + // between the virtual cursor and the real terminal cursor. + if (screen.cursor.y < y) { + const rowsToAdvance = y - screen.cursor.y + screen.txn(prev => { + const patches: Diff = new Array(1 + rowsToAdvance) + patches[0] = CARRIAGE_RETURN + + for (let i = 0; i < rowsToAdvance; i++) { + patches[1 + i] = NEWLINE + } + + return [patches, { dx: -prev.x, dy: rowsToAdvance }] + }) + } + + // Reset at start of each line — no cell rendered yet + lastRenderedStyleId = -1 + + for (let x = 0; x < screenWidth; x += 1, index += 1) { + // Skip spacers, unstyled empty cells, and fg-only styled spaces that + // match the last rendered style (since cursor-forward produces identical + // visual result). visibleCellAtIndex handles the optimization internally + // to avoid allocating Cell objects for skipped cells. + const cell = visibleCellAtIndex(cells, charPool, hyperlinkPool, index, lastRenderedStyleId) + + if (!cell) { + continue + } + + moveCursorTo(screen, x, y) + + // Handle hyperlink + const targetHyperlink = cell.hyperlink + currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, targetHyperlink) + + // Style transition — cached string, zero allocations after warmup + const styleStr = stylePool.transition(currentStyleId, cell.styleId) + + if (writeCellWithStyleStr(screen, cell, styleStr)) { + currentStyleId = cell.styleId + lastRenderedStyleId = cell.styleId + } + } + + // Reset styles/hyperlinks before newline so background color doesn't + // bleed into the next line when the terminal scrolls. The old code + // reset implicitly by writing trailing unstyled spaces; now that we + // skip empty cells, we must reset explicitly. + currentStyleId = transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none) + currentHyperlink = transitionHyperlink(screen.diff, currentHyperlink, undefined) + // CR+LF at end of row — \r resets to column 0, \n moves to next line. + // Without \r, the terminal cursor stays at whatever column content ended + // (since we skip trailing spaces, this can be mid-row). + screen.txn(prev => [[CARRIAGE_RETURN, NEWLINE], { dx: -prev.x, dy: 1 }]) + } + + // Reset any open style/hyperlink at end of slice + transitionStyle(screen.diff, stylePool, currentStyleId, stylePool.none) + transitionHyperlink(screen.diff, currentHyperlink, undefined) + + return screen +} + +type Delta = { dx: number; dy: number } + +/** + * Write a cell with a pre-serialized style transition string (from + * StylePool.transition). Inlines the txn logic to avoid closure/tuple/delta + * allocations on every cell. + * + * Returns true if the cell was written, false if skipped (wide char at + * viewport edge). Callers MUST gate currentStyleId updates on this — when + * skipped, styleStr is never pushed and the terminal's style state is + * unchanged. Updating the virtual tracker anyway desyncs it from the + * terminal, and the next transition is computed from phantom state. + */ +function writeCellWithStyleStr(screen: VirtualScreen, cell: Cell, styleStr: string): boolean { + const cellWidth = cell.width === CellWidth.Wide ? 2 : 1 + const px = screen.cursor.x + const vw = screen.viewportWidth + + // Don't write wide chars that would cross the viewport edge. + // Single-codepoint chars (CJK) at vw-2 are safe; multi-codepoint + // graphemes (flags, ZWJ emoji) need stricter threshold. + if (cellWidth === 2 && px < vw) { + const threshold = cell.char.length > 2 ? vw : vw + 1 + + if (px + 2 >= threshold) { + return false + } + } + + const diff = screen.diff + + if (styleStr.length > 0) { + diff.push({ type: 'styleStr', str: styleStr }) + } + + const needsCompensation = cellWidth === 2 && needsWidthCompensation(cell.char) + + // On terminals with old wcwidth tables, a compensated emoji only advances + // the cursor 1 column, so the CHA below skips column x+1 without painting + // it. Write a styled space there first — on correct terminals the emoji + // glyph (width 2) overwrites it harmlessly; on old terminals it fills the + // gap with the emoji's background. Also clears any stale content at x+1. + // CHA is 1-based, so column px+1 (0-based) is CHA target px+2. + if (needsCompensation && px + 1 < vw) { + diff.push({ type: 'cursorTo', col: px + 2 }) + diff.push({ type: 'stdout', content: ' ' }) + diff.push({ type: 'cursorTo', col: px + 1 }) + } + + diff.push({ type: 'stdout', content: cell.char }) + + // Force terminal cursor to correct column after the emoji. + if (needsCompensation) { + diff.push({ type: 'cursorTo', col: px + cellWidth + 1 }) + } + + // Update cursor — mutate in place to avoid Point allocation + if (px >= vw) { + screen.cursor.x = cellWidth + screen.cursor.y++ + } else { + screen.cursor.x = px + cellWidth + } + + return true +} + +function moveCursorTo(screen: VirtualScreen, targetX: number, targetY: number) { + screen.txn(prev => { + const dx = targetX - prev.x + const dy = targetY - prev.y + const inPendingWrap = prev.x >= screen.viewportWidth + + // If we're in pending wrap state (cursor.x >= width), use CR + // to reset to column 0 on the current line without advancing + // to the next line, then issue the cursor movement. + if (inPendingWrap) { + return [[CARRIAGE_RETURN, { type: 'cursorMove', x: targetX, y: dy }], { dx, dy }] + } + + // When moving to a different line, use carriage return (\r) to reset to + // column 0 first, then cursor move. + if (dy !== 0) { + return [[CARRIAGE_RETURN, { type: 'cursorMove', x: targetX, y: dy }], { dx, dy }] + } + + // Standard same-line cursor move + return [[{ type: 'cursorMove', x: dx, y: dy }], { dx, dy }] + }) +} + +/** + * Identify emoji where the terminal's wcwidth may disagree with Unicode. + * On terminals with correct tables, the CHA we emit is a harmless no-op. + * + * Two categories: + * 1. Newer emoji (Unicode 12.0+) missing from terminal wcwidth tables. + * 2. Text-by-default emoji + VS16 (U+FE0F): the base codepoint is width 1 + * in wcwidth, but VS16 triggers emoji presentation making it width 2. + * Examples: ⚔️ (U+2694), ☠️ (U+2620), ❤️ (U+2764). + */ +function needsWidthCompensation(char: string): boolean { + const cp = char.codePointAt(0) + + if (cp === undefined) { + return false + } + + // U+1FA70-U+1FAFF: Symbols and Pictographs Extended-A (Unicode 12.0-15.0) + // U+1FB00-U+1FBFF: Symbols for Legacy Computing (Unicode 13.0) + if ((cp >= 0x1fa70 && cp <= 0x1faff) || (cp >= 0x1fb00 && cp <= 0x1fbff)) { + return true + } + + // Text-by-default emoji with VS16: scan for U+FE0F in multi-codepoint + // graphemes. Single BMP chars (length 1) and surrogate pairs without VS16 + // skip this check. VS16 (0xFE0F) can't collide with surrogates (0xD800-0xDFFF). + if (char.length >= 2) { + for (let i = 0; i < char.length; i++) { + if (char.charCodeAt(i) === 0xfe0f) { + return true + } + } + } + + return false +} + +class VirtualScreen { + // Public for direct mutation by writeCellWithStyleStr (avoids txn overhead). + // File-private class — not exposed outside log-update.ts. + cursor: Point + diff: Diff = [] + + constructor( + origin: Point, + readonly viewportWidth: number + ) { + this.cursor = { ...origin } + } + + txn(fn: (prev: Point) => [patches: Diff, next: Delta]): void { + const [patches, next] = fn(this.cursor) + + for (const patch of patches) { + this.diff.push(patch) + } + + this.cursor.x += next.dx + this.cursor.y += next.dy + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/measure-element.ts b/ui-tui/packages/hermes-ink/src/ink/measure-element.ts new file mode 100644 index 0000000000..64124d6ec2 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/measure-element.ts @@ -0,0 +1,23 @@ +import type { DOMElement } from './dom.js' + +type Output = { + /** + * Element width. + */ + width: number + + /** + * Element height. + */ + height: number +} + +/** + * Measure the dimensions of a particular `` element. + */ +const measureElement = (node: DOMElement): Output => ({ + width: node.yogaNode?.getComputedWidth() ?? 0, + height: node.yogaNode?.getComputedHeight() ?? 0 +}) + +export default measureElement diff --git a/ui-tui/packages/hermes-ink/src/ink/measure-text.ts b/ui-tui/packages/hermes-ink/src/ink/measure-text.ts new file mode 100644 index 0000000000..1d81cdedea --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/measure-text.ts @@ -0,0 +1,50 @@ +import { lineWidth } from './line-width-cache.js' + +type Output = { + width: number + height: number +} + +// Single-pass measurement: computes both width and height in one +// iteration instead of two (widestLine + countVisualLines). +// Uses indexOf to avoid array allocation from split('\n'). +function measureText(text: string, maxWidth: number): Output { + if (text.length === 0) { + return { + width: 0, + height: 0 + } + } + + // Infinite or non-positive width means no wrapping — each line is one visual line. + // Must check before the loop since Math.ceil(w / Infinity) = 0. + const noWrap = maxWidth <= 0 || !Number.isFinite(maxWidth) + + let height = 0 + let width = 0 + let start = 0 + + while (start <= text.length) { + const end = text.indexOf('\n', start) + const line = end === -1 ? text.substring(start) : text.substring(start, end) + + const w = lineWidth(line) + width = Math.max(width, w) + + if (noWrap) { + height++ + } else { + height += w === 0 ? 1 : Math.ceil(w / maxWidth) + } + + if (end === -1) { + break + } + + start = end + 1 + } + + return { width, height } +} + +export default measureText diff --git a/ui-tui/packages/hermes-ink/src/ink/node-cache.ts b/ui-tui/packages/hermes-ink/src/ink/node-cache.ts new file mode 100644 index 0000000000..fe11e067ec --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/node-cache.ts @@ -0,0 +1,53 @@ +import type { DOMElement } from './dom.js' +import type { Rectangle } from './layout/geometry.js' + +/** + * Cached layout bounds for each rendered node (used for blit + clearing). + * `top` is the yoga-local getComputedTop() — stored so ScrollBox viewport + * culling can skip yoga reads for clean children whose position hasn't + * shifted (O(dirty) instead of O(mounted) first-pass). + */ +export type CachedLayout = { + x: number + y: number + width: number + height: number + top?: number +} + +export const nodeCache = new WeakMap() + +/** Rects of removed children that need clearing on next render */ +export const pendingClears = new WeakMap() + +/** + * Set when a pendingClear is added for an absolute-positioned node. + * Signals renderer to disable blit for the next frame: the removed node + * may have painted over non-siblings (e.g. an overlay over a ScrollBox + * earlier in tree order), so their blits from prevScreen would restore + * the overlay's pixels. Normal-flow removals are already handled by + * hasRemovedChild at the parent level; only absolute positioning paints + * cross-subtree. Reset at the start of each render. + */ +let absoluteNodeRemoved = false + +export function addPendingClear(parent: DOMElement, rect: Rectangle, isAbsolute: boolean): void { + const existing = pendingClears.get(parent) + + if (existing) { + existing.push(rect) + } else { + pendingClears.set(parent, [rect]) + } + + if (isAbsolute) { + absoluteNodeRemoved = true + } +} + +export function consumeAbsoluteRemovedFlag(): boolean { + const had = absoluteNodeRemoved + absoluteNodeRemoved = false + + return had +} diff --git a/ui-tui/packages/hermes-ink/src/ink/optimizer.ts b/ui-tui/packages/hermes-ink/src/ink/optimizer.ts new file mode 100644 index 0000000000..a4fd3812c7 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/optimizer.ts @@ -0,0 +1,99 @@ +import type { Diff } from './frame.js' + +/** + * Optimize a diff by applying all optimization rules in a single pass. + * This reduces the number of patches that need to be written to the terminal. + * + * Rules applied: + * - Remove empty stdout patches + * - Merge consecutive cursorMove patches + * - Remove no-op cursorMove (0,0) patches + * - Concat adjacent style patches (transition diffs — can't drop either) + * - Dedupe consecutive hyperlinks with same URI + * - Cancel cursor hide/show pairs + * - Remove clear patches with count 0 + */ +export function optimize(diff: Diff): Diff { + if (diff.length <= 1) { + return diff + } + + const result: Diff = [] + let len = 0 + + for (const patch of diff) { + const type = patch.type + + // Skip no-ops + if (type === 'stdout') { + if (patch.content === '') { + continue + } + } else if (type === 'cursorMove') { + if (patch.x === 0 && patch.y === 0) { + continue + } + } else if (type === 'clear') { + if (patch.count === 0) { + continue + } + } + + // Try to merge with previous patch + if (len > 0) { + const lastIdx = len - 1 + const last = result[lastIdx]! + const lastType = last.type + + // Merge consecutive cursorMove + if (type === 'cursorMove' && lastType === 'cursorMove') { + result[lastIdx] = { + type: 'cursorMove', + x: last.x + patch.x, + y: last.y + patch.y + } + + continue + } + + // Collapse consecutive cursorTo (only the last one matters) + if (type === 'cursorTo' && lastType === 'cursorTo') { + result[lastIdx] = patch + + continue + } + + // Concat adjacent style patches. styleStr is a transition diff + // (computed by diffAnsiCodes(from, to)), not a setter — dropping + // the first is only sound if its undo-codes are a subset of the + // second's, which is NOT guaranteed. e.g. [\e[49m, \e[2m]: dropping + // the bg reset leaks it into the next \e[2J/\e[2K via BCE. + if (type === 'styleStr' && lastType === 'styleStr') { + result[lastIdx] = { type: 'styleStr', str: last.str + patch.str } + + continue + } + + // Dedupe hyperlinks + if (type === 'hyperlink' && lastType === 'hyperlink' && patch.uri === last.uri) { + continue + } + + // Cancel cursor hide/show pairs + if ( + (type === 'cursorShow' && lastType === 'cursorHide') || + (type === 'cursorHide' && lastType === 'cursorShow') + ) { + result.pop() + len-- + + continue + } + } + + result.push(patch) + len++ + } + + return result +} diff --git a/ui-tui/packages/hermes-ink/src/ink/output.ts b/ui-tui/packages/hermes-ink/src/ink/output.ts new file mode 100644 index 0000000000..f52bf06363 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/output.ts @@ -0,0 +1,833 @@ +import { type AnsiCode, type StyledChar, styledCharsFromTokens, tokenize } from '@alcalzone/ansi-tokenize' + +import { logForDebugging } from '../utils/debug.js' +import { getGraphemeSegmenter } from '../utils/intl.js' +import sliceAnsi from '../utils/sliceAnsi.js' + +import { reorderBidi } from './bidi.js' +import { type Rectangle, unionRect } from './layout/geometry.js' +import { + blitRegion, + CellWidth, + extractHyperlinkFromStyles, + filterOutHyperlinkStyles, + markNoSelectRegion, + OSC8_PREFIX, + resetScreen, + type Screen, + setCellAt, + shiftRows, + type StylePool +} from './screen.js' +import { stringWidth } from './stringWidth.js' +import { widestLine } from './widest-line.js' + +/** + * A grapheme cluster with precomputed terminal width, styleId, and hyperlink. + * Built once per unique line (cached via charCache), so the per-char hot loop + * is just property reads + setCellAt — no stringWidth, no style interning, + * no hyperlink extraction per frame. + * + * styleId is safe to cache: StylePool is session-lived (never reset). + * hyperlink is stored as a string (not interned ID) since hyperlinkPool + * resets every 5 min; setCellAt interns it per-frame (cheap Map.get). + */ +type ClusteredChar = { + value: string + width: number + styleId: number + hyperlink: string | undefined +} + +/** + * Collects write/blit/clear/clip operations from the render tree, then + * applies them to a Screen buffer in `get()`. The Screen is what gets + * diffed against the previous frame to produce terminal updates. + */ + +type Options = { + width: number + height: number + stylePool: StylePool + /** + * Screen to render into. Will be reset before use. + * For double-buffering, pass a reusable screen. Otherwise create a new one. + */ + screen: Screen +} + +export type Operation = + | WriteOperation + | ClipOperation + | UnclipOperation + | BlitOperation + | ClearOperation + | NoSelectOperation + | ShiftOperation + +type WriteOperation = { + type: 'write' + x: number + y: number + text: string + /** + * Per-line soft-wrap flags, parallel to text.split('\n'). softWrap[i]=true + * means line i is a continuation of line i-1 (the `\n` before it was + * inserted by word-wrap, not in the source). Index 0 is always false. + * Undefined means the producer didn't track wrapping (e.g. fills, + * raw-ansi) — the screen's per-row bitmap is left untouched. + */ + softWrap?: boolean[] +} + +type ClipOperation = { + type: 'clip' + clip: Clip +} + +export type Clip = { + x1: number | undefined + x2: number | undefined + y1: number | undefined + y2: number | undefined +} + +/** + * Intersect two clips. `undefined` on an axis means unbounded; the other + * clip's bound wins. If both are bounded, take the tighter constraint + * (max of mins, min of maxes). If the resulting region is empty + * (x1 >= x2 or y1 >= y2), writes clipped by it will be dropped. + */ +function intersectClip(parent: Clip | undefined, child: Clip): Clip { + if (!parent) { + return child + } + + return { + x1: maxDefined(parent.x1, child.x1), + x2: minDefined(parent.x2, child.x2), + y1: maxDefined(parent.y1, child.y1), + y2: minDefined(parent.y2, child.y2) + } +} + +function maxDefined(a: number | undefined, b: number | undefined): number | undefined { + if (a === undefined) { + return b + } + + if (b === undefined) { + return a + } + + return Math.max(a, b) +} + +function minDefined(a: number | undefined, b: number | undefined): number | undefined { + if (a === undefined) { + return b + } + + if (b === undefined) { + return a + } + + return Math.min(a, b) +} + +type UnclipOperation = { + type: 'unclip' +} + +type BlitOperation = { + type: 'blit' + src: Screen + x: number + y: number + width: number + height: number +} + +type ShiftOperation = { + type: 'shift' + top: number + bottom: number + n: number +} + +type ClearOperation = { + type: 'clear' + region: Rectangle + /** + * Set when the clear is for an absolute-positioned node's old bounds. + * Absolute nodes overlay normal-flow siblings, so their stale paint is + * what an earlier sibling's clean-subtree blit wrongly restores from + * prevScreen. Normal-flow siblings' clears don't have this problem — + * their old position can't have been painted on top of a sibling. + */ + fromAbsolute?: boolean +} + +type NoSelectOperation = { + type: 'noSelect' + region: Rectangle +} + +export default class Output { + width: number + height: number + private readonly stylePool: StylePool + private screen: Screen + + private readonly operations: Operation[] = [] + + private charCache: Map = new Map() + + constructor(options: Options) { + const { width, height, stylePool, screen } = options + + this.width = width + this.height = height + this.stylePool = stylePool + this.screen = screen + + resetScreen(screen, width, height) + } + + /** + * Reuse this Output for a new frame. Zeroes the screen buffer, clears + * the operation list (backing storage is retained), and caps charCache + * growth. Preserving charCache across frames is the main win — most + * lines don't change between renders, so tokenize + grapheme clustering + * becomes a cache hit. + */ + reset(width: number, height: number, screen: Screen): void { + this.width = width + this.height = height + this.screen = screen + this.operations.length = 0 + resetScreen(screen, width, height) + + if (this.charCache.size > 16384) { + this.charCache.clear() + } + } + + /** + * Copy cells from a source screen region (blit = block image transfer). + */ + blit(src: Screen, x: number, y: number, width: number, height: number): void { + this.operations.push({ type: 'blit', src, x, y, width, height }) + } + + /** + * Shift full-width rows within [top, bottom] by n. n > 0 = up. Mirrors + * what DECSTBM + SU/SD does to the terminal. Paired with blit() to reuse + * prevScreen content during pure scroll, avoiding full child re-render. + */ + shift(top: number, bottom: number, n: number): void { + this.operations.push({ type: 'shift', top, bottom, n }) + } + + /** + * Clear a region by writing empty cells. Used when a node shrinks to + * ensure stale content from the previous frame is removed. + */ + clear(region: Rectangle, fromAbsolute?: boolean): void { + this.operations.push({ type: 'clear', region, fromAbsolute }) + } + + /** + * Mark a region as non-selectable (excluded from fullscreen text + * selection copy + highlight). Used by to fence off + * gutters (line numbers, diff sigils). Applied AFTER blit/write so + * the mark wins regardless of what's blitted into the region. + */ + noSelect(region: Rectangle): void { + this.operations.push({ type: 'noSelect', region }) + } + + write(x: number, y: number, text: string, softWrap?: boolean[]): void { + if (!text) { + return + } + + this.operations.push({ + type: 'write', + x, + y, + text, + softWrap + }) + } + + clip(clip: Clip) { + this.operations.push({ + type: 'clip', + clip + }) + } + + unclip() { + this.operations.push({ + type: 'unclip' + }) + } + + get(): Screen { + const screen = this.screen + const screenWidth = this.width + const screenHeight = this.height + + // Track blit vs write cell counts for debugging + let blitCells = 0 + let writeCells = 0 + + // Pass 1: expand damage to cover clear regions. The buffer is freshly + // zeroed by resetScreen, so this pass only marks damage so diff() + // checks these regions against the previous frame. + // + // Also collect clears from absolute-positioned nodes. An absolute + // node overlays normal-flow siblings; when it shrinks, its clear is + // pushed AFTER those siblings' clean-subtree blits (DOM order). The + // blit copies the absolute node's own stale paint from prevScreen, + // and since clear is damage-only, the ghost survives diff. Normal- + // flow clears don't need this — a normal-flow node's old position + // can't have been painted on top of a sibling's current position. + const absoluteClears: Rectangle[] = [] + + for (const operation of this.operations) { + if (operation.type !== 'clear') { + continue + } + + const { x, y, width, height } = operation.region + const startX = Math.max(0, x) + const startY = Math.max(0, y) + const maxX = Math.min(x + width, screenWidth) + const maxY = Math.min(y + height, screenHeight) + + if (startX >= maxX || startY >= maxY) { + continue + } + + const rect = { + x: startX, + y: startY, + width: maxX - startX, + height: maxY - startY + } + + screen.damage = screen.damage ? unionRect(screen.damage, rect) : rect + + if (operation.fromAbsolute) { + absoluteClears.push(rect) + } + } + + const clips: Clip[] = [] + + for (const operation of this.operations) { + switch (operation.type) { + case 'clear': + // handled in pass 1 + continue + + case 'clip': + // Intersect with the parent clip (if any) so nested + // overflow:hidden boxes can't write outside their ancestor's + // clip region. Without this, a message with overflow:hidden at + // the bottom of a scrollbox pushes its OWN clip (based on its + // layout bounds, already translated by -scrollTop) which can + // extend below the scrollbox viewport — writes escape into + // the sibling bottom section's rows. + clips.push(intersectClip(clips.at(-1), operation.clip)) + + continue + + case 'unclip': + clips.pop() + + continue + case 'blit': { + // Bulk-copy cells from source screen region using TypedArray.set(). + // Tracking damage ensures diff() checks blitted cells for stale content + // when a parent blits an area that previously contained child content. + const { src, x: regionX, y: regionY, width: regionWidth, height: regionHeight } = operation + + // Intersect with active clip — a child's clean-blit passes its full + // cached rect, but the parent ScrollBox may have shrunk (pill mount). + // Without this, the blit writes past the ScrollBox's new bottom edge + // into the pill's row. + const clip = clips.at(-1) + const startX = Math.max(regionX, clip?.x1 ?? 0) + const startY = Math.max(regionY, clip?.y1 ?? 0) + + const maxY = Math.min(regionY + regionHeight, screenHeight, src.height, clip?.y2 ?? Infinity) + + const maxX = Math.min(regionX + regionWidth, screenWidth, src.width, clip?.x2 ?? Infinity) + + if (startX >= maxX || startY >= maxY) { + continue + } + + // Exclude cells covered by an absolute-positioned node's clear. + // Absolute nodes overlay normal-flow siblings, so prevScreen in + // that region holds stale overlay paint. If we blit those cells + // back, removed/moved overlays ghost as a duplicate. + if (absoluteClears.length === 0) { + blitRegion(screen, src, startX, startY, maxX, maxY) + blitCells += (maxY - startY) * (maxX - startX) + + continue + } + + for (let row = startY; row < maxY; row++) { + let spans: [number, number][] = [[startX, maxX]] + + for (const r of absoluteClears) { + if (row < r.y || row >= r.y + r.height || !spans.length) { + break + } + + const cs = Math.max(startX, r.x) + const ce = Math.min(maxX, r.x + r.width) + + if (cs >= ce) { + continue + } + + const next: [number, number][] = [] + + for (const [sx, ex] of spans) { + if (ce <= sx || cs >= ex) { + next.push([sx, ex]) + + continue + } + + if (sx < cs) { + next.push([sx, cs]) + } + + if (ce < ex) { + next.push([ce, ex]) + } + } + + spans = next + } + + for (const [sx, ex] of spans) { + blitRegion(screen, src, sx, row, ex, row + 1) + blitCells += ex - sx + } + } + + continue + } + + case 'shift': { + shiftRows(screen, operation.top, operation.bottom, operation.n) + + continue + } + + case 'write': { + const { text, softWrap } = operation + let { x, y } = operation + let lines = text.split('\n') + let swFrom = 0 + let prevContentEnd = 0 + + const clip = clips.at(-1) + + if (clip) { + const clipHorizontally = typeof clip?.x1 === 'number' && typeof clip?.x2 === 'number' + + const clipVertically = typeof clip?.y1 === 'number' && typeof clip?.y2 === 'number' + + // If text is positioned outside of clipping area altogether, + // skip to the next operation to avoid unnecessary calculations + if (clipHorizontally) { + const width = widestLine(text) + + if (x + width <= clip.x1! || x >= clip.x2!) { + continue + } + } + + if (clipVertically) { + const height = lines.length + + if (y + height <= clip.y1! || y >= clip.y2!) { + continue + } + } + + if (clipHorizontally) { + lines = lines.map(line => { + const from = x < clip.x1! ? clip.x1! - x : 0 + const width = stringWidth(line) + const to = x + width > clip.x2! ? clip.x2! - x : width + let sliced = sliceAnsi(line, from, to) + + // Wide chars (CJK, emoji) occupy 2 cells. When `to` lands + // on the first cell of a wide char, sliceAnsi includes the + // entire glyph and the result overflows clip.x2 by one cell, + // writing a SpacerTail into the adjacent sibling. Re-slice + // one cell earlier; wide chars are exactly 2 cells, so a + // single retry always fits. + if (stringWidth(sliced) > to - from) { + sliced = sliceAnsi(line, from, to - 1) + } + + return sliced + }) + + if (x < clip.x1!) { + x = clip.x1! + } + } + + if (clipVertically) { + const from = y < clip.y1! ? clip.y1! - y : 0 + const height = lines.length + const to = y + height > clip.y2! ? clip.y2! - y : height + + // If the first visible line is a soft-wrap continuation, we + // need the clipped previous line's content end so + // screen.softWrap[lineY] correctly records the join point + // even though that line's cells were never written. + if (softWrap && from > 0 && softWrap[from] === true) { + prevContentEnd = x + stringWidth(lines[from - 1]!) + } + + lines = lines.slice(from, to) + swFrom = from + + if (y < clip.y1!) { + y = clip.y1! + } + } + } + + const swBits = screen.softWrap + let offsetY = 0 + + for (const line of lines) { + const lineY = y + offsetY + + // Line can be outside screen if `text` is taller than screen height + if (lineY >= screenHeight) { + break + } + + const contentEnd = writeLineToScreen(screen, line, x, lineY, screenWidth, this.stylePool, this.charCache) + + writeCells += contentEnd - x + + // See Screen.softWrap docstring for the encoding. contentEnd + // from writeLineToScreen is tab-expansion-aware, unlike + // x+stringWidth(line) which treats tabs as width 0. + if (softWrap) { + const isSW = softWrap[swFrom + offsetY] === true + swBits[lineY] = isSW ? prevContentEnd : 0 + prevContentEnd = contentEnd + } + + offsetY++ + } + + continue + } + } + } + + // noSelect ops go LAST so they win over blits (which copy noSelect + // from prevScreen) and writes (which don't touch noSelect). This way + // a box correctly fences its region even when the parent + // blits, and moving a between frames correctly clears the + // old region (resetScreen already zeroed the bitmap). + for (const operation of this.operations) { + if (operation.type === 'noSelect') { + const { x, y, width, height } = operation.region + markNoSelectRegion(screen, x, y, width, height) + } + } + + // Log blit/write ratio for debugging - high write count suggests blitting isn't working + const totalCells = blitCells + writeCells + + if (totalCells > 1000 && writeCells > blitCells) { + logForDebugging( + `High write ratio: blit=${blitCells}, write=${writeCells} (${((writeCells / totalCells) * 100).toFixed(1)}% writes), screen=${screenHeight}x${screenWidth}` + ) + } + + return screen + } +} + +function stylesEqual(a: AnsiCode[], b: AnsiCode[]): boolean { + if (a === b) { + return true + } // Reference equality fast path + + const len = a.length + + if (len !== b.length) { + return false + } + + if (len === 0) { + return true + } // Both empty + + for (let i = 0; i < len; i++) { + if (a[i]!.code !== b[i]!.code) { + return false + } + } + + return true +} + +/** + * Convert a string with ANSI codes into styled characters with proper grapheme + * clustering. Fixes ansi-tokenize splitting grapheme clusters (like family + * emojis) into individual code points. + * + * Also precomputes styleId + hyperlink per style run (not per char) — an + * 80-char line with 3 style runs does 3 intern calls instead of 80. + */ +function styledCharsWithGraphemeClustering(chars: StyledChar[], stylePool: StylePool): ClusteredChar[] { + const charCount = chars.length + + if (charCount === 0) { + return [] + } + + const result: ClusteredChar[] = [] + const bufferChars: string[] = [] + let bufferStyles: AnsiCode[] = chars[0]!.styles + + for (let i = 0; i < charCount; i++) { + const char = chars[i]! + const styles = char.styles + + // Different styles means we need to flush and start new buffer + if (bufferChars.length > 0 && !stylesEqual(styles, bufferStyles)) { + flushBuffer(bufferChars.join(''), bufferStyles, stylePool, result) + bufferChars.length = 0 + } + + bufferChars.push(char.value) + bufferStyles = styles + } + + // Final flush + if (bufferChars.length > 0) { + flushBuffer(bufferChars.join(''), bufferStyles, stylePool, result) + } + + return result +} + +function flushBuffer(buffer: string, styles: AnsiCode[], stylePool: StylePool, out: ClusteredChar[]): void { + // Compute styleId + hyperlink ONCE for the whole style run. + // Every grapheme in this buffer shares the same styles. + // + // Extract and track hyperlinks separately, filter from styles. + // Always check for OSC 8 codes to filter, not just when a URL is + // extracted. The tokenizer treats OSC 8 close codes (empty URL) as + // active styles, so they must be filtered even when no hyperlink + // URL is present. + const hyperlink = extractHyperlinkFromStyles(styles) ?? undefined + + const hasOsc8Styles = + hyperlink !== undefined || styles.some(s => s.code.length >= OSC8_PREFIX.length && s.code.startsWith(OSC8_PREFIX)) + + const filteredStyles = hasOsc8Styles ? filterOutHyperlinkStyles(styles) : styles + + const styleId = stylePool.intern(filteredStyles) + + for (const { segment: grapheme } of getGraphemeSegmenter().segment(buffer)) { + out.push({ + value: grapheme, + width: stringWidth(grapheme), + styleId, + hyperlink + }) + } +} + +/** + * Write a single line's characters into the screen buffer. + * Extracted from Output.get() so JSC can optimize this tight, + * monomorphic loop independently — better register allocation, + * setCellAt inlining, and type feedback than when buried inside + * a 300-line dispatch function. + * + * Returns the end column (x + visual width, including tab expansion) so + * the caller can record it in screen.softWrap without re-walking the + * line via stringWidth(). Caller computes the debug cell-count as end-x. + */ +function writeLineToScreen( + screen: Screen, + line: string, + x: number, + y: number, + screenWidth: number, + stylePool: StylePool, + charCache: Map +): number { + let characters = charCache.get(line) + + if (!characters) { + characters = reorderBidi(styledCharsWithGraphemeClustering(styledCharsFromTokens(tokenize(line)), stylePool)) + charCache.set(line, characters) + } + + let offsetX = x + + for (let charIdx = 0; charIdx < characters.length; charIdx++) { + const character = characters[charIdx]! + const codePoint = character.value.codePointAt(0) + + // Handle C0 control characters (0x00-0x1F) that cause cursor movement + // mismatches. stringWidth treats these as width 0, but terminals may + // move the cursor differently. + if (codePoint !== undefined && codePoint <= 0x1f) { + // Tab (0x09): expand to spaces to reach next tab stop + if (codePoint === 0x09) { + const tabWidth = 8 + const spacesToNextStop = tabWidth - (offsetX % tabWidth) + + for (let i = 0; i < spacesToNextStop && offsetX < screenWidth; i++) { + setCellAt(screen, offsetX, y, { + char: ' ', + styleId: stylePool.none, + width: CellWidth.Narrow, + hyperlink: undefined + }) + offsetX++ + } + } + // ESC (0x1B): skip incomplete escape sequences that ansi-tokenize + // didn't recognize. ansi-tokenize only parses SGR sequences (ESC[...m) + // and OSC 8 hyperlinks (ESC]8;;url BEL). Other sequences like cursor + // movement, screen clearing, or terminal title become individual char + // tokens that we need to skip here. + else if (codePoint === 0x1b) { + const nextChar = characters[charIdx + 1]?.value + const nextCode = nextChar?.codePointAt(0) + + if (nextChar === '(' || nextChar === ')' || nextChar === '*' || nextChar === '+') { + // Charset selection: ESC ( X, ESC ) X, etc. + // Skip the intermediate char and the charset designator + charIdx += 2 + } else if (nextChar === '[') { + // CSI sequence: ESC [ ... final-byte + // Final byte is in range 0x40-0x7E (@, A-Z, [\]^_`, a-z, {|}~) + // Examples: ESC[2J (clear), ESC[?25l (cursor hide), ESC[H (home) + charIdx++ // skip the [ + + while (charIdx < characters.length - 1) { + charIdx++ + const c = characters[charIdx]?.value.codePointAt(0) + + // Final byte terminates the sequence + if (c !== undefined && c >= 0x40 && c <= 0x7e) { + break + } + } + } else if (nextChar === ']' || nextChar === 'P' || nextChar === '_' || nextChar === '^' || nextChar === 'X') { + // String-based sequences terminated by BEL (0x07) or ST (ESC \): + // - OSC: ESC ] ... (Operating System Command) + // - DCS: ESC P ... (Device Control String) + // - APC: ESC _ ... (Application Program Command) + // - PM: ESC ^ ... (Privacy Message) + // - SOS: ESC X ... (Start of String) + charIdx++ // skip the introducer char + + while (charIdx < characters.length - 1) { + charIdx++ + const c = characters[charIdx]?.value + + // BEL (0x07) terminates the sequence + if (c === '\x07') { + break + } + + // ST (String Terminator) is ESC \ + // When we see ESC, check if next char is backslash + if (c === '\x1b') { + const nextC = characters[charIdx + 1]?.value + + if (nextC === '\\') { + charIdx++ // skip the backslash too + + break + } + } + } + } else if (nextCode !== undefined && nextCode >= 0x30 && nextCode <= 0x7e) { + // Single-character escape sequences: ESC followed by 0x30-0x7E + // (excluding the multi-char introducers already handled above) + // - Fp range (0x30-0x3F): ESC 7 (save cursor), ESC 8 (restore) + // - Fe range (0x40-0x5F): ESC D (index), ESC M (reverse index) + // - Fs range (0x60-0x7E): ESC c (reset) + charIdx++ // skip the command char + } + } + + // Carriage return (0x0D): would move cursor to column 0, skip it + // Backspace (0x08): would move cursor left, skip it + // Bell (0x07), vertical tab (0x0B), form feed (0x0C): skip + // All other control chars (0x00-0x06, 0x0E-0x1F): skip + // Note: newline (0x0A) is already handled by line splitting + continue + } + + // Zero-width characters (combining marks, ZWNJ, ZWS, etc.) + // don't occupy terminal cells — storing them as Narrow cells + // desyncs the virtual cursor from the real terminal cursor. + // Width was computed once during clustering (cached via charCache). + const charWidth = character.width + + if (charWidth === 0) { + continue + } + + const isWideCharacter = charWidth >= 2 + + // Wide char at last column can't fit — terminal would wrap it to + // the next line, desyncing our cursor model. Place a SpacerHead + // to mark the blank column, matching terminal behavior. + if (isWideCharacter && offsetX + 2 > screenWidth) { + setCellAt(screen, offsetX, y, { + char: ' ', + styleId: stylePool.none, + width: CellWidth.SpacerHead, + hyperlink: undefined + }) + offsetX++ + + continue + } + + // styleId + hyperlink were precomputed during clustering (once per + // style run, cached via charCache). Hot loop is now just property + // reads — no intern, no extract, no filter per frame. + setCellAt(screen, offsetX, y, { + char: character.value, + styleId: character.styleId, + width: isWideCharacter ? CellWidth.Wide : CellWidth.Narrow, + hyperlink: character.hyperlink + }) + offsetX += isWideCharacter ? 2 : 1 + } + + return offsetX +} diff --git a/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts new file mode 100644 index 0000000000..ca77058d66 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/parse-keypress.ts @@ -0,0 +1,831 @@ +/** + * Keyboard input parser - converts terminal input to key events + * + * Uses the termio tokenizer for escape sequence boundary detection, + * then interprets sequences as keypresses. + */ +import { Buffer } from 'buffer' + +import { PASTE_END, PASTE_START } from './termio/csi.js' +import { createTokenizer, type Tokenizer } from './termio/tokenize.js' + +// eslint-disable-next-line no-control-regex +const META_KEY_CODE_RE = /^(?:\x1b)([a-zA-Z0-9])$/ + +const FN_KEY_RE = + // eslint-disable-next-line no-control-regex + /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/ + +// CSI u (kitty keyboard protocol): ESC [ codepoint [; modifier] u +// Example: ESC[13;2u = Shift+Enter, ESC[27u = Escape (no modifiers) +// Modifier is optional - when absent, defaults to 1 (no modifiers) +// eslint-disable-next-line no-control-regex +const CSI_U_RE = /^\x1b\[(\d+)(?:;(\d+))?u/ + +// xterm modifyOtherKeys: ESC [ 27 ; modifier ; keycode ~ +// Example: ESC[27;2;13~ = Shift+Enter. Emitted by Ghostty/tmux/xterm when +// modifyOtherKeys=2 is active or via user keybinds, typically over SSH where +// TERM sniffing misses Ghostty and we never push Kitty keyboard mode. +// Note param order is reversed vs CSI u (modifier first, keycode second). +// eslint-disable-next-line no-control-regex +const MODIFY_OTHER_KEYS_RE = /^\x1b\[27;(\d+);(\d+)~/ + +// -- Terminal response patterns (inbound sequences from the terminal itself) -- +// DECRPM: CSI ? Ps ; Pm $ y — response to DECRQM (request mode) +// eslint-disable-next-line no-control-regex +const DECRPM_RE = /^\x1b\[\?(\d+);(\d+)\$y$/ +// DA1: CSI ? Ps ; ... c — primary device attributes response +// eslint-disable-next-line no-control-regex +const DA1_RE = /^\x1b\[\?([\d;]*)c$/ +// DA2: CSI > Ps ; ... c — secondary device attributes response +// eslint-disable-next-line no-control-regex +const DA2_RE = /^\x1b\[>([\d;]*)c$/ +// Kitty keyboard flags: CSI ? flags u — response to CSI ? u query +// (private ? marker distinguishes from CSI u key events) +// eslint-disable-next-line no-control-regex +const KITTY_FLAGS_RE = /^\x1b\[\?(\d+)u$/ +// DECXCPR cursor position: CSI ? row ; col R +// The ? marker disambiguates from modified F3 keys (Shift+F3 = CSI 1;2 R, +// Ctrl+F3 = CSI 1;5 R, etc.) — plain CSI row;col R is genuinely ambiguous. +// eslint-disable-next-line no-control-regex +const CURSOR_POSITION_RE = /^\x1b\[\?(\d+);(\d+)R$/ +// OSC response: OSC code ; data (BEL|ST) +// eslint-disable-next-line no-control-regex +const OSC_RESPONSE_RE = /^\x1b\](\d+);(.*?)(?:\x07|\x1b\\)$/s +// XTVERSION: DCS > | name ST — terminal name/version string (answer to CSI > 0 q). +// xterm.js replies "xterm.js(X.Y.Z)"; Ghostty, kitty, iTerm2, etc. reply with +// their own name. Unlike TERM_PROGRAM, this survives SSH since the query/reply +// goes through the pty, not the environment. +// eslint-disable-next-line no-control-regex +const XTVERSION_RE = /^\x1bP>\|(.*?)(?:\x07|\x1b\\)$/s +// SGR mouse event: CSI < button ; col ; row M (press) or m (release) +// Button codes: 64=wheel-up, 65=wheel-down (0x40 | wheel-bit). +// Button 32=left-drag (0x20 | motion-bit). Plain 0/1/2 = left/mid/right click. +// eslint-disable-next-line no-control-regex +const SGR_MOUSE_RE = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/ + +function createPasteKey(content: string): ParsedKey { + return { + kind: 'key', + name: '', + fn: false, + ctrl: false, + meta: false, + shift: false, + option: false, + super: false, + sequence: content, + raw: content, + isPasted: true + } +} + +/** DECRPM status values (response to DECRQM) */ +export const DECRPM_STATUS = { + NOT_RECOGNIZED: 0, + SET: 1, + RESET: 2, + PERMANENTLY_SET: 3, + PERMANENTLY_RESET: 4 +} as const + +/** + * A response sequence received from the terminal (not a keypress). + * Emitted in answer to queries like DECRQM, DA1, OSC 11, etc. + */ +export type TerminalResponse = + /** DECRPM: answer to DECRQM (request DEC private mode status) */ + | { type: 'decrpm'; mode: number; status: number } + /** DA1: primary device attributes (used as a universal sentinel) */ + | { type: 'da1'; params: number[] } + /** DA2: secondary device attributes (terminal version info) */ + | { type: 'da2'; params: number[] } + /** Kitty keyboard protocol: current flags (answer to CSI ? u) */ + | { type: 'kittyKeyboard'; flags: number } + /** DSR: cursor position report (answer to CSI 6 n) */ + | { type: 'cursorPosition'; row: number; col: number } + /** OSC response: generic operating-system-command reply (e.g. OSC 11 bg color) */ + | { type: 'osc'; code: number; data: string } + /** XTVERSION: terminal name/version string (answer to CSI > 0 q). + * Example values: "xterm.js(5.5.0)", "ghostty 1.2.0", "iTerm2 3.6". */ + | { type: 'xtversion'; name: string } + +/** + * Try to recognize a sequence token as a terminal response. + * Returns null if the sequence is not a known response pattern + * (i.e. it should be treated as a keypress). + * + * These patterns are syntactically distinguishable from keyboard input — + * no physical key produces CSI ? ... c or CSI ? ... $ y, so they can be + * safely parsed out of the input stream at any time. + */ +function parseTerminalResponse(s: string): TerminalResponse | null { + // CSI-prefixed responses + if (s.startsWith('\x1b[')) { + let m: RegExpExecArray | null + + if ((m = DECRPM_RE.exec(s))) { + return { + type: 'decrpm', + mode: parseInt(m[1]!, 10), + status: parseInt(m[2]!, 10) + } + } + + if ((m = DA1_RE.exec(s))) { + return { type: 'da1', params: splitNumericParams(m[1]!) } + } + + if ((m = DA2_RE.exec(s))) { + return { type: 'da2', params: splitNumericParams(m[1]!) } + } + + if ((m = KITTY_FLAGS_RE.exec(s))) { + return { type: 'kittyKeyboard', flags: parseInt(m[1]!, 10) } + } + + if ((m = CURSOR_POSITION_RE.exec(s))) { + return { + type: 'cursorPosition', + row: parseInt(m[1]!, 10), + col: parseInt(m[2]!, 10) + } + } + + return null + } + + // OSC responses (e.g. OSC 11 ; rgb:... for bg color query) + if (s.startsWith('\x1b]')) { + const m = OSC_RESPONSE_RE.exec(s) + + if (m) { + return { type: 'osc', code: parseInt(m[1]!, 10), data: m[2]! } + } + } + + // DCS responses (e.g. XTVERSION: DCS > | name ST) + if (s.startsWith('\x1bP')) { + const m = XTVERSION_RE.exec(s) + + if (m) { + return { type: 'xtversion', name: m[1]! } + } + } + + return null +} + +function splitNumericParams(params: string): number[] { + if (!params) { + return [] + } + + return params.split(';').map(p => parseInt(p, 10)) +} + +export type KeyParseState = { + mode: 'NORMAL' | 'IN_PASTE' + incomplete: string + pasteBuffer: string + // Internal tokenizer instance + _tokenizer?: Tokenizer +} + +export const INITIAL_STATE: KeyParseState = { + mode: 'NORMAL', + incomplete: '', + pasteBuffer: '' +} + +function inputToString(input: Buffer | string): string { + if (Buffer.isBuffer(input)) { + if (input[0]! > 127 && input[1] === undefined) { + ;(input[0] as unknown as number) -= 128 + + return '\x1b' + String(input) + } else { + return String(input) + } + } else if (input !== undefined && typeof input !== 'string') { + return String(input) + } else if (!input) { + return '' + } else { + return input + } +} + +export function parseMultipleKeypresses( + prevState: KeyParseState, + input: Buffer | string | null = '' +): [ParsedInput[], KeyParseState] { + const isFlush = input === null + const inputString = isFlush ? '' : inputToString(input) + + // Get or create tokenizer + const tokenizer = prevState._tokenizer ?? createTokenizer({ x10Mouse: true }) + + // Tokenize the input + const tokens = isFlush ? tokenizer.flush() : tokenizer.feed(inputString) + + // Convert tokens to parsed keys, handling paste mode + const keys: ParsedInput[] = [] + let inPaste = prevState.mode === 'IN_PASTE' + let pasteBuffer = prevState.pasteBuffer + + for (const token of tokens) { + if (token.type === 'sequence') { + if (token.value === PASTE_START) { + inPaste = true + pasteBuffer = '' + } else if (token.value === PASTE_END) { + // Always emit a paste key, even for empty pastes. This allows + // downstream handlers to detect empty pastes (e.g., for clipboard + // image handling on macOS). The paste content may be empty string. + keys.push(createPasteKey(pasteBuffer)) + inPaste = false + pasteBuffer = '' + } else if (inPaste) { + // Sequences inside paste are treated as literal text + pasteBuffer += token.value + } else { + const response = parseTerminalResponse(token.value) + + if (response) { + keys.push({ kind: 'response', sequence: token.value, response }) + } else { + const mouse = parseMouseEvent(token.value) + + if (mouse) { + keys.push(mouse) + } else { + keys.push(parseKeypress(token.value)) + } + } + } + } else if (token.type === 'text') { + if (inPaste) { + pasteBuffer += token.value + } else if (/^\[<\d+;\d+;\d+[Mm]$/.test(token.value) || /^\[M[\x60-\x7f][\x20-\uffff]{2}$/.test(token.value)) { + // Orphaned SGR/X10 mouse tail (fullscreen only — mouse tracking is off + // otherwise). A heavy render blocked the event loop past App's 50ms + // flush timer, so the buffered ESC was flushed as a lone Escape and + // the continuation `[ = { + /* xterm/gnome ESC O letter */ + OP: 'f1', + OQ: 'f2', + OR: 'f3', + OS: 'f4', + /* Application keypad mode (numpad digits 0-9) */ + Op: '0', + Oq: '1', + Or: '2', + Os: '3', + Ot: '4', + Ou: '5', + Ov: '6', + Ow: '7', + Ox: '8', + Oy: '9', + /* Application keypad mode (numpad operators) */ + Oj: '*', + Ok: '+', + Ol: ',', + Om: '-', + On: '.', + Oo: '/', + OM: 'return', + /* xterm/rxvt ESC [ number ~ */ + '[11~': 'f1', + '[12~': 'f2', + '[13~': 'f3', + '[14~': 'f4', + /* from Cygwin and used in libuv */ + '[[A': 'f1', + '[[B': 'f2', + '[[C': 'f3', + '[[D': 'f4', + '[[E': 'f5', + /* common */ + '[15~': 'f5', + '[17~': 'f6', + '[18~': 'f7', + '[19~': 'f8', + '[20~': 'f9', + '[21~': 'f10', + '[23~': 'f11', + '[24~': 'f12', + /* xterm ESC [ letter */ + '[A': 'up', + '[B': 'down', + '[C': 'right', + '[D': 'left', + '[E': 'clear', + '[F': 'end', + '[H': 'home', + /* xterm/gnome ESC O letter */ + OA: 'up', + OB: 'down', + OC: 'right', + OD: 'left', + OE: 'clear', + OF: 'end', + OH: 'home', + /* xterm/rxvt ESC [ number ~ */ + '[1~': 'home', + '[2~': 'insert', + '[3~': 'delete', + '[4~': 'end', + '[5~': 'pageup', + '[6~': 'pagedown', + /* putty */ + '[[5~': 'pageup', + '[[6~': 'pagedown', + /* rxvt */ + '[7~': 'home', + '[8~': 'end', + /* rxvt keys with modifiers */ + '[a': 'up', + '[b': 'down', + '[c': 'right', + '[d': 'left', + '[e': 'clear', + + '[2$': 'insert', + '[3$': 'delete', + '[5$': 'pageup', + '[6$': 'pagedown', + '[7$': 'home', + '[8$': 'end', + + Oa: 'up', + Ob: 'down', + Oc: 'right', + Od: 'left', + Oe: 'clear', + + '[2^': 'insert', + '[3^': 'delete', + '[5^': 'pageup', + '[6^': 'pagedown', + '[7^': 'home', + '[8^': 'end', + /* misc. */ + '[Z': 'tab' +} + +export const nonAlphanumericKeys = [ + // Filter out single-character values (digits, operators from numpad) since + // those are printable characters that should produce input + ...Object.values(keyName).filter(v => v.length > 1), + // escape and backspace are assigned directly in parseKeypress (not via the + // keyName map), so the spread above misses them. Without these, ctrl+escape + // via Kitty/modifyOtherKeys leaks the literal word "escape" as input text + // (input-event.ts:58 assigns keypress.name when ctrl is set). + 'escape', + 'backspace', + 'wheelup', + 'wheeldown', + 'mouse' +] + +const isShiftKey = (code: string): boolean => { + return ['[a', '[b', '[c', '[d', '[e', '[2$', '[3$', '[5$', '[6$', '[7$', '[8$', '[Z'].includes(code) +} + +const isCtrlKey = (code: string): boolean => { + return ['Oa', 'Ob', 'Oc', 'Od', 'Oe', '[2^', '[3^', '[5^', '[6^', '[7^', '[8^'].includes(code) +} + +/** + * Decode XTerm-style modifier value to individual flags. + * Modifier encoding: 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0) + (super ? 8 : 0) + * + * Note: `meta` here means Alt/Option (bit 2). `super` is a distinct + * modifier (bit 8, i.e. Cmd on macOS / Win key). Most legacy terminal + * sequences can't express super — it only arrives via kitty keyboard + * protocol (CSI u) or xterm modifyOtherKeys. + */ +function decodeModifier(modifier: number): { + shift: boolean + meta: boolean + ctrl: boolean + super: boolean +} { + const m = modifier - 1 + + return { + shift: !!(m & 1), + meta: !!(m & 2), + ctrl: !!(m & 4), + super: !!(m & 8) + } +} + +/** + * Map keycode to key name for modifyOtherKeys/CSI u sequences. + * Handles both ASCII keycodes and Kitty keyboard protocol functional keys. + * + * Numpad codepoints are from Unicode Private Use Area, defined at: + * https://sw.kovidgoyal.net/kitty/keyboard-protocol/#functional-key-definitions + */ +function keycodeToName(keycode: number): string | undefined { + switch (keycode) { + case 9: + return 'tab' + + case 13: + return 'return' + + case 27: + return 'escape' + + case 32: + return 'space' + + case 127: + return 'backspace' + + // Kitty keyboard protocol numpad keys (KP_0 through KP_9) + case 57399: + return '0' + + case 57400: + return '1' + + case 57401: + return '2' + + case 57402: + return '3' + + case 57403: + return '4' + + case 57404: + return '5' + + case 57405: + return '6' + + case 57406: + return '7' + + case 57407: + return '8' + + case 57408: + return '9' + + case 57409: // KP_DECIMAL + return '.' + + case 57410: // KP_DIVIDE + return '/' + + case 57411: // KP_MULTIPLY + return '*' + + case 57412: // KP_SUBTRACT + return '-' + + case 57413: // KP_ADD + return '+' + + case 57414: // KP_ENTER + return 'return' + + case 57415: // KP_EQUAL + return '=' + + default: + // Printable ASCII characters + if (keycode >= 32 && keycode <= 126) { + return String.fromCharCode(keycode).toLowerCase() + } + + return undefined + } +} + +export type ParsedKey = { + kind: 'key' + fn: boolean + name: string | undefined + ctrl: boolean + meta: boolean + shift: boolean + option: boolean + super: boolean + sequence: string | undefined + raw: string | undefined + code?: string + isPasted: boolean +} + +/** A terminal response sequence (DECRPM, DA1, OSC reply, etc.) parsed + * out of the input stream. Not user input — consumers should dispatch + * to a response handler. */ +export type ParsedResponse = { + kind: 'response' + /** Raw escape sequence bytes, for debugging/logging */ + sequence: string + response: TerminalResponse +} + +/** SGR mouse event with coordinates. Emitted for clicks, drags, and + * releases (wheel events remain ParsedKey). col/row are 1-indexed + * from the terminal sequence (CSI < btn;col;row M/m). */ +export type ParsedMouse = { + kind: 'mouse' + /** Raw SGR button code. Low 2 bits = button (0=left,1=mid,2=right), + * bit 5 (0x20) = drag/motion, bit 6 (0x40) = wheel. */ + button: number + /** 'press' for M terminator, 'release' for m terminator */ + action: 'press' | 'release' + /** 1-indexed column (from terminal) */ + col: number + /** 1-indexed row (from terminal) */ + row: number + sequence: string +} + +/** Everything that can come out of the input parser: a user keypress/paste, + * a mouse click/drag event, or a terminal response to a query we sent. */ +export type ParsedInput = ParsedKey | ParsedMouse | ParsedResponse + +/** + * Parse an SGR mouse event sequence into a ParsedMouse, or null if not a + * mouse event or if it's a wheel event (wheel stays as ParsedKey for the + * keybinding system). Button bit 0x40 = wheel, bit 0x20 = drag/motion. + */ +function parseMouseEvent(s: string): ParsedMouse | null { + const match = SGR_MOUSE_RE.exec(s) + + if (!match) { + return null + } + + const button = parseInt(match[1]!, 10) + + // Wheel events (bit 6 set, low bits 0/1 for up/down) stay as ParsedKey + // so the keybinding system can route them to scroll handlers. + if ((button & 0x40) !== 0) { + return null + } + + return { + kind: 'mouse', + button, + action: match[4] === 'M' ? 'press' : 'release', + col: parseInt(match[2]!, 10), + row: parseInt(match[3]!, 10), + sequence: s + } +} + +function parseKeypress(s: string = ''): ParsedKey { + let parts + + const key: ParsedKey = { + kind: 'key', + name: '', + fn: false, + ctrl: false, + meta: false, + shift: false, + option: false, + super: false, + sequence: s, + raw: s, + isPasted: false + } + + key.sequence = key.sequence || s || key.name + + // Handle CSI u (kitty keyboard protocol): ESC [ codepoint [; modifier] u + // Example: ESC[13;2u = Shift+Enter, ESC[27u = Escape (no modifiers) + let match: RegExpExecArray | null + + if ((match = CSI_U_RE.exec(s))) { + const codepoint = parseInt(match[1]!, 10) + // Modifier defaults to 1 (no modifiers) when not present + const modifier = match[2] ? parseInt(match[2], 10) : 1 + const mods = decodeModifier(modifier) + const name = keycodeToName(codepoint) + + return { + kind: 'key', + name, + fn: false, + ctrl: mods.ctrl, + meta: mods.meta, + shift: mods.shift, + option: false, + super: mods.super, + sequence: s, + raw: s, + isPasted: false + } + } + + // Handle xterm modifyOtherKeys: ESC [ 27 ; modifier ; keycode ~ + // Must run before FN_KEY_RE — FN_KEY_RE only allows 2 params before ~ and + // would leave the tail as garbage if it partially matched. + if ((match = MODIFY_OTHER_KEYS_RE.exec(s))) { + const mods = decodeModifier(parseInt(match[1]!, 10)) + const name = keycodeToName(parseInt(match[2]!, 10)) + + return { + kind: 'key', + name, + fn: false, + ctrl: mods.ctrl, + meta: mods.meta, + shift: mods.shift, + option: false, + super: mods.super, + sequence: s, + raw: s, + isPasted: false + } + } + + // SGR mouse wheel events. Click/drag/release events are handled + // earlier by parseMouseEvent and emitted as ParsedMouse, so they + // never reach here. Mask with 0x43 (bits 6+1+0) to check wheel-flag + // + direction while ignoring modifier bits (Shift=0x04, Meta=0x08, + // Ctrl=0x10) — modified wheel events (e.g. Ctrl+scroll, button=80) + // should still be recognized as wheelup/wheeldown. + if ((match = SGR_MOUSE_RE.exec(s))) { + const button = parseInt(match[1]!, 10) + + if ((button & 0x43) === 0x40) { + return createNavKey(s, 'wheelup', false) + } + + if ((button & 0x43) === 0x41) { + return createNavKey(s, 'wheeldown', false) + } + + // Shouldn't reach here (parseMouseEvent catches non-wheel) but be safe + return createNavKey(s, 'mouse', false) + } + + // X10 mouse: CSI M + 3 raw bytes (Cb+32, Cx+32, Cy+32). Terminals that + // ignore DECSET 1006 (SGR) but honor 1000/1002 emit this legacy encoding. + // Button bits match SGR: 0x40 = wheel, low bit = direction. Non-wheel + // X10 events (clicks/drags) are swallowed here — we only enable mouse + // tracking in alt-screen and only need wheel for ScrollBox. + if (s.length === 6 && s.startsWith('\x1b[M')) { + const button = s.charCodeAt(3) - 32 + + if ((button & 0x43) === 0x40) { + return createNavKey(s, 'wheelup', false) + } + + if ((button & 0x43) === 0x41) { + return createNavKey(s, 'wheeldown', false) + } + + return createNavKey(s, 'mouse', false) + } + + if (s === '\r' || s === '\n') { + key.raw = undefined + key.name = 'return' + } else if (s === '\t') { + key.name = 'tab' + } else if (s === '\b' || s === '\x1b\b') { + key.name = 'backspace' + key.meta = s.charAt(0) === '\x1b' + } else if (s === '\x7f' || s === '\x1b\x7f') { + key.name = 'backspace' + key.meta = s.charAt(0) === '\x1b' + } else if (s === '\x1b' || s === '\x1b\x1b') { + key.name = 'escape' + key.meta = s.length === 2 + } else if (s === ' ' || s === '\x1b ') { + key.name = 'space' + key.meta = s.length === 2 + } else if (s === '\x1f') { + key.name = '_' + key.ctrl = true + } else if (s <= '\x1a' && s.length === 1) { + key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1) + key.ctrl = true + } else if (s.length === 1 && s >= '0' && s <= '9') { + key.name = 'number' + } else if (s.length === 1 && s >= 'a' && s <= 'z') { + key.name = s + } else if (s.length === 1 && s >= 'A' && s <= 'Z') { + key.name = s.toLowerCase() + key.shift = true + } else if ((parts = META_KEY_CODE_RE.exec(s))) { + key.meta = true + key.shift = /^[A-Z]$/.test(parts[1]!) + } else if ((parts = FN_KEY_RE.exec(s))) { + const segs = [...s] + + if (segs[0] === '\u001b' && segs[1] === '\u001b') { + key.option = true + } + + const code = [parts[1], parts[2], parts[4], parts[6]].filter(Boolean).join('') + + const modifier = ((parts[3] || parts[5] || 1) as number) - 1 + + key.ctrl = !!(modifier & 4) + key.meta = !!(modifier & 2) + key.super = !!(modifier & 8) + key.shift = !!(modifier & 1) + key.code = code + + key.name = keyName[code] + key.shift = isShiftKey(code) || key.shift + key.ctrl = isCtrlKey(code) || key.ctrl + } + + // iTerm in natural text editing mode + if (key.raw === '\x1Bb') { + key.meta = true + key.name = 'left' + } else if (key.raw === '\x1Bf') { + key.meta = true + key.name = 'right' + } + + switch (s) { + case '\u001b[1~': + return createNavKey(s, 'home', false) + + case '\u001b[4~': + return createNavKey(s, 'end', false) + + case '\u001b[5~': + return createNavKey(s, 'pageup', false) + + case '\u001b[6~': + return createNavKey(s, 'pagedown', false) + + case '\u001b[1;5D': + return createNavKey(s, 'left', true) + + case '\u001b[1;5C': + return createNavKey(s, 'right', true) + } + + return key +} + +function createNavKey(s: string, name: string, ctrl: boolean): ParsedKey { + return { + kind: 'key', + name, + ctrl, + meta: false, + shift: false, + option: false, + super: false, + fn: false, + sequence: s, + raw: s, + isPasted: false + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/reconciler.ts b/ui-tui/packages/hermes-ink/src/ink/reconciler.ts new file mode 100644 index 0000000000..5fdce3bf9c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/reconciler.ts @@ -0,0 +1,382 @@ +import createReconciler from 'react-reconciler' + +import { + appendChildNode, + clearYogaNodeReferences, + createNode, + createTextNode, + type DOMElement, + type DOMNodeAttribute, + type ElementNames, + insertBeforeNode, + markDirty, + removeChildNode, + setAttribute, + setStyle, + setTextNodeValue, + setTextStyles, + type TextNode +} from './dom.js' +import { Dispatcher } from './events/dispatcher.js' +import { EVENT_HANDLER_PROPS } from './events/event-handlers.js' +import { getFocusManager, getRootNode } from './focus.js' +import { LayoutDisplay } from './layout/node.js' +import applyStyles, { type Styles, type TextStyles } from './styles.js' + +// We need to conditionally perform devtools connection to avoid +// accidentally breaking other third-party code. +// See https://github.com/vadimdemedes/ink/issues/384 +if (process.env.NODE_ENV === 'development') { + try { + void import('./devtools.js') + } catch (error: any) { + if (error.code === 'ERR_MODULE_NOT_FOUND') { + // biome-ignore lint/suspicious/noConsole: intentional warning + console.warn( + ` +The environment variable DEV is set to true, so Ink tried to import \`react-devtools-core\`, +but this failed as it was not installed. Debugging with React Devtools requires it. + +To install use this command: + +$ npm install --save-dev react-devtools-core + `.trim() + '\n' + ) + } else { + throw error + } + } +} + +// -- + +type AnyObject = Record + +const diff = (before: AnyObject, after: AnyObject): AnyObject | undefined => { + if (before === after) { + return + } + + if (!before) { + return after + } + + const changed: AnyObject = {} + let isChanged = false + + for (const key of Object.keys(before)) { + const isDeleted = after ? !Object.hasOwn(after, key) : true + + if (isDeleted) { + changed[key] = undefined + isChanged = true + } + } + + if (after) { + for (const key of Object.keys(after)) { + if (after[key] !== before[key]) { + changed[key] = after[key] + isChanged = true + } + } + } + + return isChanged ? changed : undefined +} + +const cleanupYogaNode = (node: DOMElement | TextNode): void => { + const yogaNode = node.yogaNode + + if (yogaNode) { + yogaNode.unsetMeasureFunc() + // Clear all references BEFORE freeing to prevent other code from + // accessing freed WASM memory during concurrent operations + clearYogaNodeReferences(node) + yogaNode.freeRecursive() + } +} + +// -- + +type Props = Record + +type HostContext = { + isInsideText: boolean +} + +function setEventHandler(node: DOMElement, key: string, value: unknown): void { + if (!node._eventHandlers) { + node._eventHandlers = {} + } + + node._eventHandlers[key] = value +} + +function applyProp(node: DOMElement, key: string, value: unknown): void { + if (key === 'children') { + return + } + + if (key === 'style') { + setStyle(node, value as Styles) + + if (node.yogaNode) { + applyStyles(node.yogaNode, value as Styles) + } + + return + } + + if (key === 'textStyles') { + node.textStyles = value as TextStyles + + return + } + + if (EVENT_HANDLER_PROPS.has(key)) { + setEventHandler(node, key, value) + + return + } + + setAttribute(node, key, value as DOMNodeAttribute) +} + +// -- + +export const dispatcher = new Dispatcher() + +// --- SCROLL PROFILING (bench/scroll-e2e.sh reads via getLastYogaMs) --- +// Set by onComputeLayout wrapper in ink.tsx; read by onRender for phases. +let _lastYogaMs = 0 +let _lastCommitMs = 0 +let _commitStart = 0 + +export function recordYogaMs(ms: number): void { + _lastYogaMs = ms +} + +export function getLastYogaMs(): number { + return _lastYogaMs +} + +export function markCommitStart(): void { + _commitStart = performance.now() +} + +export function getLastCommitMs(): number { + return _lastCommitMs +} + +export function resetProfileCounters(): void { + _lastYogaMs = 0 + _lastCommitMs = 0 + _commitStart = 0 +} +// --- END --- + +const reconciler = createReconciler({ + getRootHostContext: () => ({ isInsideText: false }), + prepareForCommit: () => null, + preparePortalMount: () => null, + clearContainer: () => false, + resetAfterCommit(rootNode: DOMElement) { + _lastCommitMs = _commitStart > 0 ? performance.now() - _commitStart : 0 + _commitStart = 0 + + if (typeof rootNode.onComputeLayout === 'function') { + rootNode.onComputeLayout() + } + + if (process.env.NODE_ENV === 'test') { + if (rootNode.childNodes.length === 0 && rootNode.hasRenderedContent) { + return + } + + if (rootNode.childNodes.length > 0) { + rootNode.hasRenderedContent = true + } + + rootNode.onImmediateRender?.() + + return + } + + rootNode.onRender?.() + }, + getChildHostContext(parentHostContext: HostContext, type: ElementNames): HostContext { + const previousIsInsideText = parentHostContext.isInsideText + + const isInsideText = type === 'ink-text' || type === 'ink-virtual-text' || type === 'ink-link' + + if (previousIsInsideText === isInsideText) { + return parentHostContext + } + + return { isInsideText } + }, + shouldSetTextContent: () => false, + createInstance( + originalType: ElementNames, + newProps: Props, + _root: DOMElement, + hostContext: HostContext, + _internalHandle?: unknown + ): DOMElement { + if (hostContext.isInsideText && originalType === 'ink-box') { + throw new Error(` can't be nested inside component`) + } + + const type = originalType === 'ink-text' && hostContext.isInsideText ? 'ink-virtual-text' : originalType + + const node = createNode(type) + + for (const [key, value] of Object.entries(newProps)) { + applyProp(node, key, value) + } + + return node + }, + createTextInstance(text: string, _root: DOMElement, hostContext: HostContext): TextNode { + if (!hostContext.isInsideText) { + throw new Error(`Text string "${text}" must be rendered inside component`) + } + + return createTextNode(text) + }, + resetTextContent() {}, + hideTextInstance(node: TextNode) { + setTextNodeValue(node, '') + }, + unhideTextInstance(node: TextNode, text: string) { + setTextNodeValue(node, text) + }, + getPublicInstance: (instance: DOMElement): DOMElement => instance, + hideInstance(node: DOMElement) { + node.isHidden = true + node.yogaNode?.setDisplay(LayoutDisplay.None) + markDirty(node) + }, + unhideInstance(node: DOMElement) { + node.isHidden = false + node.yogaNode?.setDisplay(LayoutDisplay.Flex) + markDirty(node) + }, + appendInitialChild: appendChildNode, + appendChild: appendChildNode, + insertBefore: insertBeforeNode, + finalizeInitialChildren(_node: DOMElement, _type: ElementNames, props: Props): boolean { + return props['autoFocus'] === true + }, + commitMount(node: DOMElement): void { + getFocusManager(node).handleAutoFocus(node) + }, + isPrimaryRenderer: true, + supportsMutation: true, + supportsPersistence: false, + supportsHydration: false, + scheduleTimeout: setTimeout, + cancelTimeout: clearTimeout, + noTimeout: -1, + getCurrentUpdatePriority: () => dispatcher.currentUpdatePriority, + beforeActiveInstanceBlur() {}, + afterActiveInstanceBlur() {}, + detachDeletedInstance() {}, + getInstanceFromNode: () => null, + prepareScopeUpdate() {}, + getInstanceFromScope: () => null, + appendChildToContainer: appendChildNode, + insertInContainerBefore: insertBeforeNode, + removeChildFromContainer(node: DOMElement, removeNode: DOMElement): void { + removeChildNode(node, removeNode) + cleanupYogaNode(removeNode) + getFocusManager(node).handleNodeRemoved(removeNode, node) + }, + // React 19 commitUpdate receives old and new props directly instead of an updatePayload + commitUpdate(node: DOMElement, _type: ElementNames, oldProps: Props, newProps: Props): void { + const props = diff(oldProps, newProps) + const style = diff(oldProps['style'] as Styles, newProps['style'] as Styles) + + if (props) { + for (const [key, value] of Object.entries(props)) { + if (key === 'style') { + setStyle(node, value as Styles) + + continue + } + + if (key === 'textStyles') { + setTextStyles(node, value as TextStyles) + + continue + } + + if (EVENT_HANDLER_PROPS.has(key)) { + setEventHandler(node, key, value) + + continue + } + + setAttribute(node, key, value as DOMNodeAttribute) + } + } + + if (style && node.yogaNode) { + applyStyles(node.yogaNode, style, newProps['style'] as Styles) + } + }, + commitTextUpdate(node: TextNode, _oldText: string, newText: string): void { + setTextNodeValue(node, newText) + }, + removeChild(node: DOMElement, removeNode: DOMElement | TextNode) { + removeChildNode(node, removeNode) + cleanupYogaNode(removeNode) + + if (removeNode.nodeName !== '#text') { + const root = getRootNode(node) + root.focusManager!.handleNodeRemoved(removeNode, root) + } + }, + // React 19 required methods + maySuspendCommit(): boolean { + return false + }, + preloadInstance(): boolean { + return true + }, + startSuspendingCommit(): void {}, + suspendInstance(): void {}, + waitForCommitToBeReady(): null { + return null + }, + NotPendingTransition: null, + HostTransitionContext: { + $$typeof: Symbol.for('react.context'), + _currentValue: null + } as never, + setCurrentUpdatePriority(newPriority: number): void { + dispatcher.currentUpdatePriority = newPriority + }, + resolveUpdatePriority(): number { + return dispatcher.resolveEventPriority() + }, + resetFormInstance(): void {}, + requestPostPaintCallback(): void {}, + shouldAttemptEagerTransition(): boolean { + return false + }, + trackSchedulerEvent(): void {}, + resolveEventType(): string | null { + return dispatcher.currentEvent?.type ?? null + }, + resolveEventTimeStamp(): number { + return dispatcher.currentEvent?.timeStamp ?? -1.1 + } +}) + +// Wire the reconciler's discreteUpdates into the dispatcher. +// This breaks the import cycle: dispatcher.ts doesn't import reconciler.ts. +dispatcher.discreteUpdates = reconciler.discreteUpdates.bind(reconciler) + +export default reconciler diff --git a/ui-tui/packages/hermes-ink/src/ink/render-border.ts b/ui-tui/packages/hermes-ink/src/ink/render-border.ts new file mode 100644 index 0000000000..a4fff7cb50 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/render-border.ts @@ -0,0 +1,206 @@ +import chalk from 'chalk' +import cliBoxes, { type Boxes, type BoxStyle } from 'cli-boxes' + +import { applyColor } from './colorize.js' +import type { DOMNode } from './dom.js' +import type Output from './output.js' +import { stringWidth } from './stringWidth.js' +import type { Color } from './styles.js' + +export type BorderTextOptions = { + content: string // Pre-rendered string with ANSI color codes + position: 'top' | 'bottom' + align: 'start' | 'end' | 'center' + offset?: number // Only used with 'start' or 'end' alignment. Number of characters from the edge. +} + +export const CUSTOM_BORDER_STYLES = { + dashed: { + top: '╌', + left: '╎', + right: '╎', + bottom: '╌', + // there aren't any line-drawing characters for dashes unfortunately + topLeft: ' ', + topRight: ' ', + bottomLeft: ' ', + bottomRight: ' ' + } +} as const + +export type BorderStyle = keyof Boxes | keyof typeof CUSTOM_BORDER_STYLES | BoxStyle + +function embedTextInBorder( + borderLine: string, + text: string, + align: 'start' | 'end' | 'center', + offset: number = 0, + borderChar: string +): [before: string, text: string, after: string] { + const textLength = stringWidth(text) + const borderLength = borderLine.length + + if (textLength >= borderLength - 2) { + return ['', text.substring(0, borderLength), ''] + } + + let position: number + + if (align === 'center') { + position = Math.floor((borderLength - textLength) / 2) + } else if (align === 'start') { + position = offset + 1 // +1 to account for corner character + } else { + // align === 'end' + position = borderLength - textLength - offset - 1 // -1 for corner character + } + + // Ensure position is valid + position = Math.max(1, Math.min(position, borderLength - textLength - 1)) + + const before = borderLine.substring(0, 1) + borderChar.repeat(position - 1) + + const after = borderChar.repeat(borderLength - position - textLength - 1) + borderLine.substring(borderLength - 1) + + return [before, text, after] +} + +function styleBorderLine(line: string, color: Color | undefined, dim: boolean | undefined): string { + let styled = applyColor(line, color) + + if (dim) { + styled = chalk.dim(styled) + } + + return styled +} + +const renderBorder = (x: number, y: number, node: DOMNode, output: Output): void => { + if (node.style.borderStyle) { + const width = Math.floor(node.yogaNode!.getComputedWidth()) + const height = Math.floor(node.yogaNode!.getComputedHeight()) + + const box = + typeof node.style.borderStyle === 'string' + ? (CUSTOM_BORDER_STYLES[node.style.borderStyle as keyof typeof CUSTOM_BORDER_STYLES] ?? + cliBoxes[node.style.borderStyle as keyof Boxes]) + : node.style.borderStyle + + const topBorderColor = node.style.borderTopColor ?? node.style.borderColor + + const bottomBorderColor = node.style.borderBottomColor ?? node.style.borderColor + + const leftBorderColor = node.style.borderLeftColor ?? node.style.borderColor + + const rightBorderColor = node.style.borderRightColor ?? node.style.borderColor + + const dimTopBorderColor = node.style.borderTopDimColor ?? node.style.borderDimColor + + const dimBottomBorderColor = node.style.borderBottomDimColor ?? node.style.borderDimColor + + const dimLeftBorderColor = node.style.borderLeftDimColor ?? node.style.borderDimColor + + const dimRightBorderColor = node.style.borderRightDimColor ?? node.style.borderDimColor + + const showTopBorder = node.style.borderTop !== false + const showBottomBorder = node.style.borderBottom !== false + const showLeftBorder = node.style.borderLeft !== false + const showRightBorder = node.style.borderRight !== false + + const contentWidth = Math.max(0, width - (showLeftBorder ? 1 : 0) - (showRightBorder ? 1 : 0)) + + const topBorderLine = showTopBorder + ? (showLeftBorder ? box.topLeft : '') + box.top.repeat(contentWidth) + (showRightBorder ? box.topRight : '') + : '' + + // Handle text in top border + let topBorder: string | undefined + + if (showTopBorder && node.style.borderText?.position === 'top') { + const [before, text, after] = embedTextInBorder( + topBorderLine, + node.style.borderText.content, + node.style.borderText.align, + node.style.borderText.offset, + box.top + ) + + topBorder = + styleBorderLine(before, topBorderColor, dimTopBorderColor) + + text + + styleBorderLine(after, topBorderColor, dimTopBorderColor) + } else if (showTopBorder) { + topBorder = styleBorderLine(topBorderLine, topBorderColor, dimTopBorderColor) + } + + let verticalBorderHeight = height + + if (showTopBorder) { + verticalBorderHeight -= 1 + } + + if (showBottomBorder) { + verticalBorderHeight -= 1 + } + + verticalBorderHeight = Math.max(0, verticalBorderHeight) + + let leftBorder = (applyColor(box.left, leftBorderColor) + '\n').repeat(verticalBorderHeight) + + if (dimLeftBorderColor) { + leftBorder = chalk.dim(leftBorder) + } + + let rightBorder = (applyColor(box.right, rightBorderColor) + '\n').repeat(verticalBorderHeight) + + if (dimRightBorderColor) { + rightBorder = chalk.dim(rightBorder) + } + + const bottomBorderLine = showBottomBorder + ? (showLeftBorder ? box.bottomLeft : '') + + box.bottom.repeat(contentWidth) + + (showRightBorder ? box.bottomRight : '') + : '' + + // Handle text in bottom border + let bottomBorder: string | undefined + + if (showBottomBorder && node.style.borderText?.position === 'bottom') { + const [before, text, after] = embedTextInBorder( + bottomBorderLine, + node.style.borderText.content, + node.style.borderText.align, + node.style.borderText.offset, + box.bottom + ) + + bottomBorder = + styleBorderLine(before, bottomBorderColor, dimBottomBorderColor) + + text + + styleBorderLine(after, bottomBorderColor, dimBottomBorderColor) + } else if (showBottomBorder) { + bottomBorder = styleBorderLine(bottomBorderLine, bottomBorderColor, dimBottomBorderColor) + } + + const offsetY = showTopBorder ? 1 : 0 + + if (topBorder) { + output.write(x, y, topBorder) + } + + if (showLeftBorder) { + output.write(x, y + offsetY, leftBorder) + } + + if (showRightBorder) { + output.write(x + width - 1, y + offsetY, rightBorder) + } + + if (bottomBorder) { + output.write(x, y + height - 1, bottomBorder) + } + } +} + +export default renderBorder diff --git a/ui-tui/packages/hermes-ink/src/ink/render-node-to-output.ts b/ui-tui/packages/hermes-ink/src/ink/render-node-to-output.ts new file mode 100644 index 0000000000..5c9e62b468 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/render-node-to-output.ts @@ -0,0 +1,1536 @@ +import indentString from 'indent-string' + +import { applyTextStyles } from './colorize.js' +import type { DOMElement } from './dom.js' +import getMaxWidth from './get-max-width.js' +import type { Rectangle } from './layout/geometry.js' +import { LayoutDisplay, LayoutEdge, type LayoutNode } from './layout/node.js' +import { nodeCache, pendingClears } from './node-cache.js' +import type Output from './output.js' +import renderBorder from './render-border.js' +import type { Screen } from './screen.js' +import { squashTextNodesToSegments, type StyledSegment } from './squash-text-nodes.js' +import type { Color } from './styles.js' +import { isXtermJs } from './terminal.js' +import { widestLine } from './widest-line.js' +import wrapText from './wrap-text.js' + +// Matches detectXtermJsWheel() in ScrollKeybindingHandler.tsx — the curve +// and drain must agree on terminal detection. TERM_PROGRAM check is the sync +// fallback; isXtermJs() is the authoritative XTVERSION-probe result. +function isXtermJsHost(): boolean { + return process.env.TERM_PROGRAM === 'vscode' || isXtermJs() +} + +// Per-frame scratch: set when any node's yoga position/size differs from +// its cached value, or a child was removed. Read by ink.tsx to decide +// whether the full-damage sledgehammer (PR #20120) is needed this frame. +// Applies on both alt-screen and main-screen. Steady-state frames +// (spinner tick, clock tick, text append into a fixed-height box) don't +// shift layout → narrow damage bounds → O(changed cells) diff instead of +// O(rows×cols). +let layoutShifted = false +let absoluteOverlayMoved = false + +export function resetLayoutShifted(): void { + layoutShifted = false + absoluteOverlayMoved = false +} + +export function didLayoutShift(): boolean { + return layoutShifted +} + +export function didAbsoluteOverlayMove(): boolean { + return absoluteOverlayMoved +} + +// DECSTBM scroll optimization hint. When a ScrollBox's scrollTop changes +// between frames (and nothing else moved), log-update.ts can emit a +// hardware scroll (DECSTBM + SU/SD) instead of rewriting the whole +// viewport. top/bottom are 0-indexed inclusive screen rows; delta > 0 = +// content moved up (scrollTop increased, CSI n S). +export type ScrollHint = { top: number; bottom: number; delta: number } +let scrollHint: ScrollHint | null = null + +// Rects of position:absolute nodes from the PREVIOUS frame, used by +// ScrollBox's blit+shift third-pass repair (see usage site). Recorded at +// three paths — full-render nodeCache.set, node-level blit early-return, +// blitEscapingAbsoluteDescendants — so clean-overlay consecutive scrolls +// still have the rect. +let absoluteRectsPrev: Rectangle[] = [] +let absoluteRectsCur: Rectangle[] = [] + +export function resetScrollHint(): void { + scrollHint = null + absoluteRectsPrev = absoluteRectsCur + absoluteRectsCur = [] +} + +export function getScrollHint(): ScrollHint | null { + return scrollHint +} + +// The ScrollBox DOM node (if any) with pendingScrollDelta left after this +// frame's drain. renderer.ts calls markDirty(it) post-render so the NEXT +// frame's root blit check fails and we descend to continue draining. +// Without this, after the scrollbox's dirty flag is cleared (line ~721), +// the next frame blits root and never reaches the scrollbox — drain stalls. +let scrollDrainNode: DOMElement | null = null + +export function resetScrollDrainNode(): void { + scrollDrainNode = null +} + +export function getScrollDrainNode(): DOMElement | null { + return scrollDrainNode +} + +// At-bottom follow scroll event this frame. When streaming content +// triggers scrollTop = maxScroll, the ScrollBox records the delta + +// viewport bounds here. ink.tsx consumes it post-render to translate any active +// text selection by -delta so the highlight stays anchored to the TEXT +// (native terminal behavior — the selection walks up the screen as content +// scrolls, eventually clipping at the top). The frontFrame screen buffer +// still holds the old content at that point — captureScrolledRows reads +// from it before the front/back swap to preserve the text for copy. +export type FollowScroll = { + delta: number + viewportTop: number + viewportBottom: number +} +let followScroll: FollowScroll | null = null + +export function consumeFollowScroll(): FollowScroll | null { + const f = followScroll + followScroll = null + + return f +} + +// ── Native terminal drain (iTerm2/Ghostty/etc. — proportional events) ── +// Minimum rows applied per frame. Above this, drain is proportional (~3/4 +// of remaining) so big bursts catch up in log₄ frames while the tail +// decelerates smoothly. Hard cap is innerHeight-1 so DECSTBM hint fires. +const SCROLL_MIN_PER_FRAME = 4 + +// ── xterm.js (VS Code) smooth drain ── +// Low pending (≤5) drains ALL in one frame — slow wheel clicks should be +// instant (click → visible jump → done), not micro-stutter 1-row frames. +// Higher pending drains at a small fixed step so fast-scroll animation +// stays smooth (no big jumps). Pending >MAX snaps excess. +const SCROLL_INSTANT_THRESHOLD = 5 // ≤ this: drain all at once +const SCROLL_HIGH_PENDING = 12 // threshold for HIGH step +const SCROLL_STEP_MED = 2 // pending (INSTANT, HIGH): catch-up +const SCROLL_STEP_HIGH = 3 // pending ≥ HIGH: fast flick +const SCROLL_MAX_PENDING = 30 // snap excess beyond this + +// xterm.js adaptive drain. Returns rows applied; mutates pendingScrollDelta. +function drainAdaptive(node: DOMElement, pending: number, innerHeight: number): number { + const sign = pending > 0 ? 1 : -1 + let abs = Math.abs(pending) + let applied = 0 + + // Snap excess beyond animation window so big flicks don't coast. + if (abs > SCROLL_MAX_PENDING) { + applied += sign * (abs - SCROLL_MAX_PENDING) + abs = SCROLL_MAX_PENDING + } + + // ≤5: drain all (slow click = instant). Above: small fixed step. + const step = abs <= SCROLL_INSTANT_THRESHOLD ? abs : abs < SCROLL_HIGH_PENDING ? SCROLL_STEP_MED : SCROLL_STEP_HIGH + + applied += sign * step + const rem = abs - step + // Cap total at innerHeight-1 so DECSTBM blit+shift fast path fires + // (matches drainProportional). Excess stays in pendingScrollDelta. + const cap = Math.max(1, innerHeight - 1) + const totalAbs = Math.abs(applied) + + if (totalAbs > cap) { + const excess = totalAbs - cap + node.pendingScrollDelta = sign * (rem + excess) + + return sign * cap + } + + node.pendingScrollDelta = rem > 0 ? sign * rem : undefined + + return applied +} + +// Native proportional drain. step = max(MIN, floor(abs*3/4)), capped at +// innerHeight-1 so DECSTBM + blit+shift fast path fire. +function drainProportional(node: DOMElement, pending: number, innerHeight: number): number { + const abs = Math.abs(pending) + const cap = Math.max(1, innerHeight - 1) + const step = Math.min(cap, Math.max(SCROLL_MIN_PER_FRAME, (abs * 3) >> 2)) + + if (abs <= step) { + node.pendingScrollDelta = undefined + + return pending + } + + const applied = pending > 0 ? step : -step + node.pendingScrollDelta = pending - applied + + return applied +} + +// OSC 8 hyperlink escape sequences. Empty params (;;) — ansi-tokenize only +// recognizes this exact prefix. The id= param (for grouping wrapped lines) +// is added at terminal-output time in termio/osc.ts link(). +const OSC = '\u001B]' +const BEL = '\u0007' + +function wrapWithOsc8Link(text: string, url: string): string { + return `${OSC}8;;${url}${BEL}${text}${OSC}8;;${BEL}` +} + +/** + * Build a mapping from each character position in the plain text to its segment index. + * Returns an array where charToSegment[i] is the segment index for character i. + */ +function buildCharToSegmentMap(segments: StyledSegment[]): number[] { + const map: number[] = [] + + for (let i = 0; i < segments.length; i++) { + const len = segments[i]!.text.length + + for (let j = 0; j < len; j++) { + map.push(i) + } + } + + return map +} + +/** + * Apply styles to wrapped text by mapping each character back to its original segment. + * This preserves per-segment styles even when text wraps across lines. + * + * @param trimEnabled - Whether whitespace trimming is enabled (wrap-trim mode). + * When true, we skip whitespace in the original that was trimmed from the output. + * When false (wrap mode), all whitespace is preserved so no skipping is needed. + */ +function applyStylesToWrappedText( + wrappedPlain: string, + segments: StyledSegment[], + charToSegment: number[], + originalPlain: string, + trimEnabled: boolean = false +): string { + const lines = wrappedPlain.split('\n') + const resultLines: string[] = [] + + let charIndex = 0 + + for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) { + const line = lines[lineIdx]! + + // In trim mode, skip leading whitespace that was trimmed from this line. + // Only skip if the original has whitespace but the output line doesn't start + // with whitespace (meaning it was trimmed). If both have whitespace, the + // whitespace was preserved and we shouldn't skip. + if (trimEnabled && line.length > 0) { + const lineStartsWithWhitespace = /\s/.test(line[0]!) + + const originalHasWhitespace = charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex]!) + + // Only skip if original has whitespace but line doesn't + if (originalHasWhitespace && !lineStartsWithWhitespace) { + while (charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex]!)) { + charIndex++ + } + } + } + + let styledLine = '' + let runStart = 0 + let runSegmentIndex = charToSegment[charIndex] ?? 0 + + for (let i = 0; i < line.length; i++) { + const currentSegmentIndex = charToSegment[charIndex] ?? runSegmentIndex + + if (currentSegmentIndex !== runSegmentIndex) { + // Flush the current run + const runText = line.slice(runStart, i) + const segment = segments[runSegmentIndex] + + if (segment) { + let styled = applyTextStyles(runText, segment.styles) + + if (segment.hyperlink) { + styled = wrapWithOsc8Link(styled, segment.hyperlink) + } + + styledLine += styled + } else { + styledLine += runText + } + + runStart = i + runSegmentIndex = currentSegmentIndex + } + + charIndex++ + } + + // Flush the final run + const runText = line.slice(runStart) + const segment = segments[runSegmentIndex] + + if (segment) { + let styled = applyTextStyles(runText, segment.styles) + + if (segment.hyperlink) { + styled = wrapWithOsc8Link(styled, segment.hyperlink) + } + + styledLine += styled + } else { + styledLine += runText + } + + resultLines.push(styledLine) + + // Skip newline character in original that corresponds to this line break. + // This is needed when the original text contains actual newlines (not just + // wrapping-inserted newlines). Without this, charIndex gets out of sync + // because the newline is in originalPlain/charToSegment but not in the + // split lines. + if (charIndex < originalPlain.length && originalPlain[charIndex] === '\n') { + charIndex++ + } + + // In trim mode, skip whitespace that was replaced by newline when wrapping. + // We skip whitespace in the original until we reach a character that matches + // the first character of the next line. This handles cases like: + // - "AB \tD" wrapped to "AB\n\tD" - skip spaces until we hit the tab + // In non-trim mode, whitespace is preserved so no skipping is needed. + if (trimEnabled && lineIdx < lines.length - 1) { + const nextLine = lines[lineIdx + 1]! + const nextLineFirstChar = nextLine.length > 0 ? nextLine[0] : null + + // Skip whitespace until we hit a char that matches the next line's first char + while (charIndex < originalPlain.length && /\s/.test(originalPlain[charIndex]!)) { + // Stop if we found the character that starts the next line + if (nextLineFirstChar !== null && originalPlain[charIndex] === nextLineFirstChar) { + break + } + + charIndex++ + } + } + } + + return resultLines.join('\n') +} + +/** + * Wrap text and record which output lines are soft-wrap continuations + * (i.e. the `\n` before them was inserted by word-wrap, not in the + * source). wrapAnsi already processes each input line independently, so + * wrapping per-input-line here gives identical output to a single + * whole-string wrap while letting us mark per-piece provenance. + * Truncate modes never add newlines (cli-truncate is whole-string) so + * they fall through with softWrap undefined — no tracking, no behavior + * change from the pre-softWrap path. + */ +function wrapWithSoftWrap( + plainText: string, + maxWidth: number, + textWrap: Parameters[2] +): { wrapped: string; softWrap: boolean[] | undefined } { + if (textWrap !== 'wrap' && textWrap !== 'wrap-trim') { + return { + wrapped: wrapText(plainText, maxWidth, textWrap), + softWrap: undefined + } + } + + const origLines = plainText.split('\n') + const outLines: string[] = [] + const softWrap: boolean[] = [] + + for (const orig of origLines) { + const pieces = wrapText(orig, maxWidth, textWrap).split('\n') + + for (let i = 0; i < pieces.length; i++) { + outLines.push(pieces[i]!) + softWrap.push(i > 0) + } + } + + return { wrapped: outLines.join('\n'), softWrap } +} + +// If parent container is ``, text nodes will be treated as separate nodes in +// the tree and will have their own coordinates in the layout. +// To ensure text nodes are aligned correctly, take X and Y of the first text node +// and use it as offset for the rest of the nodes +// Only first node is taken into account, because other text nodes can't have margin or padding, +// so their coordinates will be relative to the first node anyway +function applyPaddingToText(node: DOMElement, text: string, softWrap?: boolean[]): string { + const yogaNode = node.childNodes[0]?.yogaNode + + if (yogaNode) { + const offsetX = yogaNode.getComputedLeft() + const offsetY = yogaNode.getComputedTop() + text = '\n'.repeat(offsetY) + indentString(text, offsetX) + + if (softWrap && offsetY > 0) { + // Prepend `false` for each padding line so indices stay aligned + // with text.split('\n'). Mutate in place — caller owns the array. + softWrap.unshift(...Array(offsetY).fill(false)) + } + } + + return text +} + +// After nodes are laid out, render each to output object, which later gets rendered to terminal +function renderNodeToOutput( + node: DOMElement, + output: Output, + { + offsetX = 0, + offsetY = 0, + prevScreen, + skipSelfBlit = false, + inheritedBackgroundColor + }: { + offsetX?: number + offsetY?: number + prevScreen: Screen | undefined + // Force this node to descend instead of blitting its own rect, while + // still passing prevScreen to children. Used for non-opaque absolute + // overlays over a dirty clipped region: the overlay's full rect has + // transparent gaps (stale underlying content in prevScreen), but its + // opaque descendants' narrower rects are safe to blit. + skipSelfBlit?: boolean + inheritedBackgroundColor?: Color + } +): void { + const { yogaNode } = node + + if (yogaNode) { + if (yogaNode.getDisplay() === LayoutDisplay.None) { + // Clear old position if node was visible before becoming hidden + if (node.dirty) { + const cached = nodeCache.get(node) + + if (cached) { + output.clear({ + x: Math.floor(cached.x), + y: Math.floor(cached.y), + width: Math.floor(cached.width), + height: Math.floor(cached.height) + }) + // Drop descendants' cache too — hideInstance's markDirty walks UP + // only, so descendants' .dirty stays false. Their nodeCache entries + // survive with pre-hide rects. On unhide, if position didn't shift, + // the blit check at line ~432 passes and copies EMPTY cells from + // prevScreen (cleared here) → content vanishes. + dropSubtreeCache(node) + layoutShifted = true + } + } + + return + } + + // Left and top positions in Yoga are relative to their parent node + const x = offsetX + yogaNode.getComputedLeft() + const yogaTop = yogaNode.getComputedTop() + let y = offsetY + yogaTop + const width = yogaNode.getComputedWidth() + const height = yogaNode.getComputedHeight() + + // Absolute-positioned overlays (e.g. autocomplete menus with bottom='100%') + // can compute negative screen y when they extend above the viewport. Without + // clamping, setCellAt drops cells at y<0, clipping the TOP of the content + // (best matches in an autocomplete). By clamping to 0, we shift the element + // down so the top rows are visible and the bottom overflows below — the + // opaque prop ensures it paints over whatever is underneath. + if (y < 0 && node.style.position === 'absolute') { + y = 0 + } + + // Check if we can skip this subtree (clean node with unchanged layout). + // Blit cells from previous screen instead of re-rendering. + const cached = nodeCache.get(node) + + if ( + !node.dirty && + !skipSelfBlit && + node.pendingScrollDelta === undefined && + cached && + cached.x === x && + cached.y === y && + cached.width === width && + cached.height === height && + prevScreen + ) { + const fx = Math.floor(x) + const fy = Math.floor(y) + const fw = Math.floor(width) + const fh = Math.floor(height) + output.blit(prevScreen, fx, fy, fw, fh) + + if (node.style.position === 'absolute') { + absoluteRectsCur.push(cached) + } + + // Absolute descendants can paint outside this node's layout bounds + // (e.g. a slash menu with position='absolute' bottom='100%' floats + // above). If a dirty clipped sibling re-rendered and overwrote those + // cells, the blit above only restored this node's own rect — the + // absolute descendants' cells are lost. Re-blit them from prevScreen + // so the overlays survive. + blitEscapingAbsoluteDescendants(node, output, prevScreen, fx, fy, fw, fh) + + return + } + + // Clear stale content from the old position when re-rendering. + // Dirty: content changed. Moved: position/size changed (e.g., sibling + // above changed height), old cells still on the terminal. + const positionChanged = + cached !== undefined && (cached.x !== x || cached.y !== y || cached.width !== width || cached.height !== height) + + if (positionChanged) { + layoutShifted = true + absoluteOverlayMoved ||= node.style.position === 'absolute' + } + + if (cached && (node.dirty || positionChanged)) { + output.clear( + { + x: Math.floor(cached.x), + y: Math.floor(cached.y), + width: Math.floor(cached.width), + height: Math.floor(cached.height) + }, + node.style.position === 'absolute' + ) + } + + // Read before deleting — hasRemovedChild disables prevScreen blitting + // for siblings to prevent stale overflow content from being restored. + const clears = pendingClears.get(node) + const hasRemovedChild = clears !== undefined + + if (hasRemovedChild) { + layoutShifted = true + + for (const rect of clears) { + output.clear({ + x: Math.floor(rect.x), + y: Math.floor(rect.y), + width: Math.floor(rect.width), + height: Math.floor(rect.height) + }) + } + + pendingClears.delete(node) + } + + // Yoga squeezed this node to zero height (overflow in a height-constrained + // parent) AND a sibling lands at the same y. Skip rendering — both would + // write to the same row; if the sibling's content is shorter, this node's + // tail chars ghost (e.g. "false" + "true" = "truee"). The clear above + // already handled the visible→squeezed transition. + // + // The sibling-overlap check is load-bearing: Yoga's pixel-grid rounding + // can give a box h=0 while still leaving a row for it (next sibling at + // y+1, not y). HelpV2's third shortcuts column hits this — skipping + // unconditionally drops "ctrl + z to suspend" from /help output. + if (height === 0 && siblingSharesY(node, yogaNode)) { + nodeCache.set(node, { x, y, width, height, top: yogaTop }) + node.dirty = false + + return + } + + if (node.nodeName === 'ink-raw-ansi') { + // Pre-rendered ANSI content. The producer already wrapped to width and + // emitted terminal-ready escape codes. Skip squash, measure, wrap, and + // style re-application — output.write() parses ANSI directly into cells. + const text = node.attributes['rawText'] as string + + if (text) { + output.write(x, y, text) + } + } else if (node.nodeName === 'ink-text') { + const segments = squashTextNodesToSegments( + node, + inheritedBackgroundColor ? { backgroundColor: inheritedBackgroundColor } : undefined + ) + + // First, get plain text to check if wrapping is needed + const plainText = segments.map(s => s.text).join('') + + if (plainText.length > 0) { + // Upstream Ink uses getMaxWidth(yogaNode) unclamped here. That + // width comes from Yoga's AtMost pass and can exceed the actual + // screen space (see getMaxWidth docstring). Yoga's height for this + // node already reflects the constrained Exactly pass, so clamping + // the wrap width here keeps line count consistent with layout. + // Without this, characters past the screen edge are dropped by + // setCellAt's bounds check. + const maxWidth = Math.min(getMaxWidth(yogaNode), output.width - x) + const textWrap = node.style.textWrap ?? 'wrap' + + // Check if wrapping is needed + const needsWrapping = widestLine(plainText) > maxWidth + + let text: string + let softWrap: boolean[] | undefined + + if (needsWrapping && segments.length === 1) { + // Single segment: wrap plain text first, then apply styles to each line + const segment = segments[0]! + const w = wrapWithSoftWrap(plainText, maxWidth, textWrap) + softWrap = w.softWrap + text = w.wrapped + .split('\n') + .map(line => { + let styled = applyTextStyles(line, segment.styles) + + // Apply OSC 8 hyperlink per-line so each line is independently + // clickable. output.ts splits on newlines and tokenizes each + // line separately, so a single wrapper around the whole block + // would only apply the hyperlink to the first line. + if (segment.hyperlink) { + styled = wrapWithOsc8Link(styled, segment.hyperlink) + } + + return styled + }) + .join('\n') + } else if (needsWrapping) { + // Multiple segments with wrapping: wrap plain text first, then re-apply + // each segment's styles based on character positions. This preserves + // per-segment styles even when text wraps across lines. + const w = wrapWithSoftWrap(plainText, maxWidth, textWrap) + softWrap = w.softWrap + const charToSegment = buildCharToSegmentMap(segments) + text = applyStylesToWrappedText(w.wrapped, segments, charToSegment, plainText, textWrap === 'wrap-trim') + // Hyperlinks are handled per-run in applyStylesToWrappedText via + // wrapWithOsc8Link, similar to how styles are applied per-run. + } else { + // No wrapping needed: apply styles directly + text = segments + .map(segment => { + let styledText = applyTextStyles(segment.text, segment.styles) + + if (segment.hyperlink) { + styledText = wrapWithOsc8Link(styledText, segment.hyperlink) + } + + return styledText + }) + .join('') + } + + text = applyPaddingToText(node, text, softWrap) + + output.write(x, y, text, softWrap) + } + } else if (node.nodeName === 'ink-box') { + const boxBackgroundColor = node.style.backgroundColor ?? inheritedBackgroundColor + + // Mark this box's region as non-selectable (fullscreen text + // selection). noSelect ops are applied AFTER blits/writes in + // output.get(), so this wins regardless of what's rendered into + // the region — including blits from prevScreen when the box is + // clean (the op is emitted on both the dirty-render path here + // AND on the blit fast-path at line ~235 since blitRegion copies + // the noSelect bitmap alongside cells). + // + // 'from-left-edge' extends the exclusion from col 0 so any + // upstream indentation (tool prefix, tree lines) is covered too + // — a multi-row drag over a diff gutter shouldn't pick up the + // ` ⎿ ` prefix on row 0 or the blank cells under it on row 1+. + if (node.style.noSelect) { + const boxX = Math.floor(x) + const fromEdge = node.style.noSelect === 'from-left-edge' + output.noSelect({ + x: fromEdge ? 0 : boxX, + y: Math.floor(y), + width: fromEdge ? boxX + Math.floor(width) : Math.floor(width), + height: Math.floor(height) + }) + } + + const overflowX = node.style.overflowX ?? node.style.overflow + const overflowY = node.style.overflowY ?? node.style.overflow + const clipHorizontally = overflowX === 'hidden' || overflowX === 'scroll' + const clipVertically = overflowY === 'hidden' || overflowY === 'scroll' + const isScrollY = overflowY === 'scroll' + + const needsClip = clipHorizontally || clipVertically + let y1: number | undefined + let y2: number | undefined + + if (needsClip) { + const x1 = clipHorizontally ? x + yogaNode.getComputedBorder(LayoutEdge.Left) : undefined + + const x2 = clipHorizontally + ? x + yogaNode.getComputedWidth() - yogaNode.getComputedBorder(LayoutEdge.Right) + : undefined + + y1 = clipVertically ? y + yogaNode.getComputedBorder(LayoutEdge.Top) : undefined + + y2 = clipVertically + ? y + yogaNode.getComputedHeight() - yogaNode.getComputedBorder(LayoutEdge.Bottom) + : undefined + + output.clip({ x1, x2, y1, y2 }) + } + + if (isScrollY) { + // Scroll containers follow the ScrollBox component structure: + // a single content-wrapper child with flexShrink:0 (doesn't shrink + // to fit), whose children are the scrollable items. scrollHeight + // comes from the wrapper's intrinsic Yoga height. The wrapper is + // rendered with its Y translated by -scrollTop; its children are + // culled against the visible window. + const padTop = yogaNode.getComputedPadding(LayoutEdge.Top) + + const innerHeight = Math.max( + 0, + (y2 ?? y + height) - (y1 ?? y) - padTop - yogaNode.getComputedPadding(LayoutEdge.Bottom) + ) + + const content = node.childNodes.find(c => (c as DOMElement).yogaNode) as DOMElement | undefined + + const contentYoga = content?.yogaNode + // scrollHeight is the intrinsic height of the content wrapper. + // Do NOT add getComputedTop() — that's the wrapper's offset + // within the viewport (equal to the scroll container's + // paddingTop), and innerHeight already subtracts padding, so + // including it double-counts padding and inflates maxScroll. + const scrollHeight = contentYoga?.getComputedHeight() ?? 0 + // Capture previous scroll bounds BEFORE overwriting — the at-bottom + // follow check compares against last frame's max. + const prevScrollHeight = node.scrollHeight ?? scrollHeight + const prevInnerHeight = node.scrollViewportHeight ?? innerHeight + node.scrollHeight = scrollHeight + node.scrollViewportHeight = innerHeight + // Absolute screen-buffer row where the scrollable area (inside + // padding) begins. Exposed via ScrollBoxHandle.getViewportTop() so + // drag-to-scroll can detect when the drag leaves the scroll viewport. + node.scrollViewportTop = (y1 ?? y) + padTop + + const maxScroll = Math.max(0, scrollHeight - innerHeight) + + // scrollAnchor: scroll so the anchored element's top is at the + // viewport top (plus offset). Yoga is FRESH — same calculateLayout + // pass that just produced scrollHeight. Deterministic alternative + // to scrollTo(N) which bakes a number that's stale by the throttled + // render; the element ref defers the read to now. One-shot snap. + // A prior eased-seek version (proportional drain over ~5 frames) + // moved scrollTop without firing React's notify → parent's quantized + // store snapshot never updated → StickyTracker got stale range props + // → firstVisible wrong. Also: SCROLL_MIN_PER_FRAME=4 with snap-at-1 + // ping-ponged forever at delta=2. Smooth needs drain-end notify + // plumbing; shipping instant first. stickyScroll overrides. + if (node.scrollAnchor) { + const anchorTop = node.scrollAnchor.el.yogaNode?.getComputedTop() + + if (anchorTop != null) { + node.scrollTop = anchorTop + node.scrollAnchor.offset + node.pendingScrollDelta = undefined + } + + node.scrollAnchor = undefined + } + + // At-bottom follow. Positional: if scrollTop was at (or past) the + // previous max, pin to the new max. Scroll away → stop following; + // scroll back (or scrollToBottom/sticky attr) → resume. The sticky + // flag is OR'd in for cold start (scrollTop=0 before first layout) + // and scrollToBottom-from-far-away (flag set before scrollTop moves) + // — the imperative field takes precedence over the attribute so + // scrollTo/scrollBy can break stickiness. pendingDelta<0 guard: + // don't cancel an in-flight scroll-up when content races in. + // Capture scrollTop before follow so ink.tsx can translate any + // active text selection by the same delta (native terminal behavior: + // view keeps scrolling, highlight walks up with the text). + const scrollTopBeforeFollow = node.scrollTop ?? 0 + + const sticky = node.stickyScroll ?? Boolean(node.attributes['stickyScroll']) + + const prevMaxScroll = Math.max(0, prevScrollHeight - prevInnerHeight) + // Positional check only valid when content grew — virtualization can + // transiently SHRINK scrollHeight (tail unmount + stale heightCache + // spacer) making scrollTop >= prevMaxScroll true by artifact, not + // because the user was at bottom. + const grew = scrollHeight >= prevScrollHeight + + const atBottom = sticky || (grew && scrollTopBeforeFollow >= prevMaxScroll) + + if (atBottom && (node.pendingScrollDelta ?? 0) >= 0) { + node.scrollTop = maxScroll + node.pendingScrollDelta = undefined + + // Sync flag so useVirtualScroll's isSticky() agrees with positional + // state — sticky-broken-but-at-bottom (wheel tremor, click-select + // at max) otherwise leaves useVirtualScroll's clamp holding the + // viewport short of new streaming content. scrollTo/scrollBy set + // false; this restores true, same as scrollToBottom() would. + // Only restore when (a) positionally at bottom and (b) the flag + // was explicitly broken (===false) by scrollTo/scrollBy. When + // undefined (never set by user action) leave it alone — setting it + // would make the sticky flag sticky-by-default and lock out + // direct scrollTop writes (e.g. the alt-screen-perf test). + if (node.stickyScroll === false && scrollTopBeforeFollow >= prevMaxScroll) { + node.stickyScroll = true + } + } + + const followDelta = (node.scrollTop ?? 0) - scrollTopBeforeFollow + + if (followDelta > 0) { + const vpTop = node.scrollViewportTop ?? 0 + followScroll = { + delta: followDelta, + viewportTop: vpTop, + viewportBottom: vpTop + innerHeight - 1 + } + } + + // Drain pendingScrollDelta. Native terminals (proportional burst + // events) use proportional drain; xterm.js (VS Code, sparse events + + // app-side accel curve) uses adaptive small-step drain. isXtermJs() + // depends on the async XTVERSION probe, but by the time this runs + // (pendingScrollDelta is only set by wheel events, >>50ms after + // startup) the probe has resolved — same timing guarantee the + // wheel-accel curve relies on. + let cur = node.scrollTop ?? 0 + const pending = node.pendingScrollDelta + const cMin = node.scrollClampMin + const cMax = node.scrollClampMax + const haveClamp = cMin !== undefined && cMax !== undefined + + if (pending !== undefined && pending !== 0) { + // Drain continues even past the clamp — the render-clamp below + // holds the VISUAL at the mounted edge regardless. Hard-stopping + // here caused stop-start jutter: drain hits edge → pause → React + // commits → clamp widens → drain resumes → edge again. Letting + // scrollTop advance smoothly while the clamp lags gives continuous + // visual scroll at React's commit rate (the clamp catches up each + // commit). But THROTTLE the drain when already past the clamp so + // scrollTop doesn't race 5000 rows ahead of the mounted range + // (slide-cap would then take 200 commits to catch up = long + // perceived stall at the edge). Past-clamp drain caps at ~4 rows/ + // frame, roughly matching React's slide rate so the gap stays + // bounded and catch-up is quick once input stops. + const pastClamp = haveClamp && ((pending < 0 && cur < cMin) || (pending > 0 && cur > cMax)) + + const eff = pastClamp ? Math.min(4, innerHeight >> 3) : innerHeight + cur += isXtermJsHost() ? drainAdaptive(node, pending, eff) : drainProportional(node, pending, eff) + } else if (pending === 0) { + // Opposite scrollBy calls cancelled to zero — clear so we don't + // schedule an infinite loop of no-op drain frames. + node.pendingScrollDelta = undefined + } + + let scrollTop = Math.max(0, Math.min(cur, maxScroll)) + + // Virtual-scroll clamp: if scrollTop raced past the currently-mounted + // range (burst PageUp before React re-renders), render at the EDGE of + // the mounted children instead of blank spacer. Do NOT write back to + // node.scrollTop — the clamped value is for this paint only; the real + // scrollTop stays so React's next commit sees the target and mounts + // the right range. Not scheduling scrollDrainNode here keeps the + // clamp passive — React's commit → resetAfterCommit → onRender will + // paint again with fresh bounds. + const clamped = haveClamp ? Math.max(cMin, Math.min(scrollTop, cMax)) : scrollTop + + node.scrollTop = scrollTop + + // Clamp hitting top/bottom consumes any remainder. Set drainPending + // only after clamp so a wasted no-op frame isn't scheduled. + if (scrollTop !== cur) { + node.pendingScrollDelta = undefined + } + + if (node.pendingScrollDelta !== undefined) { + scrollDrainNode = node + } + + scrollTop = clamped + + if (content && contentYoga) { + // Compute content wrapper's absolute render position with scroll + // offset applied, then render its children with culling. + const contentX = x + contentYoga.getComputedLeft() + const contentY = y + contentYoga.getComputedTop() - scrollTop + // layoutShifted detection gap: when scrollTop moves by >= viewport + // height (batched PageUps, fast wheel), every visible child gets + // culled (cache dropped) and every newly-visible child has no + // cache — so the children's positionChanged check can't fire. + // The content wrapper's cached y (which encodes -scrollTop) is + // the only node that survives to witness the scroll. + const contentCached = nodeCache.get(content) + let hint: ScrollHint | null = null + + if (contentCached && contentCached.y !== contentY) { + // delta = newScrollTop - oldScrollTop (positive = scrolled down). + // Capture a DECSTBM hint if the container itself didn't move + // and the shift fits within the viewport — otherwise the full + // rewrite is needed anyway, and layoutShifted stays the fallback. + const delta = contentCached.y - contentY + const regionTop = Math.floor(y + contentYoga.getComputedTop()) + const regionBottom = regionTop + innerHeight - 1 + + if (cached?.y === y && cached.height === height && innerHeight > 0 && Math.abs(delta) < innerHeight) { + hint = { top: regionTop, bottom: regionBottom, delta } + scrollHint = hint + } else { + layoutShifted = true + } + } + + // Fast path: scroll (hint captured) with usable prevScreen. + // Blit prevScreen's scroll region into next.screen, shift in-place + // by delta (mirrors DECSTBM), then render ONLY the edge rows. The + // nested clip keeps child writes out of stable rows — a tall child + // that spans edge+stable still renders but stable cells are + // clipped, preserving the blit. Avoids re-rendering every visible + // child (expensive for long syntax-highlighted transcripts). + // + // When content.dirty (e.g. streaming text at the bottom of the + // scroll), we still use the fast path — the dirty child is almost + // always in the edge rows (the bottom, where new content appears). + // After edge rendering, any dirty children in stable rows are + // re-rendered in a second pass to avoid showing stale blitted + // content. + // + // Guard: the fast path only handles pure scroll or bottom-append. + // Child removal/insertion changes the content height in a way that + // doesn't match the scroll delta — fall back to the full path so + // removed children don't leave stale cells and shifted siblings + // render at their new positions. + const scrollHeight = contentYoga.getComputedHeight() + const prevHeight = contentCached?.height ?? scrollHeight + const heightDelta = scrollHeight - prevHeight + + const safeForFastPath = !hint || heightDelta === 0 || (hint.delta > 0 && heightDelta === hint.delta) + + // scrollHint is set above when hint is captured. If safeForFastPath + // is false the full path renders a next.screen that doesn't match + // the DECSTBM shift — emitting DECSTBM leaves stale rows (seen as + // content bleeding through during scroll-up + streaming). Clear it. + if (!safeForFastPath) { + scrollHint = null + } + + if (hint && prevScreen && safeForFastPath) { + const { top, bottom, delta } = hint + const w = Math.floor(width) + output.blit(prevScreen, Math.floor(x), top, w, bottom - top + 1) + output.shift(top, bottom, delta) + // Edge rows: new content entering the viewport. + const edgeTop = delta > 0 ? bottom - delta + 1 : top + const edgeBottom = delta > 0 ? bottom : top - delta - 1 + output.clear({ + x: Math.floor(x), + y: edgeTop, + width: w, + height: edgeBottom - edgeTop + 1 + }) + output.clip({ + x1: undefined, + x2: undefined, + y1: edgeTop, + y2: edgeBottom + 1 + }) + + // Snapshot dirty children before the first pass — the first + // pass clears dirty flags, and edge-spanning children would be + // missed by the second pass without this snapshot. + const dirtyChildren = content.dirty + ? new Set(content.childNodes.filter(c => (c as DOMElement).dirty)) + : null + + renderScrolledChildren( + content, + output, + contentX, + contentY, + hasRemovedChild, + undefined, + // Cull to edge in child-local coords (inverse of contentY offset). + edgeTop - contentY, + edgeBottom + 1 - contentY, + boxBackgroundColor, + true + ) + output.unclip() + + // Second pass: re-render children in stable rows whose screen + // position doesn't match where the shift put their old pixels. + // Covers TWO cases: + // 1. Dirty children — their content changed, blitted pixels are + // stale regardless of position. + // 2. Clean children BELOW a middle-growth point — when a dirty + // sibling above them grows, their yogaTop increases but + // scrollTop increases by the same amount (sticky), so their + // screenY is CONSTANT. The shift moved their old pixels to + // screenY-delta (wrong); they should stay at screenY. Without + // this, the spinner/tmux-monitor ghost at shifted positions + // during streaming (e.g. triple spinner, pill duplication). + // For bottom-append (the common case), all clean children are + // ABOVE the growth point; their screenY decreased by delta and + // the shift put them at the right place — skipped here, fast + // path preserved. + if (dirtyChildren) { + const edgeTopLocal = edgeTop - contentY + const edgeBottomLocal = edgeBottom + 1 - contentY + const spaces = ' '.repeat(w) + // Track cumulative height change of children iterated so far. + // A clean child's yogaTop is unchanged iff this is zero (no + // sibling above it grew/shrank/mounted). When zero, the skip + // check cached.y−delta === screenY reduces to delta === delta + // (tautology) → skip without yoga reads. Restores O(dirty) + // that #24536 traded away: for bottom-append the dirty child + // is last (all clean children skip); for virtual-scroll range + // shift the topSpacer shrink + new-item heights self-balance + // to zero before reaching the clean block. Middle-growth + // leaves shift non-zero → clean children after the growth + // point fall through to yoga + the fine-grained check below, + // preserving the ghost-box fix. + let cumHeightShift = 0 + + for (const childNode of content.childNodes) { + const childElem = childNode as DOMElement + const isDirty = dirtyChildren.has(childNode) + + if (!isDirty && cumHeightShift === 0) { + if (nodeCache.has(childElem)) { + continue + } + // Uncached = culled last frame, now re-entering. blit + // never painted it → fall through to yoga + render. + // Height unchanged (clean), so cumHeightShift stays 0. + } + + const cy = childElem.yogaNode + + if (!cy) { + continue + } + + const childTop = cy.getComputedTop() + const childH = cy.getComputedHeight() + const childBottom = childTop + childH + + if (isDirty) { + const prev = nodeCache.get(childElem) + cumHeightShift += childH - (prev ? prev.height : 0) + } + + // Skip culled children (outside viewport) + if (childBottom <= scrollTop || childTop >= scrollTop + innerHeight) { + continue + } + + // Skip children entirely within edge rows (already rendered) + if (childTop >= edgeTopLocal && childBottom <= edgeBottomLocal) { + continue + } + + const screenY = Math.floor(contentY + childTop) + + // Clean children reaching here have cumHeightShift ≠ 0 OR + // no cache. Re-check precisely: cached.y − delta is where + // the shift left old pixels; if it equals new screenY the + // blit is correct (shift re-balanced at this child, or + // yogaTop happens to net out). No cache → blit never + // painted it → render. + if (!isDirty) { + const childCached = nodeCache.get(childElem) + + if (childCached && Math.floor(childCached.y) - delta === screenY) { + continue + } + } + + // Wipe this child's region with spaces to overwrite stale + // blitted content — output.clear() only expands damage and + // cannot zero cells that the blit already wrote. + const screenBottom = Math.min( + Math.floor(contentY + childBottom), + Math.floor((y1 ?? y) + padTop + innerHeight) + ) + + if (screenY < screenBottom) { + const fill = Array(screenBottom - screenY) + .fill(spaces) + .join('\n') + + output.write(Math.floor(x), screenY, fill) + output.clip({ + x1: undefined, + x2: undefined, + y1: screenY, + y2: screenBottom + }) + renderNodeToOutput(childElem, output, { + offsetX: contentX, + offsetY: contentY, + prevScreen: undefined, + inheritedBackgroundColor: boxBackgroundColor + }) + output.unclip() + } + } + } + + // Third pass: repair rows where shifted copies of absolute + // overlays landed. The blit copied prevScreen cells INCLUDING + // overlay pixels (overlays render AFTER this ScrollBox so they + // painted into prevScreen's scroll region). After shift, those + // pixels sit at (rect.y - delta) — neither edge render nor the + // overlay's own re-render covers them. Wipe and re-render + // ScrollBox content so the diff writes correct cells. + const spaces = absoluteRectsPrev.length ? ' '.repeat(w) : '' + + for (const r of absoluteRectsPrev) { + if (r.y >= bottom + 1 || r.y + r.height <= top) { + continue + } + + const shiftedTop = Math.max(top, Math.floor(r.y) - delta) + + const shiftedBottom = Math.min(bottom + 1, Math.floor(r.y + r.height) - delta) + + // Skip if entirely within edge rows (already rendered). + if (shiftedTop >= edgeTop && shiftedBottom <= edgeBottom + 1) { + continue + } + + if (shiftedTop >= shiftedBottom) { + continue + } + + const fill = Array(shiftedBottom - shiftedTop) + .fill(spaces) + .join('\n') + + output.write(Math.floor(x), shiftedTop, fill) + output.clip({ + x1: undefined, + x2: undefined, + y1: shiftedTop, + y2: shiftedBottom + }) + renderScrolledChildren( + content, + output, + contentX, + contentY, + hasRemovedChild, + undefined, + shiftedTop - contentY, + shiftedBottom - contentY, + boxBackgroundColor, + true + ) + output.unclip() + } + } else { + // Full path. Two sub-cases: + // + // Scrolled without a usable hint (big jump, container moved): + // child positions in prevScreen are stale. Clear the viewport + // and disable blit so children don't restore shifted content. + // + // No scroll (spinner tick, content edit): child positions in + // prevScreen are still valid. Skip the viewport clear and pass + // prevScreen so unchanged children blit. Dirty children already + // self-clear via their own cached-rect clear. Without this, a + // spinner inside ScrollBox forces a full-content rewrite every + // frame — on wide terminals over tmux (no BSU/ESU) the + // bandwidth crosses the chunk boundary and the frame tears. + const scrolled = contentCached && contentCached.y !== contentY + + if (scrolled && y1 !== undefined && y2 !== undefined) { + output.clear({ + x: Math.floor(x), + y: Math.floor(y1), + width: Math.floor(width), + height: Math.floor(y2 - y1) + }) + } + + // positionChanged (ScrollBox height shrunk — pill mount) means a + // child spanning the old bottom edge would blit its full cached + // rect past the new clip. output.ts clips blits now, but also + // disable prevScreen here so the partial-row child re-renders at + // correct bounds instead of blitting a clipped (truncated) old + // rect. + renderScrolledChildren( + content, + output, + contentX, + contentY, + hasRemovedChild, + scrolled || positionChanged ? undefined : prevScreen, + scrollTop, + scrollTop + innerHeight, + boxBackgroundColor + ) + } + + nodeCache.set(content, { + x: contentX, + y: contentY, + width: contentYoga.getComputedWidth(), + height: contentYoga.getComputedHeight() + }) + content.dirty = false + } + } else { + // Fill interior with background color before rendering children. + // This covers padding areas and empty space; child text inherits + // the color via inheritedBackgroundColor so written cells also + // get the background. + // Disable prevScreen for children: the fill overwrites the entire + // interior each render, so child blits from prevScreen would restore + // stale cells (wrong bg if it changed) on top of the fresh fill. + const ownBackgroundColor = node.style.backgroundColor + + if (ownBackgroundColor || node.style.opaque) { + const borderLeft = yogaNode.getComputedBorder(LayoutEdge.Left) + const borderRight = yogaNode.getComputedBorder(LayoutEdge.Right) + const borderTop = yogaNode.getComputedBorder(LayoutEdge.Top) + const borderBottom = yogaNode.getComputedBorder(LayoutEdge.Bottom) + const innerWidth = Math.floor(width) - borderLeft - borderRight + const innerHeight = Math.floor(height) - borderTop - borderBottom + + if (innerWidth > 0 && innerHeight > 0) { + const spaces = ' '.repeat(innerWidth) + + const fillLine = ownBackgroundColor + ? applyTextStyles(spaces, { backgroundColor: ownBackgroundColor }) + : spaces + + const fill = Array(innerHeight).fill(fillLine).join('\n') + output.write(x + borderLeft, y + borderTop, fill) + } + } + + renderChildren( + node, + output, + x, + y, + hasRemovedChild, + // backgroundColor and opaque both disable child blit: the fill + // overwrites the entire interior each render, so any child whose + // layout position shifted would blit stale cells from prevScreen + // on top of the fresh fill. Previously opaque kept blit enabled + // on the assumption that plain-space fill + unchanged children = + // valid composite, but children CAN reposition (ScrollBox remeasure + // on re-render → /permissions body blanked on Down arrow, #25436). + ownBackgroundColor || node.style.opaque ? undefined : prevScreen, + boxBackgroundColor + ) + } + + if (needsClip) { + output.unclip() + } + + // Render border AFTER children to ensure it's not overwritten by child + // clearing operations. When a child shrinks, it clears its old area, + // which may overlap with where the parent's border now is. + renderBorder(x, y, node, output) + } else if (node.nodeName === 'ink-root') { + renderChildren(node, output, x, y, hasRemovedChild, prevScreen, inheritedBackgroundColor) + } + + // Cache layout bounds for dirty tracking + const rect = { x, y, width, height, top: yogaTop } + nodeCache.set(node, rect) + + if (node.style.position === 'absolute') { + absoluteRectsCur.push(rect) + } + + node.dirty = false + } +} + +// Overflow contamination: content overflows right/down, so clean siblings +// AFTER a dirty/removed sibling can contain stale overflow in prevScreen. +// Disable blit for siblings after a dirty child — but still pass prevScreen +// TO the dirty child itself so its clean descendants can blit. The dirty +// child's own blit check already fails (node.dirty=true at line 216), so +// passing prevScreen only benefits its subtree. +// For removed children we don't know their original position, so +// conservatively disable blit for all. +// +// Clipped children (overflow hidden/scroll on both axes) cannot overflow +// onto later siblings — their content is confined to their layout bounds. +// Skip the contamination guard for them so later siblings can still blit. +// Without this, a spinner inside a ScrollBox dirties the wrapper on every +// tick and the bottom prompt section never blits → 100% writes every frame. +// +// Exception: absolute-positioned clipped children may have layout bounds +// that overlap arbitrary siblings, so the clipping does not help. +// +// Overlap contamination (seenDirtyClipped): a later ABSOLUTE sibling whose +// rect sits inside a dirty clipped child's bounds would blit stale cells +// from prevScreen — the clipped child just rewrote those cells this frame. +// The clipsBothAxes skip only protects against OVERFLOW (clipped child +// painting outside its bounds), not overlap (absolute sibling painting +// inside them). For non-opaque absolute siblings, skipSelfBlit forces +// descent (the full-width rect has transparent gaps → stale blit) while +// still passing prevScreen so opaque descendants can blit their narrower +// rects (NewMessagesPill's inner Text with backgroundColor). Opaque +// absolute siblings fill their entire rect — direct blit is safe. +function renderChildren( + node: DOMElement, + output: Output, + offsetX: number, + offsetY: number, + hasRemovedChild: boolean, + prevScreen: Screen | undefined, + inheritedBackgroundColor: Color | undefined +): void { + let seenDirtyChild = false + let seenDirtyClipped = false + + for (const childNode of node.childNodes) { + const childElem = childNode as DOMElement + // Capture dirty before rendering — renderNodeToOutput clears the flag + const wasDirty = childElem.dirty + const isAbsolute = childElem.style.position === 'absolute' + renderNodeToOutput(childElem, output, { + offsetX, + offsetY, + prevScreen: hasRemovedChild || seenDirtyChild ? undefined : prevScreen, + // Short-circuits on seenDirtyClipped (false in the common case) so + // the opaque/bg reads don't happen per-child per-frame. + skipSelfBlit: + seenDirtyClipped && isAbsolute && !childElem.style.opaque && childElem.style.backgroundColor === undefined, + inheritedBackgroundColor + }) + + if (wasDirty && !seenDirtyChild) { + if (!clipsBothAxes(childElem) || isAbsolute) { + seenDirtyChild = true + } else { + seenDirtyClipped = true + } + } + } +} + +function clipsBothAxes(node: DOMElement): boolean { + const ox = node.style.overflowX ?? node.style.overflow + const oy = node.style.overflowY ?? node.style.overflow + + return (ox === 'hidden' || ox === 'scroll') && (oy === 'hidden' || oy === 'scroll') +} + +// When Yoga squeezes a box to h=0, the ghost only happens if a sibling +// lands at the same computed top — then both write to that row and the +// shorter content leaves the longer's tail visible. Yoga's pixel-grid +// rounding can give h=0 while still advancing the next sibling's top +// (HelpV2's third shortcuts column), so h=0 alone isn't sufficient. +function siblingSharesY(node: DOMElement, yogaNode: LayoutNode): boolean { + const parent = node.parentNode + + if (!parent) { + return false + } + + const myTop = yogaNode.getComputedTop() + const siblings = parent.childNodes + const idx = siblings.indexOf(node) + + for (let i = idx + 1; i < siblings.length; i++) { + const sib = (siblings[i] as DOMElement).yogaNode + + if (!sib) { + continue + } + + return sib.getComputedTop() === myTop + } + + // No next sibling with a yoga node — check previous. A run of h=0 boxes + // at the tail would all share y with each other. + for (let i = idx - 1; i >= 0; i--) { + const sib = (siblings[i] as DOMElement).yogaNode + + if (!sib) { + continue + } + + return sib.getComputedTop() === myTop + } + + return false +} + +// When a node blits, its absolute-positioned descendants that paint outside +// the node's layout bounds are NOT covered by the blit (which only copies +// the node's own rect). If a dirty sibling re-rendered and overwrote those +// cells, we must re-blit them from prevScreen so the overlays survive. +// Example: PromptInputFooter's slash menu uses position='absolute' bottom='100%' +// to float above the prompt; a spinner tick in the ScrollBox above re-renders +// and overwrites those cells. Without this, the menu vanishes on the next frame. +function blitEscapingAbsoluteDescendants( + node: DOMElement, + output: Output, + prevScreen: Screen, + px: number, + py: number, + pw: number, + ph: number +): void { + const pr = px + pw + const pb = py + ph + + for (const child of node.childNodes) { + if (child.nodeName === '#text') { + continue + } + + const elem = child as DOMElement + + if (elem.style.position === 'absolute') { + const cached = nodeCache.get(elem) + + if (cached) { + absoluteRectsCur.push(cached) + const cx = Math.floor(cached.x) + const cy = Math.floor(cached.y) + const cw = Math.floor(cached.width) + const ch = Math.floor(cached.height) + + // Only blit rects that extend outside the parent's layout bounds — + // cells within the parent rect are already covered by the parent blit. + if (cx < px || cy < py || cx + cw > pr || cy + ch > pb) { + output.blit(prevScreen, cx, cy, cw, ch) + } + } + } + + // Recurse — absolute descendants can be nested arbitrarily deep + blitEscapingAbsoluteDescendants(elem, output, prevScreen, px, py, pw, ph) + } +} + +// Render children of a scroll container with viewport culling. +// scrollTopY..scrollBottomY are the visible window in CHILD-LOCAL Yoga coords +// (i.e. what getComputedTop() returns). Children entirely outside this window +// are skipped; their nodeCache entry is deleted so if they re-enter the +// viewport later they don't emit a stale clear for a position now occupied +// by a sibling. +function renderScrolledChildren( + node: DOMElement, + output: Output, + offsetX: number, + offsetY: number, + hasRemovedChild: boolean, + prevScreen: Screen | undefined, + scrollTopY: number, + scrollBottomY: number, + inheritedBackgroundColor: Color | undefined, + // When true (DECSTBM fast path), culled children keep their cache — + // the blit+shift put stable rows in next.screen so stale cache is + // never read. Avoids walking O(total_children * subtree_depth) per frame. + preserveCulledCache = false +): void { + let seenDirtyChild = false + // Track cumulative height shift of dirty children iterated so far. When + // zero, a clean child's yogaTop is unchanged (no sibling above it grew), + // so cached.top is fresh and the cull check skips yoga. Bottom-append + // has the dirty child last → all prior clean children hit cache → + // O(dirty) not O(mounted). Middle-growth leaves shift non-zero after + // the dirty child → subsequent children yoga-read (needed for correct + // culling since their yogaTop shifted). + let cumHeightShift = 0 + + for (const childNode of node.childNodes) { + const childElem = childNode as DOMElement + const cy = childElem.yogaNode + + if (cy) { + const cached = nodeCache.get(childElem) + let top: number + let height: number + + if (cached?.top !== undefined && !childElem.dirty && cumHeightShift === 0) { + top = cached.top + height = cached.height + } else { + top = cy.getComputedTop() + height = cy.getComputedHeight() + + if (childElem.dirty) { + cumHeightShift += height - (cached ? cached.height : 0) + } + + // Refresh cached top so next frame's cumShift===0 path stays + // correct. For culled children with preserveCulledCache=true this + // is the ONLY refresh point — without it, a middle-growth frame + // leaves stale tops that misfire next frame. + if (cached) { + cached.top = top + } + } + + const bottom = top + height + + if (bottom <= scrollTopY || top >= scrollBottomY) { + // Culled — outside visible window. Drop stale cache entries from + // the subtree so when this child re-enters it doesn't fire clears + // at positions now occupied by siblings. The viewport-clear on + // scroll-change handles the visible-area repaint. + if (!preserveCulledCache) { + dropSubtreeCache(childElem) + } + + continue + } + } + + const wasDirty = childElem.dirty + renderNodeToOutput(childElem, output, { + offsetX, + offsetY, + prevScreen: hasRemovedChild || seenDirtyChild ? undefined : prevScreen, + inheritedBackgroundColor + }) + + if (wasDirty) { + seenDirtyChild = true + } + } +} + +function dropSubtreeCache(node: DOMElement): void { + nodeCache.delete(node) + + for (const child of node.childNodes) { + if (child.nodeName !== '#text') { + dropSubtreeCache(child as DOMElement) + } + } +} + +// Exported for testing +export { applyStylesToWrappedText, buildCharToSegmentMap } + +export default renderNodeToOutput diff --git a/ui-tui/packages/hermes-ink/src/ink/render-to-screen.ts b/ui-tui/packages/hermes-ink/src/ink/render-to-screen.ts new file mode 100644 index 0000000000..57272bd36a --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/render-to-screen.ts @@ -0,0 +1,236 @@ +import noop from 'lodash-es/noop.js' +import type { ReactElement } from 'react' +import { LegacyRoot } from 'react-reconciler/constants.js' + +import { logForDebugging } from '../utils/debug.js' + +import { createNode, type DOMElement } from './dom.js' +import { FocusManager } from './focus.js' +import Output from './output.js' +import reconciler from './reconciler.js' +import renderNodeToOutput, { resetLayoutShifted } from './render-node-to-output.js' +import { + cellAtIndex, + CellWidth, + CharPool, + createScreen, + HyperlinkPool, + type Screen, + setCellStyleId, + StylePool +} from './screen.js' + +/** Position of a match within a rendered message, relative to the message's + * own bounding box (row 0 = message top). Stable across scroll — to + * highlight on the real screen, add the message's screen-row offset. */ +export type MatchPosition = { + row: number + col: number + /** Number of CELLS the match spans (= query.length for ASCII, more + * for wide chars in the query). */ + len: number +} + +// Shared across calls. Pools accumulate style/char interns — reusing them +// means later calls hit cache more. Root/container reuse saves the +// createContainer cost (~1ms). LegacyRoot: all work sync, no scheduling — +// ConcurrentRoot's scheduler backlog leaks across roots via flushSyncWork. +let root: DOMElement | undefined +let container: ReturnType | undefined +let stylePool: StylePool | undefined +let charPool: CharPool | undefined +let hyperlinkPool: HyperlinkPool | undefined +let output: Output | undefined + +const timing = { reconcile: 0, yoga: 0, paint: 0, scan: 0, calls: 0 } +const LOG_EVERY = 20 + +/** Render a React element (wrapped in all contexts the component needs — + * caller's job) to an isolated Screen buffer at the given width. Returns + * the Screen + natural height (from yoga). Used for search: render ONE + * message, scan its Screen for the query, get exact (row, col) positions. + * + * ~1-3ms per call (yoga alloc + calculateLayout + paint). The + * flushSyncWork cross-root leak measured ~0.0003ms/call growth — fine + * for on-demand single-message rendering, pathological for render-all- + * 8k-upfront. Cache per (msg, query, width) upstream. + * + * Unmounts between calls. Root/container/pools persist for reuse. */ +export function renderToScreen(el: ReactElement, width: number): { screen: Screen; height: number } { + if (!root) { + root = createNode('ink-root') + root.focusManager = new FocusManager(() => false) + stylePool = new StylePool() + charPool = new CharPool() + hyperlinkPool = new HyperlinkPool() + container = reconciler.createContainer(root, LegacyRoot, null, false, null, 'search-render', noop, noop, noop, noop) + } + + const t0 = performance.now() + reconciler.updateContainerSync(el, container, null, noop) + reconciler.flushSyncWork() + const t1 = performance.now() + + // Yoga layout. Root might not have a yogaNode if the tree is empty. + root.yogaNode?.setWidth(width) + root.yogaNode?.calculateLayout(width) + const height = Math.ceil(root.yogaNode?.getComputedHeight() ?? 0) + const t2 = performance.now() + + // Paint to a fresh Screen. Width = given, height = yoga's natural. + // No alt-screen, no prevScreen (every call is fresh). + const screen = createScreen( + width, + Math.max(1, height), // avoid 0-height Screen (createScreen may choke) + stylePool!, + charPool!, + hyperlinkPool! + ) + + if (!output) { + output = new Output({ width, height, stylePool: stylePool!, screen }) + } else { + output.reset(width, height, screen) + } + + resetLayoutShifted() + renderNodeToOutput(root, output, { prevScreen: undefined }) + // renderNodeToOutput queues writes into Output; .get() flushes the + // queue into the Screen's cell arrays. Without this the screen is + // blank (constructor-zero). + const rendered = output.get() + const t3 = performance.now() + + // Unmount so next call gets a fresh tree. Leaves root/container/pools. + reconciler.updateContainerSync(null, container, null, noop) + reconciler.flushSyncWork() + + timing.reconcile += t1 - t0 + timing.yoga += t2 - t1 + timing.paint += t3 - t2 + + if (++timing.calls % LOG_EVERY === 0) { + const total = timing.reconcile + timing.yoga + timing.paint + timing.scan + logForDebugging( + `renderToScreen: ${timing.calls} calls · ` + + `reconcile=${timing.reconcile.toFixed(1)}ms yoga=${timing.yoga.toFixed(1)}ms ` + + `paint=${timing.paint.toFixed(1)}ms scan=${timing.scan.toFixed(1)}ms · ` + + `total=${total.toFixed(1)}ms · avg ${(total / timing.calls).toFixed(2)}ms/call` + ) + } + + return { screen: rendered, height } +} + +/** Scan a Screen buffer for all occurrences of query. Returns positions + * relative to the buffer (row 0 = buffer top). Same cell-skip logic as + * applySearchHighlight (SpacerTail/SpacerHead/noSelect) so positions + * match what the overlay highlight would find. Case-insensitive. + * + * For the side-render use: this Screen is the FULL message (natural + * height, not viewport-clipped). Positions are stable — to highlight + * on the real screen, add the message's screen offset (lo). */ +export function scanPositions(screen: Screen, query: string): MatchPosition[] { + const lq = query.toLowerCase() + + if (!lq) { + return [] + } + + const qlen = lq.length + const w = screen.width + const h = screen.height + const noSelect = screen.noSelect + const positions: MatchPosition[] = [] + + const t0 = performance.now() + + for (let row = 0; row < h; row++) { + const rowOff = row * w + // Same text-build as applySearchHighlight. Keep in sync — or extract + // to a shared helper (TODO once both are stable). codeUnitToCell + // maps indexOf positions (code units in the LOWERCASED text) to cell + // indices in colOf — surrogate pairs (emoji) and multi-unit lowercase + // (Turkish İ → i + U+0307) make text.length > colOf.length. + let text = '' + const colOf: number[] = [] + const codeUnitToCell: number[] = [] + + for (let col = 0; col < w; col++) { + const idx = rowOff + col + const cell = cellAtIndex(screen, idx) + + if (cell.width === CellWidth.SpacerTail || cell.width === CellWidth.SpacerHead || noSelect[idx] === 1) { + continue + } + + const lc = cell.char.toLowerCase() + const cellIdx = colOf.length + + for (let i = 0; i < lc.length; i++) { + codeUnitToCell.push(cellIdx) + } + + text += lc + colOf.push(col) + } + + // Non-overlapping — same advance as applySearchHighlight. + let pos = text.indexOf(lq) + + while (pos >= 0) { + const startCi = codeUnitToCell[pos]! + const endCi = codeUnitToCell[pos + qlen - 1]! + const col = colOf[startCi]! + const endCol = colOf[endCi]! + 1 + positions.push({ row, col, len: endCol - col }) + pos = text.indexOf(lq, pos + qlen) + } + } + + timing.scan += performance.now() - t0 + + return positions +} + +/** Write CURRENT (yellow+bold+underline) at positions[currentIdx] + + * rowOffset. OTHER positions are NOT styled here — the scan-highlight + * (applySearchHighlight with null hint) does inverse for all visible + * matches, including these. Two-layer: scan = 'you could go here', + * position = 'you ARE here'. Writing inverse again here would be a + * no-op (withInverse idempotent) but wasted work. + * + * Positions are message-relative (row 0 = message top). rowOffset = + * message's current screen-top (lo). Clips outside [0, height). */ +export function applyPositionedHighlight( + screen: Screen, + stylePool: StylePool, + positions: MatchPosition[], + rowOffset: number, + currentIdx: number +): boolean { + if (currentIdx < 0 || currentIdx >= positions.length) { + return false + } + + const p = positions[currentIdx]! + const row = p.row + rowOffset + + if (row < 0 || row >= screen.height) { + return false + } + + const transform = (id: number) => stylePool.withCurrentMatch(id) + const rowOff = row * screen.width + + for (let col = p.col; col < p.col + p.len; col++) { + if (col < 0 || col >= screen.width) { + continue + } + + const cell = cellAtIndex(screen, rowOff + col) + setCellStyleId(screen, col, row, transform(cell.styleId)) + } + + return true +} diff --git a/ui-tui/packages/hermes-ink/src/ink/renderer.ts b/ui-tui/packages/hermes-ink/src/ink/renderer.ts new file mode 100644 index 0000000000..38e5276354 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/renderer.ts @@ -0,0 +1,169 @@ +import { logForDebugging } from '../utils/debug.js' + +import { type DOMElement, markDirty } from './dom.js' +import type { Frame } from './frame.js' +import { consumeAbsoluteRemovedFlag } from './node-cache.js' +import Output from './output.js' +import renderNodeToOutput, { + didAbsoluteOverlayMove, + getScrollDrainNode, + getScrollHint, + resetLayoutShifted, + resetScrollDrainNode, + resetScrollHint +} from './render-node-to-output.js' +import { createScreen, type StylePool } from './screen.js' + +export type RenderOptions = { + frontFrame: Frame + backFrame: Frame + isTTY: boolean + terminalWidth: number + terminalRows: number + altScreen: boolean + // True when the previous frame's screen buffer was mutated post-render + // (selection overlay), reset to blank (alt-screen enter/resize/SIGCONT), + // or reset to 0×0 (forceRedraw). Blitting from such a prevScreen would + // copy stale inverted cells, blanks, or nothing. When false, blit is safe. + prevFrameContaminated: boolean +} + +export type Renderer = (options: RenderOptions) => Frame + +export default function createRenderer(node: DOMElement, stylePool: StylePool): Renderer { + // Reuse Output across frames so charCache (tokenize + grapheme clustering) + // persists — most lines don't change between renders. + let output: Output | undefined + + return options => { + const { frontFrame, backFrame, isTTY, terminalWidth, terminalRows } = options + + const prevScreen = frontFrame.screen + const backScreen = backFrame.screen + // Read pools from the back buffer's screen — pools may be replaced + // between frames (generational reset), so we can't capture them in the closure + const charPool = backScreen.charPool + const hyperlinkPool = backScreen.hyperlinkPool + + // Return empty frame if yoga node doesn't exist or layout hasn't been computed yet. + // getComputedHeight() returns NaN before calculateLayout() is called. + // Also check for invalid dimensions (negative, Infinity) that would cause RangeError + // when creating arrays. + const computedHeight = node.yogaNode?.getComputedHeight() + const computedWidth = node.yogaNode?.getComputedWidth() + + const hasInvalidHeight = computedHeight === undefined || !Number.isFinite(computedHeight) || computedHeight < 0 + + const hasInvalidWidth = computedWidth === undefined || !Number.isFinite(computedWidth) || computedWidth < 0 + + if (!node.yogaNode || hasInvalidHeight || hasInvalidWidth) { + // Log to help diagnose root cause (visible with --debug flag) + if (node.yogaNode && (hasInvalidHeight || hasInvalidWidth)) { + logForDebugging( + `Invalid yoga dimensions: width=${computedWidth}, height=${computedHeight}, ` + + `childNodes=${node.childNodes.length}, terminalWidth=${terminalWidth}, terminalRows=${terminalRows}` + ) + } + + return { + screen: createScreen(terminalWidth, 0, stylePool, charPool, hyperlinkPool), + viewport: { width: terminalWidth, height: terminalRows }, + cursor: { x: 0, y: 0, visible: true } + } + } + + const width = Math.floor(node.yogaNode.getComputedWidth()) + const yogaHeight = Math.floor(node.yogaNode.getComputedHeight()) + // Alt-screen: the screen buffer IS the alt buffer — always exactly + // terminalRows tall. wraps children in , so yogaHeight should equal + // terminalRows. But if something renders as a SIBLING of that Box + // (bug: MessageSelector was outside ), yogaHeight + // exceeds rows and every assumption below (viewport +1 hack, cursor.y + // clamp, log-update's heightDelta===0 fast path) breaks, desyncing + // virtual/physical cursors. Clamping here enforces the invariant: + // overflow writes land at y >= screen.height and setCellAt drops + // them. The sibling is invisible (obvious, easy to find) instead of + // corrupting the whole terminal. + const height = options.altScreen ? terminalRows : yogaHeight + + if (options.altScreen && yogaHeight > terminalRows) { + logForDebugging( + `alt-screen: yoga height ${yogaHeight} > terminalRows ${terminalRows} — ` + + `something is rendering outside . Overflow clipped.`, + { level: 'warn' } + ) + } + + const screen = backScreen ?? createScreen(width, height, stylePool, charPool, hyperlinkPool) + + if (output) { + output.reset(width, height, screen) + } else { + output = new Output({ width, height, stylePool, screen }) + } + + resetLayoutShifted() + resetScrollHint() + resetScrollDrainNode() + + // prevFrameContaminated: selection overlay mutated the returned screen + // buffer post-render (in ink.tsx), resetFramesForAltScreen() replaced it + // with blanks, or forceRedraw() reset it to 0×0. Blit on the NEXT frame + // would copy stale inverted cells / blanks / nothing. When clean, blit + // restores the O(unchanged) fast path for steady-state frames (spinner + // tick, text stream). + // Removing an absolute-positioned node poisons prevScreen: it may + // have painted over non-siblings (e.g. an overlay over a ScrollBox + // earlier in tree order), so their blits would restore the removed + // node's pixels. hasRemovedChild only shields direct siblings. + // Normal-flow removals don't paint cross-subtree and are fine. + const absoluteRemoved = consumeAbsoluteRemovedFlag() + renderNodeToOutput(node, output, { + prevScreen: absoluteRemoved || options.prevFrameContaminated ? undefined : prevScreen + }) + + const renderedScreen = output.get() + + // Drain continuation: render cleared scrollbox.dirty, so next frame's + // root blit would skip the subtree. markDirty walks ancestors so the + // next frame descends. Done AFTER render so the clear-dirty at the end + // of renderNodeToOutput doesn't overwrite this. + const drainNode = getScrollDrainNode() + + if (drainNode) { + markDirty(drainNode) + } + + return { + absoluteOverlayMoved: didAbsoluteOverlayMove(), + scrollHint: options.altScreen ? getScrollHint() : null, + scrollDrainPending: drainNode !== null, + screen: renderedScreen, + viewport: { + width: terminalWidth, + // Alt screen: fake viewport.height = rows + 1 so that + // shouldClearScreen()'s `screen.height >= viewport.height` check + // (which treats exactly-filling content as "overflows" for + // scrollback purposes) never fires. Alt-screen content is always + // exactly `rows` tall (via ) but never + // scrolls — the cursor.y clamp below keeps the cursor-restore + // from emitting an LF. With the standard diff path, every frame + // is incremental; no fullResetSequence_CAUSES_FLICKER. + height: options.altScreen ? terminalRows + 1 : terminalRows + }, + cursor: { + x: 0, + // In the alt screen, keep the cursor inside the viewport. When + // screen.height === terminalRows exactly (content fills the alt + // screen), cursor.y = screen.height would trigger log-update's + // cursor-restore LF at the last row, scrolling one row off the top + // of the alt buffer and desyncing the diff's cursor model. The + // cursor is hidden so its position only matters for diff coords. + y: options.altScreen ? Math.max(0, Math.min(screen.height, terminalRows) - 1) : screen.height, + // Hide cursor when there's dynamic output to render (only in TTY mode) + visible: !isTTY || screen.height === 0 + } + } + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/root.ts b/ui-tui/packages/hermes-ink/src/ink/root.ts new file mode 100644 index 0000000000..27ace59a6b --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/root.ts @@ -0,0 +1,174 @@ +import { Stream } from 'stream' + +import type { ReactNode } from 'react' + +import { logForDebugging } from '../utils/debug.js' + +import type { FrameEvent } from './frame.js' +import Ink, { type Options as InkOptions } from './ink.js' +import instances from './instances.js' + +export type RenderOptions = { + /** + * Output stream where app will be rendered. + * + * @default process.stdout + */ + stdout?: NodeJS.WriteStream + /** + * Input stream where app will listen for input. + * + * @default process.stdin + */ + stdin?: NodeJS.ReadStream + /** + * Error stream. + * @default process.stderr + */ + stderr?: NodeJS.WriteStream + /** + * Configure whether Ink should listen to Ctrl+C keyboard input and exit the app. This is needed in case `process.stdin` is in raw mode, because then Ctrl+C is ignored by default and process is expected to handle it manually. + * + * @default true + */ + exitOnCtrlC?: boolean + + /** + * Patch console methods to ensure console output doesn't mix with Ink output. + * + * @default true + */ + patchConsole?: boolean + + /** + * Called after each frame render with timing and flicker information. + */ + onFrame?: (event: FrameEvent) => void +} + +export type Instance = { + /** + * Replace previous root node with a new one or update props of the current root node. + */ + rerender: Ink['render'] + /** + * Manually unmount the whole Ink app. + */ + unmount: Ink['unmount'] + /** + * Returns a promise, which resolves when app is unmounted. + */ + waitUntilExit: Ink['waitUntilExit'] + cleanup: () => void +} + +/** + * A managed Ink root, similar to react-dom's createRoot API. + * Separates instance creation from rendering so the same root + * can be reused for multiple sequential screens. + */ +export type Root = { + render: (node: ReactNode) => void + unmount: () => void + waitUntilExit: () => Promise +} + +/** + * Mount a component and render the output. + */ +export const renderSync = (node: ReactNode, options?: NodeJS.WriteStream | RenderOptions): Instance => { + const opts = getOptions(options) + + const inkOptions: InkOptions = { + stdout: process.stdout, + stdin: process.stdin, + stderr: process.stderr, + exitOnCtrlC: true, + patchConsole: true, + ...opts + } + + const instance: Ink = getInstance(inkOptions.stdout, () => new Ink(inkOptions)) + + instance.render(node) + + return { + rerender: instance.render, + unmount() { + instance.unmount() + }, + waitUntilExit: instance.waitUntilExit, + cleanup: () => instances.delete(inkOptions.stdout) + } +} + +const wrappedRender = async (node: ReactNode, options?: NodeJS.WriteStream | RenderOptions): Promise => { + // Preserve the microtask boundary that `await loadYoga()` used to provide. + // Without it, the first render fires synchronously before async startup work + // (e.g. useReplBridge notification state) settles, and the subsequent Static + // write overwrites scrollback instead of appending below the logo. + await Promise.resolve() + const instance = renderSync(node, options) + logForDebugging(`[render] first ink render: ${Math.round(process.uptime() * 1000)}ms since process start`) + + return instance +} + +export default wrappedRender + +/** + * Create an Ink root without rendering anything yet. + * Like react-dom's createRoot — call root.render() to mount a tree. + */ +export async function createRoot({ + stdout = process.stdout, + stdin = process.stdin, + stderr = process.stderr, + exitOnCtrlC = true, + patchConsole = true, + onFrame +}: RenderOptions = {}): Promise { + // See wrappedRender — preserve microtask boundary from the old WASM await. + await Promise.resolve() + + const instance = new Ink({ + stdout, + stdin, + stderr, + exitOnCtrlC, + patchConsole, + onFrame + }) + + // Register in the instances map so that code that looks up the Ink + // instance by stdout (e.g. external editor pause/resume) can find it. + instances.set(stdout, instance) + + return { + render: node => instance.render(node), + unmount: () => instance.unmount(), + waitUntilExit: () => instance.waitUntilExit() + } +} + +const getOptions = (stdout: NodeJS.WriteStream | RenderOptions | undefined = {}): RenderOptions => { + if (stdout instanceof Stream) { + return { + stdout, + stdin: process.stdin + } + } + + return stdout +} + +const getInstance = (stdout: NodeJS.WriteStream, createInstance: () => Ink): Ink => { + let instance = instances.get(stdout) + + if (!instance) { + instance = createInstance() + instances.set(stdout, instance) + } + + return instance +} diff --git a/ui-tui/packages/hermes-ink/src/ink/screen.ts b/ui-tui/packages/hermes-ink/src/ink/screen.ts new file mode 100644 index 0000000000..5a9b9df229 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/screen.ts @@ -0,0 +1,1543 @@ +import { type AnsiCode, ansiCodesToString, diffAnsiCodes } from '@alcalzone/ansi-tokenize' + +import { type Point, type Rectangle, type Size, unionRect } from './layout/geometry.js' +import { BEL, ESC, SEP } from './termio/ansi.js' +import * as warn from './warn.js' + +// --- Shared Pools (interning for memory efficiency) --- + +// Character string pool shared across all screens. +// With a shared pool, interned char IDs are valid across screens, +// so blitRegion can copy IDs directly (no re-interning) and +// diffEach can compare IDs as integers (no string lookup). +export class CharPool { + private strings: string[] = [' ', ''] // Index 0 = space, 1 = empty (spacer) + private stringMap = new Map([ + [' ', 0], + ['', 1] + ]) + private ascii: Int32Array = initCharAscii() // charCode → index, -1 = not interned + + intern(char: string): number { + // ASCII fast-path: direct array lookup instead of Map.get + if (char.length === 1) { + const code = char.charCodeAt(0) + + if (code < 128) { + const cached = this.ascii[code]! + + if (cached !== -1) { + return cached + } + + const index = this.strings.length + this.strings.push(char) + this.ascii[code] = index + + return index + } + } + + const existing = this.stringMap.get(char) + + if (existing !== undefined) { + return existing + } + + const index = this.strings.length + this.strings.push(char) + this.stringMap.set(char, index) + + return index + } + + get(index: number): string { + return this.strings[index] ?? ' ' + } +} + +// Hyperlink string pool shared across all screens. +// Index 0 = no hyperlink. +export class HyperlinkPool { + private strings: string[] = [''] // Index 0 = no hyperlink + private stringMap = new Map() + + intern(hyperlink: string | undefined): number { + if (!hyperlink) { + return 0 + } + + let id = this.stringMap.get(hyperlink) + + if (id === undefined) { + id = this.strings.length + this.strings.push(hyperlink) + this.stringMap.set(hyperlink, id) + } + + return id + } + + get(id: number): string | undefined { + return id === 0 ? undefined : this.strings[id] + } +} + +// SGR 7 (inverse) as an AnsiCode. endCode '\x1b[27m' flags VISIBLE_ON_SPACE +// so bit 0 of the resulting styleId is set → renderer won't skip inverted +// spaces as invisible. +const INVERSE_CODE: AnsiCode = { + type: 'ansi', + code: '\x1b[7m', + endCode: '\x1b[27m' +} + +// Bold (SGR 1) — stacks cleanly, no reflow in monospace. endCode 22 +// also cancels dim (SGR 2); harmless here since we never add dim. +const BOLD_CODE: AnsiCode = { + type: 'ansi', + code: '\x1b[1m', + endCode: '\x1b[22m' +} + +// Underline (SGR 4). Kept alongside yellow+bold — the underline is the +// unambiguous visible-on-any-theme marker. Yellow-bg-via-inverse can +// clash with existing bg colors (user-prompt style, tool chrome, syntax +// bg). If you see underline but no yellow, the yellow is being lost in +// the existing cell styling — the overlay IS finding the match. +const UNDERLINE_CODE: AnsiCode = { + type: 'ansi', + code: '\x1b[4m', + endCode: '\x1b[24m' +} + +// fg→yellow (SGR 33). With inverse already in the stack, the terminal +// swaps fg↔bg at render — so yellow-fg becomes yellow-BG. Original bg +// becomes fg (readable on most themes: dark-bg → dark-text on yellow). +// endCode 39 is 'default fg' — cancels any prior fg color cleanly. +const YELLOW_FG_CODE: AnsiCode = { + type: 'ansi', + code: '\x1b[33m', + endCode: '\x1b[39m' +} + +export class StylePool { + private ids = new Map() + private styles: AnsiCode[][] = [] + private transitionCache = new Map() + readonly none: number + + constructor() { + this.none = this.intern([]) + } + + /** + * Intern a style and return its ID. Bit 0 of the ID encodes whether the + * style has a visible effect on space characters (background, inverse, + * underline, etc.). Foreground-only styles get even IDs; styles visible + * on spaces get odd IDs. This lets the renderer skip invisible spaces + * with a single bitmask check on the packed word. + */ + intern(styles: AnsiCode[]): number { + const key = styles.length === 0 ? '' : styles.map(s => s.code).join('\0') + let id = this.ids.get(key) + + if (id === undefined) { + const rawId = this.styles.length + this.styles.push(styles.length === 0 ? [] : styles) + id = (rawId << 1) | (styles.length > 0 && hasVisibleSpaceEffect(styles) ? 1 : 0) + this.ids.set(key, id) + } + + return id + } + + /** Recover styles from an encoded ID. Strips the bit-0 flag via >>> 1. */ + get(id: number): AnsiCode[] { + return this.styles[id >>> 1] ?? [] + } + + /** + * Returns the pre-serialized ANSI string to transition from one style to + * another. Cached by (fromId, toId) — zero allocations after first call + * for a given pair. + */ + transition(fromId: number, toId: number): string { + if (fromId === toId) { + return '' + } + + const key = fromId * 0x100000 + toId + let str = this.transitionCache.get(key) + + if (str === undefined) { + str = ansiCodesToString(diffAnsiCodes(this.get(fromId), this.get(toId))) + this.transitionCache.set(key, str) + } + + return str + } + + /** + * Intern a style that is `base + inverse`. Cached by base ID so + * repeated calls for the same underlying style don't re-scan the + * AnsiCode[] array. Used by the selection overlay. + */ + private inverseCache = new Map() + withInverse(baseId: number): number { + let id = this.inverseCache.get(baseId) + + if (id === undefined) { + const baseCodes = this.get(baseId) + // If already inverted, use as-is (avoids SGR 7 stacking) + const hasInverse = baseCodes.some(c => c.endCode === '\x1b[27m') + id = hasInverse ? baseId : this.intern([...baseCodes, INVERSE_CODE]) + this.inverseCache.set(baseId, id) + } + + return id + } + + /** Inverse + bold + yellow-bg-via-fg-swap for the CURRENT search match. + * OTHER matches are plain inverse — bg inherits from the theme. Current + * gets a distinct yellow bg (via fg-then-inverse swap) plus bold weight + * so it stands out in a sea of inverse. Underline was too subtle. Zero + * reflow risk: all pure SGR overlays, per-cell, post-layout. The yellow + * overrides any existing fg (syntax highlighting) on those cells — fine, + * the "you are here" signal IS the point, syntax color can yield. */ + private currentMatchCache = new Map() + withCurrentMatch(baseId: number): number { + let id = this.currentMatchCache.get(baseId) + + if (id === undefined) { + const baseCodes = this.get(baseId) + + // Filter BOTH fg + bg so yellow-via-inverse is unambiguous. + // User-prompt cells have an explicit bg (grey box); with that bg + // still set, inverse swaps yellow-fg↔grey-bg → grey-on-yellow on + // SOME terminals, yellow-on-grey on others (inverse semantics vary + // when both colors are explicit). Filtering both gives clean + // yellow-bg + terminal-default-fg everywhere. Bold/dim/italic + // coexist — keep those. + const codes = baseCodes.filter(c => c.endCode !== '\x1b[39m' && c.endCode !== '\x1b[49m') + + // fg-yellow FIRST so inverse swaps it to bg. Bold after inverse is + // fine — SGR 1 is fg-attribute-only, order-independent vs 7. + codes.push(YELLOW_FG_CODE) + + if (!baseCodes.some(c => c.endCode === '\x1b[27m')) { + codes.push(INVERSE_CODE) + } + + if (!baseCodes.some(c => c.endCode === '\x1b[22m')) { + codes.push(BOLD_CODE) + } + + // Underline as the unambiguous marker — yellow-bg can clash with + // existing bg styling (user-prompt bg, syntax bg). If you see + // underline but no yellow on a match, the overlay IS finding it; + // the yellow is just losing a styling fight. + if (!baseCodes.some(c => c.endCode === '\x1b[24m')) { + codes.push(UNDERLINE_CODE) + } + + id = this.intern(codes) + this.currentMatchCache.set(baseId, id) + } + + return id + } + + /** + * Selection overlay: REPLACE the cell's background with a solid color + * while preserving its foreground (color, bold, italic, dim, underline). + * Matches native terminal selection — a dedicated bg color, not SGR-7 + * inverse. Inverse swaps fg/bg per-cell, which fragments visually over + * syntax-highlighted text (every fg color becomes a different bg stripe). + * + * Strips any existing bg (endCode 49m — REPLACES, so diff-added green + * etc. don't bleed through) and any existing inverse (endCode 27m — + * inverse on top of a solid bg would re-swap and look wrong). + * + * bg is set via setSelectionBg(); null → fallback to withInverse() so the + * overlay still works before theme wiring sets a color (tests, first frame). + * Cache is keyed by baseId only — setSelectionBg() clears it on change. + */ + private selectionBgCode: AnsiCode | null = null + private selectionBgCache = new Map() + setSelectionBg(bg: AnsiCode | null): void { + if (this.selectionBgCode?.code === bg?.code) { + return + } + + this.selectionBgCode = bg + this.selectionBgCache.clear() + } + withSelectionBg(baseId: number): number { + const bg = this.selectionBgCode + + if (bg === null) { + return this.withInverse(baseId) + } + + let id = this.selectionBgCache.get(baseId) + + if (id === undefined) { + // Keep everything except bg (49m) and inverse (27m). Fg, bold, dim, + // italic, underline, strikethrough all preserved. + const kept = this.get(baseId).filter(c => c.endCode !== '\x1b[49m' && c.endCode !== '\x1b[27m') + + kept.push(bg) + id = this.intern(kept) + this.selectionBgCache.set(baseId, id) + } + + return id + } +} + +// endCodes that produce visible effects on space characters +const VISIBLE_ON_SPACE = new Set([ + '\x1b[49m', // background color + '\x1b[27m', // inverse + '\x1b[24m', // underline + '\x1b[29m', // strikethrough + '\x1b[55m' // overline +]) + +function hasVisibleSpaceEffect(styles: AnsiCode[]): boolean { + for (const style of styles) { + if (VISIBLE_ON_SPACE.has(style.endCode)) { + return true + } + } + + return false +} + +/** + * Cell width classification for handling double-wide characters (CJK, emoji, + * etc.) + * + * We use explicit spacer cells rather than inferring width at render time. This + * makes the data structure self-describing and simplifies cursor positioning + * logic. + * + * @see https://mitchellh.com/writing/grapheme-clusters-in-terminals + */ +// const enum is inlined at compile time - no runtime object, no property access +export const enum CellWidth { + // Not a wide character, cell width 1 + Narrow = 0, + // Wide character, cell width 2. This cell contains the actual character. + Wide = 1, + // Spacer occupying the second visual column of a wide character. Do not render. + SpacerTail = 2, + // Spacer at the end of a soft-wrapped line indicating that a wide character + // continues on the next line. Used for preserving wide character semantics + // across line breaks during soft wrapping. + SpacerHead = 3 +} + +export type Hyperlink = string | undefined + +/** + * Cell is a view type returned by cellAt(). Cells are stored as packed typed + * arrays internally to avoid GC pressure from allocating objects per cell. + */ +export type Cell = { + char: string + styleId: number + width: CellWidth + hyperlink: Hyperlink +} + +// Constants for empty/spacer cells to enable fast comparisons +// These are indices into the charStrings table, not codepoints +const EMPTY_CHAR_INDEX = 0 // ' ' (space) +const SPACER_CHAR_INDEX = 1 // '' (empty string for spacer cells) +// Unwritten cells are [EMPTY_CHAR_INDEX=0, packWord1(emptyStyleId=0,0,0)=0]. +// Since StylePool.none is always 0 (first intern), unwritten cells are +// indistinguishable from explicitly-cleared cells in the packed array. +// This is intentional: diffEach can compare raw ints with zero normalization. +// isEmptyCellByIndex checks if both words are 0 to identify "never visually written" cells. + +function initCharAscii(): Int32Array { + const table = new Int32Array(128) + table.fill(-1) + table[32] = EMPTY_CHAR_INDEX // ' ' (space) + + return table +} + +// --- Packed cell layout --- +// Each cell is 2 consecutive Int32 elements in the cells array: +// word0 (cells[ci]): charId (full 32 bits) +// word1 (cells[ci + 1]): styleId[31:17] | hyperlinkId[16:2] | width[1:0] +const STYLE_SHIFT = 17 +const HYPERLINK_SHIFT = 2 +const HYPERLINK_MASK = 0x7fff // 15 bits +const WIDTH_MASK = 3 // 2 bits + +// Pack styleId, hyperlinkId, and width into a single Int32 +function packWord1(styleId: number, hyperlinkId: number, width: number): number { + return (styleId << STYLE_SHIFT) | (hyperlinkId << HYPERLINK_SHIFT) | width +} + +// Unwritten cell as BigInt64 — both words are 0, so the 64-bit value is 0n. +// Used by BigInt64Array.fill() for bulk clears (resetScreen, clearRegion). +// Not used for comparison — BigInt element reads cause heap allocation. +const EMPTY_CELL_VALUE = 0n + +/** + * Screen uses a packed Int32Array instead of Cell objects to eliminate GC + * pressure. For a 200x120 screen, this avoids allocating 24,000 objects. + * + * Cell data is stored as 2 Int32s per cell in a single contiguous array: + * word0: charId (full 32 bits — index into CharPool) + * word1: styleId[31:17] | hyperlinkId[16:2] | width[1:0] + * + * This layout halves memory accesses in diffEach (2 int loads vs 4) and + * enables future SIMD comparison via Bun.indexOfFirstDifference. + */ +export type Screen = Size & { + // Packed cell data — 2 Int32s per cell: [charId, packed(styleId|hyperlinkId|width)] + // cells and cells64 are views over the same ArrayBuffer. + cells: Int32Array + cells64: BigInt64Array // 1 BigInt64 per cell — used for bulk fill in resetScreen/clearRegion + + // Shared pools — IDs are valid across all screens using the same pools + charPool: CharPool + hyperlinkPool: HyperlinkPool + + // Empty style ID for comparisons + emptyStyleId: number + + /** + * Bounding box of cells that were written to (not blitted) during rendering. + * Used by diff() to limit iteration to only the region that could have changed. + */ + damage: Rectangle | undefined + + /** + * Per-cell noSelect bitmap — 1 byte per cell, 1 = exclude from text + * selection (copy + highlight). Used by to mark gutters + * (line numbers, diff sigils) so click-drag over a diff yields clean + * copyable code. Fully reset each frame in resetScreen; blitRegion + * copies it alongside cells so the blit optimization preserves marks. + */ + noSelect: Uint8Array + + /** + * Per-ROW soft-wrap continuation marker. softWrap[r]=N>0 means row r + * is a word-wrap continuation of row r-1 (the `\n` before it was + * inserted by wrapAnsi, not in the source), and row r-1's written + * content ends at absolute column N (exclusive — cells [0..N) are the + * fragment, past N is unwritten padding). 0 means row r is NOT a + * continuation (hard newline or first row). Selection copy checks + * softWrap[r]>0 to join row r onto row r-1 without a newline, and + * reads softWrap[r+1] to know row r's content end when row r+1 + * continues from it. The content-end column is needed because an + * unwritten cell and a written-unstyled-space are indistinguishable in + * the packed typed array (both all-zero) — without it we'd either drop + * the word-separator space (trim) or include trailing padding (no + * trim). This encoding (continuation-on-self, prev-content-end-here) + * is chosen so shiftRows preserves the is-continuation semantics: when + * row r scrolls off the top and row r+1 shifts to row r, sw[r] gets + * old sw[r+1] — which correctly says the new row r is a continuation + * of what's now in scrolledOffAbove. Reset each frame; copied by + * blitRegion/shiftRows. + */ + softWrap: Int32Array +} + +function isEmptyCellByIndex(screen: Screen, index: number): boolean { + // An empty/unwritten cell has both words === 0: + // word0 = EMPTY_CHAR_INDEX (0), word1 = packWord1(emptyStyleId=0, 0, 0) = 0. + const ci = index << 1 + + return screen.cells[ci] === 0 && screen.cells[ci | 1] === 0 +} + +export function isEmptyCellAt(screen: Screen, x: number, y: number): boolean { + if (x < 0 || y < 0 || x >= screen.width || y >= screen.height) { + return true + } + + return isEmptyCellByIndex(screen, y * screen.width + x) +} + +/** + * Check if a Cell (view object) represents an empty cell. + */ +export function isCellEmpty(screen: Screen, cell: Cell): boolean { + // Check if cell looks like an empty cell (space, empty style, narrow, no link). + // Note: After cellAt mapping, unwritten cells have emptyStyleId, so this + // returns true for both unwritten AND cleared cells. Use isEmptyCellAt + // for the internal distinction. + return cell.char === ' ' && cell.styleId === screen.emptyStyleId && cell.width === CellWidth.Narrow && !cell.hyperlink +} + +// Intern a hyperlink string and return its ID (0 = no hyperlink) +function internHyperlink(screen: Screen, hyperlink: Hyperlink): number { + return screen.hyperlinkPool.intern(hyperlink) +} + +// --- + +export function createScreen( + width: number, + height: number, + styles: StylePool, + charPool: CharPool, + hyperlinkPool: HyperlinkPool +): Screen { + // Warn if dimensions are not valid integers (likely bad yoga layout output) + warn.ifNotInteger(width, 'createScreen width') + warn.ifNotInteger(height, 'createScreen height') + + // Ensure width and height are valid integers to prevent crashes + if (!Number.isInteger(width) || width < 0) { + width = Math.max(0, Math.floor(width) || 0) + } + + if (!Number.isInteger(height) || height < 0) { + height = Math.max(0, Math.floor(height) || 0) + } + + const size = width * height + + // Allocate one buffer, two views: Int32Array for per-word access, + // BigInt64Array for bulk fill in resetScreen/clearRegion. + // ArrayBuffer is zero-filled, which is exactly the empty cell value: + // [EMPTY_CHAR_INDEX=0, packWord1(emptyStyleId=0,0,0)=0]. + const buf = new ArrayBuffer(size << 3) // 8 bytes per cell + const cells = new Int32Array(buf) + const cells64 = new BigInt64Array(buf) + + return { + width, + height, + cells, + cells64, + charPool, + hyperlinkPool, + emptyStyleId: styles.none, + damage: undefined, + noSelect: new Uint8Array(size), + softWrap: new Int32Array(height) + } +} + +/** + * Reset an existing screen for reuse, avoiding allocation of new typed arrays. + * Resizes if needed and clears all cells to empty/unwritten state. + * + * For double-buffering, this allows swapping between front and back buffers + * without allocating new Screen objects each frame. + */ +export function resetScreen(screen: Screen, width: number, height: number): void { + // Warn if dimensions are not valid integers + warn.ifNotInteger(width, 'resetScreen width') + warn.ifNotInteger(height, 'resetScreen height') + + // Ensure width and height are valid integers to prevent crashes + if (!Number.isInteger(width) || width < 0) { + width = Math.max(0, Math.floor(width) || 0) + } + + if (!Number.isInteger(height) || height < 0) { + height = Math.max(0, Math.floor(height) || 0) + } + + const size = width * height + + // Resize if needed (only grow, to avoid reallocations) + if (screen.cells64.length < size) { + const buf = new ArrayBuffer(size << 3) + screen.cells = new Int32Array(buf) + screen.cells64 = new BigInt64Array(buf) + screen.noSelect = new Uint8Array(size) + } + + if (screen.softWrap.length < height) { + screen.softWrap = new Int32Array(height) + } + + // Reset all cells — single fill call, no loop + screen.cells64.fill(EMPTY_CELL_VALUE, 0, size) + screen.noSelect.fill(0, 0, size) + screen.softWrap.fill(0, 0, height) + + // Update dimensions + screen.width = width + screen.height = height + + // Shared pools accumulate — no clearing needed. Unique char/hyperlink sets are bounded. + + // Clear damage tracking + screen.damage = undefined +} + +/** + * Re-intern a screen's char and hyperlink IDs into new pools. + * Used for generational pool reset — after migrating, the screen's + * typed arrays contain valid IDs for the new pools, and the old pools + * can be GC'd. + * + * O(width * height) but only called occasionally (e.g., between conversation turns). + */ +export function migrateScreenPools(screen: Screen, charPool: CharPool, hyperlinkPool: HyperlinkPool): void { + const oldCharPool = screen.charPool + const oldHyperlinkPool = screen.hyperlinkPool + + if (oldCharPool === charPool && oldHyperlinkPool === hyperlinkPool) { + return + } + + const size = screen.width * screen.height + const cells = screen.cells + + // Re-intern chars and hyperlinks in a single pass, stride by 2 + for (let ci = 0; ci < size << 1; ci += 2) { + // Re-intern charId (word0) + const oldCharId = cells[ci]! + cells[ci] = charPool.intern(oldCharPool.get(oldCharId)) + + // Re-intern hyperlinkId (packed in word1) + const word1 = cells[ci + 1]! + const oldHyperlinkId = (word1 >>> HYPERLINK_SHIFT) & HYPERLINK_MASK + + if (oldHyperlinkId !== 0) { + const oldStr = oldHyperlinkPool.get(oldHyperlinkId) + const newHyperlinkId = hyperlinkPool.intern(oldStr) + // Repack word1 with new hyperlinkId, preserving styleId and width + const styleId = word1 >>> STYLE_SHIFT + const width = word1 & WIDTH_MASK + cells[ci + 1] = packWord1(styleId, newHyperlinkId, width) + } + } + + screen.charPool = charPool + screen.hyperlinkPool = hyperlinkPool +} + +/** + * Get a Cell view at the given position. Returns a new object each call - + * this is intentional as cells are stored packed, not as objects. + */ +export function cellAt(screen: Screen, x: number, y: number): Cell | undefined { + if (x < 0 || y < 0 || x >= screen.width || y >= screen.height) { + return undefined + } + + return cellAtIndex(screen, y * screen.width + x) +} + +/** + * Get a Cell view by pre-computed array index. Skips bounds checks and + * index computation — caller must ensure index is valid. + */ +export function cellAtIndex(screen: Screen, index: number): Cell { + const ci = index << 1 + const word1 = screen.cells[ci + 1]! + const hid = (word1 >>> HYPERLINK_SHIFT) & HYPERLINK_MASK + + return { + // Unwritten cells have charIndex=0 (EMPTY_CHAR_INDEX); charPool.get(0) returns ' ' + char: screen.charPool.get(screen.cells[ci]!), + styleId: word1 >>> STYLE_SHIFT, + width: word1 & WIDTH_MASK, + hyperlink: hid === 0 ? undefined : screen.hyperlinkPool.get(hid) + } +} + +/** + * Get a Cell at the given index, or undefined if it has no visible content. + * Returns undefined for spacer cells (charId 1), empty unstyled spaces, and + * fg-only styled spaces that match lastRenderedStyleId (cursor-forward + * produces an identical visual result, avoiding a Cell allocation). + * + * @param lastRenderedStyleId - styleId of the last rendered cell on this + * line, or -1 if none yet. + */ +export function visibleCellAtIndex( + cells: Int32Array, + charPool: CharPool, + hyperlinkPool: HyperlinkPool, + index: number, + lastRenderedStyleId: number +): Cell | undefined { + const ci = index << 1 + const charId = cells[ci]! + + if (charId === 1) { + return undefined + } // spacer + + const word1 = cells[ci + 1]! + + // For spaces: 0x3fffc masks bits 2-17 (hyperlinkId + styleId visibility + // bit). If zero, the space has no hyperlink and at most a fg-only style. + // Then word1 >>> STYLE_SHIFT is the foreground style — skip if it's zero + // (truly invisible) or matches the last rendered style on this line. + if (charId === 0 && (word1 & 0x3fffc) === 0) { + const fgStyle = word1 >>> STYLE_SHIFT + + if (fgStyle === 0 || fgStyle === lastRenderedStyleId) { + return undefined + } + } + + const hid = (word1 >>> HYPERLINK_SHIFT) & HYPERLINK_MASK + + return { + char: charPool.get(charId), + styleId: word1 >>> STYLE_SHIFT, + width: word1 & WIDTH_MASK, + hyperlink: hid === 0 ? undefined : hyperlinkPool.get(hid) + } +} + +/** + * Write cell data into an existing Cell object to avoid allocation. + * Caller must ensure index is valid. + */ +function cellAtCI(screen: Screen, ci: number, out: Cell): void { + const w1 = ci | 1 + const word1 = screen.cells[w1]! + out.char = screen.charPool.get(screen.cells[ci]!) + out.styleId = word1 >>> STYLE_SHIFT + out.width = word1 & WIDTH_MASK + const hid = (word1 >>> HYPERLINK_SHIFT) & HYPERLINK_MASK + out.hyperlink = hid === 0 ? undefined : screen.hyperlinkPool.get(hid) +} + +export function charInCellAt(screen: Screen, x: number, y: number): string | undefined { + if (x < 0 || y < 0 || x >= screen.width || y >= screen.height) { + return undefined + } + + const ci = (y * screen.width + x) << 1 + + return screen.charPool.get(screen.cells[ci]!) +} + +/** + * Set a cell, optionally creating a spacer for wide characters. + * + * Wide characters (CJK, emoji) occupy 2 cells in the buffer: + * 1. First cell: Contains the actual character with width = Wide + * 2. Second cell: Spacer cell with width = SpacerTail (empty, not rendered) + * + * If the cell has width = Wide, this function automatically creates the + * corresponding SpacerTail in the next column. This two-cell model keeps + * the buffer aligned to visual columns, making cursor positioning + * straightforward. + * + * TODO: When soft-wrapping is implemented, SpacerHead cells will be explicitly + * placed by the wrapping logic at line-end positions where wide characters + * wrap to the next line. This function doesn't need to handle SpacerHead + * automatically - it will be set directly by the wrapping code. + */ +export function setCellAt(screen: Screen, x: number, y: number, cell: Cell): void { + if (x < 0 || y < 0 || x >= screen.width || y >= screen.height) { + return + } + + const ci = (y * screen.width + x) << 1 + const cells = screen.cells + + // When a Wide char is overwritten by a Narrow char, its SpacerTail remains + // as a ghost cell that the diff/render pipeline skips, causing stale content + // to leak through from previous frames. + const prevWidth = cells[ci + 1]! & WIDTH_MASK + + if (prevWidth === CellWidth.Wide && cell.width !== CellWidth.Wide) { + const spacerX = x + 1 + + if (spacerX < screen.width) { + const spacerCI = ci + 2 + + if ((cells[spacerCI + 1]! & WIDTH_MASK) === CellWidth.SpacerTail) { + cells[spacerCI] = EMPTY_CHAR_INDEX + cells[spacerCI + 1] = packWord1(screen.emptyStyleId, 0, CellWidth.Narrow) + } + } + } + + // Track cleared Wide position for damage expansion below + let clearedWideX = -1 + + if (prevWidth === CellWidth.SpacerTail && cell.width !== CellWidth.SpacerTail) { + // Overwriting a SpacerTail: clear the orphaned Wide char at (x-1). + // Keeping the wide character with Narrow width would cause the terminal + // to still render it with width 2, desyncing the cursor model. + if (x > 0) { + const wideCI = ci - 2 + + if ((cells[wideCI + 1]! & WIDTH_MASK) === CellWidth.Wide) { + cells[wideCI] = EMPTY_CHAR_INDEX + cells[wideCI + 1] = packWord1(screen.emptyStyleId, 0, CellWidth.Narrow) + clearedWideX = x - 1 + } + } + } + + // Pack cell data into cells array + cells[ci] = internCharString(screen, cell.char) + cells[ci + 1] = packWord1(cell.styleId, internHyperlink(screen, cell.hyperlink), cell.width) + + // Track damage - expand bounds in place instead of allocating new objects + // Include the main cell position and any cleared orphan cells + const minX = clearedWideX >= 0 ? Math.min(x, clearedWideX) : x + const damage = screen.damage + + if (damage) { + const right = damage.x + damage.width + const bottom = damage.y + damage.height + + if (minX < damage.x) { + damage.width += damage.x - minX + damage.x = minX + } else if (x >= right) { + damage.width = x - damage.x + 1 + } + + if (y < damage.y) { + damage.height += damage.y - y + damage.y = y + } else if (y >= bottom) { + damage.height = y - damage.y + 1 + } + } else { + screen.damage = { x: minX, y, width: x - minX + 1, height: 1 } + } + + // If this is a wide character, create a spacer in the next column + if (cell.width === CellWidth.Wide) { + const spacerX = x + 1 + + if (spacerX < screen.width) { + const spacerCI = ci + 2 + + // If the cell we're overwriting with our SpacerTail is itself Wide, + // clear ITS SpacerTail at x+2 too. Otherwise the orphan SpacerTail + // makes diffEach report it as `added` and log-update's skip-spacer + // rule prevents clearing whatever prev content was at that column. + // Scenario: [a, 💻, spacer] → [本, spacer, ORPHAN spacer] when + // yoga squishes a💻 to height 0 and 本 renders at the same y. + if ((cells[spacerCI + 1]! & WIDTH_MASK) === CellWidth.Wide) { + const orphanCI = spacerCI + 2 + + if (spacerX + 1 < screen.width && (cells[orphanCI + 1]! & WIDTH_MASK) === CellWidth.SpacerTail) { + cells[orphanCI] = EMPTY_CHAR_INDEX + cells[orphanCI + 1] = packWord1(screen.emptyStyleId, 0, CellWidth.Narrow) + } + } + + cells[spacerCI] = SPACER_CHAR_INDEX + cells[spacerCI + 1] = packWord1(screen.emptyStyleId, 0, CellWidth.SpacerTail) + + // Expand damage to include SpacerTail so diff() scans it + const d = screen.damage + + if (d && spacerX >= d.x + d.width) { + d.width = spacerX - d.x + 1 + } + } + } +} + +/** + * Replace the styleId of a cell in-place without disturbing char, width, + * or hyperlink. Preserves empty cells as-is (char stays ' '). Tracks damage + * for the cell so diffEach picks up the change. + */ +export function setCellStyleId(screen: Screen, x: number, y: number, styleId: number): void { + if (x < 0 || y < 0 || x >= screen.width || y >= screen.height) { + return + } + + const ci = (y * screen.width + x) << 1 + const cells = screen.cells + const word1 = cells[ci + 1]! + const width = word1 & WIDTH_MASK + + // Skip spacer cells — inverse on the head cell visually covers both columns + if (width === CellWidth.SpacerTail || width === CellWidth.SpacerHead) { + return + } + + const hid = (word1 >>> HYPERLINK_SHIFT) & HYPERLINK_MASK + cells[ci + 1] = packWord1(styleId, hid, width) + // Expand damage so diffEach scans this cell + const d = screen.damage + + if (d) { + screen.damage = unionRect(d, { x, y, width: 1, height: 1 }) + } else { + screen.damage = { x, y, width: 1, height: 1 } + } +} + +/** + * Intern a character string via the screen's shared CharPool. + * Supports grapheme clusters like family emoji. + */ +function internCharString(screen: Screen, char: string): number { + return screen.charPool.intern(char) +} + +/** + * Bulk-copy a rectangular region from src to dst using TypedArray.set(). + * Single cells.set() call per row (or one call for contiguous blocks). + * Damage is computed once for the whole region. + * + * Clamps negative regionX/regionY to 0 (matching clearRegion) — absolute- + * positioned overlays in tiny terminals can compute negative screen coords. + * maxX/maxY should already be clamped to both screen bounds by the caller. + */ +export function blitRegion( + dst: Screen, + src: Screen, + regionX: number, + regionY: number, + maxX: number, + maxY: number +): void { + regionX = Math.max(0, regionX) + regionY = Math.max(0, regionY) + + if (regionX >= maxX || regionY >= maxY) { + return + } + + const rowLen = maxX - regionX + const srcStride = src.width << 1 + const dstStride = dst.width << 1 + const rowBytes = rowLen << 1 // 2 Int32s per cell + const srcCells = src.cells + const dstCells = dst.cells + const srcNoSel = src.noSelect + const dstNoSel = dst.noSelect + + // softWrap is per-row — copy the row range regardless of stride/width. + // Partial-width blits still carry the row's wrap provenance since the + // blitted content (a cached ink-text node) is what set the bit. + dst.softWrap.set(src.softWrap.subarray(regionY, maxY), regionY) + + // Fast path: contiguous memory when copying full-width rows at same stride + if (regionX === 0 && maxX === src.width && src.width === dst.width) { + const srcStart = regionY * srcStride + const totalBytes = (maxY - regionY) * srcStride + dstCells.set( + srcCells.subarray(srcStart, srcStart + totalBytes), + srcStart // srcStart === dstStart when strides match and regionX === 0 + ) + // noSelect is 1 byte/cell vs cells' 8 — same region, different scale + const nsStart = regionY * src.width + const nsLen = (maxY - regionY) * src.width + dstNoSel.set(srcNoSel.subarray(nsStart, nsStart + nsLen), nsStart) + } else { + // Per-row copy for partial-width or mismatched-stride regions + let srcRowCI = regionY * srcStride + (regionX << 1) + let dstRowCI = regionY * dstStride + (regionX << 1) + let srcRowNS = regionY * src.width + regionX + let dstRowNS = regionY * dst.width + regionX + + for (let y = regionY; y < maxY; y++) { + dstCells.set(srcCells.subarray(srcRowCI, srcRowCI + rowBytes), dstRowCI) + dstNoSel.set(srcNoSel.subarray(srcRowNS, srcRowNS + rowLen), dstRowNS) + srcRowCI += srcStride + dstRowCI += dstStride + srcRowNS += src.width + dstRowNS += dst.width + } + } + + // Compute damage once for the whole region + const regionRect = { + x: regionX, + y: regionY, + width: rowLen, + height: maxY - regionY + } + + if (dst.damage) { + dst.damage = unionRect(dst.damage, regionRect) + } else { + dst.damage = regionRect + } + + // Handle wide char at right edge: spacer might be outside blit region + // but still within dst bounds. Per-row check only at the boundary column. + if (maxX < dst.width) { + let srcLastCI = (regionY * src.width + (maxX - 1)) << 1 + let dstSpacerCI = (regionY * dst.width + maxX) << 1 + let wroteSpacerOutsideRegion = false + + for (let y = regionY; y < maxY; y++) { + if ((srcCells[srcLastCI + 1]! & WIDTH_MASK) === CellWidth.Wide) { + dstCells[dstSpacerCI] = SPACER_CHAR_INDEX + dstCells[dstSpacerCI + 1] = packWord1(dst.emptyStyleId, 0, CellWidth.SpacerTail) + wroteSpacerOutsideRegion = true + } + + srcLastCI += srcStride + dstSpacerCI += dstStride + } + + // Expand damage to include SpacerTail column if we wrote any + if (wroteSpacerOutsideRegion && dst.damage) { + const rightEdge = dst.damage.x + dst.damage.width + + if (rightEdge === maxX) { + dst.damage = { ...dst.damage, width: dst.damage.width + 1 } + } + } + } +} + +/** + * Bulk-clear a rectangular region of the screen. + * Uses BigInt64Array.fill() for fast row clears. + * Handles wide character boundary cleanup at region edges. + */ +export function clearRegion( + screen: Screen, + regionX: number, + regionY: number, + regionWidth: number, + regionHeight: number +): void { + const startX = Math.max(0, regionX) + const startY = Math.max(0, regionY) + const maxX = Math.min(regionX + regionWidth, screen.width) + const maxY = Math.min(regionY + regionHeight, screen.height) + + if (startX >= maxX || startY >= maxY) { + return + } + + const cells = screen.cells + const cells64 = screen.cells64 + const screenWidth = screen.width + const rowBase = startY * screenWidth + let damageMinX = startX + let damageMaxX = maxX + + // EMPTY_CELL_VALUE (0n) matches the zero-initialized state: + // word0=EMPTY_CHAR_INDEX(0), word1=packWord1(0,0,0)=0 + if (startX === 0 && maxX === screenWidth) { + // Full-width: single fill, no boundary checks needed + cells64.fill(EMPTY_CELL_VALUE, rowBase, rowBase + (maxY - startY) * screenWidth) + } else { + // Partial-width: single loop handles boundary cleanup and fill per row. + const stride = screenWidth << 1 // 2 Int32s per cell + const rowLen = maxX - startX + const checkLeft = startX > 0 + const checkRight = maxX < screenWidth + let leftEdge = (rowBase + startX) << 1 + let rightEdge = (rowBase + maxX - 1) << 1 + let fillStart = rowBase + startX + + for (let y = startY; y < maxY; y++) { + // Left boundary: if cell at startX is a SpacerTail, the Wide char + // at startX-1 (outside the region) will be orphaned. Clear it. + if (checkLeft) { + // leftEdge points to word0 of cell at startX; +1 is its word1 + if ((cells[leftEdge + 1]! & WIDTH_MASK) === CellWidth.SpacerTail) { + // word1 of cell at startX-1 is leftEdge-1; word0 is leftEdge-2 + const prevW1 = leftEdge - 1 + + if ((cells[prevW1]! & WIDTH_MASK) === CellWidth.Wide) { + cells[prevW1 - 1] = EMPTY_CHAR_INDEX + cells[prevW1] = packWord1(screen.emptyStyleId, 0, CellWidth.Narrow) + damageMinX = startX - 1 + } + } + } + + // Right boundary: if cell at maxX-1 is Wide, its SpacerTail at maxX + // (outside the region) will be orphaned. Clear it. + if (checkRight) { + // rightEdge points to word0 of cell at maxX-1; +1 is its word1 + if ((cells[rightEdge + 1]! & WIDTH_MASK) === CellWidth.Wide) { + // word1 of cell at maxX is rightEdge+3 (+2 to next word0, +1 to word1) + const nextW1 = rightEdge + 3 + + if ((cells[nextW1]! & WIDTH_MASK) === CellWidth.SpacerTail) { + cells[nextW1 - 1] = EMPTY_CHAR_INDEX + cells[nextW1] = packWord1(screen.emptyStyleId, 0, CellWidth.Narrow) + damageMaxX = maxX + 1 + } + } + } + + cells64.fill(EMPTY_CELL_VALUE, fillStart, fillStart + rowLen) + leftEdge += stride + rightEdge += stride + fillStart += screenWidth + } + } + + // Update damage once for the whole region + const regionRect = { + x: damageMinX, + y: startY, + width: damageMaxX - damageMinX, + height: maxY - startY + } + + if (screen.damage) { + screen.damage = unionRect(screen.damage, regionRect) + } else { + screen.damage = regionRect + } +} + +/** + * Shift full-width rows within [top, bottom] (inclusive, 0-indexed) by n. + * n > 0 shifts UP (simulating CSI n S); n < 0 shifts DOWN (CSI n T). + * Vacated rows are cleared. Does NOT update damage. Both cells and the + * noSelect bitmap are shifted so text-selection markers stay aligned when + * this is applied to next.screen during scroll fast path. + */ +export function shiftRows(screen: Screen, top: number, bottom: number, n: number): void { + if (n === 0 || top < 0 || bottom >= screen.height || top > bottom) { + return + } + + const w = screen.width + const cells64 = screen.cells64 + const noSel = screen.noSelect + const sw = screen.softWrap + const absN = Math.abs(n) + + if (absN > bottom - top) { + cells64.fill(EMPTY_CELL_VALUE, top * w, (bottom + 1) * w) + noSel.fill(0, top * w, (bottom + 1) * w) + sw.fill(0, top, bottom + 1) + + return + } + + if (n > 0) { + // SU: row top+n..bottom → top..bottom-n; clear bottom-n+1..bottom + cells64.copyWithin(top * w, (top + n) * w, (bottom + 1) * w) + noSel.copyWithin(top * w, (top + n) * w, (bottom + 1) * w) + sw.copyWithin(top, top + n, bottom + 1) + cells64.fill(EMPTY_CELL_VALUE, (bottom - n + 1) * w, (bottom + 1) * w) + noSel.fill(0, (bottom - n + 1) * w, (bottom + 1) * w) + sw.fill(0, bottom - n + 1, bottom + 1) + } else { + // SD: row top..bottom+n → top-n..bottom; clear top..top-n-1 + cells64.copyWithin((top - n) * w, top * w, (bottom + n + 1) * w) + noSel.copyWithin((top - n) * w, top * w, (bottom + n + 1) * w) + sw.copyWithin(top - n, top, bottom + n + 1) + cells64.fill(EMPTY_CELL_VALUE, top * w, (top - n) * w) + noSel.fill(0, top * w, (top - n) * w) + sw.fill(0, top, top - n) + } +} + +// Matches OSC 8 ; ; URI BEL +const OSC8_REGEX = new RegExp(`^${ESC}\\]8${SEP}${SEP}([^${BEL}]*)${BEL}$`) +// OSC8 prefix: ESC ] 8 ; — cheap check to skip regex for the vast majority of styles (SGR = ESC [) +export const OSC8_PREFIX = `${ESC}]8${SEP}` + +export function extractHyperlinkFromStyles(styles: AnsiCode[]): Hyperlink | null { + for (const style of styles) { + const code = style.code + + if (code.length < 5 || !code.startsWith(OSC8_PREFIX)) { + continue + } + + const match = code.match(OSC8_REGEX) + + if (match) { + return match[1] || null + } + } + + return null +} + +export function filterOutHyperlinkStyles(styles: AnsiCode[]): AnsiCode[] { + return styles.filter(style => !style.code.startsWith(OSC8_PREFIX) || !OSC8_REGEX.test(style.code)) +} + +// --- + +/** + * Returns an array of all changes between two screens. Used by tests. + * Production code should use diffEach() to avoid allocations. + */ +export function diff(prev: Screen, next: Screen): [point: Point, removed: Cell | undefined, added: Cell | undefined][] { + const output: [Point, Cell | undefined, Cell | undefined][] = [] + diffEach(prev, next, (x, y, removed, added) => { + // Copy cells since diffEach reuses the objects + output.push([{ x, y }, removed ? { ...removed } : undefined, added ? { ...added } : undefined]) + }) + + return output +} + +type DiffCallback = (x: number, y: number, removed: Cell | undefined, added: Cell | undefined) => boolean | void + +/** + * Like diff(), but calls a callback for each change instead of building an array. + * Reuses two Cell objects to avoid per-change allocations. The callback must not + * retain references to the Cell objects — their contents are overwritten each call. + * + * Returns true if the callback ever returned true (early exit signal). + */ +export function diffEach(prev: Screen, next: Screen, cb: DiffCallback): boolean { + const prevWidth = prev.width + const nextWidth = next.width + const prevHeight = prev.height + const nextHeight = next.height + + let region: Rectangle + + if (prevWidth === 0 && prevHeight === 0) { + region = { x: 0, y: 0, width: nextWidth, height: nextHeight } + } else if (next.damage) { + region = next.damage + + if (prev.damage) { + region = unionRect(region, prev.damage) + } + } else if (prev.damage) { + region = prev.damage + } else { + region = { x: 0, y: 0, width: 0, height: 0 } + } + + if (prevHeight > nextHeight) { + region = unionRect(region, { + x: 0, + y: nextHeight, + width: prevWidth, + height: prevHeight - nextHeight + }) + } + + if (prevWidth > nextWidth) { + region = unionRect(region, { + x: nextWidth, + y: 0, + width: prevWidth - nextWidth, + height: prevHeight + }) + } + + const maxHeight = Math.max(prevHeight, nextHeight) + const maxWidth = Math.max(prevWidth, nextWidth) + const endY = Math.min(region.y + region.height, maxHeight) + const endX = Math.min(region.x + region.width, maxWidth) + + if (prevWidth === nextWidth) { + return diffSameWidth(prev, next, region.x, endX, region.y, endY, cb) + } + + return diffDifferentWidth(prev, next, region.x, endX, region.y, endY, cb) +} + +/** + * Scan for the next cell that differs between two Int32Arrays. + * Returns the number of matching cells before the first difference, + * or `count` if all cells match. Tiny and pure for JIT inlining. + */ +function findNextDiff(a: Int32Array, b: Int32Array, w0: number, count: number): number { + for (let i = 0; i < count; i++, w0 += 2) { + const w1 = w0 | 1 + + if (a[w0] !== b[w0] || a[w1] !== b[w1]) { + return i + } + } + + return count +} + +/** + * Diff one row where both screens are in bounds. + * Scans for differences with findNextDiff, unpacks and calls cb for each. + */ +function diffRowBoth( + prevCells: Int32Array, + nextCells: Int32Array, + prev: Screen, + next: Screen, + ci: number, + y: number, + startX: number, + endX: number, + prevCell: Cell, + nextCell: Cell, + cb: DiffCallback +): boolean { + let x = startX + + while (x < endX) { + const skip = findNextDiff(prevCells, nextCells, ci, endX - x) + x += skip + ci += skip << 1 + + if (x >= endX) { + break + } + + cellAtCI(prev, ci, prevCell) + cellAtCI(next, ci, nextCell) + + if (cb(x, y, prevCell, nextCell)) { + return true + } + + x++ + ci += 2 + } + + return false +} + +/** + * Emit removals for a row that only exists in prev (height shrank). + * Cannot skip empty cells — the terminal still has content from the + * previous frame that needs to be cleared. + */ +function diffRowRemoved( + prev: Screen, + ci: number, + y: number, + startX: number, + endX: number, + prevCell: Cell, + cb: DiffCallback +): boolean { + for (let x = startX; x < endX; x++, ci += 2) { + cellAtCI(prev, ci, prevCell) + + if (cb(x, y, prevCell, undefined)) { + return true + } + } + + return false +} + +/** + * Emit additions for a row that only exists in next (height grew). + * Skips empty/unwritten cells. + */ +function diffRowAdded( + nextCells: Int32Array, + next: Screen, + ci: number, + y: number, + startX: number, + endX: number, + nextCell: Cell, + cb: DiffCallback +): boolean { + for (let x = startX; x < endX; x++, ci += 2) { + if (nextCells[ci] === 0 && nextCells[ci | 1] === 0) { + continue + } + + cellAtCI(next, ci, nextCell) + + if (cb(x, y, undefined, nextCell)) { + return true + } + } + + return false +} + +/** + * Diff two screens with identical width. + * Dispatches each row to a small, JIT-friendly function. + */ +function diffSameWidth( + prev: Screen, + next: Screen, + startX: number, + endX: number, + startY: number, + endY: number, + cb: DiffCallback +): boolean { + const prevCells = prev.cells + const nextCells = next.cells + const width = prev.width + const prevHeight = prev.height + const nextHeight = next.height + const stride = width << 1 + + const prevCell: Cell = { + char: ' ', + styleId: 0, + width: CellWidth.Narrow, + hyperlink: undefined + } + + const nextCell: Cell = { + char: ' ', + styleId: 0, + width: CellWidth.Narrow, + hyperlink: undefined + } + + const rowEndX = Math.min(endX, width) + let rowCI = (startY * width + startX) << 1 + + for (let y = startY; y < endY; y++) { + const prevIn = y < prevHeight + const nextIn = y < nextHeight + + if (prevIn && nextIn) { + if (diffRowBoth(prevCells, nextCells, prev, next, rowCI, y, startX, rowEndX, prevCell, nextCell, cb)) { + return true + } + } else if (prevIn) { + if (diffRowRemoved(prev, rowCI, y, startX, rowEndX, prevCell, cb)) { + return true + } + } else if (nextIn) { + if (diffRowAdded(nextCells, next, rowCI, y, startX, rowEndX, nextCell, cb)) { + return true + } + } + + rowCI += stride + } + + return false +} + +/** + * Fallback: diff two screens with different widths (resize). + * Separate indices for prev and next cells arrays. + */ +function diffDifferentWidth( + prev: Screen, + next: Screen, + startX: number, + endX: number, + startY: number, + endY: number, + cb: DiffCallback +): boolean { + const prevWidth = prev.width + const nextWidth = next.width + const prevCells = prev.cells + const nextCells = next.cells + + const prevCell: Cell = { + char: ' ', + styleId: 0, + width: CellWidth.Narrow, + hyperlink: undefined + } + + const nextCell: Cell = { + char: ' ', + styleId: 0, + width: CellWidth.Narrow, + hyperlink: undefined + } + + const prevStride = prevWidth << 1 + const nextStride = nextWidth << 1 + let prevRowCI = (startY * prevWidth + startX) << 1 + let nextRowCI = (startY * nextWidth + startX) << 1 + + for (let y = startY; y < endY; y++) { + const prevIn = y < prev.height + const nextIn = y < next.height + const prevEndX = prevIn ? Math.min(endX, prevWidth) : startX + const nextEndX = nextIn ? Math.min(endX, nextWidth) : startX + const bothEndX = Math.min(prevEndX, nextEndX) + + let prevCI = prevRowCI + let nextCI = nextRowCI + + for (let x = startX; x < bothEndX; x++) { + if (prevCells[prevCI] === nextCells[nextCI] && prevCells[prevCI + 1] === nextCells[nextCI + 1]) { + prevCI += 2 + nextCI += 2 + + continue + } + + cellAtCI(prev, prevCI, prevCell) + cellAtCI(next, nextCI, nextCell) + prevCI += 2 + nextCI += 2 + + if (cb(x, y, prevCell, nextCell)) { + return true + } + } + + if (prevEndX > bothEndX) { + prevCI = prevRowCI + ((bothEndX - startX) << 1) + + for (let x = bothEndX; x < prevEndX; x++) { + cellAtCI(prev, prevCI, prevCell) + prevCI += 2 + + if (cb(x, y, prevCell, undefined)) { + return true + } + } + } + + if (nextEndX > bothEndX) { + nextCI = nextRowCI + ((bothEndX - startX) << 1) + + for (let x = bothEndX; x < nextEndX; x++) { + if (nextCells[nextCI] === 0 && nextCells[nextCI | 1] === 0) { + nextCI += 2 + + continue + } + + cellAtCI(next, nextCI, nextCell) + nextCI += 2 + + if (cb(x, y, undefined, nextCell)) { + return true + } + } + } + + prevRowCI += prevStride + nextRowCI += nextStride + } + + return false +} + +/** + * Mark a rectangular region as noSelect (exclude from text selection). + * Clamps to screen bounds. Called from output.ts when a box + * renders. No damage tracking — noSelect doesn't affect terminal output, + * only getSelectedText/applySelectionOverlay which read it directly. + */ +export function markNoSelectRegion(screen: Screen, x: number, y: number, width: number, height: number): void { + const maxX = Math.min(x + width, screen.width) + const maxY = Math.min(y + height, screen.height) + const noSel = screen.noSelect + const stride = screen.width + + for (let row = Math.max(0, y); row < maxY; row++) { + const rowStart = row * stride + noSel.fill(1, rowStart + Math.max(0, x), rowStart + maxX) + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/searchHighlight.ts b/ui-tui/packages/hermes-ink/src/ink/searchHighlight.ts new file mode 100644 index 0000000000..278c3fd63c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/searchHighlight.ts @@ -0,0 +1,91 @@ +import { cellAtIndex, CellWidth, type Screen, setCellStyleId, type StylePool } from './screen.js' + +/** + * Highlight all visible occurrences of `query` in the screen buffer by + * inverting cell styles (SGR 7). Post-render, same damage-tracking machinery + * as applySelectionOverlay — the diff picks up highlighted cells as ordinary + * changes, LogUpdate stays a pure diff engine. + * + * Case-insensitive. Handles wide characters (CJK, emoji) by building a + * col-of-char map per row — the Nth character isn't at col N when wide chars + * are present (each occupies 2 cells: head + SpacerTail). + * + * This ONLY inverts — there is no "current match" logic here. The yellow + * current-match overlay is handled separately by applyPositionedHighlight + * (render-to-screen.ts), which writes on top using positions scanned from + * the target message's DOM subtree. + * + * Returns true if any match was highlighted (damage gate — caller forces + * full-frame damage when true). + */ +export function applySearchHighlight(screen: Screen, query: string, stylePool: StylePool): boolean { + if (!query) { + return false + } + + const lq = query.toLowerCase() + const qlen = lq.length + const w = screen.width + const noSelect = screen.noSelect + const height = screen.height + + let applied = false + + for (let row = 0; row < height; row++) { + const rowOff = row * w + // Build row text (already lowercased) + code-unit→cell-index map. + // Three skip conditions, all aligned with setCellStyleId / + // extractRowText (selection.ts): + // - SpacerTail: 2nd cell of a wide char, no char of its own + // - SpacerHead: end-of-line padding when a wide char wraps + // - noSelect: gutters (⎿, line numbers) — same exclusion as + // applySelectionOverlay. "Highlight what you see" still holds for + // content; gutters aren't search targets. + // Lowercasing per-char (not on the joined string at the end) means + // codeUnitToCell maps positions in the LOWERCASED text — U+0130 + // (Turkish İ) lowercases to 2 code units, so lowering the joined + // string would desync indexOf positions from the map. + let text = '' + const colOf: number[] = [] + const codeUnitToCell: number[] = [] + + for (let col = 0; col < w; col++) { + const idx = rowOff + col + const cell = cellAtIndex(screen, idx) + + if (cell.width === CellWidth.SpacerTail || cell.width === CellWidth.SpacerHead || noSelect[idx] === 1) { + continue + } + + const lc = cell.char.toLowerCase() + const cellIdx = colOf.length + + for (let i = 0; i < lc.length; i++) { + codeUnitToCell.push(cellIdx) + } + + text += lc + colOf.push(col) + } + + let pos = text.indexOf(lq) + + while (pos >= 0) { + applied = true + const startCi = codeUnitToCell[pos]! + const endCi = codeUnitToCell[pos + qlen - 1]! + + for (let ci = startCi; ci <= endCi; ci++) { + const col = colOf[ci]! + const cell = cellAtIndex(screen, rowOff + col) + setCellStyleId(screen, col, row, stylePool.withInverse(cell.styleId)) + } + + // Non-overlapping advance (less/vim/grep/Ctrl+F). pos+1 would find + // 'aa' at 0 AND 1 in 'aaa' → double-invert cell 1. + pos = text.indexOf(lq, pos + qlen) + } + } + + return applied +} diff --git a/ui-tui/packages/hermes-ink/src/ink/selection.ts b/ui-tui/packages/hermes-ink/src/ink/selection.ts new file mode 100644 index 0000000000..9ee71564e6 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/selection.ts @@ -0,0 +1,1070 @@ +/** + * Text selection state for fullscreen mode. + * + * Tracks a linear selection in screen-buffer coordinates (0-indexed col/row). + * Selection is line-based: cells from (startCol, startRow) through + * (endCol, endRow) inclusive, wrapping across line boundaries. This matches + * terminal-native selection behavior (not rectangular/block). + * + * The selection is stored as ANCHOR (where the drag started) + FOCUS (where + * the cursor is now). The rendered highlight normalizes to start ≤ end. + */ + +import { clamp } from './layout/geometry.js' +import type { Screen, StylePool } from './screen.js' +import { cellAt, cellAtIndex, CellWidth, setCellStyleId } from './screen.js' + +type Point = { col: number; row: number } + +export type SelectionState = { + /** Where the mouse-down occurred. Null when no selection. */ + anchor: Point | null + /** Current drag position (updated on mouse-move while dragging). */ + focus: Point | null + /** True between mouse-down and mouse-up. */ + isDragging: boolean + /** For word/line mode: the initial word/line bounds from the first + * multi-click. Drag extends from this span to the word/line at the + * current mouse position so the original word/line stays selected + * even when dragging backward past it. Null ⇔ char mode. The kind + * tells extendSelection whether to snap to word or line boundaries. */ + anchorSpan: { lo: Point; hi: Point; kind: 'word' | 'line' } | null + /** Text from rows that scrolled out ABOVE the viewport during + * drag-to-scroll. The screen buffer only holds the current viewport, + * so without this accumulator, dragging down past the bottom edge + * loses the top of the selection once the anchor clamps. Prepended + * to the on-screen text by getSelectedText. Reset on start/clear. */ + scrolledOffAbove: string[] + /** Symmetric: rows scrolled out BELOW when dragging up. Appended. */ + scrolledOffBelow: string[] + /** Soft-wrap bits parallel to scrolledOffAbove — true means the row + * is a continuation of the one before it (the `\n` was inserted by + * word-wrap, not in the source). Captured alongside the text at + * scroll time since the screen's softWrap bitmap shifts with content. + * getSelectedText uses these to join wrapped rows back into logical + * lines. */ + scrolledOffAboveSW: boolean[] + /** Parallel to scrolledOffBelow. */ + scrolledOffBelowSW: boolean[] + /** Pre-clamp anchor row. Set when shiftSelection clamps anchor so a + * reverse scroll can restore the true position and pop accumulators. + * Without this, PgDn (clamps anchor) → PgUp leaves anchor at the wrong + * row AND scrolledOffAbove stale — highlight ≠ copy. Undefined when + * anchor is in-bounds (no clamp debt). Cleared on start/clear. */ + virtualAnchorRow?: number + /** Same for focus. */ + virtualFocusRow?: number + /** True if the mouse-down that started this selection had the alt + * modifier set (SGR button bit 0x08). On macOS xterm.js this is a + * signal that VS Code's macOptionClickForcesSelection is OFF — if it + * were on, xterm.js would have consumed the event for native selection + * and we'd never receive it. Used by the footer to show the right hint. */ + lastPressHadAlt: boolean +} + +export function createSelectionState(): SelectionState { + return { + anchor: null, + focus: null, + isDragging: false, + anchorSpan: null, + scrolledOffAbove: [], + scrolledOffBelow: [], + scrolledOffAboveSW: [], + scrolledOffBelowSW: [], + lastPressHadAlt: false + } +} + +export function startSelection(s: SelectionState, col: number, row: number): void { + s.anchor = { col, row } + // Focus is not set until the first drag motion. A click-release with no + // drag leaves focus null → hasSelection/selectionBounds return false/null + // via the `!s.focus` check, so a bare click never highlights a cell. + s.focus = null + s.isDragging = true + s.anchorSpan = null + s.scrolledOffAbove = [] + s.scrolledOffBelow = [] + s.scrolledOffAboveSW = [] + s.scrolledOffBelowSW = [] + s.virtualAnchorRow = undefined + s.virtualFocusRow = undefined + s.lastPressHadAlt = false +} + +export function updateSelection(s: SelectionState, col: number, row: number): void { + if (!s.isDragging) { + return + } + + // First motion at the same cell as anchor is a no-op. Terminals in mode + // 1002 can fire a drag event at the anchor cell (sub-pixel tremor, or a + // motion-release pair). Setting focus here would turn a bare click into + // a 1-cell selection and clobber the clipboard via useCopyOnSelect. Once + // focus is set (real drag), we track normally including back to anchor. + if (!s.focus && s.anchor && s.anchor.col === col && s.anchor.row === row) { + return + } + + s.focus = { col, row } +} + +export function finishSelection(s: SelectionState): void { + s.isDragging = false + // Keep anchor/focus so highlight stays visible and text can be copied. + // Clear via clearSelection() on Esc or after copy. +} + +export function clearSelection(s: SelectionState): void { + s.anchor = null + s.focus = null + s.isDragging = false + s.anchorSpan = null + s.scrolledOffAbove = [] + s.scrolledOffBelow = [] + s.scrolledOffAboveSW = [] + s.scrolledOffBelowSW = [] + s.virtualAnchorRow = undefined + s.virtualFocusRow = undefined + s.lastPressHadAlt = false +} + +// Unicode-aware word character matcher: letters (any script), digits, +// and the punctuation set iTerm2 treats as word-part by default. +// Matching iTerm2's default means double-clicking a path like +// which is the muscle memory most macOS terminal users have. +// iTerm2 default "characters considered part of a word": /-+\~_. +const WORD_CHAR = /[\p{L}\p{N}_/.\-+~\\]/u + +/** + * Character class for double-click word-expansion. Cells with the same + * class as the clicked cell are included in the selection; a class change + * is a boundary. Matches typical terminal-emulator behavior (iTerm2 etc.): + * double-click on `foo` selects `foo`, on `->` selects `->`, on spaces + * selects the whitespace run. + */ +function charClass(c: string): 0 | 1 | 2 { + if (c === ' ' || c === '') { + return 0 + } + + if (WORD_CHAR.test(c)) { + return 1 + } + + return 2 +} + +/** + * Find the bounds of the same-class character run at (col, row). Returns + * null if the click is out of bounds or lands on a noSelect cell. Used by + * selectWordAt (initial double-click) and extendWordSelection (drag). + */ +function wordBoundsAt(screen: Screen, col: number, row: number): { lo: number; hi: number } | null { + if (row < 0 || row >= screen.height) { + return null + } + + const width = screen.width + const noSelect = screen.noSelect + const rowOff = row * width + + // If the click landed on the spacer tail of a wide char, step back to + // the head so the class check sees the actual grapheme. + let c = col + + if (c > 0) { + const cell = cellAt(screen, c, row) + + if (cell && cell.width === CellWidth.SpacerTail) { + c -= 1 + } + } + + if (c < 0 || c >= width || noSelect[rowOff + c] === 1) { + return null + } + + const startCell = cellAt(screen, c, row) + + if (!startCell) { + return null + } + + const cls = charClass(startCell.char) + + // Expand left: include cells of the same class, stop at noSelect or + // class change. SpacerTail cells are stepped over (the wide-char head + // at the preceding column determines the class). + let lo = c + + while (lo > 0) { + const prev = lo - 1 + + if (noSelect[rowOff + prev] === 1) { + break + } + + const pc = cellAt(screen, prev, row) + + if (!pc) { + break + } + + if (pc.width === CellWidth.SpacerTail) { + // Step over the spacer to the wide-char head + if (prev === 0 || noSelect[rowOff + prev - 1] === 1) { + break + } + + const head = cellAt(screen, prev - 1, row) + + if (!head || charClass(head.char) !== cls) { + break + } + + lo = prev - 1 + + continue + } + + if (charClass(pc.char) !== cls) { + break + } + + lo = prev + } + + // Expand right: same logic, skipping spacer tails. + let hi = c + + while (hi < width - 1) { + const next = hi + 1 + + if (noSelect[rowOff + next] === 1) { + break + } + + const nc = cellAt(screen, next, row) + + if (!nc) { + break + } + + if (nc.width === CellWidth.SpacerTail) { + // Include the spacer tail in the selection range (it belongs to + // the wide char at hi) and continue past it. + hi = next + + continue + } + + if (charClass(nc.char) !== cls) { + break + } + + hi = next + } + + return { lo, hi } +} + +/** -1 if a < b, 1 if a > b, 0 if equal (reading order: row then col). */ +function comparePoints(a: Point, b: Point): number { + if (a.row !== b.row) { + return a.row < b.row ? -1 : 1 + } + + if (a.col !== b.col) { + return a.col < b.col ? -1 : 1 + } + + return 0 +} + +/** + * Select the word at (col, row) by scanning the screen buffer for the + * bounds of the same-class character run. Mutates the selection in place. + * No-op if the click is out of bounds or lands on a noSelect cell. + * Sets isDragging=true and anchorSpan so a subsequent drag extends the + * selection word-by-word (native macOS behavior). + */ +export function selectWordAt(s: SelectionState, screen: Screen, col: number, row: number): void { + const b = wordBoundsAt(screen, col, row) + + if (!b) { + return + } + + const lo = { col: b.lo, row } + const hi = { col: b.hi, row } + s.anchor = lo + s.focus = hi + s.isDragging = true + s.anchorSpan = { lo, hi, kind: 'word' } +} + +// Printable ASCII minus terminal URL delimiters. Restricting to single- +// codeunit ASCII keeps cell-count === string-index, so the column-span +// check below is exact (no wide-char/grapheme drift). +const URL_BOUNDARY = new Set([...'<>"\'` ']) + +function isUrlChar(c: string): boolean { + if (c.length !== 1) { + return false + } + + const code = c.charCodeAt(0) + + return code >= 0x21 && code <= 0x7e && !URL_BOUNDARY.has(c) +} + +/** + * Scan the screen buffer for a plain-text URL at (col, row). Mirrors the + * terminal's native Cmd+Click URL detection, which fullscreen mode's mouse + * tracking intercepts. Called from getHyperlinkAt as a fallback when the + * cell has no OSC 8 hyperlink. + */ +export function findPlainTextUrlAt(screen: Screen, col: number, row: number): string | undefined { + if (row < 0 || row >= screen.height) { + return undefined + } + + const width = screen.width + const noSelect = screen.noSelect + const rowOff = row * width + + let c = col + + if (c > 0) { + const cell = cellAt(screen, c, row) + + if (cell && cell.width === CellWidth.SpacerTail) { + c -= 1 + } + } + + if (c < 0 || c >= width || noSelect[rowOff + c] === 1) { + return undefined + } + + const startCell = cellAt(screen, c, row) + + if (!startCell || !isUrlChar(startCell.char)) { + return undefined + } + + // Expand left/right to the bounds of the URL-char run. URLs are ASCII + // (CellWidth.Narrow, 1 codeunit), so hitting a non-ASCII/wide/spacer + // cell is a boundary — no need to step over spacers like wordBoundsAt. + let lo = c + + while (lo > 0) { + const prev = lo - 1 + + if (noSelect[rowOff + prev] === 1) { + break + } + + const pc = cellAt(screen, prev, row) + + if (!pc || pc.width !== CellWidth.Narrow || !isUrlChar(pc.char)) { + break + } + + lo = prev + } + + let hi = c + + while (hi < width - 1) { + const next = hi + 1 + + if (noSelect[rowOff + next] === 1) { + break + } + + const nc = cellAt(screen, next, row) + + if (!nc || nc.width !== CellWidth.Narrow || !isUrlChar(nc.char)) { + break + } + + hi = next + } + + let token = '' + + for (let i = lo; i <= hi; i++) { + token += cellAt(screen, i, row)!.char + } + + // 1 cell = 1 char across [lo, hi] (ASCII-only run), so string index = + // column offset. Find the last scheme anchor at or before the click — + // a run like `https://a.com,https://b.com` has two, and clicking the + // second should return the second URL, not the greedy match of both. + const clickIdx = c - lo + const schemeRe = /(?:https?|file):\/\//g + let urlStart = -1 + let urlEnd = token.length + + for (let m; (m = schemeRe.exec(token)); ) { + if (m.index > clickIdx) { + urlEnd = m.index + + break + } + + urlStart = m.index + } + + if (urlStart < 0) { + return undefined + } + + let url = token.slice(urlStart, urlEnd) + + // Strip trailing sentence punctuation. For closers () ] }, only strip + // if unbalanced — `/wiki/Foo_(bar)` keeps `)`, `/arr[0]` keeps `]`. + const OPENER: Record = { ')': '(', ']': '[', '}': '{' } + + while (url.length > 0) { + const last = url.at(-1)! + + if ('.,;:!?'.includes(last)) { + url = url.slice(0, -1) + + continue + } + + const opener = OPENER[last] + + if (!opener) { + break + } + + let opens = 0 + let closes = 0 + + for (let i = 0; i < url.length; i++) { + const ch = url.charAt(i) + + if (ch === opener) { + opens++ + } else if (ch === last) { + closes++ + } + } + + if (closes > opens) { + url = url.slice(0, -1) + } else { + break + } + } + + // urlStart already guarantees click >= URL start; check right edge. + if (clickIdx >= urlStart + url.length) { + return undefined + } + + return url +} + +/** + * Select the entire row. Sets isDragging=true and anchorSpan so a + * subsequent drag extends the selection line-by-line. The anchor/focus + * span from col 0 to width-1; getSelectedText handles noSelect skipping + * and trailing-whitespace trimming so the copied text is just the visible + * line content. + */ +export function selectLineAt(s: SelectionState, screen: Screen, row: number): void { + if (row < 0 || row >= screen.height) { + return + } + + const lo = { col: 0, row } + const hi = { col: screen.width - 1, row } + s.anchor = lo + s.focus = hi + s.isDragging = true + s.anchorSpan = { lo, hi, kind: 'line' } +} + +/** + * Extend a word/line-mode selection to the word/line at (col, row). The + * anchor span (the original multi-clicked word/line) stays selected; the + * selection grows from that span to the word/line at the current mouse + * position. Word mode falls back to the raw cell when the mouse is over a + * noSelect cell or out of bounds, so dragging into gutters still extends. + */ +export function extendSelection(s: SelectionState, screen: Screen, col: number, row: number): void { + if (!s.isDragging || !s.anchorSpan) { + return + } + + const span = s.anchorSpan + let mLo: Point + let mHi: Point + + if (span.kind === 'word') { + const b = wordBoundsAt(screen, col, row) + mLo = { col: b ? b.lo : col, row } + mHi = { col: b ? b.hi : col, row } + } else { + const r = clamp(row, 0, screen.height - 1) + mLo = { col: 0, row: r } + mHi = { col: screen.width - 1, row: r } + } + + if (comparePoints(mHi, span.lo) < 0) { + // Mouse target ends before anchor span: extend backward. + s.anchor = span.hi + s.focus = mLo + } else if (comparePoints(mLo, span.hi) > 0) { + // Mouse target starts after anchor span: extend forward. + s.anchor = span.lo + s.focus = mHi + } else { + // Mouse overlaps the anchor span: just select the anchor span. + s.anchor = span.lo + s.focus = span.hi + } +} + +/** Semantic keyboard focus moves. See moveSelectionFocus in ink.tsx for + * how screen bounds + row-wrap are applied. */ +export type FocusMove = 'left' | 'right' | 'up' | 'down' | 'lineStart' | 'lineEnd' + +/** + * Set focus to (col, row) for keyboard selection extension (shift+arrow). + * Anchor stays fixed; selection grows or shrinks depending on where focus + * moves relative to anchor. Drops to char mode (clears anchorSpan) — + * native macOS does this too: shift+arrow after a double-click word-select + * extends char-by-char from the word edge, not word-by-word. Scrolled-off + * accumulators are preserved: keyboard-extending a drag-scrolled selection + * keeps the off-screen rows. Caller supplies coords already clamped/wrapped. + */ +export function moveFocus(s: SelectionState, col: number, row: number): void { + if (!s.focus) { + return + } + + s.anchorSpan = null + s.focus = { col, row } + // Explicit user repositioning — any stale virtual focus (from a prior + // shiftSelection clamp) no longer reflects intent. Anchor stays put so + // virtualAnchorRow is still valid for its own round-trip. + s.virtualFocusRow = undefined +} + +/** + * Shift anchor AND focus by dRow, clamped to [minRow, maxRow]. Used for + * keyboard scroll (PgUp/PgDn/ctrl+u/d/b/f): the whole selection must track + * the content, unlike drag-to-scroll where focus stays at the mouse. Any + * point that hits a clamp bound gets its col reset to the full-width edge — + * its original content scrolled off-screen and was captured by + * captureScrolledRows, so the col constraint was already consumed. Keeping + * it would truncate the NEW content now at that screen row. Clamp col is 0 + * for dRow<0 (scrolling down, top leaves, 'above' semantics) or width-1 for + * dRow>0 (scrolling up, bottom leaves, 'below' semantics). + * + * If both ends overshoot the SAME viewport edge (select text → Home/End/g/G + * jumps far enough that both are out of view), clear — otherwise both clamp + * to the same corner cell and a ghost 1-cell highlight lingers, and + * getSelectedText returns one unrelated char from that corner. Symmetric + * with shiftSelectionForFollow's top-edge check, but bidirectional: keyboard + * scroll can jump either way. + */ +export function shiftSelection(s: SelectionState, dRow: number, minRow: number, maxRow: number, width: number): void { + if (!s.anchor || !s.focus) { + return + } + + // Virtual rows track pre-clamp positions so reverse scrolls restore + // correctly. Without this, clamp(5→0) + shift(+10) = 10, not the true 5, + // and scrolledOffAbove stays stale (highlight ≠ copy). + const vAnchor = (s.virtualAnchorRow ?? s.anchor.row) + dRow + const vFocus = (s.virtualFocusRow ?? s.focus.row) + dRow + + if ((vAnchor < minRow && vFocus < minRow) || (vAnchor > maxRow && vFocus > maxRow)) { + clearSelection(s) + + return + } + + // Debt = how far the nearer endpoint overshoots each edge. When debt + // shrinks (reverse scroll), those rows are back on-screen — pop from + // the accumulator so getSelectedText doesn't double-count them. + const oldMin = Math.min(s.virtualAnchorRow ?? s.anchor.row, s.virtualFocusRow ?? s.focus.row) + + const oldMax = Math.max(s.virtualAnchorRow ?? s.anchor.row, s.virtualFocusRow ?? s.focus.row) + + const oldAboveDebt = Math.max(0, minRow - oldMin) + const oldBelowDebt = Math.max(0, oldMax - maxRow) + const newAboveDebt = Math.max(0, minRow - Math.min(vAnchor, vFocus)) + const newBelowDebt = Math.max(0, Math.max(vAnchor, vFocus) - maxRow) + + if (newAboveDebt < oldAboveDebt) { + // scrolledOffAbove pushes newest at the end (closest to on-screen). + const drop = oldAboveDebt - newAboveDebt + s.scrolledOffAbove.length -= drop + s.scrolledOffAboveSW.length = s.scrolledOffAbove.length + } + + if (newBelowDebt < oldBelowDebt) { + // scrolledOffBelow unshifts newest at the front (closest to on-screen). + const drop = oldBelowDebt - newBelowDebt + s.scrolledOffBelow.splice(0, drop) + s.scrolledOffBelowSW.splice(0, drop) + } + + // Invariant: accumulator length ≤ debt. If the accumulator exceeds debt, + // the excess is stale — e.g., moveFocus cleared virtualFocusRow without + // trimming the accumulator, orphaning entries the pop above can never + // reach because oldDebt was ALREADY 0. Truncate to debt (keeping the + // newest = closest-to-on-screen entries). Check newDebt (not oldDebt): + // captureScrolledRows runs BEFORE this shift in the real flow (ink.tsx), + // so at entry the accumulator is populated but oldDebt is still 0 — + // that's the normal establish-debt path, not stale. + if (s.scrolledOffAbove.length > newAboveDebt) { + // Above pushes newest at END → keep END. + s.scrolledOffAbove = newAboveDebt > 0 ? s.scrolledOffAbove.slice(-newAboveDebt) : [] + s.scrolledOffAboveSW = newAboveDebt > 0 ? s.scrolledOffAboveSW.slice(-newAboveDebt) : [] + } + + if (s.scrolledOffBelow.length > newBelowDebt) { + // Below unshifts newest at FRONT → keep FRONT. + s.scrolledOffBelow = s.scrolledOffBelow.slice(0, newBelowDebt) + s.scrolledOffBelowSW = s.scrolledOffBelowSW.slice(0, newBelowDebt) + } + + // Clamp col depends on which EDGE (not dRow direction): virtual tracking + // means a top-clamped point can stay top-clamped during a dRow>0 reverse + // shift — dRow-based clampCol would give it the bottom col. + const shift = (p: Point, vRow: number): Point => { + if (vRow < minRow) { + return { col: 0, row: minRow } + } + + if (vRow > maxRow) { + return { col: width - 1, row: maxRow } + } + + return { col: p.col, row: vRow } + } + + s.anchor = shift(s.anchor, vAnchor) + s.focus = shift(s.focus, vFocus) + s.virtualAnchorRow = vAnchor < minRow || vAnchor > maxRow ? vAnchor : undefined + s.virtualFocusRow = vFocus < minRow || vFocus > maxRow ? vFocus : undefined + + // anchorSpan not virtual-tracked: it's for word/line extend-on-drag, + // irrelevant to the keyboard-scroll round-trip case. + if (s.anchorSpan) { + const sp = (p: Point): Point => { + const r = p.row + dRow + + if (r < minRow) { + return { col: 0, row: minRow } + } + + if (r > maxRow) { + return { col: width - 1, row: maxRow } + } + + return { col: p.col, row: r } + } + + s.anchorSpan = { + lo: sp(s.anchorSpan.lo), + hi: sp(s.anchorSpan.hi), + kind: s.anchorSpan.kind + } + } +} + +/** + * Shift the anchor row by dRow, clamped to [minRow, maxRow]. Used during + * drag-to-scroll: when the ScrollBox scrolls by N rows, the content that + * was under the anchor is now at a different viewport row, so the anchor + * must follow it. Focus is left unchanged (it stays at the mouse position). + */ +export function shiftAnchor(s: SelectionState, dRow: number, minRow: number, maxRow: number): void { + if (!s.anchor) { + return + } + + // Same virtual-row tracking as shiftSelection/shiftSelectionForFollow: the + // drag→follow transition hands off to shiftSelectionForFollow, which reads + // (virtualAnchorRow ?? anchor.row). Without this, drag-phase clamping + // leaves virtual undefined → follow initializes from the already-clamped + // row, under-counting total drift → shiftSelection's invariant-restore + // prematurely clears valid drag-phase accumulator entries. + const raw = (s.virtualAnchorRow ?? s.anchor.row) + dRow + s.anchor = { col: s.anchor.col, row: clamp(raw, minRow, maxRow) } + s.virtualAnchorRow = raw < minRow || raw > maxRow ? raw : undefined + + // anchorSpan not virtual-tracked (word/line extend, irrelevant to + // keyboard-scroll round-trip) — plain clamp from current row. + if (s.anchorSpan) { + const shift = (p: Point): Point => ({ + col: p.col, + row: clamp(p.row + dRow, minRow, maxRow) + }) + + s.anchorSpan = { + lo: shift(s.anchorSpan.lo), + hi: shift(s.anchorSpan.hi), + kind: s.anchorSpan.kind + } + } +} + +/** + * Shift the whole selection (anchor + focus + anchorSpan) by dRow, clamped + * to [minRow, maxRow]. Used when sticky/auto-follow scrolls the ScrollBox + * while a selection is active — native terminal behavior is for the + * highlight to walk up the screen with the text (not stay at the same + * screen position). + * + * Differs from shiftAnchor: during drag-to-scroll, focus tracks the live + * mouse position and only anchor follows the text. During streaming-follow, + * the selection is text-anchored at both ends — both must move. The + * isDragging check in ink.tsx picks which shift to apply. + * + * If both ends would shift strictly BELOW minRow (unclamped), the selected + * text has scrolled entirely off the top. Clear it — otherwise a single + * inverted cell lingers at the viewport top as a ghost (native terminals + * drop the selection when it leaves scrollback). Landing AT minRow is + * still valid: that cell holds the correct text. Returns true if the + * selection was cleared so the caller can notify React-land subscribers + * (useHasSelection) — the caller is inside onRender so it can't use + * notifySelectionChange (recursion), must fire listeners directly. + */ +export function shiftSelectionForFollow(s: SelectionState, dRow: number, minRow: number, maxRow: number): boolean { + if (!s.anchor) { + return false + } + + // Mirror shiftSelection: compute raw (unclamped) positions from virtual + // if set, else current. This handles BOTH the update path (virtual already + // set from a prior keyboard scroll) AND the initialize path (first clamp + // happens HERE via follow-scroll, no prior keyboard scroll). Without the + // initialize path, follow-scroll-first leaves virtual undefined even + // though the clamp below occurred → a later PgUp computes debt from the + // clamped row instead of the true pre-clamp row and never pops the + // accumulator — getSelectedText double-counts the off-screen rows. + const rawAnchor = (s.virtualAnchorRow ?? s.anchor.row) + dRow + + const rawFocus = s.focus ? (s.virtualFocusRow ?? s.focus.row) + dRow : undefined + + if (rawAnchor < minRow && rawFocus !== undefined && rawFocus < minRow) { + clearSelection(s) + + return true + } + + // Clamp from raw, not p.row+dRow — so a virtual position coming back + // in-bounds lands at the TRUE position, not the stale clamped one. + s.anchor = { col: s.anchor.col, row: clamp(rawAnchor, minRow, maxRow) } + + if (s.focus && rawFocus !== undefined) { + s.focus = { col: s.focus.col, row: clamp(rawFocus, minRow, maxRow) } + } + + s.virtualAnchorRow = rawAnchor < minRow || rawAnchor > maxRow ? rawAnchor : undefined + s.virtualFocusRow = rawFocus !== undefined && (rawFocus < minRow || rawFocus > maxRow) ? rawFocus : undefined + + // anchorSpan not virtual-tracked (word/line extend, irrelevant to + // keyboard-scroll round-trip) — plain clamp from current row. + if (s.anchorSpan) { + const shift = (p: Point): Point => ({ + col: p.col, + row: clamp(p.row + dRow, minRow, maxRow) + }) + + s.anchorSpan = { + lo: shift(s.anchorSpan.lo), + hi: shift(s.anchorSpan.hi), + kind: s.anchorSpan.kind + } + } + + return false +} + +export function hasSelection(s: SelectionState): boolean { + return s.anchor !== null && s.focus !== null +} + +/** + * Normalized selection bounds: start is always before end in reading order. + * Returns null if no active selection. + */ +export function selectionBounds(s: SelectionState): { + start: { col: number; row: number } + end: { col: number; row: number } +} | null { + if (!s.anchor || !s.focus) { + return null + } + + return comparePoints(s.anchor, s.focus) <= 0 ? { start: s.anchor, end: s.focus } : { start: s.focus, end: s.anchor } +} + +/** + * Check if a cell at (col, row) is within the current selection range. + * Used by the renderer to apply inverse style. + */ +export function isCellSelected(s: SelectionState, col: number, row: number): boolean { + const b = selectionBounds(s) + + if (!b) { + return false + } + + const { start, end } = b + + if (row < start.row || row > end.row) { + return false + } + + if (row === start.row && col < start.col) { + return false + } + + if (row === end.row && col > end.col) { + return false + } + + return true +} + +/** Extract text from one screen row. When the next row is a soft-wrap + * continuation (screen.softWrap[row+1]>0), clamp to that content-end + * column and skip the trailing trim so the word-separator space survives + * the join. See Screen.softWrap for why the clamp is necessary. */ +function extractRowText(screen: Screen, row: number, colStart: number, colEnd: number): string { + const noSelect = screen.noSelect + const rowOff = row * screen.width + const contentEnd = row + 1 < screen.height ? screen.softWrap[row + 1]! : 0 + const lastCol = contentEnd > 0 ? Math.min(colEnd, contentEnd - 1) : colEnd + let line = '' + + for (let col = colStart; col <= lastCol; col++) { + // Skip cells marked noSelect (gutters, line numbers, diff sigils). + // Check before cellAt to avoid the decode cost for excluded cells. + if (noSelect[rowOff + col] === 1) { + continue + } + + const cell = cellAt(screen, col, row) + + if (!cell) { + continue + } + + // Skip spacer tails (second half of wide chars) — the head already + // contains the full grapheme. SpacerHead is a blank at line-end. + if (cell.width === CellWidth.SpacerTail || cell.width === CellWidth.SpacerHead) { + continue + } + + line += cell.char + } + + return contentEnd > 0 ? line : line.replace(/\s+$/, '') +} + +/** Accumulator for selected text that merges soft-wrapped rows back + * into logical lines. push(text, sw) appends a newline before text + * only when sw=false (i.e. the row starts a new logical line). Rows + * with sw=true are concatenated onto the previous row. */ +function joinRows(lines: string[], text: string, sw: boolean | undefined): void { + if (sw && lines.length > 0) { + lines[lines.length - 1] += text + } else { + lines.push(text) + } +} + +/** + * Extract text from the screen buffer within the selection range. + * Rows are joined with newlines unless the screen's softWrap bitmap + * marks a row as a word-wrap continuation — those rows are concatenated + * onto the previous row so the copied text matches the logical source + * line, not the visual wrapped layout. Trailing whitespace on the last + * fragment of each logical line is trimmed. Wide-char spacer cells are + * skipped. Rows that scrolled out of the viewport during drag-to-scroll + * are joined back in from the scrolledOffAbove/Below accumulators along + * with their captured softWrap bits. + */ +export function getSelectedText(s: SelectionState, screen: Screen): string { + const b = selectionBounds(s) + + if (!b) { + return '' + } + + const { start, end } = b + const sw = screen.softWrap + const lines: string[] = [] + + for (let i = 0; i < s.scrolledOffAbove.length; i++) { + joinRows(lines, s.scrolledOffAbove[i]!, s.scrolledOffAboveSW[i]) + } + + for (let row = start.row; row <= end.row; row++) { + const rowStart = row === start.row ? start.col : 0 + const rowEnd = row === end.row ? end.col : screen.width - 1 + joinRows(lines, extractRowText(screen, row, rowStart, rowEnd), sw[row]! > 0) + } + + for (let i = 0; i < s.scrolledOffBelow.length; i++) { + joinRows(lines, s.scrolledOffBelow[i]!, s.scrolledOffBelowSW[i]) + } + + return lines.join('\n') +} + +/** + * Capture text from rows about to scroll out of the viewport during + * drag-to-scroll, BEFORE scrollBy overwrites them. Only the rows that + * intersect the selection are captured, using the selection's col bounds + * for the anchor-side boundary row. After capturing the anchor row, the + * anchor.col AND anchorSpan cols are reset to the full-width boundary so + * subsequent captures and the final getSelectedText don't re-apply a stale + * col constraint to content that's no longer under the original anchor. + * Both span cols are reset (not just the near side): after a blocked + * reversal the drag can flip direction, and extendSelection then reads the + * OPPOSITE span side — which would otherwise still hold the original word + * boundary and truncate one subsequently-captured row. + * + * side='above': rows scrolling out the top (dragging down, anchor=start). + * side='below': rows scrolling out the bottom (dragging up, anchor=end). + */ +export function captureScrolledRows( + s: SelectionState, + screen: Screen, + firstRow: number, + lastRow: number, + side: 'above' | 'below' +): void { + const b = selectionBounds(s) + + if (!b || firstRow > lastRow) { + return + } + + const { start, end } = b + // Intersect [firstRow, lastRow] with [start.row, end.row]. Rows outside + // the selection aren't captured — they weren't selected. + const lo = Math.max(firstRow, start.row) + const hi = Math.min(lastRow, end.row) + + if (lo > hi) { + return + } + + const width = screen.width + const sw = screen.softWrap + const captured: string[] = [] + const capturedSW: boolean[] = [] + + for (let row = lo; row <= hi; row++) { + const colStart = row === start.row ? start.col : 0 + const colEnd = row === end.row ? end.col : width - 1 + captured.push(extractRowText(screen, row, colStart, colEnd)) + capturedSW.push(sw[row]! > 0) + } + + if (side === 'above') { + // Newest rows go at the bottom of the above-accumulator (closest to + // the on-screen content in reading order). + s.scrolledOffAbove.push(...captured) + s.scrolledOffAboveSW.push(...capturedSW) + + // We just captured the top of the selection. The anchor (=start when + // dragging down) is now pointing at content that will scroll out; its + // col constraint was applied to the captured row. Reset to col 0 so + // the NEXT tick and the final getSelectedText read the full row. + if (s.anchor && s.anchor.row === start.row && lo === start.row) { + s.anchor = { col: 0, row: s.anchor.row } + + if (s.anchorSpan) { + s.anchorSpan = { + kind: s.anchorSpan.kind, + lo: { col: 0, row: s.anchorSpan.lo.row }, + hi: { col: width - 1, row: s.anchorSpan.hi.row } + } + } + } + } else { + // Newest rows go at the TOP of the below-accumulator — they're + // closest to the on-screen content. + s.scrolledOffBelow.unshift(...captured) + s.scrolledOffBelowSW.unshift(...capturedSW) + + if (s.anchor && s.anchor.row === end.row && hi === end.row) { + s.anchor = { col: width - 1, row: s.anchor.row } + + if (s.anchorSpan) { + s.anchorSpan = { + kind: s.anchorSpan.kind, + lo: { col: 0, row: s.anchorSpan.lo.row }, + hi: { col: width - 1, row: s.anchorSpan.hi.row } + } + } + } + } +} + +/** + * Apply the selection overlay directly to the screen buffer by changing + * the style of every cell in the selection range. Called after the + * renderer produces the Frame but before the diff — the normal diffEach + * then picks up the restyled cells as ordinary changes, so LogUpdate + * stays a pure diff engine with no selection awareness. + * + * Uses a SOLID selection background (theme-provided via StylePool. + * setSelectionBg) that REPLACES each cell's bg while PRESERVING its fg — + * matches native terminal selection. Previously SGR-7 inverse (swapped + * fg/bg per cell), which fragmented badly over syntax-highlighted text: + * every distinct fg color became a different bg stripe. + * + * Uses StylePool caches so on drag the only work per cell is a Map + * lookup + packed-int write. + */ +export function applySelectionOverlay(screen: Screen, selection: SelectionState, stylePool: StylePool): void { + const b = selectionBounds(selection) + + if (!b) { + return + } + + const { start, end } = b + const width = screen.width + const noSelect = screen.noSelect + + for (let row = start.row; row <= end.row && row < screen.height; row++) { + const colStart = row === start.row ? start.col : 0 + const colEnd = row === end.row ? Math.min(end.col, width - 1) : width - 1 + const rowOff = row * width + + for (let col = colStart; col <= colEnd; col++) { + const idx = rowOff + col + + // Skip noSelect cells — gutters stay visually unchanged so it's + // clear they're not part of the copy. Surrounding selectable cells + // still highlight so the selection extent remains visible. + if (noSelect[idx] === 1) { + continue + } + + const cell = cellAtIndex(screen, idx) + setCellStyleId(screen, col, row, stylePool.withSelectionBg(cell.styleId)) + } + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/squash-text-nodes.ts b/ui-tui/packages/hermes-ink/src/ink/squash-text-nodes.ts new file mode 100644 index 0000000000..edb26b3b69 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/squash-text-nodes.ts @@ -0,0 +1,74 @@ +import type { DOMElement } from './dom.js' +import type { TextStyles } from './styles.js' + +/** + * A segment of text with its associated styles. + * Used for structured rendering without ANSI string transforms. + */ +export type StyledSegment = { + text: string + styles: TextStyles + hyperlink?: string +} + +/** + * Squash text nodes into styled segments, propagating styles down through the tree. + * This allows structured styling without relying on ANSI string transforms. + */ +export function squashTextNodesToSegments( + node: DOMElement, + inheritedStyles: TextStyles = {}, + inheritedHyperlink?: string, + out: StyledSegment[] = [] +): StyledSegment[] { + const mergedStyles = node.textStyles ? { ...inheritedStyles, ...node.textStyles } : inheritedStyles + + for (const childNode of node.childNodes) { + if (childNode === undefined) { + continue + } + + if (childNode.nodeName === '#text') { + if (childNode.nodeValue.length > 0) { + out.push({ + text: childNode.nodeValue, + styles: mergedStyles, + hyperlink: inheritedHyperlink + }) + } + } else if (childNode.nodeName === 'ink-text' || childNode.nodeName === 'ink-virtual-text') { + squashTextNodesToSegments(childNode, mergedStyles, inheritedHyperlink, out) + } else if (childNode.nodeName === 'ink-link') { + const href = childNode.attributes['href'] as string | undefined + squashTextNodesToSegments(childNode, mergedStyles, href || inheritedHyperlink, out) + } + } + + return out +} + +/** + * Squash text nodes into a plain string (without styles). + * Used for text measurement in layout calculations. + */ +function squashTextNodes(node: DOMElement): string { + let text = '' + + for (const childNode of node.childNodes) { + if (childNode === undefined) { + continue + } + + if (childNode.nodeName === '#text') { + text += childNode.nodeValue + } else if (childNode.nodeName === 'ink-text' || childNode.nodeName === 'ink-virtual-text') { + text += squashTextNodes(childNode) + } else if (childNode.nodeName === 'ink-link') { + text += squashTextNodes(childNode) + } + } + + return text +} + +export default squashTextNodes diff --git a/ui-tui/packages/hermes-ink/src/ink/stringWidth.ts b/ui-tui/packages/hermes-ink/src/ink/stringWidth.ts new file mode 100644 index 0000000000..0b97ac1519 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/stringWidth.ts @@ -0,0 +1,275 @@ +import emojiRegex from 'emoji-regex' +import { eastAsianWidth } from 'get-east-asian-width' +import stripAnsi from 'strip-ansi' + +import { getGraphemeSegmenter } from '../utils/intl.js' + +const EMOJI_REGEX = emojiRegex() + +/** + * Fallback JavaScript implementation of stringWidth when Bun.stringWidth is not available. + * + * Get the display width of a string as it would appear in a terminal. + * + * This is a more accurate alternative to the string-width package that correctly handles + * characters like ⚠ (U+26A0) which string-width incorrectly reports as width 2. + * + * The implementation uses eastAsianWidth directly with ambiguousAsWide: false, + * which correctly treats ambiguous-width characters as narrow (width 1) as + * recommended by the Unicode standard for Western contexts. + */ +function stringWidthJavaScript(str: string): number { + if (typeof str !== 'string' || str.length === 0) { + return 0 + } + + // Fast path: pure ASCII string (no ANSI codes, no wide chars) + let isPureAscii = true + + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i) + + // Check for non-ASCII or ANSI escape (0x1b) + if (code >= 127 || code === 0x1b) { + isPureAscii = false + + break + } + } + + if (isPureAscii) { + // Count printable characters (exclude control chars) + let width = 0 + + for (let i = 0; i < str.length; i++) { + const code = str.charCodeAt(i) + + if (code > 0x1f) { + width++ + } + } + + return width + } + + // Strip ANSI if escape character is present + if (str.includes('\x1b')) { + str = stripAnsi(str) + + if (str.length === 0) { + return 0 + } + } + + // Fast path: simple Unicode (no emoji, variation selectors, or joiners) + if (!needsSegmentation(str)) { + let width = 0 + + for (const char of str) { + const codePoint = char.codePointAt(0)! + + if (!isZeroWidth(codePoint)) { + width += eastAsianWidth(codePoint, { ambiguousAsWide: false }) + } + } + + return width + } + + let width = 0 + + for (const { segment: grapheme } of getGraphemeSegmenter().segment(str)) { + // Check for emoji first (most emoji sequences are width 2) + EMOJI_REGEX.lastIndex = 0 + + if (EMOJI_REGEX.test(grapheme)) { + width += getEmojiWidth(grapheme) + + continue + } + + // Calculate width for non-emoji graphemes + // For grapheme clusters (like Devanagari conjuncts with virama+ZWJ), only count + // the first non-zero-width character's width since the cluster renders as one glyph + for (const char of grapheme) { + const codePoint = char.codePointAt(0)! + + if (!isZeroWidth(codePoint)) { + width += eastAsianWidth(codePoint, { ambiguousAsWide: false }) + + break + } + } + } + + return width +} + +function needsSegmentation(str: string): boolean { + for (const char of str) { + const cp = char.codePointAt(0)! + + // Emoji ranges + if (cp >= 0x1f300 && cp <= 0x1faff) { + return true + } + + if (cp >= 0x2600 && cp <= 0x27bf) { + return true + } + + if (cp >= 0x1f1e6 && cp <= 0x1f1ff) { + return true + } + + // Variation selectors, ZWJ + if (cp >= 0xfe00 && cp <= 0xfe0f) { + return true + } + + if (cp === 0x200d) { + return true + } + } + + return false +} + +function getEmojiWidth(grapheme: string): number { + // Regional indicators: single = 1, pair = 2 + const first = grapheme.codePointAt(0)! + + if (first >= 0x1f1e6 && first <= 0x1f1ff) { + let count = 0 + + for (const _ of grapheme) { + count++ + } + + return count === 1 ? 1 : 2 + } + + // Incomplete keycap: digit/symbol + VS16 without U+20E3 + if (grapheme.length === 2) { + const second = grapheme.codePointAt(1) + + if (second === 0xfe0f && ((first >= 0x30 && first <= 0x39) || first === 0x23 || first === 0x2a)) { + return 1 + } + } + + return 2 +} + +function isZeroWidth(codePoint: number): boolean { + // Fast path for common printable range + if (codePoint >= 0x20 && codePoint < 0x7f) { + return false + } + + if (codePoint >= 0xa0 && codePoint < 0x0300) { + return codePoint === 0x00ad + } + + // Control characters + if (codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f)) { + return true + } + + // Zero-width and invisible characters + if ( + (codePoint >= 0x200b && codePoint <= 0x200d) || // ZW space/joiner + codePoint === 0xfeff || // BOM + (codePoint >= 0x2060 && codePoint <= 0x2064) // Word joiner etc. + ) { + return true + } + + // Variation selectors + if ((codePoint >= 0xfe00 && codePoint <= 0xfe0f) || (codePoint >= 0xe0100 && codePoint <= 0xe01ef)) { + return true + } + + // Combining diacritical marks + if ( + (codePoint >= 0x0300 && codePoint <= 0x036f) || + (codePoint >= 0x1ab0 && codePoint <= 0x1aff) || + (codePoint >= 0x1dc0 && codePoint <= 0x1dff) || + (codePoint >= 0x20d0 && codePoint <= 0x20ff) || + (codePoint >= 0xfe20 && codePoint <= 0xfe2f) + ) { + return true + } + + // Indic script combining marks (covers Devanagari through Malayalam) + if (codePoint >= 0x0900 && codePoint <= 0x0d4f) { + // Signs and vowel marks at start of each script block + const offset = codePoint & 0x7f + + if (offset <= 0x03) { + return true + } // Signs at block start + + if (offset >= 0x3a && offset <= 0x4f) { + return true + } // Vowel signs, virama + + if (offset >= 0x51 && offset <= 0x57) { + return true + } // Stress signs + + if (offset >= 0x62 && offset <= 0x63) { + return true + } // Vowel signs + } + + // Thai/Lao combining marks + // Note: U+0E32 (SARA AA), U+0E33 (SARA AM), U+0EB2, U+0EB3 are spacing vowels (width 1), not combining marks + if ( + codePoint === 0x0e31 || // Thai MAI HAN-AKAT + (codePoint >= 0x0e34 && codePoint <= 0x0e3a) || // Thai vowel signs (skip U+0E32, U+0E33) + (codePoint >= 0x0e47 && codePoint <= 0x0e4e) || // Thai vowel signs and marks + codePoint === 0x0eb1 || // Lao MAI KAN + (codePoint >= 0x0eb4 && codePoint <= 0x0ebc) || // Lao vowel signs (skip U+0EB2, U+0EB3) + (codePoint >= 0x0ec8 && codePoint <= 0x0ecd) // Lao tone marks + ) { + return true + } + + // Arabic formatting + if ( + (codePoint >= 0x0600 && codePoint <= 0x0605) || + codePoint === 0x06dd || + codePoint === 0x070f || + codePoint === 0x08e2 + ) { + return true + } + + // Surrogates, tag characters + if (codePoint >= 0xd800 && codePoint <= 0xdfff) { + return true + } + + if (codePoint >= 0xe0000 && codePoint <= 0xe007f) { + return true + } + + return false +} + +// Note: complex-script graphemes like Devanagari क्ष (ka+virama+ZWJ+ssa) render +// as a single ligature glyph but occupy 2 terminal cells (wcwidth sums the base +// consonants). Bun.stringWidth=2 matches terminal cell allocation, which is what +// we need for cursor positioning — the JS fallback's grapheme-cluster width of 1 +// would desync Ink's layout from the terminal. +// +// Bun.stringWidth is resolved once at module scope rather than checked on every +// call — typeof guards deopt property access and this is a hot path (~100k calls/frame). +const bunStringWidth = typeof Bun !== 'undefined' && typeof Bun.stringWidth === 'function' ? Bun.stringWidth : null + +const BUN_STRING_WIDTH_OPTS = { ambiguousIsNarrow: true } as const + +export const stringWidth: (str: string) => number = bunStringWidth + ? str => bunStringWidth(str, BUN_STRING_WIDTH_OPTS) + : stringWidthJavaScript diff --git a/ui-tui/packages/hermes-ink/src/ink/styles.ts b/ui-tui/packages/hermes-ink/src/ink/styles.ts new file mode 100644 index 0000000000..e5321f6e50 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/styles.ts @@ -0,0 +1,749 @@ +import { + LayoutAlign, + LayoutDisplay, + LayoutEdge, + LayoutFlexDirection, + LayoutGutter, + LayoutJustify, + type LayoutNode, + LayoutOverflow, + LayoutPositionType, + LayoutWrap +} from './layout/node.js' +import type { BorderStyle, BorderTextOptions } from './render-border.js' + +export type RGBColor = `rgb(${number},${number},${number})` +export type HexColor = `#${string}` +export type Ansi256Color = `ansi256(${number})` +export type AnsiColor = + | 'ansi:black' + | 'ansi:red' + | 'ansi:green' + | 'ansi:yellow' + | 'ansi:blue' + | 'ansi:magenta' + | 'ansi:cyan' + | 'ansi:white' + | 'ansi:blackBright' + | 'ansi:redBright' + | 'ansi:greenBright' + | 'ansi:yellowBright' + | 'ansi:blueBright' + | 'ansi:magentaBright' + | 'ansi:cyanBright' + | 'ansi:whiteBright' + +/** Raw color value - not a theme key */ +export type Color = RGBColor | HexColor | Ansi256Color | AnsiColor + +/** + * Structured text styling properties. + * Used to style text without relying on ANSI string transforms. + * Colors are raw values - theme resolution happens at the component layer. + */ +export type TextStyles = { + readonly color?: Color + readonly backgroundColor?: Color + readonly dim?: boolean + readonly bold?: boolean + readonly italic?: boolean + readonly underline?: boolean + readonly strikethrough?: boolean + readonly inverse?: boolean +} + +export type Styles = { + readonly textWrap?: + | 'wrap' + | 'wrap-trim' + | 'end' + | 'middle' + | 'truncate-end' + | 'truncate' + | 'truncate-middle' + | 'truncate-start' + + readonly position?: 'absolute' | 'relative' + readonly top?: number | `${number}%` + readonly bottom?: number | `${number}%` + readonly left?: number | `${number}%` + readonly right?: number | `${number}%` + + /** + * Size of the gap between an element's columns. + */ + readonly columnGap?: number + + /** + * Size of the gap between element's rows. + */ + readonly rowGap?: number + + /** + * Size of the gap between an element's columns and rows. Shorthand for `columnGap` and `rowGap`. + */ + readonly gap?: number + + /** + * Margin on all sides. Equivalent to setting `marginTop`, `marginBottom`, `marginLeft` and `marginRight`. + */ + readonly margin?: number + + /** + * Horizontal margin. Equivalent to setting `marginLeft` and `marginRight`. + */ + readonly marginX?: number + + /** + * Vertical margin. Equivalent to setting `marginTop` and `marginBottom`. + */ + readonly marginY?: number + + /** + * Top margin. + */ + readonly marginTop?: number + + /** + * Bottom margin. + */ + readonly marginBottom?: number + + /** + * Left margin. + */ + readonly marginLeft?: number + + /** + * Right margin. + */ + readonly marginRight?: number + + /** + * Padding on all sides. Equivalent to setting `paddingTop`, `paddingBottom`, `paddingLeft` and `paddingRight`. + */ + readonly padding?: number + + /** + * Horizontal padding. Equivalent to setting `paddingLeft` and `paddingRight`. + */ + readonly paddingX?: number + + /** + * Vertical padding. Equivalent to setting `paddingTop` and `paddingBottom`. + */ + readonly paddingY?: number + + /** + * Top padding. + */ + readonly paddingTop?: number + + /** + * Bottom padding. + */ + readonly paddingBottom?: number + + /** + * Left padding. + */ + readonly paddingLeft?: number + + /** + * Right padding. + */ + readonly paddingRight?: number + + /** + * This property defines the ability for a flex item to grow if necessary. + * See [flex-grow](https://css-tricks.com/almanac/properties/f/flex-grow/). + */ + readonly flexGrow?: number + + /** + * It specifies the “flex shrink factor”, which determines how much the flex item will shrink relative to the rest of the flex items in the flex container when there isn’t enough space on the row. + * See [flex-shrink](https://css-tricks.com/almanac/properties/f/flex-shrink/). + */ + readonly flexShrink?: number + + /** + * It establishes the main-axis, thus defining the direction flex items are placed in the flex container. + * See [flex-direction](https://css-tricks.com/almanac/properties/f/flex-direction/). + */ + readonly flexDirection?: 'row' | 'column' | 'row-reverse' | 'column-reverse' + + /** + * It specifies the initial size of the flex item, before any available space is distributed according to the flex factors. + * See [flex-basis](https://css-tricks.com/almanac/properties/f/flex-basis/). + */ + readonly flexBasis?: number | string + + /** + * It defines whether the flex items are forced in a single line or can be flowed into multiple lines. If set to multiple lines, it also defines the cross-axis which determines the direction new lines are stacked in. + * See [flex-wrap](https://css-tricks.com/almanac/properties/f/flex-wrap/). + */ + readonly flexWrap?: 'nowrap' | 'wrap' | 'wrap-reverse' + + /** + * The align-items property defines the default behavior for how items are laid out along the cross axis (perpendicular to the main axis). + * See [align-items](https://css-tricks.com/almanac/properties/a/align-items/). + */ + readonly alignItems?: 'flex-start' | 'center' | 'flex-end' | 'stretch' + + /** + * It makes possible to override the align-items value for specific flex items. + * See [align-self](https://css-tricks.com/almanac/properties/a/align-self/). + */ + readonly alignSelf?: 'flex-start' | 'center' | 'flex-end' | 'auto' + + /** + * It defines the alignment along the main axis. + * See [justify-content](https://css-tricks.com/almanac/properties/j/justify-content/). + */ + readonly justifyContent?: 'flex-start' | 'flex-end' | 'space-between' | 'space-around' | 'space-evenly' | 'center' + + /** + * Width of the element in spaces. + * You can also set it in percent, which will calculate the width based on the width of parent element. + */ + readonly width?: number | string + + /** + * Height of the element in lines (rows). + * You can also set it in percent, which will calculate the height based on the height of parent element. + */ + readonly height?: number | string + + /** + * Sets a minimum width of the element. + */ + readonly minWidth?: number | string + + /** + * Sets a minimum height of the element. + */ + readonly minHeight?: number | string + + /** + * Sets a maximum width of the element. + */ + readonly maxWidth?: number | string + + /** + * Sets a maximum height of the element. + */ + readonly maxHeight?: number | string + + /** + * Set this property to `none` to hide the element. + */ + readonly display?: 'flex' | 'none' + + /** + * Add a border with a specified style. + * If `borderStyle` is `undefined` (which it is by default), no border will be added. + */ + readonly borderStyle?: BorderStyle + + /** + * Determines whether top border is visible. + * + * @default true + */ + readonly borderTop?: boolean + + /** + * Determines whether bottom border is visible. + * + * @default true + */ + readonly borderBottom?: boolean + + /** + * Determines whether left border is visible. + * + * @default true + */ + readonly borderLeft?: boolean + + /** + * Determines whether right border is visible. + * + * @default true + */ + readonly borderRight?: boolean + + /** + * Change border color. + * Shorthand for setting `borderTopColor`, `borderRightColor`, `borderBottomColor` and `borderLeftColor`. + */ + readonly borderColor?: Color + + /** + * Change top border color. + * Accepts raw color values (rgb, hex, ansi). + */ + readonly borderTopColor?: Color + + /** + * Change bottom border color. + * Accepts raw color values (rgb, hex, ansi). + */ + readonly borderBottomColor?: Color + + /** + * Change left border color. + * Accepts raw color values (rgb, hex, ansi). + */ + readonly borderLeftColor?: Color + + /** + * Change right border color. + * Accepts raw color values (rgb, hex, ansi). + */ + readonly borderRightColor?: Color + + /** + * Dim the border color. + * Shorthand for setting `borderTopDimColor`, `borderBottomDimColor`, `borderLeftDimColor` and `borderRightDimColor`. + * + * @default false + */ + readonly borderDimColor?: boolean + + /** + * Dim the top border color. + * + * @default false + */ + readonly borderTopDimColor?: boolean + + /** + * Dim the bottom border color. + * + * @default false + */ + readonly borderBottomDimColor?: boolean + + /** + * Dim the left border color. + * + * @default false + */ + readonly borderLeftDimColor?: boolean + + /** + * Dim the right border color. + * + * @default false + */ + readonly borderRightDimColor?: boolean + + /** + * Add text within the border. Only applies to top or bottom borders. + */ + readonly borderText?: BorderTextOptions + + /** + * Background color for the box. Fills the interior with background-colored + * spaces and is inherited by child text nodes as their default background. + */ + readonly backgroundColor?: Color + + /** + * Fill the box's interior (padding included) with spaces before + * rendering children, so nothing behind it shows through. Like + * `backgroundColor` but without emitting any SGR — the terminal's + * default background is used. Useful for absolute-positioned overlays + * where Box padding/gaps would otherwise be transparent. + */ + readonly opaque?: boolean + + /** + * Behavior for an element's overflow in both directions. + * 'scroll' constrains the container's size (children do not expand it) + * and enables scrollTop-based virtualized scrolling at render time. + * + * @default 'visible' + */ + readonly overflow?: 'visible' | 'hidden' | 'scroll' + + /** + * Behavior for an element's overflow in horizontal direction. + * + * @default 'visible' + */ + readonly overflowX?: 'visible' | 'hidden' | 'scroll' + + /** + * Behavior for an element's overflow in vertical direction. + * + * @default 'visible' + */ + readonly overflowY?: 'visible' | 'hidden' | 'scroll' + + /** + * Exclude this box's cells from text selection in fullscreen mode. + * Cells inside this region are skipped by both the selection highlight + * and the copied text — useful for fencing off gutters (line numbers, + * diff sigils) so click-drag over a diff yields clean copyable code. + * Only affects alt-screen text selection; no-op otherwise. + * + * `'from-left-edge'` extends the exclusion from column 0 to the box's + * right edge for every row it occupies — this covers any upstream + * indentation (tool message prefix, tree lines) so a multi-row drag + * doesn't pick up leading whitespace from middle rows. + */ + readonly noSelect?: boolean | 'from-left-edge' +} + +const applyPositionStyles = (node: LayoutNode, style: Styles): void => { + if ('position' in style) { + node.setPositionType(style.position === 'absolute' ? LayoutPositionType.Absolute : LayoutPositionType.Relative) + } + + if ('top' in style) { + applyPositionEdge(node, 'top', style.top) + } + + if ('bottom' in style) { + applyPositionEdge(node, 'bottom', style.bottom) + } + + if ('left' in style) { + applyPositionEdge(node, 'left', style.left) + } + + if ('right' in style) { + applyPositionEdge(node, 'right', style.right) + } +} + +function applyPositionEdge( + node: LayoutNode, + edge: 'top' | 'bottom' | 'left' | 'right', + v: number | `${number}%` | undefined +): void { + if (typeof v === 'string') { + node.setPositionPercent(edge, Number.parseInt(v, 10)) + } else if (typeof v === 'number') { + node.setPosition(edge, v) + } else { + node.setPosition(edge, Number.NaN) + } +} + +const applyOverflowStyles = (node: LayoutNode, style: Styles): void => { + // Yoga's Overflow controls whether children expand the container. + // 'hidden' and 'scroll' both prevent expansion; 'scroll' additionally + // signals that the renderer should apply scrollTop translation. + // overflowX/Y are render-time concerns; for layout we use the union. + const y = style.overflowY ?? style.overflow + const x = style.overflowX ?? style.overflow + + if (y === 'scroll' || x === 'scroll') { + node.setOverflow(LayoutOverflow.Scroll) + } else if (y === 'hidden' || x === 'hidden') { + node.setOverflow(LayoutOverflow.Hidden) + } else if ('overflow' in style || 'overflowX' in style || 'overflowY' in style) { + node.setOverflow(LayoutOverflow.Visible) + } +} + +const applyMarginStyles = (node: LayoutNode, style: Styles): void => { + if ('margin' in style) { + node.setMargin(LayoutEdge.All, style.margin ?? 0) + } + + if ('marginX' in style) { + node.setMargin(LayoutEdge.Horizontal, style.marginX ?? 0) + } + + if ('marginY' in style) { + node.setMargin(LayoutEdge.Vertical, style.marginY ?? 0) + } + + if ('marginLeft' in style) { + node.setMargin(LayoutEdge.Start, style.marginLeft || 0) + } + + if ('marginRight' in style) { + node.setMargin(LayoutEdge.End, style.marginRight || 0) + } + + if ('marginTop' in style) { + node.setMargin(LayoutEdge.Top, style.marginTop || 0) + } + + if ('marginBottom' in style) { + node.setMargin(LayoutEdge.Bottom, style.marginBottom || 0) + } +} + +const applyPaddingStyles = (node: LayoutNode, style: Styles): void => { + if ('padding' in style) { + node.setPadding(LayoutEdge.All, style.padding ?? 0) + } + + if ('paddingX' in style) { + node.setPadding(LayoutEdge.Horizontal, style.paddingX ?? 0) + } + + if ('paddingY' in style) { + node.setPadding(LayoutEdge.Vertical, style.paddingY ?? 0) + } + + if ('paddingLeft' in style) { + node.setPadding(LayoutEdge.Left, style.paddingLeft || 0) + } + + if ('paddingRight' in style) { + node.setPadding(LayoutEdge.Right, style.paddingRight || 0) + } + + if ('paddingTop' in style) { + node.setPadding(LayoutEdge.Top, style.paddingTop || 0) + } + + if ('paddingBottom' in style) { + node.setPadding(LayoutEdge.Bottom, style.paddingBottom || 0) + } +} + +const applyFlexStyles = (node: LayoutNode, style: Styles): void => { + if ('flexGrow' in style) { + node.setFlexGrow(style.flexGrow ?? 0) + } + + if ('flexShrink' in style) { + node.setFlexShrink(typeof style.flexShrink === 'number' ? style.flexShrink : 1) + } + + if ('flexWrap' in style) { + if (style.flexWrap === 'nowrap') { + node.setFlexWrap(LayoutWrap.NoWrap) + } + + if (style.flexWrap === 'wrap') { + node.setFlexWrap(LayoutWrap.Wrap) + } + + if (style.flexWrap === 'wrap-reverse') { + node.setFlexWrap(LayoutWrap.WrapReverse) + } + } + + if ('flexDirection' in style) { + if (style.flexDirection === 'row') { + node.setFlexDirection(LayoutFlexDirection.Row) + } + + if (style.flexDirection === 'row-reverse') { + node.setFlexDirection(LayoutFlexDirection.RowReverse) + } + + if (style.flexDirection === 'column') { + node.setFlexDirection(LayoutFlexDirection.Column) + } + + if (style.flexDirection === 'column-reverse') { + node.setFlexDirection(LayoutFlexDirection.ColumnReverse) + } + } + + if ('flexBasis' in style) { + if (typeof style.flexBasis === 'number') { + node.setFlexBasis(style.flexBasis) + } else if (typeof style.flexBasis === 'string') { + node.setFlexBasisPercent(Number.parseInt(style.flexBasis, 10)) + } else { + node.setFlexBasis(Number.NaN) + } + } + + if ('alignItems' in style) { + if (style.alignItems === 'stretch' || !style.alignItems) { + node.setAlignItems(LayoutAlign.Stretch) + } + + if (style.alignItems === 'flex-start') { + node.setAlignItems(LayoutAlign.FlexStart) + } + + if (style.alignItems === 'center') { + node.setAlignItems(LayoutAlign.Center) + } + + if (style.alignItems === 'flex-end') { + node.setAlignItems(LayoutAlign.FlexEnd) + } + } + + if ('alignSelf' in style) { + if (style.alignSelf === 'auto' || !style.alignSelf) { + node.setAlignSelf(LayoutAlign.Auto) + } + + if (style.alignSelf === 'flex-start') { + node.setAlignSelf(LayoutAlign.FlexStart) + } + + if (style.alignSelf === 'center') { + node.setAlignSelf(LayoutAlign.Center) + } + + if (style.alignSelf === 'flex-end') { + node.setAlignSelf(LayoutAlign.FlexEnd) + } + } + + if ('justifyContent' in style) { + if (style.justifyContent === 'flex-start' || !style.justifyContent) { + node.setJustifyContent(LayoutJustify.FlexStart) + } + + if (style.justifyContent === 'center') { + node.setJustifyContent(LayoutJustify.Center) + } + + if (style.justifyContent === 'flex-end') { + node.setJustifyContent(LayoutJustify.FlexEnd) + } + + if (style.justifyContent === 'space-between') { + node.setJustifyContent(LayoutJustify.SpaceBetween) + } + + if (style.justifyContent === 'space-around') { + node.setJustifyContent(LayoutJustify.SpaceAround) + } + + if (style.justifyContent === 'space-evenly') { + node.setJustifyContent(LayoutJustify.SpaceEvenly) + } + } +} + +const applyDimensionStyles = (node: LayoutNode, style: Styles): void => { + if ('width' in style) { + if (typeof style.width === 'number') { + node.setWidth(style.width) + } else if (typeof style.width === 'string') { + node.setWidthPercent(Number.parseInt(style.width, 10)) + } else { + node.setWidthAuto() + } + } + + if ('height' in style) { + if (typeof style.height === 'number') { + node.setHeight(style.height) + } else if (typeof style.height === 'string') { + node.setHeightPercent(Number.parseInt(style.height, 10)) + } else { + node.setHeightAuto() + } + } + + if ('minWidth' in style) { + if (typeof style.minWidth === 'string') { + node.setMinWidthPercent(Number.parseInt(style.minWidth, 10)) + } else { + node.setMinWidth(style.minWidth ?? 0) + } + } + + if ('minHeight' in style) { + if (typeof style.minHeight === 'string') { + node.setMinHeightPercent(Number.parseInt(style.minHeight, 10)) + } else { + node.setMinHeight(style.minHeight ?? 0) + } + } + + if ('maxWidth' in style) { + if (typeof style.maxWidth === 'string') { + node.setMaxWidthPercent(Number.parseInt(style.maxWidth, 10)) + } else { + node.setMaxWidth(style.maxWidth ?? 0) + } + } + + if ('maxHeight' in style) { + if (typeof style.maxHeight === 'string') { + node.setMaxHeightPercent(Number.parseInt(style.maxHeight, 10)) + } else { + node.setMaxHeight(style.maxHeight ?? 0) + } + } +} + +const applyDisplayStyles = (node: LayoutNode, style: Styles): void => { + if ('display' in style) { + node.setDisplay(style.display === 'flex' ? LayoutDisplay.Flex : LayoutDisplay.None) + } +} + +const applyBorderStyles = (node: LayoutNode, style: Styles, resolvedStyle?: Styles): void => { + // resolvedStyle is the full current style (already set on the DOM node). + // style may be a diff with only changed properties. For border side props, + // we need the resolved value because `borderStyle` in a diff may not include + // unchanged border side values (e.g. borderTop stays false but isn't in the diff). + const resolved = resolvedStyle ?? style + + if ('borderStyle' in style) { + const borderWidth = style.borderStyle ? 1 : 0 + + node.setBorder(LayoutEdge.Top, resolved.borderTop !== false ? borderWidth : 0) + node.setBorder(LayoutEdge.Bottom, resolved.borderBottom !== false ? borderWidth : 0) + node.setBorder(LayoutEdge.Left, resolved.borderLeft !== false ? borderWidth : 0) + node.setBorder(LayoutEdge.Right, resolved.borderRight !== false ? borderWidth : 0) + } else { + // Handle individual border property changes (when only borderX changes without borderStyle). + // Skip undefined values — they mean the prop was removed or never set, + // not that a border should be enabled. + if ('borderTop' in style && style.borderTop !== undefined) { + node.setBorder(LayoutEdge.Top, style.borderTop === false ? 0 : 1) + } + + if ('borderBottom' in style && style.borderBottom !== undefined) { + node.setBorder(LayoutEdge.Bottom, style.borderBottom === false ? 0 : 1) + } + + if ('borderLeft' in style && style.borderLeft !== undefined) { + node.setBorder(LayoutEdge.Left, style.borderLeft === false ? 0 : 1) + } + + if ('borderRight' in style && style.borderRight !== undefined) { + node.setBorder(LayoutEdge.Right, style.borderRight === false ? 0 : 1) + } + } +} + +const applyGapStyles = (node: LayoutNode, style: Styles): void => { + if ('gap' in style) { + node.setGap(LayoutGutter.All, style.gap ?? 0) + } + + if ('columnGap' in style) { + node.setGap(LayoutGutter.Column, style.columnGap ?? 0) + } + + if ('rowGap' in style) { + node.setGap(LayoutGutter.Row, style.rowGap ?? 0) + } +} + +const styles = (node: LayoutNode, style: Styles = {}, resolvedStyle?: Styles): void => { + applyPositionStyles(node, style) + applyOverflowStyles(node, style) + applyMarginStyles(node, style) + applyPaddingStyles(node, style) + applyFlexStyles(node, style) + applyDimensionStyles(node, style) + applyDisplayStyles(node, style) + applyBorderStyles(node, style, resolvedStyle) + applyGapStyles(node, style) +} + +export default styles diff --git a/ui-tui/packages/hermes-ink/src/ink/supports-hyperlinks.ts b/ui-tui/packages/hermes-ink/src/ink/supports-hyperlinks.ts new file mode 100644 index 0000000000..16aed4a6c0 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/supports-hyperlinks.ts @@ -0,0 +1,51 @@ +import supportsHyperlinksLib from 'supports-hyperlinks' + +// Additional terminals that support OSC 8 hyperlinks but aren't detected by supports-hyperlinks. +// Checked against both TERM_PROGRAM and LC_TERMINAL (the latter is preserved inside tmux). +export const ADDITIONAL_HYPERLINK_TERMINALS = ['ghostty', 'Hyper', 'kitty', 'alacritty', 'iTerm.app', 'iTerm2'] + +type EnvLike = Record + +type SupportsHyperlinksOptions = { + env?: EnvLike + stdoutSupported?: boolean +} + +/** + * Returns whether stdout supports OSC 8 hyperlinks. + * Extends the supports-hyperlinks library with additional terminal detection. + * @param options Optional overrides for testing (env, stdoutSupported) + */ +export function supportsHyperlinks(options?: SupportsHyperlinksOptions): boolean { + const stdoutSupported = options?.stdoutSupported ?? supportsHyperlinksLib.stdout + + if (stdoutSupported) { + return true + } + + const env = options?.env ?? process.env + + // Check for additional terminals not detected by supports-hyperlinks + const termProgram = env['TERM_PROGRAM'] + + if (termProgram && ADDITIONAL_HYPERLINK_TERMINALS.includes(termProgram)) { + return true + } + + // LC_TERMINAL is set by some terminals (e.g. iTerm2) and preserved inside tmux, + // where TERM_PROGRAM is overwritten to 'tmux'. + const lcTerminal = env['LC_TERMINAL'] + + if (lcTerminal && ADDITIONAL_HYPERLINK_TERMINALS.includes(lcTerminal)) { + return true + } + + // Kitty sets TERM=xterm-kitty + const term = env['TERM'] + + if (term?.includes('kitty')) { + return true + } + + return false +} diff --git a/ui-tui/packages/hermes-ink/src/ink/tabstops.ts b/ui-tui/packages/hermes-ink/src/ink/tabstops.ts new file mode 100644 index 0000000000..9b6007b101 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/tabstops.ts @@ -0,0 +1,44 @@ +// Tab expansion, inspired by Ghostty's Tabstops.zig +// Uses 8-column intervals (POSIX default, hardcoded in terminals like Ghostty) + +import { stringWidth } from './stringWidth.js' +import { createTokenizer } from './termio/tokenize.js' + +const DEFAULT_TAB_INTERVAL = 8 + +export function expandTabs(text: string, interval = DEFAULT_TAB_INTERVAL): string { + if (!text.includes('\t')) { + return text + } + + const tokenizer = createTokenizer() + const tokens = tokenizer.feed(text) + tokens.push(...tokenizer.flush()) + + let result = '' + let column = 0 + + for (const token of tokens) { + if (token.type === 'sequence') { + result += token.value + } else { + const parts = token.value.split(/(\t|\n)/) + + for (const part of parts) { + if (part === '\t') { + const spaces = interval - (column % interval) + result += ' '.repeat(spaces) + column += spaces + } else if (part === '\n') { + result += part + column = 0 + } else { + result += part + column += stringWidth(part) + } + } + } + } + + return result +} diff --git a/ui-tui/packages/hermes-ink/src/ink/terminal-focus-state.ts b/ui-tui/packages/hermes-ink/src/ink/terminal-focus-state.ts new file mode 100644 index 0000000000..ed6c60ab4d --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/terminal-focus-state.ts @@ -0,0 +1,52 @@ +// Terminal focus state signal — non-React access to DECSET 1004 focus events. +// 'unknown' is the default for terminals that don't support focus reporting; +// consumers treat 'unknown' identically to 'focused' (no throttling). +// Subscribers are notified synchronously when focus changes, used by +// TerminalFocusProvider to avoid polling. +export type TerminalFocusState = 'focused' | 'blurred' | 'unknown' + +let focusState: TerminalFocusState = 'unknown' +const resolvers: Set<() => void> = new Set() +const subscribers: Set<() => void> = new Set() + +export function setTerminalFocused(v: boolean): void { + focusState = v ? 'focused' : 'blurred' + + // Notify useSyncExternalStore subscribers + for (const cb of subscribers) { + cb() + } + + if (!v) { + for (const resolve of resolvers) { + resolve() + } + + resolvers.clear() + } +} + +export function getTerminalFocused(): boolean { + return focusState !== 'blurred' +} + +export function getTerminalFocusState(): TerminalFocusState { + return focusState +} + +// For useSyncExternalStore +export function subscribeTerminalFocus(cb: () => void): () => void { + subscribers.add(cb) + + return () => { + subscribers.delete(cb) + } +} + +export function resetTerminalFocusState(): void { + focusState = 'unknown' + + for (const cb of subscribers) { + cb() + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/terminal-querier.ts b/ui-tui/packages/hermes-ink/src/ink/terminal-querier.ts new file mode 100644 index 0000000000..80b1b80ef6 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/terminal-querier.ts @@ -0,0 +1,222 @@ +/** + * Query the terminal and await responses without timeouts. + * + * Terminal queries (DECRQM, DA1, OSC 11, etc.) share the stdin stream + * with keyboard input. Response sequences are syntactically + * distinguishable from key events, so the input parser recognizes them + * and dispatches them here. + * + * To avoid timeouts, each query batch is terminated by a DA1 sentinel + * (CSI c) — every terminal since VT100 responds to DA1, and terminals + * answer queries in order. So: if your query's response arrives before + * DA1's, the terminal supports it; if DA1 arrives first, it doesn't. + * + * Usage: + * const [sync, grapheme] = await Promise.all([ + * querier.send(decrqm(2026)), + * querier.send(decrqm(2027)), + * querier.flush(), + * ]) + * // sync and grapheme are DECRPM responses or undefined if unsupported + */ + +import type { TerminalResponse } from './parse-keypress.js' +import { csi } from './termio/csi.js' +import { osc } from './termio/osc.js' + +/** A terminal query: an outbound request sequence paired with a matcher + * that recognizes the expected inbound response. Built by `decrqm()`, + * `oscColor()`, `kittyKeyboard()`, etc. */ +export type TerminalQuery = { + /** Escape sequence to write to stdout */ + request: string + /** Recognizes the expected response in the inbound stream */ + match: (r: TerminalResponse) => r is T +} + +type DecrpmResponse = Extract +type Da1Response = Extract +type Da2Response = Extract +type KittyResponse = Extract +type CursorPosResponse = Extract +type OscResponse = Extract +type XtversionResponse = Extract + +// -- Query builders -- + +/** DECRQM: request DEC private mode status (CSI ? mode $ p). + * Terminal replies with DECRPM (CSI ? mode ; status $ y) or ignores. */ +export function decrqm(mode: number): TerminalQuery { + return { + request: csi(`?${mode}$p`), + match: (r): r is DecrpmResponse => r.type === 'decrpm' && r.mode === mode + } +} + +/** Primary Device Attributes query (CSI c). Every terminal answers this — + * used internally by flush() as a universal sentinel. Call directly if + * you want the DA1 params. */ +export function da1(): TerminalQuery { + return { + request: csi('c'), + match: (r): r is Da1Response => r.type === 'da1' + } +} + +/** Secondary Device Attributes query (CSI > c). Returns terminal version. */ +export function da2(): TerminalQuery { + return { + request: csi('>c'), + match: (r): r is Da2Response => r.type === 'da2' + } +} + +/** Query current Kitty keyboard protocol flags (CSI ? u). + * Terminal replies with CSI ? flags u or ignores. */ +export function kittyKeyboard(): TerminalQuery { + return { + request: csi('?u'), + match: (r): r is KittyResponse => r.type === 'kittyKeyboard' + } +} + +/** DECXCPR: request cursor position with DEC-private marker (CSI ? 6 n). + * Terminal replies with CSI ? row ; col R. The `?` marker is critical — + * the plain DSR form (CSI 6 n → CSI row;col R) is ambiguous with + * modified F3 keys (Shift+F3 = CSI 1;2 R, etc.). */ +export function cursorPosition(): TerminalQuery { + return { + request: csi('?6n'), + match: (r): r is CursorPosResponse => r.type === 'cursorPosition' + } +} + +/** OSC dynamic color query (e.g. OSC 11 for bg color, OSC 10 for fg). + * The `?` data slot asks the terminal to reply with the current value. */ +export function oscColor(code: number): TerminalQuery { + return { + request: osc(code, '?'), + match: (r): r is OscResponse => r.type === 'osc' && r.code === code + } +} + +/** XTVERSION: request terminal name/version (CSI > 0 q). + * Terminal replies with DCS > | name ST (e.g. "xterm.js(5.5.0)") or ignores. + * This survives SSH — the query goes through the pty, not the environment, + * so it identifies the *client* terminal even when TERM_PROGRAM isn't + * forwarded. Used to detect xterm.js for wheel-scroll compensation. */ +export function xtversion(): TerminalQuery { + return { + request: csi('>0q'), + match: (r): r is XtversionResponse => r.type === 'xtversion' + } +} + +// -- Querier -- + +/** Sentinel request sequence (DA1). Kept internal; flush() writes it. */ +const SENTINEL = csi('c') + +type Pending = + | { + kind: 'query' + match: (r: TerminalResponse) => boolean + resolve: (r: TerminalResponse | undefined) => void + } + | { kind: 'sentinel'; resolve: () => void } + +export class TerminalQuerier { + /** + * Interleaved queue of queries and sentinels in send order. Terminals + * respond in order, so each flush() barrier only drains queries queued + * before it — concurrent batches from independent callers stay isolated. + */ + private queue: Pending[] = [] + + constructor(private stdout: NodeJS.WriteStream) {} + + /** + * Send a query and wait for its response. + * + * Resolves with the response when `query.match` matches an incoming + * TerminalResponse, or with `undefined` when a flush() sentinel arrives + * before any matching response (meaning the terminal ignored the query). + * + * Never rejects; never times out on its own. If you never call flush() + * and the terminal doesn't respond, the promise remains pending. + */ + send(query: TerminalQuery): Promise { + return new Promise(resolve => { + this.queue.push({ + kind: 'query', + match: query.match, + resolve: r => resolve(r as T | undefined) + }) + this.stdout.write(query.request) + }) + } + + /** + * Send the DA1 sentinel. Resolves when DA1's response arrives. + * + * As a side effect, all queries still pending when DA1 arrives are + * resolved with `undefined` (terminal didn't respond → doesn't support + * the query). This is the barrier that makes send() timeout-free. + * + * Safe to call with no pending queries — still waits for a round-trip. + */ + flush(): Promise { + return new Promise(resolve => { + this.queue.push({ kind: 'sentinel', resolve }) + this.stdout.write(SENTINEL) + }) + } + + /** + * Dispatch a response parsed from stdin. Called by App.tsx's + * processKeysInBatch for every `kind: 'response'` item. + * + * Matching strategy: + * - First, try to match a pending query (FIFO, first match wins). + * This lets callers send(da1()) explicitly if they want the DA1 + * params — a separate DA1 write means the terminal sends TWO DA1 + * responses. The first matches the explicit query; the second + * (unmatched) fires the sentinel. + * - Otherwise, if this is a DA1, fire the FIRST pending sentinel: + * resolve any queries queued before that sentinel with undefined + * (the terminal answered DA1 without answering them → unsupported) + * and signal its flush() completion. Only draining up to the first + * sentinel keeps later batches intact when multiple callers have + * concurrent queries in flight. + * - Unsolicited responses (no match, no sentinel) are silently dropped. + */ + onResponse(r: TerminalResponse): void { + const idx = this.queue.findIndex(p => p.kind === 'query' && p.match(r)) + + if (idx !== -1) { + const [q] = this.queue.splice(idx, 1) + + if (q?.kind === 'query') { + q.resolve(r) + } + + return + } + + if (r.type === 'da1') { + const s = this.queue.findIndex(p => p.kind === 'sentinel') + + if (s === -1) { + return + } + + for (const p of this.queue.splice(0, s + 1)) { + if (p.kind === 'query') { + p.resolve(undefined) + } else { + p.resolve() + } + } + } + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/terminal.ts b/ui-tui/packages/hermes-ink/src/ink/terminal.ts new file mode 100644 index 0000000000..8bdac62212 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/terminal.ts @@ -0,0 +1,282 @@ +import type { Writable } from 'stream' + +import { coerce } from 'semver' + +import { env } from '../utils/env.js' +import { gte } from '../utils/semver.js' + +import { getClearTerminalSequence } from './clearTerminal.js' +import type { Diff } from './frame.js' +import { cursorMove, cursorTo, eraseLines } from './termio/csi.js' +import { BSU, ESU, HIDE_CURSOR, SHOW_CURSOR } from './termio/dec.js' +import { link } from './termio/osc.js' + +export type Progress = { + state: 'running' | 'completed' | 'error' | 'indeterminate' + percentage?: number +} + +/** + * Checks if the terminal supports OSC 9;4 progress reporting. + * Supported terminals: + * - ConEmu (Windows) - all versions + * - Ghostty 1.2.0+ + * - iTerm2 3.6.6+ + * + * Note: Windows Terminal interprets OSC 9;4 as notifications, not progress. + */ +export function isProgressReportingAvailable(): boolean { + // Only available if we have a TTY (not piped) + if (!process.stdout.isTTY) { + return false + } + + // Explicitly exclude Windows Terminal, which interprets OSC 9;4 as + // notifications rather than progress indicators + if (process.env.WT_SESSION) { + return false + } + + // ConEmu supports OSC 9;4 for progress (all versions) + if (process.env.ConEmuANSI || process.env.ConEmuPID || process.env.ConEmuTask) { + return true + } + + const version = coerce(process.env.TERM_PROGRAM_VERSION) + + if (!version) { + return false + } + + // Ghostty 1.2.0+ supports OSC 9;4 for progress + // https://ghostty.org/docs/install/release-notes/1-2-0 + if (process.env.TERM_PROGRAM === 'ghostty') { + return gte(version.version, '1.2.0') + } + + // iTerm2 3.6.6+ supports OSC 9;4 for progress + // https://iterm2.com/downloads.html + if (process.env.TERM_PROGRAM === 'iTerm.app') { + return gte(version.version, '3.6.6') + } + + return false +} + +/** + * Checks if the terminal supports DEC mode 2026 (synchronized output). + * When supported, BSU/ESU sequences prevent visible flicker during redraws. + */ +export function isSynchronizedOutputSupported(): boolean { + // tmux parses and proxies every byte but doesn't implement DEC 2026. + // BSU/ESU pass through to the outer terminal but tmux has already + // broken atomicity by chunking. Skip to save 16 bytes/frame + parser work. + if (process.env.TMUX) { + return false + } + + const termProgram = process.env.TERM_PROGRAM + const term = process.env.TERM + + // Modern terminals with known DEC 2026 support + if ( + termProgram === 'iTerm.app' || + termProgram === 'WezTerm' || + termProgram === 'WarpTerminal' || + termProgram === 'ghostty' || + termProgram === 'contour' || + termProgram === 'vscode' || + termProgram === 'alacritty' + ) { + return true + } + + // kitty sets TERM=xterm-kitty or KITTY_WINDOW_ID + if (term?.includes('kitty') || process.env.KITTY_WINDOW_ID) { + return true + } + + // Ghostty may set TERM=xterm-ghostty without TERM_PROGRAM + if (term === 'xterm-ghostty') { + return true + } + + // foot sets TERM=foot or TERM=foot-extra + if (term?.startsWith('foot')) { + return true + } + + // Alacritty may set TERM containing 'alacritty' + if (term?.includes('alacritty')) { + return true + } + + // Zed uses the alacritty_terminal crate which supports DEC 2026 + if (process.env.ZED_TERM) { + return true + } + + // Windows Terminal + if (process.env.WT_SESSION) { + return true + } + + // VTE-based terminals (GNOME Terminal, Tilix, etc.) since VTE 0.68 + const vteVersion = process.env.VTE_VERSION + + if (vteVersion) { + const version = parseInt(vteVersion, 10) + + if (version >= 6800) { + return true + } + } + + return false +} + +// -- XTVERSION-detected terminal name (populated async at startup) -- +// +// TERM_PROGRAM is not forwarded over SSH by default, so env-based detection +// fails when the process runs remotely inside a VS Code integrated terminal. +// XTVERSION (CSI > 0 q → DCS > | name ST) goes through the pty — the query +// reaches the *client* terminal and the reply comes back through stdin. +// App.tsx fires the query when raw mode enables; setXtversionName() is called +// from the response handler. Readers should treat undefined as "not yet known" +// and fall back to env-var detection. + +let xtversionName: string | undefined + +/** Record the XTVERSION response. Called once from App.tsx when the reply + * arrives on stdin. No-op if already set (defend against re-probe). */ +export function setXtversionName(name: string): void { + if (xtversionName === undefined) { + xtversionName = name + } +} + +/** True if running in an xterm.js-based terminal (VS Code, Cursor, Windsurf + * integrated terminals). Combines TERM_PROGRAM env check (fast, sync, but + * not forwarded over SSH) with the XTVERSION probe result (async, survives + * SSH — query/reply goes through the pty). Early calls may miss the probe + * reply — call lazily (e.g. in an event handler) if SSH detection matters. */ +export function isXtermJs(): boolean { + if (process.env.TERM_PROGRAM === 'vscode') { + return true + } + + return xtversionName?.startsWith('xterm.js') ?? false +} + +// Terminals known to correctly implement the Kitty keyboard protocol +// (CSI >1u) and/or xterm modifyOtherKeys (CSI >4;2m) for ctrl+shift+ +// disambiguation. We previously enabled unconditionally (#23350), assuming +// terminals silently ignore unknown CSI — but some terminals honor the enable +// and emit codepoints our input parser doesn't handle (notably over SSH and +// in xterm.js-based terminals like VS Code). tmux is allowlisted because it +// accepts modifyOtherKeys and doesn't forward the kitty sequence to the outer +// terminal. +const EXTENDED_KEYS_TERMINALS = ['iTerm.app', 'kitty', 'WezTerm', 'ghostty', 'tmux', 'windows-terminal'] + +/** True if this terminal correctly handles extended key reporting + * (Kitty keyboard protocol + xterm modifyOtherKeys). */ +export function supportsExtendedKeys(): boolean { + return EXTENDED_KEYS_TERMINALS.includes(env.terminal ?? '') +} + +/** True if the terminal scrolls the viewport when it receives cursor-up + * sequences that reach above the visible area. On Windows, conhost's + * SetConsoleCursorPosition follows the cursor into scrollback + * (microsoft/terminal#14774), yanking users to the top of their buffer + * mid-stream. WT_SESSION catches WSL-in-Windows-Terminal where platform + * is linux but output still routes through conhost. */ +export function hasCursorUpViewportYankBug(): boolean { + return process.platform === 'win32' || !!process.env.WT_SESSION +} + +// Computed once at module load — terminal capabilities don't change mid-session. +// Exported so callers can pass a sync-skip hint gated to specific modes. +export const SYNC_OUTPUT_SUPPORTED = isSynchronizedOutputSupported() + +export type Terminal = { + stdout: Writable + stderr: Writable +} + +export function writeDiffToTerminal(terminal: Terminal, diff: Diff, skipSyncMarkers = false): void { + // No output if there are no patches + if (diff.length === 0) { + return + } + + // BSU/ESU wrapping is opt-out to keep main-screen behavior unchanged. + // Callers pass skipSyncMarkers=true when the terminal doesn't support + // DEC 2026 (e.g. tmux) AND the cost matters (high-frequency alt-screen). + const useSync = !skipSyncMarkers + + // Buffer all writes into a single string to avoid multiple write calls + let buffer = useSync ? BSU : '' + + for (const patch of diff) { + switch (patch.type) { + case 'stdout': + buffer += patch.content + + break + + case 'clear': + if (patch.count > 0) { + buffer += eraseLines(patch.count) + } + + break + + case 'clearTerminal': + buffer += getClearTerminalSequence() + + break + + case 'cursorHide': + buffer += HIDE_CURSOR + + break + + case 'cursorShow': + buffer += SHOW_CURSOR + + break + + case 'cursorMove': + buffer += cursorMove(patch.x, patch.y) + + break + + case 'cursorTo': + buffer += cursorTo(patch.col) + + break + + case 'carriageReturn': + buffer += '\r' + + break + + case 'hyperlink': + buffer += link(patch.uri) + + break + + case 'styleStr': + buffer += patch.str + + break + } + } + + // Add synchronized update end and flush buffer + if (useSync) { + buffer += ESU + } + + terminal.stdout.write(buffer) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio.ts b/ui-tui/packages/hermes-ink/src/ink/termio.ts new file mode 100644 index 0000000000..e14db928cb --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio.ts @@ -0,0 +1,42 @@ +/** + * ANSI Parser Module + * + * A semantic ANSI escape sequence parser inspired by ghostty, tmux, and iTerm2. + * + * Key features: + * - Semantic output: produces structured actions, not string tokens + * - Streaming: can parse input incrementally via Parser class + * - Style tracking: maintains text style state across parse calls + * - Comprehensive: supports SGR, CSI, OSC, ESC sequences + * + * Usage: + * + * ```typescript + * import { Parser } from './termio.js' + * + * const parser = new Parser() + * const actions = parser.feed('\x1b[31mred\x1b[0m') + * // => [{ type: 'text', graphemes: [...], style: { fg: { type: 'named', name: 'red' }, ... } }] + * ``` + */ + +// Parser +export { Parser } from './termio/parser.js' +// Types +export type { + Action, + Color, + CursorAction, + CursorDirection, + EraseAction, + Grapheme, + LinkAction, + ModeAction, + NamedColor, + ScrollAction, + TextSegment, + TextStyle, + TitleAction, + UnderlineStyle +} from './termio/types.js' +export { colorsEqual, defaultStyle, stylesEqual } from './termio/types.js' diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/ansi.ts b/ui-tui/packages/hermes-ink/src/ink/termio/ansi.ts new file mode 100644 index 0000000000..138cfef29c --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/ansi.ts @@ -0,0 +1,75 @@ +/** + * ANSI Control Characters and Escape Sequence Introducers + * + * Based on ECMA-48 / ANSI X3.64 standards. + */ + +/** + * C0 (7-bit) control characters + */ +export const C0 = { + NUL: 0x00, + SOH: 0x01, + STX: 0x02, + ETX: 0x03, + EOT: 0x04, + ENQ: 0x05, + ACK: 0x06, + BEL: 0x07, + BS: 0x08, + HT: 0x09, + LF: 0x0a, + VT: 0x0b, + FF: 0x0c, + CR: 0x0d, + SO: 0x0e, + SI: 0x0f, + DLE: 0x10, + DC1: 0x11, + DC2: 0x12, + DC3: 0x13, + DC4: 0x14, + NAK: 0x15, + SYN: 0x16, + ETB: 0x17, + CAN: 0x18, + EM: 0x19, + SUB: 0x1a, + ESC: 0x1b, + FS: 0x1c, + GS: 0x1d, + RS: 0x1e, + US: 0x1f, + DEL: 0x7f +} as const + +// String constants for output generation +export const ESC = '\x1b' +export const BEL = '\x07' +export const SEP = ';' + +/** + * Escape sequence type introducers (byte after ESC) + */ +export const ESC_TYPE = { + CSI: 0x5b, // [ - Control Sequence Introducer + OSC: 0x5d, // ] - Operating System Command + DCS: 0x50, // P - Device Control String + APC: 0x5f, // _ - Application Program Command + PM: 0x5e, // ^ - Privacy Message + SOS: 0x58, // X - Start of String + ST: 0x5c // \ - String Terminator +} as const + +/** Check if a byte is a C0 control character */ +export function isC0(byte: number): boolean { + return byte < 0x20 || byte === 0x7f +} + +/** + * Check if a byte is an ESC sequence final byte (0-9, :, ;, <, =, >, ?, @ through ~) + * ESC sequences have a wider final byte range than CSI + */ +export function isEscFinal(byte: number): boolean { + return byte >= 0x30 && byte <= 0x7e +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/csi.ts b/ui-tui/packages/hermes-ink/src/ink/termio/csi.ts new file mode 100644 index 0000000000..5d4fbe7ef7 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/csi.ts @@ -0,0 +1,334 @@ +/** + * CSI (Control Sequence Introducer) Types + * + * Enums and types for CSI command parameters. + */ + +import { ESC, ESC_TYPE, SEP } from './ansi.js' + +export const CSI_PREFIX = ESC + String.fromCharCode(ESC_TYPE.CSI) + +/** + * CSI parameter byte ranges + */ +export const CSI_RANGE = { + PARAM_START: 0x30, + PARAM_END: 0x3f, + INTERMEDIATE_START: 0x20, + INTERMEDIATE_END: 0x2f, + FINAL_START: 0x40, + FINAL_END: 0x7e +} as const + +/** Check if a byte is a CSI parameter byte */ +export function isCSIParam(byte: number): boolean { + return byte >= CSI_RANGE.PARAM_START && byte <= CSI_RANGE.PARAM_END +} + +/** Check if a byte is a CSI intermediate byte */ +export function isCSIIntermediate(byte: number): boolean { + return byte >= CSI_RANGE.INTERMEDIATE_START && byte <= CSI_RANGE.INTERMEDIATE_END +} + +/** Check if a byte is a CSI final byte (@ through ~) */ +export function isCSIFinal(byte: number): boolean { + return byte >= CSI_RANGE.FINAL_START && byte <= CSI_RANGE.FINAL_END +} + +/** + * Generate a CSI sequence: ESC [ p1;p2;...;pN final + * Single arg: treated as raw body + * Multiple args: last is final byte, rest are params joined by ; + */ +export function csi(...args: (string | number)[]): string { + if (args.length === 0) { + return CSI_PREFIX + } + + if (args.length === 1) { + return `${CSI_PREFIX}${args[0]}` + } + + const params = args.slice(0, -1) + const final = args[args.length - 1] + + return `${CSI_PREFIX}${params.join(SEP)}${final}` +} + +/** + * CSI final bytes - the command identifier + */ +export const CSI = { + // Cursor movement + CUU: 0x41, // A - Cursor Up + CUD: 0x42, // B - Cursor Down + CUF: 0x43, // C - Cursor Forward + CUB: 0x44, // D - Cursor Back + CNL: 0x45, // E - Cursor Next Line + CPL: 0x46, // F - Cursor Previous Line + CHA: 0x47, // G - Cursor Horizontal Absolute + CUP: 0x48, // H - Cursor Position + CHT: 0x49, // I - Cursor Horizontal Tab + VPA: 0x64, // d - Vertical Position Absolute + HVP: 0x66, // f - Horizontal Vertical Position + + // Erase + ED: 0x4a, // J - Erase in Display + EL: 0x4b, // K - Erase in Line + ECH: 0x58, // X - Erase Character + + // Insert/Delete + IL: 0x4c, // L - Insert Lines + DL: 0x4d, // M - Delete Lines + ICH: 0x40, // @ - Insert Characters + DCH: 0x50, // P - Delete Characters + + // Scroll + SU: 0x53, // S - Scroll Up + SD: 0x54, // T - Scroll Down + + // Modes + SM: 0x68, // h - Set Mode + RM: 0x6c, // l - Reset Mode + + // SGR + SGR: 0x6d, // m - Select Graphic Rendition + + // Other + DSR: 0x6e, // n - Device Status Report + DECSCUSR: 0x71, // q - Set Cursor Style (with space intermediate) + DECSTBM: 0x72, // r - Set Top and Bottom Margins + SCOSC: 0x73, // s - Save Cursor Position + SCORC: 0x75, // u - Restore Cursor Position + CBT: 0x5a // Z - Cursor Backward Tabulation +} as const + +/** + * Erase in Display regions (ED command parameter) + */ +export const ERASE_DISPLAY = ['toEnd', 'toStart', 'all', 'scrollback'] as const + +/** + * Erase in Line regions (EL command parameter) + */ +export const ERASE_LINE_REGION = ['toEnd', 'toStart', 'all'] as const + +/** + * Cursor styles (DECSCUSR) + */ +export type CursorStyle = 'block' | 'underline' | 'bar' + +export const CURSOR_STYLES: Array<{ style: CursorStyle; blinking: boolean }> = [ + { style: 'block', blinking: true }, // 0 - default + { style: 'block', blinking: true }, // 1 + { style: 'block', blinking: false }, // 2 + { style: 'underline', blinking: true }, // 3 + { style: 'underline', blinking: false }, // 4 + { style: 'bar', blinking: true }, // 5 + { style: 'bar', blinking: false } // 6 +] + +// Cursor movement generators + +/** Move cursor up n lines (CSI n A) */ +export function cursorUp(n = 1): string { + return n === 0 ? '' : csi(n, 'A') +} + +/** Move cursor down n lines (CSI n B) */ +export function cursorDown(n = 1): string { + return n === 0 ? '' : csi(n, 'B') +} + +/** Move cursor forward n columns (CSI n C) */ +export function cursorForward(n = 1): string { + return n === 0 ? '' : csi(n, 'C') +} + +/** Move cursor back n columns (CSI n D) */ +export function cursorBack(n = 1): string { + return n === 0 ? '' : csi(n, 'D') +} + +/** Move cursor to column n (1-indexed) (CSI n G) */ +export function cursorTo(col: number): string { + return csi(col, 'G') +} + +/** Move cursor to column 1 (CSI G) */ +export const CURSOR_LEFT = csi('G') + +/** Move cursor to row, col (1-indexed) (CSI row ; col H) */ +export function cursorPosition(row: number, col: number): string { + return csi(row, col, 'H') +} + +/** Move cursor to home position (CSI H) */ +export const CURSOR_HOME = csi('H') + +/** + * Move cursor relative to current position + * Positive x = right, negative x = left + * Positive y = down, negative y = up + */ +export function cursorMove(x: number, y: number): string { + let result = '' + + // Horizontal first (matches ansi-escapes behavior) + if (x < 0) { + result += cursorBack(-x) + } else if (x > 0) { + result += cursorForward(x) + } + + // Then vertical + if (y < 0) { + result += cursorUp(-y) + } else if (y > 0) { + result += cursorDown(y) + } + + return result +} + +// Save/restore cursor position + +/** Save cursor position (CSI s) */ +export const CURSOR_SAVE = csi('s') + +/** Restore cursor position (CSI u) */ +export const CURSOR_RESTORE = csi('u') + +// Erase generators + +/** Erase from cursor to end of line (CSI K) */ +export function eraseToEndOfLine(): string { + return csi('K') +} + +/** Erase from cursor to start of line (CSI 1 K) */ +export function eraseToStartOfLine(): string { + return csi(1, 'K') +} + +/** Erase entire line (CSI 2 K) */ +export function eraseLine(): string { + return csi(2, 'K') +} + +/** Erase entire line - constant form */ +export const ERASE_LINE = csi(2, 'K') + +/** Erase from cursor to end of screen (CSI J) */ +export function eraseToEndOfScreen(): string { + return csi('J') +} + +/** Erase from cursor to start of screen (CSI 1 J) */ +export function eraseToStartOfScreen(): string { + return csi(1, 'J') +} + +/** Erase entire screen (CSI 2 J) */ +export function eraseScreen(): string { + return csi(2, 'J') +} + +/** Erase entire screen - constant form */ +export const ERASE_SCREEN = csi(2, 'J') + +/** Erase scrollback buffer (CSI 3 J) */ +export const ERASE_SCROLLBACK = csi(3, 'J') + +/** + * Erase n lines starting from cursor line, moving cursor up + * This erases each line and moves up, ending at column 1 + */ +export function eraseLines(n: number): string { + if (n <= 0) { + return '' + } + + let result = '' + + for (let i = 0; i < n; i++) { + result += ERASE_LINE + + if (i < n - 1) { + result += cursorUp(1) + } + } + + result += CURSOR_LEFT + + return result +} + +// Scroll + +/** Scroll up n lines (CSI n S) */ +export function scrollUp(n = 1): string { + return n === 0 ? '' : csi(n, 'S') +} + +/** Scroll down n lines (CSI n T) */ +export function scrollDown(n = 1): string { + return n === 0 ? '' : csi(n, 'T') +} + +/** Set scroll region (DECSTBM, CSI top;bottom r). 1-indexed, inclusive. */ +export function setScrollRegion(top: number, bottom: number): string { + return csi(top, bottom, 'r') +} + +/** Reset scroll region to full screen (DECSTBM, CSI r). Homes the cursor. */ +export const RESET_SCROLL_REGION = csi('r') + +// Bracketed paste markers (input from terminal, not output) +// These are sent by the terminal to delimit pasted content when +// bracketed paste mode is enabled (via DEC mode 2004) + +/** Sent by terminal before pasted content (CSI 200 ~) */ +export const PASTE_START = csi('200~') + +/** Sent by terminal after pasted content (CSI 201 ~) */ +export const PASTE_END = csi('201~') + +// Focus event markers (input from terminal, not output) +// These are sent by the terminal when focus changes while +// focus events mode is enabled (via DEC mode 1004) + +/** Sent by terminal when it gains focus (CSI I) */ +export const FOCUS_IN = csi('I') + +/** Sent by terminal when it loses focus (CSI O) */ +export const FOCUS_OUT = csi('O') + +// Kitty keyboard protocol (CSI u) +// Enables enhanced key reporting with modifier information +// See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/ + +/** + * Enable Kitty keyboard protocol with basic modifier reporting + * CSI > 1 u - pushes mode with flags=1 (disambiguate escape codes) + * This makes Shift+Enter send CSI 13;2 u instead of just CR + */ +export const ENABLE_KITTY_KEYBOARD = csi('>1u') + +/** + * Disable Kitty keyboard protocol + * CSI < u - pops the keyboard mode stack + */ +export const DISABLE_KITTY_KEYBOARD = csi('4;2m') + +/** + * Disable xterm modifyOtherKeys (reset to default). + */ +export const DISABLE_MODIFY_OTHER_KEYS = csi('>4m') diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/dec.ts b/ui-tui/packages/hermes-ink/src/ink/termio/dec.ts new file mode 100644 index 0000000000..4548b923ff --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/dec.ts @@ -0,0 +1,54 @@ +/** + * DEC (Digital Equipment Corporation) Private Mode Sequences + * + * DEC private modes use CSI ? N h (set) and CSI ? N l (reset) format. + * These are terminal-specific extensions to the ANSI standard. + */ + +import { csi } from './csi.js' + +/** + * DEC private mode numbers + */ +export const DEC = { + CURSOR_VISIBLE: 25, + ALT_SCREEN: 47, + ALT_SCREEN_CLEAR: 1049, + MOUSE_NORMAL: 1000, + MOUSE_BUTTON: 1002, + MOUSE_ANY: 1003, + MOUSE_SGR: 1006, + FOCUS_EVENTS: 1004, + BRACKETED_PASTE: 2004, + SYNCHRONIZED_UPDATE: 2026 +} as const + +/** Generate CSI ? N h sequence (set mode) */ +export function decset(mode: number): string { + return csi(`?${mode}h`) +} + +/** Generate CSI ? N l sequence (reset mode) */ +export function decreset(mode: number): string { + return csi(`?${mode}l`) +} + +// Pre-generated sequences for common modes +export const BSU = decset(DEC.SYNCHRONIZED_UPDATE) +export const ESU = decreset(DEC.SYNCHRONIZED_UPDATE) +export const EBP = decset(DEC.BRACKETED_PASTE) +export const DBP = decreset(DEC.BRACKETED_PASTE) +export const EFE = decset(DEC.FOCUS_EVENTS) +export const DFE = decreset(DEC.FOCUS_EVENTS) +export const SHOW_CURSOR = decset(DEC.CURSOR_VISIBLE) +export const HIDE_CURSOR = decreset(DEC.CURSOR_VISIBLE) +export const ENTER_ALT_SCREEN = decset(DEC.ALT_SCREEN_CLEAR) +export const EXIT_ALT_SCREEN = decreset(DEC.ALT_SCREEN_CLEAR) +// Mouse tracking: 1000 reports button press/release/wheel, 1002 adds drag +// events (button-motion), 1003 adds all-motion (no button held — for +// hover), 1006 uses SGR format (CSI < btn;col;row M/m) instead of legacy +// X10 bytes. Combined: wheel + click/drag for selection + hover. +export const ENABLE_MOUSE_TRACKING = + decset(DEC.MOUSE_NORMAL) + decset(DEC.MOUSE_BUTTON) + decset(DEC.MOUSE_ANY) + decset(DEC.MOUSE_SGR) +export const DISABLE_MOUSE_TRACKING = + decreset(DEC.MOUSE_SGR) + decreset(DEC.MOUSE_ANY) + decreset(DEC.MOUSE_BUTTON) + decreset(DEC.MOUSE_NORMAL) diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/esc.ts b/ui-tui/packages/hermes-ink/src/ink/termio/esc.ts new file mode 100644 index 0000000000..4e38d7d035 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/esc.ts @@ -0,0 +1,69 @@ +/** + * ESC Sequence Parser + * + * Handles simple escape sequences: ESC + one or two characters + */ + +import type { Action } from './types.js' + +/** + * Parse a simple ESC sequence + * + * @param chars - Characters after ESC (not including ESC itself) + */ +export function parseEsc(chars: string): Action | null { + if (chars.length === 0) { + return null + } + + const first = chars[0]! + + // Full reset (RIS) + if (first === 'c') { + return { type: 'reset' } + } + + // Cursor save (DECSC) + if (first === '7') { + return { type: 'cursor', action: { type: 'save' } } + } + + // Cursor restore (DECRC) + if (first === '8') { + return { type: 'cursor', action: { type: 'restore' } } + } + + // Index - move cursor down (IND) + if (first === 'D') { + return { + type: 'cursor', + action: { type: 'move', direction: 'down', count: 1 } + } + } + + // Reverse index - move cursor up (RI) + if (first === 'M') { + return { + type: 'cursor', + action: { type: 'move', direction: 'up', count: 1 } + } + } + + // Next line (NEL) + if (first === 'E') { + return { type: 'cursor', action: { type: 'nextLine', count: 1 } } + } + + // Horizontal tab set (HTS) + if (first === 'H') { + return null // Tab stop, not commonly needed + } + + // Charset selection (ESC ( X, ESC ) X, etc.) - silently ignore + if ('()'.includes(first) && chars.length >= 2) { + return null + } + + // Unknown + return { type: 'unknown', sequence: `\x1b${chars}` } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/osc.ts b/ui-tui/packages/hermes-ink/src/ink/termio/osc.ts new file mode 100644 index 0000000000..49f222395a --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/osc.ts @@ -0,0 +1,554 @@ +/** + * OSC (Operating System Command) Types and Parser + */ + +import { Buffer } from 'buffer' + +import { env } from '../../utils/env.js' +import { execFileNoThrow } from '../../utils/execFileNoThrow.js' + +import { BEL, ESC, ESC_TYPE, SEP } from './ansi.js' +import type { Action, Color, TabStatusAction } from './types.js' + +export const OSC_PREFIX = ESC + String.fromCharCode(ESC_TYPE.OSC) + +/** String Terminator (ESC \) - alternative to BEL for terminating OSC */ +export const ST = ESC + '\\' + +/** Generate an OSC sequence: ESC ] p1;p2;...;pN + * Uses ST terminator for Kitty (avoids beeps), BEL for others */ +export function osc(...parts: (string | number)[]): string { + const terminator = env.terminal === 'kitty' ? ST : BEL + + return `${OSC_PREFIX}${parts.join(SEP)}${terminator}` +} + +/** + * Wrap an escape sequence for terminal multiplexer passthrough. + * tmux and GNU screen intercept escape sequences; DCS passthrough + * tunnels them to the outer terminal unmodified. + * + * tmux 3.3+ gates this behind `allow-passthrough` (default off). When off, + * tmux silently drops the whole DCS — no junk, no worse than unwrapped OSC. + * Users who want passthrough set it in their .tmux.conf; we don't mutate it. + * + * Do NOT wrap BEL: raw \x07 triggers tmux's bell-action (window flag); + * wrapped \x07 is opaque DCS payload and tmux never sees the bell. + */ +export function wrapForMultiplexer(sequence: string): string { + if (process.env['TMUX']) { + const escaped = sequence.replaceAll('\x1b', '\x1b\x1b') + + return `\x1bPtmux;${escaped}\x1b\\` + } + + if (process.env['STY']) { + return `\x1bP${sequence}\x1b\\` + } + + return sequence +} + +/** + * Which path setClipboard() will take, based on env state. Synchronous so + * callers can show an honest toast without awaiting the copy itself. + * + * - 'native': pbcopy (or equivalent) will run — high-confidence system + * clipboard write. tmux buffer may also be loaded as a bonus. + * - 'tmux-buffer': tmux load-buffer will run, but no native tool — paste + * with prefix+] works. System clipboard depends on tmux's set-clipboard + * option + outer terminal OSC 52 support; can't know from here. + * - 'osc52': only the raw OSC 52 sequence will be written to stdout. + * Best-effort; iTerm2 disables OSC 52 by default. + * + * pbcopy gating uses SSH_CONNECTION specifically, not SSH_TTY — tmux panes + * inherit SSH_TTY forever even after local reattach, but SSH_CONNECTION is + * in tmux's default update-environment set and gets cleared. + */ +export type ClipboardPath = 'native' | 'tmux-buffer' | 'osc52' + +export function getClipboardPath(): ClipboardPath { + const nativeAvailable = process.platform === 'darwin' && !process.env['SSH_CONNECTION'] + + if (nativeAvailable) { + return 'native' + } + + if (process.env['TMUX']) { + return 'tmux-buffer' + } + + return 'osc52' +} + +/** + * Wrap a payload in tmux's DCS passthrough: ESC P tmux ; ESC \ + * tmux forwards the payload to the outer terminal, bypassing its own parser. + * Inner ESCs must be doubled. Requires `set -g allow-passthrough on` in + * ~/.tmux.conf; without it, tmux silently drops the whole DCS (no regression). + */ +function tmuxPassthrough(payload: string): string { + return `${ESC}Ptmux;${payload.replaceAll(ESC, ESC + ESC)}${ST}` +} + +/** + * Load text into tmux's paste buffer via `tmux load-buffer`. + * -w (tmux 3.2+) propagates to the outer terminal's clipboard via tmux's + * own OSC 52 emission. -w is dropped for iTerm2: tmux's OSC 52 emission + * crashes the iTerm2 session over SSH. + * + * Returns true if the buffer was loaded successfully. + */ +export async function tmuxLoadBuffer(text: string): Promise { + if (!process.env['TMUX']) { + return false + } + + const args = process.env['LC_TERMINAL'] === 'iTerm2' ? ['load-buffer', '-'] : ['load-buffer', '-w', '-'] + + const { code } = await execFileNoThrow('tmux', args, { + input: text, + useCwd: false, + timeout: 2000 + }) + + return code === 0 +} + +/** + * OSC 52 clipboard write: ESC ] 52 ; c ; BEL/ST + * 'c' selects the clipboard (vs 'p' for primary selection on X11). + * + * When inside tmux ($TMUX set), `tmux load-buffer -w -` is the primary + * path. tmux's buffer is always reachable — works over SSH, survives + * detach/reattach, immune to stale env vars. The -w flag (tmux 3.2+) tells + * tmux to also propagate to the outer terminal via its own OSC 52 path, + * which tmux wraps correctly for the attached client. On older tmux, -w is + * ignored and the buffer is still loaded. -w is dropped for iTerm2 (#22432) + * because tmux's own OSC 52 emission (empty selection param: ESC]52;;b64) + * crashes iTerm2 over SSH. + * + * After load-buffer succeeds, we ALSO return a DCS-passthrough-wrapped + * OSC 52 for the caller to write to stdout. Our sequence uses explicit `c` + * (not tmux's crashy empty-param variant), so it sidesteps the #22432 path. + * With `allow-passthrough on` + an OSC-52-capable outer terminal, selection + * reaches the system clipboard; with either off, tmux silently drops the + * DCS and prefix+] still works. See Greg Smith's "free pony" in + * https://anthropic.slack.com/archives/C07VBSHV7EV/p1773177228548119. + * + * If load-buffer fails entirely, fall through to raw OSC 52. + * + * Outside tmux, write raw OSC 52 to stdout (caller handles the write). + * + * Local (no SSH_CONNECTION): also shell out to a native clipboard utility. + * OSC 52 and tmux -w both depend on terminal settings — iTerm2 disables + * OSC 52 by default, VS Code shows a permission prompt on first use. Native + * utilities (pbcopy/wl-copy/xclip/xsel/clip.exe) always work locally. Over + * SSH these would write to the remote clipboard — OSC 52 is the right path there. + * + * Returns the sequence for the caller to write to stdout (raw OSC 52 + * outside tmux, DCS-wrapped inside). + */ +export async function setClipboard(text: string): Promise { + const b64 = Buffer.from(text, 'utf8').toString('base64') + const raw = osc(OSC.CLIPBOARD, 'c', b64) + + // Native safety net — fire FIRST, before the tmux await, so a quick + // focus-switch after selecting doesn't race pbcopy. Previously this ran + // AFTER awaiting tmux load-buffer, adding ~50-100ms of subprocess latency + // before pbcopy even started — fast cmd+tab → paste would beat it + // (https://anthropic.slack.com/archives/C07VBSHV7EV/p1773943921788829). + // Gated on SSH_CONNECTION (not SSH_TTY) since tmux panes inherit SSH_TTY + // forever but SSH_CONNECTION is in tmux's default update-environment and + // clears on local attach. Fire-and-forget. + if (!process.env['SSH_CONNECTION']) { + copyNative(text) + } + + const tmuxBufferLoaded = await tmuxLoadBuffer(text) + + // Inner OSC uses BEL directly (not osc()) — ST's ESC would need doubling + // too, and BEL works everywhere for OSC 52. + if (tmuxBufferLoaded) { + return tmuxPassthrough(`${ESC}]52;c;${b64}${BEL}`) + } + + return raw +} + +// Linux clipboard tool: undefined = not yet probed, null = none available. +// Probe order: wl-copy (Wayland) → xclip (X11) → xsel (X11 fallback). +// Cached after first attempt so repeated mouse-ups skip the probe chain. +let linuxCopy: 'wl-copy' | 'xclip' | 'xsel' | null | undefined + +/** + * Shell out to a native clipboard utility as a safety net for OSC 52. + * Only called when not in an SSH session (over SSH, these would write to + * the remote machine's clipboard — OSC 52 is the right path there). + * Fire-and-forget: failures are silent since OSC 52 may have succeeded. + */ +function copyNative(text: string): void { + const opts = { input: text, useCwd: false, timeout: 2000 } + + switch (process.platform) { + case 'darwin': + void execFileNoThrow('pbcopy', [], opts) + + return + case 'linux': { + if (linuxCopy === null) { + return + } + + if (linuxCopy === 'wl-copy') { + void execFileNoThrow('wl-copy', [], opts) + + return + } + + if (linuxCopy === 'xclip') { + void execFileNoThrow('xclip', ['-selection', 'clipboard'], opts) + + return + } + + if (linuxCopy === 'xsel') { + void execFileNoThrow('xsel', ['--clipboard', '--input'], opts) + + return + } + + // First call: probe wl-copy (Wayland) then xclip/xsel (X11), cache winner. + void execFileNoThrow('wl-copy', [], opts).then(r => { + if (r.code === 0) { + linuxCopy = 'wl-copy' + + return + } + + void execFileNoThrow('xclip', ['-selection', 'clipboard'], opts).then(r2 => { + if (r2.code === 0) { + linuxCopy = 'xclip' + + return + } + + void execFileNoThrow('xsel', ['--clipboard', '--input'], opts).then(r3 => { + linuxCopy = r3.code === 0 ? 'xsel' : null + }) + }) + }) + + return + } + + case 'win32': + // clip.exe is always available on Windows. Unicode handling is + // imperfect (system locale encoding) but good enough for a fallback. + void execFileNoThrow('clip', [], opts) + + return + } +} + +/** @internal test-only */ +export function _resetLinuxCopyCache(): void { + linuxCopy = undefined +} + +/** + * OSC command numbers + */ +export const OSC = { + SET_TITLE_AND_ICON: 0, + SET_ICON: 1, + SET_TITLE: 2, + SET_COLOR: 4, + SET_CWD: 7, + HYPERLINK: 8, + ITERM2: 9, // iTerm2 proprietary sequences + SET_FG_COLOR: 10, + SET_BG_COLOR: 11, + SET_CURSOR_COLOR: 12, + CLIPBOARD: 52, + KITTY: 99, // Kitty notification protocol + RESET_COLOR: 104, + RESET_FG_COLOR: 110, + RESET_BG_COLOR: 111, + RESET_CURSOR_COLOR: 112, + SEMANTIC_PROMPT: 133, + GHOSTTY: 777, // Ghostty notification protocol + TAB_STATUS: 21337 // Tab status extension +} as const + +/** + * Parse an OSC sequence into an action + * + * @param content - The sequence content (without ESC ] and terminator) + */ +export function parseOSC(content: string): Action | null { + const semicolonIdx = content.indexOf(';') + const command = semicolonIdx >= 0 ? content.slice(0, semicolonIdx) : content + const data = semicolonIdx >= 0 ? content.slice(semicolonIdx + 1) : '' + + const commandNum = parseInt(command, 10) + + // Window/icon title + if (commandNum === OSC.SET_TITLE_AND_ICON) { + return { type: 'title', action: { type: 'both', title: data } } + } + + if (commandNum === OSC.SET_ICON) { + return { type: 'title', action: { type: 'iconName', name: data } } + } + + if (commandNum === OSC.SET_TITLE) { + return { type: 'title', action: { type: 'windowTitle', title: data } } + } + + // Hyperlinks (OSC 8) + if (commandNum === OSC.HYPERLINK) { + const parts = data.split(';') + const paramsStr = parts[0] ?? '' + const url = parts.slice(1).join(';') + + if (url === '') { + return { type: 'link', action: { type: 'end' } } + } + + const params: Record = {} + + if (paramsStr) { + for (const pair of paramsStr.split(':')) { + const eqIdx = pair.indexOf('=') + + if (eqIdx >= 0) { + params[pair.slice(0, eqIdx)] = pair.slice(eqIdx + 1) + } + } + } + + return { + type: 'link', + action: { + type: 'start', + url, + params: Object.keys(params).length > 0 ? params : undefined + } + } + } + + // Tab status (OSC 21337) + if (commandNum === OSC.TAB_STATUS) { + return { type: 'tabStatus', action: parseTabStatus(data) } + } + + return { type: 'unknown', sequence: `\x1b]${content}` } +} + +/** + * Parse an XParseColor-style color spec into an RGB Color. + * Accepts `#RRGGBB` and `rgb:R/G/B` (1–4 hex digits per component, scaled + * to 8-bit). Returns null on parse failure. + */ +export function parseOscColor(spec: string): Color | null { + const hex = spec.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i) + + if (hex) { + return { + type: 'rgb', + r: parseInt(hex[1]!, 16), + g: parseInt(hex[2]!, 16), + b: parseInt(hex[3]!, 16) + } + } + + const rgb = spec.match(/^rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})$/i) + + if (rgb) { + // XParseColor: N hex digits → value / (16^N - 1), scale to 0-255 + const scale = (s: string) => Math.round((parseInt(s, 16) / (16 ** s.length - 1)) * 255) + + return { + type: 'rgb', + r: scale(rgb[1]!), + g: scale(rgb[2]!), + b: scale(rgb[3]!) + } + } + + return null +} + +/** + * Parse OSC 21337 payload: `key=value;key=value;...` with `\;` and `\\` + * escapes inside values. Bare key or `key=` clears that field; unknown + * keys are ignored. + */ +function parseTabStatus(data: string): TabStatusAction { + const action: TabStatusAction = {} + + for (const [key, value] of splitTabStatusPairs(data)) { + switch (key) { + case 'indicator': + action.indicator = value === '' ? null : parseOscColor(value) + + break + + case 'status': + action.status = value === '' ? null : value + + break + + case 'status-color': + action.statusColor = value === '' ? null : parseOscColor(value) + + break + } + } + + return action +} + +/** Split `k=v;k=v` honoring `\;` and `\\` escapes. Yields [key, unescapedValue]. */ +function* splitTabStatusPairs(data: string): Generator<[string, string]> { + let key = '' + let val = '' + let inVal = false + let esc = false + + for (const c of data) { + if (esc) { + if (inVal) { + val += c + } else { + key += c + } + + esc = false + } else if (c === '\\') { + esc = true + } else if (c === ';') { + yield [key, val] + key = '' + val = '' + inVal = false + } else if (c === '=' && !inVal) { + inVal = true + } else if (inVal) { + val += c + } else { + key += c + } + } + + if (key || inVal) { + yield [key, val] + } +} + +// Output generators + +/** Start a hyperlink (OSC 8). Auto-assigns an id= param derived from the URL + * so terminals group wrapped lines of the same link together (the spec says + * cells with matching URI *and* nonempty id are joined; without an id each + * wrapped line is a separate link — inconsistent hover, partial tooltips). + * Empty url = close sequence (empty params per spec). */ +export function link(url: string, params?: Record): string { + if (!url) { + return LINK_END + } + + const p = { id: osc8Id(url), ...params } + + const paramStr = Object.entries(p) + .map(([k, v]) => `${k}=${v}`) + .join(':') + + return osc(OSC.HYPERLINK, paramStr, url) +} + +function osc8Id(url: string): string { + let h = 0 + + for (let i = 0; i < url.length; i++) { + h = ((h << 5) - h + url.charCodeAt(i)) | 0 + } + + return (h >>> 0).toString(36) +} + +/** End a hyperlink (OSC 8) */ +export const LINK_END = osc(OSC.HYPERLINK, '', '') + +// iTerm2 OSC 9 subcommands + +/** iTerm2 OSC 9 subcommand numbers */ +export const ITERM2 = { + NOTIFY: 0, + BADGE: 2, + PROGRESS: 4 +} as const + +/** Progress operation codes (for use with ITERM2.PROGRESS) */ +export const PROGRESS = { + CLEAR: 0, + SET: 1, + ERROR: 2, + INDETERMINATE: 3 +} as const + +/** + * Clear iTerm2 progress bar sequence (OSC 9;4;0;BEL) + * Uses BEL terminator since this is for cleanup (not runtime notification) + * and we want to ensure it's always sent regardless of terminal type. + */ +export const CLEAR_ITERM2_PROGRESS = `${OSC_PREFIX}${OSC.ITERM2};${ITERM2.PROGRESS};${PROGRESS.CLEAR};${BEL}` + +/** + * Clear terminal title sequence (OSC 0 with empty string + BEL). + * Uses BEL terminator for cleanup — safe on all terminals. + */ +export const CLEAR_TERMINAL_TITLE = `${OSC_PREFIX}${OSC.SET_TITLE_AND_ICON};${BEL}` + +/** Clear all three OSC 21337 tab-status fields. Used on exit. */ +export const CLEAR_TAB_STATUS = osc(OSC.TAB_STATUS, 'indicator=;status=;status-color=') + +/** + * Gate for emitting OSC 21337 (tab-status indicator). Ant-only while the + * spec is unstable. Terminals that don't recognize it discard silently, so + * emission is safe unconditionally — we don't gate on terminal detection + * since support is expected across several terminals. + * + * Callers must wrap output with wrapForMultiplexer() so tmux/screen + * DCS-passthrough carries the sequence to the outer terminal. + */ +export function supportsTabStatus(): boolean { + return process.env.USER_TYPE === 'ant' +} + +/** + * Emit an OSC 21337 tab-status sequence. Omitted fields are left unchanged + * by the receiving terminal; `null` sends an empty value to clear. + * `;` and `\` in status text are escaped per the spec. + */ +export function tabStatus(fields: TabStatusAction): string { + const parts: string[] = [] + + const rgb = (c: Color) => + c.type === 'rgb' ? `#${[c.r, c.g, c.b].map(n => n.toString(16).padStart(2, '0')).join('')}` : '' + + if ('indicator' in fields) { + parts.push(`indicator=${fields.indicator ? rgb(fields.indicator) : ''}`) + } + + if ('status' in fields) { + parts.push(`status=${fields.status?.replaceAll('\\', '\\\\').replaceAll(';', '\\;') ?? ''}`) + } + + if ('statusColor' in fields) { + parts.push(`status-color=${fields.statusColor ? rgb(fields.statusColor) : ''}`) + } + + return osc(OSC.TAB_STATUS, parts.join(';')) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/parser.ts b/ui-tui/packages/hermes-ink/src/ink/termio/parser.ts new file mode 100644 index 0000000000..0f58d6f203 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/parser.ts @@ -0,0 +1,467 @@ +/** + * ANSI Parser - Semantic Action Generator + * + * A streaming parser for ANSI escape sequences that produces semantic actions. + * Uses the tokenizer for escape sequence boundary detection, then interprets + * each sequence to produce structured actions. + * + * Key design decisions: + * - Streaming: can process input incrementally + * - Semantic output: produces structured actions, not string tokens + * - Style tracking: maintains current text style state + */ + +import { getGraphemeSegmenter } from '../../utils/intl.js' + +import { C0 } from './ansi.js' +import { CSI, CURSOR_STYLES, ERASE_DISPLAY, ERASE_LINE_REGION } from './csi.js' +import { DEC } from './dec.js' +import { parseEsc } from './esc.js' +import { parseOSC } from './osc.js' +import { applySGR } from './sgr.js' +import { createTokenizer, type Token, type Tokenizer } from './tokenize.js' +import type { Action, Grapheme, TextStyle } from './types.js' +import { defaultStyle } from './types.js' + +// ============================================================================= +// Grapheme Utilities +// ============================================================================= + +function isEmoji(codePoint: number): boolean { + return ( + (codePoint >= 0x2600 && codePoint <= 0x26ff) || + (codePoint >= 0x2700 && codePoint <= 0x27bf) || + (codePoint >= 0x1f300 && codePoint <= 0x1f9ff) || + (codePoint >= 0x1fa00 && codePoint <= 0x1faff) || + (codePoint >= 0x1f1e0 && codePoint <= 0x1f1ff) + ) +} + +function isEastAsianWide(codePoint: number): boolean { + return ( + (codePoint >= 0x1100 && codePoint <= 0x115f) || + (codePoint >= 0x2e80 && codePoint <= 0x9fff) || + (codePoint >= 0xac00 && codePoint <= 0xd7a3) || + (codePoint >= 0xf900 && codePoint <= 0xfaff) || + (codePoint >= 0xfe10 && codePoint <= 0xfe1f) || + (codePoint >= 0xfe30 && codePoint <= 0xfe6f) || + (codePoint >= 0xff00 && codePoint <= 0xff60) || + (codePoint >= 0xffe0 && codePoint <= 0xffe6) || + (codePoint >= 0x20000 && codePoint <= 0x2fffd) || + (codePoint >= 0x30000 && codePoint <= 0x3fffd) + ) +} + +function hasMultipleCodepoints(str: string): boolean { + let count = 0 + + for (const _ of str) { + count++ + + if (count > 1) { + return true + } + } + + return false +} + +function graphemeWidth(grapheme: string): 1 | 2 { + if (hasMultipleCodepoints(grapheme)) { + return 2 + } + + const codePoint = grapheme.codePointAt(0) + + if (codePoint === undefined) { + return 1 + } + + if (isEmoji(codePoint) || isEastAsianWide(codePoint)) { + return 2 + } + + return 1 +} + +function* segmentGraphemes(str: string): Generator { + for (const { segment } of getGraphemeSegmenter().segment(str)) { + yield { value: segment, width: graphemeWidth(segment) } + } +} + +// ============================================================================= +// Sequence Parsing +// ============================================================================= + +function parseCSIParams(paramStr: string): number[] { + if (paramStr === '') { + return [] + } + + return paramStr.split(/[;:]/).map(s => (s === '' ? 0 : parseInt(s, 10))) +} + +/** Parse a raw CSI sequence (e.g., "\x1b[31m") into an action */ +function parseCSI(rawSequence: string): Action | null { + const inner = rawSequence.slice(2) + + if (inner.length === 0) { + return null + } + + const finalByte = inner.charCodeAt(inner.length - 1) + const beforeFinal = inner.slice(0, -1) + + let privateMode = '' + let paramStr = beforeFinal + let intermediate = '' + + if (beforeFinal.length > 0 && '?>='.includes(beforeFinal[0]!)) { + privateMode = beforeFinal[0]! + paramStr = beforeFinal.slice(1) + } + + const intermediateMatch = paramStr.match(/([^0-9;:]+)$/) + + if (intermediateMatch) { + intermediate = intermediateMatch[1]! + paramStr = paramStr.slice(0, -intermediate.length) + } + + const params = parseCSIParams(paramStr) + const p0 = params[0] ?? 1 + const p1 = params[1] ?? 1 + + // SGR (Select Graphic Rendition) + if (finalByte === CSI.SGR && privateMode === '') { + return { type: 'sgr', params: paramStr } + } + + // Cursor movement + if (finalByte === CSI.CUU) { + return { + type: 'cursor', + action: { type: 'move', direction: 'up', count: p0 } + } + } + + if (finalByte === CSI.CUD) { + return { + type: 'cursor', + action: { type: 'move', direction: 'down', count: p0 } + } + } + + if (finalByte === CSI.CUF) { + return { + type: 'cursor', + action: { type: 'move', direction: 'forward', count: p0 } + } + } + + if (finalByte === CSI.CUB) { + return { + type: 'cursor', + action: { type: 'move', direction: 'back', count: p0 } + } + } + + if (finalByte === CSI.CNL) { + return { type: 'cursor', action: { type: 'nextLine', count: p0 } } + } + + if (finalByte === CSI.CPL) { + return { type: 'cursor', action: { type: 'prevLine', count: p0 } } + } + + if (finalByte === CSI.CHA) { + return { type: 'cursor', action: { type: 'column', col: p0 } } + } + + if (finalByte === CSI.CUP || finalByte === CSI.HVP) { + return { type: 'cursor', action: { type: 'position', row: p0, col: p1 } } + } + + if (finalByte === CSI.VPA) { + return { type: 'cursor', action: { type: 'row', row: p0 } } + } + + // Erase + if (finalByte === CSI.ED) { + const region = ERASE_DISPLAY[params[0] ?? 0] ?? 'toEnd' + + return { type: 'erase', action: { type: 'display', region } } + } + + if (finalByte === CSI.EL) { + const region = ERASE_LINE_REGION[params[0] ?? 0] ?? 'toEnd' + + return { type: 'erase', action: { type: 'line', region } } + } + + if (finalByte === CSI.ECH) { + return { type: 'erase', action: { type: 'chars', count: p0 } } + } + + // Scroll + if (finalByte === CSI.SU) { + return { type: 'scroll', action: { type: 'up', count: p0 } } + } + + if (finalByte === CSI.SD) { + return { type: 'scroll', action: { type: 'down', count: p0 } } + } + + if (finalByte === CSI.DECSTBM) { + return { + type: 'scroll', + action: { type: 'setRegion', top: p0, bottom: p1 } + } + } + + // Cursor save/restore + if (finalByte === CSI.SCOSC) { + return { type: 'cursor', action: { type: 'save' } } + } + + if (finalByte === CSI.SCORC) { + return { type: 'cursor', action: { type: 'restore' } } + } + + // Cursor style + if (finalByte === CSI.DECSCUSR && intermediate === ' ') { + const styleInfo = CURSOR_STYLES[p0] ?? CURSOR_STYLES[0]! + + return { type: 'cursor', action: { type: 'style', ...styleInfo } } + } + + // Private modes + if (privateMode === '?' && (finalByte === CSI.SM || finalByte === CSI.RM)) { + const enabled = finalByte === CSI.SM + + if (p0 === DEC.CURSOR_VISIBLE) { + return { + type: 'cursor', + action: enabled ? { type: 'show' } : { type: 'hide' } + } + } + + if (p0 === DEC.ALT_SCREEN_CLEAR || p0 === DEC.ALT_SCREEN) { + return { type: 'mode', action: { type: 'alternateScreen', enabled } } + } + + if (p0 === DEC.BRACKETED_PASTE) { + return { type: 'mode', action: { type: 'bracketedPaste', enabled } } + } + + if (p0 === DEC.MOUSE_NORMAL) { + return { + type: 'mode', + action: { type: 'mouseTracking', mode: enabled ? 'normal' : 'off' } + } + } + + if (p0 === DEC.MOUSE_BUTTON) { + return { + type: 'mode', + action: { type: 'mouseTracking', mode: enabled ? 'button' : 'off' } + } + } + + if (p0 === DEC.MOUSE_ANY) { + return { + type: 'mode', + action: { type: 'mouseTracking', mode: enabled ? 'any' : 'off' } + } + } + + if (p0 === DEC.FOCUS_EVENTS) { + return { type: 'mode', action: { type: 'focusEvents', enabled } } + } + } + + return { type: 'unknown', sequence: rawSequence } +} + +/** + * Identify the type of escape sequence from its raw form. + */ +function identifySequence(seq: string): 'csi' | 'osc' | 'esc' | 'ss3' | 'unknown' { + if (seq.length < 2) { + return 'unknown' + } + + if (seq.charCodeAt(0) !== C0.ESC) { + return 'unknown' + } + + const second = seq.charCodeAt(1) + + if (second === 0x5b) { + return 'csi' + } // [ + + if (second === 0x5d) { + return 'osc' + } // ] + + if (second === 0x4f) { + return 'ss3' + } // O + + return 'esc' +} + +// ============================================================================= +// Main Parser +// ============================================================================= + +/** + * Parser class - maintains state for streaming/incremental parsing + * + * Usage: + * ```typescript + * const parser = new Parser() + * const actions1 = parser.feed('partial\x1b[') + * const actions2 = parser.feed('31mred') // state maintained internally + * ``` + */ +export class Parser { + private tokenizer: Tokenizer = createTokenizer() + + style: TextStyle = defaultStyle() + inLink = false + linkUrl: string | undefined + + reset(): void { + this.tokenizer.reset() + this.style = defaultStyle() + this.inLink = false + this.linkUrl = undefined + } + + /** Feed input and get resulting actions */ + feed(input: string): Action[] { + const tokens = this.tokenizer.feed(input) + const actions: Action[] = [] + + for (const token of tokens) { + const tokenActions = this.processToken(token) + actions.push(...tokenActions) + } + + return actions + } + + private processToken(token: Token): Action[] { + switch (token.type) { + case 'text': + return this.processText(token.value) + + case 'sequence': + return this.processSequence(token.value) + } + } + + private processText(text: string): Action[] { + // Handle BEL characters embedded in text + const actions: Action[] = [] + let current = '' + + for (const char of text) { + if (char.charCodeAt(0) === C0.BEL) { + if (current) { + const graphemes = [...segmentGraphemes(current)] + + if (graphemes.length > 0) { + actions.push({ type: 'text', graphemes, style: { ...this.style } }) + } + + current = '' + } + + actions.push({ type: 'bell' }) + } else { + current += char + } + } + + if (current) { + const graphemes = [...segmentGraphemes(current)] + + if (graphemes.length > 0) { + actions.push({ type: 'text', graphemes, style: { ...this.style } }) + } + } + + return actions + } + + private processSequence(seq: string): Action[] { + const seqType = identifySequence(seq) + + switch (seqType) { + case 'csi': { + const action = parseCSI(seq) + + if (!action) { + return [] + } + + if (action.type === 'sgr') { + this.style = applySGR(action.params, this.style) + + return [] + } + + return [action] + } + + case 'osc': { + // Extract OSC content (between ESC ] and terminator) + let content = seq.slice(2) + + // Remove terminator (BEL or ESC \) + if (content.endsWith('\x07')) { + content = content.slice(0, -1) + } else if (content.endsWith('\x1b\\')) { + content = content.slice(0, -2) + } + + const action = parseOSC(content) + + if (action) { + if (action.type === 'link') { + if (action.action.type === 'start') { + this.inLink = true + this.linkUrl = action.action.url + } else { + this.inLink = false + this.linkUrl = undefined + } + } + + return [action] + } + + return [] + } + + case 'esc': { + const escContent = seq.slice(1) + const action = parseEsc(escContent) + + return action ? [action] : [] + } + + case 'ss3': + // SS3 sequences are typically cursor keys in application mode + // For output parsing, treat as unknown + return [{ type: 'unknown', sequence: seq }] + + default: + return [{ type: 'unknown', sequence: seq }] + } + } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/sgr.ts b/ui-tui/packages/hermes-ink/src/ink/termio/sgr.ts new file mode 100644 index 0000000000..67a1f6b385 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/sgr.ts @@ -0,0 +1,362 @@ +/** + * SGR (Select Graphic Rendition) Parser + * + * Parses SGR parameters and applies them to a TextStyle. + * Handles both semicolon (;) and colon (:) separated parameters. + */ + +import type { NamedColor, TextStyle, UnderlineStyle } from './types.js' +import { defaultStyle } from './types.js' + +const NAMED_COLORS: NamedColor[] = [ + 'black', + 'red', + 'green', + 'yellow', + 'blue', + 'magenta', + 'cyan', + 'white', + 'brightBlack', + 'brightRed', + 'brightGreen', + 'brightYellow', + 'brightBlue', + 'brightMagenta', + 'brightCyan', + 'brightWhite' +] + +const UNDERLINE_STYLES: UnderlineStyle[] = ['none', 'single', 'double', 'curly', 'dotted', 'dashed'] + +type Param = { value: number | null; subparams: number[]; colon: boolean } + +function parseParams(str: string): Param[] { + if (str === '') { + return [{ value: 0, subparams: [], colon: false }] + } + + const result: Param[] = [] + let current: Param = { value: null, subparams: [], colon: false } + let num = '' + let inSub = false + + for (let i = 0; i <= str.length; i++) { + const c = str[i] + + if (c === ';' || c === undefined) { + const n = num === '' ? null : parseInt(num, 10) + + if (inSub) { + if (n !== null) { + current.subparams.push(n) + } + } else { + current.value = n + } + + result.push(current) + current = { value: null, subparams: [], colon: false } + num = '' + inSub = false + } else if (c === ':') { + const n = num === '' ? null : parseInt(num, 10) + + if (!inSub) { + current.value = n + current.colon = true + inSub = true + } else { + if (n !== null) { + current.subparams.push(n) + } + } + + num = '' + } else if (c >= '0' && c <= '9') { + num += c + } + } + + return result +} + +function parseExtendedColor( + params: Param[], + idx: number +): { r: number; g: number; b: number } | { index: number } | null { + const p = params[idx] + + if (!p) { + return null + } + + if (p.colon && p.subparams.length >= 1) { + if (p.subparams[0] === 5 && p.subparams.length >= 2) { + return { index: p.subparams[1]! } + } + + if (p.subparams[0] === 2 && p.subparams.length >= 4) { + const off = p.subparams.length >= 5 ? 1 : 0 + + return { + r: p.subparams[1 + off]!, + g: p.subparams[2 + off]!, + b: p.subparams[3 + off]! + } + } + } + + const next = params[idx + 1] + + if (!next) { + return null + } + + if (next.value === 5 && params[idx + 2]?.value !== null && params[idx + 2]?.value !== undefined) { + return { index: params[idx + 2]!.value! } + } + + if (next.value === 2) { + const r = params[idx + 2]?.value + const g = params[idx + 3]?.value + const b = params[idx + 4]?.value + + if (r !== null && r !== undefined && g !== null && g !== undefined && b !== null && b !== undefined) { + return { r, g, b } + } + } + + return null +} + +export function applySGR(paramStr: string, style: TextStyle): TextStyle { + const params = parseParams(paramStr) + let s = { ...style } + let i = 0 + + while (i < params.length) { + const p = params[i]! + const code = p.value ?? 0 + + if (code === 0) { + s = defaultStyle() + i++ + + continue + } + + if (code === 1) { + s.bold = true + i++ + + continue + } + + if (code === 2) { + s.dim = true + i++ + + continue + } + + if (code === 3) { + s.italic = true + i++ + + continue + } + + if (code === 4) { + s.underline = p.colon ? (UNDERLINE_STYLES[p.subparams[0]!] ?? 'single') : 'single' + i++ + + continue + } + + if (code === 5 || code === 6) { + s.blink = true + i++ + + continue + } + + if (code === 7) { + s.inverse = true + i++ + + continue + } + + if (code === 8) { + s.hidden = true + i++ + + continue + } + + if (code === 9) { + s.strikethrough = true + i++ + + continue + } + + if (code === 21) { + s.underline = 'double' + i++ + + continue + } + + if (code === 22) { + s.bold = false + s.dim = false + i++ + + continue + } + + if (code === 23) { + s.italic = false + i++ + + continue + } + + if (code === 24) { + s.underline = 'none' + i++ + + continue + } + + if (code === 25) { + s.blink = false + i++ + + continue + } + + if (code === 27) { + s.inverse = false + i++ + + continue + } + + if (code === 28) { + s.hidden = false + i++ + + continue + } + + if (code === 29) { + s.strikethrough = false + i++ + + continue + } + + if (code === 53) { + s.overline = true + i++ + + continue + } + + if (code === 55) { + s.overline = false + i++ + + continue + } + + if (code >= 30 && code <= 37) { + s.fg = { type: 'named', name: NAMED_COLORS[code - 30]! } + i++ + + continue + } + + if (code === 39) { + s.fg = { type: 'default' } + i++ + + continue + } + + if (code >= 40 && code <= 47) { + s.bg = { type: 'named', name: NAMED_COLORS[code - 40]! } + i++ + + continue + } + + if (code === 49) { + s.bg = { type: 'default' } + i++ + + continue + } + + if (code >= 90 && code <= 97) { + s.fg = { type: 'named', name: NAMED_COLORS[code - 90 + 8]! } + i++ + + continue + } + + if (code >= 100 && code <= 107) { + s.bg = { type: 'named', name: NAMED_COLORS[code - 100 + 8]! } + i++ + + continue + } + + if (code === 38) { + const c = parseExtendedColor(params, i) + + if (c) { + s.fg = 'index' in c ? { type: 'indexed', index: c.index } : { type: 'rgb', ...c } + i += p.colon ? 1 : 'index' in c ? 3 : 5 + + continue + } + } + + if (code === 48) { + const c = parseExtendedColor(params, i) + + if (c) { + s.bg = 'index' in c ? { type: 'indexed', index: c.index } : { type: 'rgb', ...c } + i += p.colon ? 1 : 'index' in c ? 3 : 5 + + continue + } + } + + if (code === 58) { + const c = parseExtendedColor(params, i) + + if (c) { + s.underlineColor = 'index' in c ? { type: 'indexed', index: c.index } : { type: 'rgb', ...c } + i += p.colon ? 1 : 'index' in c ? 3 : 5 + + continue + } + } + + if (code === 59) { + s.underlineColor = { type: 'default' } + i++ + + continue + } + + i++ + } + + return s +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/tokenize.ts b/ui-tui/packages/hermes-ink/src/ink/termio/tokenize.ts new file mode 100644 index 0000000000..40ba7e2143 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/tokenize.ts @@ -0,0 +1,316 @@ +/** + * Input Tokenizer - Escape sequence boundary detection + * + * Splits terminal input into tokens: text chunks and raw escape sequences. + * Unlike the Parser which interprets sequences semantically, this just + * identifies boundaries for use by keyboard input parsing. + */ + +import { C0, ESC_TYPE, isEscFinal } from './ansi.js' +import { isCSIFinal, isCSIIntermediate, isCSIParam } from './csi.js' + +export type Token = { type: 'text'; value: string } | { type: 'sequence'; value: string } + +type State = 'ground' | 'escape' | 'escapeIntermediate' | 'csi' | 'ss3' | 'osc' | 'dcs' | 'apc' + +export type Tokenizer = { + /** Feed input and get resulting tokens */ + feed(input: string): Token[] + /** Flush any buffered incomplete sequences */ + flush(): Token[] + /** Reset tokenizer state */ + reset(): void + /** Get any buffered incomplete sequence */ + buffer(): string +} + +type TokenizerOptions = { + /** + * Treat `CSI M` as an X10 mouse event prefix and consume 3 payload bytes. + * Only enable for stdin input — `\x1b[M` is also CSI DL (Delete Lines) in + * output streams, and enabling this there swallows display text. Default false. + */ + x10Mouse?: boolean +} + +/** + * Create a streaming tokenizer for terminal input. + * + * Usage: + * ```typescript + * const tokenizer = createTokenizer() + * const tokens1 = tokenizer.feed('hello\x1b[') + * const tokens2 = tokenizer.feed('A') // completes the escape sequence + * const remaining = tokenizer.flush() // force output incomplete sequences + * ``` + */ +export function createTokenizer(options?: TokenizerOptions): Tokenizer { + let currentState: State = 'ground' + let currentBuffer = '' + const x10Mouse = options?.x10Mouse ?? false + + return { + feed(input: string): Token[] { + const result = tokenize(input, currentState, currentBuffer, false, x10Mouse) + + currentState = result.state.state + currentBuffer = result.state.buffer + + return result.tokens + }, + + flush(): Token[] { + const result = tokenize('', currentState, currentBuffer, true, x10Mouse) + currentState = result.state.state + currentBuffer = result.state.buffer + + return result.tokens + }, + + reset(): void { + currentState = 'ground' + currentBuffer = '' + }, + + buffer(): string { + return currentBuffer + } + } +} + +type InternalState = { + state: State + buffer: string +} + +function tokenize( + input: string, + initialState: State, + initialBuffer: string, + flush: boolean, + x10Mouse: boolean +): { tokens: Token[]; state: InternalState } { + const tokens: Token[] = [] + + const result: InternalState = { + state: initialState, + buffer: '' + } + + const data = initialBuffer + input + let i = 0 + let textStart = 0 + let seqStart = 0 + + const flushText = (): void => { + if (i > textStart) { + const text = data.slice(textStart, i) + + if (text) { + tokens.push({ type: 'text', value: text }) + } + } + + textStart = i + } + + const emitSequence = (seq: string): void => { + if (seq) { + tokens.push({ type: 'sequence', value: seq }) + } + + result.state = 'ground' + textStart = i + } + + while (i < data.length) { + const code = data.charCodeAt(i) + + switch (result.state) { + case 'ground': + if (code === C0.ESC) { + flushText() + seqStart = i + result.state = 'escape' + i++ + } else { + i++ + } + + break + + case 'escape': + if (code === ESC_TYPE.CSI) { + result.state = 'csi' + i++ + } else if (code === ESC_TYPE.OSC) { + result.state = 'osc' + i++ + } else if (code === ESC_TYPE.DCS) { + result.state = 'dcs' + i++ + } else if (code === ESC_TYPE.APC) { + result.state = 'apc' + i++ + } else if (code === 0x4f) { + // 'O' - SS3 + result.state = 'ss3' + i++ + } else if (isCSIIntermediate(code)) { + // Intermediate byte (e.g., ESC ( for charset) - continue buffering + result.state = 'escapeIntermediate' + i++ + } else if (isEscFinal(code)) { + // Two-character escape sequence + i++ + emitSequence(data.slice(seqStart, i)) + } else if (code === C0.ESC) { + // Double escape - emit first, start new + emitSequence(data.slice(seqStart, i)) + seqStart = i + result.state = 'escape' + i++ + } else { + // Invalid - treat ESC as text + result.state = 'ground' + textStart = seqStart + } + + break + + case 'escapeIntermediate': + // After intermediate byte(s), wait for final byte + if (isCSIIntermediate(code)) { + // More intermediate bytes + i++ + } else if (isEscFinal(code)) { + // Final byte - complete the sequence + i++ + emitSequence(data.slice(seqStart, i)) + } else { + // Invalid - treat as text + result.state = 'ground' + textStart = seqStart + } + + break + + case 'csi': + // X10 mouse: CSI M + 3 raw payload bytes (Cb+32, Cx+32, Cy+32). + // M immediately after [ (offset 2) means no params — SGR mouse + // (CSI < … M) has a `<` param byte first and reaches M at offset > 2. + // Terminals that ignore DECSET 1006 but honor 1000/1002 emit this + // legacy encoding; without this branch the 3 payload bytes leak + // through as text (`` `rK `` / `arK` garbage in the prompt). + // + // Gated on x10Mouse — `\x1b[M` is also CSI DL (Delete Lines) and + // blindly consuming 3 chars corrupts output rendering (Parser/Ansi) + // and fragments bracketed-paste PASTE_END. Only stdin enables this. + // The ≥0x20 check on each payload slot is belt-and-suspenders: X10 + // guarantees Cb≥32, Cx≥33, Cy≥33, so a control byte (ESC=0x1B) in + // any slot means this is CSI DL adjacent to another sequence, not a + // mouse event. Checking all three slots prevents PASTE_END's ESC + // from being consumed when paste content ends in `\x1b[M`+0-2 chars. + // + // Known limitation: this counts JS string chars, but X10 is byte- + // oriented and stdin uses utf8 encoding (App.tsx). At col 162-191 × + // row 96-159 the two coord bytes (0xC2-0xDF, 0x80-0xBF) form a valid + // UTF-8 2-byte sequence and collapse to one char — the length check + // fails and the event buffers until the next keypress absorbs it. + // Fixing this requires latin1 stdin; X10's 223-coord cap is exactly + // why SGR was invented, and no-SGR terminals at 162+ cols are rare. + if ( + x10Mouse && + code === 0x4d /* M */ && + i - seqStart === 2 && + (i + 1 >= data.length || data.charCodeAt(i + 1) >= 0x20) && + (i + 2 >= data.length || data.charCodeAt(i + 2) >= 0x20) && + (i + 3 >= data.length || data.charCodeAt(i + 3) >= 0x20) + ) { + if (i + 4 <= data.length) { + i += 4 + emitSequence(data.slice(seqStart, i)) + } else { + // Incomplete — exit loop; end-of-input buffers from seqStart. + // Re-entry re-tokenizes from ground via the invalid-CSI fallthrough. + i = data.length + } + + break + } + + if (isCSIFinal(code)) { + i++ + emitSequence(data.slice(seqStart, i)) + } else if (isCSIParam(code) || isCSIIntermediate(code)) { + i++ + } else { + // Invalid CSI - abort, treat as text + result.state = 'ground' + textStart = seqStart + } + + break + + case 'ss3': + // SS3 sequences: ESC O followed by a single final byte + if (code >= 0x40 && code <= 0x7e) { + i++ + emitSequence(data.slice(seqStart, i)) + } else { + // Invalid - treat as text + result.state = 'ground' + textStart = seqStart + } + + break + + case 'osc': + if (code === C0.BEL) { + i++ + emitSequence(data.slice(seqStart, i)) + } else if (code === C0.ESC && i + 1 < data.length && data.charCodeAt(i + 1) === ESC_TYPE.ST) { + i += 2 + emitSequence(data.slice(seqStart, i)) + } else { + i++ + } + + break + + case 'dcs': + + case 'apc': + if (code === C0.BEL) { + i++ + emitSequence(data.slice(seqStart, i)) + } else if (code === C0.ESC && i + 1 < data.length && data.charCodeAt(i + 1) === ESC_TYPE.ST) { + i += 2 + emitSequence(data.slice(seqStart, i)) + } else { + i++ + } + + break + } + } + + // Handle end of input + if (result.state === 'ground') { + flushText() + } else if (flush) { + // Force output incomplete sequence + const remaining = data.slice(seqStart) + + if (remaining) { + tokens.push({ type: 'sequence', value: remaining }) + } + + result.state = 'ground' + } else { + // Buffer incomplete sequence for next call + result.buffer = data.slice(seqStart) + } + + return { tokens, state: result } +} diff --git a/ui-tui/packages/hermes-ink/src/ink/termio/types.ts b/ui-tui/packages/hermes-ink/src/ink/termio/types.ts new file mode 100644 index 0000000000..4af1dc4cec --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/termio/types.ts @@ -0,0 +1,230 @@ +/** + * ANSI Parser - Semantic Types + * + * These types represent the semantic meaning of ANSI escape sequences, + * not their string representation. Inspired by ghostty's action-based design. + */ + +// ============================================================================= +// Colors +// ============================================================================= + +/** Named colors from the 16-color palette */ +export type NamedColor = + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'brightBlack' + | 'brightRed' + | 'brightGreen' + | 'brightYellow' + | 'brightBlue' + | 'brightMagenta' + | 'brightCyan' + | 'brightWhite' + +/** Color specification - can be named, indexed (256), or RGB */ +export type Color = + | { type: 'named'; name: NamedColor } + | { type: 'indexed'; index: number } // 0-255 + | { type: 'rgb'; r: number; g: number; b: number } + | { type: 'default' } + +// ============================================================================= +// Text Styles +// ============================================================================= + +/** Underline style variants */ +export type UnderlineStyle = 'none' | 'single' | 'double' | 'curly' | 'dotted' | 'dashed' + +/** Text style attributes - represents current styling state */ +export type TextStyle = { + bold: boolean + dim: boolean + italic: boolean + underline: UnderlineStyle + blink: boolean + inverse: boolean + hidden: boolean + strikethrough: boolean + overline: boolean + fg: Color + bg: Color + underlineColor: Color +} + +/** Create a default (reset) text style */ +export function defaultStyle(): TextStyle { + return { + bold: false, + dim: false, + italic: false, + underline: 'none', + blink: false, + inverse: false, + hidden: false, + strikethrough: false, + overline: false, + fg: { type: 'default' }, + bg: { type: 'default' }, + underlineColor: { type: 'default' } + } +} + +/** Check if two styles are equal */ +export function stylesEqual(a: TextStyle, b: TextStyle): boolean { + return ( + a.bold === b.bold && + a.dim === b.dim && + a.italic === b.italic && + a.underline === b.underline && + a.blink === b.blink && + a.inverse === b.inverse && + a.hidden === b.hidden && + a.strikethrough === b.strikethrough && + a.overline === b.overline && + colorsEqual(a.fg, b.fg) && + colorsEqual(a.bg, b.bg) && + colorsEqual(a.underlineColor, b.underlineColor) + ) +} + +/** Check if two colors are equal */ +export function colorsEqual(a: Color, b: Color): boolean { + if (a.type !== b.type) { + return false + } + + switch (a.type) { + case 'named': + return a.name === (b as typeof a).name + + case 'indexed': + return a.index === (b as typeof a).index + + case 'rgb': + return a.r === (b as typeof a).r && a.g === (b as typeof a).g && a.b === (b as typeof a).b + + case 'default': + return true + } +} + +// ============================================================================= +// Cursor Actions +// ============================================================================= + +export type CursorDirection = 'up' | 'down' | 'forward' | 'back' + +export type CursorAction = + | { type: 'move'; direction: CursorDirection; count: number } + | { type: 'position'; row: number; col: number } + | { type: 'column'; col: number } + | { type: 'row'; row: number } + | { type: 'save' } + | { type: 'restore' } + | { type: 'show' } + | { type: 'hide' } + | { + type: 'style' + style: 'block' | 'underline' | 'bar' + blinking: boolean + } + | { type: 'nextLine'; count: number } + | { type: 'prevLine'; count: number } + +// ============================================================================= +// Erase Actions +// ============================================================================= + +export type EraseAction = + | { type: 'display'; region: 'toEnd' | 'toStart' | 'all' | 'scrollback' } + | { type: 'line'; region: 'toEnd' | 'toStart' | 'all' } + | { type: 'chars'; count: number } + +// ============================================================================= +// Scroll Actions +// ============================================================================= + +export type ScrollAction = + | { type: 'up'; count: number } + | { type: 'down'; count: number } + | { type: 'setRegion'; top: number; bottom: number } + +// ============================================================================= +// Mode Actions +// ============================================================================= + +export type ModeAction = + | { type: 'alternateScreen'; enabled: boolean } + | { type: 'bracketedPaste'; enabled: boolean } + | { type: 'mouseTracking'; mode: 'off' | 'normal' | 'button' | 'any' } + | { type: 'focusEvents'; enabled: boolean } + +// ============================================================================= +// Link Actions (OSC 8) +// ============================================================================= + +export type LinkAction = { type: 'start'; url: string; params?: Record } | { type: 'end' } + +// ============================================================================= +// Title Actions (OSC 0/1/2) +// ============================================================================= + +export type TitleAction = + | { type: 'windowTitle'; title: string } + | { type: 'iconName'; name: string } + | { type: 'both'; title: string } + +// ============================================================================= +// Tab Status Action (OSC 21337) +// ============================================================================= + +/** + * Per-tab chrome metadata. Tristate for each field: + * - property absent → not mentioned in sequence, no change + * - null → explicitly cleared (bare key or key= with empty value) + * - value → set to this + */ +export type TabStatusAction = { + indicator?: Color | null + status?: string | null + statusColor?: Color | null +} + +// ============================================================================= +// Parsed Segments - The output of the parser +// ============================================================================= + +/** A segment of styled text */ +export type TextSegment = { + type: 'text' + text: string + style: TextStyle +} + +/** A grapheme (visual character unit) with width info */ +export type Grapheme = { + value: string + width: 1 | 2 // Display width in columns +} + +/** All possible parsed actions */ +export type Action = + | { type: 'text'; graphemes: Grapheme[]; style: TextStyle } + | { type: 'cursor'; action: CursorAction } + | { type: 'erase'; action: EraseAction } + | { type: 'scroll'; action: ScrollAction } + | { type: 'mode'; action: ModeAction } + | { type: 'link'; action: LinkAction } + | { type: 'title'; action: TitleAction } + | { type: 'tabStatus'; action: TabStatusAction } + | { type: 'sgr'; params: string } // Select Graphic Rendition (style change) + | { type: 'bell' } + | { type: 'reset' } // Full terminal reset (ESC c) + | { type: 'unknown'; sequence: string } // Unrecognized sequence diff --git a/ui-tui/packages/hermes-ink/src/ink/useTerminalNotification.ts b/ui-tui/packages/hermes-ink/src/ink/useTerminalNotification.ts new file mode 100644 index 0000000000..1fcde2bdb0 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/useTerminalNotification.ts @@ -0,0 +1,110 @@ +import { createContext, useCallback, useContext, useMemo } from 'react' + +import { isProgressReportingAvailable, type Progress } from './terminal.js' +import { BEL } from './termio/ansi.js' +import { ITERM2, OSC, osc, PROGRESS, wrapForMultiplexer } from './termio/osc.js' + +type WriteRaw = (data: string) => void + +export const TerminalWriteContext = createContext(null) + +export const TerminalWriteProvider = TerminalWriteContext.Provider + +export type TerminalNotification = { + notifyITerm2: (opts: { message: string; title?: string }) => void + notifyKitty: (opts: { message: string; title: string; id: number }) => void + notifyGhostty: (opts: { message: string; title: string }) => void + notifyBell: () => void + /** + * Report progress to the terminal via OSC 9;4 sequences. + * Supported terminals: ConEmu, Ghostty 1.2.0+, iTerm2 3.6.6+ + * Pass state=null to clear progress. + */ + progress: (state: Progress['state'] | null, percentage?: number) => void +} + +export function useTerminalNotification(): TerminalNotification { + const writeRaw = useContext(TerminalWriteContext) + + if (!writeRaw) { + throw new Error('useTerminalNotification must be used within TerminalWriteProvider') + } + + const notifyITerm2 = useCallback( + ({ message, title }: { message: string; title?: string }) => { + const displayString = title ? `${title}:\n${message}` : message + writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, `\n\n${displayString}`))) + }, + [writeRaw] + ) + + const notifyKitty = useCallback( + ({ message, title, id }: { message: string; title: string; id: number }) => { + writeRaw(wrapForMultiplexer(osc(OSC.KITTY, `i=${id}:d=0:p=title`, title))) + writeRaw(wrapForMultiplexer(osc(OSC.KITTY, `i=${id}:p=body`, message))) + writeRaw(wrapForMultiplexer(osc(OSC.KITTY, `i=${id}:d=1:a=focus`, ''))) + }, + [writeRaw] + ) + + const notifyGhostty = useCallback( + ({ message, title }: { message: string; title: string }) => { + writeRaw(wrapForMultiplexer(osc(OSC.GHOSTTY, 'notify', title, message))) + }, + [writeRaw] + ) + + const notifyBell = useCallback(() => { + // Raw BEL — inside tmux this triggers tmux's bell-action (window flag). + // Wrapping would make it opaque DCS payload and lose that fallback. + writeRaw(BEL) + }, [writeRaw]) + + const progress = useCallback( + (state: Progress['state'] | null, percentage?: number) => { + if (!isProgressReportingAvailable()) { + return + } + + if (!state) { + writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.CLEAR, ''))) + + return + } + + const pct = Math.max(0, Math.min(100, Math.round(percentage ?? 0))) + + switch (state) { + case 'completed': + writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.CLEAR, ''))) + + break + + case 'error': + writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.ERROR, pct))) + + break + + case 'indeterminate': + writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.INDETERMINATE, ''))) + + break + + case 'running': + writeRaw(wrapForMultiplexer(osc(OSC.ITERM2, ITERM2.PROGRESS, PROGRESS.SET, pct))) + + break + + case null: + // Handled by the if guard above + break + } + }, + [writeRaw] + ) + + return useMemo( + () => ({ notifyITerm2, notifyKitty, notifyGhostty, notifyBell, progress }), + [notifyITerm2, notifyKitty, notifyGhostty, notifyBell, progress] + ) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/warn.ts b/ui-tui/packages/hermes-ink/src/ink/warn.ts new file mode 100644 index 0000000000..016b4ecd2b --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/warn.ts @@ -0,0 +1,15 @@ +import { logForDebugging } from '../utils/debug.js' + +export function ifNotInteger(value: number | undefined, name: string): void { + if (value === undefined) { + return + } + + if (Number.isInteger(value)) { + return + } + + logForDebugging(`${name} should be an integer, got ${value}`, { + level: 'warn' + }) +} diff --git a/ui-tui/packages/hermes-ink/src/ink/widest-line.ts b/ui-tui/packages/hermes-ink/src/ink/widest-line.ts new file mode 100644 index 0000000000..ac78cb6d5a --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/widest-line.ts @@ -0,0 +1,22 @@ +import { lineWidth } from './line-width-cache.js' + +export function widestLine(string: string): number { + let maxWidth = 0 + let start = 0 + + while (start <= string.length) { + const end = string.indexOf('\n', start) + + const line = end === -1 ? string.substring(start) : string.substring(start, end) + + maxWidth = Math.max(maxWidth, lineWidth(line)) + + if (end === -1) { + break + } + + start = end + 1 + } + + return maxWidth +} diff --git a/ui-tui/packages/hermes-ink/src/ink/wrap-text.ts b/ui-tui/packages/hermes-ink/src/ink/wrap-text.ts new file mode 100644 index 0000000000..4d157bc2af --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/wrap-text.ts @@ -0,0 +1,75 @@ +import sliceAnsi from '../utils/sliceAnsi.js' + +import { stringWidth } from './stringWidth.js' +import type { Styles } from './styles.js' +import { wrapAnsi } from './wrapAnsi.js' + +const ELLIPSIS = '…' + +// sliceAnsi may include a boundary-spanning wide char (e.g. CJK at position +// end-1 with width 2 overshoots by 1). Retry with a tighter bound once. +function sliceFit(text: string, start: number, end: number): string { + const s = sliceAnsi(text, start, end) + + return stringWidth(s) > end - start ? sliceAnsi(text, start, end - 1) : s +} + +function truncate(text: string, columns: number, position: 'start' | 'middle' | 'end'): string { + if (columns < 1) { + return '' + } + + if (columns === 1) { + return ELLIPSIS + } + + const length = stringWidth(text) + + if (length <= columns) { + return text + } + + if (position === 'start') { + return ELLIPSIS + sliceFit(text, length - columns + 1, length) + } + + if (position === 'middle') { + const half = Math.floor(columns / 2) + + return sliceFit(text, 0, half) + ELLIPSIS + sliceFit(text, length - (columns - half) + 1, length) + } + + return sliceFit(text, 0, columns - 1) + ELLIPSIS +} + +export default function wrapText(text: string, maxWidth: number, wrapType: Styles['textWrap']): string { + if (wrapType === 'wrap') { + return wrapAnsi(text, maxWidth, { + trim: false, + hard: true + }) + } + + if (wrapType === 'wrap-trim') { + return wrapAnsi(text, maxWidth, { + trim: true, + hard: true + }) + } + + if (wrapType!.startsWith('truncate')) { + let position: 'end' | 'middle' | 'start' = 'end' + + if (wrapType === 'truncate-middle') { + position = 'middle' + } + + if (wrapType === 'truncate-start') { + position = 'start' + } + + return truncate(text, maxWidth, position) + } + + return text +} diff --git a/ui-tui/packages/hermes-ink/src/ink/wrapAnsi.ts b/ui-tui/packages/hermes-ink/src/ink/wrapAnsi.ts new file mode 100644 index 0000000000..61b56dbf3f --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/ink/wrapAnsi.ts @@ -0,0 +1,13 @@ +import wrapAnsiNpm from 'wrap-ansi' + +type WrapAnsiOptions = { + hard?: boolean + wordWrap?: boolean + trim?: boolean +} + +const wrapAnsiBun = typeof Bun !== 'undefined' && typeof Bun.wrapAnsi === 'function' ? Bun.wrapAnsi : null + +const wrapAnsi: (input: string, columns: number, options?: WrapAnsiOptions) => string = wrapAnsiBun ?? wrapAnsiNpm + +export { wrapAnsi } diff --git a/ui-tui/packages/hermes-ink/src/native-ts/yoga-layout/enums.ts b/ui-tui/packages/hermes-ink/src/native-ts/yoga-layout/enums.ts new file mode 100644 index 0000000000..95d66bf348 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/native-ts/yoga-layout/enums.ts @@ -0,0 +1,112 @@ +export const Align = { + Auto: 0, + FlexStart: 1, + Center: 2, + FlexEnd: 3, + Stretch: 4, + Baseline: 5, + SpaceBetween: 6, + SpaceAround: 7, + SpaceEvenly: 8 +} as const +export type Align = (typeof Align)[keyof typeof Align] +export const BoxSizing = { + BorderBox: 0, + ContentBox: 1 +} as const +export type BoxSizing = (typeof BoxSizing)[keyof typeof BoxSizing] +export const Dimension = { + Width: 0, + Height: 1 +} as const +export type Dimension = (typeof Dimension)[keyof typeof Dimension] +export const Direction = { + Inherit: 0, + LTR: 1, + RTL: 2 +} as const +export type Direction = (typeof Direction)[keyof typeof Direction] +export const Display = { + Flex: 0, + None: 1, + Contents: 2 +} as const +export type Display = (typeof Display)[keyof typeof Display] +export const Edge = { + Left: 0, + Top: 1, + Right: 2, + Bottom: 3, + Start: 4, + End: 5, + Horizontal: 6, + Vertical: 7, + All: 8 +} as const +export type Edge = (typeof Edge)[keyof typeof Edge] +export const Errata = { + None: 0, + StretchFlexBasis: 1, + AbsolutePositionWithoutInsetsExcludesPadding: 2, + AbsolutePercentAgainstInnerSize: 4, + All: 2147483647, + Classic: 2147483646 +} as const +export type Errata = (typeof Errata)[keyof typeof Errata] +export const ExperimentalFeature = { + WebFlexBasis: 0 +} as const +export type ExperimentalFeature = (typeof ExperimentalFeature)[keyof typeof ExperimentalFeature] +export const FlexDirection = { + Column: 0, + ColumnReverse: 1, + Row: 2, + RowReverse: 3 +} as const +export type FlexDirection = (typeof FlexDirection)[keyof typeof FlexDirection] +export const Gutter = { + Column: 0, + Row: 1, + All: 2 +} as const +export type Gutter = (typeof Gutter)[keyof typeof Gutter] +export const Justify = { + FlexStart: 0, + Center: 1, + FlexEnd: 2, + SpaceBetween: 3, + SpaceAround: 4, + SpaceEvenly: 5 +} as const +export type Justify = (typeof Justify)[keyof typeof Justify] +export const MeasureMode = { + Undefined: 0, + Exactly: 1, + AtMost: 2 +} as const +export type MeasureMode = (typeof MeasureMode)[keyof typeof MeasureMode] +export const Overflow = { + Visible: 0, + Hidden: 1, + Scroll: 2 +} as const +export type Overflow = (typeof Overflow)[keyof typeof Overflow] +export const PositionType = { + Static: 0, + Relative: 1, + Absolute: 2 +} as const +export type PositionType = (typeof PositionType)[keyof typeof PositionType] +export const Unit = { + Undefined: 0, + Point: 1, + Percent: 2, + Auto: 3 +} as const +export type Unit = (typeof Unit)[keyof typeof Unit] +export const Wrap = { + NoWrap: 0, + Wrap: 1, + WrapReverse: 2 +} as const +export type Wrap = (typeof Wrap)[keyof typeof Wrap] diff --git a/ui-tui/packages/hermes-ink/src/native-ts/yoga-layout/index.ts b/ui-tui/packages/hermes-ink/src/native-ts/yoga-layout/index.ts new file mode 100644 index 0000000000..a62a4bae16 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/native-ts/yoga-layout/index.ts @@ -0,0 +1,2326 @@ +import { + Align, + BoxSizing, + Dimension, + Direction, + Display, + Edge, + Errata, + ExperimentalFeature, + FlexDirection, + Gutter, + Justify, + MeasureMode, + Overflow, + PositionType, + Unit, + Wrap +} from './enums.js' +export { + Align, + BoxSizing, + Dimension, + Direction, + Display, + Edge, + Errata, + ExperimentalFeature, + FlexDirection, + Gutter, + Justify, + MeasureMode, + Overflow, + PositionType, + Unit, + Wrap +} +export type Value = { + unit: Unit + value: number +} +const UNDEFINED_VALUE: Value = { unit: Unit.Undefined, value: NaN } +const AUTO_VALUE: Value = { unit: Unit.Auto, value: NaN } + +function pointValue(v: number): Value { + return { unit: Unit.Point, value: v } +} + +function percentValue(v: number): Value { + return { unit: Unit.Percent, value: v } +} + +function resolveValue(v: Value, ownerSize: number): number { + switch (v.unit) { + case Unit.Point: + return v.value + + case Unit.Percent: + return isNaN(ownerSize) ? NaN : (v.value * ownerSize) / 100 + + default: + return NaN + } +} + +function isDefined(n: number): boolean { + return !isNaN(n) +} + +function sameFloat(a: number, b: number): boolean { + return a === b || (a !== a && b !== b) +} + +type Layout = { + left: number + top: number + width: number + height: number + border: [number, number, number, number] + padding: [number, number, number, number] + margin: [number, number, number, number] +} +type Style = { + direction: Direction + flexDirection: FlexDirection + justifyContent: Justify + alignItems: Align + alignSelf: Align + alignContent: Align + flexWrap: Wrap + overflow: Overflow + display: Display + positionType: PositionType + flexGrow: number + flexShrink: number + flexBasis: Value + margin: Value[] + padding: Value[] + border: Value[] + position: Value[] + gap: Value[] + width: Value + height: Value + minWidth: Value + minHeight: Value + maxWidth: Value + maxHeight: Value +} + +function defaultStyle(): Style { + return { + direction: Direction.Inherit, + flexDirection: FlexDirection.Column, + justifyContent: Justify.FlexStart, + alignItems: Align.Stretch, + alignSelf: Align.Auto, + alignContent: Align.FlexStart, + flexWrap: Wrap.NoWrap, + overflow: Overflow.Visible, + display: Display.Flex, + positionType: PositionType.Relative, + flexGrow: 0, + flexShrink: 0, + flexBasis: AUTO_VALUE, + margin: new Array(9).fill(UNDEFINED_VALUE), + padding: new Array(9).fill(UNDEFINED_VALUE), + border: new Array(9).fill(UNDEFINED_VALUE), + position: new Array(9).fill(UNDEFINED_VALUE), + gap: new Array(3).fill(UNDEFINED_VALUE), + width: AUTO_VALUE, + height: AUTO_VALUE, + minWidth: UNDEFINED_VALUE, + minHeight: UNDEFINED_VALUE, + maxWidth: UNDEFINED_VALUE, + maxHeight: UNDEFINED_VALUE + } +} + +const EDGE_LEFT = 0 +const EDGE_TOP = 1 +const EDGE_RIGHT = 2 +const EDGE_BOTTOM = 3 + +function resolveEdge(edges: Value[], physicalEdge: number, ownerSize: number, allowAuto = false): number { + let v = edges[physicalEdge]! + + if (v.unit === Unit.Undefined) { + if (physicalEdge === EDGE_LEFT || physicalEdge === EDGE_RIGHT) { + v = edges[Edge.Horizontal]! + } else { + v = edges[Edge.Vertical]! + } + } + + if (v.unit === Unit.Undefined) { + v = edges[Edge.All]! + } + + if (v.unit === Unit.Undefined) { + if (physicalEdge === EDGE_LEFT) { + v = edges[Edge.Start]! + } + + if (physicalEdge === EDGE_RIGHT) { + v = edges[Edge.End]! + } + } + + if (v.unit === Unit.Undefined) { + return 0 + } + + if (v.unit === Unit.Auto) { + return allowAuto ? NaN : 0 + } + + return resolveValue(v, ownerSize) +} + +function resolveEdgeRaw(edges: Value[], physicalEdge: number): Value { + let v = edges[physicalEdge]! + + if (v.unit === Unit.Undefined) { + if (physicalEdge === EDGE_LEFT || physicalEdge === EDGE_RIGHT) { + v = edges[Edge.Horizontal]! + } else { + v = edges[Edge.Vertical]! + } + } + + if (v.unit === Unit.Undefined) { + v = edges[Edge.All]! + } + + if (v.unit === Unit.Undefined) { + if (physicalEdge === EDGE_LEFT) { + v = edges[Edge.Start]! + } + + if (physicalEdge === EDGE_RIGHT) { + v = edges[Edge.End]! + } + } + + return v +} + +function isMarginAuto(edges: Value[], physicalEdge: number): boolean { + return resolveEdgeRaw(edges, physicalEdge).unit === Unit.Auto +} + +function hasAnyAutoEdge(edges: Value[]): boolean { + for (let i = 0; i < 9; i++) { + if (edges[i]!.unit === 3) { + return true + } + } + + return false +} + +function hasAnyDefinedEdge(edges: Value[]): boolean { + for (let i = 0; i < 9; i++) { + if (edges[i]!.unit !== 0) { + return true + } + } + + return false +} + +function resolveEdges4Into(edges: Value[], ownerSize: number, out: [number, number, number, number]): void { + const eH = edges[6]! + const eV = edges[7]! + const eA = edges[8]! + const eS = edges[4]! + const eE = edges[5]! + const pctDenom = isNaN(ownerSize) ? NaN : ownerSize / 100 + let v = edges[0]! + + if (v.unit === 0) { + v = eH + } + + if (v.unit === 0) { + v = eA + } + + if (v.unit === 0) { + v = eS + } + + out[0] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0 + v = edges[1]! + + if (v.unit === 0) { + v = eV + } + + if (v.unit === 0) { + v = eA + } + + out[1] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0 + v = edges[2]! + + if (v.unit === 0) { + v = eH + } + + if (v.unit === 0) { + v = eA + } + + if (v.unit === 0) { + v = eE + } + + out[2] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0 + v = edges[3]! + + if (v.unit === 0) { + v = eV + } + + if (v.unit === 0) { + v = eA + } + + out[3] = v.unit === 1 ? v.value : v.unit === 2 ? v.value * pctDenom : 0 +} + +function isRow(dir: FlexDirection): boolean { + return dir === FlexDirection.Row || dir === FlexDirection.RowReverse +} + +function isReverse(dir: FlexDirection): boolean { + return dir === FlexDirection.RowReverse || dir === FlexDirection.ColumnReverse +} + +function crossAxis(dir: FlexDirection): FlexDirection { + return isRow(dir) ? FlexDirection.Column : FlexDirection.Row +} + +function leadingEdge(dir: FlexDirection): number { + switch (dir) { + case FlexDirection.Row: + return EDGE_LEFT + + case FlexDirection.RowReverse: + return EDGE_RIGHT + + case FlexDirection.Column: + return EDGE_TOP + + case FlexDirection.ColumnReverse: + return EDGE_BOTTOM + } +} + +function trailingEdge(dir: FlexDirection): number { + switch (dir) { + case FlexDirection.Row: + return EDGE_RIGHT + + case FlexDirection.RowReverse: + return EDGE_LEFT + + case FlexDirection.Column: + return EDGE_BOTTOM + + case FlexDirection.ColumnReverse: + return EDGE_TOP + } +} + +export type MeasureFunction = ( + width: number, + widthMode: MeasureMode, + height: number, + heightMode: MeasureMode +) => { + width: number + height: number +} +export type Size = { + width: number + height: number +} +export type Config = { + pointScaleFactor: number + errata: Errata + useWebDefaults: boolean + free(): void + isExperimentalFeatureEnabled(_: ExperimentalFeature): boolean + setExperimentalFeatureEnabled(_: ExperimentalFeature, __: boolean): void + setPointScaleFactor(factor: number): void + getErrata(): Errata + setErrata(errata: Errata): void + setUseWebDefaults(v: boolean): void +} + +function createConfig(): Config { + const config: Config = { + pointScaleFactor: 1, + errata: Errata.None, + useWebDefaults: false, + free() {}, + isExperimentalFeatureEnabled() { + return false + }, + setExperimentalFeatureEnabled() {}, + setPointScaleFactor(f) { + config.pointScaleFactor = f + }, + getErrata() { + return config.errata + }, + setErrata(e) { + config.errata = e + }, + setUseWebDefaults(v) { + config.useWebDefaults = v + } + } + + return config +} + +export class Node { + style: Style + layout: Layout + parent: Node | null + children: Node[] + measureFunc: MeasureFunction | null + config: Config + isDirty_: boolean + isReferenceBaseline_: boolean + _flexBasis = 0 + _mainSize = 0 + _crossSize = 0 + _lineIndex = 0 + _hasAutoMargin = false + _hasPosition = false + _hasPadding = false + _hasBorder = false + _hasMargin = false + _lW = NaN + _lH = NaN + _lWM: MeasureMode = 0 + _lHM: MeasureMode = 0 + _lOW = NaN + _lOH = NaN + _lFW = false + _lFH = false + _lOutW = NaN + _lOutH = NaN + _hasL = false + _mW = NaN + _mH = NaN + _mWM: MeasureMode = 0 + _mHM: MeasureMode = 0 + _mOW = NaN + _mOH = NaN + _mOutW = NaN + _mOutH = NaN + _hasM = false + _fbBasis = NaN + _fbOwnerW = NaN + _fbOwnerH = NaN + _fbAvailMain = NaN + _fbAvailCross = NaN + _fbCrossMode: MeasureMode = 0 + _fbGen = -1 + _cIn: Float64Array | null = null + _cOut: Float64Array | null = null + _cGen = -1 + _cN = 0 + _cWr = 0 + constructor(config?: Config) { + this.style = defaultStyle() + this.layout = { + left: 0, + top: 0, + width: 0, + height: 0, + border: [0, 0, 0, 0], + padding: [0, 0, 0, 0], + margin: [0, 0, 0, 0] + } + this.parent = null + this.children = [] + this.measureFunc = null + this.config = config ?? DEFAULT_CONFIG + this.isDirty_ = true + this.isReferenceBaseline_ = false + _yogaLiveNodes++ + } + insertChild(child: Node, index: number): void { + child.parent = this + this.children.splice(index, 0, child) + this.markDirty() + } + removeChild(child: Node): void { + const idx = this.children.indexOf(child) + + if (idx >= 0) { + this.children.splice(idx, 1) + child.parent = null + this.markDirty() + } + } + getChild(index: number): Node { + return this.children[index]! + } + getChildCount(): number { + return this.children.length + } + getParent(): Node | null { + return this.parent + } + free(): void { + this.parent = null + this.children = [] + this.measureFunc = null + this._cIn = null + this._cOut = null + _yogaLiveNodes-- + } + freeRecursive(): void { + for (const c of this.children) { + c.freeRecursive() + } + + this.free() + } + reset(): void { + this.style = defaultStyle() + this.children = [] + this.parent = null + this.measureFunc = null + this.isDirty_ = true + this._hasAutoMargin = false + this._hasPosition = false + this._hasPadding = false + this._hasBorder = false + this._hasMargin = false + this._hasL = false + this._hasM = false + this._cN = 0 + this._cWr = 0 + this._fbBasis = NaN + } + markDirty(): void { + this.isDirty_ = true + + if (this.parent && !this.parent.isDirty_) { + this.parent.markDirty() + } + } + isDirty(): boolean { + return this.isDirty_ + } + hasNewLayout(): boolean { + return true + } + markLayoutSeen(): void {} + setMeasureFunc(fn: MeasureFunction | null): void { + this.measureFunc = fn + this.markDirty() + } + unsetMeasureFunc(): void { + this.measureFunc = null + this.markDirty() + } + getComputedLeft(): number { + return this.layout.left + } + getComputedTop(): number { + return this.layout.top + } + getComputedWidth(): number { + return this.layout.width + } + getComputedHeight(): number { + return this.layout.height + } + getComputedRight(): number { + const p = this.parent + + return p ? p.layout.width - this.layout.left - this.layout.width : 0 + } + getComputedBottom(): number { + const p = this.parent + + return p ? p.layout.height - this.layout.top - this.layout.height : 0 + } + getComputedLayout(): { + left: number + top: number + right: number + bottom: number + width: number + height: number + } { + return { + left: this.layout.left, + top: this.layout.top, + right: this.getComputedRight(), + bottom: this.getComputedBottom(), + width: this.layout.width, + height: this.layout.height + } + } + getComputedBorder(edge: Edge): number { + return this.layout.border[physicalEdge(edge)]! + } + getComputedPadding(edge: Edge): number { + return this.layout.padding[physicalEdge(edge)]! + } + getComputedMargin(edge: Edge): number { + return this.layout.margin[physicalEdge(edge)]! + } + setWidth(v: number | 'auto' | string | undefined): void { + this.style.width = parseDimension(v) + this.markDirty() + } + setWidthPercent(v: number): void { + this.style.width = percentValue(v) + this.markDirty() + } + setWidthAuto(): void { + this.style.width = AUTO_VALUE + this.markDirty() + } + setHeight(v: number | 'auto' | string | undefined): void { + this.style.height = parseDimension(v) + this.markDirty() + } + setHeightPercent(v: number): void { + this.style.height = percentValue(v) + this.markDirty() + } + setHeightAuto(): void { + this.style.height = AUTO_VALUE + this.markDirty() + } + setMinWidth(v: number | string | undefined): void { + this.style.minWidth = parseDimension(v) + this.markDirty() + } + setMinWidthPercent(v: number): void { + this.style.minWidth = percentValue(v) + this.markDirty() + } + setMinHeight(v: number | string | undefined): void { + this.style.minHeight = parseDimension(v) + this.markDirty() + } + setMinHeightPercent(v: number): void { + this.style.minHeight = percentValue(v) + this.markDirty() + } + setMaxWidth(v: number | string | undefined): void { + this.style.maxWidth = parseDimension(v) + this.markDirty() + } + setMaxWidthPercent(v: number): void { + this.style.maxWidth = percentValue(v) + this.markDirty() + } + setMaxHeight(v: number | string | undefined): void { + this.style.maxHeight = parseDimension(v) + this.markDirty() + } + setMaxHeightPercent(v: number): void { + this.style.maxHeight = percentValue(v) + this.markDirty() + } + setFlexDirection(dir: FlexDirection): void { + this.style.flexDirection = dir + this.markDirty() + } + setFlexGrow(v: number | undefined): void { + this.style.flexGrow = v ?? 0 + this.markDirty() + } + setFlexShrink(v: number | undefined): void { + this.style.flexShrink = v ?? 0 + this.markDirty() + } + setFlex(v: number | undefined): void { + if (v === undefined || isNaN(v)) { + this.style.flexGrow = 0 + this.style.flexShrink = 0 + } else if (v > 0) { + this.style.flexGrow = v + this.style.flexShrink = 1 + this.style.flexBasis = pointValue(0) + } else if (v < 0) { + this.style.flexGrow = 0 + this.style.flexShrink = -v + } else { + this.style.flexGrow = 0 + this.style.flexShrink = 0 + } + + this.markDirty() + } + setFlexBasis(v: number | 'auto' | string | undefined): void { + this.style.flexBasis = parseDimension(v) + this.markDirty() + } + setFlexBasisPercent(v: number): void { + this.style.flexBasis = percentValue(v) + this.markDirty() + } + setFlexBasisAuto(): void { + this.style.flexBasis = AUTO_VALUE + this.markDirty() + } + setFlexWrap(wrap: Wrap): void { + this.style.flexWrap = wrap + this.markDirty() + } + setAlignItems(a: Align): void { + this.style.alignItems = a + this.markDirty() + } + setAlignSelf(a: Align): void { + this.style.alignSelf = a + this.markDirty() + } + setAlignContent(a: Align): void { + this.style.alignContent = a + this.markDirty() + } + setJustifyContent(j: Justify): void { + this.style.justifyContent = j + this.markDirty() + } + setDisplay(d: Display): void { + this.style.display = d + this.markDirty() + } + getDisplay(): Display { + return this.style.display + } + setPositionType(t: PositionType): void { + this.style.positionType = t + this.markDirty() + } + setPosition(edge: Edge, v: number | string | undefined): void { + this.style.position[edge] = parseDimension(v) + this._hasPosition = hasAnyDefinedEdge(this.style.position) + this.markDirty() + } + setPositionPercent(edge: Edge, v: number): void { + this.style.position[edge] = percentValue(v) + this._hasPosition = true + this.markDirty() + } + setPositionAuto(edge: Edge): void { + this.style.position[edge] = AUTO_VALUE + this._hasPosition = true + this.markDirty() + } + setOverflow(o: Overflow): void { + this.style.overflow = o + this.markDirty() + } + setDirection(d: Direction): void { + this.style.direction = d + this.markDirty() + } + setBoxSizing(_: BoxSizing): void {} + setMargin(edge: Edge, v: number | 'auto' | string | undefined): void { + const val = parseDimension(v) + this.style.margin[edge] = val + + if (val.unit === Unit.Auto) { + this._hasAutoMargin = true + } else { + this._hasAutoMargin = hasAnyAutoEdge(this.style.margin) + } + + this._hasMargin = this._hasAutoMargin || hasAnyDefinedEdge(this.style.margin) + this.markDirty() + } + setMarginPercent(edge: Edge, v: number): void { + this.style.margin[edge] = percentValue(v) + this._hasAutoMargin = hasAnyAutoEdge(this.style.margin) + this._hasMargin = true + this.markDirty() + } + setMarginAuto(edge: Edge): void { + this.style.margin[edge] = AUTO_VALUE + this._hasAutoMargin = true + this._hasMargin = true + this.markDirty() + } + setPadding(edge: Edge, v: number | string | undefined): void { + this.style.padding[edge] = parseDimension(v) + this._hasPadding = hasAnyDefinedEdge(this.style.padding) + this.markDirty() + } + setPaddingPercent(edge: Edge, v: number): void { + this.style.padding[edge] = percentValue(v) + this._hasPadding = true + this.markDirty() + } + setBorder(edge: Edge, v: number | undefined): void { + this.style.border[edge] = v === undefined ? UNDEFINED_VALUE : pointValue(v) + this._hasBorder = hasAnyDefinedEdge(this.style.border) + this.markDirty() + } + setGap(gutter: Gutter, v: number | string | undefined): void { + this.style.gap[gutter] = parseDimension(v) + this.markDirty() + } + setGapPercent(gutter: Gutter, v: number): void { + this.style.gap[gutter] = percentValue(v) + this.markDirty() + } + getFlexDirection(): FlexDirection { + return this.style.flexDirection + } + getJustifyContent(): Justify { + return this.style.justifyContent + } + getAlignItems(): Align { + return this.style.alignItems + } + getAlignSelf(): Align { + return this.style.alignSelf + } + getAlignContent(): Align { + return this.style.alignContent + } + getFlexGrow(): number { + return this.style.flexGrow + } + getFlexShrink(): number { + return this.style.flexShrink + } + getFlexBasis(): Value { + return this.style.flexBasis + } + getFlexWrap(): Wrap { + return this.style.flexWrap + } + getWidth(): Value { + return this.style.width + } + getHeight(): Value { + return this.style.height + } + getOverflow(): Overflow { + return this.style.overflow + } + getPositionType(): PositionType { + return this.style.positionType + } + getDirection(): Direction { + return this.style.direction + } + copyStyle(_: Node): void {} + setDirtiedFunc(_: unknown): void {} + unsetDirtiedFunc(): void {} + setIsReferenceBaseline(v: boolean): void { + this.isReferenceBaseline_ = v + this.markDirty() + } + isReferenceBaseline(): boolean { + return this.isReferenceBaseline_ + } + setAspectRatio(_: number | undefined): void {} + getAspectRatio(): number { + return NaN + } + setAlwaysFormsContainingBlock(_: boolean): void {} + calculateLayout(ownerWidth: number | undefined, ownerHeight: number | undefined, _direction?: Direction): void { + _yogaNodesVisited = 0 + _yogaMeasureCalls = 0 + _yogaCacheHits = 0 + _generation++ + const w = ownerWidth === undefined ? NaN : ownerWidth + const h = ownerHeight === undefined ? NaN : ownerHeight + layoutNode( + this, + w, + h, + isDefined(w) ? MeasureMode.Exactly : MeasureMode.Undefined, + isDefined(h) ? MeasureMode.Exactly : MeasureMode.Undefined, + w, + h, + true + ) + const mar = this.layout.margin + const posL = resolveValue(resolveEdgeRaw(this.style.position, EDGE_LEFT), isDefined(w) ? w : 0) + const posT = resolveValue(resolveEdgeRaw(this.style.position, EDGE_TOP), isDefined(w) ? w : 0) + this.layout.left = mar[EDGE_LEFT] + (isDefined(posL) ? posL : 0) + this.layout.top = mar[EDGE_TOP] + (isDefined(posT) ? posT : 0) + roundLayout(this, this.config.pointScaleFactor, 0, 0) + } +} +const DEFAULT_CONFIG = createConfig() +const CACHE_SLOTS = 4 + +function cacheWrite( + node: Node, + aW: number, + aH: number, + wM: MeasureMode, + hM: MeasureMode, + oW: number, + oH: number, + fW: boolean, + fH: boolean, + wasDirty: boolean +): void { + if (!node._cIn) { + node._cIn = new Float64Array(CACHE_SLOTS * 8) + node._cOut = new Float64Array(CACHE_SLOTS * 2) + } + + if (wasDirty && node._cGen !== _generation) { + node._cN = 0 + node._cWr = 0 + } + + const i = node._cWr++ % CACHE_SLOTS + + if (node._cN < CACHE_SLOTS) { + node._cN = node._cWr + } + + const o = i * 8 + const cIn = node._cIn + cIn[o] = aW + cIn[o + 1] = aH + cIn[o + 2] = wM + cIn[o + 3] = hM + cIn[o + 4] = oW + cIn[o + 5] = oH + cIn[o + 6] = fW ? 1 : 0 + cIn[o + 7] = fH ? 1 : 0 + node._cOut![i * 2] = node.layout.width + node._cOut![i * 2 + 1] = node.layout.height + node._cGen = _generation +} + +function commitCacheOutputs(node: Node, performLayout: boolean): void { + if (performLayout) { + node._lOutW = node.layout.width + node._lOutH = node.layout.height + } else { + node._mOutW = node.layout.width + node._mOutH = node.layout.height + } +} + +let _generation = 0 +let _yogaNodesVisited = 0 +let _yogaMeasureCalls = 0 +let _yogaCacheHits = 0 +let _yogaLiveNodes = 0 + +export function getYogaCounters(): { + visited: number + measured: number + cacheHits: number + live: number +} { + return { + visited: _yogaNodesVisited, + measured: _yogaMeasureCalls, + cacheHits: _yogaCacheHits, + live: _yogaLiveNodes + } +} + +function layoutNode( + node: Node, + availableWidth: number, + availableHeight: number, + widthMode: MeasureMode, + heightMode: MeasureMode, + ownerWidth: number, + ownerHeight: number, + performLayout: boolean, + forceWidth = false, + forceHeight = false +): void { + _yogaNodesVisited++ + const style = node.style + const layout = node.layout + const sameGen = node._cGen === _generation && !performLayout + + if (!node.isDirty_ || sameGen) { + if ( + !node.isDirty_ && + node._hasL && + node._lWM === widthMode && + node._lHM === heightMode && + node._lFW === forceWidth && + node._lFH === forceHeight && + sameFloat(node._lW, availableWidth) && + sameFloat(node._lH, availableHeight) && + sameFloat(node._lOW, ownerWidth) && + sameFloat(node._lOH, ownerHeight) + ) { + _yogaCacheHits++ + layout.width = node._lOutW + layout.height = node._lOutH + + return + } + + if (node._cN > 0 && (sameGen || !node.isDirty_)) { + const cIn = node._cIn! + + for (let i = 0; i < node._cN; i++) { + const o = i * 8 + + if ( + cIn[o + 2] === widthMode && + cIn[o + 3] === heightMode && + cIn[o + 6] === (forceWidth ? 1 : 0) && + cIn[o + 7] === (forceHeight ? 1 : 0) && + sameFloat(cIn[o]!, availableWidth) && + sameFloat(cIn[o + 1]!, availableHeight) && + sameFloat(cIn[o + 4]!, ownerWidth) && + sameFloat(cIn[o + 5]!, ownerHeight) + ) { + layout.width = node._cOut![i * 2]! + layout.height = node._cOut![i * 2 + 1]! + _yogaCacheHits++ + + return + } + } + } + + if ( + !node.isDirty_ && + !performLayout && + node._hasM && + node._mWM === widthMode && + node._mHM === heightMode && + sameFloat(node._mW, availableWidth) && + sameFloat(node._mH, availableHeight) && + sameFloat(node._mOW, ownerWidth) && + sameFloat(node._mOH, ownerHeight) + ) { + layout.width = node._mOutW + layout.height = node._mOutH + _yogaCacheHits++ + + return + } + } + + const wasDirty = node.isDirty_ + + if (performLayout) { + node._lW = availableWidth + node._lH = availableHeight + node._lWM = widthMode + node._lHM = heightMode + node._lOW = ownerWidth + node._lOH = ownerHeight + node._lFW = forceWidth + node._lFH = forceHeight + node._hasL = true + node.isDirty_ = false + + if (wasDirty) { + node._hasM = false + } + } else { + node._mW = availableWidth + node._mH = availableHeight + node._mWM = widthMode + node._mHM = heightMode + node._mOW = ownerWidth + node._mOH = ownerHeight + node._hasM = true + + if (wasDirty) { + node._hasL = false + } + } + + const pad = layout.padding + const bor = layout.border + const mar = layout.margin + + if (node._hasPadding) { + resolveEdges4Into(style.padding, ownerWidth, pad) + } else { + pad[0] = pad[1] = pad[2] = pad[3] = 0 + } + + if (node._hasBorder) { + resolveEdges4Into(style.border, ownerWidth, bor) + } else { + bor[0] = bor[1] = bor[2] = bor[3] = 0 + } + + if (node._hasMargin) { + resolveEdges4Into(style.margin, ownerWidth, mar) + } else { + mar[0] = mar[1] = mar[2] = mar[3] = 0 + } + + const paddingBorderWidth = pad[0] + pad[2] + bor[0] + bor[2] + const paddingBorderHeight = pad[1] + pad[3] + bor[1] + bor[3] + const styleWidth = forceWidth ? NaN : resolveValue(style.width, ownerWidth) + + const styleHeight = forceHeight ? NaN : resolveValue(style.height, ownerHeight) + + let width = availableWidth + let height = availableHeight + let wMode = widthMode + let hMode = heightMode + + if (isDefined(styleWidth)) { + width = styleWidth + wMode = MeasureMode.Exactly + } + + if (isDefined(styleHeight)) { + height = styleHeight + hMode = MeasureMode.Exactly + } + + width = boundAxis(style, true, width, ownerWidth, ownerHeight) + height = boundAxis(style, false, height, ownerWidth, ownerHeight) + + if (node.measureFunc && node.children.length === 0) { + const innerW = wMode === MeasureMode.Undefined ? NaN : Math.max(0, width - paddingBorderWidth) + + const innerH = hMode === MeasureMode.Undefined ? NaN : Math.max(0, height - paddingBorderHeight) + + _yogaMeasureCalls++ + const measured = node.measureFunc(innerW, wMode, innerH, hMode) + node.layout.width = + wMode === MeasureMode.Exactly + ? width + : boundAxis(style, true, (measured.width ?? 0) + paddingBorderWidth, ownerWidth, ownerHeight) + node.layout.height = + hMode === MeasureMode.Exactly + ? height + : boundAxis(style, false, (measured.height ?? 0) + paddingBorderHeight, ownerWidth, ownerHeight) + commitCacheOutputs(node, performLayout) + cacheWrite( + node, + availableWidth, + availableHeight, + widthMode, + heightMode, + ownerWidth, + ownerHeight, + forceWidth, + forceHeight, + wasDirty + ) + + return + } + + if (node.children.length === 0) { + node.layout.width = + wMode === MeasureMode.Exactly ? width : boundAxis(style, true, paddingBorderWidth, ownerWidth, ownerHeight) + node.layout.height = + hMode === MeasureMode.Exactly ? height : boundAxis(style, false, paddingBorderHeight, ownerWidth, ownerHeight) + commitCacheOutputs(node, performLayout) + cacheWrite( + node, + availableWidth, + availableHeight, + widthMode, + heightMode, + ownerWidth, + ownerHeight, + forceWidth, + forceHeight, + wasDirty + ) + + return + } + + const mainAxis = style.flexDirection + const crossAx = crossAxis(mainAxis) + const isMainRow = isRow(mainAxis) + const mainSize = isMainRow ? width : height + const crossSize = isMainRow ? height : width + const mainMode = isMainRow ? wMode : hMode + const crossMode = isMainRow ? hMode : wMode + const mainPadBorder = isMainRow ? paddingBorderWidth : paddingBorderHeight + const crossPadBorder = isMainRow ? paddingBorderHeight : paddingBorderWidth + + const innerMainSize = isDefined(mainSize) ? Math.max(0, mainSize - mainPadBorder) : NaN + + const innerCrossSize = isDefined(crossSize) ? Math.max(0, crossSize - crossPadBorder) : NaN + + const gapMain = resolveGap(style, isMainRow ? Gutter.Column : Gutter.Row, innerMainSize) + const flowChildren: Node[] = [] + const absChildren: Node[] = [] + collectLayoutChildren(node, flowChildren, absChildren) + const ownerW = isDefined(width) ? width : NaN + const ownerH = isDefined(height) ? height : NaN + const isWrap = style.flexWrap !== Wrap.NoWrap + const gapCross = resolveGap(style, isMainRow ? Gutter.Row : Gutter.Column, innerCrossSize) + + for (const c of flowChildren) { + c._flexBasis = computeFlexBasis(c, mainAxis, innerMainSize, innerCrossSize, crossMode, ownerW, ownerH) + } + + const lines: Node[][] = [] + + if (!isWrap || !isDefined(innerMainSize) || flowChildren.length === 0) { + for (const c of flowChildren) { + c._lineIndex = 0 + } + + lines.push(flowChildren) + } else { + let lineStart = 0 + let lineLen = 0 + + for (let i = 0; i < flowChildren.length; i++) { + const c = flowChildren[i]! + const hypo = boundAxis(c.style, isMainRow, c._flexBasis, ownerW, ownerH) + const outer = Math.max(0, hypo) + childMarginForAxis(c, mainAxis, ownerW) + const withGap = i > lineStart ? gapMain : 0 + + if (i > lineStart && lineLen + withGap + outer > innerMainSize) { + lines.push(flowChildren.slice(lineStart, i)) + lineStart = i + lineLen = outer + } else { + lineLen += withGap + outer + } + + c._lineIndex = lines.length + } + + lines.push(flowChildren.slice(lineStart)) + } + + const lineCount = lines.length + const isBaseline = isBaselineLayout(node, flowChildren) + const lineConsumedMain: number[] = new Array(lineCount) + const lineCrossSizes: number[] = new Array(lineCount) + const lineMaxAscent: number[] = isBaseline ? new Array(lineCount).fill(0) : [] + let maxLineMain = 0 + let totalLinesCross = 0 + + for (let li = 0; li < lineCount; li++) { + const line = lines[li]! + const lineGap = line.length > 1 ? gapMain * (line.length - 1) : 0 + let lineBasis = lineGap + + for (const c of line) { + lineBasis += c._flexBasis + childMarginForAxis(c, mainAxis, ownerW) + } + + let availMain = innerMainSize + + if (!isDefined(availMain)) { + const mainOwner = isMainRow ? ownerWidth : ownerHeight + const minM = resolveValue(isMainRow ? style.minWidth : style.minHeight, mainOwner) + const maxM = resolveValue(isMainRow ? style.maxWidth : style.maxHeight, mainOwner) + + if (isDefined(maxM) && lineBasis > maxM - mainPadBorder) { + availMain = Math.max(0, maxM - mainPadBorder) + } else if (isDefined(minM) && lineBasis < minM - mainPadBorder) { + availMain = Math.max(0, minM - mainPadBorder) + } + } + + resolveFlexibleLengths(line, availMain, lineBasis, isMainRow, ownerW, ownerH) + let lineCross = 0 + + for (const c of line) { + const cStyle = c.style + const childAlign = cStyle.alignSelf === Align.Auto ? style.alignItems : cStyle.alignSelf + const cMarginCross = childMarginForAxis(c, crossAx, ownerW) + let childCrossSize = NaN + let childCrossMode: MeasureMode = MeasureMode.Undefined + const resolvedCrossStyle = resolveValue(isMainRow ? cStyle.height : cStyle.width, isMainRow ? ownerH : ownerW) + const crossLeadE = isMainRow ? EDGE_TOP : EDGE_LEFT + const crossTrailE = isMainRow ? EDGE_BOTTOM : EDGE_RIGHT + + const hasCrossAutoMargin = + c._hasAutoMargin && (isMarginAuto(cStyle.margin, crossLeadE) || isMarginAuto(cStyle.margin, crossTrailE)) + + if (isDefined(resolvedCrossStyle)) { + childCrossSize = resolvedCrossStyle + childCrossMode = MeasureMode.Exactly + } else if ( + childAlign === Align.Stretch && + !hasCrossAutoMargin && + !isWrap && + isDefined(innerCrossSize) && + crossMode === MeasureMode.Exactly + ) { + childCrossSize = Math.max(0, innerCrossSize - cMarginCross) + childCrossMode = MeasureMode.Exactly + } else if (!isWrap && isDefined(innerCrossSize)) { + childCrossSize = Math.max(0, innerCrossSize - cMarginCross) + childCrossMode = MeasureMode.AtMost + } + + const cw = isMainRow ? c._mainSize : childCrossSize + const ch = isMainRow ? childCrossSize : c._mainSize + layoutNode( + c, + cw, + ch, + isMainRow ? MeasureMode.Exactly : childCrossMode, + isMainRow ? childCrossMode : MeasureMode.Exactly, + ownerW, + ownerH, + performLayout, + isMainRow, + !isMainRow + ) + c._crossSize = isMainRow ? c.layout.height : c.layout.width + lineCross = Math.max(lineCross, c._crossSize + cMarginCross) + } + + if (isBaseline) { + let maxAscent = 0 + let maxDescent = 0 + + for (const c of line) { + if (resolveChildAlign(node, c) !== Align.Baseline) { + continue + } + + const mTop = resolveEdge(c.style.margin, EDGE_TOP, ownerW) + const mBot = resolveEdge(c.style.margin, EDGE_BOTTOM, ownerW) + const ascent = calculateBaseline(c) + mTop + const descent = c.layout.height + mTop + mBot - ascent + + if (ascent > maxAscent) { + maxAscent = ascent + } + + if (descent > maxDescent) { + maxDescent = descent + } + } + + lineMaxAscent[li] = maxAscent + + if (maxAscent + maxDescent > lineCross) { + lineCross = maxAscent + maxDescent + } + } + + const mainLead = leadingEdge(mainAxis) + const mainTrail = trailingEdge(mainAxis) + let consumed = lineGap + + for (const c of line) { + const cm = c.layout.margin + consumed += c._mainSize + cm[mainLead]! + cm[mainTrail]! + } + + lineConsumedMain[li] = consumed + lineCrossSizes[li] = lineCross + maxLineMain = Math.max(maxLineMain, consumed) + totalLinesCross += lineCross + } + + const totalCrossGap = lineCount > 1 ? gapCross * (lineCount - 1) : 0 + totalLinesCross += totalCrossGap + const isScroll = style.overflow === Overflow.Scroll + const contentMain = maxLineMain + mainPadBorder + + const finalMainSize = + mainMode === MeasureMode.Exactly + ? mainSize + : mainMode === MeasureMode.AtMost && isScroll + ? Math.max(Math.min(mainSize, contentMain), mainPadBorder) + : isWrap && lineCount > 1 && mainMode === MeasureMode.AtMost + ? mainSize + : contentMain + + const contentCross = totalLinesCross + crossPadBorder + + const finalCrossSize = + crossMode === MeasureMode.Exactly + ? crossSize + : crossMode === MeasureMode.AtMost && isScroll + ? Math.max(Math.min(crossSize, contentCross), crossPadBorder) + : contentCross + + node.layout.width = boundAxis(style, true, isMainRow ? finalMainSize : finalCrossSize, ownerWidth, ownerHeight) + node.layout.height = boundAxis(style, false, isMainRow ? finalCrossSize : finalMainSize, ownerWidth, ownerHeight) + commitCacheOutputs(node, performLayout) + cacheWrite( + node, + availableWidth, + availableHeight, + widthMode, + heightMode, + ownerWidth, + ownerHeight, + forceWidth, + forceHeight, + wasDirty + ) + + if (!performLayout) { + return + } + + const actualInnerMain = (isMainRow ? node.layout.width : node.layout.height) - mainPadBorder + const actualInnerCross = (isMainRow ? node.layout.height : node.layout.width) - crossPadBorder + const mainLeadEdgePhys = leadingEdge(mainAxis) + const mainTrailEdgePhys = trailingEdge(mainAxis) + const crossLeadEdgePhys = isMainRow ? EDGE_TOP : EDGE_LEFT + const crossTrailEdgePhys = isMainRow ? EDGE_BOTTOM : EDGE_RIGHT + const reversed = isReverse(mainAxis) + const mainContainerSize = isMainRow ? node.layout.width : node.layout.height + const crossLead = pad[crossLeadEdgePhys]! + bor[crossLeadEdgePhys]! + let lineCrossOffset = crossLead + let betweenLines = gapCross + const freeCross = actualInnerCross - totalLinesCross + + if (lineCount === 1 && !isWrap && !isBaseline) { + lineCrossSizes[0] = actualInnerCross + } else { + const remCross = Math.max(0, freeCross) + + switch (style.alignContent) { + case Align.FlexStart: + break + + case Align.Center: + lineCrossOffset += freeCross / 2 + + break + + case Align.FlexEnd: + lineCrossOffset += freeCross + + break + + case Align.Stretch: + if (lineCount > 0 && remCross > 0) { + const add = remCross / lineCount + + for (let i = 0; i < lineCount; i++) { + lineCrossSizes[i]! += add + } + } + + break + + case Align.SpaceBetween: + if (lineCount > 1) { + betweenLines += remCross / (lineCount - 1) + } + + break + + case Align.SpaceAround: + if (lineCount > 0) { + betweenLines += remCross / lineCount + lineCrossOffset += remCross / lineCount / 2 + } + + break + + case Align.SpaceEvenly: + if (lineCount > 0) { + betweenLines += remCross / (lineCount + 1) + lineCrossOffset += remCross / (lineCount + 1) + } + + break + + default: + break + } + } + + const wrapReverse = style.flexWrap === Wrap.WrapReverse + const crossContainerSize = isMainRow ? node.layout.height : node.layout.width + let lineCrossPos = lineCrossOffset + + for (let li = 0; li < lineCount; li++) { + const line = lines[li]! + const lineCross = lineCrossSizes[li]! + const consumedMain = lineConsumedMain[li]! + const n = line.length + + if (isWrap || crossMode !== MeasureMode.Exactly) { + for (const c of line) { + const cStyle = c.style + const childAlign = cStyle.alignSelf === Align.Auto ? style.alignItems : cStyle.alignSelf + + const crossStyleDef = isDefined( + resolveValue(isMainRow ? cStyle.height : cStyle.width, isMainRow ? ownerH : ownerW) + ) + + const hasCrossAutoMargin = + c._hasAutoMargin && + (isMarginAuto(cStyle.margin, crossLeadEdgePhys) || isMarginAuto(cStyle.margin, crossTrailEdgePhys)) + + if (childAlign === Align.Stretch && !crossStyleDef && !hasCrossAutoMargin) { + const cMarginCross = childMarginForAxis(c, crossAx, ownerW) + const target = Math.max(0, lineCross - cMarginCross) + + if (c._crossSize !== target) { + const cw = isMainRow ? c._mainSize : target + const ch = isMainRow ? target : c._mainSize + layoutNode( + c, + cw, + ch, + MeasureMode.Exactly, + MeasureMode.Exactly, + ownerW, + ownerH, + performLayout, + isMainRow, + !isMainRow + ) + c._crossSize = target + } + } + } + } + + let mainOffset = pad[mainLeadEdgePhys]! + bor[mainLeadEdgePhys]! + let betweenMain = gapMain + let numAutoMarginsMain = 0 + + for (const c of line) { + if (!c._hasAutoMargin) { + continue + } + + if (isMarginAuto(c.style.margin, mainLeadEdgePhys)) { + numAutoMarginsMain++ + } + + if (isMarginAuto(c.style.margin, mainTrailEdgePhys)) { + numAutoMarginsMain++ + } + } + + const freeMain = actualInnerMain - consumedMain + const remainingMain = Math.max(0, freeMain) + + const autoMarginMainSize = numAutoMarginsMain > 0 && remainingMain > 0 ? remainingMain / numAutoMarginsMain : 0 + + if (numAutoMarginsMain === 0) { + switch (style.justifyContent) { + case Justify.FlexStart: + break + + case Justify.Center: + mainOffset += freeMain / 2 + + break + + case Justify.FlexEnd: + mainOffset += freeMain + + break + + case Justify.SpaceBetween: + if (n > 1) { + betweenMain += remainingMain / (n - 1) + } + + break + + case Justify.SpaceAround: + if (n > 0) { + betweenMain += remainingMain / n + mainOffset += remainingMain / n / 2 + } + + break + + case Justify.SpaceEvenly: + if (n > 0) { + betweenMain += remainingMain / (n + 1) + mainOffset += remainingMain / (n + 1) + } + + break + } + } + + const effectiveLineCrossPos = wrapReverse ? crossContainerSize - lineCrossPos - lineCross : lineCrossPos + + let pos = mainOffset + + for (const c of line) { + const cMargin = c.style.margin + const cLayoutMargin = c.layout.margin + let autoMainLead = false + let autoMainTrail = false + let autoCrossLead = false + let autoCrossTrail = false + let mMainLead: number + let mMainTrail: number + let mCrossLead: number + let mCrossTrail: number + + if (c._hasAutoMargin) { + autoMainLead = isMarginAuto(cMargin, mainLeadEdgePhys) + autoMainTrail = isMarginAuto(cMargin, mainTrailEdgePhys) + autoCrossLead = isMarginAuto(cMargin, crossLeadEdgePhys) + autoCrossTrail = isMarginAuto(cMargin, crossTrailEdgePhys) + mMainLead = autoMainLead ? autoMarginMainSize : cLayoutMargin[mainLeadEdgePhys]! + mMainTrail = autoMainTrail ? autoMarginMainSize : cLayoutMargin[mainTrailEdgePhys]! + mCrossLead = autoCrossLead ? 0 : cLayoutMargin[crossLeadEdgePhys]! + mCrossTrail = autoCrossTrail ? 0 : cLayoutMargin[crossTrailEdgePhys]! + } else { + mMainLead = cLayoutMargin[mainLeadEdgePhys]! + mMainTrail = cLayoutMargin[mainTrailEdgePhys]! + mCrossLead = cLayoutMargin[crossLeadEdgePhys]! + mCrossTrail = cLayoutMargin[crossTrailEdgePhys]! + } + + const mainPos = reversed ? mainContainerSize - (pos + mMainLead) - c._mainSize : pos + mMainLead + + const childAlign = c.style.alignSelf === Align.Auto ? style.alignItems : c.style.alignSelf + let crossPos = effectiveLineCrossPos + mCrossLead + const crossFree = lineCross - c._crossSize - mCrossLead - mCrossTrail + + if (autoCrossLead && autoCrossTrail) { + crossPos += Math.max(0, crossFree) / 2 + } else if (autoCrossLead) { + crossPos += Math.max(0, crossFree) + } else if (autoCrossTrail) { + } else { + switch (childAlign) { + case Align.FlexStart: + + case Align.Stretch: + if (wrapReverse) { + crossPos += crossFree + } + + break + + case Align.Center: + crossPos += crossFree / 2 + + break + + case Align.FlexEnd: + if (!wrapReverse) { + crossPos += crossFree + } + + break + + case Align.Baseline: + if (isBaseline) { + crossPos = effectiveLineCrossPos + lineMaxAscent[li]! - calculateBaseline(c) + } + + break + + default: + break + } + } + + let relX = 0 + let relY = 0 + + if (c._hasPosition) { + const relLeft = resolveValue(resolveEdgeRaw(c.style.position, EDGE_LEFT), ownerW) + const relRight = resolveValue(resolveEdgeRaw(c.style.position, EDGE_RIGHT), ownerW) + const relTop = resolveValue(resolveEdgeRaw(c.style.position, EDGE_TOP), ownerW) + const relBottom = resolveValue(resolveEdgeRaw(c.style.position, EDGE_BOTTOM), ownerW) + relX = isDefined(relLeft) ? relLeft : isDefined(relRight) ? -relRight : 0 + relY = isDefined(relTop) ? relTop : isDefined(relBottom) ? -relBottom : 0 + } + + if (isMainRow) { + c.layout.left = mainPos + relX + c.layout.top = crossPos + relY + } else { + c.layout.left = crossPos + relX + c.layout.top = mainPos + relY + } + + pos += c._mainSize + mMainLead + mMainTrail + betweenMain + } + + lineCrossPos += lineCross + betweenLines + } + + for (const c of absChildren) { + layoutAbsoluteChild(node, c, node.layout.width, node.layout.height, pad, bor) + } +} + +function layoutAbsoluteChild( + parent: Node, + child: Node, + parentWidth: number, + parentHeight: number, + pad: [number, number, number, number], + bor: [number, number, number, number] +): void { + const cs = child.style + const posLeft = resolveEdgeRaw(cs.position, EDGE_LEFT) + const posRight = resolveEdgeRaw(cs.position, EDGE_RIGHT) + const posTop = resolveEdgeRaw(cs.position, EDGE_TOP) + const posBottom = resolveEdgeRaw(cs.position, EDGE_BOTTOM) + const rLeft = resolveValue(posLeft, parentWidth) + const rRight = resolveValue(posRight, parentWidth) + const rTop = resolveValue(posTop, parentHeight) + const rBottom = resolveValue(posBottom, parentHeight) + const paddingBoxW = parentWidth - bor[0] - bor[2] + const paddingBoxH = parentHeight - bor[1] - bor[3] + let cw = resolveValue(cs.width, paddingBoxW) + let ch = resolveValue(cs.height, paddingBoxH) + + if (!isDefined(cw) && isDefined(rLeft) && isDefined(rRight)) { + cw = paddingBoxW - rLeft - rRight + } + + if (!isDefined(ch) && isDefined(rTop) && isDefined(rBottom)) { + ch = paddingBoxH - rTop - rBottom + } + + layoutNode( + child, + cw, + ch, + isDefined(cw) ? MeasureMode.Exactly : MeasureMode.Undefined, + isDefined(ch) ? MeasureMode.Exactly : MeasureMode.Undefined, + paddingBoxW, + paddingBoxH, + true + ) + const mL = resolveEdge(cs.margin, EDGE_LEFT, parentWidth) + const mT = resolveEdge(cs.margin, EDGE_TOP, parentWidth) + const mR = resolveEdge(cs.margin, EDGE_RIGHT, parentWidth) + const mB = resolveEdge(cs.margin, EDGE_BOTTOM, parentWidth) + const mainAxis = parent.style.flexDirection + const reversed = isReverse(mainAxis) + const mainRow = isRow(mainAxis) + const wrapReverse = parent.style.flexWrap === Wrap.WrapReverse + const alignment = cs.alignSelf === Align.Auto ? parent.style.alignItems : cs.alignSelf + let left: number + + if (isDefined(rLeft)) { + left = bor[0] + rLeft + mL + } else if (isDefined(rRight)) { + left = parentWidth - bor[2] - rRight - child.layout.width - mR + } else if (mainRow) { + const lead = pad[0] + bor[0] + const trail = parentWidth - pad[2] - bor[2] + left = reversed + ? trail - child.layout.width - mR + : justifyAbsolute(parent.style.justifyContent, lead, trail, child.layout.width) + mL + } else { + left = + alignAbsolute(alignment, pad[0] + bor[0], parentWidth - pad[2] - bor[2], child.layout.width, wrapReverse) + mL + } + + let top: number + + if (isDefined(rTop)) { + top = bor[1] + rTop + mT + } else if (isDefined(rBottom)) { + top = parentHeight - bor[3] - rBottom - child.layout.height - mB + } else if (mainRow) { + top = + alignAbsolute(alignment, pad[1] + bor[1], parentHeight - pad[3] - bor[3], child.layout.height, wrapReverse) + mT + } else { + const lead = pad[1] + bor[1] + const trail = parentHeight - pad[3] - bor[3] + top = reversed + ? trail - child.layout.height - mB + : justifyAbsolute(parent.style.justifyContent, lead, trail, child.layout.height) + mT + } + + child.layout.left = left + child.layout.top = top +} + +function justifyAbsolute(justify: Justify, leadEdge: number, trailEdge: number, childSize: number): number { + switch (justify) { + case Justify.Center: + return leadEdge + (trailEdge - leadEdge - childSize) / 2 + + case Justify.FlexEnd: + return trailEdge - childSize + + default: + return leadEdge + } +} + +function alignAbsolute( + align: Align, + leadEdge: number, + trailEdge: number, + childSize: number, + wrapReverse: boolean +): number { + switch (align) { + case Align.Center: + return leadEdge + (trailEdge - leadEdge - childSize) / 2 + + case Align.FlexEnd: + return wrapReverse ? leadEdge : trailEdge - childSize + + default: + return wrapReverse ? trailEdge - childSize : leadEdge + } +} + +function computeFlexBasis( + child: Node, + mainAxis: FlexDirection, + availableMain: number, + availableCross: number, + crossMode: MeasureMode, + ownerWidth: number, + ownerHeight: number +): number { + const sameGen = child._fbGen === _generation + + if ( + (sameGen || !child.isDirty_) && + child._fbCrossMode === crossMode && + sameFloat(child._fbOwnerW, ownerWidth) && + sameFloat(child._fbOwnerH, ownerHeight) && + sameFloat(child._fbAvailMain, availableMain) && + sameFloat(child._fbAvailCross, availableCross) + ) { + return child._fbBasis + } + + const cs = child.style + const isMainRow = isRow(mainAxis) + const basis = resolveValue(cs.flexBasis, availableMain) + + if (isDefined(basis)) { + const b = Math.max(0, basis) + child._fbBasis = b + child._fbOwnerW = ownerWidth + child._fbOwnerH = ownerHeight + child._fbAvailMain = availableMain + child._fbAvailCross = availableCross + child._fbCrossMode = crossMode + child._fbGen = _generation + + return b + } + + const mainStyleDim = isMainRow ? cs.width : cs.height + const mainOwner = isMainRow ? ownerWidth : ownerHeight + const resolved = resolveValue(mainStyleDim, mainOwner) + + if (isDefined(resolved)) { + const b = Math.max(0, resolved) + child._fbBasis = b + child._fbOwnerW = ownerWidth + child._fbOwnerH = ownerHeight + child._fbAvailMain = availableMain + child._fbAvailCross = availableCross + child._fbCrossMode = crossMode + child._fbGen = _generation + + return b + } + + const crossStyleDim = isMainRow ? cs.height : cs.width + const crossOwner = isMainRow ? ownerHeight : ownerWidth + let crossConstraint = resolveValue(crossStyleDim, crossOwner) + + let crossConstraintMode: MeasureMode = isDefined(crossConstraint) ? MeasureMode.Exactly : MeasureMode.Undefined + + if (!isDefined(crossConstraint) && isDefined(availableCross)) { + crossConstraint = availableCross + crossConstraintMode = + crossMode === MeasureMode.Exactly && isStretchAlign(child) ? MeasureMode.Exactly : MeasureMode.AtMost + } + + let mainConstraint = NaN + let mainConstraintMode: MeasureMode = MeasureMode.Undefined + + if (isMainRow && isDefined(availableMain) && hasMeasureFuncInSubtree(child)) { + mainConstraint = availableMain + mainConstraintMode = MeasureMode.AtMost + } + + const mw = isMainRow ? mainConstraint : crossConstraint + const mh = isMainRow ? crossConstraint : mainConstraint + const mwMode = isMainRow ? mainConstraintMode : crossConstraintMode + const mhMode = isMainRow ? crossConstraintMode : mainConstraintMode + layoutNode(child, mw, mh, mwMode, mhMode, ownerWidth, ownerHeight, false) + const b = isMainRow ? child.layout.width : child.layout.height + child._fbBasis = b + child._fbOwnerW = ownerWidth + child._fbOwnerH = ownerHeight + child._fbAvailMain = availableMain + child._fbAvailCross = availableCross + child._fbCrossMode = crossMode + child._fbGen = _generation + + return b +} + +function hasMeasureFuncInSubtree(node: Node): boolean { + if (node.measureFunc) { + return true + } + + for (const c of node.children) { + if (hasMeasureFuncInSubtree(c)) { + return true + } + } + + return false +} + +function resolveFlexibleLengths( + children: Node[], + availableInnerMain: number, + totalFlexBasis: number, + isMainRow: boolean, + ownerW: number, + ownerH: number +): void { + const n = children.length + const frozen: boolean[] = new Array(n).fill(false) + + const initialFree = isDefined(availableInnerMain) ? availableInnerMain - totalFlexBasis : 0 + + for (let i = 0; i < n; i++) { + const c = children[i]! + const clamped = boundAxis(c.style, isMainRow, c._flexBasis, ownerW, ownerH) + + const inflexible = + !isDefined(availableInnerMain) || (initialFree >= 0 ? c.style.flexGrow === 0 : c.style.flexShrink === 0) + + if (inflexible) { + c._mainSize = Math.max(0, clamped) + frozen[i] = true + } else { + c._mainSize = c._flexBasis + } + } + + const unclamped: number[] = new Array(n) + + for (let iter = 0; iter <= n; iter++) { + let frozenDelta = 0 + let totalGrow = 0 + let totalShrinkScaled = 0 + let unfrozenCount = 0 + + for (let i = 0; i < n; i++) { + const c = children[i]! + + if (frozen[i]) { + frozenDelta += c._mainSize - c._flexBasis + } else { + totalGrow += c.style.flexGrow + totalShrinkScaled += c.style.flexShrink * c._flexBasis + unfrozenCount++ + } + } + + if (unfrozenCount === 0) { + break + } + + let remaining = initialFree - frozenDelta + + if (remaining > 0 && totalGrow > 0 && totalGrow < 1) { + const scaled = initialFree * totalGrow + + if (scaled < remaining) { + remaining = scaled + } + } else if (remaining < 0 && totalShrinkScaled > 0) { + let totalShrink = 0 + + for (let i = 0; i < n; i++) { + if (!frozen[i]) { + totalShrink += children[i]!.style.flexShrink + } + } + + if (totalShrink < 1) { + const scaled = initialFree * totalShrink + + if (scaled > remaining) { + remaining = scaled + } + } + } + + let totalViolation = 0 + + for (let i = 0; i < n; i++) { + if (frozen[i]) { + continue + } + + const c = children[i]! + let t = c._flexBasis + + if (remaining > 0 && totalGrow > 0) { + t += (remaining * c.style.flexGrow) / totalGrow + } else if (remaining < 0 && totalShrinkScaled > 0) { + t += (remaining * (c.style.flexShrink * c._flexBasis)) / totalShrinkScaled + } + + unclamped[i] = t + const clamped = Math.max(0, boundAxis(c.style, isMainRow, t, ownerW, ownerH)) + c._mainSize = clamped + totalViolation += clamped - t + } + + if (totalViolation === 0) { + break + } + + let anyFrozen = false + + for (let i = 0; i < n; i++) { + if (frozen[i]) { + continue + } + + const v = children[i]!._mainSize - unclamped[i]! + + if ((totalViolation > 0 && v > 0) || (totalViolation < 0 && v < 0)) { + frozen[i] = true + anyFrozen = true + } + } + + if (!anyFrozen) { + break + } + } +} + +function isStretchAlign(child: Node): boolean { + const p = child.parent + + if (!p) { + return false + } + + const align = child.style.alignSelf === Align.Auto ? p.style.alignItems : child.style.alignSelf + + return align === Align.Stretch +} + +function resolveChildAlign(parent: Node, child: Node): Align { + return child.style.alignSelf === Align.Auto ? parent.style.alignItems : child.style.alignSelf +} + +function calculateBaseline(node: Node): number { + let baselineChild: Node | null = null + + for (const c of node.children) { + if (c._lineIndex > 0) { + break + } + + if (c.style.positionType === PositionType.Absolute) { + continue + } + + if (c.style.display === Display.None) { + continue + } + + if (resolveChildAlign(node, c) === Align.Baseline || c.isReferenceBaseline_) { + baselineChild = c + + break + } + + if (baselineChild === null) { + baselineChild = c + } + } + + if (baselineChild === null) { + return node.layout.height + } + + return calculateBaseline(baselineChild) + baselineChild.layout.top +} + +function isBaselineLayout(node: Node, flowChildren: Node[]): boolean { + if (!isRow(node.style.flexDirection)) { + return false + } + + if (node.style.alignItems === Align.Baseline) { + return true + } + + for (const c of flowChildren) { + if (c.style.alignSelf === Align.Baseline) { + return true + } + } + + return false +} + +function childMarginForAxis(child: Node, axis: FlexDirection, ownerWidth: number): number { + if (!child._hasMargin) { + return 0 + } + + const lead = resolveEdge(child.style.margin, leadingEdge(axis), ownerWidth) + const trail = resolveEdge(child.style.margin, trailingEdge(axis), ownerWidth) + + return lead + trail +} + +function resolveGap(style: Style, gutter: Gutter, ownerSize: number): number { + let v = style.gap[gutter]! + + if (v.unit === Unit.Undefined) { + v = style.gap[Gutter.All]! + } + + const r = resolveValue(v, ownerSize) + + return isDefined(r) ? Math.max(0, r) : 0 +} + +function boundAxis(style: Style, isWidth: boolean, value: number, ownerWidth: number, ownerHeight: number): number { + const minV = isWidth ? style.minWidth : style.minHeight + const maxV = isWidth ? style.maxWidth : style.maxHeight + const minU = minV.unit + const maxU = maxV.unit + + if (minU === 0 && maxU === 0) { + return value + } + + const owner = isWidth ? ownerWidth : ownerHeight + let v = value + + if (maxU === 1) { + if (v > maxV.value) { + v = maxV.value + } + } else if (maxU === 2) { + const m = (maxV.value * owner) / 100 + + if (m === m && v > m) { + v = m + } + } + + if (minU === 1) { + if (v < minV.value) { + v = minV.value + } + } else if (minU === 2) { + const m = (minV.value * owner) / 100 + + if (m === m && v < m) { + v = m + } + } + + return v +} + +function zeroLayoutRecursive(node: Node): void { + for (const c of node.children) { + c.layout.left = 0 + c.layout.top = 0 + c.layout.width = 0 + c.layout.height = 0 + c.isDirty_ = true + c._hasL = false + c._hasM = false + zeroLayoutRecursive(c) + } +} + +function collectLayoutChildren(node: Node, flow: Node[], abs: Node[]): void { + for (const c of node.children) { + const disp = c.style.display + + if (disp === Display.None) { + c.layout.left = 0 + c.layout.top = 0 + c.layout.width = 0 + c.layout.height = 0 + zeroLayoutRecursive(c) + } else if (disp === Display.Contents) { + c.layout.left = 0 + c.layout.top = 0 + c.layout.width = 0 + c.layout.height = 0 + collectLayoutChildren(c, flow, abs) + } else if (c.style.positionType === PositionType.Absolute) { + abs.push(c) + } else { + flow.push(c) + } + } +} + +function roundLayout(node: Node, scale: number, absLeft: number, absTop: number): void { + if (scale === 0) { + return + } + + const l = node.layout + const nodeLeft = l.left + const nodeTop = l.top + const nodeWidth = l.width + const nodeHeight = l.height + const absNodeLeft = absLeft + nodeLeft + const absNodeTop = absTop + nodeTop + const isText = node.measureFunc !== null + l.left = roundValue(nodeLeft, scale, false, isText) + l.top = roundValue(nodeTop, scale, false, isText) + const absRight = absNodeLeft + nodeWidth + const absBottom = absNodeTop + nodeHeight + const hasFracW = !isWholeNumber(nodeWidth * scale) + const hasFracH = !isWholeNumber(nodeHeight * scale) + l.width = + roundValue(absRight, scale, isText && hasFracW, isText && !hasFracW) - roundValue(absNodeLeft, scale, false, isText) + l.height = + roundValue(absBottom, scale, isText && hasFracH, isText && !hasFracH) - roundValue(absNodeTop, scale, false, isText) + + for (const c of node.children) { + roundLayout(c, scale, absNodeLeft, absNodeTop) + } +} + +function isWholeNumber(v: number): boolean { + const frac = v - Math.floor(v) + + return frac < 0.0001 || frac > 0.9999 +} + +function roundValue(v: number, scale: number, forceCeil: boolean, forceFloor: boolean): number { + let scaled = v * scale + let frac = scaled - Math.floor(scaled) + + if (frac < 0) { + frac += 1 + } + + if (frac < 0.0001) { + scaled = Math.floor(scaled) + } else if (frac > 0.9999) { + scaled = Math.ceil(scaled) + } else if (forceCeil) { + scaled = Math.ceil(scaled) + } else if (forceFloor) { + scaled = Math.floor(scaled) + } else { + scaled = Math.floor(scaled) + (frac >= 0.4999 ? 1 : 0) + } + + return scaled / scale +} + +function parseDimension(v: number | string | undefined): Value { + if (v === undefined) { + return UNDEFINED_VALUE + } + + if (v === 'auto') { + return AUTO_VALUE + } + + if (typeof v === 'number') { + return Number.isFinite(v) ? pointValue(v) : UNDEFINED_VALUE + } + + if (typeof v === 'string' && v.endsWith('%')) { + return percentValue(parseFloat(v)) + } + + const n = parseFloat(v) + + return isNaN(n) ? UNDEFINED_VALUE : pointValue(n) +} + +function physicalEdge(edge: Edge): number { + switch (edge) { + case Edge.Left: + + case Edge.Start: + return EDGE_LEFT + + case Edge.Top: + return EDGE_TOP + + case Edge.Right: + + case Edge.End: + return EDGE_RIGHT + + case Edge.Bottom: + return EDGE_BOTTOM + + default: + return EDGE_LEFT + } +} + +export type Yoga = { + Config: { + create(): Config + destroy(config: Config): void + } + Node: { + create(config?: Config): Node + createDefault(): Node + createWithConfig(config: Config): Node + destroy(node: Node): void + } +} + +const YOGA_INSTANCE: Yoga = { + Config: { + create: createConfig, + destroy() {} + }, + Node: { + create: (config?: Config) => new Node(config), + createDefault: () => new Node(), + createWithConfig: (config: Config) => new Node(config), + destroy() {} + } +} + +export function loadYoga(): Promise { + return Promise.resolve(YOGA_INSTANCE) +} + +export default YOGA_INSTANCE diff --git a/ui-tui/packages/hermes-ink/src/utils/debug.ts b/ui-tui/packages/hermes-ink/src/utils/debug.ts new file mode 100644 index 0000000000..285a07ac1b --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/debug.ts @@ -0,0 +1,6 @@ +export function logForDebugging( + _message: string, + _options: { + level?: string + } = {} +): void {} diff --git a/ui-tui/packages/hermes-ink/src/utils/earlyInput.ts b/ui-tui/packages/hermes-ink/src/utils/earlyInput.ts new file mode 100644 index 0000000000..bdc8418415 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/earlyInput.ts @@ -0,0 +1,131 @@ +import { lastGrapheme } from './intl.js' +let earlyInputBuffer = '' +let isCapturing = false +let readableHandler: (() => void) | null = null + +export function startCapturingEarlyInput(): void { + if (!process.stdin.isTTY || isCapturing || process.argv.includes('-p') || process.argv.includes('--print')) { + return + } + + isCapturing = true + earlyInputBuffer = '' + + try { + process.stdin.setEncoding('utf8') + process.stdin.setRawMode(true) + process.stdin.ref() + + readableHandler = () => { + let chunk = process.stdin.read() + + while (chunk !== null) { + if (typeof chunk === 'string') { + processChunk(chunk) + } + + chunk = process.stdin.read() + } + } + + process.stdin.on('readable', readableHandler) + } catch { + isCapturing = false + } +} + +function processChunk(str: string): void { + let i = 0 + + while (i < str.length) { + const char = str[i]! + const code = char.charCodeAt(0) + + if (code === 3) { + stopCapturingEarlyInput() + process.exit(130) + + return + } + + if (code === 4) { + stopCapturingEarlyInput() + + return + } + + if (code === 127 || code === 8) { + if (earlyInputBuffer.length > 0) { + const last = lastGrapheme(earlyInputBuffer) + earlyInputBuffer = earlyInputBuffer.slice(0, -(last.length || 1)) + } + + i++ + + continue + } + + if (code === 27) { + i++ + + while (i < str.length && !(str.charCodeAt(i) >= 64 && str.charCodeAt(i) <= 126)) { + i++ + } + + if (i < str.length) { + i++ + } + + continue + } + + if (code < 32 && code !== 9 && code !== 10 && code !== 13) { + i++ + + continue + } + + if (code === 13) { + earlyInputBuffer += '\n' + i++ + + continue + } + + earlyInputBuffer += char + i++ + } +} + +export function stopCapturingEarlyInput(): void { + if (!isCapturing) { + return + } + + isCapturing = false + + if (readableHandler) { + process.stdin.removeListener('readable', readableHandler) + readableHandler = null + } +} + +export function consumeEarlyInput(): string { + stopCapturingEarlyInput() + const input = earlyInputBuffer.trim() + earlyInputBuffer = '' + + return input +} + +export function hasEarlyInput(): boolean { + return earlyInputBuffer.trim().length > 0 +} + +export function seedEarlyInput(text: string): void { + earlyInputBuffer = text +} + +export function isCapturingEarlyInput(): boolean { + return isCapturing +} diff --git a/ui-tui/packages/hermes-ink/src/utils/env.ts b/ui-tui/packages/hermes-ink/src/utils/env.ts new file mode 100644 index 0000000000..7393f1baa7 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/env.ts @@ -0,0 +1,41 @@ +type TerminalName = string | null + +function detectTerminal(): TerminalName { + if (process.env.CURSOR_TRACE_ID) { + return 'cursor' + } + + if (process.env.TERM === 'xterm-ghostty') { + return 'ghostty' + } + + if (process.env.TERM?.includes('kitty')) { + return 'kitty' + } + + if (process.env.TERM_PROGRAM) { + return process.env.TERM_PROGRAM + } + + if (process.env.TMUX) { + return 'tmux' + } + + if (process.env.STY) { + return 'screen' + } + + if (process.env.KITTY_WINDOW_ID) { + return 'kitty' + } + + if (process.env.WT_SESSION) { + return 'windows-terminal' + } + + return process.env.TERM ?? null +} + +export const env = { + terminal: detectTerminal() +} diff --git a/ui-tui/packages/hermes-ink/src/utils/envUtils.ts b/ui-tui/packages/hermes-ink/src/utils/envUtils.ts new file mode 100644 index 0000000000..f3286197b5 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/envUtils.ts @@ -0,0 +1,13 @@ +export function isEnvTruthy(envVar: string | boolean | undefined): boolean { + if (!envVar) { + return false + } + + if (typeof envVar === 'boolean') { + return envVar + } + + const v = envVar.toLowerCase().trim() + + return ['1', 'true', 'yes', 'on'].includes(v) +} diff --git a/ui-tui/packages/hermes-ink/src/utils/execFileNoThrow.ts b/ui-tui/packages/hermes-ink/src/utils/execFileNoThrow.ts new file mode 100644 index 0000000000..106555b13e --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/execFileNoThrow.ts @@ -0,0 +1,64 @@ +import { spawn } from 'child_process' +type ExecFileOptions = { + input?: string + timeout?: number + useCwd?: boolean + env?: NodeJS.ProcessEnv +} + +export function execFileNoThrow( + file: string, + args: string[], + options: ExecFileOptions = {} +): Promise<{ + stdout: string + stderr: string + code: number + error?: string +}> { + return new Promise(resolve => { + const child = spawn(file, args, { + cwd: options.useCwd ? process.cwd() : undefined, + env: options.env, + stdio: 'pipe' + }) + + let stdout = '' + let stderr = '' + let timedOut = false + + const timer = options.timeout + ? setTimeout(() => { + timedOut = true + child.kill('SIGTERM') + }, options.timeout) + : null + + child.stdout?.on('data', chunk => { + stdout += String(chunk) + }) + child.stderr?.on('data', chunk => { + stderr += String(chunk) + }) + child.on('error', error => { + if (timer) { + clearTimeout(timer) + } + + resolve({ stdout, stderr, code: 1, error: String(error) }) + }) + child.on('close', code => { + if (timer) { + clearTimeout(timer) + } + + resolve({ stdout, stderr, code: timedOut ? 124 : (code ?? 0) }) + }) + + if (options.input) { + child.stdin?.write(options.input) + } + + child.stdin?.end() + }) +} diff --git a/ui-tui/packages/hermes-ink/src/utils/fullscreen.ts b/ui-tui/packages/hermes-ink/src/utils/fullscreen.ts new file mode 100644 index 0000000000..523a43102b --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/fullscreen.ts @@ -0,0 +1,3 @@ +export function isMouseClicksDisabled(): boolean { + return /^(1|true|yes|on)$/.test((process.env.HERMES_TUI_DISABLE_MOUSE_CLICKS ?? '').trim().toLowerCase()) +} diff --git a/ui-tui/packages/hermes-ink/src/utils/intl.ts b/ui-tui/packages/hermes-ink/src/utils/intl.ts new file mode 100644 index 0000000000..6f9dfaf92d --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/intl.ts @@ -0,0 +1,87 @@ +let graphemeSegmenter: Intl.Segmenter | null = null +let wordSegmenter: Intl.Segmenter | null = null + +export function getGraphemeSegmenter(): Intl.Segmenter { + if (!graphemeSegmenter) { + graphemeSegmenter = new Intl.Segmenter(undefined, { + granularity: 'grapheme' + }) + } + + return graphemeSegmenter +} + +export function firstGrapheme(text: string): string { + if (!text) { + return '' + } + + const segments = getGraphemeSegmenter().segment(text) + const first = segments[Symbol.iterator]().next().value + + return first?.segment ?? '' +} + +export function lastGrapheme(text: string): string { + if (!text) { + return '' + } + + let last = '' + + for (const { segment } of getGraphemeSegmenter().segment(text)) { + last = segment + } + + return last +} + +export function getWordSegmenter(): Intl.Segmenter { + if (!wordSegmenter) { + wordSegmenter = new Intl.Segmenter(undefined, { granularity: 'word' }) + } + + return wordSegmenter +} + +const rtfCache = new Map() + +export function getRelativeTimeFormat( + style: 'long' | 'short' | 'narrow', + numeric: 'always' | 'auto' +): Intl.RelativeTimeFormat { + const key = `${style}:${numeric}` + let rtf = rtfCache.get(key) + + if (!rtf) { + rtf = new Intl.RelativeTimeFormat('en', { style, numeric }) + rtfCache.set(key, rtf) + } + + return rtf +} + +let cachedTimeZone: string | null = null + +export function getTimeZone(): string { + if (!cachedTimeZone) { + cachedTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone + } + + return cachedTimeZone +} + +let cachedSystemLocaleLanguage: string | undefined | null = null + +export function getSystemLocaleLanguage(): string | undefined { + if (cachedSystemLocaleLanguage === null) { + try { + const locale = Intl.DateTimeFormat().resolvedOptions().locale + cachedSystemLocaleLanguage = new Intl.Locale(locale).language + } catch { + cachedSystemLocaleLanguage = undefined + } + } + + return cachedSystemLocaleLanguage +} diff --git a/ui-tui/packages/hermes-ink/src/utils/log.ts b/ui-tui/packages/hermes-ink/src/utils/log.ts new file mode 100644 index 0000000000..369763eee0 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/log.ts @@ -0,0 +1,7 @@ +export function logError(error: unknown): void { + if (!process.env.HERMES_INK_DEBUG_ERRORS) { + return + } + + console.error(error) +} diff --git a/ui-tui/packages/hermes-ink/src/utils/semver.ts b/ui-tui/packages/hermes-ink/src/utils/semver.ts new file mode 100644 index 0000000000..87025ed0fd --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/semver.ts @@ -0,0 +1,57 @@ +let _npmSemver: typeof import('semver') | undefined + +function getNpmSemver(): typeof import('semver') { + if (!_npmSemver) { + _npmSemver = require('semver') as typeof import('semver') + } + + return _npmSemver +} + +export function gt(a: string, b: string): boolean { + if (typeof Bun !== 'undefined') { + return Bun.semver.order(a, b) === 1 + } + + return getNpmSemver().gt(a, b, { loose: true }) +} + +export function gte(a: string, b: string): boolean { + if (typeof Bun !== 'undefined') { + return Bun.semver.order(a, b) >= 0 + } + + return getNpmSemver().gte(a, b, { loose: true }) +} + +export function lt(a: string, b: string): boolean { + if (typeof Bun !== 'undefined') { + return Bun.semver.order(a, b) === -1 + } + + return getNpmSemver().lt(a, b, { loose: true }) +} + +export function lte(a: string, b: string): boolean { + if (typeof Bun !== 'undefined') { + return Bun.semver.order(a, b) <= 0 + } + + return getNpmSemver().lte(a, b, { loose: true }) +} + +export function satisfies(version: string, range: string): boolean { + if (typeof Bun !== 'undefined') { + return Bun.semver.satisfies(version, range) + } + + return getNpmSemver().satisfies(version, range, { loose: true }) +} + +export function order(a: string, b: string): -1 | 0 | 1 { + if (typeof Bun !== 'undefined') { + return Bun.semver.order(a, b) + } + + return getNpmSemver().compare(a, b, { loose: true }) as -1 | 0 | 1 +} diff --git a/ui-tui/packages/hermes-ink/src/utils/sliceAnsi.ts b/ui-tui/packages/hermes-ink/src/utils/sliceAnsi.ts new file mode 100644 index 0000000000..7be1950b12 --- /dev/null +++ b/ui-tui/packages/hermes-ink/src/utils/sliceAnsi.ts @@ -0,0 +1,58 @@ +import { type AnsiCode, ansiCodesToString, reduceAnsiCodes, tokenize, undoAnsiCodes } from '@alcalzone/ansi-tokenize' + +import { stringWidth } from '../ink/stringWidth.js' + +function isEndCode(code: AnsiCode): boolean { + return code.code === code.endCode +} + +function filterStartCodes(codes: AnsiCode[]): AnsiCode[] { + return codes.filter(c => !isEndCode(c)) +} + +export default function sliceAnsi(str: string, start: number, end?: number): string { + const tokens = tokenize(str) + let activeCodes: AnsiCode[] = [] + let position = 0 + let result = '' + let include = false + + for (const token of tokens) { + const width = token.type === 'ansi' ? 0 : token.fullWidth ? 2 : stringWidth(token.value) + + if (end !== undefined && position >= end) { + if (token.type === 'ansi' || width > 0 || !include) { + break + } + } + + if (token.type === 'ansi') { + activeCodes.push(token) + + if (include) { + result += token.code + } + } else { + if (!include && position >= start) { + if (start > 0 && width === 0) { + continue + } + + include = true + activeCodes = filterStartCodes(reduceAnsiCodes(activeCodes)) + result = ansiCodesToString(activeCodes) + } + + if (include) { + result += token.value + } + + position += width + } + } + + const activeStartCodes = filterStartCodes(reduceAnsiCodes(activeCodes)) + result += ansiCodesToString(undoAnsiCodes(activeStartCodes)) + + return result +} diff --git a/ui-tui/packages/hermes-ink/text-input.d.ts b/ui-tui/packages/hermes-ink/text-input.d.ts new file mode 100644 index 0000000000..f9f5df1c8d --- /dev/null +++ b/ui-tui/packages/hermes-ink/text-input.d.ts @@ -0,0 +1,2 @@ +export { default, UncontrolledTextInput } from 'ink-text-input' +export type { Props } from 'ink-text-input' diff --git a/ui-tui/packages/hermes-ink/text-input.js b/ui-tui/packages/hermes-ink/text-input.js new file mode 100644 index 0000000000..8cb79c0ccb --- /dev/null +++ b/ui-tui/packages/hermes-ink/text-input.js @@ -0,0 +1 @@ +export { default, UncontrolledTextInput } from 'ink-text-input' diff --git a/ui-tui/src/__tests__/asCommandDispatch.test.ts b/ui-tui/src/__tests__/asCommandDispatch.test.ts new file mode 100644 index 0000000000..49ea56936c --- /dev/null +++ b/ui-tui/src/__tests__/asCommandDispatch.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' + +import { asCommandDispatch } from '../lib/rpc.js' + +describe('asCommandDispatch', () => { + it('parses exec, alias, and skill', () => { + expect(asCommandDispatch({ type: 'exec', output: 'hi' })).toEqual({ type: 'exec', output: 'hi' }) + expect(asCommandDispatch({ type: 'alias', target: 'help' })).toEqual({ type: 'alias', target: 'help' }) + expect(asCommandDispatch({ type: 'skill', name: 'x', message: 'do' })).toEqual({ + type: 'skill', + name: 'x', + message: 'do' + }) + }) + + it('rejects malformed payloads', () => { + expect(asCommandDispatch(null)).toBeNull() + expect(asCommandDispatch({ type: 'alias' })).toBeNull() + expect(asCommandDispatch({ type: 'skill', name: 1 })).toBeNull() + }) +}) diff --git a/ui-tui/src/__tests__/constants.test.ts b/ui-tui/src/__tests__/constants.test.ts new file mode 100644 index 0000000000..d069d24c2d --- /dev/null +++ b/ui-tui/src/__tests__/constants.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' + +import { FACES } from '../content/faces.js' +import { HOTKEYS } from '../content/hotkeys.js' +import { PLACEHOLDERS } from '../content/placeholders.js' +import { TOOL_VERBS, VERBS } from '../content/verbs.js' +import { ROLE } from '../domain/roles.js' +import { ZERO } from '../domain/usage.js' +import { INTERPOLATION_RE } from '../protocol/interpolation.js' +import { DEFAULT_THEME } from '../theme.js' + +describe('constants', () => { + it('ZERO', () => expect(ZERO).toEqual({ calls: 0, input: 0, output: 0, total: 0 })) + + it('string arrays are populated', () => { + for (const arr of [FACES, PLACEHOLDERS, VERBS]) { + expect(arr.length).toBeGreaterThan(0) + arr.forEach(s => expect(typeof s).toBe('string')) + } + }) + + it('HOTKEYS are [key, desc] pairs', () => { + HOTKEYS.forEach(([k, d]) => { + expect(typeof k).toBe('string') + expect(typeof d).toBe('string') + }) + }) + + it('TOOL_VERBS maps known tools (verb-only, no emoji)', () => { + expect(TOOL_VERBS.terminal).toBe('terminal') + expect(TOOL_VERBS.read_file).toBe('reading') + }) + + it('INTERPOLATION_RE matches {!cmd}', () => { + INTERPOLATION_RE.lastIndex = 0 + expect(INTERPOLATION_RE.test('{!date}')).toBe(true) + + INTERPOLATION_RE.lastIndex = 0 + expect(INTERPOLATION_RE.test('plain')).toBe(false) + }) + + it('ROLE produces glyph/body/prefix per role', () => { + for (const role of ['assistant', 'system', 'tool', 'user'] as const) { + expect(ROLE[role](DEFAULT_THEME)).toHaveProperty('glyph') + } + }) +}) diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts new file mode 100644 index 0000000000..e546ce640e --- /dev/null +++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts @@ -0,0 +1,164 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js' +import { resetOverlayState } from '../app/overlayStore.js' +import { turnController } from '../app/turnController.js' +import { resetTurnState } from '../app/turnStore.js' +import { resetUiState } from '../app/uiStore.js' +import { estimateTokensRough } from '../lib/text.js' +import type { Msg } from '../types.js' + +const ref = (current: T) => ({ current }) + +const buildCtx = (appended: Msg[]) => + ({ + composer: { + dequeue: () => undefined, + queueEditRef: ref(null), + sendQueued: vi.fn() + }, + gateway: { + gw: { request: vi.fn() }, + rpc: vi.fn(async () => null) + }, + session: { + STARTUP_RESUME_ID: '', + colsRef: ref(80), + newSession: vi.fn(), + resetSession: vi.fn(), + resumeById: vi.fn(), + setCatalog: vi.fn() + }, + system: { + bellOnComplete: false, + sys: vi.fn() + }, + transcript: { + appendMessage: (msg: Msg) => appended.push(msg), + panel: (title: string, sections: any[]) => + appended.push({ kind: 'panel', panelData: { sections, title }, role: 'system', text: '' }), + setHistoryItems: vi.fn() + } + }) as any + +describe('createGatewayEventHandler', () => { + beforeEach(() => { + resetOverlayState() + resetUiState() + resetTurnState() + turnController.fullReset() + }) + + it('persists completed tool rows when message.complete lands immediately after tool.complete', () => { + const appended: Msg[] = [] + + turnController.reasoningText = 'mapped the page' + const onEvent = createGatewayEventHandler(buildCtx(appended)) + + onEvent({ + payload: { context: 'home page', name: 'search', tool_id: 'tool-1' }, + type: 'tool.start' + } as any) + onEvent({ + payload: { name: 'search', preview: 'hero cards' }, + type: 'tool.progress' + } as any) + onEvent({ + payload: { summary: 'done', tool_id: 'tool-1' }, + type: 'tool.complete' + } as any) + onEvent({ + payload: { text: 'final answer' }, + type: 'message.complete' + } as any) + + expect(appended).toHaveLength(1) + expect(appended[0]).toMatchObject({ + role: 'assistant', + text: 'final answer', + thinking: 'mapped the page' + }) + expect(appended[0]?.tools).toHaveLength(1) + expect(appended[0]?.tools?.[0]).toContain('hero cards') + expect(appended[0]?.toolTokens).toBeGreaterThan(0) + }) + + it('keeps tool tokens across handler recreation mid-turn', () => { + const appended: Msg[] = [] + + turnController.reasoningText = 'mapped the page' + + createGatewayEventHandler(buildCtx(appended))({ + payload: { context: 'home page', name: 'search', tool_id: 'tool-1' }, + type: 'tool.start' + } as any) + + const onEvent = createGatewayEventHandler(buildCtx(appended)) + + onEvent({ + payload: { name: 'search', preview: 'hero cards' }, + type: 'tool.progress' + } as any) + onEvent({ + payload: { summary: 'done', tool_id: 'tool-1' }, + type: 'tool.complete' + } as any) + onEvent({ + payload: { text: 'final answer' }, + type: 'message.complete' + } as any) + + expect(appended).toHaveLength(1) + expect(appended[0]?.tools).toHaveLength(1) + expect(appended[0]?.toolTokens).toBeGreaterThan(0) + }) + + it('ignores fallback reasoning.available when streamed reasoning already exists', () => { + const appended: Msg[] = [] + const streamed = 'short streamed reasoning' + const fallback = 'x'.repeat(400) + + const onEvent = createGatewayEventHandler(buildCtx(appended)) + + onEvent({ payload: { text: streamed }, type: 'reasoning.delta' } as any) + onEvent({ payload: { text: fallback }, type: 'reasoning.available' } as any) + onEvent({ payload: { text: 'final answer' }, type: 'message.complete' } as any) + + expect(appended).toHaveLength(1) + expect(appended[0]?.thinking).toBe(streamed) + expect(appended[0]?.thinkingTokens).toBe(estimateTokensRough(streamed)) + }) + + it('uses message.complete reasoning when no streamed reasoning ref', () => { + const appended: Msg[] = [] + const fromServer = 'recovered from last_reasoning' + + const onEvent = createGatewayEventHandler(buildCtx(appended)) + + onEvent({ payload: { reasoning: fromServer, text: 'final answer' }, type: 'message.complete' } as any) + + expect(appended).toHaveLength(1) + expect(appended[0]?.thinking).toBe(fromServer) + expect(appended[0]?.thinkingTokens).toBe(estimateTokensRough(fromServer)) + }) + + it('shows setup panel for missing provider startup error', () => { + const appended: Msg[] = [] + const onEvent = createGatewayEventHandler(buildCtx(appended)) + + onEvent({ + payload: { + message: + 'agent init failed: No LLM provider configured. Run `hermes model` to select a provider, or run `hermes setup` for first-time configuration.' + }, + type: 'error' + } as any) + + expect(appended).toHaveLength(1) + expect(appended[0]).toMatchObject({ + kind: 'panel', + panelData: { title: 'Setup Required' }, + role: 'system' + }) + }) +}) diff --git a/ui-tui/src/__tests__/createSlashHandler.test.ts b/ui-tui/src/__tests__/createSlashHandler.test.ts new file mode 100644 index 0000000000..9e1db99463 --- /dev/null +++ b/ui-tui/src/__tests__/createSlashHandler.test.ts @@ -0,0 +1,192 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { createSlashHandler } from '../app/createSlashHandler.js' +import { getOverlayState, resetOverlayState } from '../app/overlayStore.js' +import { getUiState, resetUiState } from '../app/uiStore.js' + +describe('createSlashHandler', () => { + beforeEach(() => { + resetOverlayState() + resetUiState() + }) + + it('opens the resume picker locally', () => { + const ctx = buildCtx() + + expect(createSlashHandler(ctx)('/resume')).toBe(true) + expect(getOverlayState().picker).toBe(true) + }) + + it('cycles details mode and persists it', async () => { + const ctx = buildCtx() + + expect(getUiState().detailsMode).toBe('collapsed') + expect(createSlashHandler(ctx)('/details toggle')).toBe(true) + expect(getUiState().detailsMode).toBe('expanded') + expect(ctx.gateway.rpc).toHaveBeenCalledWith('config.set', { + key: 'details_mode', + value: 'expanded' + }) + expect(ctx.transcript.sys).toHaveBeenCalledWith('details: expanded') + }) + + it('shows tool enable usage when names are missing', () => { + const ctx = buildCtx() + + expect(createSlashHandler(ctx)('/tools enable')).toBe(true) + expect(ctx.transcript.sys).toHaveBeenNthCalledWith(1, 'usage: /tools enable [name ...]') + expect(ctx.transcript.sys).toHaveBeenNthCalledWith(2, 'built-in toolset: /tools enable web') + expect(ctx.transcript.sys).toHaveBeenNthCalledWith(3, 'MCP tool: /tools enable github:create_issue') + }) + + it('drops stale slash.exec output after a newer slash', async () => { + let resolveLate: (v: { output?: string }) => void + let slashExecCalls = 0 + + const ctx = buildCtx({ + gateway: { + gw: { + getLogTail: vi.fn(() => ''), + request: vi.fn((method: string) => { + if (method === 'slash.exec') { + slashExecCalls += 1 + + if (slashExecCalls === 1) { + return new Promise<{ output?: string }>(res => { + resolveLate = res + }) + } + + return Promise.resolve({ output: 'fresh' }) + } + + return Promise.resolve({}) + }) + }, + rpc: vi.fn(() => Promise.resolve({})) + } + }) + + const h = createSlashHandler(ctx) + expect(h('/slow')).toBe(true) + expect(h('/fast')).toBe(true) + resolveLate!({ output: 'too late' }) + await vi.waitFor(() => { + expect(ctx.transcript.sys).toHaveBeenCalled() + }) + + expect(ctx.transcript.sys).not.toHaveBeenCalledWith('too late') + }) + + it('dispatches command.dispatch with typed alias', async () => { + const ctx = buildCtx({ + gateway: { + gw: { + getLogTail: vi.fn(() => ''), + request: vi.fn((method: string) => { + if (method === 'slash.exec') { + return Promise.reject(new Error('no')) + } + + if (method === 'command.dispatch') { + return Promise.resolve({ type: 'alias', target: 'help' }) + } + + return Promise.resolve({}) + }) + }, + rpc: vi.fn(() => Promise.resolve({})) + } + }) + + const h = createSlashHandler(ctx) + expect(h('/zzz')).toBe(true) + await vi.waitFor(() => { + expect(ctx.transcript.panel).toHaveBeenCalledWith(expect.any(String), expect.any(Array)) + }) + }) + + it('resolves unique local aliases through the catalog', () => { + const ctx = buildCtx({ + local: { + catalog: { + canon: { + '/h': '/help', + '/help': '/help' + } + } + } + }) + + expect(createSlashHandler(ctx)('/h')).toBe(true) + expect(ctx.transcript.panel).toHaveBeenCalledWith(expect.any(String), expect.any(Array)) + }) +}) + +const buildCtx = (overrides: Partial = {}): Ctx => ({ + ...overrides, + slashFlightRef: overrides.slashFlightRef ?? { current: 0 }, + composer: { ...buildComposer(), ...overrides.composer }, + gateway: { ...buildGateway(), ...overrides.gateway }, + local: { ...buildLocal(), ...overrides.local }, + session: { ...buildSession(), ...overrides.session }, + transcript: { ...buildTranscript(), ...overrides.transcript }, + voice: { ...buildVoice(), ...overrides.voice } +}) + +const buildComposer = () => ({ + enqueue: vi.fn(), + hasSelection: false, + paste: vi.fn(), + queueRef: { current: [] as string[] }, + selection: { copySelection: vi.fn(() => '') }, + setInput: vi.fn() +}) + +const buildGateway = () => ({ + gw: { + getLogTail: vi.fn(() => ''), + request: vi.fn(() => Promise.resolve({})) + }, + rpc: vi.fn(() => Promise.resolve({})) +}) + +const buildLocal = () => ({ + catalog: null, + getHistoryItems: vi.fn(() => []), + getLastUserMsg: vi.fn(() => ''), + maybeWarn: vi.fn() +}) + +const buildSession = () => ({ + closeSession: vi.fn(() => Promise.resolve(null)), + die: vi.fn(), + guardBusySessionSwitch: vi.fn(() => false), + newSession: vi.fn(), + resetVisibleHistory: vi.fn(), + resumeById: vi.fn(), + setSessionStartedAt: vi.fn() +}) + +const buildTranscript = () => ({ + page: vi.fn(), + panel: vi.fn(), + send: vi.fn(), + setHistoryItems: vi.fn(), + sys: vi.fn(), + trimLastExchange: vi.fn(items => items) +}) + +const buildVoice = () => ({ + setVoiceEnabled: vi.fn() +}) + +interface Ctx { + slashFlightRef: { current: number } + composer: ReturnType + gateway: ReturnType + local: ReturnType + session: ReturnType + transcript: ReturnType + voice: ReturnType +} diff --git a/ui-tui/src/__tests__/messages.test.ts b/ui-tui/src/__tests__/messages.test.ts new file mode 100644 index 0000000000..8f6a265f1d --- /dev/null +++ b/ui-tui/src/__tests__/messages.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' + +import { upsert } from '../lib/messages.js' + +describe('upsert', () => { + it('appends when last role differs', () => { + expect(upsert([{ role: 'user', text: 'hi' }], 'assistant', 'hello')).toHaveLength(2) + }) + + it('replaces when last role matches', () => { + expect(upsert([{ role: 'assistant', text: 'partial' }], 'assistant', 'full')[0]!.text).toBe('full') + }) + + it('appends to empty', () => { + expect(upsert([], 'user', 'first')).toEqual([{ role: 'user', text: 'first' }]) + }) + + it('does not mutate', () => { + const prev = [{ role: 'user' as const, text: 'hi' }] + upsert(prev, 'assistant', 'yo') + expect(prev).toHaveLength(1) + }) +}) diff --git a/ui-tui/src/__tests__/rpc.test.ts b/ui-tui/src/__tests__/rpc.test.ts new file mode 100644 index 0000000000..7980093a9e --- /dev/null +++ b/ui-tui/src/__tests__/rpc.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' + +import { asRpcResult, rpcErrorMessage } from '../lib/rpc.js' + +describe('asRpcResult', () => { + it('keeps plain object payloads', () => { + expect(asRpcResult({ ok: true, value: 'x' })).toEqual({ ok: true, value: 'x' }) + }) + + it('rejects missing or non-object payloads', () => { + expect(asRpcResult(undefined)).toBeNull() + expect(asRpcResult(null)).toBeNull() + expect(asRpcResult('oops')).toBeNull() + expect(asRpcResult(['bad'])).toBeNull() + }) +}) + +describe('rpcErrorMessage', () => { + it('prefers Error messages', () => { + expect(rpcErrorMessage(new Error('boom'))).toBe('boom') + }) + + it('falls back for unknown errors', () => { + expect(rpcErrorMessage('broken')).toBe('broken') + expect(rpcErrorMessage({ code: 500 })).toBe('request failed') + }) +}) diff --git a/ui-tui/src/__tests__/text.test.ts b/ui-tui/src/__tests__/text.test.ts new file mode 100644 index 0000000000..0a11e3cc06 --- /dev/null +++ b/ui-tui/src/__tests__/text.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest' + +import { + edgePreview, + estimateRows, + estimateTokensRough, + fmtK, + isToolTrailResultLine, + lastCotTrailIndex, + pasteTokenLabel, + sameToolTrailGroup +} from '../lib/text.js' + +describe('isToolTrailResultLine', () => { + it('detects completion markers', () => { + expect(isToolTrailResultLine('foo ✓')).toBe(true) + expect(isToolTrailResultLine('foo ✗')).toBe(true) + expect(isToolTrailResultLine('drafting x…')).toBe(false) + }) +}) + +describe('lastCotTrailIndex', () => { + it('finds last non-result line', () => { + expect(lastCotTrailIndex(['a ✓', 'thinking…'])).toBe(1) + expect(lastCotTrailIndex(['only result ✓'])).toBe(-1) + }) +}) + +describe('sameToolTrailGroup', () => { + it('matches bare check lines', () => { + expect(sameToolTrailGroup('searching', 'searching ✓')).toBe(true) + expect(sameToolTrailGroup('searching', 'searching ✗')).toBe(true) + }) + + it('matches contextual lines', () => { + expect(sameToolTrailGroup('searching', 'searching: * ✓')).toBe(true) + expect(sameToolTrailGroup('searching', 'searching: foo ✓')).toBe(true) + }) + + it('rejects other tools', () => { + expect(sameToolTrailGroup('searching', 'reading ✓')).toBe(false) + expect(sameToolTrailGroup('searching', 'searching extra ✓')).toBe(false) + }) +}) + +describe('fmtK', () => { + it('keeps small numbers plain', () => { + expect(fmtK(999)).toBe('999') + }) + + it('formats thousands as lowercase k', () => { + expect(fmtK(1000)).toBe('1k') + expect(fmtK(1500)).toBe('1.5k') + }) + + it('formats millions and billions with lowercase suffixes', () => { + expect(fmtK(1_000_000)).toBe('1m') + expect(fmtK(1_000_000_000)).toBe('1b') + }) +}) + +describe('estimateTokensRough', () => { + it('uses 4 chars per token rounding up', () => { + expect(estimateTokensRough('')).toBe(0) + expect(estimateTokensRough('a')).toBe(1) + expect(estimateTokensRough('abcd')).toBe(1) + expect(estimateTokensRough('abcde')).toBe(2) + }) +}) + +describe('edgePreview', () => { + it('keeps both ends for long text', () => { + expect(edgePreview('Vampire Bondage ropes slipped from her neck, still stained with blood', 8, 18)).toBe( + 'Vampire.. stained with blood' + ) + }) +}) + +describe('pasteTokenLabel', () => { + it('builds readable long-paste labels with counts', () => { + const label = pasteTokenLabel('Vampire Bondage ropes slipped from her neck, still stained with blood', 250) + expect(label.startsWith('[[ ')).toBe(true) + expect(label).toContain('[250 lines]') + expect(label.endsWith(' ]]')).toBe(true) + }) +}) + +describe('estimateRows', () => { + it('handles tilde code fences', () => { + const md = ['~~~markdown', '# heading', '~~~'].join('\n') + + expect(estimateRows(md, 40)).toBeGreaterThanOrEqual(2) + }) + + it('handles checklist bullets as list rows', () => { + const md = ['- [x] done', '- [ ] todo'].join('\n') + + expect(estimateRows(md, 40)).toBe(2) + }) +}) diff --git a/ui-tui/src/__tests__/theme.test.ts b/ui-tui/src/__tests__/theme.test.ts new file mode 100644 index 0000000000..86a9768b0f --- /dev/null +++ b/ui-tui/src/__tests__/theme.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from 'vitest' + +import { DEFAULT_THEME, fromSkin } from '../theme.js' + +describe('DEFAULT_THEME', () => { + it('has brand defaults', () => { + expect(DEFAULT_THEME.brand.name).toBe('Hermes Agent') + expect(DEFAULT_THEME.brand.prompt).toBe('❯') + expect(DEFAULT_THEME.brand.tool).toBe('┊') + }) + + it('has color palette', () => { + expect(DEFAULT_THEME.color.gold).toBe('#FFD700') + expect(DEFAULT_THEME.color.error).toBe('#ef5350') + }) +}) + +describe('fromSkin', () => { + it('overrides banner colors', () => { + expect(fromSkin({ banner_title: '#FF0000' }, {}).color.gold).toBe('#FF0000') + }) + + it('preserves unset colors', () => { + expect(fromSkin({ banner_title: '#FF0000' }, {}).color.amber).toBe(DEFAULT_THEME.color.amber) + }) + + it('overrides branding', () => { + const { brand } = fromSkin({}, { agent_name: 'TestBot', prompt_symbol: '$' }) + expect(brand.name).toBe('TestBot') + expect(brand.prompt).toBe('$') + }) + + it('defaults for empty skin', () => { + expect(fromSkin({}, {}).color).toEqual(DEFAULT_THEME.color) + expect(fromSkin({}, {}).brand.icon).toBe(DEFAULT_THEME.brand.icon) + }) + + it('passes banner logo/hero', () => { + expect(fromSkin({}, {}, 'LOGO', 'HERO').bannerLogo).toBe('LOGO') + expect(fromSkin({}, {}, 'LOGO', 'HERO').bannerHero).toBe('HERO') + }) + + it('maps ui_ color keys + cascades to status', () => { + const { color } = fromSkin({ ui_ok: '#008000' }, {}) + expect(color.ok).toBe('#008000') + expect(color.statusGood).toBe('#008000') + }) +}) diff --git a/ui-tui/src/app.tsx b/ui-tui/src/app.tsx new file mode 100644 index 0000000000..631bd7a350 --- /dev/null +++ b/ui-tui/src/app.tsx @@ -0,0 +1,22 @@ +import { GatewayProvider } from './app/gatewayContext.js' +import { useMainApp } from './app/useMainApp.js' +import { AppLayout } from './components/appLayout.js' +import { MOUSE_TRACKING } from './config/env.js' +import type { GatewayClient } from './gatewayClient.js' + +export function App({ gw }: { gw: GatewayClient }) { + const { appActions, appComposer, appProgress, appStatus, appTranscript, gateway } = useMainApp(gw) + + return ( + + + + ) +} diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts new file mode 100644 index 0000000000..e728f8bbd0 --- /dev/null +++ b/ui-tui/src/app/createGatewayEventHandler.ts @@ -0,0 +1,430 @@ +import { STREAM_BATCH_MS } from '../config/timing.js' +import { buildSetupRequiredSections, SETUP_REQUIRED_TITLE } from '../content/setup.js' +import type { CommandsCatalogResponse, GatewayEvent, GatewaySkin } from '../gatewayTypes.js' +import { rpcErrorMessage } from '../lib/rpc.js' +import { formatToolCall } from '../lib/text.js' +import { fromSkin } from '../theme.js' +import type { Msg, SubagentProgress } from '../types.js' + +import type { GatewayEventHandlerContext } from './interfaces.js' +import { patchOverlayState } from './overlayStore.js' +import { turnController } from './turnController.js' +import { getUiState, patchUiState } from './uiStore.js' + +const ERRLIKE_RE = /\b(error|traceback|exception|failed|spawn)\b/i +const NO_PROVIDER_RE = /\bNo (?:LLM|inference) provider configured\b/i + +const statusFromBusy = () => (getUiState().busy ? 'running…' : 'ready') + +const applySkin = (s: GatewaySkin) => + patchUiState({ + theme: fromSkin( + s.colors ?? {}, + s.branding ?? {}, + s.banner_logo ?? '', + s.banner_hero ?? '', + s.tool_prefix ?? '', + s.help_header ?? '' + ) + }) + +const dropBgTask = (taskId: string) => + patchUiState(state => { + const next = new Set(state.bgTasks) + next.delete(taskId) + + return { ...state, bgTasks: next } + }) + +const pushUnique = + (max: number) => + (xs: T[], x: T): T[] => + xs.at(-1) === x ? xs : [...xs, x].slice(-max) + +const pushThinking = pushUnique(6) +const pushNote = pushUnique(6) +const pushTool = pushUnique(8) + +export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev: GatewayEvent) => void { + const { dequeue, queueEditRef, sendQueued } = ctx.composer + const { rpc } = ctx.gateway + const { STARTUP_RESUME_ID, newSession, resumeById, setCatalog } = ctx.session + const { bellOnComplete, stdout, sys } = ctx.system + const { appendMessage, panel, setHistoryItems } = ctx.transcript + + let pendingThinkingStatus = '' + let thinkingStatusTimer: null | ReturnType = null + + const setStatus = (status: string) => { + pendingThinkingStatus = '' + + if (thinkingStatusTimer) { + clearTimeout(thinkingStatusTimer) + thinkingStatusTimer = null + } + + patchUiState({ status }) + } + + const scheduleThinkingStatus = (status: string) => { + pendingThinkingStatus = status + + if (thinkingStatusTimer) { + return + } + + thinkingStatusTimer = setTimeout(() => { + thinkingStatusTimer = null + patchUiState({ status: pendingThinkingStatus || statusFromBusy() }) + }, STREAM_BATCH_MS) + } + + const restoreStatusAfter = (ms: number) => { + turnController.clearStatusTimer() + turnController.statusTimer = setTimeout(() => { + turnController.statusTimer = null + patchUiState({ status: statusFromBusy() }) + }, ms) + } + + const keepCompletedElseRunning = (s: SubagentProgress['status']) => (s === 'completed' ? s : 'running') + + const handleReady = (skin?: GatewaySkin) => { + if (skin) { + applySkin(skin) + } + + rpc('commands.catalog', {}) + .then(r => { + if (!r?.pairs) { + return + } + + setCatalog({ + canon: (r.canon ?? {}) as Record, + categories: r.categories ?? [], + pairs: r.pairs as [string, string][], + skillCount: (r.skill_count ?? 0) as number, + sub: (r.sub ?? {}) as Record + }) + + if (r.warning) { + turnController.pushActivity(String(r.warning), 'warn') + } + }) + .catch((e: unknown) => turnController.pushActivity(`command catalog unavailable: ${rpcErrorMessage(e)}`, 'warn')) + + if (!STARTUP_RESUME_ID) { + patchUiState({ status: 'forging session…' }) + newSession() + + return + } + + patchUiState({ status: 'resuming…' }) + resumeById(STARTUP_RESUME_ID) + } + + return (ev: GatewayEvent) => { + const sid = getUiState().sid + + if (ev.session_id && sid && ev.session_id !== sid && !ev.type.startsWith('gateway.')) { + return + } + + switch (ev.type) { + case 'gateway.ready': + handleReady(ev.payload?.skin) + + return + + case 'skin.changed': + if (ev.payload) { + applySkin(ev.payload) + } + + return + case 'session.info': { + const info = ev.payload + + patchUiState(state => ({ + ...state, + info, + status: state.status === 'starting agent…' ? 'ready' : state.status, + usage: info.usage ? { ...state.usage, ...info.usage } : state.usage + })) + + setHistoryItems(prev => prev.map(m => (m.kind === 'intro' ? { ...m, info } : m))) + + return + } + + case 'thinking.delta': { + const text = ev.payload?.text + + if (text !== undefined) { + scheduleThinkingStatus(text ? String(text) : statusFromBusy()) + } + + return + } + + case 'message.start': + turnController.startMessage() + + return + case 'status.update': { + const p = ev.payload + + if (!p?.text) { + return + } + + setStatus(p.text) + + if (!p.kind || p.kind === 'status') { + return + } + + if (turnController.lastStatusNote !== p.text) { + turnController.lastStatusNote = p.text + turnController.pushActivity( + p.text, + p.kind === 'error' ? 'error' : p.kind === 'warn' || p.kind === 'approval' ? 'warn' : 'info' + ) + } + + restoreStatusAfter(4000) + + return + } + + case 'gateway.stderr': { + const line = String(ev.payload.line).slice(0, 120) + + turnController.pushActivity(line, ERRLIKE_RE.test(line) ? 'error' : 'warn') + + return + } + + case 'gateway.start_timeout': { + const { cwd, python } = ev.payload ?? {} + const trace = python || cwd ? ` · ${String(python || '')} ${String(cwd || '')}`.trim() : '' + + setStatus('gateway startup timeout') + turnController.pushActivity(`gateway startup timed out${trace} · /logs to inspect`, 'error') + + return + } + + case 'gateway.protocol_error': + setStatus('protocol warning') + restoreStatusAfter(4000) + + if (!turnController.protocolWarned) { + turnController.protocolWarned = true + turnController.pushActivity('protocol noise detected · /logs to inspect', 'warn') + } + + if (ev.payload?.preview) { + turnController.pushActivity(`protocol noise: ${String(ev.payload.preview).slice(0, 120)}`, 'warn') + } + + return + + case 'reasoning.delta': + if (ev.payload?.text) { + turnController.recordReasoningDelta(ev.payload.text) + } + + return + + case 'reasoning.available': + turnController.recordReasoningAvailable(String(ev.payload?.text ?? '')) + + return + + case 'tool.progress': + if (ev.payload?.preview && ev.payload.name) { + turnController.recordToolProgress(ev.payload.name, ev.payload.preview) + } + + return + + case 'tool.generating': + if (ev.payload?.name) { + turnController.pushTrail(`drafting ${ev.payload.name}…`) + } + + return + + case 'tool.start': + turnController.recordToolStart(ev.payload.tool_id, ev.payload.name ?? 'tool', ev.payload.context ?? '') + + return + + case 'tool.complete': + turnController.recordToolComplete(ev.payload.tool_id, ev.payload.name, ev.payload.error, ev.payload.summary) + + if (ev.payload.inline_diff) { + sys(ev.payload.inline_diff) + } + + return + + case 'clarify.request': + patchOverlayState({ + clarify: { choices: ev.payload.choices, question: ev.payload.question, requestId: ev.payload.request_id } + }) + setStatus('waiting for input…') + + return + case 'approval.request': { + const description = String(ev.payload.description ?? 'dangerous command') + + patchOverlayState({ approval: { command: String(ev.payload.command ?? ''), description } }) + turnController.pushActivity(`approval needed · ${description}`, 'warn') + setStatus('approval needed') + + return + } + + case 'sudo.request': + patchOverlayState({ sudo: { requestId: ev.payload.request_id } }) + setStatus('sudo password needed') + + return + + case 'secret.request': + patchOverlayState({ + secret: { envVar: ev.payload.env_var, prompt: ev.payload.prompt, requestId: ev.payload.request_id } + }) + setStatus('secret input needed') + + return + + case 'background.complete': + dropBgTask(ev.payload.task_id) + sys(`[bg ${ev.payload.task_id}] ${ev.payload.text}`) + + return + + case 'btw.complete': + dropBgTask('btw:x') + sys(`[btw] ${ev.payload.text}`) + + return + + case 'subagent.start': + turnController.upsertSubagent(ev.payload, () => ({ status: 'running' })) + + return + case 'subagent.thinking': { + const text = String(ev.payload.text ?? '').trim() + + if (!text) { + return + } + + turnController.upsertSubagent(ev.payload, c => ({ + status: keepCompletedElseRunning(c.status), + thinking: pushThinking(c.thinking, text) + })) + + return + } + + case 'subagent.tool': { + const line = formatToolCall( + ev.payload.tool_name ?? 'delegate_task', + ev.payload.tool_preview ?? ev.payload.text ?? '' + ) + + turnController.upsertSubagent(ev.payload, c => ({ + status: keepCompletedElseRunning(c.status), + tools: pushTool(c.tools, line) + })) + + return + } + + case 'subagent.progress': { + const text = String(ev.payload.text ?? '').trim() + + if (!text) { + return + } + + turnController.upsertSubagent(ev.payload, c => ({ + notes: pushNote(c.notes, text), + status: keepCompletedElseRunning(c.status) + })) + + return + } + + case 'subagent.complete': + turnController.upsertSubagent(ev.payload, c => ({ + durationSeconds: ev.payload.duration_seconds ?? c.durationSeconds, + status: ev.payload.status ?? 'completed', + summary: ev.payload.summary || ev.payload.text || c.summary + })) + + return + + case 'message.delta': + turnController.recordMessageDelta(ev.payload ?? {}) + + return + case 'message.complete': { + const { finalMessages, finalText, wasInterrupted } = turnController.recordMessageComplete(ev.payload ?? {}) + + if (!wasInterrupted) { + const msgs: Msg[] = finalMessages.length ? finalMessages : [{ role: 'assistant', text: finalText }] + msgs.forEach(appendMessage) + + if (bellOnComplete && stdout?.isTTY) { + stdout.write('\x07') + } + } + + setStatus('ready') + + if (ev.payload?.usage) { + patchUiState(state => ({ ...state, usage: { ...state.usage, ...ev.payload!.usage } })) + } + + if (queueEditRef.current !== null) { + return + } + + const next = dequeue() + + if (next) { + sendQueued(next) + } + + return + } + + case 'error': + turnController.recordError() + + { + const message = String(ev.payload?.message || 'unknown error') + + turnController.pushActivity(message, 'error') + + if (NO_PROVIDER_RE.test(message)) { + panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections()) + setStatus('setup required') + + return + } + + sys(`error: ${message}`) + setStatus('ready') + } + } + } +} diff --git a/ui-tui/src/app/createSlashHandler.ts b/ui-tui/src/app/createSlashHandler.ts new file mode 100644 index 0000000000..87475341ae --- /dev/null +++ b/ui-tui/src/app/createSlashHandler.ts @@ -0,0 +1,116 @@ +import { parseSlashCommand } from '../domain/slash.js' +import type { SlashExecResponse } from '../gatewayTypes.js' +import { asCommandDispatch, rpcErrorMessage } from '../lib/rpc.js' + +import type { SlashHandlerContext } from './interfaces.js' +import { findSlashCommand } from './slash/registry.js' +import type { SlashRunCtx } from './slash/types.js' +import { getUiState } from './uiStore.js' + +export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => boolean { + const { gw } = ctx.gateway + const { catalog } = ctx.local + const { page, send, sys } = ctx.transcript + + const handler = (cmd: string): boolean => { + const flight = ++ctx.slashFlightRef.current + const ui = getUiState() + const sid = ui.sid + const parsed = parseSlashCommand(cmd) + const argTail = parsed.arg ? ` ${parsed.arg}` : '' + + const stale = () => flight !== ctx.slashFlightRef.current || getUiState().sid !== sid + + const guarded = + (fn: (r: T) => void) => + (r: null | T): void => { + if (!stale() && r) { + fn(r) + } + } + + const guardedErr = (e: unknown) => { + if (!stale()) { + sys(`error: ${rpcErrorMessage(e)}`) + } + } + + const runCtx: SlashRunCtx = { ...ctx, flight, guarded, guardedErr, sid, stale, ui } + + const found = findSlashCommand(parsed.name) + + if (found) { + found.run(parsed.arg, runCtx, cmd) + + return true + } + + if (catalog?.canon) { + const needle = `/${parsed.name}`.toLowerCase() + + const matches = [ + ...new Set( + Object.entries(catalog.canon) + .filter(([alias]) => alias.startsWith(needle)) + .map(([, canon]) => canon) + ) + ] + + if (matches.length === 1 && matches[0]!.toLowerCase() !== needle) { + return handler(`${matches[0]}${argTail}`) + } + + if (matches.length > 1) { + sys(`ambiguous command: ${matches.slice(0, 6).join(', ')}${matches.length > 6 ? ', …' : ''}`) + + return true + } + } + + gw.request('slash.exec', { command: cmd.slice(1), session_id: sid }) + .then(r => { + if (stale()) { + return + } + + const body = r?.output || `/${parsed.name}: no output` + const text = r?.warning ? `warning: ${r.warning}\n${body}` : body + const long = text.length > 180 || text.split('\n').filter(Boolean).length > 2 + + long ? page(text, parsed.name[0]!.toUpperCase() + parsed.name.slice(1)) : sys(text) + }) + .catch(() => { + gw.request('command.dispatch', { arg: parsed.arg, name: parsed.name, session_id: sid }) + .then((raw: unknown) => { + if (stale()) { + return + } + + const d = asCommandDispatch(raw) + + if (!d) { + return sys('error: invalid response: command.dispatch') + } + + if (d.type === 'exec' || d.type === 'plugin') { + return sys(d.output || '(no output)') + } + + if (d.type === 'alias') { + return handler(`/${d.target}${argTail}`) + } + + if (d.type === 'skill') { + sys(`⚡ loading skill: ${d.name}`) + + return d.message?.trim() ? send(d.message) : sys(`/${parsed.name}: skill payload missing message`) + } + }) + .catch(guardedErr) + }) + + return true + } + + return handler +} diff --git a/ui-tui/src/app/gatewayContext.tsx b/ui-tui/src/app/gatewayContext.tsx new file mode 100644 index 0000000000..9187f15a3a --- /dev/null +++ b/ui-tui/src/app/gatewayContext.tsx @@ -0,0 +1,19 @@ +import { createContext, useContext } from 'react' + +import type { GatewayProviderProps, GatewayServices } from './interfaces.js' + +const GatewayContext = createContext(null) + +export function GatewayProvider({ children, value }: GatewayProviderProps) { + return {children} +} + +export function useGateway() { + const value = useContext(GatewayContext) + + if (!value) { + throw new Error('GatewayContext missing') + } + + return value +} diff --git a/ui-tui/src/app/interfaces.ts b/ui-tui/src/app/interfaces.ts new file mode 100644 index 0000000000..998afe2a19 --- /dev/null +++ b/ui-tui/src/app/interfaces.ts @@ -0,0 +1,339 @@ +import type { ScrollBoxHandle } from '@hermes/ink' +import type { MutableRefObject, ReactNode, RefObject, SetStateAction } from 'react' + +import type { PasteEvent } from '../components/textInput.js' +import type { GatewayClient } from '../gatewayClient.js' +import type { RpcResult } from '../lib/rpc.js' +import type { Theme } from '../theme.js' +import type { + ActiveTool, + ActivityItem, + ApprovalReq, + ClarifyReq, + DetailsMode, + Msg, + PanelSection, + SecretReq, + SessionInfo, + SlashCatalog, + SubagentProgress, + SudoReq, + Usage +} from '../types.js' + +export interface StateSetter { + (value: SetStateAction): void +} + +export interface SelectionApi { + clearSelection: () => void + copySelection: () => string +} + +export interface CompletionItem { + display: string + meta?: string + text: string +} + +export interface GatewayRpc { + (method: string, params?: Record): Promise +} + +export interface GatewayServices { + gw: GatewayClient + rpc: GatewayRpc +} + +export interface GatewayProviderProps { + children: ReactNode + value: GatewayServices +} + +export interface OverlayState { + approval: ApprovalReq | null + clarify: ClarifyReq | null + modelPicker: boolean + pager: null | PagerState + picker: boolean + secret: null | SecretReq + sudo: null | SudoReq +} + +export interface PagerState { + lines: string[] + offset: number + title?: string +} + +export interface TranscriptRow { + index: number + key: string + msg: Msg +} + +export interface UiState { + bgTasks: Set + busy: boolean + compact: boolean + detailsMode: DetailsMode + info: null | SessionInfo + sid: null | string + status: string + statusBar: boolean + theme: Theme + usage: Usage +} + +export interface VirtualHistoryState { + bottomSpacer: number + end: number + measureRef: (key: string) => (el: unknown) => void + offsets: ArrayLike + start: number + topSpacer: number +} + +export interface ComposerPasteResult { + cursor: number + value: string +} + +export interface ComposerActions { + clearIn: () => void + dequeue: () => string | undefined + enqueue: (text: string) => void + handleTextPaste: (event: PasteEvent) => ComposerPasteResult | null + openEditor: () => void + pushHistory: (text: string) => void + replaceQueue: (index: number, text: string) => void + setCompIdx: StateSetter + setHistoryIdx: StateSetter + setInput: StateSetter + setInputBuf: StateSetter + setPasteSnips: StateSetter + setQueueEdit: (index: null | number) => void + syncQueue: () => void +} + +export interface ComposerRefs { + historyDraftRef: MutableRefObject + historyRef: MutableRefObject + queueEditRef: MutableRefObject + queueRef: MutableRefObject + submitRef: MutableRefObject<(value: string) => void> +} + +export interface ComposerState { + compIdx: number + compReplace: number + completions: CompletionItem[] + historyIdx: null | number + input: string + inputBuf: string[] + pasteSnips: PasteSnippet[] + queueEditIdx: null | number + queuedDisplay: string[] +} + +export interface UseComposerStateOptions { + gw: GatewayClient + onClipboardPaste: (quiet?: boolean) => Promise | void + submitRef: MutableRefObject<(value: string) => void> +} + +export interface UseComposerStateResult { + actions: ComposerActions + refs: ComposerRefs + state: ComposerState +} + +export interface InputHandlerActions { + answerClarify: (answer: string) => void + appendMessage: (msg: Msg) => void + die: () => void + dispatchSubmission: (full: string) => void + guardBusySessionSwitch: (what?: string) => boolean + newSession: (msg?: string) => void + sys: (text: string) => void +} + +export interface InputHandlerContext { + actions: InputHandlerActions + composer: { + actions: ComposerActions + refs: ComposerRefs + state: ComposerState + } + gateway: GatewayServices + terminal: { + hasSelection: boolean + scrollRef: RefObject + scrollWithSelection: (delta: number) => void + selection: SelectionApi + stdout?: NodeJS.WriteStream + } + voice: { + recording: boolean + setProcessing: StateSetter + setRecording: StateSetter + } + wheelStep: number +} + +export interface InputHandlerResult { + pagerPageSize: number +} + +export interface GatewayEventHandlerContext { + composer: { + dequeue: () => string | undefined + queueEditRef: MutableRefObject + sendQueued: (text: string) => void + } + gateway: GatewayServices + session: { + STARTUP_RESUME_ID: string + colsRef: MutableRefObject + newSession: (msg?: string) => void + resetSession: () => void + resumeById: (id: string) => void + setCatalog: StateSetter + } + system: { + bellOnComplete: boolean + stdout?: NodeJS.WriteStream + sys: (text: string) => void + } + transcript: { + appendMessage: (msg: Msg) => void + panel: (title: string, sections: PanelSection[]) => void + setHistoryItems: StateSetter + } +} + +export interface SlashHandlerContext { + composer: { + enqueue: (text: string) => void + hasSelection: boolean + paste: (quiet?: boolean) => void + queueRef: MutableRefObject + selection: SelectionApi + setInput: StateSetter + } + gateway: GatewayServices + local: { + catalog: null | SlashCatalog + getHistoryItems: () => Msg[] + getLastUserMsg: () => string + maybeWarn: (value: unknown) => void + } + session: { + closeSession: (targetSid?: null | string) => Promise + die: () => void + guardBusySessionSwitch: (what?: string) => boolean + newSession: (msg?: string) => void + resetVisibleHistory: (info?: null | SessionInfo) => void + resumeById: (id: string) => void + setSessionStartedAt: StateSetter + } + slashFlightRef: MutableRefObject + transcript: { + page: (text: string, title?: string) => void + panel: (title: string, sections: PanelSection[]) => void + send: (text: string) => void + setHistoryItems: StateSetter + sys: (text: string) => void + trimLastExchange: (items: Msg[]) => Msg[] + } + voice: { + setVoiceEnabled: StateSetter + } +} + +export interface AppLayoutActions { + answerApproval: (choice: string) => void + answerClarify: (answer: string) => void + answerSecret: (value: string) => void + answerSudo: (pw: string) => void + onModelSelect: (value: string) => void + resumeById: (id: string) => void + setStickyPrompt: (value: string) => void +} + +export interface AppLayoutComposerProps { + cols: number + compIdx: number + completions: CompletionItem[] + empty: boolean + handleTextPaste: (event: PasteEvent) => ComposerPasteResult | null + input: string + inputBuf: string[] + pagerPageSize: number + queueEditIdx: null | number + queuedDisplay: string[] + submit: (value: string) => void + updateInput: StateSetter +} + +export interface AppLayoutProgressProps { + activity: ActivityItem[] + outcome: string + reasoning: string + reasoningActive: boolean + reasoningStreaming: boolean + reasoningTokens: number + showProgressArea: boolean + showStreamingArea: boolean + streamPendingTools: string[] + streamSegments: Msg[] + streaming: string + subagents: SubagentProgress[] + toolTokens: number + tools: ActiveTool[] + turnTrail: string[] +} + +export interface AppLayoutStatusProps { + cwdLabel: string + goodVibesTick: number + sessionStartedAt: null | number + showStickyPrompt: boolean + statusColor: string + stickyPrompt: string + voiceLabel: string +} + +export interface AppLayoutTranscriptProps { + historyItems: Msg[] + scrollRef: RefObject + virtualHistory: VirtualHistoryState + virtualRows: TranscriptRow[] +} + +export interface AppLayoutProps { + actions: AppLayoutActions + composer: AppLayoutComposerProps + mouseTracking: boolean + progress: AppLayoutProgressProps + status: AppLayoutStatusProps + transcript: AppLayoutTranscriptProps +} + +export interface AppOverlaysProps { + cols: number + compIdx: number + completions: CompletionItem[] + onApprovalChoice: (choice: string) => void + onClarifyAnswer: (value: string) => void + onModelSelect: (value: string) => void + onPickerSelect: (sessionId: string) => void + onSecretSubmit: (value: string) => void + onSudoSubmit: (pw: string) => void + pagerPageSize: number +} + +export interface PasteSnippet { + label: string + text: string +} diff --git a/ui-tui/src/app/overlayStore.ts b/ui-tui/src/app/overlayStore.ts new file mode 100644 index 0000000000..4b24f0daab --- /dev/null +++ b/ui-tui/src/app/overlayStore.ts @@ -0,0 +1,26 @@ +import { atom, computed } from 'nanostores' + +import type { OverlayState } from './interfaces.js' + +const buildOverlayState = (): OverlayState => ({ + approval: null, + clarify: null, + modelPicker: false, + pager: null, + picker: false, + secret: null, + sudo: null +}) + +export const $overlayState = atom(buildOverlayState()) + +export const $isBlocked = computed($overlayState, ({ approval, clarify, modelPicker, pager, picker, secret, sudo }) => + Boolean(approval || clarify || modelPicker || pager || picker || secret || sudo) +) + +export const getOverlayState = () => $overlayState.get() + +export const patchOverlayState = (next: Partial | ((state: OverlayState) => OverlayState)) => + $overlayState.set(typeof next === 'function' ? next($overlayState.get()) : { ...$overlayState.get(), ...next }) + +export const resetOverlayState = () => $overlayState.set(buildOverlayState()) diff --git a/ui-tui/src/app/setupHandoff.ts b/ui-tui/src/app/setupHandoff.ts new file mode 100644 index 0000000000..21338c95e4 --- /dev/null +++ b/ui-tui/src/app/setupHandoff.ts @@ -0,0 +1,54 @@ +import type { RunExternalProcess } from '@hermes/ink' + +import type { SetupStatusResponse } from '../gatewayTypes.js' +import type { LaunchResult } from '../lib/externalCli.js' + +import type { SlashHandlerContext } from './interfaces.js' +import { patchUiState } from './uiStore.js' + +export interface RunExternalSetupOptions { + args: string[] + ctx: Pick + done: string + launcher: (args: string[]) => Promise + suspend: (run: RunExternalProcess) => Promise +} + +export async function runExternalSetup({ args, ctx, done, launcher, suspend }: RunExternalSetupOptions) { + const { gateway, session, transcript } = ctx + + transcript.sys(`launching \`hermes ${args.join(' ')}\`…`) + patchUiState({ status: 'setup running…' }) + + let result: LaunchResult = { code: null } + + await suspend(async () => { + result = await launcher(args) + }) + + if (result.error) { + transcript.sys(`error launching hermes: ${result.error}`) + patchUiState({ status: 'setup required' }) + + return + } + + if (result.code !== 0) { + transcript.sys(`hermes ${args[0]} exited with code ${result.code}`) + patchUiState({ status: 'setup required' }) + + return + } + + const setup = await gateway.rpc('setup.status', {}) + + if (setup?.provider_configured === false) { + transcript.sys('still no provider configured') + patchUiState({ status: 'setup required' }) + + return + } + + transcript.sys(done) + session.newSession() +} diff --git a/ui-tui/src/app/slash/commands/core.ts b/ui-tui/src/app/slash/commands/core.ts new file mode 100644 index 0000000000..e0832c7a69 --- /dev/null +++ b/ui-tui/src/app/slash/commands/core.ts @@ -0,0 +1,295 @@ +import { dailyFortune, randomFortune } from '../../../content/fortunes.js' +import { HOTKEYS } from '../../../content/hotkeys.js' +import { nextDetailsMode, parseDetailsMode } from '../../../domain/details.js' +import type { ConfigGetValueResponse, ConfigSetResponse, SessionUndoResponse } from '../../../gatewayTypes.js' +import { writeOsc52Clipboard } from '../../../lib/osc52.js' +import type { DetailsMode, Msg, PanelSection } from '../../../types.js' +import { patchOverlayState } from '../../overlayStore.js' +import { patchUiState } from '../../uiStore.js' +import type { SlashCommand } from '../types.js' + +const flagFromArg = (arg: string, current: boolean): boolean | null => { + if (!arg) { + return !current + } + + const mode = arg.trim().toLowerCase() + + if (mode === 'on') { + return true + } + + if (mode === 'off') { + return false + } + + if (mode === 'toggle') { + return !current + } + + return null +} + +const DETAIL_MODES = new Set(['collapsed', 'cycle', 'expanded', 'hidden', 'toggle']) + +export const coreCommands: SlashCommand[] = [ + { + help: 'list commands + hotkeys', + name: 'help', + run: (_arg, ctx) => { + const sections: PanelSection[] = (ctx.local.catalog?.categories ?? []).map(cat => ({ + rows: cat.pairs, + title: cat.name + })) + + if (ctx.local.catalog?.skillCount) { + sections.push({ text: `${ctx.local.catalog.skillCount} skill commands available — /skills to browse` }) + } + + sections.push( + { + rows: [ + ['/details [hidden|collapsed|expanded|cycle]', 'set agent detail visibility mode'], + ['/fortune [random|daily]', 'show a random or daily local fortune'] + ], + title: 'TUI' + }, + { rows: HOTKEYS, title: 'Hotkeys' } + ) + + ctx.transcript.panel(ctx.ui.theme.brand.helpHeader, sections) + } + }, + + { + aliases: ['exit', 'q'], + help: 'exit hermes', + name: 'quit', + run: (_arg, ctx) => ctx.session.die() + }, + + { + aliases: ['new'], + help: 'start a new session', + name: 'clear', + run: (_arg, ctx, cmd) => { + if (ctx.session.guardBusySessionSwitch('switch sessions')) { + return + } + + patchUiState({ status: 'forging session…' }) + ctx.session.newSession(cmd.startsWith('/new') ? 'new session started' : undefined) + } + }, + + { + help: 'resume a prior session', + name: 'resume', + run: (arg, ctx) => { + if (ctx.session.guardBusySessionSwitch('switch sessions')) { + return + } + + arg ? ctx.session.resumeById(arg) : patchOverlayState({ picker: true }) + } + }, + + { + help: 'toggle compact transcript', + name: 'compact', + run: (arg, ctx) => { + const next = flagFromArg(arg, ctx.ui.compact) + + if (next === null) { + return ctx.transcript.sys('usage: /compact [on|off|toggle]') + } + + patchUiState({ compact: next }) + ctx.gateway.rpc('config.set', { key: 'compact', value: next ? 'on' : 'off' }).catch(() => {}) + + queueMicrotask(() => ctx.transcript.sys(`compact ${next ? 'on' : 'off'}`)) + } + }, + + { + aliases: ['detail'], + help: 'control agent detail visibility', + name: 'details', + run: (arg, ctx) => { + const { gateway, transcript, ui } = ctx + + if (!arg) { + gateway + .rpc('config.get', { key: 'details_mode' }) + .then(r => { + if (ctx.stale()) { + return + } + + const mode = parseDetailsMode(r?.value) ?? ui.detailsMode + + patchUiState({ detailsMode: mode }) + transcript.sys(`details: ${mode}`) + }) + .catch(() => { + if (!ctx.stale()) { + transcript.sys(`details: ${ui.detailsMode}`) + } + }) + + return + } + + const mode = arg.trim().toLowerCase() + + if (!DETAIL_MODES.has(mode)) { + return transcript.sys('usage: /details [hidden|collapsed|expanded|cycle]') + } + + const next = mode === 'cycle' || mode === 'toggle' ? nextDetailsMode(ui.detailsMode) : (mode as DetailsMode) + + patchUiState({ detailsMode: next }) + gateway.rpc('config.set', { key: 'details_mode', value: next }).catch(() => {}) + transcript.sys(`details: ${next}`) + } + }, + + { + help: 'local fortune', + name: 'fortune', + run: (arg, ctx) => { + const key = arg.trim().toLowerCase() + + if (!arg || key === 'random') { + return ctx.transcript.sys(randomFortune()) + } + + if (['daily', 'stable', 'today'].includes(key)) { + return ctx.transcript.sys(dailyFortune(ctx.sid)) + } + + ctx.transcript.sys('usage: /fortune [random|daily]') + } + }, + + { + help: 'copy selection or assistant message', + name: 'copy', + run: (arg, ctx) => { + const { sys } = ctx.transcript + + if (!arg && ctx.composer.hasSelection && ctx.composer.selection.copySelection()) { + return sys('copied selection') + } + + if (arg && Number.isNaN(parseInt(arg, 10))) { + return sys('usage: /copy [number]') + } + + const all = ctx.local.getHistoryItems().filter(m => m.role === 'assistant') + const target = all[arg ? Math.min(parseInt(arg, 10), all.length) - 1 : all.length - 1] + + if (!target) { + return sys('nothing to copy') + } + + writeOsc52Clipboard(target.text) + sys('sent OSC52 copy sequence (terminal support required)') + } + }, + + { + help: 'paste clipboard image', + name: 'paste', + run: (arg, ctx) => (arg ? ctx.transcript.sys('usage: /paste') : ctx.composer.paste()) + }, + + { + help: 'view gateway logs', + name: 'logs', + run: (arg, ctx) => { + const text = ctx.gateway.gw.getLogTail(Math.min(80, Math.max(1, parseInt(arg, 10) || 20))) + + text ? ctx.transcript.page(text, 'Logs') : ctx.transcript.sys('no gateway logs') + } + }, + + { + aliases: ['sb'], + help: 'toggle status bar', + name: 'statusbar', + run: (arg, ctx) => { + const next = flagFromArg(arg, ctx.ui.statusBar) + + if (next === null) { + return ctx.transcript.sys('usage: /statusbar [on|off|toggle]') + } + + patchUiState({ statusBar: next }) + ctx.gateway.rpc('config.set', { key: 'statusbar', value: next ? 'on' : 'off' }).catch(() => {}) + + queueMicrotask(() => ctx.transcript.sys(`status bar ${next ? 'on' : 'off'}`)) + } + }, + + { + help: 'inspect or enqueue a message', + name: 'queue', + run: (arg, ctx) => { + if (!arg) { + return ctx.transcript.sys(`${ctx.composer.queueRef.current.length} queued message(s)`) + } + + ctx.composer.enqueue(arg) + ctx.transcript.sys(`queued: "${arg.slice(0, 50)}${arg.length > 50 ? '…' : ''}"`) + } + }, + + { + help: 'undo last exchange', + name: 'undo', + run: (_arg, ctx) => { + if (!ctx.sid) { + return ctx.transcript.sys('nothing to undo') + } + + ctx.gateway.rpc('session.undo', { session_id: ctx.sid }).then( + ctx.guarded(r => { + if ((r.removed ?? 0) > 0) { + ctx.transcript.setHistoryItems((prev: Msg[]) => ctx.transcript.trimLastExchange(prev)) + ctx.transcript.sys(`undid ${r.removed} messages`) + } else { + ctx.transcript.sys('nothing to undo') + } + }) + ) + } + }, + + { + help: 'retry last user message', + name: 'retry', + run: (_arg, ctx) => { + const last = ctx.local.getLastUserMsg() + + if (!last) { + return ctx.transcript.sys('nothing to retry') + } + + if (!ctx.sid) { + return ctx.transcript.send(last) + } + + ctx.gateway.rpc('session.undo', { session_id: ctx.sid }).then( + ctx.guarded(r => { + if ((r.removed ?? 0) <= 0) { + return ctx.transcript.sys('nothing to retry') + } + + ctx.transcript.setHistoryItems((prev: Msg[]) => ctx.transcript.trimLastExchange(prev)) + ctx.transcript.send(last) + }) + ) + } + } +] diff --git a/ui-tui/src/app/slash/commands/ops.ts b/ui-tui/src/app/slash/commands/ops.ts new file mode 100644 index 0000000000..979e1f470a --- /dev/null +++ b/ui-tui/src/app/slash/commands/ops.ts @@ -0,0 +1,52 @@ +import type { ToolsConfigureResponse } from '../../../gatewayTypes.js' +import type { SlashCommand } from '../types.js' + +export const opsCommands: SlashCommand[] = [ + { + help: 'enable or disable tools (client-side history reset on change)', + name: 'tools', + run: (arg, ctx) => { + const [subcommand, ...names] = arg.trim().split(/\s+/).filter(Boolean) + + if (subcommand !== 'disable' && subcommand !== 'enable') { + return + } + + if (!names.length) { + ctx.transcript.sys(`usage: /tools ${subcommand} [name ...]`) + ctx.transcript.sys(`built-in toolset: /tools ${subcommand} web`) + ctx.transcript.sys(`MCP tool: /tools ${subcommand} github:create_issue`) + + return + } + + ctx.gateway + .rpc('tools.configure', { action: subcommand, names, session_id: ctx.sid }) + .then( + ctx.guarded(r => { + if (r.info) { + ctx.session.setSessionStartedAt(Date.now()) + ctx.session.resetVisibleHistory(r.info) + } + + if (r.changed?.length) { + ctx.transcript.sys(`${subcommand === 'disable' ? 'disabled' : 'enabled'}: ${r.changed.join(', ')}`) + } + + if (r.unknown?.length) { + ctx.transcript.sys(`unknown toolsets: ${r.unknown.join(', ')}`) + } + + if (r.missing_servers?.length) { + ctx.transcript.sys(`missing MCP servers: ${r.missing_servers.join(', ')}`) + } + + if (r.reset) { + ctx.transcript.sys('session reset. new tool configuration is active.') + } + }) + ) + .catch(ctx.guardedErr) + } + } +] diff --git a/ui-tui/src/app/slash/commands/session.ts b/ui-tui/src/app/slash/commands/session.ts new file mode 100644 index 0000000000..354d3c1975 --- /dev/null +++ b/ui-tui/src/app/slash/commands/session.ts @@ -0,0 +1,309 @@ +import { imageTokenMeta, introMsg, toTranscriptMessages } from '../../../domain/messages.js' +import type { + BackgroundStartResponse, + BtwStartResponse, + ConfigGetValueResponse, + ConfigSetResponse, + ImageAttachResponse, + SessionBranchResponse, + SessionCompressResponse, + SessionUsageResponse, + VoiceToggleResponse +} from '../../../gatewayTypes.js' +import { fmtK } from '../../../lib/text.js' +import type { PanelSection } from '../../../types.js' +import { patchOverlayState } from '../../overlayStore.js' +import { patchUiState } from '../../uiStore.js' +import type { SlashCommand } from '../types.js' + +export const sessionCommands: SlashCommand[] = [ + { + aliases: ['bg'], + help: 'launch a background prompt', + name: 'background', + run: (arg, ctx) => { + if (!arg) { + return ctx.transcript.sys('/background ') + } + + ctx.gateway.rpc('prompt.background', { session_id: ctx.sid, text: arg }).then( + ctx.guarded(r => { + if (!r.task_id) { + return + } + + patchUiState(state => ({ ...state, bgTasks: new Set(state.bgTasks).add(r.task_id!) })) + ctx.transcript.sys(`bg ${r.task_id} started`) + }) + ) + } + }, + + { + help: 'by-the-way follow-up', + name: 'btw', + run: (arg, ctx) => { + if (!arg) { + return ctx.transcript.sys('/btw ') + } + + ctx.gateway.rpc('prompt.btw', { session_id: ctx.sid, text: arg }).then( + ctx.guarded(() => { + patchUiState(state => ({ ...state, bgTasks: new Set(state.bgTasks).add('btw:x') })) + ctx.transcript.sys('btw running…') + }) + ) + } + }, + + { + help: 'change or show model', + name: 'model', + run: (arg, ctx) => { + if (ctx.session.guardBusySessionSwitch('change models')) { + return + } + + if (!arg) { + return patchOverlayState({ modelPicker: true }) + } + + ctx.gateway.rpc('config.set', { key: 'model', session_id: ctx.sid, value: arg.trim() }).then( + ctx.guarded(r => { + if (!r.value) { + return ctx.transcript.sys('error: invalid response: model switch') + } + + ctx.transcript.sys(`model → ${r.value}`) + ctx.local.maybeWarn(r) + + patchUiState(state => ({ + ...state, + info: state.info ? { ...state.info, model: r.value! } : { model: r.value!, skills: {}, tools: {} } + })) + }) + ) + } + }, + + { + help: 'attach an image', + name: 'image', + run: (arg, ctx) => { + ctx.gateway.rpc('image.attach', { path: arg, session_id: ctx.sid }).then( + ctx.guarded(r => { + const meta = imageTokenMeta(r) + + ctx.transcript.sys(`attached image: ${r.name ?? ''}${meta ? ` · ${meta}` : ''}`) + + if (r.remainder) { + ctx.composer.setInput(r.remainder) + } + }) + ) + } + }, + + { + help: 'switch or reset personality (history reset on set)', + name: 'personality', + run: (arg, ctx) => { + if (!arg) { + return + } + + ctx.gateway.rpc('config.set', { key: 'personality', session_id: ctx.sid, value: arg }).then( + ctx.guarded(r => { + if (r.history_reset) { + ctx.session.resetVisibleHistory(r.info ?? null) + } + + ctx.transcript.sys(`personality: ${r.value || 'default'}${r.history_reset ? ' · transcript cleared' : ''}`) + ctx.local.maybeWarn(r) + }) + ) + } + }, + + { + help: 'compress transcript', + name: 'compress', + run: (arg, ctx) => { + ctx.gateway + .rpc('session.compress', { + session_id: ctx.sid, + ...(arg ? { focus_topic: arg } : {}) + }) + .then( + ctx.guarded(r => { + if (Array.isArray(r.messages)) { + const rows = toTranscriptMessages(r.messages) + + ctx.transcript.setHistoryItems(r.info ? [introMsg(r.info), ...rows] : rows) + } + + if (r.info) { + patchUiState({ info: r.info }) + } + + if (r.usage) { + patchUiState(state => ({ ...state, usage: { ...state.usage, ...r.usage } })) + } + + if ((r.removed ?? 0) <= 0) { + return ctx.transcript.sys('nothing to compress') + } + + ctx.transcript.sys( + `compressed ${r.removed} messages${r.usage?.total ? ` · ${fmtK(r.usage.total)} tok` : ''}` + ) + }) + ) + } + }, + + { + aliases: ['fork'], + help: 'branch the session', + name: 'branch', + run: (arg, ctx) => { + const prevSid = ctx.sid + + ctx.gateway.rpc('session.branch', { name: arg, session_id: ctx.sid }).then( + ctx.guarded(r => { + if (!r.session_id) { + return + } + + void ctx.session.closeSession(prevSid) + patchUiState({ sid: r.session_id }) + ctx.session.setSessionStartedAt(Date.now()) + ctx.transcript.setHistoryItems([]) + ctx.transcript.sys(`branched → ${r.title ?? ''}`) + }) + ) + } + }, + + { + help: 'toggle voice input', + name: 'voice', + run: (arg, ctx) => { + const action = arg === 'on' || arg === 'off' ? arg : 'status' + + ctx.gateway.rpc('voice.toggle', { action }).then( + ctx.guarded(r => { + ctx.voice.setVoiceEnabled(!!r.enabled) + ctx.transcript.sys(`voice: ${r.enabled ? 'on' : 'off'}`) + }) + ) + } + }, + + { + help: 'switch theme skin (fires skin.changed)', + name: 'skin', + run: (arg, ctx) => { + if (!arg) { + return ctx.gateway + .rpc('config.get', { key: 'skin' }) + .then(ctx.guarded(r => ctx.transcript.sys(`skin: ${r.value || 'default'}`))) + } + + ctx.gateway + .rpc('config.set', { key: 'skin', value: arg }) + .then(ctx.guarded(r => r.value && ctx.transcript.sys(`skin → ${r.value}`))) + } + }, + + { + help: 'toggle yolo mode (per-session approvals)', + name: 'yolo', + run: (_arg, ctx) => { + ctx.gateway + .rpc('config.set', { key: 'yolo', session_id: ctx.sid }) + .then(ctx.guarded(r => ctx.transcript.sys(`yolo ${r.value === '1' ? 'on' : 'off'}`))) + } + }, + + { + help: 'inspect or set reasoning effort (updates live agent)', + name: 'reasoning', + run: (arg, ctx) => { + if (!arg) { + return ctx.gateway + .rpc('config.get', { key: 'reasoning' }) + .then( + ctx.guarded( + r => r.value && ctx.transcript.sys(`reasoning: ${r.value} · display ${r.display || 'hide'}`) + ) + ) + } + + ctx.gateway + .rpc('config.set', { key: 'reasoning', session_id: ctx.sid, value: arg }) + .then(ctx.guarded(r => r.value && ctx.transcript.sys(`reasoning: ${r.value}`))) + } + }, + + { + help: 'cycle verbose tool-output mode (updates live agent)', + name: 'verbose', + run: (arg, ctx) => { + ctx.gateway + .rpc('config.set', { key: 'verbose', session_id: ctx.sid, value: arg || 'cycle' }) + .then(ctx.guarded(r => r.value && ctx.transcript.sys(`verbose: ${r.value}`))) + } + }, + + { + help: 'session usage (live counts — worker sees zeros)', + name: 'usage', + run: (_arg, ctx) => { + ctx.gateway.rpc('session.usage', { session_id: ctx.sid }).then(r => { + if (ctx.stale()) { + return + } + + if (r) { + patchUiState({ + usage: { calls: r.calls ?? 0, input: r.input ?? 0, output: r.output ?? 0, total: r.total ?? 0 } + }) + } + + if (!r?.calls) { + return ctx.transcript.sys('no API calls yet') + } + + const f = (v: number | undefined) => (v ?? 0).toLocaleString() + const cost = r.cost_usd != null ? `${r.cost_status === 'estimated' ? '~' : ''}$${r.cost_usd.toFixed(4)}` : null + + const rows: [string, string][] = [ + ['Model', r.model ?? ''], + ['Input tokens', f(r.input)], + ['Cache read tokens', f(r.cache_read)], + ['Cache write tokens', f(r.cache_write)], + ['Output tokens', f(r.output)], + ['Total tokens', f(r.total)], + ['API calls', f(r.calls)] + ] + + if (cost) { + rows.push(['Cost', cost]) + } + + const sections: PanelSection[] = [{ rows }] + + if (r.context_max) { + sections.push({ text: `Context: ${f(r.context_used)} / ${f(r.context_max)} (${r.context_percent}%)` }) + } + + if (r.compressions) { + sections.push({ text: `Compressions: ${r.compressions}` }) + } + + ctx.transcript.panel('Usage', sections) + }) + } + } +] diff --git a/ui-tui/src/app/slash/commands/setup.ts b/ui-tui/src/app/slash/commands/setup.ts new file mode 100644 index 0000000000..c6d5cc8637 --- /dev/null +++ b/ui-tui/src/app/slash/commands/setup.ts @@ -0,0 +1,33 @@ +import { withInkSuspended } from '@hermes/ink' + +import { launchHermesCommand } from '../../../lib/externalCli.js' +import { runExternalSetup } from '../../setupHandoff.js' +import type { SlashCommand } from '../types.js' + +export const setupCommands: SlashCommand[] = [ + { + aliases: ['provider'], + help: 'configure LLM provider and model (launches `hermes model`)', + name: 'model', + run: (_arg, ctx) => + void runExternalSetup({ + args: ['model'], + ctx, + done: 'provider updated — starting session…', + launcher: launchHermesCommand, + suspend: withInkSuspended + }) + }, + { + help: 'run full setup wizard (launches `hermes setup`)', + name: 'setup', + run: (arg, ctx) => + void runExternalSetup({ + args: ['setup', ...arg.split(/\s+/).filter(Boolean)], + ctx, + done: 'setup complete — starting session…', + launcher: launchHermesCommand, + suspend: withInkSuspended + }) + } +] diff --git a/ui-tui/src/app/slash/registry.ts b/ui-tui/src/app/slash/registry.ts new file mode 100644 index 0000000000..ae7d7d50be --- /dev/null +++ b/ui-tui/src/app/slash/registry.ts @@ -0,0 +1,13 @@ +import { coreCommands } from './commands/core.js' +import { opsCommands } from './commands/ops.js' +import { sessionCommands } from './commands/session.js' +import { setupCommands } from './commands/setup.js' +import type { SlashCommand } from './types.js' + +export const SLASH_COMMANDS: SlashCommand[] = [...coreCommands, ...sessionCommands, ...opsCommands, ...setupCommands] + +const byName = new Map( + SLASH_COMMANDS.flatMap(cmd => [cmd.name, ...(cmd.aliases ?? [])].map(name => [name, cmd] as const)) +) + +export const findSlashCommand = (name: string) => byName.get(name.toLowerCase()) diff --git a/ui-tui/src/app/slash/types.ts b/ui-tui/src/app/slash/types.ts new file mode 100644 index 0000000000..bbd187a23b --- /dev/null +++ b/ui-tui/src/app/slash/types.ts @@ -0,0 +1,21 @@ +import type { MutableRefObject } from 'react' + +import type { SlashHandlerContext, UiState } from '../interfaces.js' + +export interface SlashRunCtx extends SlashHandlerContext { + flight: number + guarded: (fn: (r: T) => void) => (r: null | T) => void + guardedErr: (e: unknown) => void + sid: null | string + slashFlightRef: MutableRefObject + stale: () => boolean + ui: UiState +} + +export interface SlashCommand { + aliases?: string[] + help?: string + name: string + run: (arg: string, ctx: SlashRunCtx, cmd: string) => void + usage?: string +} diff --git a/ui-tui/src/app/turnController.ts b/ui-tui/src/app/turnController.ts new file mode 100644 index 0000000000..73d0571734 --- /dev/null +++ b/ui-tui/src/app/turnController.ts @@ -0,0 +1,397 @@ +import { REASONING_PULSE_MS, STREAM_BATCH_MS } from '../config/timing.js' +import type { SessionInterruptResponse, SubagentEventPayload } from '../gatewayTypes.js' +import { + buildToolTrailLine, + estimateTokensRough, + isTransientTrailLine, + sameToolTrailGroup, + toolTrailLabel +} from '../lib/text.js' +import type { ActiveTool, ActivityItem, Msg, SubagentProgress } from '../types.js' + +import { resetOverlayState } from './overlayStore.js' +import { patchTurnState, resetTurnState } from './turnStore.js' +import { patchUiState } from './uiStore.js' + +const INTERRUPT_COOLDOWN_MS = 1500 +const ACTIVITY_LIMIT = 8 +const TRAIL_LIMIT = 8 + +export interface InterruptDeps { + appendMessage: (msg: Msg) => void + gw: { request: (method: string, params?: Record) => Promise } + sid: string + sys: (text: string) => void +} + +type Timer = null | ReturnType + +const clear = (t: Timer): null => { + if (t) { + clearTimeout(t) + } + + return null +} + +class TurnController { + bufRef = '' + interrupted = false + lastStatusNote = '' + persistedToolLabels = new Set() + protocolWarned = false + reasoningText = '' + segmentMessages: Msg[] = [] + pendingSegmentTools: string[] = [] + statusTimer: Timer = null + toolTokenAcc = 0 + turnTools: string[] = [] + + private activeTools: ActiveTool[] = [] + private activityId = 0 + private reasoningStreamingTimer: Timer = null + private reasoningTimer: Timer = null + private streamTimer: Timer = null + private toolProgressTimer: Timer = null + + clearReasoning() { + this.reasoningTimer = clear(this.reasoningTimer) + this.reasoningText = '' + this.toolTokenAcc = 0 + patchTurnState({ reasoning: '', reasoningTokens: 0, toolTokens: 0 }) + } + + clearStatusTimer() { + this.statusTimer = clear(this.statusTimer) + } + + endReasoningPhase() { + this.reasoningStreamingTimer = clear(this.reasoningStreamingTimer) + patchTurnState({ reasoningActive: false, reasoningStreaming: false }) + } + + idle() { + this.endReasoningPhase() + this.activeTools = [] + this.streamTimer = clear(this.streamTimer) + this.bufRef = '' + this.pendingSegmentTools = [] + this.segmentMessages = [] + + patchTurnState({ + streamPendingTools: [], + streamSegments: [], + streaming: '', + subagents: [], + tools: [], + turnTrail: [] + }) + patchUiState({ busy: false }) + resetOverlayState() + } + + interruptTurn({ appendMessage, gw, sid, sys }: InterruptDeps) { + this.interrupted = true + gw.request('session.interrupt', { session_id: sid }).catch(() => {}) + + const partial = this.bufRef.trimStart() + + partial ? appendMessage({ role: 'assistant', text: `${partial}\n\n*[interrupted]*` }) : sys('interrupted') + + this.idle() + this.clearReasoning() + this.turnTools = [] + patchTurnState({ activity: [], outcome: '' }) + patchUiState({ status: 'interrupted' }) + this.clearStatusTimer() + + this.statusTimer = setTimeout(() => { + this.statusTimer = null + patchUiState({ status: 'ready' }) + }, INTERRUPT_COOLDOWN_MS) + } + + pruneTransient() { + this.turnTools = this.turnTools.filter(line => !isTransientTrailLine(line)) + patchTurnState(state => { + const next = state.turnTrail.filter(line => !isTransientTrailLine(line)) + + return next.length === state.turnTrail.length ? state : { ...state, turnTrail: next } + }) + } + + flushStreamingSegment() { + const text = this.bufRef.trimStart() + + if (!text) { + return + } + + const tools = this.pendingSegmentTools + + this.streamTimer = clear(this.streamTimer) + this.segmentMessages = [...this.segmentMessages, { role: 'assistant', text, ...(tools.length && { tools }) }] + this.bufRef = '' + this.pendingSegmentTools = [] + patchTurnState({ streamPendingTools: [], streamSegments: this.segmentMessages, streaming: '' }) + } + + pulseReasoningStreaming() { + this.reasoningStreamingTimer = clear(this.reasoningStreamingTimer) + patchTurnState({ reasoningActive: true, reasoningStreaming: true }) + + this.reasoningStreamingTimer = setTimeout(() => { + this.reasoningStreamingTimer = null + patchTurnState({ reasoningStreaming: false }) + }, REASONING_PULSE_MS) + } + + pushActivity(text: string, tone: ActivityItem['tone'] = 'info', replaceLabel?: string) { + patchTurnState(state => { + const base = replaceLabel + ? state.activity.filter(item => !sameToolTrailGroup(replaceLabel, item.text)) + : state.activity + + const tail = base.at(-1) + + if (tail?.text === text && tail.tone === tone) { + return state + } + + return { ...state, activity: [...base, { id: ++this.activityId, text, tone }].slice(-ACTIVITY_LIMIT) } + }) + } + + pushTrail(line: string) { + patchTurnState(state => { + if (state.turnTrail.at(-1) === line) { + return state + } + + const next = [...state.turnTrail.filter(item => !isTransientTrailLine(item)), line].slice(-TRAIL_LIMIT) + + this.turnTools = next + + return { ...state, turnTrail: next } + }) + } + + recordError() { + this.idle() + this.clearReasoning() + this.clearStatusTimer() + this.pendingSegmentTools = [] + this.segmentMessages = [] + this.turnTools = [] + this.persistedToolLabels.clear() + } + + recordMessageComplete(payload: { rendered?: string; reasoning?: string; text?: string }) { + const finalText = (payload.rendered ?? payload.text ?? this.bufRef).trimStart() + const savedReasoning = this.reasoningText.trim() || String(payload.reasoning ?? '').trim() + const savedReasoningTokens = savedReasoning ? estimateTokensRough(savedReasoning) : 0 + const savedToolTokens = this.toolTokenAcc + const tools = this.pendingSegmentTools + const finalMessages = [...this.segmentMessages] + + if (finalText) { + finalMessages.push({ + role: 'assistant', + text: finalText, + thinking: savedReasoning || undefined, + thinkingTokens: savedReasoning ? savedReasoningTokens : undefined, + toolTokens: savedToolTokens || undefined, + ...(tools.length && { tools }) + }) + } + + const wasInterrupted = this.interrupted + + this.idle() + this.clearReasoning() + this.turnTools = [] + this.persistedToolLabels.clear() + this.bufRef = '' + patchTurnState({ activity: [], outcome: '' }) + + return { finalMessages, finalText, wasInterrupted } + } + + recordMessageDelta({ rendered, text }: { rendered?: string; text?: string }) { + this.pruneTransient() + this.endReasoningPhase() + + if (!text || this.interrupted) { + return + } + + this.bufRef = rendered ?? this.bufRef + text + this.scheduleStreaming() + } + + recordReasoningAvailable(text: string) { + const incoming = text.trim() + + if (!incoming || this.reasoningText.trim()) { + return + } + + this.reasoningText = incoming + this.scheduleReasoning() + this.pulseReasoningStreaming() + } + + recordReasoningDelta(text: string) { + this.reasoningText += text + this.scheduleReasoning() + this.pulseReasoningStreaming() + } + + recordToolComplete(toolId: string, fallbackName?: string, error?: string, summary?: string) { + const done = this.activeTools.find(tool => tool.id === toolId) + const name = done?.name ?? fallbackName ?? 'tool' + const label = toolTrailLabel(name) + const line = buildToolTrailLine(name, done?.context || '', Boolean(error), error || summary || '') + + this.activeTools = this.activeTools.filter(tool => tool.id !== toolId) + this.pendingSegmentTools = [...this.pendingSegmentTools, line] + + const next = this.turnTools.filter(item => !sameToolTrailGroup(label, item)) + + if (!this.activeTools.length) { + next.push('analyzing tool output…') + } + + this.turnTools = next.slice(-TRAIL_LIMIT) + patchTurnState({ + streamPendingTools: this.pendingSegmentTools, + tools: this.activeTools, + turnTrail: this.turnTools + }) + } + + recordToolProgress(toolName: string, preview: string) { + const index = this.activeTools.findIndex(tool => tool.name === toolName) + + if (index < 0) { + return + } + + this.activeTools = this.activeTools.map((tool, i) => (i === index ? { ...tool, context: preview } : tool)) + + if (this.toolProgressTimer) { + return + } + + this.toolProgressTimer = setTimeout(() => { + this.toolProgressTimer = null + patchTurnState({ tools: [...this.activeTools] }) + }, STREAM_BATCH_MS) + } + + recordToolStart(toolId: string, name: string, context: string) { + this.flushStreamingSegment() + this.pruneTransient() + this.endReasoningPhase() + + const sample = `${name} ${context}`.trim() + + this.toolTokenAcc += sample ? estimateTokensRough(sample) : 0 + this.activeTools = [...this.activeTools, { context, id: toolId, name, startedAt: Date.now() }] + + patchTurnState({ toolTokens: this.toolTokenAcc, tools: this.activeTools }) + } + + reset() { + this.clearReasoning() + this.clearStatusTimer() + this.idle() + this.bufRef = '' + this.interrupted = false + this.lastStatusNote = '' + this.pendingSegmentTools = [] + this.protocolWarned = false + this.segmentMessages = [] + this.turnTools = [] + this.toolTokenAcc = 0 + this.persistedToolLabels.clear() + patchTurnState({ activity: [], outcome: '' }) + } + + fullReset() { + this.reset() + resetTurnState() + } + + scheduleReasoning() { + if (this.reasoningTimer) { + return + } + + this.reasoningTimer = setTimeout(() => { + this.reasoningTimer = null + patchTurnState({ + reasoning: this.reasoningText, + reasoningTokens: estimateTokensRough(this.reasoningText) + }) + }, STREAM_BATCH_MS) + } + + scheduleStreaming() { + if (this.streamTimer) { + return + } + + this.streamTimer = setTimeout(() => { + this.streamTimer = null + patchTurnState({ streaming: this.bufRef.trimStart() }) + }, STREAM_BATCH_MS) + } + + startMessage() { + this.endReasoningPhase() + this.clearReasoning() + this.activeTools = [] + this.turnTools = [] + this.toolTokenAcc = 0 + this.persistedToolLabels.clear() + patchUiState({ busy: true }) + patchTurnState({ activity: [], outcome: '', subagents: [], toolTokens: 0, tools: [], turnTrail: [] }) + } + + upsertSubagent(p: SubagentEventPayload, patch: (current: SubagentProgress) => Partial) { + const id = `sa:${p.task_index}:${p.goal || 'subagent'}` + + patchTurnState(state => { + const existing = state.subagents.find(item => item.id === id) + + const base: SubagentProgress = existing ?? { + goal: p.goal, + id, + index: p.task_index, + notes: [], + status: 'running', + taskCount: p.task_count ?? 1, + thinking: [], + tools: [] + } + + const next: SubagentProgress = { + ...base, + goal: p.goal || base.goal, + taskCount: p.task_count ?? base.taskCount, + ...patch(base) + } + + const subagents = existing + ? state.subagents.map(item => (item.id === id ? next : item)) + : [...state.subagents, next].sort((a, b) => a.index - b.index) + + return { ...state, subagents } + }) + } +} + +export const turnController = new TurnController() + +export type { TurnController } diff --git a/ui-tui/src/app/turnStore.ts b/ui-tui/src/app/turnStore.ts new file mode 100644 index 0000000000..148a50c196 --- /dev/null +++ b/ui-tui/src/app/turnStore.ts @@ -0,0 +1,44 @@ +import { atom } from 'nanostores' + +import type { ActiveTool, ActivityItem, Msg, SubagentProgress } from '../types.js' + +const buildTurnState = (): TurnState => ({ + activity: [], + outcome: '', + reasoning: '', + reasoningActive: false, + reasoningStreaming: false, + reasoningTokens: 0, + streamPendingTools: [], + streamSegments: [], + streaming: '', + subagents: [], + toolTokens: 0, + tools: [], + turnTrail: [] +}) + +export const $turnState = atom(buildTurnState()) + +export const getTurnState = () => $turnState.get() + +export const patchTurnState = (next: Partial | ((state: TurnState) => TurnState)) => + $turnState.set(typeof next === 'function' ? next($turnState.get()) : { ...$turnState.get(), ...next }) + +export const resetTurnState = () => $turnState.set(buildTurnState()) + +export interface TurnState { + activity: ActivityItem[] + outcome: string + reasoning: string + reasoningActive: boolean + reasoningStreaming: boolean + reasoningTokens: number + streamPendingTools: string[] + streamSegments: Msg[] + streaming: string + subagents: SubagentProgress[] + toolTokens: number + tools: ActiveTool[] + turnTrail: string[] +} diff --git a/ui-tui/src/app/uiStore.ts b/ui-tui/src/app/uiStore.ts new file mode 100644 index 0000000000..b7f5c20f4d --- /dev/null +++ b/ui-tui/src/app/uiStore.ts @@ -0,0 +1,28 @@ +import { atom } from 'nanostores' + +import { ZERO } from '../domain/usage.js' +import { DEFAULT_THEME } from '../theme.js' + +import type { UiState } from './interfaces.js' + +const buildUiState = (): UiState => ({ + bgTasks: new Set(), + busy: false, + compact: false, + detailsMode: 'collapsed', + info: null, + sid: null, + status: 'summoning hermes…', + statusBar: true, + theme: DEFAULT_THEME, + usage: ZERO +}) + +export const $uiState = atom(buildUiState()) + +export const getUiState = () => $uiState.get() + +export const patchUiState = (next: Partial | ((state: UiState) => UiState)) => + $uiState.set(typeof next === 'function' ? next($uiState.get()) : { ...$uiState.get(), ...next }) + +export const resetUiState = () => $uiState.set(buildUiState()) diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.ts new file mode 100644 index 0000000000..14a40412c9 --- /dev/null +++ b/ui-tui/src/app/useComposerState.ts @@ -0,0 +1,166 @@ +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { useStore } from '@nanostores/react' +import { useCallback, useMemo, useState } from 'react' + +import type { PasteEvent } from '../components/textInput.js' +import { LARGE_PASTE } from '../config/limits.js' +import { useCompletion } from '../hooks/useCompletion.js' +import { useInputHistory } from '../hooks/useInputHistory.js' +import { useQueue } from '../hooks/useQueue.js' +import { pasteTokenLabel, stripTrailingPasteNewlines } from '../lib/text.js' + +import type { PasteSnippet, UseComposerStateOptions, UseComposerStateResult } from './interfaces.js' +import { $isBlocked } from './overlayStore.js' + +export function useComposerState({ gw, onClipboardPaste, submitRef }: UseComposerStateOptions): UseComposerStateResult { + const [input, setInput] = useState('') + const [inputBuf, setInputBuf] = useState([]) + const [pasteSnips, setPasteSnips] = useState([]) + const isBlocked = useStore($isBlocked) + + const { queueRef, queueEditRef, queuedDisplay, queueEditIdx, enqueue, dequeue, replaceQ, setQueueEdit, syncQueue } = + useQueue() + + const { historyRef, historyIdx, setHistoryIdx, historyDraftRef, pushHistory } = useInputHistory() + const { completions, compIdx, setCompIdx, compReplace } = useCompletion(input, isBlocked, gw) + + const clearIn = useCallback(() => { + setInput('') + setInputBuf([]) + setQueueEdit(null) + setHistoryIdx(null) + historyDraftRef.current = '' + }, [historyDraftRef, setQueueEdit, setHistoryIdx]) + + const handleTextPaste = useCallback( + ({ bracketed, cursor, hotkey, text, value }: PasteEvent) => { + if (hotkey) { + void onClipboardPaste(false) + + return null + } + + const cleanedText = stripTrailingPasteNewlines(text) + + if (!cleanedText || !/[^\n]/.test(cleanedText)) { + if (bracketed) { + void onClipboardPaste(true) + } + + return null + } + + const lineCount = cleanedText.split('\n').length + + if (cleanedText.length < LARGE_PASTE.chars && lineCount < LARGE_PASTE.lines) { + return { + cursor: cursor + cleanedText.length, + value: value.slice(0, cursor) + cleanedText + value.slice(cursor) + } + } + + const label = pasteTokenLabel(cleanedText, lineCount) + const lead = cursor > 0 && !/\s/.test(value[cursor - 1] ?? '') ? ' ' : '' + const tail = cursor < value.length && !/\s/.test(value[cursor] ?? '') ? ' ' : '' + const insert = `${lead}${label}${tail}` + + setPasteSnips(prev => [...prev, { label, text: cleanedText }].slice(-32)) + + return { + cursor: cursor + insert.length, + value: value.slice(0, cursor) + insert + value.slice(cursor) + } + }, + [onClipboardPaste] + ) + + const openEditor = useCallback(() => { + const editor = process.env.EDITOR || process.env.VISUAL || 'vi' + const file = join(mkdtempSync(join(tmpdir(), 'hermes-')), 'prompt.md') + + writeFileSync(file, [...inputBuf, input].join('\n')) + process.stdout.write('\x1b[?1049l') + const { status: code } = spawnSync(editor, [file], { stdio: 'inherit' }) + process.stdout.write('\x1b[?1049h\x1b[2J\x1b[H') + + if (code === 0) { + const text = readFileSync(file, 'utf8').trimEnd() + + if (text) { + setInput('') + setInputBuf([]) + submitRef.current(text) + } + } + + rmSync(file, { force: true }) + }, [input, inputBuf, submitRef]) + + const actions = useMemo( + () => ({ + clearIn, + dequeue, + enqueue, + handleTextPaste, + openEditor, + pushHistory, + replaceQueue: replaceQ, + setCompIdx, + setHistoryIdx, + setInput, + setInputBuf, + setPasteSnips, + setQueueEdit, + syncQueue + }), + [ + clearIn, + dequeue, + enqueue, + handleTextPaste, + openEditor, + pushHistory, + replaceQ, + setCompIdx, + setHistoryIdx, + setQueueEdit, + syncQueue + ] + ) + + const refs = useMemo( + () => ({ + historyDraftRef, + historyRef, + queueEditRef, + queueRef, + submitRef + }), + [historyDraftRef, historyRef, queueEditRef, queueRef, submitRef] + ) + + const state = useMemo( + () => ({ + compIdx, + compReplace, + completions, + historyIdx, + input, + inputBuf, + pasteSnips, + queueEditIdx, + queuedDisplay + }), + [compIdx, compReplace, completions, historyIdx, input, inputBuf, pasteSnips, queueEditIdx, queuedDisplay] + ) + + return { + actions, + refs, + state + } +} diff --git a/ui-tui/src/app/useConfigSync.ts b/ui-tui/src/app/useConfigSync.ts new file mode 100644 index 0000000000..fe3cec5737 --- /dev/null +++ b/ui-tui/src/app/useConfigSync.ts @@ -0,0 +1,95 @@ +import { useEffect, useRef } from 'react' + +import { resolveDetailsMode } from '../domain/details.js' +import type { GatewayClient } from '../gatewayClient.js' +import type { + ConfigFullResponse, + ConfigMtimeResponse, + ReloadMcpResponse, + VoiceToggleResponse +} from '../gatewayTypes.js' +import { asRpcResult } from '../lib/rpc.js' + +import { turnController } from './turnController.js' +import { patchUiState } from './uiStore.js' + +const MTIME_POLL_MS = 5000 + +const quietRpc = async = Record>( + gw: GatewayClient, + method: string, + params: Record = {} +): Promise => { + try { + return asRpcResult(await gw.request(method, params)) + } catch { + return null + } +} + +const applyDisplay = (cfg: ConfigFullResponse | null, setBell: (v: boolean) => void) => { + const d = cfg?.config?.display ?? {} + + setBell(!!d.bell_on_complete) + patchUiState({ + compact: !!d.tui_compact, + detailsMode: resolveDetailsMode(d), + statusBar: d.tui_statusbar !== false + }) +} + +export function useConfigSync({ gw, setBellOnComplete, setVoiceEnabled, sid }: UseConfigSyncOptions) { + const mtimeRef = useRef(0) + + useEffect(() => { + if (!sid) { + return + } + + quietRpc(gw, 'voice.toggle', { action: 'status' }).then(r => setVoiceEnabled(!!r?.enabled)) + quietRpc(gw, 'config.get', { key: 'mtime' }).then(r => { + mtimeRef.current = Number(r?.mtime ?? 0) + }) + quietRpc(gw, 'config.get', { key: 'full' }).then(r => applyDisplay(r, setBellOnComplete)) + }, [gw, setBellOnComplete, setVoiceEnabled, sid]) + + useEffect(() => { + if (!sid) { + return + } + + const id = setInterval(() => { + quietRpc(gw, 'config.get', { key: 'mtime' }).then(r => { + const next = Number(r?.mtime ?? 0) + + if (!mtimeRef.current) { + if (next) { + mtimeRef.current = next + } + + return + } + + if (!next || next === mtimeRef.current) { + return + } + + mtimeRef.current = next + + quietRpc(gw, 'reload.mcp', { session_id: sid }).then( + r => r && turnController.pushActivity('MCP reloaded after config change') + ) + quietRpc(gw, 'config.get', { key: 'full' }).then(r => applyDisplay(r, setBellOnComplete)) + }) + }, MTIME_POLL_MS) + + return () => clearInterval(id) + }, [gw, setBellOnComplete, sid]) +} + +export interface UseConfigSyncOptions { + gw: GatewayClient + setBellOnComplete: (v: boolean) => void + setVoiceEnabled: (v: boolean) => void + sid: null | string +} diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.ts new file mode 100644 index 0000000000..70000b73c8 --- /dev/null +++ b/ui-tui/src/app/useInputHandlers.ts @@ -0,0 +1,310 @@ +import { useInput } from '@hermes/ink' +import { useStore } from '@nanostores/react' + +import type { + ApprovalRespondResponse, + SecretRespondResponse, + SudoRespondResponse, + VoiceRecordResponse +} from '../gatewayTypes.js' + +import type { InputHandlerContext, InputHandlerResult } from './interfaces.js' +import { $isBlocked, $overlayState, patchOverlayState } from './overlayStore.js' +import { turnController } from './turnController.js' +import { patchTurnState } from './turnStore.js' +import { getUiState, patchUiState } from './uiStore.js' + +const isCtrl = (key: { ctrl: boolean }, ch: string, target: string) => key.ctrl && ch.toLowerCase() === target + +export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult { + const { actions, composer, gateway, terminal, voice, wheelStep } = ctx + const { actions: cActions, refs: cRefs, state: cState } = composer + + const overlay = useStore($overlayState) + const isBlocked = useStore($isBlocked) + const pagerPageSize = Math.max(5, (terminal.stdout?.rows ?? 24) - 6) + + const copySelection = () => { + const text = terminal.selection.copySelection() + + if (text) { + actions.sys(`copied ${text.length} chars`) + } + } + + const clearSelection = () => { + terminal.selection.clearSelection() + } + + const cancelOverlayFromCtrlC = () => { + if (overlay.clarify) { + return actions.answerClarify('') + } + + if (overlay.approval) { + return gateway + .rpc('approval.respond', { choice: 'deny', session_id: getUiState().sid }) + .then(r => r && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' }))) + } + + if (overlay.sudo) { + return gateway + .rpc('sudo.respond', { password: '', request_id: overlay.sudo.requestId }) + .then(r => r && (patchOverlayState({ sudo: null }), actions.sys('sudo cancelled'))) + } + + if (overlay.secret) { + return gateway + .rpc('secret.respond', { request_id: overlay.secret.requestId, value: '' }) + .then(r => r && (patchOverlayState({ secret: null }), actions.sys('secret entry cancelled'))) + } + + if (overlay.modelPicker) { + return patchOverlayState({ modelPicker: false }) + } + + if (overlay.picker) { + return patchOverlayState({ picker: false }) + } + } + + const cycleQueue = (dir: 1 | -1) => { + const len = cRefs.queueRef.current.length + + if (!len) { + return false + } + + const index = cState.queueEditIdx === null ? (dir > 0 ? 0 : len - 1) : (cState.queueEditIdx + dir + len) % len + + cActions.setQueueEdit(index) + cActions.setHistoryIdx(null) + cActions.setInput(cRefs.queueRef.current[index] ?? '') + + return true + } + + const cycleHistory = (dir: 1 | -1) => { + const h = cRefs.historyRef.current + const cur = cState.historyIdx + + if (dir < 0) { + if (!h.length) { + return + } + + if (cur === null) { + cRefs.historyDraftRef.current = cState.input + } + + const index = cur === null ? h.length - 1 : Math.max(0, cur - 1) + + cActions.setHistoryIdx(index) + cActions.setQueueEdit(null) + cActions.setInput(h[index] ?? '') + + return + } + + if (cur === null) { + return + } + + const next = cur + 1 + + if (next >= h.length) { + cActions.setHistoryIdx(null) + cActions.setInput(cRefs.historyDraftRef.current) + } else { + cActions.setHistoryIdx(next) + cActions.setInput(h[next] ?? '') + } + } + + const voiceStop = () => { + voice.setRecording(false) + voice.setProcessing(true) + + gateway + .rpc('voice.record', { action: 'stop' }) + .then(r => { + if (!r) { + return + } + + const transcript = String(r.text || '').trim() + + if (!transcript) { + return actions.sys('voice: no speech detected') + } + + cActions.setInput(prev => (prev ? `${prev}${/\s$/.test(prev) ? '' : ' '}${transcript}` : transcript)) + }) + .catch((e: Error) => actions.sys(`voice error: ${e.message}`)) + .finally(() => { + voice.setProcessing(false) + patchUiState({ status: 'ready' }) + }) + } + + const voiceStart = () => + gateway + .rpc('voice.record', { action: 'start' }) + .then(r => { + if (!r) { + return + } + + voice.setRecording(true) + patchUiState({ status: 'recording…' }) + }) + .catch((e: Error) => actions.sys(`voice error: ${e.message}`)) + + useInput((ch, key) => { + const live = getUiState() + + if (isBlocked) { + if (overlay.pager) { + if (key.return || ch === ' ') { + const nextOffset = overlay.pager.offset + pagerPageSize + + patchOverlayState({ + pager: nextOffset >= overlay.pager.lines.length ? null : { ...overlay.pager, offset: nextOffset } + }) + } else if (key.escape || isCtrl(key, ch, 'c') || ch === 'q') { + patchOverlayState({ pager: null }) + } + + return + } + + if (isCtrl(key, ch, 'c')) { + cancelOverlayFromCtrlC() + } else if (key.escape && overlay.picker) { + patchOverlayState({ picker: false }) + } + + return + } + + if (cState.completions.length && cState.input && cState.historyIdx === null && (key.upArrow || key.downArrow)) { + const len = cState.completions.length + + cActions.setCompIdx(i => (key.upArrow ? (i - 1 + len) % len : (i + 1) % len)) + + return + } + + if (key.wheelUp) { + return terminal.scrollWithSelection(-wheelStep) + } + + if (key.wheelDown) { + return terminal.scrollWithSelection(wheelStep) + } + + if (key.shift && key.upArrow) { + return terminal.scrollWithSelection(-1) + } + + if (key.shift && key.downArrow) { + return terminal.scrollWithSelection(1) + } + + if (key.pageUp || key.pageDown) { + const viewport = terminal.scrollRef.current?.getViewportHeight() ?? Math.max(6, (terminal.stdout?.rows ?? 24) - 8) + const step = Math.max(4, viewport - 2) + + return terminal.scrollWithSelection(key.pageUp ? -step : step) + } + + if (key.ctrl && key.shift && ch.toLowerCase() === 'c') { + return copySelection() + } + + if (key.escape && terminal.hasSelection) { + return clearSelection() + } + + if (key.upArrow && !cState.inputBuf.length) { + cycleQueue(1) || cycleHistory(-1) + + return + } + + if (key.downArrow && !cState.inputBuf.length) { + cycleQueue(-1) || cycleHistory(1) + + return + } + + if (isCtrl(key, ch, 'c')) { + if (terminal.hasSelection) { + return copySelection() + } + + if (live.busy && live.sid) { + return turnController.interruptTurn({ + appendMessage: actions.appendMessage, + gw: gateway.gw, + sid: live.sid, + sys: actions.sys + }) + } + + if (cState.input || cState.inputBuf.length) { + return cActions.clearIn() + } + + return actions.die() + } + + if (isCtrl(key, ch, 'd')) { + return actions.die() + } + + if (isCtrl(key, ch, 'l')) { + if (actions.guardBusySessionSwitch()) { + return + } + + patchUiState({ status: 'forging session…' }) + + return actions.newSession() + } + + if (isCtrl(key, ch, 'b')) { + return voice.recording ? voiceStop() : voiceStart() + } + + if (isCtrl(key, ch, 'g')) { + return cActions.openEditor() + } + + if (key.tab && cState.completions.length) { + const row = cState.completions[cState.compIdx] + + if (row?.text) { + const text = + cState.input.startsWith('/') && row.text.startsWith('/') && cState.compReplace > 0 + ? row.text.slice(1) + : row.text + + cActions.setInput(cState.input.slice(0, cState.compReplace) + text) + } + + return + } + + if (isCtrl(key, ch, 'k') && cRefs.queueRef.current.length && live.sid) { + const next = cActions.dequeue() + + if (next) { + cActions.setQueueEdit(null) + actions.dispatchSubmission(next) + } + } + }) + + return { pagerPageSize } +} diff --git a/ui-tui/src/app/useLongRunToolCharms.ts b/ui-tui/src/app/useLongRunToolCharms.ts new file mode 100644 index 0000000000..a65898db2b --- /dev/null +++ b/ui-tui/src/app/useLongRunToolCharms.ts @@ -0,0 +1,61 @@ +import { useEffect, useRef } from 'react' + +import { LONG_RUN_CHARMS } from '../content/charms.js' +import { pick, toolTrailLabel } from '../lib/text.js' +import type { ActiveTool } from '../types.js' + +import { turnController } from './turnController.js' + +const DELAY_MS = 8_000 +const INTERVAL_MS = 10_000 +const MAX_CHARMS_PER_TOOL = 2 + +interface Slot { + count: number + lastAt: number +} + +export function useLongRunToolCharms(busy: boolean, tools: ActiveTool[]) { + const slots = useRef(new Map()) + + useEffect(() => { + if (!busy || !tools.length) { + slots.current.clear() + + return + } + + const tick = () => { + const now = Date.now() + const liveIds = new Set(tools.map(t => t.id)) + + for (const key of [...slots.current.keys()]) { + if (!liveIds.has(key)) { + slots.current.delete(key) + } + } + + for (const tool of tools) { + if (!tool.startedAt || now - tool.startedAt < DELAY_MS) { + continue + } + + const slot = slots.current.get(tool.id) ?? { count: 0, lastAt: 0 } + + if (slot.count >= MAX_CHARMS_PER_TOOL || now - slot.lastAt < INTERVAL_MS) { + continue + } + + slots.current.set(tool.id, { count: slot.count + 1, lastAt: now }) + turnController.pushActivity( + `${pick(LONG_RUN_CHARMS)} (${toolTrailLabel(tool.name)} · ${Math.round((now - tool.startedAt) / 1000)}s)` + ) + } + } + + tick() + const id = setInterval(tick, 1000) + + return () => clearInterval(id) + }, [busy, tools]) +} diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts new file mode 100644 index 0000000000..73ea9febda --- /dev/null +++ b/ui-tui/src/app/useMainApp.ts @@ -0,0 +1,635 @@ +import { type ScrollBoxHandle, useApp, useHasSelection, useSelection, useStdout } from '@hermes/ink' +import { useStore } from '@nanostores/react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' + +import { STARTUP_RESUME_ID } from '../config/env.js' +import { MAX_HISTORY, WHEEL_SCROLL_STEP } from '../config/limits.js' +import { imageTokenMeta } from '../domain/messages.js' +import { shortCwd } from '../domain/paths.js' +import { type GatewayClient } from '../gatewayClient.js' +import type { + ClarifyRespondResponse, + ClipboardPasteResponse, + GatewayEvent, + TerminalResizeResponse +} from '../gatewayTypes.js' +import { useVirtualHistory } from '../hooks/useVirtualHistory.js' +import { asRpcResult, rpcErrorMessage } from '../lib/rpc.js' +import { buildToolTrailLine, sameToolTrailGroup, toolTrailLabel } from '../lib/text.js' +import type { Msg, PanelSection, SlashCatalog } from '../types.js' + +import { createGatewayEventHandler } from './createGatewayEventHandler.js' +import { createSlashHandler } from './createSlashHandler.js' +import { type GatewayRpc, type TranscriptRow } from './interfaces.js' +import { $overlayState, patchOverlayState } from './overlayStore.js' +import { turnController } from './turnController.js' +import { $turnState, patchTurnState } from './turnStore.js' +import { $uiState, getUiState, patchUiState } from './uiStore.js' +import { useComposerState } from './useComposerState.js' +import { useConfigSync } from './useConfigSync.js' +import { useInputHandlers } from './useInputHandlers.js' +import { useLongRunToolCharms } from './useLongRunToolCharms.js' +import { useSessionLifecycle } from './useSessionLifecycle.js' +import { useSubmission } from './useSubmission.js' + +const GOOD_VIBES_RE = /\b(good bot|thanks|thank you|thx|ty|ily|love you)\b/i +const BRACKET_PASTE_ON = '\x1b[?2004h' +const BRACKET_PASTE_OFF = '\x1b[?2004l' + +const capHistory = (items: Msg[]): Msg[] => { + if (items.length <= MAX_HISTORY) { + return items + } + + return items[0]?.kind === 'intro' ? [items[0]!, ...items.slice(-(MAX_HISTORY - 1))] : items.slice(-MAX_HISTORY) +} + +const statusColorOf = (status: string, t: { dim: string; error: string; ok: string; warn: string }) => { + if (status === 'ready') { + return t.ok + } + + if (status.startsWith('error')) { + return t.error + } + + if (status === 'interrupted') { + return t.warn + } + + return t.dim +} + +interface SelectionSnap { + anchor?: { row: number } + focus?: { row: number } + isDragging?: boolean +} + +export function useMainApp(gw: GatewayClient) { + const { exit } = useApp() + const { stdout } = useStdout() + const [cols, setCols] = useState(stdout?.columns ?? 80) + + useEffect(() => { + if (!stdout) { + return + } + + const sync = () => setCols(stdout.columns ?? 80) + + stdout.on('resize', sync) + + if (stdout.isTTY) { + stdout.write(BRACKET_PASTE_ON) + } + + return () => { + stdout.off('resize', sync) + + if (stdout.isTTY) { + stdout.write(BRACKET_PASTE_OFF) + } + } + }, [stdout]) + + const [historyItems, setHistoryItems] = useState(() => [{ kind: 'intro', role: 'system', text: '' }]) + const [lastUserMsg, setLastUserMsg] = useState('') + const [stickyPrompt, setStickyPrompt] = useState('') + const [catalog, setCatalog] = useState(null) + const [voiceEnabled, setVoiceEnabled] = useState(false) + const [voiceRecording, setVoiceRecording] = useState(false) + const [voiceProcessing, setVoiceProcessing] = useState(false) + const [sessionStartedAt, setSessionStartedAt] = useState(() => Date.now()) + const [goodVibesTick, setGoodVibesTick] = useState(0) + const [bellOnComplete, setBellOnComplete] = useState(false) + + const ui = useStore($uiState) + const overlay = useStore($overlayState) + const turn = useStore($turnState) + + const slashFlightRef = useRef(0) + const slashRef = useRef<(cmd: string) => boolean>(() => false) + const colsRef = useRef(cols) + const scrollRef = useRef(null) + const onEventRef = useRef<(ev: GatewayEvent) => void>(() => {}) + const clipboardPasteRef = useRef<(quiet?: boolean) => Promise | void>(() => {}) + const submitRef = useRef<(value: string) => void>(() => {}) + const historyItemsRef = useRef(historyItems) + const lastUserMsgRef = useRef(lastUserMsg) + const msgIdsRef = useRef(new WeakMap()) + const nextMsgIdRef = useRef(0) + + colsRef.current = cols + historyItemsRef.current = historyItems + lastUserMsgRef.current = lastUserMsg + + const hasSelection = useHasSelection() + const selection = useSelection() + + useEffect(() => { + selection.setSelectionBgColor(ui.theme.color.selectionBg) + }, [selection, ui.theme.color.selectionBg]) + + const composer = useComposerState({ + gw, + onClipboardPaste: quiet => clipboardPasteRef.current(quiet), + submitRef + }) + + const { actions: composerActions, refs: composerRefs, state: composerState } = composer + const empty = !historyItems.some(msg => msg.kind !== 'intro') + + const messageId = useCallback((msg: Msg) => { + const hit = msgIdsRef.current.get(msg) + + if (hit) { + return hit + } + + const next = `m${++nextMsgIdRef.current}` + + msgIdsRef.current.set(msg, next) + + return next + }, []) + + const virtualRows = useMemo( + () => historyItems.map((msg, index) => ({ index, key: messageId(msg), msg })), + [historyItems, messageId] + ) + + const virtualHistory = useVirtualHistory(scrollRef, virtualRows) + + const scrollWithSelection = useCallback( + (delta: number) => { + const s = scrollRef.current + + if (!s) { + return + } + + const sel = selection.getState() as null | SelectionSnap + const top = s.getViewportTop() + const bottom = top + s.getViewportHeight() - 1 + + if ( + !sel?.anchor || + !sel.focus || + sel.anchor.row < top || + sel.anchor.row > bottom || + (!sel.isDragging && (sel.focus.row < top || sel.focus.row > bottom)) + ) { + return s.scrollBy(delta) + } + + const max = Math.max(0, s.getScrollHeight() - s.getViewportHeight()) + const cur = s.getScrollTop() + s.getPendingDelta() + const actual = Math.max(0, Math.min(max, cur + delta)) - cur + + if (actual === 0) { + return + } + + const shift = sel!.isDragging ? selection.shiftAnchor : selection.shiftSelection + + if (actual > 0) { + selection.captureScrolledRows(top, top + actual - 1, 'above') + } else { + selection.captureScrolledRows(bottom + actual + 1, bottom, 'below') + } + + shift(-actual, top, bottom) + s.scrollBy(delta) + }, + [selection] + ) + + const appendMessage = useCallback((msg: Msg) => setHistoryItems(prev => capHistory([...prev, msg])), []) + + const sys = useCallback((text: string) => appendMessage({ role: 'system', text }), [appendMessage]) + + const page = useCallback( + (text: string, title?: string) => patchOverlayState({ pager: { lines: text.split('\n'), offset: 0, title } }), + [] + ) + + const panel = useCallback( + (title: string, sections: PanelSection[]) => + appendMessage({ kind: 'panel', panelData: { sections, title }, role: 'system', text: '' }), + [appendMessage] + ) + + const maybeWarn = useCallback( + (value: unknown) => { + const warning = (value as { warning?: unknown } | null)?.warning + + if (typeof warning === 'string' && warning) { + sys(`warning: ${warning}`) + } + }, + [sys] + ) + + const maybeGoodVibes = useCallback((text: string) => { + if (GOOD_VIBES_RE.test(text)) { + setGoodVibesTick(v => v + 1) + } + }, []) + + const rpc: GatewayRpc = useCallback( + async = Record>( + method: string, + params: Record = {} + ) => { + try { + const result = asRpcResult(await gw.request(method, params)) + + if (result) { + return result + } + + sys(`error: invalid response: ${method}`) + } catch (e) { + sys(`error: ${rpcErrorMessage(e)}`) + } + + return null + }, + [gw, sys] + ) + + const gateway = useMemo(() => ({ gw, rpc }), [gw, rpc]) + + const die = useCallback(() => { + gw.kill() + exit() + }, [exit, gw]) + + const session = useSessionLifecycle({ + colsRef, + composerActions, + gw, + panel, + rpc, + scrollRef, + setHistoryItems, + setLastUserMsg, + setSessionStartedAt, + setStickyPrompt, + setVoiceProcessing, + setVoiceRecording, + sys + }) + + useConfigSync({ gw, setBellOnComplete, setVoiceEnabled, sid: ui.sid }) + + useEffect(() => { + if (!ui.sid || !stdout) { + return + } + + const onResize = () => + rpc('terminal.resize', { cols: stdout.columns ?? 80, session_id: ui.sid }) + + stdout.on('resize', onResize) + + return () => { + stdout.off('resize', onResize) + } + }, [rpc, stdout, ui.sid]) + + const answerClarify = useCallback( + (answer: string) => { + const clarify = overlay.clarify + + if (!clarify) { + return + } + + const label = toolTrailLabel('clarify') + + turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line)) + patchTurnState({ turnTrail: turnController.turnTools }) + + rpc('clarify.respond', { answer, request_id: clarify.requestId }).then(r => { + if (!r) { + return + } + + if (answer) { + turnController.persistedToolLabels.add(label) + appendMessage({ + kind: 'trail', + role: 'system', + text: '', + tools: [buildToolTrailLine('clarify', clarify.question)] + }) + appendMessage({ role: 'user', text: answer }) + patchUiState({ status: 'running…' }) + } else { + sys('prompt cancelled') + } + + patchOverlayState({ clarify: null }) + }) + }, + [appendMessage, overlay.clarify, rpc, sys] + ) + + const paste = useCallback( + (quiet = false) => + rpc('clipboard.paste', { session_id: getUiState().sid }).then(r => { + if (!r) { + return + } + + if (r.attached) { + const meta = imageTokenMeta(r) + + return sys(`📎 Image #${r.count} attached from clipboard${meta ? ` · ${meta}` : ''}`) + } + + if (!quiet) { + sys(r.message || 'No image found in clipboard') + } + }), + [rpc, sys] + ) + + clipboardPasteRef.current = paste + + const { dispatchSubmission, send, sendQueued, shellExec, submit } = useSubmission({ + appendMessage, + composerActions, + composerRefs, + composerState, + gw, + maybeGoodVibes, + setLastUserMsg, + slashRef, + submitRef, + sys + }) + + const prevSidRef = useRef(null) + useEffect(() => { + const prev = prevSidRef.current + prevSidRef.current = ui.sid + + if (prev !== null || !ui.sid || ui.busy || composerRefs.queueEditRef.current !== null) { + return + } + + const next = composerActions.dequeue() + + if (next) { + sendQueued(next) + } + }, [ui.sid, ui.busy, composerActions, composerRefs, sendQueued]) + + const { pagerPageSize } = useInputHandlers({ + actions: { + answerClarify, + appendMessage, + die, + dispatchSubmission, + guardBusySessionSwitch: session.guardBusySessionSwitch, + newSession: session.newSession, + sys + }, + composer: { actions: composerActions, refs: composerRefs, state: composerState }, + gateway, + terminal: { hasSelection, scrollRef, scrollWithSelection, selection, stdout }, + voice: { recording: voiceRecording, setProcessing: setVoiceProcessing, setRecording: setVoiceRecording }, + wheelStep: WHEEL_SCROLL_STEP + }) + + const onEvent = useMemo( + () => + createGatewayEventHandler({ + composer: { dequeue: composerActions.dequeue, queueEditRef: composerRefs.queueEditRef, sendQueued }, + gateway, + session: { + STARTUP_RESUME_ID, + colsRef, + newSession: session.newSession, + resetSession: session.resetSession, + resumeById: session.resumeById, + setCatalog + }, + system: { bellOnComplete, stdout, sys }, + transcript: { appendMessage, panel, setHistoryItems } + }), + [ + appendMessage, + bellOnComplete, + composerActions, + composerRefs, + gateway, + panel, + sendQueued, + session.newSession, + session.resetSession, + session.resumeById, + stdout, + sys + ] + ) + + onEventRef.current = onEvent + + useEffect(() => { + const handler = (ev: GatewayEvent) => onEventRef.current(ev) + + const exitHandler = () => { + patchUiState({ busy: false, sid: null, status: 'gateway exited' }) + turnController.pushActivity('gateway exited · /logs to inspect', 'error') + sys('error: gateway exited') + } + + gw.on('event', handler) + gw.on('exit', exitHandler) + gw.drain() + + return () => { + gw.off('event', handler) + gw.off('exit', exitHandler) + gw.kill() + } + }, [gw, sys]) + + useLongRunToolCharms(ui.busy, turn.tools) + + const slash = useMemo( + () => + createSlashHandler({ + composer: { + enqueue: composerActions.enqueue, + hasSelection, + paste, + queueRef: composerRefs.queueRef, + selection, + setInput: composerActions.setInput + }, + gateway, + local: { + catalog, + getHistoryItems: () => historyItemsRef.current, + getLastUserMsg: () => lastUserMsgRef.current, + maybeWarn + }, + session: { + closeSession: session.closeSession, + die, + guardBusySessionSwitch: session.guardBusySessionSwitch, + newSession: session.newSession, + resetVisibleHistory: session.resetVisibleHistory, + resumeById: session.resumeById, + setSessionStartedAt + }, + slashFlightRef, + transcript: { page, panel, send, setHistoryItems, sys, trimLastExchange: session.trimLastExchange }, + voice: { setVoiceEnabled } + }), + [ + catalog, + composerActions, + composerRefs, + die, + gateway, + hasSelection, + maybeWarn, + page, + panel, + paste, + selection, + send, + session, + sys + ] + ) + + slashRef.current = slash + + const respondWith = useCallback( + (method: string, params: Record, done: () => void) => rpc(method, params).then(r => r && done()), + [rpc] + ) + + const answerApproval = useCallback( + (choice: string) => + respondWith('approval.respond', { choice, session_id: ui.sid }, () => { + patchOverlayState({ approval: null }) + patchTurnState({ outcome: choice === 'deny' ? 'denied' : `approved (${choice})` }) + patchUiState({ status: 'running…' }) + }), + [respondWith, ui.sid] + ) + + const answerSudo = useCallback( + (pw: string) => { + if (!overlay.sudo) { + return + } + + return respondWith('sudo.respond', { password: pw, request_id: overlay.sudo.requestId }, () => { + patchOverlayState({ sudo: null }) + patchUiState({ status: 'running…' }) + }) + }, + [overlay.sudo, respondWith] + ) + + const answerSecret = useCallback( + (value: string) => { + if (!overlay.secret) { + return + } + + return respondWith('secret.respond', { request_id: overlay.secret.requestId, value }, () => { + patchOverlayState({ secret: null }) + patchUiState({ status: 'running…' }) + }) + }, + [overlay.secret, respondWith] + ) + + const onModelSelect = useCallback((value: string) => { + patchOverlayState({ modelPicker: false }) + slashRef.current(`/model ${value}`) + }, []) + + const hasReasoning = Boolean(turn.reasoning.trim()) + + const showProgressArea = + ui.detailsMode === 'hidden' + ? turn.activity.some(item => item.tone !== 'info') + : Boolean( + ui.busy || + turn.outcome || + turn.streamPendingTools.length || + turn.streamSegments.length || + turn.subagents.length || + turn.tools.length || + turn.turnTrail.length || + hasReasoning || + turn.activity.length + ) + + const appActions = useMemo( + () => ({ + answerApproval, + answerClarify, + answerSecret, + answerSudo, + onModelSelect, + resumeById: session.resumeById, + setStickyPrompt + }), + [answerApproval, answerClarify, answerSecret, answerSudo, onModelSelect, session.resumeById] + ) + + const appComposer = useMemo( + () => ({ + cols, + compIdx: composerState.compIdx, + completions: composerState.completions, + empty, + handleTextPaste: composerActions.handleTextPaste, + input: composerState.input, + inputBuf: composerState.inputBuf, + pagerPageSize, + queueEditIdx: composerState.queueEditIdx, + queuedDisplay: composerState.queuedDisplay, + submit, + updateInput: composerActions.setInput + }), + [cols, composerActions, composerState, empty, pagerPageSize, submit] + ) + + const appProgress = useMemo( + () => ({ ...turn, showProgressArea, showStreamingArea: Boolean(turn.streaming) }), + [turn, showProgressArea] + ) + + const appStatus = useMemo( + () => ({ + cwdLabel: shortCwd(ui.info?.cwd || process.env.HERMES_CWD || process.cwd()), + goodVibesTick, + sessionStartedAt: ui.sid ? sessionStartedAt : null, + showStickyPrompt: !!stickyPrompt, + statusColor: statusColorOf(ui.status, ui.theme.color), + stickyPrompt, + voiceLabel: voiceRecording ? 'REC' : voiceProcessing ? 'STT' : `voice ${voiceEnabled ? 'on' : 'off'}` + }), + [goodVibesTick, sessionStartedAt, stickyPrompt, ui, voiceEnabled, voiceProcessing, voiceRecording] + ) + + const appTranscript = useMemo( + () => ({ historyItems, scrollRef, virtualHistory, virtualRows }), + [historyItems, virtualHistory, virtualRows] + ) + + return { appActions, appComposer, appProgress, appStatus, appTranscript, gateway } +} diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts new file mode 100644 index 0000000000..acd10135e1 --- /dev/null +++ b/ui-tui/src/app/useSessionLifecycle.ts @@ -0,0 +1,223 @@ +import type { ScrollBoxHandle } from '@hermes/ink' +import { type RefObject, useCallback } from 'react' + +import { buildSetupRequiredSections, SETUP_REQUIRED_TITLE } from '../content/setup.js' +import { introMsg, toTranscriptMessages } from '../domain/messages.js' +import { ZERO } from '../domain/usage.js' +import { type GatewayClient } from '../gatewayClient.js' +import type { + SessionCloseResponse, + SessionCreateResponse, + SessionResumeResponse, + SetupStatusResponse +} from '../gatewayTypes.js' +import { asRpcResult } from '../lib/rpc.js' +import type { Msg, PanelSection, SessionInfo, Usage } from '../types.js' + +import type { ComposerActions, GatewayRpc, StateSetter } from './interfaces.js' +import { patchOverlayState } from './overlayStore.js' +import { turnController } from './turnController.js' +import { patchTurnState } from './turnStore.js' +import { getUiState, patchUiState } from './uiStore.js' + +const usageFrom = (info: null | SessionInfo): Usage => (info?.usage ? { ...ZERO, ...info.usage } : ZERO) + +const trimTail = (items: Msg[]) => { + const q = [...items] + + while (q.at(-1)?.role === 'assistant' || q.at(-1)?.role === 'tool') { + q.pop() + } + + if (q.at(-1)?.role === 'user') { + q.pop() + } + + return q +} + +export interface UseSessionLifecycleOptions { + colsRef: { current: number } + composerActions: ComposerActions + gw: GatewayClient + panel: (title: string, sections: PanelSection[]) => void + rpc: GatewayRpc + scrollRef: RefObject + setHistoryItems: StateSetter + setLastUserMsg: StateSetter + setSessionStartedAt: StateSetter + setStickyPrompt: StateSetter + setVoiceProcessing: StateSetter + setVoiceRecording: StateSetter + sys: (text: string) => void +} + +export function useSessionLifecycle(opts: UseSessionLifecycleOptions) { + const { + colsRef, + composerActions, + gw, + panel, + rpc, + scrollRef, + setHistoryItems, + setLastUserMsg, + setSessionStartedAt, + setStickyPrompt, + setVoiceProcessing, + setVoiceRecording, + sys + } = opts + + const closeSession = useCallback( + (targetSid?: null | string) => + targetSid ? rpc('session.close', { session_id: targetSid }) : Promise.resolve(null), + [rpc] + ) + + const resetSession = useCallback(() => { + turnController.fullReset() + setVoiceRecording(false) + setVoiceProcessing(false) + patchUiState({ bgTasks: new Set(), info: null, sid: null, usage: ZERO }) + setHistoryItems([]) + setLastUserMsg('') + setStickyPrompt('') + composerActions.setPasteSnips([]) + }, [composerActions, setHistoryItems, setLastUserMsg, setStickyPrompt, setVoiceProcessing, setVoiceRecording]) + + const resetVisibleHistory = useCallback( + (info: null | SessionInfo = null) => { + turnController.idle() + turnController.clearReasoning() + turnController.turnTools = [] + turnController.persistedToolLabels.clear() + + setHistoryItems(info ? [introMsg(info)] : []) + setStickyPrompt('') + setLastUserMsg('') + composerActions.setPasteSnips([]) + patchTurnState({ activity: [] }) + patchUiState({ info, usage: usageFrom(info) }) + }, + [composerActions, setHistoryItems, setLastUserMsg, setStickyPrompt] + ) + + const newSession = useCallback( + async (msg?: string) => { + const setup = await rpc('setup.status', {}) + + if (setup?.provider_configured === false) { + panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections()) + patchUiState({ status: 'setup required' }) + + return + } + + await closeSession(getUiState().sid) + + const r = await rpc('session.create', { cols: colsRef.current }) + + if (!r) { + return patchUiState({ status: 'ready' }) + } + + const info = r.info ?? null + + resetSession() + setSessionStartedAt(Date.now()) + + patchUiState({ + info, + sid: r.session_id, + status: info?.version ? 'ready' : 'starting agent…', + usage: usageFrom(info) + }) + + if (info) { + setHistoryItems([introMsg(info)]) + } + + if (info?.credential_warning) { + sys(`warning: ${info.credential_warning}`) + } + + if (msg) { + sys(msg) + } + }, + [closeSession, colsRef, panel, resetSession, rpc, setHistoryItems, setSessionStartedAt, sys] + ) + + const resumeById = useCallback( + (id: string) => { + patchOverlayState({ picker: false }) + patchUiState({ status: 'resuming…' }) + + rpc('setup.status', {}).then(setup => { + if (setup?.provider_configured === false) { + panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections()) + patchUiState({ status: 'setup required' }) + + return + } + + closeSession(getUiState().sid === id ? null : getUiState().sid).then(() => + gw + .request('session.resume', { cols: colsRef.current, session_id: id }) + .then(raw => { + const r = asRpcResult(raw) + + if (!r) { + sys('error: invalid response: session.resume') + + return patchUiState({ status: 'ready' }) + } + + resetSession() + setSessionStartedAt(Date.now()) + + const resumed = toTranscriptMessages(r.messages) + + setHistoryItems(r.info ? [introMsg(r.info), ...resumed] : resumed) + patchUiState({ + info: r.info ?? null, + sid: r.session_id, + status: 'ready', + usage: usageFrom(r.info ?? null) + }) + setTimeout(() => scrollRef.current?.scrollToBottom(), 0) + }) + .catch((e: Error) => { + sys(`error: ${e.message}`) + patchUiState({ status: 'ready' }) + }) + ) + }) + }, + [closeSession, colsRef, gw, panel, resetSession, rpc, scrollRef, setHistoryItems, setSessionStartedAt, sys] + ) + + const guardBusySessionSwitch = useCallback( + (what = 'switch sessions') => { + if (!getUiState().busy) { + return false + } + + sys(`interrupt the current turn before trying to ${what}`) + + return true + }, + [sys] + ) + + return { + closeSession, + guardBusySessionSwitch, + newSession, + resetSession, + resetVisibleHistory, + resumeById, + trimLastExchange: trimTail + } +} diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts new file mode 100644 index 0000000000..f8a40f5a08 --- /dev/null +++ b/ui-tui/src/app/useSubmission.ts @@ -0,0 +1,303 @@ +import { type MutableRefObject, useCallback, useRef } from 'react' + +import { imageTokenMeta } from '../domain/messages.js' +import { looksLikeSlashCommand } from '../domain/slash.js' +import type { GatewayClient } from '../gatewayClient.js' +import type { InputDetectDropResponse, PromptSubmitResponse, ShellExecResponse } from '../gatewayTypes.js' +import { asRpcResult } from '../lib/rpc.js' +import { hasInterpolation, INTERPOLATION_RE } from '../protocol/interpolation.js' +import { PASTE_SNIPPET_RE } from '../protocol/paste.js' +import type { Msg } from '../types.js' + +import type { ComposerActions, ComposerRefs, ComposerState, PasteSnippet } from './interfaces.js' +import { turnController } from './turnController.js' +import { getUiState, patchUiState } from './uiStore.js' + +const DOUBLE_ENTER_MS = 450 + +const expandSnips = (snips: PasteSnippet[]) => { + const byLabel = new Map() + + for (const { label, text } of snips) { + const hit = byLabel.get(label) + hit ? hit.push(text) : byLabel.set(label, [text]) + } + + return (value: string) => value.replace(PASTE_SNIPPET_RE, tok => byLabel.get(tok)?.shift() ?? tok) +} + +const spliceMatches = (text: string, matches: RegExpMatchArray[], results: string[]) => + matches.reduceRight((acc, m, i) => acc.slice(0, m.index!) + results[i] + acc.slice(m.index! + m[0].length), text) + +export function useSubmission(opts: UseSubmissionOptions) { + const { + appendMessage, + composerActions, + composerRefs, + composerState, + gw, + maybeGoodVibes, + setLastUserMsg, + slashRef, + submitRef, + sys + } = opts + + const lastEmptyAt = useRef(0) + + const send = useCallback( + (text: string) => { + const expand = expandSnips(composerState.pasteSnips) + + const startSubmit = (displayText: string, submitText: string) => { + const sid = getUiState().sid + + if (!sid) { + return sys('session not ready yet') + } + + turnController.clearStatusTimer() + maybeGoodVibes(submitText) + setLastUserMsg(text) + appendMessage({ role: 'user', text: displayText }) + patchUiState({ busy: true, status: 'running…' }) + turnController.bufRef = '' + turnController.interrupted = false + + gw.request('prompt.submit', { session_id: sid, text: submitText }).catch((e: Error) => { + sys(`error: ${e.message}`) + patchUiState({ busy: false, status: 'ready' }) + }) + } + + const sid = getUiState().sid + + if (!sid) { + return sys('session not ready yet') + } + + gw.request('input.detect_drop', { session_id: sid, text }) + .then(r => { + if (!r?.matched) { + return startSubmit(text, expand(text)) + } + + if (r.is_image) { + const meta = imageTokenMeta(r) + + turnController.pushActivity(`attached image: ${r.name}${meta ? ` · ${meta}` : ''}`) + } else { + turnController.pushActivity(`detected file: ${r.name}`) + } + + startSubmit(r.text || text, expand(r.text || text)) + }) + .catch(() => startSubmit(text, expand(text))) + }, + [appendMessage, composerState.pasteSnips, gw, maybeGoodVibes, setLastUserMsg, sys] + ) + + const shellExec = useCallback( + (cmd: string) => { + appendMessage({ role: 'user', text: `!${cmd}` }) + patchUiState({ busy: true, status: 'running…' }) + + gw.request('shell.exec', { command: cmd }) + .then(raw => { + const r = asRpcResult(raw) + + if (!r) { + return sys('error: invalid response: shell.exec') + } + + const out = [r.stdout, r.stderr].filter(Boolean).join('\n').trim() + + if (out) { + sys(out) + } + + if (r.code !== 0 || !out) { + sys(`exit ${r.code}`) + } + }) + .catch((e: Error) => sys(`error: ${e.message}`)) + .finally(() => patchUiState({ busy: false, status: 'ready' })) + }, + [appendMessage, gw, sys] + ) + + const interpolate = useCallback( + (text: string, then: (result: string) => void) => { + patchUiState({ status: 'interpolating…' }) + const matches = [...text.matchAll(new RegExp(INTERPOLATION_RE.source, 'g'))] + + Promise.all( + matches.map(m => + gw + .request('shell.exec', { command: m[1]! }) + .then(raw => { + const r = asRpcResult(raw) + + return [r?.stdout, r?.stderr].filter(Boolean).join('\n').trim() + }) + .catch(() => '(error)') + ) + ).then(results => then(spliceMatches(text, matches, results))) + }, + [gw] + ) + + const sendQueued = useCallback( + (text: string) => { + if (text.startsWith('!')) { + return shellExec(text.slice(1).trim()) + } + + if (hasInterpolation(text)) { + patchUiState({ busy: true }) + + return interpolate(text, send) + } + + send(text) + }, + [interpolate, send, shellExec] + ) + + const dispatchSubmission = useCallback( + (full: string) => { + if (!full.trim()) { + return + } + + if (looksLikeSlashCommand(full)) { + appendMessage({ kind: 'slash', role: 'system', text: full }) + composerActions.pushHistory(full) + slashRef.current(full) + composerActions.clearIn() + + return + } + + if (full.startsWith('!')) { + composerActions.clearIn() + + return shellExec(full.slice(1).trim()) + } + + const live = getUiState() + + if (!live.sid) { + composerActions.pushHistory(full) + composerActions.enqueue(full) + composerActions.clearIn() + + return + } + + const editIdx = composerRefs.queueEditRef.current + composerActions.clearIn() + + if (editIdx !== null) { + composerActions.replaceQueue(editIdx, full) + const picked = composerRefs.queueRef.current.splice(editIdx, 1)[0] + composerActions.syncQueue() + composerActions.setQueueEdit(null) + + if (!picked || !live.sid) { + return + } + + if (getUiState().busy) { + composerRefs.queueRef.current.unshift(picked) + + return composerActions.syncQueue() + } + + return sendQueued(picked) + } + + composerActions.pushHistory(full) + + if (getUiState().busy) { + return composerActions.enqueue(full) + } + + if (hasInterpolation(full)) { + patchUiState({ busy: true }) + + return interpolate(full, send) + } + + send(full) + }, + [appendMessage, composerActions, composerRefs, interpolate, send, sendQueued, shellExec, slashRef] + ) + + const submit = useCallback( + (value: string) => { + if (value.startsWith('/') && composerState.completions.length) { + const row = composerState.completions[composerState.compIdx] + + if (row?.text) { + const text = row.text.startsWith('/') && composerState.compReplace > 0 ? row.text.slice(1) : row.text + const next = value.slice(0, composerState.compReplace) + text + + if (next !== value) { + return composerActions.setInput(next) + } + } + } + + if (!value.trim() && !composerState.inputBuf.length) { + const live = getUiState() + const now = Date.now() + const doubleTap = now - lastEmptyAt.current < DOUBLE_ENTER_MS + lastEmptyAt.current = now + + if (doubleTap && live.busy && live.sid) { + return turnController.interruptTurn({ appendMessage, gw, sid: live.sid, sys }) + } + + if (doubleTap && live.sid && composerRefs.queueRef.current.length) { + const next = composerActions.dequeue() + + if (next) { + composerActions.setQueueEdit(null) + dispatchSubmission(next) + } + } + + return + } + + lastEmptyAt.current = 0 + + if (value.endsWith('\\')) { + composerActions.setInputBuf(prev => [...prev, value.slice(0, -1)]) + + return composerActions.setInput('') + } + + dispatchSubmission([...composerState.inputBuf, value].join('\n')) + }, + [appendMessage, composerActions, composerRefs, composerState, dispatchSubmission, gw, sys] + ) + + submitRef.current = submit + + return { dispatchSubmission, send, sendQueued, shellExec, submit } +} + +export interface UseSubmissionOptions { + appendMessage: (msg: Msg) => void + composerActions: ComposerActions + composerRefs: ComposerRefs + composerState: ComposerState + gw: GatewayClient + maybeGoodVibes: (text: string) => void + setLastUserMsg: (value: string) => void + slashRef: MutableRefObject<(cmd: string) => boolean> + submitRef: MutableRefObject<(value: string) => void> + sys: (text: string) => void +} diff --git a/ui-tui/src/banner.ts b/ui-tui/src/banner.ts new file mode 100644 index 0000000000..d048b7dac8 --- /dev/null +++ b/ui-tui/src/banner.ts @@ -0,0 +1,93 @@ +import type { ThemeColors } from './theme.js' + +const RICH_RE = /\[(?:bold\s+)?(?:dim\s+)?(#(?:[0-9a-fA-F]{3,8}))\]([\s\S]*?)(\[\/\])/g + +export function parseRichMarkup(markup: string): Line[] { + const lines: Line[] = [] + + for (const raw of markup.split('\n')) { + const trimmed = raw.trimEnd() + + if (!trimmed) { + lines.push(['', ' ']) + + continue + } + + const matches = [...trimmed.matchAll(RICH_RE)] + + if (!matches.length) { + lines.push(['', trimmed]) + + continue + } + + let cursor = 0 + + for (const m of matches) { + const before = trimmed.slice(cursor, m.index) + + if (before) { + lines.push(['', before]) + } + + lines.push([m[1]!, m[2]!]) + cursor = m.index! + m[0].length + } + + if (cursor < trimmed.length) { + lines.push(['', trimmed.slice(cursor)]) + } + } + + return lines +} + +const LOGO_ART = [ + '██╗ ██╗███████╗██████╗ ███╗ ███╗███████╗███████╗ █████╗ ██████╗ ███████╗███╗ ██╗████████╗', + '██║ ██║██╔════╝██╔══██╗████╗ ████║██╔════╝██╔════╝ ██╔══██╗██╔════╝ ██╔════╝████╗ ██║╚══██╔══╝', + '███████║█████╗ ██████╔╝██╔████╔██║█████╗ ███████╗█████╗███████║██║ ███╗█████╗ ██╔██╗ ██║ ██║ ', + '██╔══██║██╔══╝ ██╔══██╗██║╚██╔╝██║██╔══╝ ╚════██║╚════╝██╔══██║██║ ██║██╔══╝ ██║╚██╗██║ ██║ ', + '██║ ██║███████╗██║ ██║██║ ╚═╝ ██║███████╗███████║ ██║ ██║╚██████╔╝███████╗██║ ╚████║ ██║ ', + '╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ' +] + +const CADUCEUS_ART = [ + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⡀⠀⣀⣀⠀⢀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⢀⣠⣴⣾⣿⣿⣇⠸⣿⣿⠇⣸⣿⣿⣷⣦⣄⡀⠀⠀⠀⠀⠀⠀', + '⠀⢀⣠⣴⣶⠿⠋⣩⡿⣿⡿⠻⣿⡇⢠⡄⢸⣿⠟⢿⣿⢿⣍⠙⠿⣶⣦⣄⡀⠀', + '⠀⠀⠉⠉⠁⠶⠟⠋⠀⠉⠀⢀⣈⣁⡈⢁⣈⣁⡀⠀⠉⠀⠙⠻⠶⠈⠉⠉⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⡿⠛⢁⡈⠛⢿⣿⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠿⣿⣦⣤⣈⠁⢠⣴⣿⠿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠻⢿⣿⣦⡉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⢷⣦⣈⠛⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣴⠦⠈⠙⠿⣦⡄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣤⡈⠁⢤⣿⠇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠷⠄⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⠑⢶⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⠁⢰⡆⠈⡿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠳⠈⣡⠞⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀', + '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀' +] + +const LOGO_GRADIENT = [0, 0, 1, 1, 2, 2] as const +const CADUC_GRADIENT = [2, 2, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 3, 3, 3] as const + +const colorize = (art: string[], gradient: readonly number[], c: ThemeColors): Line[] => { + const p = [c.gold, c.amber, c.bronze, c.dim] + + return art.map((text, i) => [p[gradient[i]!] ?? c.dim, text]) +} + +export const LOGO_WIDTH = 98 +export const CADUCEUS_WIDTH = 30 + +export const logo = (c: ThemeColors, customLogo?: string): Line[] => + customLogo ? parseRichMarkup(customLogo) : colorize(LOGO_ART, LOGO_GRADIENT, c) + +export const caduceus = (c: ThemeColors, customHero?: string): Line[] => + customHero ? parseRichMarkup(customHero) : colorize(CADUCEUS_ART, CADUC_GRADIENT, c) + +export const artWidth = (lines: Line[]) => lines.reduce((m, [, t]) => Math.max(m, t.length), 0) + +type Line = [string, string] diff --git a/ui-tui/src/bootBanner.ts b/ui-tui/src/bootBanner.ts new file mode 100644 index 0000000000..2c85387bd4 --- /dev/null +++ b/ui-tui/src/bootBanner.ts @@ -0,0 +1,26 @@ +const GOLD = '\x1b[38;2;255;215;0m' +const AMBER = '\x1b[38;2;255;191;0m' +const BRONZE = '\x1b[38;2;205;127;50m' +const DIM = '\x1b[38;2;184;134;11m' +const RESET = '\x1b[0m' + +const LOGO = [ + '██╗ ██╗███████╗██████╗ ███╗ ███╗███████╗███████╗ █████╗ ██████╗ ███████╗███╗ ██╗████████╗', + '██║ ██║██╔════╝██╔══██╗████╗ ████║██╔════╝██╔════╝ ██╔══██╗██╔════╝ ██╔════╝████╗ ██║╚══██╔══╝', + '███████║█████╗ ██████╔╝██╔████╔██║█████╗ ███████╗█████╗███████║██║ ███╗█████╗ ██╔██╗ ██║ ██║ ', + '██╔══██║██╔══╝ ██╔══██╗██║╚██╔╝██║██╔══╝ ╚════██║╚════╝██╔══██║██║ ██║██╔══╝ ██║╚██╗██║ ██║ ', + '██║ ██║███████╗██║ ██║██║ ╚═╝ ██║███████╗███████║ ██║ ██║╚██████╔╝███████╗██║ ╚████║ ██║ ', + '╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═══╝ ╚═╝ ' +] + +const GRADIENT = [GOLD, GOLD, AMBER, AMBER, BRONZE, BRONZE] as const +const LOGO_WIDTH = 98 + +const TAGLINE = `${DIM}⚕ Nous Research · Messenger of the Digital Gods${RESET}` +const FALLBACK = `\x1b[1m${GOLD}⚕ NOUS HERMES${RESET}` + +export function bootBanner(cols: number = process.stdout.columns || 80): string { + const body = cols >= LOGO_WIDTH ? LOGO.map((text, i) => `${GRADIENT[i]}${text}${RESET}`).join('\n') : FALLBACK + + return `\n${body}\n${TAGLINE}\n\n` +} diff --git a/ui-tui/src/components/appChrome.tsx b/ui-tui/src/components/appChrome.tsx new file mode 100644 index 0000000000..ed6f914c96 --- /dev/null +++ b/ui-tui/src/components/appChrome.tsx @@ -0,0 +1,305 @@ +import { Box, type ScrollBoxHandle, Text } from '@hermes/ink' +import { type ReactNode, type RefObject, useCallback, useEffect, useState, useSyncExternalStore } from 'react' + +import { FACES } from '../content/faces.js' +import { VERBS } from '../content/verbs.js' +import { fmtDuration } from '../domain/messages.js' +import { stickyPromptFromViewport } from '../domain/viewport.js' +import { fmtK } from '../lib/text.js' +import type { Theme } from '../theme.js' +import type { Msg, Usage } from '../types.js' + +const FACE_TICK_MS = 2500 +const HEART_COLORS = ['#ff5fa2', '#ff4d6d'] + +function FaceTicker({ color }: { color: string }) { + const [tick, setTick] = useState(() => Math.floor(Math.random() * 1000)) + + useEffect(() => { + const id = setInterval(() => setTick(n => n + 1), FACE_TICK_MS) + + return () => clearInterval(id) + }, []) + + return ( + + {FACES[tick % FACES.length]} {VERBS[tick % VERBS.length]}… + + ) +} + +function ctxBarColor(pct: number | undefined, t: Theme) { + if (pct == null) { + return t.color.dim + } + + if (pct >= 95) { + return t.color.statusCritical + } + + if (pct > 80) { + return t.color.statusBad + } + + if (pct >= 50) { + return t.color.statusWarn + } + + return t.color.statusGood +} + +function ctxBar(pct: number | undefined, w = 10) { + const p = Math.max(0, Math.min(100, pct ?? 0)) + const filled = Math.round((p / 100) * w) + + return '█'.repeat(filled) + '░'.repeat(w - filled) +} + +function SessionDuration({ startedAt }: { startedAt: number }) { + const [now, setNow] = useState(() => Date.now()) + + useEffect(() => { + setNow(Date.now()) + const id = setInterval(() => setNow(Date.now()), 1000) + + return () => clearInterval(id) + }, [startedAt]) + + return fmtDuration(now - startedAt) +} + +export function GoodVibesHeart({ tick, t }: { tick: number; t: Theme }) { + const [active, setActive] = useState(false) + const [color, setColor] = useState(t.color.amber) + + useEffect(() => { + if (tick <= 0) { + return + } + + const palette = [...HEART_COLORS, t.color.amber] + setColor(palette[Math.floor(Math.random() * palette.length)]!) + setActive(true) + + const id = setTimeout(() => setActive(false), 650) + + return () => clearTimeout(id) + }, [t.color.amber, tick]) + + return {active ? '♥' : ' '} +} + +export function StatusRule({ + cwdLabel, + cols, + busy, + status, + statusColor, + model, + usage, + bgCount, + sessionStartedAt, + voiceLabel, + t +}: StatusRuleProps) { + const pct = usage.context_percent + const barColor = ctxBarColor(pct, t) + + const ctxLabel = usage.context_max + ? `${fmtK(usage.context_used ?? 0)}/${fmtK(usage.context_max)}` + : usage.total > 0 + ? `${fmtK(usage.total)} tok` + : '' + + const bar = usage.context_max ? ctxBar(pct) : '' + const leftWidth = Math.max(12, cols - cwdLabel.length - 3) + + return ( + + + + {'─ '} + {busy ? : {status}} + │ {model} + {ctxLabel ? │ {ctxLabel} : null} + {bar ? ( + + {' │ '} + [{bar}] {pct != null ? `${pct}%` : ''} + + ) : null} + {sessionStartedAt ? ( + + {' │ '} + + + ) : null} + {voiceLabel ? │ {voiceLabel} : null} + {bgCount > 0 ? │ {bgCount} bg : null} + + + + + {cwdLabel} + + ) +} + +export function FloatBox({ children, color }: { children: ReactNode; color: string }) { + return ( + + {children} + + ) +} + +export function StickyPromptTracker({ messages, offsets, scrollRef, onChange }: StickyPromptTrackerProps) { + useSyncExternalStore( + useCallback((cb: () => void) => scrollRef.current?.subscribe(cb) ?? (() => {}), [scrollRef]), + () => { + const s = scrollRef.current + + if (!s) { + return NaN + } + + const top = Math.max(0, s.getScrollTop() + s.getPendingDelta()) + + return s.isSticky() ? -1 - top : top + }, + () => NaN + ) + + const s = scrollRef.current + const top = Math.max(0, (s?.getScrollTop() ?? 0) + (s?.getPendingDelta() ?? 0)) + const text = stickyPromptFromViewport(messages, offsets, top, s?.isSticky() ?? true) + + useEffect(() => onChange(text), [onChange, text]) + + return null +} + +export function TranscriptScrollbar({ scrollRef, t }: TranscriptScrollbarProps) { + useSyncExternalStore( + useCallback((cb: () => void) => scrollRef.current?.subscribe(cb) ?? (() => {}), [scrollRef]), + () => { + const s = scrollRef.current + + if (!s) { + return NaN + } + + const vp = Math.max(0, s.getViewportHeight()) + const total = Math.max(vp, s.getScrollHeight()) + const top = Math.max(0, s.getScrollTop() + s.getPendingDelta()) + const thumb = total > vp ? Math.max(1, Math.round((vp * vp) / total)) : vp + const travel = Math.max(1, vp - thumb) + const thumbTop = total > vp ? Math.round((top / Math.max(1, total - vp)) * travel) : 0 + + return `${thumbTop}:${thumb}:${vp}` + }, + () => '' + ) + + const [hover, setHover] = useState(false) + const [grab, setGrab] = useState(null) + + const s = scrollRef.current + const vp = Math.max(0, s?.getViewportHeight() ?? 0) + + if (!vp) { + return + } + + const total = Math.max(vp, s?.getScrollHeight() ?? vp) + const scrollable = total > vp + const thumb = scrollable ? Math.max(1, Math.round((vp * vp) / total)) : vp + const travel = Math.max(1, vp - thumb) + const pos = Math.max(0, (s?.getScrollTop() ?? 0) + (s?.getPendingDelta() ?? 0)) + const thumbTop = scrollable ? Math.round((pos / Math.max(1, total - vp)) * travel) : 0 + const thumbColor = grab !== null ? t.color.gold : hover ? t.color.amber : t.color.bronze + const trackColor = hover ? t.color.bronze : t.color.dim + + const jump = (row: number, offset: number) => { + if (!s || !scrollable) { + return + } + + s.scrollTo(Math.round((Math.max(0, Math.min(travel, row - offset)) / travel) * Math.max(0, total - vp))) + } + + return ( + { + const row = Math.max(0, Math.min(vp - 1, e.localRow ?? 0)) + const off = row >= thumbTop && row < thumbTop + thumb ? row - thumbTop : Math.floor(thumb / 2) + setGrab(off) + jump(row, off) + }} + onMouseDrag={(e: { localRow?: number }) => + jump(Math.max(0, Math.min(vp - 1, e.localRow ?? 0)), grab ?? Math.floor(thumb / 2)) + } + onMouseEnter={() => setHover(true)} + onMouseLeave={() => setHover(false)} + onMouseUp={() => setGrab(null)} + width={1} + > + {!scrollable ? ( + + {' \n'.repeat(Math.max(0, vp - 1))}{' '} + + ) : ( + <> + {thumbTop > 0 ? ( + + {`${'│\n'.repeat(Math.max(0, thumbTop - 1))}${thumbTop > 0 ? '│' : ''}`} + + ) : null} + {thumb > 0 ? ( + {`${'┃\n'.repeat(Math.max(0, thumb - 1))}${thumb > 0 ? '┃' : ''}`} + ) : null} + {vp - thumbTop - thumb > 0 ? ( + + {`${'│\n'.repeat(Math.max(0, vp - thumbTop - thumb - 1))}${vp - thumbTop - thumb > 0 ? '│' : ''}`} + + ) : null} + + )} + + ) +} + +interface StatusRuleProps { + bgCount: number + busy: boolean + cols: number + cwdLabel: string + model: string + sessionStartedAt?: number | null + status: string + statusColor: string + t: Theme + usage: Usage + voiceLabel?: string +} + +interface StickyPromptTrackerProps { + messages: readonly Msg[] + offsets: ArrayLike + onChange: (text: string) => void + scrollRef: RefObject +} + +interface TranscriptScrollbarProps { + scrollRef: RefObject + t: Theme +} diff --git a/ui-tui/src/components/appLayout.tsx b/ui-tui/src/components/appLayout.tsx new file mode 100644 index 0000000000..26d8e4b0a9 --- /dev/null +++ b/ui-tui/src/components/appLayout.tsx @@ -0,0 +1,293 @@ +import { AlternateScreen, Box, NoSelect, ScrollBox, Text } from '@hermes/ink' +import { useStore } from '@nanostores/react' +import { memo } from 'react' + +import type { AppLayoutProgressProps, AppLayoutProps } from '../app/interfaces.js' +import { $isBlocked } from '../app/overlayStore.js' +import { $uiState } from '../app/uiStore.js' +import { PLACEHOLDER } from '../content/placeholders.js' +import type { Theme } from '../theme.js' +import type { DetailsMode } from '../types.js' + +import { GoodVibesHeart, StatusRule, StickyPromptTracker, TranscriptScrollbar } from './appChrome.js' +import { FloatingOverlays, PromptZone } from './appOverlays.js' +import { Banner, Panel, SessionPanel } from './branding.js' +import { MessageLine } from './messageLine.js' +import { QueuedMessages } from './queuedMessages.js' +import { TextInput } from './textInput.js' +import { ToolTrail } from './thinking.js' + +const StreamingAssistant = memo(function StreamingAssistant({ + busy, + cols, + compact, + detailsMode, + progress, + t +}: StreamingAssistantProps) { + if (!progress.showProgressArea && !progress.showStreamingArea) { + return null + } + + return ( + <> + {progress.streamSegments.map((msg, i) => ( + + ))} + + {progress.showProgressArea && ( + + + + )} + + {progress.showStreamingArea && ( + + )} + + {!progress.showStreamingArea && !!progress.streamPendingTools.length && ( + + )} + + ) +}) + +const TranscriptPane = memo(function TranscriptPane({ + actions, + composer, + progress, + transcript +}: Pick) { + const ui = useStore($uiState) + + return ( + <> + + + {transcript.virtualHistory.topSpacer > 0 ? : null} + + {transcript.virtualRows.slice(transcript.virtualHistory.start, transcript.virtualHistory.end).map(row => ( + + {row.msg.kind === 'intro' ? ( + + + + {row.msg.info?.version && } + + ) : row.msg.kind === 'panel' && row.msg.panelData ? ( + + ) : ( + + )} + + ))} + + {transcript.virtualHistory.bottomSpacer > 0 ? : null} + + + + + + + + + + + + ) +}) + +const ComposerPane = memo(function ComposerPane({ + actions, + composer, + status +}: Pick) { + const ui = useStore($uiState) + const isBlocked = useStore($isBlocked) + const sh = (composer.inputBuf[0] ?? composer.input).startsWith('!') + const pw = sh ? 2 : 3 + + return ( + + + + {ui.bgTasks.size > 0 && ( + + {ui.bgTasks.size} background {ui.bgTasks.size === 1 ? 'task' : 'tasks'} running + + )} + + {status.showStickyPrompt ? ( + + + + {status.stickyPrompt} + + ) : ( + + )} + + + {ui.statusBar && ( + + )} + + + + + {!isBlocked && ( + + {composer.inputBuf.map((line, i) => ( + + + {i === 0 ? `${ui.theme.brand.prompt} ` : ' '} + + + {line || ' '} + + ))} + + + + {sh ? ( + $ + ) : ( + + {composer.inputBuf.length ? ' ' : `${ui.theme.brand.prompt} `} + + )} + + + + + + + + + + + + )} + + {!composer.empty && !ui.sid && ⚕ {ui.status}} + + ) +}) + +export const AppLayout = memo(function AppLayout({ + actions, + composer, + mouseTracking, + progress, + status, + transcript +}: AppLayoutProps) { + return ( + + + + + + + + + + + + ) +}) + +interface StreamingAssistantProps { + busy: boolean + cols: number + compact?: boolean + detailsMode: DetailsMode + progress: AppLayoutProgressProps + t: Theme +} diff --git a/ui-tui/src/components/appOverlays.tsx b/ui-tui/src/components/appOverlays.tsx new file mode 100644 index 0000000000..23187cf3f9 --- /dev/null +++ b/ui-tui/src/components/appOverlays.tsx @@ -0,0 +1,170 @@ +import { Box, Text } from '@hermes/ink' +import { useStore } from '@nanostores/react' + +import { useGateway } from '../app/gatewayContext.js' +import type { AppOverlaysProps } from '../app/interfaces.js' +import { $overlayState, patchOverlayState } from '../app/overlayStore.js' +import { $uiState } from '../app/uiStore.js' + +import { FloatBox } from './appChrome.js' +import { MaskedPrompt } from './maskedPrompt.js' +import { ModelPicker } from './modelPicker.js' +import { ApprovalPrompt, ClarifyPrompt } from './prompts.js' +import { SessionPicker } from './sessionPicker.js' + +export function PromptZone({ + cols, + onApprovalChoice, + onClarifyAnswer, + onSecretSubmit, + onSudoSubmit +}: Pick) { + const overlay = useStore($overlayState) + const ui = useStore($uiState) + + if (overlay.approval) { + return ( + + + + ) + } + + if (overlay.clarify) { + return ( + + onClarifyAnswer('')} + req={overlay.clarify} + t={ui.theme} + /> + + ) + } + + if (overlay.sudo) { + return ( + + + + ) + } + + if (overlay.secret) { + return ( + + + + ) + } + + return null +} + +export function FloatingOverlays({ + cols, + compIdx, + completions, + onModelSelect, + onPickerSelect, + pagerPageSize +}: Pick) { + const { gw } = useGateway() + const overlay = useStore($overlayState) + const ui = useStore($uiState) + + const hasAny = overlay.modelPicker || overlay.pager || overlay.picker || completions.length + + if (!hasAny) { + return null + } + + const start = Math.max(0, compIdx - 8) + + return ( + + {overlay.picker && ( + + patchOverlayState({ picker: false })} + onSelect={onPickerSelect} + t={ui.theme} + /> + + )} + + {overlay.modelPicker && ( + + patchOverlayState({ modelPicker: false })} + onSelect={onModelSelect} + sessionId={ui.sid} + t={ui.theme} + /> + + )} + + {overlay.pager && ( + + + {overlay.pager.title && ( + + + {overlay.pager.title} + + + )} + + {overlay.pager.lines.slice(overlay.pager.offset, overlay.pager.offset + pagerPageSize).map((line, i) => ( + {line} + ))} + + + + {overlay.pager.offset + pagerPageSize < overlay.pager.lines.length + ? `Enter/Space for more · q to close (${Math.min(overlay.pager.offset + pagerPageSize, overlay.pager.lines.length)}/${overlay.pager.lines.length})` + : `end · q to close (${overlay.pager.lines.length} lines)`} + + + + + )} + + {!!completions.length && ( + + + {completions.slice(start, compIdx + 8).map((item, i) => { + const active = start + i === compIdx + + return ( + + + {' '} + {item.display} + + {item.meta ? {item.meta} : null} + + ) + })} + + + )} + + ) +} diff --git a/ui-tui/src/components/branding.tsx b/ui-tui/src/components/branding.tsx new file mode 100644 index 0000000000..fc019ac86f --- /dev/null +++ b/ui-tui/src/components/branding.tsx @@ -0,0 +1,206 @@ +import { Box, Text, useStdout } from '@hermes/ink' + +import { artWidth, caduceus, CADUCEUS_WIDTH, logo, LOGO_WIDTH } from '../banner.js' +import { flat } from '../lib/text.js' +import type { Theme } from '../theme.js' +import type { PanelSection, SessionInfo } from '../types.js' + +export function ArtLines({ lines }: { lines: [string, string][] }) { + return ( + <> + {lines.map(([c, text], i) => ( + + {text} + + ))} + + ) +} + +export function Banner({ t }: { t: Theme }) { + const cols = useStdout().stdout?.columns ?? 80 + const logoLines = logo(t.color, t.bannerLogo || undefined) + + return ( + + {cols >= (t.bannerLogo ? artWidth(logoLines) : LOGO_WIDTH) ? ( + + ) : ( + + {t.brand.icon} NOUS HERMES + + )} + + {t.brand.icon} Nous Research · Messenger of the Digital Gods + + ) +} + +export function SessionPanel({ info, sid, t }: SessionPanelProps) { + const cols = useStdout().stdout?.columns ?? 100 + const heroLines = caduceus(t.color, t.bannerHero || undefined) + const leftW = Math.min((artWidth(heroLines) || CADUCEUS_WIDTH) + 4, Math.floor(cols * 0.4)) + const wide = cols >= 90 && leftW + 40 < cols + const w = Math.max(20, wide ? cols - leftW - 14 : cols - 12) + const lineBudget = Math.max(12, w - 2) + const strip = (s: string) => (s.endsWith('_tools') ? s.slice(0, -6) : s) + + const truncLine = (pfx: string, items: string[]) => { + let line = '' + let shown = 0 + + for (const item of [...items].sort()) { + const next = line ? `${line}, ${item}` : item + + if (pfx.length + next.length > lineBudget) { + return line ? `${line}, …+${items.length - shown}` : `${item}, …` + } + + line = next + shown++ + } + + return line + } + + const section = (title: string, data: Record, max = 8, overflowLabel = 'more…') => { + const entries = Object.entries(data).sort() + const shown = entries.slice(0, max) + const overflow = entries.length - max + + return ( + + + Available {title} + + + {shown.map(([k, vs]) => ( + + {strip(k)}: + {truncLine(strip(k) + ': ', vs)} + + ))} + + {overflow > 0 && ( + + (and {overflow} {overflowLabel}) + + )} + + ) + } + + return ( + + {wide && ( + + + + + + {info.model.split('/').pop()} + · Nous Research + + + + {info.cwd || process.cwd()} + + + {sid && ( + + Session: + {sid} + + )} + + )} + + + + + {t.brand.name} + {info.version ? ` v${info.version}` : ''} + {info.release_date ? ` (${info.release_date})` : ''} + + + + {section('Tools', info.tools, 8, 'more toolsets…')} + {section('Skills', info.skills)} + + + + {flat(info.tools).length} tools{' · '} + {flat(info.skills).length} skills + {' · '} + /help for commands + + + {typeof info.update_behind === 'number' && info.update_behind > 0 && ( + + ! {info.update_behind} {info.update_behind === 1 ? 'commit' : 'commits'} behind + + {' '} + - run{' '} + + + {info.update_command || 'hermes update'} + + + {' '} + to update + + + )} + + + ) +} + +export function Panel({ sections, t, title }: PanelProps) { + return ( + + + + {title} + + + + {sections.map((sec, si) => ( + 0 ? 1 : 0}> + {sec.title && ( + + {sec.title} + + )} + + {sec.rows?.map(([k, v], ri) => ( + + {k.padEnd(20)} + {v} + + ))} + + {sec.items?.map((item, ii) => ( + + {item} + + ))} + + {sec.text && {sec.text}} + + ))} + + ) +} + +interface PanelProps { + sections: PanelSection[] + t: Theme + title: string +} + +interface SessionPanelProps { + info: SessionInfo + sid?: string | null + t: Theme +} diff --git a/ui-tui/src/components/markdown.tsx b/ui-tui/src/components/markdown.tsx new file mode 100644 index 0000000000..865ab85796 --- /dev/null +++ b/ui-tui/src/components/markdown.tsx @@ -0,0 +1,590 @@ +import { Box, Text } from '@hermes/ink' +import { memo, type ReactNode, useMemo } from 'react' + +import type { Theme } from '../theme.js' + +const FENCE_RE = /^\s*(`{3,}|~{3,})(.*)$/ +const HR_RE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/ +const HEADING_RE = /^\s{0,3}(#{1,6})\s+(.*?)(?:\s+#+\s*)?$/ +const FOOTNOTE_RE = /^\[\^([^\]]+)\]:\s*(.*)$/ +const DEF_RE = /^\s*:\s+(.+)$/ +const TABLE_DIVIDER_CELL_RE = /^:?-{3,}:?$/ +const MD_URL_RE = '((?:[^\\s()]|\\([^\\s()]*\\))+?)' + +const INLINE_RE = new RegExp( + `(!\\[(.*?)\\]\\(${MD_URL_RE}\\)|\\[(.+?)\\]\\(${MD_URL_RE}\\)|<((?:https?:\\/\\/|mailto:)[^>\\s]+|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,})>|~~(.+?)~~|\`([^\\\`]+)\`|\\*\\*(.+?)\\*\\*|__(.+?)__|\\*(.+?)\\*|_(.+?)_|==(.+?)==|\\[\\^([^\\]]+)\\]|\\^([^^\\s][^^]*?)\\^|~([^~\\s][^~]*?)~|(https?:\\/\\/[^\\s<]+))`, + 'g' +) + +type Fence = { + char: '`' | '~' + lang: string + len: number +} + +const renderLink = (key: number, t: Theme, label: string) => ( + + {label} + +) + +const trimBareUrl = (value: string) => { + const trimmed = value.replace(/[),.;:!?]+$/g, '') + + return { + tail: value.slice(trimmed.length), + url: trimmed + } +} + +const renderAutolink = (key: number, t: Theme, raw: string) => ( + + {raw.replace(/^mailto:/, '')} + +) + +const indentDepth = (indent: string) => Math.floor(indent.replace(/\t/g, ' ').length / 2) + +const parseFence = (line: string): Fence | null => { + const m = line.match(FENCE_RE) + + if (!m) { + return null + } + + return { + char: m[1]![0] as '`' | '~', + lang: m[2]!.trim().toLowerCase(), + len: m[1]!.length + } +} + +const isFenceClose = (line: string, fence: Fence) => { + const end = line.match(/^\s*(`{3,}|~{3,})\s*$/) + + return Boolean(end && end[1]![0] === fence.char && end[1]!.length >= fence.len) +} + +const isMarkdownFence = (lang: string) => ['md', 'markdown'].includes(lang) + +const splitTableRow = (row: string) => + row + .trim() + .replace(/^\|/, '') + .replace(/\|$/, '') + .split('|') + .map(cell => cell.trim()) + +const isTableDivider = (row: string) => { + const cells = splitTableRow(row) + + return cells.length > 1 && cells.every(cell => TABLE_DIVIDER_CELL_RE.test(cell)) +} + +const stripInlineMarkup = (value: string) => + value + .replace(/!\[(.*?)\]\(((?:[^\s()]|\([^\s()]*\))+?)\)/g, '[image: $1] $2') + .replace(/\[(.+?)\]\(((?:[^\s()]|\([^\s()]*\))+?)\)/g, '$1') + .replace(/<((?:https?:\/\/|mailto:)[^>\s]+|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})>/g, '$1') + .replace(/~~(.+?)~~/g, '$1') + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*(.+?)\*\*/g, '$1') + .replace(/__(.+?)__/g, '$1') + .replace(/\*(.+?)\*/g, '$1') + .replace(/_(.+?)_/g, '$1') + .replace(/==(.+?)==/g, '$1') + .replace(/\[\^([^\]]+)\]/g, '[$1]') + .replace(/\^([^^\s][^^]*?)\^/g, '^$1') + .replace(/~([^~\s][^~]*?)~/g, '_$1') + +const renderTable = (key: number, rows: string[][], t: Theme) => { + const widths = rows[0]!.map((_, ci) => Math.max(...rows.map(r => stripInlineMarkup(r[ci] ?? '').length))) + + return ( + + {rows.map((row, ri) => ( + + {widths.map((width, ci) => { + const cell = row[ci] ?? '' + const pad = ' '.repeat(Math.max(0, width - stripInlineMarkup(cell).length)) + + return ( + + + {pad} + {ci < widths.length - 1 ? ' ' : ''} + + ) + })} + + ))} + + ) +} + +function MdInline({ t, text }: { t: Theme; text: string }) { + const parts: ReactNode[] = [] + + let last = 0 + + for (const m of text.matchAll(INLINE_RE)) { + const i = m.index ?? 0 + + if (i > last) { + parts.push({text.slice(last, i)}) + } + + if (m[2] && m[3]) { + parts.push( + + [image: {m[2]}] {m[3]} + + ) + } else if (m[4] && m[5]) { + parts.push(renderLink(parts.length, t, m[4])) + } else if (m[6]) { + parts.push(renderAutolink(parts.length, t, m[6])) + } else if (m[7]) { + parts.push( + + {m[7]} + + ) + } else if (m[8]) { + parts.push( + + {m[8]} + + ) + } else if (m[9] || m[10]) { + parts.push( + + {m[9] ?? m[10]} + + ) + } else if (m[11] || m[12]) { + parts.push( + + {m[11] ?? m[12]} + + ) + } else if (m[13]) { + parts.push( + + {m[13]} + + ) + } else if (m[14]) { + parts.push( + + [{m[14]}] + + ) + } else if (m[15]) { + parts.push( + + ^{m[15]} + + ) + } else if (m[16]) { + parts.push( + + _{m[16]} + + ) + } else if (m[17]) { + const { tail, url } = trimBareUrl(m[17]) + + parts.push(renderAutolink(parts.length, t, url)) + + if (tail) { + parts.push({tail}) + } + } + + last = i + m[0].length + } + + if (last < text.length) { + parts.push({text.slice(last)}) + } + + return {parts.length ? parts : {text}} +} + +interface MdProps { + compact?: boolean + t: Theme + text: string +} + +function MdImpl({ compact, t, text }: MdProps) { + const nodes = useMemo(() => { + const lines = text.split('\n') + const nodes: ReactNode[] = [] + let i = 0 + + let prevKind: 'blank' | 'code' | 'heading' | 'list' | 'paragraph' | 'quote' | 'rule' | 'table' | null = null + + const gap = () => { + if (nodes.length && prevKind !== 'blank') { + nodes.push( ) + prevKind = 'blank' + } + } + + const start = (kind: Exclude) => { + if (prevKind && prevKind !== 'blank' && prevKind !== kind) { + gap() + } + + prevKind = kind + } + + while (i < lines.length) { + const line = lines[i]! + const key = nodes.length + + if (compact && !line.trim()) { + i++ + + continue + } + + if (!line.trim()) { + gap() + i++ + + continue + } + + const fence = parseFence(line) + + if (fence) { + const block: string[] = [] + const lang = fence.lang + + for (i++; i < lines.length && !isFenceClose(lines[i]!, fence); i++) { + block.push(lines[i]!) + } + + if (i < lines.length) { + i++ + } + + if (isMarkdownFence(lang)) { + start('paragraph') + nodes.push() + + continue + } + + start('code') + + const isDiff = lang === 'diff' + + nodes.push( + + {lang && !isDiff && {'─ ' + lang}} + {block.map((l, j) => { + const add = isDiff && l.startsWith('+') + const del = isDiff && l.startsWith('-') + const hunk = isDiff && l.startsWith('@@') + + return ( + + {l} + + ) + })} + + ) + + continue + } + + if (line.trim().startsWith('$$')) { + start('code') + + const block: string[] = [] + + for (i++; i < lines.length; i++) { + if (lines[i]!.trim().startsWith('$$')) { + i++ + + break + } + + block.push(lines[i]!) + } + + nodes.push( + + ─ math + {block.map((l, j) => ( + + {l} + + ))} + + ) + + continue + } + + const heading = line.match(HEADING_RE) + + if (heading) { + start('heading') + nodes.push( + + {heading[2]} + + ) + i++ + + continue + } + + if (i + 1 < lines.length && line.trim()) { + const setext = lines[i + 1]!.match(/^\s{0,3}(=+|-+)\s*$/) + + if (setext) { + start('heading') + nodes.push( + + {line.trim()} + + ) + i += 2 + + continue + } + } + + if (HR_RE.test(line)) { + start('rule') + nodes.push( + + {'─'.repeat(36)} + + ) + i++ + + continue + } + + const footnote = line.match(FOOTNOTE_RE) + + if (footnote) { + start('list') + nodes.push( + + [{footnote[1]}] + + ) + i++ + + while (i < lines.length && /^\s{2,}\S/.test(lines[i]!)) { + nodes.push( + + + + + + ) + i++ + } + + continue + } + + if (i + 1 < lines.length && DEF_RE.test(lines[i + 1]!)) { + start('list') + nodes.push( + + {line.trim()} + + ) + i++ + + while (i < lines.length) { + const def = lines[i]!.match(DEF_RE) + + if (!def) { + break + } + + nodes.push( + + · + + + ) + i++ + } + + continue + } + + const bullet = line.match(/^(\s*)[-+*]\s+(.*)$/) + + if (bullet) { + start('list') + const depth = indentDepth(bullet[1]!) + const task = bullet[2]!.match(/^\[( |x|X)\]\s+(.*)$/) + const marker = task ? (task[1]!.toLowerCase() === 'x' ? '☑' : '☐') : '•' + const body = task ? task[2]! : bullet[2]! + + nodes.push( + + + {' '.repeat(depth * 2)} + {marker}{' '} + + + + ) + i++ + + continue + } + + const numbered = line.match(/^(\s*)(\d+)[.)]\s+(.*)$/) + + if (numbered) { + start('list') + const depth = indentDepth(numbered[1]!) + + nodes.push( + + + {' '.repeat(depth * 2)} + {numbered[2]}.{' '} + + + + ) + i++ + + continue + } + + if (/^\s*(?:>\s*)+/.test(line)) { + start('quote') + const quoteLines: Array<{ depth: number; text: string }> = [] + + while (i < lines.length && /^\s*(?:>\s*)+/.test(lines[i]!)) { + const raw = lines[i]! + const prefix = raw.match(/^\s*(?:>\s*)+/)?.[0] ?? '' + + quoteLines.push({ + depth: (prefix.match(/>/g) ?? []).length, + text: raw.slice(prefix.length) + }) + i++ + } + + nodes.push( + + {quoteLines.map((ql, qi) => ( + + {' '.repeat(Math.max(0, ql.depth - 1) * 2)} + {'│ '} + + + ))} + + ) + + continue + } + + if (line.includes('|') && i + 1 < lines.length && isTableDivider(lines[i + 1]!)) { + start('table') + const tableRows: string[][] = [] + + tableRows.push(splitTableRow(line)) + i += 2 + + while (i < lines.length && lines[i]!.includes('|') && lines[i]!.trim()) { + tableRows.push(splitTableRow(lines[i]!)) + i++ + } + + nodes.push(renderTable(key, tableRows, t)) + + continue + } + + if (/^/i.test(line)) { + i++ + + continue + } + + const summary = line.match(/^(.*?)<\/summary>$/i) + + if (summary) { + start('paragraph') + nodes.push( + + ▶ {summary[1]} + + ) + i++ + + continue + } + + if (/^<\/?[^>]+>$/.test(line.trim())) { + start('paragraph') + nodes.push( + + {line.trim()} + + ) + i++ + + continue + } + + if (line.includes('|') && line.trim().startsWith('|')) { + start('table') + const tableRows: string[][] = [] + + while (i < lines.length && lines[i]!.trim().startsWith('|')) { + const row = lines[i]!.trim() + + if (!/^[|\s:-]+$/.test(row)) { + tableRows.push(splitTableRow(row)) + } + + i++ + } + + if (tableRows.length) { + nodes.push(renderTable(key, tableRows, t)) + } + + continue + } + + start('paragraph') + nodes.push() + + i++ + } + + return nodes + }, [compact, t, text]) + + return {nodes} +} + +export const Md = memo(MdImpl) diff --git a/ui-tui/src/components/maskedPrompt.tsx b/ui-tui/src/components/maskedPrompt.tsx new file mode 100644 index 0000000000..3739326bcc --- /dev/null +++ b/ui-tui/src/components/maskedPrompt.tsx @@ -0,0 +1,34 @@ +import { Box, Text } from '@hermes/ink' +import { useState } from 'react' + +import type { Theme } from '../theme.js' + +import { TextInput } from './textInput.js' + +export function MaskedPrompt({ cols = 80, icon, label, onSubmit, sub, t }: MaskedPromptProps) { + const [value, setValue] = useState('') + + return ( + + + {icon} {label} + + + {sub && {sub}} + + + {'> '} + + + + ) +} + +interface MaskedPromptProps { + cols?: number + icon: string + label: string + onSubmit: (v: string) => void + sub?: string + t: Theme +} diff --git a/ui-tui/src/components/messageLine.tsx b/ui-tui/src/components/messageLine.tsx new file mode 100644 index 0000000000..59db604e4b --- /dev/null +++ b/ui-tui/src/components/messageLine.tsx @@ -0,0 +1,114 @@ +import { Ansi, Box, NoSelect, Text } from '@hermes/ink' +import { memo } from 'react' + +import { LONG_MSG } from '../config/limits.js' +import { userDisplay } from '../domain/messages.js' +import { ROLE } from '../domain/roles.js' +import { compactPreview, hasAnsi, isPasteBackedText, stripAnsi } from '../lib/text.js' +import type { Theme } from '../theme.js' +import type { DetailsMode, Msg } from '../types.js' + +import { Md } from './markdown.js' +import { ToolTrail } from './thinking.js' + +export const MessageLine = memo(function MessageLine({ + cols, + compact, + detailsMode = 'collapsed', + isStreaming = false, + msg, + t +}: MessageLineProps) { + if (msg.kind === 'trail' && msg.tools?.length) { + return detailsMode === 'hidden' ? null : ( + + + + ) + } + + if (msg.role === 'tool') { + return ( + + + {compactPreview(hasAnsi(msg.text) ? stripAnsi(msg.text) : msg.text, Math.max(24, cols - 14)) || + '(empty tool result)'} + + + ) + } + + const { body, glyph, prefix } = ROLE[msg.role](t) + const thinking = msg.thinking?.trim() ?? '' + const showDetails = detailsMode !== 'hidden' && (Boolean(msg.tools?.length) || Boolean(thinking)) + + const content = (() => { + if (msg.kind === 'slash') { + return {msg.text} + } + + if (msg.role !== 'user' && hasAnsi(msg.text)) { + return {msg.text} + } + + if (msg.role === 'assistant') { + return isStreaming ? {msg.text} : + } + + if (msg.role === 'user' && msg.text.length > LONG_MSG && isPasteBackedText(msg.text)) { + const [head, ...rest] = userDisplay(msg.text).split('[long message]') + + return ( + + {head} + + [long message] + + {rest.join('')} + + ) + } + + return {msg.text} + })() + + return ( + + {showDetails && ( + + + + )} + + + + + {glyph}{' '} + + + + {content} + + + ) +}) + +interface MessageLineProps { + cols: number + compact?: boolean + detailsMode?: DetailsMode + isStreaming?: boolean + msg: Msg + t: Theme +} diff --git a/ui-tui/src/components/modelPicker.tsx b/ui-tui/src/components/modelPicker.tsx new file mode 100644 index 0000000000..10a00cdf19 --- /dev/null +++ b/ui-tui/src/components/modelPicker.tsx @@ -0,0 +1,235 @@ +import { Box, Text, useInput } from '@hermes/ink' +import { useEffect, useState } from 'react' + +import type { GatewayClient } from '../gatewayClient.js' +import type { ModelOptionProvider, ModelOptionsResponse } from '../gatewayTypes.js' +import { asRpcResult, rpcErrorMessage } from '../lib/rpc.js' +import type { Theme } from '../theme.js' + +const VISIBLE = 12 + +const pageOffset = (count: number, sel: number) => Math.max(0, Math.min(sel - Math.floor(VISIBLE / 2), count - VISIBLE)) + +const visibleItems = (items: string[], sel: number) => { + const off = pageOffset(items.length, sel) + + return { items: items.slice(off, off + VISIBLE), off } +} + +export function ModelPicker({ gw, onCancel, onSelect, sessionId, t }: ModelPickerProps) { + const [providers, setProviders] = useState([]) + const [currentModel, setCurrentModel] = useState('') + const [err, setErr] = useState('') + const [loading, setLoading] = useState(true) + const [persistGlobal, setPersistGlobal] = useState(false) + const [providerIdx, setProviderIdx] = useState(0) + const [modelIdx, setModelIdx] = useState(0) + const [stage, setStage] = useState<'model' | 'provider'>('provider') + + useEffect(() => { + gw.request('model.options', sessionId ? { session_id: sessionId } : {}) + .then(raw => { + const r = asRpcResult(raw) + + if (!r) { + setErr('invalid response: model.options') + setLoading(false) + + return + } + + const next = r.providers ?? [] + setProviders(next) + setCurrentModel(String(r.model ?? '')) + setProviderIdx( + Math.max( + 0, + next.findIndex(p => p.is_current) + ) + ) + setModelIdx(0) + setErr('') + setLoading(false) + }) + .catch((e: unknown) => { + setErr(rpcErrorMessage(e)) + setLoading(false) + }) + }, [gw, sessionId]) + + const provider = providers[providerIdx] + const models = provider?.models ?? [] + + useInput((ch, key) => { + if (key.escape) { + if (stage === 'model') { + setStage('provider') + setModelIdx(0) + + return + } + + onCancel() + + return + } + + const count = stage === 'provider' ? providers.length : models.length + const sel = stage === 'provider' ? providerIdx : modelIdx + const setSel = stage === 'provider' ? setProviderIdx : setModelIdx + + if (key.upArrow && sel > 0) { + setSel(v => v - 1) + + return + } + + if (key.downArrow && sel < count - 1) { + setSel(v => v + 1) + + return + } + + if (key.return) { + if (stage === 'provider') { + if (!provider) { + return + } + + setStage('model') + setModelIdx(0) + + return + } + + const model = models[modelIdx] + + if (provider && model) { + onSelect(`${model} --provider ${provider.slug}${persistGlobal ? ' --global' : ''}`) + } else { + setStage('provider') + } + + return + } + + if (ch.toLowerCase() === 'g') { + setPersistGlobal(v => !v) + + return + } + + const n = ch === '0' ? 10 : parseInt(ch, 10) + + if (!Number.isNaN(n) && n >= 1 && n <= Math.min(10, count)) { + const off = pageOffset(count, sel) + + if (stage === 'provider') { + const next = off + n - 1 + + if (providers[next]) { + setProviderIdx(next) + } + } else if (provider && models[off + n - 1]) { + onSelect(`${models[off + n - 1]} --provider ${provider.slug}${persistGlobal ? ' --global' : ''}`) + } + } + }) + + if (loading) { + return loading models… + } + + if (err) { + return ( + + error: {err} + Esc to cancel + + ) + } + + if (!providers.length) { + return ( + + no authenticated providers + Esc to cancel + + ) + } + + if (stage === 'provider') { + const rows = providers.map( + p => `${p.is_current ? '*' : ' '} ${p.name} · ${p.total_models ?? p.models?.length ?? 0} models` + ) + + const { items, off } = visibleItems(rows, providerIdx) + + return ( + + + Select Provider + + + Current model: {currentModel || '(unknown)'} + {provider?.warning ? warning: {provider.warning} : null} + {off > 0 && ↑ {off} more} + + {items.map((row, i) => { + const idx = off + i + + return ( + + {providerIdx === idx ? '▸ ' : ' '} + {i + 1}. {row} + + ) + })} + + {off + VISIBLE < rows.length && ↓ {rows.length - off - VISIBLE} more} + persist: {persistGlobal ? 'global' : 'session'} · g toggle + ↑/↓ select · Enter choose · 1-9,0 quick · Esc cancel + + ) + } + + const { items, off } = visibleItems(models, modelIdx) + + return ( + + + Select Model + + + {provider?.name || '(unknown provider)'} + {!models.length ? no models listed for this provider : null} + {provider?.warning ? warning: {provider.warning} : null} + {off > 0 && ↑ {off} more} + + {items.map((row, i) => { + const idx = off + i + + return ( + + {modelIdx === idx ? '▸ ' : ' '} + {i + 1}. {row} + + ) + })} + + {off + VISIBLE < models.length && ↓ {models.length - off - VISIBLE} more} + persist: {persistGlobal ? 'global' : 'session'} · g toggle + + {models.length ? '↑/↓ select · Enter switch · 1-9,0 quick · Esc back' : 'Enter/Esc back'} + + + ) +} + +interface ModelPickerProps { + gw: GatewayClient + onCancel: () => void + onSelect: (value: string) => void + sessionId: string | null + t: Theme +} diff --git a/ui-tui/src/components/prompts.tsx b/ui-tui/src/components/prompts.tsx new file mode 100644 index 0000000000..98aba0789b --- /dev/null +++ b/ui-tui/src/components/prompts.tsx @@ -0,0 +1,148 @@ +import { Box, Text, useInput } from '@hermes/ink' +import { useState } from 'react' + +import type { Theme } from '../theme.js' +import type { ApprovalReq, ClarifyReq } from '../types.js' + +import { TextInput } from './textInput.js' + +const OPTS = ['once', 'session', 'always', 'deny'] as const +const LABELS = { always: 'Always allow', deny: 'Deny', once: 'Allow once', session: 'Allow this session' } as const + +export function ApprovalPrompt({ onChoice, req, t }: ApprovalPromptProps) { + const [sel, setSel] = useState(0) + + useInput((ch, key) => { + if (key.upArrow && sel > 0) { + setSel(s => s - 1) + } + + if (key.downArrow && sel < OPTS.length - 1) { + setSel(s => s + 1) + } + + const n = parseInt(ch, 10) + + if (n >= 1 && n <= OPTS.length) { + onChoice(OPTS[n - 1]!) + + return + } + + if (key.return) { + onChoice(OPTS[sel]!) + } + }) + + return ( + + + ⚠ approval required · {req.description} + + + {req.command} + + + {OPTS.map((o, i) => ( + + {sel === i ? '▸ ' : ' '} + + {i + 1}. {LABELS[o]} + + + ))} + + ↑/↓ select · Enter confirm · 1-4 quick pick · Ctrl+C deny + + ) +} + +export function ClarifyPrompt({ cols = 80, onAnswer, onCancel, req, t }: ClarifyPromptProps) { + const [sel, setSel] = useState(0) + const [custom, setCustom] = useState('') + const [typing, setTyping] = useState(false) + const choices = req.choices ?? [] + + const heading = ( + + ask + {req.question} + + ) + + useInput((ch, key) => { + if (key.escape) { + typing && choices.length ? setTyping(false) : onCancel() + + return + } + + if (typing || !choices.length) { + return + } + + if (key.upArrow && sel > 0) { + setSel(s => s - 1) + } + + if (key.downArrow && sel < choices.length) { + setSel(s => s + 1) + } + + if (key.return) { + sel === choices.length ? setTyping(true) : choices[sel] && onAnswer(choices[sel]!) + } + + const n = parseInt(ch) + + if (n >= 1 && n <= choices.length) { + onAnswer(choices[n - 1]!) + } + }) + + if (typing || !choices.length) { + return ( + + {heading} + + + {'> '} + + + + Enter send · Esc {choices.length ? 'back' : 'cancel'} · Ctrl+C cancel + + ) + } + + return ( + + {heading} + + {[...choices, 'Other (type your answer)'].map((c, i) => ( + + {sel === i ? '▸ ' : ' '} + + {i + 1}. {c} + + + ))} + + ↑/↓ select · Enter confirm · 1-{choices.length} quick pick · Esc/Ctrl+C cancel + + ) +} + +interface ApprovalPromptProps { + onChoice: (s: string) => void + req: ApprovalReq + t: Theme +} + +interface ClarifyPromptProps { + cols?: number + onAnswer: (s: string) => void + onCancel: () => void + req: ClarifyReq + t: Theme +} diff --git a/ui-tui/src/components/queuedMessages.tsx b/ui-tui/src/components/queuedMessages.tsx new file mode 100644 index 0000000000..ab9c42c551 --- /dev/null +++ b/ui-tui/src/components/queuedMessages.tsx @@ -0,0 +1,62 @@ +import { Box, Text } from '@hermes/ink' + +import { compactPreview } from '../lib/text.js' +import type { Theme } from '../theme.js' + +export const QUEUE_WINDOW = 3 + +export function getQueueWindow(queueLen: number, queueEditIdx: number | null) { + const start = + queueEditIdx === null ? 0 : Math.max(0, Math.min(queueEditIdx - 1, Math.max(0, queueLen - QUEUE_WINDOW))) + + const end = Math.min(queueLen, start + QUEUE_WINDOW) + + return { end, showLead: start > 0, showTail: end < queueLen, start } +} + +export function QueuedMessages({ cols, queueEditIdx, queued, t }: QueuedMessagesProps) { + if (!queued.length) { + return null + } + + const q = getQueueWindow(queued.length, queueEditIdx) + + return ( + + + queued ({queued.length}){queueEditIdx !== null ? ` · editing ${queueEditIdx + 1}` : ''} + + + {q.showLead && ( + + {' '} + … + + )} + + {queued.slice(q.start, q.end).map((item, i) => { + const idx = q.start + i + const active = queueEditIdx === idx + + return ( + + {active ? '▸' : ' '} {idx + 1}. {compactPreview(item, Math.max(16, cols - 10))} + + ) + })} + + {q.showTail && ( + + {' '}…and {queued.length - q.end} more + + )} + + ) +} + +interface QueuedMessagesProps { + cols: number + queueEditIdx: number | null + queued: string[] + t: Theme +} diff --git a/ui-tui/src/components/sessionPicker.tsx b/ui-tui/src/components/sessionPicker.tsx new file mode 100644 index 0000000000..905fa707e3 --- /dev/null +++ b/ui-tui/src/components/sessionPicker.tsx @@ -0,0 +1,144 @@ +import { Box, Text, useInput } from '@hermes/ink' +import { useEffect, useState } from 'react' + +import type { GatewayClient } from '../gatewayClient.js' +import type { SessionListItem, SessionListResponse } from '../gatewayTypes.js' +import { asRpcResult, rpcErrorMessage } from '../lib/rpc.js' +import type { Theme } from '../theme.js' + +const VISIBLE = 15 + +const age = (ts: number) => { + const d = (Date.now() / 1000 - ts) / 86400 + + if (d < 1) { + return 'today' + } + + if (d < 2) { + return 'yesterday' + } + + return `${Math.floor(d)}d ago` +} + +export function SessionPicker({ gw, onCancel, onSelect, t }: SessionPickerProps) { + const [items, setItems] = useState([]) + const [err, setErr] = useState('') + const [sel, setSel] = useState(0) + const [loading, setLoading] = useState(true) + + useEffect(() => { + gw.request('session.list', { limit: 20 }) + .then(raw => { + const r = asRpcResult(raw) + + if (!r) { + setErr('invalid response: session.list') + setLoading(false) + + return + } + + setItems(r.sessions ?? []) + setErr('') + setLoading(false) + }) + .catch((e: unknown) => { + setErr(rpcErrorMessage(e)) + setLoading(false) + }) + }, [gw]) + + useInput((ch, key) => { + if (key.escape) { + return onCancel() + } + + if (key.upArrow && sel > 0) { + setSel(s => s - 1) + } + + if (key.downArrow && sel < items.length - 1) { + setSel(s => s + 1) + } + + if (key.return && items[sel]) { + onSelect(items[sel]!.id) + } + + const n = parseInt(ch) + + if (n >= 1 && n <= Math.min(9, items.length)) { + onSelect(items[n - 1]!.id) + } + }) + + if (loading) { + return loading sessions… + } + + if (err) { + return ( + + error: {err} + Esc to cancel + + ) + } + + if (!items.length) { + return ( + + no previous sessions + Esc to cancel + + ) + } + + const off = Math.max(0, Math.min(sel - Math.floor(VISIBLE / 2), items.length - VISIBLE)) + + return ( + + + Resume Session + + + {off > 0 && ↑ {off} more} + + {items.slice(off, off + VISIBLE).map((s, vi) => { + const i = off + vi + + return ( + + {sel === i ? '▸ ' : ' '} + + + + {String(i + 1).padStart(2)}. [{s.id}] + + + + + + ({s.message_count} msgs, {age(s.started_at)}, {s.source || 'tui'}) + + + + {s.title || s.preview || '(untitled)'} + + ) + })} + + {off + VISIBLE < items.length && ↓ {items.length - off - VISIBLE} more} + ↑/↓ select · Enter resume · 1-9 quick · Esc cancel + + ) +} + +interface SessionPickerProps { + gw: GatewayClient + onCancel: () => void + onSelect: (id: string) => void + t: Theme +} diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsx new file mode 100644 index 0000000000..f2bbee63cf --- /dev/null +++ b/ui-tui/src/components/textInput.tsx @@ -0,0 +1,674 @@ +import type { InputEvent, Key } from '@hermes/ink' +import * as Ink from '@hermes/ink' +import { useEffect, useMemo, useRef, useState } from 'react' + +type InkExt = typeof Ink & { + stringWidth: (s: string) => number + useDeclaredCursor: (a: { line: number; column: number; active: boolean }) => (el: any) => void + useTerminalFocus: () => boolean +} + +const ink = Ink as unknown as InkExt +const { Box, Text, useStdin, useInput, stringWidth, useDeclaredCursor, useTerminalFocus } = ink + +const ESC = '\x1b' +const INV = `${ESC}[7m` +const INV_OFF = `${ESC}[27m` +const DIM = `${ESC}[2m` +const DIM_OFF = `${ESC}[22m` +const FWD_DEL_RE = new RegExp(`${ESC}\\[3(?:[~$^]|;)`) +const PRINTABLE = /^[ -~\u00a0-\uffff]+$/ +const BRACKET_PASTE = new RegExp(`${ESC}?\\[20[01]~`, 'g') + +const invert = (s: string) => INV + s + INV_OFF +const dim = (s: string) => DIM + s + DIM_OFF + +let _seg: Intl.Segmenter | null = null +const seg = () => (_seg ??= new Intl.Segmenter(undefined, { granularity: 'grapheme' })) +const STOP_CACHE_MAX = 32 +const stopCache = new Map() + +function graphemeStops(s: string) { + const hit = stopCache.get(s) + + if (hit) { + return hit + } + + const stops = [0] + + for (const { index } of seg().segment(s)) { + if (index > 0) { + stops.push(index) + } + } + + if (stops.at(-1) !== s.length) { + stops.push(s.length) + } + + stopCache.set(s, stops) + + if (stopCache.size > STOP_CACHE_MAX) { + const oldest = stopCache.keys().next().value + + if (oldest !== undefined) { + stopCache.delete(oldest) + } + } + + return stops +} + +function snapPos(s: string, p: number) { + const pos = Math.max(0, Math.min(p, s.length)) + let last = 0 + + for (const stop of graphemeStops(s)) { + if (stop > pos) { + break + } + + last = stop + } + + return last +} + +function prevPos(s: string, p: number) { + const pos = snapPos(s, p) + let prev = 0 + + for (const stop of graphemeStops(s)) { + if (stop >= pos) { + return prev + } + + prev = stop + } + + return prev +} + +function nextPos(s: string, p: number) { + const pos = snapPos(s, p) + + for (const stop of graphemeStops(s)) { + if (stop > pos) { + return stop + } + } + + return s.length +} + +function wordLeft(s: string, p: number) { + let i = snapPos(s, p) - 1 + + while (i > 0 && /\s/.test(s[i]!)) { + i-- + } + + while (i > 0 && !/\s/.test(s[i - 1]!)) { + i-- + } + + return Math.max(0, i) +} + +function wordRight(s: string, p: number) { + let i = snapPos(s, p) + + while (i < s.length && !/\s/.test(s[i]!)) { + i++ + } + + while (i < s.length && /\s/.test(s[i]!)) { + i++ + } + + return i +} + +function cursorLayout(value: string, cursor: number, cols: number) { + const pos = Math.max(0, Math.min(cursor, value.length)) + const w = Math.max(1, cols - 1) + + let col = 0, + line = 0 + + for (const { segment, index } of seg().segment(value)) { + if (index >= pos) { + break + } + + if (segment === '\n') { + line++ + col = 0 + + continue + } + + const sw = stringWidth(segment) + + if (!sw) { + continue + } + + if (col + sw > w) { + line++ + col = 0 + } + + col += sw + } + + return { column: col, line } +} + +function offsetFromPosition(value: string, row: number, col: number, cols: number) { + if (!value.length) { + return 0 + } + + const targetRow = Math.max(0, Math.floor(row)) + const targetCol = Math.max(0, Math.floor(col)) + const w = Math.max(1, cols - 1) + + let line = 0 + let column = 0 + let lastOffset = 0 + + for (const { segment, index } of seg().segment(value)) { + lastOffset = index + + if (segment === '\n') { + if (line === targetRow) { + return index + } + + line++ + column = 0 + + continue + } + + const sw = Math.max(1, stringWidth(segment)) + + if (column + sw > w) { + if (line === targetRow) { + return index + } + + line++ + column = 0 + } + + if (line === targetRow && targetCol <= column + Math.max(0, sw - 1)) { + return index + } + + column += sw + } + + if (targetRow >= line) { + return value.length + } + + return lastOffset +} + +function renderWithCursor(value: string, cursor: number) { + const pos = Math.max(0, Math.min(cursor, value.length)) + + let out = '', + done = false + + for (const { segment, index } of seg().segment(value)) { + if (!done && index >= pos) { + out += invert(index === pos && segment !== '\n' ? segment : ' ') + done = true + + if (index === pos && segment !== '\n') { + continue + } + } + + out += segment + } + + return done ? out : out + invert(' ') +} + +function renderWithSelection(value: string, start: number, end: number) { + if (start >= end) { + return value + } + + return value.slice(0, start) + invert(value.slice(start, end) || ' ') + value.slice(end) +} + +function useFwdDelete(active: boolean) { + const ref = useRef(false) + const { inputEmitter: ee } = useStdin() + + useEffect(() => { + if (!active) { + return + } + + const h = (d: string) => { + ref.current = FWD_DEL_RE.test(d) + } + + ee.prependListener('input', h) + + return () => { + ee.removeListener('input', h) + } + }, [active, ee]) + + return ref +} + +export function TextInput({ + columns = 80, + value, + onChange, + onPaste, + onSubmit, + mask, + placeholder = '', + focus = true +}: TextInputProps) { + const [cur, setCur] = useState(value.length) + const [sel, setSel] = useState(null) + const fwdDel = useFwdDelete(focus) + const termFocus = useTerminalFocus() + + const curRef = useRef(cur) + const selRef = useRef(null) + const vRef = useRef(value) + const self = useRef(false) + const pasteBuf = useRef('') + const pasteEnd = useRef(null) + const pasteTimer = useRef | null>(null) + const pastePos = useRef(0) + const undo = useRef<{ cursor: number; value: string }[]>([]) + const redo = useRef<{ cursor: number; value: string }[]>([]) + + const cbChange = useRef(onChange) + const cbSubmit = useRef(onSubmit) + const cbPaste = useRef(onPaste) + cbChange.current = onChange + cbSubmit.current = onSubmit + cbPaste.current = onPaste + + const raw = self.current ? vRef.current : value + const display = mask ? raw.replace(/[^\n]/g, mask[0] ?? '*') : raw + + const selected = useMemo( + () => + sel && sel.start !== sel.end ? { end: Math.max(sel.start, sel.end), start: Math.min(sel.start, sel.end) } : null, + [sel] + ) + + const layout = useMemo(() => cursorLayout(display, cur, columns), [columns, cur, display]) + + const boxRef = useDeclaredCursor({ + line: layout.line, + column: layout.column, + active: focus && termFocus && !selected + }) + + const rendered = useMemo(() => { + if (!focus) { + return display || dim(placeholder) + } + + if (!display && placeholder) { + return invert(placeholder[0] ?? ' ') + dim(placeholder.slice(1)) + } + + if (selected) { + return renderWithSelection(display, selected.start, selected.end) + } + + return renderWithCursor(display, cur) + }, [cur, display, focus, placeholder, selected]) + + useEffect(() => { + if (self.current) { + self.current = false + } else { + setCur(value.length) + setSel(null) + curRef.current = value.length + selRef.current = null + vRef.current = value + undo.current = [] + redo.current = [] + } + }, [value]) + + useEffect( + () => () => { + if (pasteTimer.current) { + clearTimeout(pasteTimer.current) + } + }, + [] + ) + + const commit = (next: string, nextCur: number, track = true) => { + const prev = vRef.current + const c = snapPos(next, nextCur) + + if (selRef.current) { + selRef.current = null + setSel(null) + } + + if (track && next !== prev) { + undo.current.push({ cursor: curRef.current, value: prev }) + + if (undo.current.length > 200) { + undo.current.shift() + } + + redo.current = [] + } + + setCur(c) + curRef.current = c + vRef.current = next + + if (next !== prev) { + self.current = true + cbChange.current(next) + } + } + + const swap = (from: typeof undo, to: typeof redo) => { + const entry = from.current.pop() + + if (!entry) { + return + } + + to.current.push({ cursor: curRef.current, value: vRef.current }) + commit(entry.value, entry.cursor, false) + } + + const emitPaste = (e: PasteEvent) => { + const h = cbPaste.current?.(e) + + if (h) { + commit(h.value, h.cursor) + } + + return !!h + } + + const flushPaste = () => { + const text = pasteBuf.current + const at = pastePos.current + const end = pasteEnd.current ?? at + pasteBuf.current = '' + pasteEnd.current = null + pasteTimer.current = null + + if (!text) { + return + } + + if (!emitPaste({ cursor: at, text, value: vRef.current }) && PRINTABLE.test(text)) { + commit(vRef.current.slice(0, at) + text + vRef.current.slice(end), at + text.length) + } + } + + const clearSel = () => { + if (!selRef.current) { + return + } + + selRef.current = null + setSel(null) + } + + const selectAll = () => { + const end = vRef.current.length + + if (!end) { + return + } + + const next = { end, start: 0 } + selRef.current = next + setSel(next) + setCur(end) + curRef.current = end + } + + const selRange = () => { + const range = selRef.current + + return range && range.start !== range.end + ? { end: Math.max(range.start, range.end), start: Math.min(range.start, range.end) } + : null + } + + const ins = (v: string, c: number, s: string) => v.slice(0, c) + s + v.slice(c) + + useInput( + (inp: string, k: Key, event: InputEvent) => { + const eventRaw = event.keypress.raw + + if (eventRaw === '\x1bv' || eventRaw === '\x1bV') { + return void emitPaste({ cursor: curRef.current, hotkey: true, text: '', value: vRef.current }) + } + + if ( + k.upArrow || + k.downArrow || + (k.ctrl && inp === 'c') || + k.tab || + (k.shift && k.tab) || + k.pageUp || + k.pageDown || + k.escape + ) { + return + } + + if (k.return) { + k.shift || k.meta + ? commit(ins(vRef.current, curRef.current, '\n'), curRef.current + 1) + : cbSubmit.current?.(vRef.current) + + return + } + + let c = curRef.current + let v = vRef.current + const mod = k.ctrl || k.meta + const range = selRange() + const delFwd = k.delete || fwdDel.current + + if (k.ctrl && inp === 'z') { + return swap(undo, redo) + } + + if ((k.ctrl && inp === 'y') || (k.meta && k.shift && inp === 'z')) { + return swap(redo, undo) + } + + if (k.ctrl && inp === 'a') { + return selectAll() + } + + if (k.home) { + clearSel() + c = 0 + } else if (k.end || (k.ctrl && inp === 'e')) { + clearSel() + c = v.length + } else if (k.leftArrow) { + if (range && !mod) { + clearSel() + c = range.start + } else { + clearSel() + c = mod ? wordLeft(v, c) : prevPos(v, c) + } + } else if (k.rightArrow) { + if (range && !mod) { + clearSel() + c = range.end + } else { + clearSel() + c = mod ? wordRight(v, c) : nextPos(v, c) + } + } else if (k.meta && inp === 'b') { + clearSel() + c = wordLeft(v, c) + } else if (k.meta && inp === 'f') { + clearSel() + c = wordRight(v, c) + } else if (range && (k.backspace || delFwd)) { + v = v.slice(0, range.start) + v.slice(range.end) + c = range.start + } else if (k.backspace && c > 0) { + if (mod) { + const t = wordLeft(v, c) + v = v.slice(0, t) + v.slice(c) + c = t + } else { + const t = prevPos(v, c) + v = v.slice(0, t) + v.slice(c) + c = t + } + } else if (delFwd && c < v.length) { + if (mod) { + const t = wordRight(v, c) + v = v.slice(0, c) + v.slice(t) + } else { + v = v.slice(0, c) + v.slice(nextPos(v, c)) + } + } else if (k.ctrl && inp === 'w') { + if (range) { + v = v.slice(0, range.start) + v.slice(range.end) + c = range.start + } else if (c > 0) { + clearSel() + const t = wordLeft(v, c) + v = v.slice(0, t) + v.slice(c) + c = t + } else { + return + } + } else if (k.ctrl && inp === 'u') { + if (range) { + v = v.slice(0, range.start) + v.slice(range.end) + c = range.start + } else { + v = v.slice(c) + c = 0 + } + } else if (k.ctrl && inp === 'k') { + if (range) { + v = v.slice(0, range.start) + v.slice(range.end) + c = range.start + } else { + v = v.slice(0, c) + } + } else if (inp.length > 0) { + const bracketed = inp.includes('[200~') + const text = inp.replace(BRACKET_PASTE, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n') + + if (bracketed && emitPaste({ bracketed: true, cursor: c, text, value: v })) { + return + } + + if (!text) { + return + } + + if (text === '\n') { + return commit(ins(v, c, '\n'), c + 1) + } + + if (text.length > 1 || text.includes('\n')) { + if (!pasteBuf.current) { + pastePos.current = range ? range.start : c + pasteEnd.current = range ? range.end : pastePos.current + } + + pasteBuf.current += text + + if (pasteTimer.current) { + clearTimeout(pasteTimer.current) + } + + pasteTimer.current = setTimeout(flushPaste, 50) + + return + } + + if (PRINTABLE.test(text)) { + if (range) { + v = v.slice(0, range.start) + text + v.slice(range.end) + c = range.start + text.length + } else { + v = v.slice(0, c) + text + v.slice(c) + c += text.length + } + } else { + return + } + } else { + return + } + + commit(v, c) + }, + { isActive: focus } + ) + + return ( + { + if (!focus) { + return + } + + clearSel() + const next = offsetFromPosition(display, e.localRow ?? 0, e.localCol ?? 0, columns) + setCur(next) + curRef.current = next + }} + ref={boxRef} + > + {rendered} + + ) +} + +export interface PasteEvent { + bracketed?: boolean + cursor: number + hotkey?: boolean + text: string + value: string +} + +interface TextInputProps { + columns?: number + focus?: boolean + mask?: string + onChange: (v: string) => void + onPaste?: (e: PasteEvent) => { cursor: number; value: string } | null + onSubmit?: (v: string) => void + placeholder?: string + value: string +} diff --git a/ui-tui/src/components/themed.tsx b/ui-tui/src/components/themed.tsx new file mode 100644 index 0000000000..25fb43b44c --- /dev/null +++ b/ui-tui/src/components/themed.tsx @@ -0,0 +1,30 @@ +import { Text } from '@hermes/ink' +import { useStore } from '@nanostores/react' +import type { ReactNode } from 'react' + +import { $uiState } from '../app/uiStore.js' +import type { ThemeColors } from '../theme.js' + +export function Fg({ bold, c, children, dim, italic, literal, strikethrough, underline, wrap }: FgProps) { + const { theme } = useStore($uiState) + + return ( + + {children} + + ) +} + +export type ThemeColor = keyof ThemeColors + +export interface FgProps { + bold?: boolean + c?: ThemeColor + children?: ReactNode + dim?: boolean + italic?: boolean + literal?: string + strikethrough?: boolean + underline?: boolean + wrap?: 'end' | 'middle' | 'truncate' | 'truncate-end' | 'truncate-middle' | 'truncate-start' | 'wrap' | 'wrap-trim' +} diff --git a/ui-tui/src/components/thinking.tsx b/ui-tui/src/components/thinking.tsx new file mode 100644 index 0000000000..958333d6e5 --- /dev/null +++ b/ui-tui/src/components/thinking.tsx @@ -0,0 +1,984 @@ +import { Box, NoSelect, Text } from '@hermes/ink' +import { memo, type ReactNode, useEffect, useMemo, useState } from 'react' +import spinners, { type BrailleSpinnerName } from 'unicode-animations' + +import { THINKING_COT_MAX } from '../config/limits.js' +import { + compactPreview, + estimateTokensRough, + fmtK, + formatToolCall, + parseToolTrailResultLine, + pick, + thinkingPreview, + toolTrailLabel +} from '../lib/text.js' +import type { Theme } from '../theme.js' +import type { ActiveTool, ActivityItem, DetailsMode, SubagentProgress, ThinkingMode } from '../types.js' + +const THINK: BrailleSpinnerName[] = ['helix', 'breathe', 'orbit', 'dna', 'waverows', 'snake', 'pulse'] +const TOOL: BrailleSpinnerName[] = ['cascade', 'scan', 'diagswipe', 'fillsweep', 'rain', 'columns', 'sparkle'] + +const fmtElapsed = (ms: number) => { + const sec = Math.max(0, ms) / 1000 + + return sec < 10 ? `${sec.toFixed(1)}s` : `${Math.round(sec)}s` +} + +type TreeBranch = 'mid' | 'last' +type TreeRails = readonly boolean[] + +const nextTreeRails = (rails: TreeRails, branch: TreeBranch) => [...rails, branch === 'mid'] + +const treeLead = (rails: TreeRails, branch: TreeBranch) => + `${rails.map(on => (on ? '│ ' : ' ')).join('')}${branch === 'mid' ? '├─ ' : '└─ '}` + +// ── Primitives ─────────────────────────────────────────────────────── + +function TreeRow({ + branch, + children, + rails = [], + stemColor, + stemDim = true, + t +}: { + branch: TreeBranch + children: ReactNode + rails?: TreeRails + stemColor?: string + stemDim?: boolean + t: Theme +}) { + const lead = treeLead(rails, branch) + + return ( + + + + {lead} + + + + {children} + + + ) +} + +function TreeTextRow({ + branch, + color, + content, + dimColor, + rails = [], + t, + wrap = 'wrap-trim' +}: { + branch: TreeBranch + color: string + content: ReactNode + dimColor?: boolean + rails?: TreeRails + t: Theme + wrap?: 'truncate-end' | 'wrap' | 'wrap-trim' +}) { + const text = dimColor ? ( + + {content} + + ) : ( + + {content} + + ) + + return ( + + {text} + + ) +} + +function TreeNode({ + branch, + children, + header, + open, + rails = [], + t +}: { + branch: TreeBranch + children?: (rails: boolean[]) => ReactNode + header: ReactNode + open: boolean + rails?: TreeRails + t: Theme +}) { + return ( + + + {header} + + {open ? children?.(nextTreeRails(rails, branch)) : null} + + ) +} + +export function Spinner({ color, variant = 'think' }: { color: string; variant?: 'think' | 'tool' }) { + const spin = useMemo(() => { + const raw = spinners[pick(variant === 'tool' ? TOOL : THINK)] + + return { ...raw, frames: raw.frames.map(f => [...f][0] ?? '⠀') } + }, [variant]) + + const [frame, setFrame] = useState(0) + + useEffect(() => { + setFrame(0) + }, [spin]) + + useEffect(() => { + const id = setInterval(() => setFrame(f => (f + 1) % spin.frames.length), spin.interval) + + return () => clearInterval(id) + }, [spin]) + + return {spin.frames[frame]} +} + +interface DetailRow { + color: string + content: ReactNode + dimColor?: boolean + key: string +} + +function Detail({ + branch = 'last', + color, + content, + dimColor, + rails = [], + t +}: DetailRow & { branch?: TreeBranch; rails?: TreeRails; t: Theme }) { + return +} + +function StreamCursor({ + color, + dimColor, + streaming = false, + visible = false +}: { + color: string + dimColor?: boolean + streaming?: boolean + visible?: boolean +}) { + const [on, setOn] = useState(true) + + useEffect(() => { + if (!visible || !streaming) { + setOn(true) + + return + } + + const id = setInterval(() => setOn(v => !v), 420) + + return () => clearInterval(id) + }, [streaming, visible]) + + if (!visible) { + return null + } + + return dimColor ? ( + + {streaming && on ? '▍' : ' '} + + ) : ( + {streaming && on ? '▍' : ' '} + ) +} + +function Chevron({ + count, + onClick, + open, + suffix, + t, + title, + tone = 'dim' +}: { + count?: number + onClick: (deep?: boolean) => void + open: boolean + suffix?: string + t: Theme + title: string + tone?: 'dim' | 'error' | 'warn' +}) { + const color = tone === 'error' ? t.color.error : tone === 'warn' ? t.color.warn : t.color.dim + + return ( + onClick(!!e?.shiftKey || !!e?.ctrlKey)}> + + {open ? '▾ ' : '▸ '} + {title} + {typeof count === 'number' ? ` (${count})` : ''} + {suffix ? ( + + {' '} + {suffix} + + ) : null} + + + ) +} + +function SubagentAccordion({ + branch, + expanded, + item, + rails = [], + t +}: { + branch: TreeBranch + expanded: boolean + item: SubagentProgress + rails?: TreeRails + t: Theme +}) { + const [open, setOpen] = useState(expanded) + const [deep, setDeep] = useState(expanded) + const [openThinking, setOpenThinking] = useState(expanded) + const [openTools, setOpenTools] = useState(expanded) + const [openNotes, setOpenNotes] = useState(expanded) + + useEffect(() => { + if (!expanded) { + return + } + + setOpen(true) + setDeep(true) + setOpenThinking(true) + setOpenTools(true) + setOpenNotes(true) + }, [expanded]) + + const expandAll = () => { + setOpen(true) + setDeep(true) + setOpenThinking(true) + setOpenTools(true) + setOpenNotes(true) + } + + const statusTone: 'dim' | 'error' | 'warn' = + item.status === 'failed' ? 'error' : item.status === 'interrupted' ? 'warn' : 'dim' + + const prefix = item.taskCount > 1 ? `[${item.index + 1}/${item.taskCount}] ` : '' + const goalLabel = item.goal || `Subagent ${item.index + 1}` + const title = `${prefix}${open ? goalLabel : compactPreview(goalLabel, 60)}` + const summary = compactPreview((item.summary || '').replace(/\s+/g, ' ').trim(), 72) + + const suffix = + item.status === 'running' + ? 'running' + : `${item.status}${item.durationSeconds ? ` · ${fmtElapsed(item.durationSeconds * 1000)}` : ''}` + + const thinkingText = item.thinking.join('\n') + const hasThinking = Boolean(thinkingText) + const hasTools = item.tools.length > 0 + const noteRows = [...(summary ? [summary] : []), ...item.notes] + const hasNotes = noteRows.length > 0 + const showChildren = expanded || deep + const noteColor = statusTone === 'error' ? t.color.error : statusTone === 'warn' ? t.color.warn : t.color.dim + + const sections: { + header: ReactNode + key: string + open: boolean + render: (rails: boolean[]) => ReactNode + }[] = [] + + if (hasThinking) { + sections.push({ + header: ( + { + if (shift) { + expandAll() + } else { + setOpenThinking(v => !v) + } + }} + open={showChildren || openThinking} + t={t} + title="Thinking" + /> + ), + key: 'thinking', + open: showChildren || openThinking, + render: childRails => ( + + ) + }) + } + + if (hasTools) { + sections.push({ + header: ( + { + if (shift) { + expandAll() + } else { + setOpenTools(v => !v) + } + }} + open={showChildren || openTools} + t={t} + title="Tool calls" + /> + ), + key: 'tools', + open: showChildren || openTools, + render: childRails => ( + + {item.tools.map((line, index) => ( + + + {line} + + } + key={`${item.id}-tool-${index}`} + rails={childRails} + t={t} + /> + ))} + + ) + }) + } + + if (hasNotes) { + sections.push({ + header: ( + { + if (shift) { + expandAll() + } else { + setOpenNotes(v => !v) + } + }} + open={showChildren || openNotes} + t={t} + title="Progress" + tone={statusTone} + /> + ), + key: 'notes', + open: showChildren || openNotes, + render: childRails => ( + + {noteRows.map((line, index) => ( + + ))} + + ) + }) + } + + return ( + { + if (shift) { + expandAll() + + return + } + + setOpen(v => { + if (!v) { + setDeep(false) + } + + return !v + }) + }} + open={open} + suffix={suffix} + t={t} + title={title} + tone={statusTone} + /> + } + open={open} + rails={rails} + t={t} + > + {childRails => ( + + {sections.map((section, index) => ( + + {section.render} + + ))} + + )} + + ) +} + +// ── Thinking ───────────────────────────────────────────────────────── + +export const Thinking = memo(function Thinking({ + active = false, + branch = 'last', + mode = 'truncated', + rails = [], + reasoning, + streaming = false, + t +}: { + active?: boolean + branch?: TreeBranch + mode?: ThinkingMode + rails?: TreeRails + reasoning: string + streaming?: boolean + t: Theme +}) { + const preview = useMemo(() => thinkingPreview(reasoning, mode, THINKING_COT_MAX), [mode, reasoning]) + const lines = useMemo(() => preview.split('\n').map(line => line.replace(/\t/g, ' ')), [preview]) + + if (!preview && !active) { + return null + } + + return ( + + + {preview ? ( + mode === 'full' ? ( + lines.map((line, index) => ( + + {line || ' '} + {index === lines.length - 1 ? ( + + ) : null} + + )) + ) : ( + + {preview} + + + ) + ) : ( + + + + )} + + + ) +}) + +// ── ToolTrail ──────────────────────────────────────────────────────── + +interface Group { + color: string + content: ReactNode + details: DetailRow[] + key: string + label: string +} + +export const ToolTrail = memo(function ToolTrail({ + busy = false, + detailsMode = 'collapsed', + outcome = '', + reasoningActive = false, + reasoning = '', + reasoningTokens, + reasoningStreaming = false, + subagents = [], + t, + tools = [], + toolTokens, + trail = [], + activity = [] +}: { + busy?: boolean + detailsMode?: DetailsMode + outcome?: string + reasoningActive?: boolean + reasoning?: string + reasoningTokens?: number + reasoningStreaming?: boolean + subagents?: SubagentProgress[] + t: Theme + tools?: ActiveTool[] + toolTokens?: number + trail?: string[] + activity?: ActivityItem[] +}) { + const [now, setNow] = useState(() => Date.now()) + const [openThinking, setOpenThinking] = useState(false) + const [openTools, setOpenTools] = useState(false) + const [openSubagents, setOpenSubagents] = useState(false) + const [deepSubagents, setDeepSubagents] = useState(false) + const [openMeta, setOpenMeta] = useState(false) + + useEffect(() => { + if (!tools.length || (detailsMode === 'collapsed' && !openTools)) { + return + } + + const id = setInterval(() => setNow(Date.now()), 500) + + return () => clearInterval(id) + }, [detailsMode, openTools, tools.length]) + + useEffect(() => { + if (detailsMode === 'expanded') { + setOpenThinking(true) + setOpenTools(true) + setOpenSubagents(true) + setOpenMeta(true) + } + + if (detailsMode === 'hidden') { + setOpenThinking(false) + setOpenTools(false) + setOpenSubagents(false) + setOpenMeta(false) + } + }, [detailsMode]) + + const cot = useMemo(() => thinkingPreview(reasoning, 'full', THINKING_COT_MAX), [reasoning]) + + if ( + !busy && + !trail.length && + !tools.length && + !subagents.length && + !activity.length && + !cot && + !reasoningActive && + !outcome + ) { + return null + } + + // ── Build groups + meta ──────────────────────────────────────── + + const groups: Group[] = [] + const meta: DetailRow[] = [] + const pushDetail = (row: DetailRow) => (groups.at(-1)?.details ?? meta).push(row) + + for (const [i, line] of trail.entries()) { + const parsed = parseToolTrailResultLine(line) + + if (parsed) { + groups.push({ + color: parsed.mark === '✗' ? t.color.error : t.color.cornsilk, + content: parsed.detail ? parsed.call : `${parsed.call} ${parsed.mark}`, + details: [], + key: `tr-${i}`, + label: parsed.call + }) + + if (parsed.detail) { + pushDetail({ + color: parsed.mark === '✗' ? t.color.error : t.color.dim, + content: parsed.detail, + dimColor: parsed.mark !== '✗', + key: `tr-${i}-d` + }) + } + + continue + } + + if (line.startsWith('drafting ')) { + const label = toolTrailLabel(line.slice(9).replace(/…$/, '').trim()) + + groups.push({ + color: t.color.cornsilk, + content: label, + details: [{ color: t.color.dim, content: 'drafting...', dimColor: true, key: `tr-${i}-d` }], + key: `tr-${i}`, + label + }) + + continue + } + + if (line === 'analyzing tool output…') { + pushDetail({ + color: t.color.dim, + dimColor: true, + key: `tr-${i}`, + content: groups.length ? ( + <> + {line} + + ) : ( + line + ) + }) + + continue + } + + meta.push({ color: t.color.dim, content: line, dimColor: true, key: `tr-${i}` }) + } + + for (const tool of tools) { + const label = formatToolCall(tool.name, tool.context || '') + + groups.push({ + color: t.color.cornsilk, + key: tool.id, + label, + details: [], + content: ( + <> + {label} + {tool.startedAt ? ` (${fmtElapsed(now - tool.startedAt)})` : ''} + + ) + }) + } + + for (const item of activity.slice(-4)) { + const glyph = item.tone === 'error' ? '✗' : item.tone === 'warn' ? '!' : '·' + const color = item.tone === 'error' ? t.color.error : item.tone === 'warn' ? t.color.warn : t.color.dim + meta.push({ color, content: `${glyph} ${item.text}`, dimColor: item.tone === 'info', key: `a-${item.id}` }) + } + + // ── Derived ──────────────────────────────────────────────────── + + const hasTools = groups.length > 0 + const hasSubagents = subagents.length > 0 + const hasMeta = meta.length > 0 + const hasThinking = !!cot || reasoningActive || busy + const thinkingLive = reasoningActive || reasoningStreaming + + const tokenCount = + reasoningTokens && reasoningTokens > 0 ? reasoningTokens : reasoning ? estimateTokensRough(reasoning) : 0 + + const toolTokenCount = toolTokens ?? 0 + const totalTokenCount = tokenCount + toolTokenCount + const thinkingTokensLabel = tokenCount > 0 ? `~${fmtK(tokenCount)} tokens` : null + + const toolTokensLabel = toolTokens !== undefined && toolTokens > 0 ? `~${fmtK(toolTokens)} tokens` : undefined + + const totalTokensLabel = tokenCount > 0 && toolTokenCount > 0 ? `~${fmtK(totalTokenCount)} total` : null + const delegateGroups = groups.filter(g => g.label.startsWith('Delegate Task')) + const inlineDelegateKey = hasSubagents && delegateGroups.length === 1 ? delegateGroups[0]!.key : null + + // ── Hidden: errors/warnings only ────────────────────────────── + + if (detailsMode === 'hidden') { + const alerts = activity.filter(i => i.tone !== 'info').slice(-2) + + return alerts.length ? ( + + {alerts.map(i => ( + + {i.tone === 'error' ? '✗' : '!'} {i.text} + + ))} + + ) : null + } + + // ── Tree render fragments ────────────────────────────────────── + + const expandAll = () => { + setOpenThinking(true) + setOpenTools(true) + setOpenSubagents(true) + setDeepSubagents(true) + setOpenMeta(true) + } + + const metaTone: 'dim' | 'error' | 'warn' = activity.some(i => i.tone === 'error') + ? 'error' + : activity.some(i => i.tone === 'warn') + ? 'warn' + : 'dim' + + const renderSubagentList = (rails: boolean[]) => ( + + {subagents.map((item, index) => ( + + ))} + + ) + + const sections: { + header: ReactNode + key: string + open: boolean + render: (rails: boolean[]) => ReactNode + }[] = [] + + if (hasThinking) { + sections.push({ + header: ( + { + if (e?.shiftKey || e?.ctrlKey) { + expandAll() + } else { + setOpenThinking(v => !v) + } + }} + > + + {detailsMode === 'expanded' || openThinking ? '▾ ' : '▸ '} + {thinkingLive ? ( + + Thinking + + ) : ( + + Thinking + + )} + {thinkingTokensLabel ? ( + + {' '} + {thinkingTokensLabel} + + ) : null} + + + ), + key: 'thinking', + open: detailsMode === 'expanded' || openThinking, + render: rails => ( + + ) + }) + } + + if (hasTools) { + sections.push({ + header: ( + { + if (shift) { + expandAll() + } else { + setOpenTools(v => !v) + } + }} + open={detailsMode === 'expanded' || openTools} + suffix={toolTokensLabel} + t={t} + title="Tool calls" + /> + ), + key: 'tools', + open: detailsMode === 'expanded' || openTools, + render: rails => ( + + {groups.map((group, index) => { + const branch: TreeBranch = index === groups.length - 1 ? 'last' : 'mid' + const childRails = nextTreeRails(rails, branch) + const hasInlineSubagents = inlineDelegateKey === group.key + + return ( + + + + {group.content} + + } + rails={rails} + t={t} + /> + {group.details.map((detail, detailIndex) => ( + + ))} + {hasInlineSubagents ? renderSubagentList(childRails) : null} + + ) + })} + + ) + }) + } + + if (hasSubagents && !inlineDelegateKey) { + sections.push({ + header: ( + { + if (shift) { + expandAll() + setDeepSubagents(true) + } else { + setOpenSubagents(v => !v) + setDeepSubagents(false) + } + }} + open={detailsMode === 'expanded' || openSubagents} + t={t} + title="Subagents" + /> + ), + key: 'subagents', + open: detailsMode === 'expanded' || openSubagents, + render: renderSubagentList + }) + } + + if (hasMeta) { + sections.push({ + header: ( + { + if (shift) { + expandAll() + } else { + setOpenMeta(v => !v) + } + }} + open={detailsMode === 'expanded' || openMeta} + t={t} + title="Activity" + tone={metaTone} + /> + ), + key: 'meta', + open: detailsMode === 'expanded' || openMeta, + render: rails => ( + + {meta.map((row, index) => ( + + ))} + + ) + }) + } + + const topCount = sections.length + (totalTokensLabel ? 1 : 0) + + return ( + + {sections.map((section, index) => ( + + {section.render} + + ))} + {totalTokensLabel ? ( + + Σ + {totalTokensLabel} + + } + dimColor + t={t} + /> + ) : null} + {outcome ? ( + + + · {outcome} + + + ) : null} + + ) +}) diff --git a/ui-tui/src/config/env.ts b/ui-tui/src/config/env.ts new file mode 100644 index 0000000000..3a476d6bc5 --- /dev/null +++ b/ui-tui/src/config/env.ts @@ -0,0 +1,2 @@ +export const STARTUP_RESUME_ID = (process.env.HERMES_TUI_RESUME ?? '').trim() +export const MOUSE_TRACKING = !/^(?:1|true|yes|on)$/i.test((process.env.HERMES_TUI_DISABLE_MOUSE ?? '').trim()) diff --git a/ui-tui/src/config/limits.ts b/ui-tui/src/config/limits.ts new file mode 100644 index 0000000000..aa1090396b --- /dev/null +++ b/ui-tui/src/config/limits.ts @@ -0,0 +1,5 @@ +export const LARGE_PASTE = { chars: 8000, lines: 80 } +export const LONG_MSG = 300 +export const MAX_HISTORY = 800 +export const THINKING_COT_MAX = 160 +export const WHEEL_SCROLL_STEP = 3 diff --git a/ui-tui/src/config/timing.ts b/ui-tui/src/config/timing.ts new file mode 100644 index 0000000000..63498dbae8 --- /dev/null +++ b/ui-tui/src/config/timing.ts @@ -0,0 +1,2 @@ +export const STREAM_BATCH_MS = 16 +export const REASONING_PULSE_MS = 700 diff --git a/ui-tui/src/content/charms.ts b/ui-tui/src/content/charms.ts new file mode 100644 index 0000000000..546e44dd09 --- /dev/null +++ b/ui-tui/src/content/charms.ts @@ -0,0 +1 @@ +export const LONG_RUN_CHARMS = ['still cooking…', 'polishing edges…', 'asking the void nicely…'] diff --git a/ui-tui/src/content/faces.ts b/ui-tui/src/content/faces.ts new file mode 100644 index 0000000000..1bb64debb2 --- /dev/null +++ b/ui-tui/src/content/faces.ts @@ -0,0 +1,17 @@ +export const FACES = [ + '(。•́︿•̀。)', + '(◔_◔)', + '(¬‿¬)', + '( •_•)>⌐■-■', + '(⌐■_■)', + '(´・_・`)', + '◉_◉', + '(°ロ°)', + '( ˘⌣˘)♡', + 'ヽ(>∀<☆)☆', + '٩(๑❛ᴗ❛๑)۶', + '(⊙_⊙)', + '(¬_¬)', + '( ͡° ͜ʖ ͡°)', + 'ಠ_ಠ' +] diff --git a/ui-tui/src/content/fortunes.ts b/ui-tui/src/content/fortunes.ts new file mode 100644 index 0000000000..87943f9f42 --- /dev/null +++ b/ui-tui/src/content/fortunes.ts @@ -0,0 +1,30 @@ +const FORTUNES = [ + 'you are one clean refactor away from clarity', + 'a tiny rename today prevents a huge bug tomorrow', + 'your next commit message will be immaculate', + 'the edge case you are ignoring is already solved in your head', + 'minimal diff, maximal calm', + 'today favors bold deletions over new abstractions', + 'the right helper is already in your codebase', + 'you will ship before overthinking catches up', + 'tests are about to save your future self', + 'your instincts are correctly suspicious of that one branch' +] + +const LEGENDARY = [ + 'legendary drop: one-line fix, first try', + 'legendary drop: every flaky test passes cleanly', + 'legendary drop: your diff teaches by itself' +] + +const hash = (s: string) => [...s].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619), 2166136261) >>> 0 + +const fromScore = (n: number) => { + const rare = n % 20 === 0 + const bag = rare ? LEGENDARY : FORTUNES + + return `${rare ? '🌟' : '🔮'} ${bag[n % bag.length]}` +} + +export const randomFortune = () => fromScore(Math.floor(Math.random() * 0x7fffffff)) +export const dailyFortune = (seed: null | string) => fromScore(hash(`${seed || 'anon'}|${new Date().toDateString()}`)) diff --git a/ui-tui/src/content/hotkeys.ts b/ui-tui/src/content/hotkeys.ts new file mode 100644 index 0000000000..f08ca61365 --- /dev/null +++ b/ui-tui/src/content/hotkeys.ts @@ -0,0 +1,19 @@ +export const HOTKEYS: [string, string][] = [ + ['Ctrl+C', 'interrupt / clear draft / exit'], + ['Ctrl+D', 'exit'], + ['Ctrl+G', 'open $EDITOR for prompt'], + ['Ctrl+L', 'new session (clear)'], + ['Alt+V / /paste', 'paste clipboard image'], + ['Tab', 'apply completion'], + ['↑/↓', 'completions / queue edit / history'], + ['Ctrl+A/E', 'home / end of line'], + ['Ctrl+Z / Ctrl+Y', 'undo / redo input edits'], + ['Ctrl+W', 'delete word'], + ['Ctrl+U/K', 'delete to start / end'], + ['Ctrl+←/→', 'jump word'], + ['Home/End', 'start / end of line'], + ['Shift+Enter / Alt+Enter', 'insert newline'], + ['\\+Enter', 'multi-line continuation (fallback)'], + ['!cmd', 'run shell command'], + ['{!cmd}', 'interpolate shell output inline'] +] diff --git a/ui-tui/src/content/placeholders.ts b/ui-tui/src/content/placeholders.ts new file mode 100644 index 0000000000..3d97eecac0 --- /dev/null +++ b/ui-tui/src/content/placeholders.ts @@ -0,0 +1,13 @@ +import { pick } from '../lib/text.js' + +export const PLACEHOLDERS = [ + 'Ask me anything…', + 'Try "explain this codebase"', + 'Try "write a test for…"', + 'Try "refactor the auth module"', + 'Try "/help" for commands', + 'Try "fix the lint errors"', + 'Try "how does the config loader work?"' +] + +export const PLACEHOLDER = pick(PLACEHOLDERS) diff --git a/ui-tui/src/content/setup.ts b/ui-tui/src/content/setup.ts new file mode 100644 index 0000000000..49dd9aa247 --- /dev/null +++ b/ui-tui/src/content/setup.ts @@ -0,0 +1,17 @@ +import type { PanelSection } from '../types.js' + +export const SETUP_REQUIRED_TITLE = 'Setup Required' + +export const buildSetupRequiredSections = (): PanelSection[] => [ + { + text: 'Hermes needs a model provider before the TUI can start a session.' + }, + { + rows: [ + ['/model', 'configure provider + model in-place'], + ['/setup', 'run full first-time setup wizard in-place'], + ['Ctrl+C', 'exit and run `hermes setup` manually'] + ], + title: 'Actions' + } +] diff --git a/ui-tui/src/content/verbs.ts b/ui-tui/src/content/verbs.ts new file mode 100644 index 0000000000..41b441d5cd --- /dev/null +++ b/ui-tui/src/content/verbs.ts @@ -0,0 +1,38 @@ +export const TOOL_VERBS: Record = { + browser: 'browsing', + clarify: 'asking', + create_file: 'creating', + delegate_task: 'delegating', + delete_file: 'deleting', + execute_code: 'executing', + image_generate: 'generating', + list_files: 'listing', + memory: 'remembering', + patch: 'patching', + read_file: 'reading', + run_command: 'running', + search_code: 'searching', + search_files: 'searching', + terminal: 'terminal', + web_extract: 'extracting', + web_search: 'searching', + write_file: 'writing' +} + +export const VERBS = [ + 'pondering', + 'contemplating', + 'musing', + 'cogitating', + 'ruminating', + 'deliberating', + 'mulling', + 'reflecting', + 'processing', + 'reasoning', + 'analyzing', + 'computing', + 'synthesizing', + 'formulating', + 'brainstorming' +] diff --git a/ui-tui/src/domain/details.ts b/ui-tui/src/domain/details.ts new file mode 100644 index 0000000000..fa01092f5d --- /dev/null +++ b/ui-tui/src/domain/details.ts @@ -0,0 +1,26 @@ +import type { DetailsMode } from '../types.js' + +const MODES = ['hidden', 'collapsed', 'expanded'] as const + +const THINKING_FALLBACK: Record = { + collapsed: 'collapsed', + full: 'expanded', + truncated: 'collapsed' +} + +export const parseDetailsMode = (v: unknown): DetailsMode | null => { + const s = typeof v === 'string' ? v.trim().toLowerCase() : '' + + return MODES.find(m => m === s) ?? null +} + +export const resolveDetailsMode = (d?: { details_mode?: unknown; thinking_mode?: unknown } | null): DetailsMode => + parseDetailsMode(d?.details_mode) ?? + THINKING_FALLBACK[ + String(d?.thinking_mode ?? '') + .trim() + .toLowerCase() + ] ?? + 'collapsed' + +export const nextDetailsMode = (m: DetailsMode): DetailsMode => MODES[(MODES.indexOf(m) + 1) % MODES.length]! diff --git a/ui-tui/src/domain/messages.ts b/ui-tui/src/domain/messages.ts new file mode 100644 index 0000000000..34b072f01a --- /dev/null +++ b/ui-tui/src/domain/messages.ts @@ -0,0 +1,84 @@ +import { LONG_MSG } from '../config/limits.js' +import { buildToolTrailLine, fmtK } from '../lib/text.js' +import type { Msg, SessionInfo } from '../types.js' + +export const introMsg = (info: SessionInfo): Msg => ({ info, kind: 'intro', role: 'system', text: '' }) + +export const imageTokenMeta = (info?: ImageMeta | null) => { + const { width, height, token_estimate: t } = info ?? {} + + return [width && height ? `${width}x${height}` : '', (t ?? 0) > 0 ? `~${fmtK(t!)} tok` : ''] + .filter(Boolean) + .join(' · ') +} + +export const userDisplay = (text: string) => { + if (text.length <= LONG_MSG) { + return text + } + + const first = text.split('\n')[0]?.trim() ?? '' + const words = first.split(/\s+/).filter(Boolean) + const prefix = (words.length > 1 ? words.slice(0, 4).join(' ') : first).slice(0, 80) + + return `${prefix || '(message)'} [long message]` +} + +export const toTranscriptMessages = (rows: unknown): Msg[] => { + if (!Array.isArray(rows)) { + return [] + } + + const out: Msg[] = [] + let pending: string[] = [] + + for (const row of rows) { + if (!row || typeof row !== 'object') { + continue + } + + const { context, name, role, text } = row as TranscriptRow + + if (role === 'tool') { + pending.push(buildToolTrailLine(name ?? 'tool', context ?? '')) + + continue + } + + if (typeof text !== 'string' || !text.trim()) { + continue + } + + if (role === 'assistant') { + out.push({ role, text, ...(pending.length && { tools: pending }) }) + pending = [] + } else if (role === 'user' || role === 'system') { + out.push({ role, text }) + pending = [] + } + } + + return out +} + +export const fmtDuration = (ms: number) => { + const t = Math.max(0, Math.floor(ms / 1000)) + const h = Math.floor(t / 3600) + const m = Math.floor((t % 3600) / 60) + const s = t % 60 + + return h > 0 ? `${h}h ${m}m` : m > 0 ? `${m}m ${s}s` : `${s}s` +} + +interface ImageMeta { + height?: number + token_estimate?: number + width?: number +} + +interface TranscriptRow { + context?: string + name?: string + role?: string + text?: string +} diff --git a/ui-tui/src/domain/paths.ts b/ui-tui/src/domain/paths.ts new file mode 100644 index 0000000000..78daff170a --- /dev/null +++ b/ui-tui/src/domain/paths.ts @@ -0,0 +1,6 @@ +export const shortCwd = (cwd: string, max = 28) => { + const h = process.env.HOME + const p = h && cwd.startsWith(h) ? `~${cwd.slice(h.length)}` : cwd + + return p.length <= max ? p : `…${p.slice(-(max - 1))}` +} diff --git a/ui-tui/src/domain/roles.ts b/ui-tui/src/domain/roles.ts new file mode 100644 index 0000000000..f92d175e65 --- /dev/null +++ b/ui-tui/src/domain/roles.ts @@ -0,0 +1,9 @@ +import type { Theme } from '../theme.js' +import type { Role } from '../types.js' + +export const ROLE: Record { body: string; glyph: string; prefix: string }> = { + assistant: t => ({ body: t.color.cornsilk, glyph: t.brand.tool, prefix: t.color.bronze }), + system: t => ({ body: '', glyph: '·', prefix: t.color.dim }), + tool: t => ({ body: t.color.dim, glyph: '⚡', prefix: t.color.dim }), + user: t => ({ body: t.color.label, glyph: t.brand.prompt, prefix: t.color.label }) +} diff --git a/ui-tui/src/domain/slash.ts b/ui-tui/src/domain/slash.ts new file mode 100644 index 0000000000..1fc8082ba5 --- /dev/null +++ b/ui-tui/src/domain/slash.ts @@ -0,0 +1,7 @@ +export const looksLikeSlashCommand = (text: string) => /^\/[^\s/]*(?:\s|$)/.test(text) + +export const parseSlashCommand = (cmd: string) => { + const [name = '', ...rest] = cmd.slice(1).split(/\s+/) + + return { arg: rest.join(' '), cmd, name: name.toLowerCase() } +} diff --git a/ui-tui/src/domain/usage.ts b/ui-tui/src/domain/usage.ts new file mode 100644 index 0000000000..508195f253 --- /dev/null +++ b/ui-tui/src/domain/usage.ts @@ -0,0 +1,3 @@ +import type { Usage } from '../types.js' + +export const ZERO: Usage = { calls: 0, input: 0, output: 0, total: 0 } diff --git a/ui-tui/src/domain/viewport.ts b/ui-tui/src/domain/viewport.ts new file mode 100644 index 0000000000..788f94269e --- /dev/null +++ b/ui-tui/src/domain/viewport.ts @@ -0,0 +1,39 @@ +import type { Msg } from '../types.js' + +import { userDisplay } from './messages.js' + +const upperBound = (offsets: ArrayLike, target: number) => { + let lo = 0 + let hi = offsets.length + + while (lo < hi) { + const mid = (lo + hi) >> 1 + + offsets[mid]! <= target ? (lo = mid + 1) : (hi = mid) + } + + return lo +} + +export const stickyPromptFromViewport = ( + messages: readonly Msg[], + offsets: ArrayLike, + top: number, + sticky: boolean +) => { + if (sticky || !messages.length) { + return '' + } + + const first = Math.max(0, Math.min(messages.length - 1, upperBound(offsets, top) - 1)) + + for (let i = first; i >= 0; i--) { + if (messages[i]?.role !== 'user') { + continue + } + + return (offsets[i] ?? 0) + 1 < top ? userDisplay(messages[i]!.text.trim()).replace(/\s+/g, ' ').trim() : '' + } + + return '' +} diff --git a/ui-tui/src/entry.tsx b/ui-tui/src/entry.tsx new file mode 100644 index 0000000000..e0a4379342 --- /dev/null +++ b/ui-tui/src/entry.tsx @@ -0,0 +1,18 @@ +#!/usr/bin/env node +// Order matters: paint banner + spawn python before loading @hermes/ink. +import { bootBanner } from './bootBanner.js' +import { GatewayClient } from './gatewayClient.js' + +if (!process.stdin.isTTY) { + console.log('hermes-tui: no TTY') + process.exit(0) +} + +process.stdout.write(bootBanner()) + +const gw = new GatewayClient() +gw.start() + +const [{ render }, { App }] = await Promise.all([import('@hermes/ink'), import('./app.js')]) + +render(, { exitOnCtrlC: false }) diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts new file mode 100644 index 0000000000..3d5f89eb8c --- /dev/null +++ b/ui-tui/src/gatewayClient.ts @@ -0,0 +1,258 @@ +import { type ChildProcess, spawn } from 'node:child_process' +import { EventEmitter } from 'node:events' +import { existsSync } from 'node:fs' +import { delimiter, resolve } from 'node:path' +import { createInterface } from 'node:readline' + +import type { GatewayEvent } from './gatewayTypes.js' + +const MAX_GATEWAY_LOG_LINES = 200 +const MAX_LOG_PREVIEW = 240 +const STARTUP_TIMEOUT_MS = Math.max(5000, parseInt(process.env.HERMES_TUI_STARTUP_TIMEOUT_MS ?? '15000', 10) || 15000) +const REQUEST_TIMEOUT_MS = Math.max(30000, parseInt(process.env.HERMES_TUI_RPC_TIMEOUT_MS ?? '120000', 10) || 120000) + +const resolvePython = (root: string) => { + const configured = process.env.HERMES_PYTHON?.trim() || process.env.PYTHON?.trim() + + if (configured) { + return configured + } + + const venv = process.env.VIRTUAL_ENV?.trim() + + const hit = [ + venv && resolve(venv, 'bin/python'), + venv && resolve(venv, 'Scripts/python.exe'), + resolve(root, '.venv/bin/python'), + resolve(root, '.venv/bin/python3'), + resolve(root, 'venv/bin/python'), + resolve(root, 'venv/bin/python3') + ].find(p => p && existsSync(p)) + + return hit || (process.platform === 'win32' ? 'python' : 'python3') +} + +const asGatewayEvent = (value: unknown): GatewayEvent | null => + value && typeof value === 'object' && !Array.isArray(value) && typeof (value as { type?: unknown }).type === 'string' + ? (value as GatewayEvent) + : null + +interface Pending { + reject: (e: Error) => void + resolve: (v: unknown) => void +} + +export class GatewayClient extends EventEmitter { + private proc: ChildProcess | null = null + private reqId = 0 + private logs: string[] = [] + private pending = new Map() + private bufferedEvents: GatewayEvent[] = [] + private pendingExit: number | null | undefined + private ready = false + private readyTimer: ReturnType | null = null + private subscribed = false + private stdoutRl: ReturnType | null = null + private stderrRl: ReturnType | null = null + + private publish(ev: GatewayEvent) { + if (ev.type === 'gateway.ready') { + this.ready = true + + if (this.readyTimer) { + clearTimeout(this.readyTimer) + this.readyTimer = null + } + } + + if (this.subscribed) { + return void this.emit('event', ev) + } + + this.bufferedEvents.push(ev) + } + + start() { + const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../') + const python = resolvePython(root) + const cwd = process.env.HERMES_CWD || root + const env = { ...process.env } + const pyPath = env.PYTHONPATH?.trim() + env.PYTHONPATH = pyPath ? `${root}${delimiter}${pyPath}` : root + + this.ready = false + this.bufferedEvents = [] + this.pendingExit = undefined + this.stdoutRl?.close() + this.stderrRl?.close() + this.stdoutRl = null + this.stderrRl = null + + if (this.proc && !this.proc.killed && this.proc.exitCode === null) { + this.proc.kill() + } + + if (this.readyTimer) { + clearTimeout(this.readyTimer) + } + + this.readyTimer = setTimeout(() => { + if (this.ready) { + return + } + + this.pushLog(`[startup] timed out waiting for gateway.ready (python=${python}, cwd=${cwd})`) + this.publish({ type: 'gateway.start_timeout', payload: { cwd, python } }) + }, STARTUP_TIMEOUT_MS) + + this.proc = spawn(python, ['-m', 'tui_gateway.entry'], { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] }) + + this.stdoutRl = createInterface({ input: this.proc.stdout! }) + this.stdoutRl.on('line', raw => { + try { + this.dispatch(JSON.parse(raw)) + } catch { + const preview = raw.trim().slice(0, MAX_LOG_PREVIEW) || '(empty line)' + + this.pushLog(`[protocol] malformed stdout: ${preview}`) + this.publish({ type: 'gateway.protocol_error', payload: { preview } }) + } + }) + + this.stderrRl = createInterface({ input: this.proc.stderr! }) + this.stderrRl.on('line', raw => { + const line = raw.trim() + + if (!line) { + return + } + + this.pushLog(line) + this.publish({ type: 'gateway.stderr', payload: { line } }) + }) + + this.proc.on('error', err => { + this.pushLog(`[spawn] ${err.message}`) + this.rejectPending(new Error(`gateway error: ${err.message}`)) + this.publish({ type: 'gateway.stderr', payload: { line: `[spawn] ${err.message}` } }) + }) + + this.proc.on('exit', code => { + if (this.readyTimer) { + clearTimeout(this.readyTimer) + this.readyTimer = null + } + + this.rejectPending(new Error(`gateway exited${code === null ? '' : ` (${code})`}`)) + + if (this.subscribed) { + this.emit('exit', code) + } else { + this.pendingExit = code + } + }) + } + + private dispatch(msg: Record) { + const id = msg.id as string | undefined + const p = id ? this.pending.get(id) : undefined + + if (p) { + this.pending.delete(id!) + + if (msg.error) { + const err = msg.error as { message?: unknown } | null | undefined + + p.reject(new Error(typeof err?.message === 'string' ? err.message : 'request failed')) + } else { + p.resolve(msg.result) + } + + return + } + + if (msg.method === 'event') { + const ev = asGatewayEvent(msg.params) + + if (ev) { + this.publish(ev) + } + } + } + + private pushLog(line: string) { + if (this.logs.push(line) > MAX_GATEWAY_LOG_LINES) { + this.logs.splice(0, this.logs.length - MAX_GATEWAY_LOG_LINES) + } + } + + private rejectPending(err: Error) { + for (const p of this.pending.values()) { + p.reject(err) + } + + this.pending.clear() + } + + drain() { + this.subscribed = true + + for (const ev of this.bufferedEvents.splice(0)) { + this.emit('event', ev) + } + + if (this.pendingExit !== undefined) { + const code = this.pendingExit + + this.pendingExit = undefined + this.emit('exit', code) + } + } + + getLogTail(limit = 20): string { + return this.logs.slice(-Math.max(1, limit)).join('\n') + } + + request(method: string, params: Record = {}): Promise { + if (!this.proc?.stdin || this.proc.killed || this.proc.exitCode !== null) { + this.start() + } + + if (!this.proc?.stdin) { + return Promise.reject(new Error('gateway not running')) + } + + const id = `r${++this.reqId}` + + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + if (this.pending.delete(id)) { + reject(new Error(`timeout: ${method}`)) + } + }, REQUEST_TIMEOUT_MS) + + this.pending.set(id, { + reject: e => { + clearTimeout(timeout) + reject(e) + }, + resolve: v => { + clearTimeout(timeout) + resolve(v as T) + } + }) + + try { + this.proc!.stdin!.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n') + } catch (e) { + clearTimeout(timeout) + this.pending.delete(id) + reject(e instanceof Error ? e : new Error(String(e))) + } + }) + } + + kill() { + this.proc?.kill() + } +} diff --git a/ui-tui/src/gatewayTypes.ts b/ui-tui/src/gatewayTypes.ts new file mode 100644 index 0000000000..9e21b9bc58 --- /dev/null +++ b/ui-tui/src/gatewayTypes.ts @@ -0,0 +1,324 @@ +import type { SessionInfo, SlashCategory, Usage } from './types.js' + +export interface GatewaySkin { + banner_hero?: string + banner_logo?: string + branding?: Record + colors?: Record + help_header?: string + tool_prefix?: string +} + +export interface GatewayCompletionItem { + display: string + meta?: string + text: string +} + +export interface GatewayTranscriptMessage { + context?: string + name?: string + role: 'assistant' | 'system' | 'tool' | 'user' + text?: string +} + +// ── Commands / completion ──────────────────────────────────────────── + +export interface CommandsCatalogResponse { + canon?: Record + categories?: SlashCategory[] + pairs?: [string, string][] + skill_count?: number + sub?: Record + warning?: string +} + +export interface CompletionResponse { + items?: GatewayCompletionItem[] + replace_from?: number +} + +export interface SlashExecResponse { + output?: string + warning?: string +} + +export type CommandDispatchResponse = + | { output?: string; type: 'exec' | 'plugin' } + | { target: string; type: 'alias' } + | { message?: string; name: string; type: 'skill' } + +// ── Config ─────────────────────────────────────────────────────────── + +export interface ConfigDisplayConfig { + bell_on_complete?: boolean + details_mode?: string + thinking_mode?: string + tui_compact?: boolean + tui_statusbar?: boolean +} + +export interface ConfigFullResponse { + config?: { display?: ConfigDisplayConfig } +} + +export interface ConfigMtimeResponse { + mtime?: number +} + +export interface ConfigGetValueResponse { + display?: string + home?: string + value?: string +} + +export interface ConfigSetResponse { + credential_warning?: string + history_reset?: boolean + info?: SessionInfo + value?: string + warning?: string +} + +export interface SetupStatusResponse { + provider_configured?: boolean +} + +// ── Session lifecycle ──────────────────────────────────────────────── + +export interface SessionCreateResponse { + info?: SessionInfo & { credential_warning?: string } + session_id: string +} + +export interface SessionResumeResponse { + info?: SessionInfo + message_count?: number + messages: GatewayTranscriptMessage[] + resumed?: string + session_id: string +} + +export interface SessionListItem { + id: string + message_count: number + preview: string + source?: string + started_at: number + title: string +} + +export interface SessionListResponse { + sessions?: SessionListItem[] +} + +export interface SessionUndoResponse { + removed?: number +} + +export interface SessionUsageResponse { + cache_read?: number + cache_write?: number + calls?: number + compressions?: number + context_max?: number + context_percent?: number + context_used?: number + cost_status?: 'estimated' | 'exact' + cost_usd?: number + input?: number + model?: string + output?: number + total?: number +} + +export interface SessionCompressResponse { + info?: SessionInfo + messages?: GatewayTranscriptMessage[] + removed?: number + usage?: Usage +} + +export interface SessionBranchResponse { + session_id?: string + title?: string +} + +export interface SessionCloseResponse { + ok?: boolean +} + +export interface SessionInterruptResponse { + ok?: boolean +} + +// ── Prompt / submission ────────────────────────────────────────────── + +export interface PromptSubmitResponse { + ok?: boolean +} + +export interface BackgroundStartResponse { + task_id?: string +} + +export interface BtwStartResponse { + ok?: boolean +} + +export interface ClarifyRespondResponse { + ok?: boolean +} + +export interface ApprovalRespondResponse { + ok?: boolean +} + +export interface SudoRespondResponse { + ok?: boolean +} + +export interface SecretRespondResponse { + ok?: boolean +} + +// ── Shell / clipboard / input ──────────────────────────────────────── + +export interface ShellExecResponse { + code: number + stderr?: string + stdout?: string +} + +export interface ClipboardPasteResponse { + attached?: boolean + count?: number + height?: number + message?: string + token_estimate?: number + width?: number +} + +export interface InputDetectDropResponse { + height?: number + is_image?: boolean + matched?: boolean + name?: string + text?: string + token_estimate?: number + width?: number +} + +export interface TerminalResizeResponse { + ok?: boolean +} + +// ── Image attach ───────────────────────────────────────────────────── + +export interface ImageAttachResponse { + height?: number + name?: string + remainder?: string + token_estimate?: number + width?: number +} + +// ── Voice ──────────────────────────────────────────────────────────── + +export interface VoiceToggleResponse { + enabled?: boolean +} + +export interface VoiceRecordResponse { + text?: string +} + +// ── Tools (TS keeps configure since it resets local history) ───────── + +export interface ToolsConfigureResponse { + changed?: string[] + enabled_toolsets?: string[] + info?: SessionInfo + missing_servers?: string[] + reset?: boolean + unknown?: string[] +} + +// ── Model picker ───────────────────────────────────────────────────── + +export interface ModelOptionProvider { + is_current?: boolean + models?: string[] + name: string + slug: string + total_models?: number + warning?: string +} + +export interface ModelOptionsResponse { + model?: string + provider?: string + providers?: ModelOptionProvider[] +} + +// ── MCP ────────────────────────────────────────────────────────────── + +export interface ReloadMcpResponse { + ok?: boolean +} + +// ── Subagent events ────────────────────────────────────────────────── + +export interface SubagentEventPayload { + duration_seconds?: number + goal: string + status?: 'completed' | 'failed' | 'interrupted' | 'running' + summary?: string + task_count?: number + task_index: number + text?: string + tool_name?: string + tool_preview?: string +} + +export type GatewayEvent = + | { payload?: { skin?: GatewaySkin }; session_id?: string; type: 'gateway.ready' } + | { payload?: GatewaySkin; session_id?: string; type: 'skin.changed' } + | { payload: SessionInfo; session_id?: string; type: 'session.info' } + | { payload?: { text?: string }; session_id?: string; type: 'thinking.delta' } + | { payload?: undefined; session_id?: string; type: 'message.start' } + | { payload?: { kind?: string; text?: string }; session_id?: string; type: 'status.update' } + | { payload: { line: string }; session_id?: string; type: 'gateway.stderr' } + | { payload?: { cwd?: string; python?: string }; session_id?: string; type: 'gateway.start_timeout' } + | { payload?: { preview?: string }; session_id?: string; type: 'gateway.protocol_error' } + | { payload?: { text?: string }; session_id?: string; type: 'reasoning.delta' | 'reasoning.available' } + | { payload: { name?: string; preview?: string }; session_id?: string; type: 'tool.progress' } + | { payload: { name?: string }; session_id?: string; type: 'tool.generating' } + | { payload: { context?: string; name?: string; tool_id: string }; session_id?: string; type: 'tool.start' } + | { + payload: { error?: string; inline_diff?: string; name?: string; summary?: string; tool_id: string } + session_id?: string + type: 'tool.complete' + } + | { + payload: { choices: string[] | null; question: string; request_id: string } + session_id?: string + type: 'clarify.request' + } + | { payload: { command: string; description: string }; session_id?: string; type: 'approval.request' } + | { payload: { request_id: string }; session_id?: string; type: 'sudo.request' } + | { payload: { env_var: string; prompt: string; request_id: string }; session_id?: string; type: 'secret.request' } + | { payload: { task_id: string; text: string }; session_id?: string; type: 'background.complete' } + | { payload: { text: string }; session_id?: string; type: 'btw.complete' } + | { payload: SubagentEventPayload; session_id?: string; type: 'subagent.start' } + | { payload: SubagentEventPayload; session_id?: string; type: 'subagent.thinking' } + | { payload: SubagentEventPayload; session_id?: string; type: 'subagent.tool' } + | { payload: SubagentEventPayload; session_id?: string; type: 'subagent.progress' } + | { payload: SubagentEventPayload; session_id?: string; type: 'subagent.complete' } + | { payload: { rendered?: string; text?: string }; session_id?: string; type: 'message.delta' } + | { + payload?: { reasoning?: string; rendered?: string; text?: string; usage?: Usage } + session_id?: string + type: 'message.complete' + } + | { payload?: { message?: string }; session_id?: string; type: 'error' } diff --git a/ui-tui/src/hooks/useCompletion.ts b/ui-tui/src/hooks/useCompletion.ts new file mode 100644 index 0000000000..5b0c2659ed --- /dev/null +++ b/ui-tui/src/hooks/useCompletion.ts @@ -0,0 +1,89 @@ +import { useEffect, useRef, useState } from 'react' + +import type { CompletionItem } from '../app/interfaces.js' +import type { GatewayClient } from '../gatewayClient.js' +import type { CompletionResponse } from '../gatewayTypes.js' +import { asRpcResult } from '../lib/rpc.js' + +const TAB_PATH_RE = /((?:["']?(?:[A-Za-z]:[\\/]|\.{1,2}\/|~\/|\/|@|[^"'`\s]+\/))[^\s]*)$/ + +export function useCompletion(input: string, blocked: boolean, gw: GatewayClient) { + const [completions, setCompletions] = useState([]) + const [compIdx, setCompIdx] = useState(0) + const [compReplace, setCompReplace] = useState(0) + const ref = useRef('') + + useEffect(() => { + const clear = () => { + setCompletions(prev => (prev.length ? [] : prev)) + setCompIdx(prev => (prev ? 0 : prev)) + setCompReplace(prev => (prev ? 0 : prev)) + } + + if (blocked) { + ref.current = '' + clear() + + return + } + + if (input === ref.current) { + return + } + + ref.current = input + + const isSlash = input.startsWith('/') + const pathWord = isSlash ? null : (input.match(TAB_PATH_RE)?.[1] ?? null) + + if (!isSlash && !pathWord) { + clear() + + return + } + + const pathReplace = input.length - (pathWord?.length ?? 0) + + const t = setTimeout(() => { + if (ref.current !== input) { + return + } + + const req = isSlash + ? gw.request('complete.slash', { text: input }) + : gw.request('complete.path', { word: pathWord }) + + req + .then(raw => { + if (ref.current !== input) { + return + } + + const r = asRpcResult(raw) + + setCompletions(r?.items ?? []) + setCompIdx(0) + setCompReplace(isSlash ? (r?.replace_from ?? 1) : pathReplace) + }) + .catch((e: unknown) => { + if (ref.current !== input) { + return + } + + setCompletions([ + { + text: '', + display: 'completion unavailable', + meta: e instanceof Error && e.message ? e.message : 'unavailable' + } + ]) + setCompIdx(0) + setCompReplace(isSlash ? 1 : pathReplace) + }) + }, 60) + + return () => clearTimeout(t) + }, [blocked, gw, input]) + + return { completions, compIdx, setCompIdx, compReplace } +} diff --git a/ui-tui/src/hooks/useInputHistory.ts b/ui-tui/src/hooks/useInputHistory.ts new file mode 100644 index 0000000000..8192b86c8f --- /dev/null +++ b/ui-tui/src/hooks/useInputHistory.ts @@ -0,0 +1,11 @@ +import { useRef, useState } from 'react' + +import * as inputHistory from '../lib/history.js' + +export function useInputHistory() { + const historyRef = useRef(inputHistory.load()) + const [historyIdx, setHistoryIdx] = useState(null) + const historyDraftRef = useRef('') + + return { historyRef, historyIdx, setHistoryIdx, historyDraftRef, pushHistory: inputHistory.append } +} diff --git a/ui-tui/src/hooks/useQueue.ts b/ui-tui/src/hooks/useQueue.ts new file mode 100644 index 0000000000..7546d64e74 --- /dev/null +++ b/ui-tui/src/hooks/useQueue.ts @@ -0,0 +1,50 @@ +import { useCallback, useRef, useState } from 'react' + +export function useQueue() { + const queueRef = useRef([]) + const [queuedDisplay, setQueuedDisplay] = useState([]) + const queueEditRef = useRef(null) + const [queueEditIdx, setQueueEditIdx] = useState(null) + + const syncQueue = useCallback(() => setQueuedDisplay([...queueRef.current]), []) + + const setQueueEdit = useCallback((idx: number | null) => { + queueEditRef.current = idx + setQueueEditIdx(idx) + }, []) + + const enqueue = useCallback( + (text: string) => { + queueRef.current.push(text) + syncQueue() + }, + [syncQueue] + ) + + const dequeue = useCallback(() => { + const head = queueRef.current.shift() + syncQueue() + + return head + }, [syncQueue]) + + const replaceQ = useCallback( + (i: number, text: string) => { + queueRef.current[i] = text + syncQueue() + }, + [syncQueue] + ) + + return { + dequeue, + enqueue, + queueEditIdx, + queueEditRef, + queueRef, + queuedDisplay, + replaceQ, + setQueueEdit, + syncQueue + } +} diff --git a/ui-tui/src/hooks/useVirtualHistory.ts b/ui-tui/src/hooks/useVirtualHistory.ts new file mode 100644 index 0000000000..efa2642df3 --- /dev/null +++ b/ui-tui/src/hooks/useVirtualHistory.ts @@ -0,0 +1,181 @@ +import type { ScrollBoxHandle } from '@hermes/ink' +import { + type RefObject, + useCallback, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, + useSyncExternalStore +} from 'react' + +const ESTIMATE = 4 +const OVERSCAN = 40 +const MAX_MOUNTED = 260 +const COLD_START = 40 +const QUANTUM = OVERSCAN >> 1 + +const upperBound = (arr: number[], target: number) => { + let lo = 0, + hi = arr.length + + while (lo < hi) { + const mid = (lo + hi) >> 1 + arr[mid]! <= target ? (lo = mid + 1) : (hi = mid) + } + + return lo +} + +export function useVirtualHistory( + scrollRef: RefObject, + items: readonly { key: string }[], + { estimate = ESTIMATE, overscan = OVERSCAN, maxMounted = MAX_MOUNTED, coldStartCount = COLD_START } = {} +) { + const nodes = useRef(new Map()) + const heights = useRef(new Map()) + const refs = useRef(new Map void>()) + const [ver, setVer] = useState(0) + const [hasScrollRef, setHasScrollRef] = useState(false) + const metrics = useRef({ sticky: true, top: 0, vp: 0 }) + + useLayoutEffect(() => { + setHasScrollRef(Boolean(scrollRef.current)) + }, [scrollRef]) + + useSyncExternalStore( + useCallback( + (cb: () => void) => (hasScrollRef ? scrollRef.current?.subscribe(cb) : null) ?? (() => () => {}), + [hasScrollRef, scrollRef] + ), + () => { + const s = scrollRef.current + + if (!s) { + return NaN + } + + const b = Math.floor(s.getScrollTop() / QUANTUM) + + return s.isSticky() ? -b - 1 : b + }, + () => NaN + ) + + useEffect(() => { + const keep = new Set(items.map(i => i.key)) + let dirty = false + + for (const k of heights.current.keys()) { + if (!keep.has(k)) { + heights.current.delete(k) + nodes.current.delete(k) + refs.current.delete(k) + dirty = true + } + } + + if (dirty) { + setVer(v => v + 1) + } + }, [items]) + + const offsets = useMemo(() => { + void ver + const out = new Array(items.length + 1).fill(0) + + for (let i = 0; i < items.length; i++) { + out[i + 1] = out[i]! + Math.max(1, Math.floor(heights.current.get(items[i]!.key) ?? estimate)) + } + + return out + }, [estimate, items, ver]) + + const total = offsets[items.length] ?? 0 + const top = Math.max(0, scrollRef.current?.getScrollTop() ?? 0) + const vp = Math.max(0, scrollRef.current?.getViewportHeight() ?? 0) + const sticky = scrollRef.current?.isSticky() ?? true + + let start = 0, + end = items.length + + if (items.length > 0) { + if (vp <= 0) { + start = Math.max(0, items.length - coldStartCount) + } else { + start = Math.max(0, Math.min(items.length - 1, upperBound(offsets, Math.max(0, top - overscan)) - 1)) + end = Math.max(start + 1, Math.min(items.length, upperBound(offsets, top + vp + overscan))) + } + } + + if (end - start > maxMounted) { + sticky ? (start = Math.max(0, end - maxMounted)) : (end = Math.min(items.length, start + maxMounted)) + } + + const measureRef = useCallback((key: string) => { + let fn = refs.current.get(key) + + if (!fn) { + fn = (el: unknown) => (el ? nodes.current.set(key, el) : nodes.current.delete(key)) + refs.current.set(key, fn) + } + + return fn + }, []) + + useLayoutEffect(() => { + let dirty = false + + for (let i = start; i < end; i++) { + const k = items[i]?.key + + if (!k) { + continue + } + + const h = Math.ceil((nodes.current.get(k) as MeasuredNode | undefined)?.yogaNode?.getComputedHeight?.() ?? 0) + + if (h > 0 && heights.current.get(k) !== h) { + heights.current.set(k, h) + dirty = true + } + } + + const s = scrollRef.current + + if (s) { + const next = { + sticky: s.isSticky(), + top: Math.max(0, s.getScrollTop() + s.getPendingDelta()), + vp: Math.max(0, s.getViewportHeight()) + } + + if ( + next.sticky !== metrics.current.sticky || + next.top !== metrics.current.top || + next.vp !== metrics.current.vp + ) { + metrics.current = next + dirty = true + } + } + + if (dirty) { + setVer(v => v + 1) + } + }, [end, hasScrollRef, items, scrollRef, start]) + + return { + bottomSpacer: Math.max(0, total - (offsets[end] ?? total)), + end, + measureRef, + offsets, + start, + topSpacer: offsets[start] ?? 0 + } +} + +interface MeasuredNode { + yogaNode?: { getComputedHeight?: () => number } | null +} diff --git a/ui-tui/src/lib/externalCli.ts b/ui-tui/src/lib/externalCli.ts new file mode 100644 index 0000000000..7ff88f2b86 --- /dev/null +++ b/ui-tui/src/lib/externalCli.ts @@ -0,0 +1,16 @@ +import { spawn } from 'node:child_process' + +export interface LaunchResult { + code: null | number + error?: string +} + +const resolveHermesBin = () => process.env.HERMES_BIN?.trim() || 'hermes' + +export const launchHermesCommand = (args: string[]): Promise => + new Promise(resolve => { + const child = spawn(resolveHermesBin(), args, { stdio: 'inherit' }) + + child.on('error', err => resolve({ code: null, error: err.message })) + child.on('exit', code => resolve({ code })) + }) diff --git a/ui-tui/src/lib/history.ts b/ui-tui/src/lib/history.ts new file mode 100644 index 0000000000..9affbb8085 --- /dev/null +++ b/ui-tui/src/lib/history.ts @@ -0,0 +1,82 @@ +import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs' +import { homedir } from 'node:os' +import { join } from 'node:path' + +const MAX = 1000 +const dir = process.env.HERMES_HOME ?? join(homedir(), '.hermes') +const file = join(dir, '.hermes_history') + +let cache: string[] | null = null + +export function load() { + if (cache) { + return cache + } + + try { + if (!existsSync(file)) { + cache = [] + + return cache + } + + const entries: string[] = [] + let current: string[] = [] + + for (const line of readFileSync(file, 'utf8').split('\n')) { + if (line.startsWith('+')) { + current.push(line.slice(1)) + } else if (current.length) { + entries.push(current.join('\n')) + current = [] + } + } + + if (current.length) { + entries.push(current.join('\n')) + } + + cache = entries.slice(-MAX) + } catch { + cache = [] + } + + return cache +} + +export function append(line: string) { + const trimmed = line.trim() + + if (!trimmed) { + return + } + + const items = load() + + if (items.at(-1) === trimmed) { + return + } + + items.push(trimmed) + + if (items.length > MAX) { + items.splice(0, items.length - MAX) + } + + try { + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }) + } + + const ts = new Date().toISOString().replace('T', ' ').replace('Z', '') + + const encoded = trimmed + .split('\n') + .map(l => `+${l}`) + .join('\n') + + appendFileSync(file, `\n# ${ts}\n${encoded}\n`) + } catch { + void 0 + } +} diff --git a/ui-tui/src/lib/messages.ts b/ui-tui/src/lib/messages.ts new file mode 100644 index 0000000000..a459ec5a8a --- /dev/null +++ b/ui-tui/src/lib/messages.ts @@ -0,0 +1,4 @@ +import type { Msg, Role } from '../types.js' + +export const upsert = (prev: Msg[], role: Role, text: string): Msg[] => + prev.at(-1)?.role === role ? [...prev.slice(0, -1), { role, text }] : [...prev, { role, text }] diff --git a/ui-tui/src/lib/osc52.ts b/ui-tui/src/lib/osc52.ts new file mode 100644 index 0000000000..d990829921 --- /dev/null +++ b/ui-tui/src/lib/osc52.ts @@ -0,0 +1,2 @@ +export const writeOsc52Clipboard = (s: string) => + process.stdout.write(`\x1b]52;c;${Buffer.from(s, 'utf8').toString('base64')}\x07`) diff --git a/ui-tui/src/lib/rpc.ts b/ui-tui/src/lib/rpc.ts new file mode 100644 index 0000000000..1697d142bb --- /dev/null +++ b/ui-tui/src/lib/rpc.ts @@ -0,0 +1,33 @@ +import type { CommandDispatchResponse } from '../gatewayTypes.js' + +export type RpcResult = Record + +export const asRpcResult = (value: unknown): T | null => + !value || typeof value !== 'object' || Array.isArray(value) ? null : (value as T) + +export const asCommandDispatch = (value: unknown): CommandDispatchResponse | null => { + const o = asRpcResult(value) + + if (!o || typeof o.type !== 'string') { + return null + } + + const t = o.type + + if (t === 'exec' || t === 'plugin') { + return { type: t, output: typeof o.output === 'string' ? o.output : undefined } + } + + if (t === 'alias' && typeof o.target === 'string') { + return { type: 'alias', target: o.target } + } + + if (t === 'skill' && typeof o.name === 'string') { + return { type: 'skill', name: o.name, message: typeof o.message === 'string' ? o.message : undefined } + } + + return null +} + +export const rpcErrorMessage = (err: unknown) => + err instanceof Error && err.message ? err.message : typeof err === 'string' && err.trim() ? err : 'request failed' diff --git a/ui-tui/src/lib/text.test.ts b/ui-tui/src/lib/text.test.ts new file mode 100644 index 0000000000..1a3800ec76 --- /dev/null +++ b/ui-tui/src/lib/text.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' + +import { stripTrailingPasteNewlines } from './text.js' + +describe('stripTrailingPasteNewlines', () => { + it('removes trailing newline runs from pasted text', () => { + expect(stripTrailingPasteNewlines('alpha\n')).toBe('alpha') + expect(stripTrailingPasteNewlines('alpha\nbeta\n\n')).toBe('alpha\nbeta') + }) + + it('preserves interior newlines', () => { + expect(stripTrailingPasteNewlines('alpha\nbeta\ngamma')).toBe('alpha\nbeta\ngamma') + }) + + it('preserves newline-only pastes', () => { + expect(stripTrailingPasteNewlines('\n\n')).toBe('\n\n') + }) +}) diff --git a/ui-tui/src/lib/text.ts b/ui-tui/src/lib/text.ts new file mode 100644 index 0000000000..fb10d7d2d4 --- /dev/null +++ b/ui-tui/src/lib/text.ts @@ -0,0 +1,197 @@ +import { THINKING_COT_MAX } from '../config/limits.js' +import type { ThinkingMode } from '../types.js' + +const ESC = String.fromCharCode(27) +const ANSI_RE = new RegExp(`${ESC}\\[[0-9;]*m`, 'g') +const WS_RE = /\s+/g + +export const stripAnsi = (s: string) => s.replace(ANSI_RE, '') + +export const hasAnsi = (s: string) => s.includes(`${ESC}[`) || s.includes(`${ESC}]`) + +const renderEstimateLine = (line: string) => { + const trimmed = line.trim() + + if (trimmed.startsWith('|')) { + return trimmed + .split('|') + .filter(Boolean) + .map(cell => cell.trim()) + .join(' ') + } + + return line + .replace(/!\[(.*?)\]\(([^)\s]+)\)/g, '[image: $1]') + .replace(/\[(.+?)\]\((https?:\/\/[^\s)]+)\)/g, '$1') + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*(.+?)\*\*/g, '$1') + .replace(/__(.+?)__/g, '$1') + .replace(/\*(.+?)\*/g, '$1') + .replace(/_(.+?)_/g, '$1') + .replace(/~~(.+?)~~/g, '$1') + .replace(/==(.+?)==/g, '$1') + .replace(/\[\^([^\]]+)\]/g, '[$1]') + .replace(/^#{1,6}\s+/, '') + .replace(/^\s*[-*+]\s+\[( |x|X)\]\s+/, (_m, checked: string) => `• [${checked.toLowerCase() === 'x' ? 'x' : ' '}] `) + .replace(/^\s*[-*+]\s+/, '• ') + .replace(/^\s*(\d+)\.\s+/, '$1. ') + .replace(/^\s*(?:>\s*)+/, '│ ') +} + +export const compactPreview = (s: string, max: number) => { + const one = s.replace(WS_RE, ' ').trim() + + return !one ? '' : one.length > max ? one.slice(0, max - 1) + '…' : one +} + +export const estimateTokensRough = (text: string) => (!text ? 0 : (text.length + 3) >> 2) + +export const edgePreview = (s: string, head = 16, tail = 28) => { + const one = s.replace(WS_RE, ' ').trim().replace(/\]\]/g, '] ]') + + return !one + ? '' + : one.length <= head + tail + 4 + ? one + : `${one.slice(0, head).trimEnd()}.. ${one.slice(-tail).trimStart()}` +} + +export const pasteTokenLabel = (text: string, lineCount: number) => { + const preview = edgePreview(text) + + if (!preview) { + return `[[ [${fmtK(lineCount)} lines] ]]` + } + + const [head = preview, tail = ''] = preview.split('.. ', 2) + + return tail + ? `[[ ${head.trimEnd()}.. [${fmtK(lineCount)} lines] .. ${tail.trimStart()} ]]` + : `[[ ${preview} [${fmtK(lineCount)} lines] ]]` +} + +export const thinkingPreview = (reasoning: string, mode: ThinkingMode, max: number = THINKING_COT_MAX) => { + const raw = reasoning.trim() + + return !raw || mode === 'collapsed' ? '' : mode === 'full' ? raw : compactPreview(raw.replace(WS_RE, ' '), max) +} + +export const stripTrailingPasteNewlines = (text: string) => (/[^\n]/.test(text) ? text.replace(/\n+$/, '') : text) + +export const toolTrailLabel = (name: string) => + name + .split('_') + .filter(Boolean) + .map(p => p[0]!.toUpperCase() + p.slice(1)) + .join(' ') || name + +export const formatToolCall = (name: string, context = '') => { + const label = toolTrailLabel(name) + const preview = compactPreview(context, 64) + + return preview ? `${label}("${preview}")` : label +} + +export const buildToolTrailLine = (name: string, context: string, error?: boolean, note?: string) => { + const detail = compactPreview(note ?? '', 72) + + return `${formatToolCall(name, context)}${detail ? ` :: ${detail}` : ''} ${error ? ' ✗' : ' ✓'}` +} + +export const isToolTrailResultLine = (line: string) => line.endsWith(' ✓') || line.endsWith(' ✗') + +export const parseToolTrailResultLine = (line: string) => { + if (!isToolTrailResultLine(line)) { + return null + } + + const mark = line.endsWith(' ✗') ? '✗' : '✓' + const body = line.slice(0, -2) + const [call, detail] = body.split(' :: ', 2) + + if (detail != null) { + return { call, detail, mark } + } + + const legacy = body.indexOf(': ') + + if (legacy > 0) { + return { call: body.slice(0, legacy), detail: body.slice(legacy + 2), mark } + } + + return { call: body, detail: '', mark } +} + +export const isTransientTrailLine = (line: string) => line.startsWith('drafting ') || line === 'analyzing tool output…' + +export const sameToolTrailGroup = (label: string, entry: string) => + entry === `${label} ✓` || + entry === `${label} ✗` || + entry.startsWith(`${label}(`) || + entry.startsWith(`${label} ::`) || + entry.startsWith(`${label}:`) + +export const lastCotTrailIndex = (trail: readonly string[]) => { + for (let i = trail.length - 1; i >= 0; i--) { + if (!isToolTrailResultLine(trail[i]!)) { + return i + } + } + + return -1 +} + +export const estimateRows = (text: string, w: number, compact = false) => { + let fence: { char: '`' | '~'; len: number } | null = null + let rows = 0 + + for (const raw of text.split('\n')) { + const line = stripAnsi(raw) + const maybeFence = line.match(/^\s*(`{3,}|~{3,})(.*)$/) + + if (maybeFence) { + const marker = maybeFence[1]! + const lang = maybeFence[2]!.trim() + + if (!fence) { + fence = { char: marker[0] as '`' | '~', len: marker.length } + + if (lang) { + rows += Math.ceil((`─ ${lang}`.length || 1) / w) + } + } else if (marker[0] === fence.char && marker.length >= fence.len) { + fence = null + } + + continue + } + + const inCode = Boolean(fence) + const trimmed = line.trim() + + if (!inCode && trimmed.startsWith('|') && /^[|\s:-]+$/.test(trimmed)) { + continue + } + + const rendered = inCode ? line : renderEstimateLine(line) + + if (compact && !rendered.trim()) { + continue + } + + rows += Math.ceil((rendered.length || 1) / w) + } + + return Math.max(1, rows) +} + +export const flat = (r: Record) => Object.values(r).flat() + +const COMPACT_NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 1, notation: 'compact' }) + +export const fmtK = (n: number) => COMPACT_NUMBER.format(n).replace(/[KMBT]$/, s => s.toLowerCase()) + +export const pick = (a: T[]) => a[Math.floor(Math.random() * a.length)]! + +export const isPasteBackedText = (text: string) => + /\[\[paste:\d+(?:[^\n]*?)\]\]|\[paste #\d+ (?:attached|excerpt)(?:[^\n]*?)\]/.test(text) diff --git a/ui-tui/src/protocol/interpolation.ts b/ui-tui/src/protocol/interpolation.ts new file mode 100644 index 0000000000..804cf1cf04 --- /dev/null +++ b/ui-tui/src/protocol/interpolation.ts @@ -0,0 +1,3 @@ +export const INTERPOLATION_RE = /\{!(.+?)\}/g + +export const hasInterpolation = (s: string) => /\{!.+?\}/.test(s) diff --git a/ui-tui/src/protocol/paste.ts b/ui-tui/src/protocol/paste.ts new file mode 100644 index 0000000000..9eae137cea --- /dev/null +++ b/ui-tui/src/protocol/paste.ts @@ -0,0 +1 @@ +export const PASTE_SNIPPET_RE = /\[\[[^\n]*?\]\]/g diff --git a/ui-tui/src/theme.ts b/ui-tui/src/theme.ts new file mode 100644 index 0000000000..88bc3c3908 --- /dev/null +++ b/ui-tui/src/theme.ts @@ -0,0 +1,193 @@ +export interface ThemeColors { + gold: string + amber: string + bronze: string + cornsilk: string + dim: string + completionBg: string + completionCurrentBg: string + + label: string + ok: string + error: string + warn: string + + prompt: string + sessionLabel: string + sessionBorder: string + + statusBg: string + statusFg: string + statusGood: string + statusWarn: string + statusBad: string + statusCritical: string + selectionBg: string + + diffAdded: string + diffRemoved: string + diffAddedWord: string + diffRemovedWord: string + + shellDollar: string +} + +export interface ThemeBrand { + name: string + icon: string + prompt: string + welcome: string + goodbye: string + tool: string + helpHeader: string +} + +export interface Theme { + color: ThemeColors + brand: ThemeBrand + bannerLogo: string + bannerHero: string +} + +// ── Color math ─────────────────────────────────────────────────────── + +function parseHex(h: string): [number, number, number] | null { + const m = /^#?([0-9a-f]{6})$/i.exec(h) + + if (!m) { + return null + } + + const n = parseInt(m[1]!, 16) + + return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff] +} + +function mix(a: string, b: string, t: number) { + const pa = parseHex(a) + const pb = parseHex(b) + + if (!pa || !pb) { + return a + } + + const lerp = (i: 0 | 1 | 2) => Math.round(pa[i] + (pb[i] - pa[i]) * t) + + return '#' + ((1 << 24) | (lerp(0) << 16) | (lerp(1) << 8) | lerp(2)).toString(16).slice(1) +} + +// ── Defaults ───────────────────────────────────────────────────────── + +export const DEFAULT_THEME: Theme = { + color: { + gold: '#FFD700', + amber: '#FFBF00', + bronze: '#CD7F32', + cornsilk: '#FFF8DC', + dim: '#B8860B', + completionBg: '#FFFFFF', + completionCurrentBg: mix('#FFFFFF', '#FFBF00', 0.25), + + label: '#DAA520', + ok: '#4caf50', + error: '#ef5350', + warn: '#ffa726', + + prompt: '#FFF8DC', + sessionLabel: '#B8860B', + sessionBorder: '#B8860B', + + statusBg: '#1a1a2e', + statusFg: '#C0C0C0', + statusGood: '#8FBC8F', + statusWarn: '#FFD700', + statusBad: '#FF8C00', + statusCritical: '#FF6B6B', + selectionBg: '#3a3a55', + + diffAdded: 'rgb(220,255,220)', + diffRemoved: 'rgb(255,220,220)', + diffAddedWord: 'rgb(36,138,61)', + diffRemovedWord: 'rgb(207,34,46)', + shellDollar: '#4dabf7' + }, + + brand: { + name: 'Hermes Agent', + icon: '⚕', + prompt: '❯', + welcome: 'Type your message or /help for commands.', + goodbye: 'Goodbye! ⚕', + tool: '┊', + helpHeader: '(^_^)? Commands' + }, + + bannerLogo: '', + bannerHero: '' +} + +// ── Skin → Theme ───────────────────────────────────────────────────── + +export function fromSkin( + colors: Record, + branding: Record, + bannerLogo = '', + bannerHero = '', + toolPrefix = '', + helpHeader = '' +): Theme { + const d = DEFAULT_THEME + const c = (k: string) => colors[k] + + const amber = c('ui_accent') ?? c('banner_accent') ?? d.color.amber + const accent = c('banner_accent') ?? c('banner_title') ?? d.color.amber + const dim = c('banner_dim') ?? d.color.dim + + return { + color: { + gold: c('banner_title') ?? d.color.gold, + amber, + bronze: c('banner_border') ?? d.color.bronze, + cornsilk: c('banner_text') ?? d.color.cornsilk, + dim, + completionBg: c('completion_menu_bg') ?? '#FFFFFF', + completionCurrentBg: c('completion_menu_current_bg') ?? mix('#FFFFFF', accent, 0.25), + + label: c('ui_label') ?? d.color.label, + ok: c('ui_ok') ?? d.color.ok, + error: c('ui_error') ?? d.color.error, + warn: c('ui_warn') ?? d.color.warn, + + prompt: c('prompt') ?? c('banner_text') ?? d.color.prompt, + sessionLabel: c('session_label') ?? dim, + sessionBorder: c('session_border') ?? dim, + + statusBg: d.color.statusBg, + statusFg: d.color.statusFg, + statusGood: c('ui_ok') ?? d.color.statusGood, + statusWarn: c('ui_warn') ?? d.color.statusWarn, + statusBad: d.color.statusBad, + statusCritical: d.color.statusCritical, + selectionBg: c('selection_bg') ?? d.color.selectionBg, + + diffAdded: d.color.diffAdded, + diffRemoved: d.color.diffRemoved, + diffAddedWord: d.color.diffAddedWord, + diffRemovedWord: d.color.diffRemovedWord, + shellDollar: c('shell_dollar') ?? d.color.shellDollar + }, + + brand: { + name: branding.agent_name ?? d.brand.name, + icon: d.brand.icon, + prompt: branding.prompt_symbol ?? d.brand.prompt, + welcome: branding.welcome ?? d.brand.welcome, + goodbye: branding.goodbye ?? d.brand.goodbye, + tool: toolPrefix || d.brand.tool, + helpHeader: branding.help_header ?? (helpHeader || d.brand.helpHeader) + }, + + bannerLogo, + bannerHero + } +} diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.ts new file mode 100644 index 0000000000..ab7d7efab9 --- /dev/null +++ b/ui-tui/src/types.ts @@ -0,0 +1,109 @@ +export interface ActiveTool { + context?: string + id: string + name: string + startedAt?: number +} + +export interface ActivityItem { + id: number + text: string + tone: 'error' | 'info' | 'warn' +} + +export interface SubagentProgress { + durationSeconds?: number + goal: string + id: string + index: number + notes: string[] + status: 'completed' | 'failed' | 'interrupted' | 'running' + summary?: string + taskCount: number + thinking: string[] + tools: string[] +} + +export interface ApprovalReq { + command: string + description: string +} + +export interface ClarifyReq { + choices: string[] | null + question: string + requestId: string +} + +export interface Msg { + info?: SessionInfo + kind?: 'intro' | 'panel' | 'slash' | 'trail' + panelData?: PanelData + role: Role + text: string + thinking?: string + thinkingTokens?: number + toolTokens?: number + tools?: string[] +} + +export type Role = 'assistant' | 'system' | 'tool' | 'user' +export type DetailsMode = 'hidden' | 'collapsed' | 'expanded' +export type ThinkingMode = 'collapsed' | 'truncated' | 'full' + +export interface SessionInfo { + cwd?: string + model: string + release_date?: string + skills: Record + tools: Record + update_behind?: number | null + update_command?: string + usage?: Usage + version?: string +} + +export interface Usage { + calls: number + context_max?: number + context_percent?: number + context_used?: number + input: number + output: number + total: number +} + +export interface SudoReq { + requestId: string +} + +export interface SecretReq { + envVar: string + prompt: string + requestId: string +} + +export interface PanelData { + sections: PanelSection[] + title: string +} + +export interface PanelSection { + items?: string[] + rows?: [string, string][] + text?: string + title?: string +} + +export interface SlashCatalog { + canon: Record + categories: SlashCategory[] + pairs: [string, string][] + skillCount: number + sub: Record +} + +export interface SlashCategory { + name: string + pairs: [string, string][] +} diff --git a/ui-tui/src/types/hermes-ink.d.ts b/ui-tui/src/types/hermes-ink.d.ts new file mode 100644 index 0000000000..9b2deec35f --- /dev/null +++ b/ui-tui/src/types/hermes-ink.d.ts @@ -0,0 +1,108 @@ +import type * as React from 'react' + +declare module '@hermes/ink' { + export type Key = { + readonly ctrl: boolean + readonly meta: boolean + readonly shift: boolean + readonly alt: boolean + readonly upArrow: boolean + readonly downArrow: boolean + readonly leftArrow: boolean + readonly rightArrow: boolean + readonly return: boolean + readonly backspace: boolean + readonly delete: boolean + readonly escape: boolean + readonly tab: boolean + readonly pageUp: boolean + readonly pageDown: boolean + readonly wheelUp: boolean + readonly wheelDown: boolean + readonly home: boolean + readonly end: boolean + readonly [key: string]: boolean + } + + export type InputEvent = { + readonly input: string + readonly key: Key + readonly keypress: { readonly raw?: string } + } + + export type InputHandler = (input: string, key: Key, event: InputEvent) => void + + export type RenderOptions = { + readonly stdin?: NodeJS.ReadStream + readonly stdout?: NodeJS.WriteStream + readonly stderr?: NodeJS.WriteStream + readonly exitOnCtrlC?: boolean + } + + export type Instance = { + readonly rerender: (node: React.ReactNode) => void + readonly unmount: () => void + readonly waitUntilExit: () => Promise + readonly cleanup: () => void + } + + export type ScrollBoxHandle = { + readonly scrollTo: (y: number) => void + readonly scrollBy: (dy: number) => void + readonly scrollToElement: (el: unknown, offset?: number) => void + readonly scrollToBottom: () => void + readonly getScrollTop: () => number + readonly getPendingDelta: () => number + readonly getScrollHeight: () => number + readonly getViewportHeight: () => number + readonly getViewportTop: () => number + readonly isSticky: () => boolean + readonly subscribe: (listener: () => void) => () => void + } + + export const Box: React.ComponentType + export const AlternateScreen: React.ComponentType + export const Ansi: React.ComponentType + export const NoSelect: React.ComponentType + export const ScrollBox: React.ComponentType + export const Text: React.ComponentType + export const TextInput: React.ComponentType + export const stringWidth: (s: string) => number + + export function render(node: React.ReactNode, options?: NodeJS.WriteStream | RenderOptions): Instance + + export function useApp(): { readonly exit: (error?: Error) => void } + export type RunExternalProcess = () => Promise + export function useExternalProcess(): (run: RunExternalProcess) => Promise + export function withInkSuspended(run: RunExternalProcess): Promise + export function useInput(handler: InputHandler, options?: { readonly isActive?: boolean }): void + export function useSelection(): { + readonly copySelection: () => string + readonly copySelectionNoClear: () => string + readonly clearSelection: () => void + readonly hasSelection: () => boolean + readonly getState: () => unknown + readonly subscribe: (cb: () => void) => () => void + readonly shiftAnchor: (dRow: number, minRow: number, maxRow: number) => void + readonly shiftSelection: (dRow: number, minRow: number, maxRow: number) => void + readonly moveFocus: (move: unknown) => void + readonly captureScrolledRows: (firstRow: number, lastRow: number, side: 'above' | 'below') => void + readonly setSelectionBgColor: (color: string) => void + } + export function useHasSelection(): boolean + export function useStdout(): { readonly stdout?: NodeJS.WriteStream } + export function useTerminalFocus(): boolean + export function useDeclaredCursor(args: { + readonly line: number + readonly column: number + readonly active: boolean + }): (el: unknown) => void + export function useStdin(): { + readonly stdin: NodeJS.ReadStream + readonly setRawMode: (value: boolean) => void + readonly isRawModeSupported: boolean + readonly exitOnCtrlC: boolean + readonly inputEmitter: NodeJS.EventEmitter + readonly querier: unknown + } +} diff --git a/ui-tui/tsconfig.build.json b/ui-tui/tsconfig.build.json new file mode 100644 index 0000000000..a0a8b410d8 --- /dev/null +++ b/ui-tui/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@hermes/ink": ["src/types/hermes-ink.d.ts"] + } + } +} diff --git a/ui-tui/tsconfig.json b/ui-tui/tsconfig.json new file mode 100644 index 0000000000..67a50d6a7b --- /dev/null +++ b/ui-tui/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "nodenext", + "moduleResolution": "nodenext", + "jsx": "react-jsx", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": false, + "sourceMap": false, + "resolveJsonModule": true + }, + "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.tsx"], + "exclude": ["src/__tests__", "node_modules", "dist"] +} diff --git a/ui-tui/vitest.config.ts b/ui-tui/vitest.config.ts new file mode 100644 index 0000000000..b3efa48af9 --- /dev/null +++ b/ui-tui/vitest.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + exclude: ['dist/**', 'node_modules/**'] + } +}) diff --git a/website/docs/getting-started/quickstart.md b/website/docs/getting-started/quickstart.md index bda74b9ed4..428d23b7ce 100644 --- a/website/docs/getting-started/quickstart.md +++ b/website/docs/getting-started/quickstart.md @@ -78,11 +78,16 @@ You can switch providers at any time with `hermes model` — no code changes, no ## 3. Start Chatting ```bash -hermes +hermes # classic CLI +hermes --tui # modern TUI (recommended) ``` That's it! You'll see a welcome banner with your model, available tools, and skills. Type a message and press Enter. +:::tip Pick your interface +Hermes ships with two terminal interfaces: the classic `prompt_toolkit` CLI and a newer [TUI](../user-guide/tui.md) with modal overlays, mouse selection, and non-blocking input. Both share the same sessions, slash commands, and config — try each with `hermes` vs `hermes --tui`. +::: + ``` ❯ What can you help me with? ``` diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md index fb93cf6480..6b08552676 100644 --- a/website/docs/reference/cli-commands.md +++ b/website/docs/reference/cli-commands.md @@ -27,6 +27,8 @@ hermes [global-options] [subcommand/options] | `--worktree`, `-w` | Start in an isolated git worktree for parallel-agent workflows. | | `--yolo` | Bypass dangerous-command approval prompts. | | `--pass-session-id` | Include the session ID in the agent's system prompt. | +| `--tui` | Launch the [TUI](../user-guide/tui.md) instead of the classic CLI. Equivalent to `HERMES_TUI=1`. | +| `--dev` | With `--tui`: run the TypeScript sources directly via `tsx` instead of the prebuilt bundle (for TUI contributors). | ## Top-level commands diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md index b6cfabb3d6..ead884ba7b 100644 --- a/website/docs/reference/environment-variables.md +++ b/website/docs/reference/environment-variables.md @@ -346,6 +346,13 @@ For cloud sandbox backends, persistence is filesystem-oriented. `TERMINAL_LIFETI | `HERMES_BACKGROUND_NOTIFICATIONS` | Background process notification mode in gateway: `all` (default), `result`, `error`, `off` | | `HERMES_EPHEMERAL_SYSTEM_PROMPT` | Ephemeral system prompt injected at API-call time (never persisted to sessions) | +## Interface + +| Variable | Description | +|----------|-------------| +| `HERMES_TUI` | Launch the [TUI](../user-guide/tui.md) instead of the classic CLI when set to `1`. Equivalent to passing `--tui`. | +| `HERMES_TUI_DIR` | Path to a prebuilt `ui-tui/` directory (must contain `dist/entry.js` and populated `node_modules`). Used by distros and Nix to skip the first-launch `npm install`. | + ## Cron Scheduler | Variable | Description | diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.md index 43d12611f9..62e70e3cc3 100644 --- a/website/docs/user-guide/cli.md +++ b/website/docs/user-guide/cli.md @@ -8,6 +8,10 @@ description: "Master the Hermes Agent terminal interface — commands, keybindin Hermes Agent's CLI is a full terminal user interface (TUI) — not a web UI. It features multiline editing, slash-command autocomplete, conversation history, interrupt-and-redirect, and streaming tool output. Built for people who live in the terminal. +:::tip +Hermes also ships a modern TUI with modal overlays, mouse selection, and non-blocking input. Launch it with `hermes --tui` — see the [TUI](tui.md) guide. +::: + ## Running the CLI ```bash diff --git a/website/docs/user-guide/tui.md b/website/docs/user-guide/tui.md new file mode 100644 index 0000000000..a296a63f7b --- /dev/null +++ b/website/docs/user-guide/tui.md @@ -0,0 +1,142 @@ +--- +sidebar_position: 2 +title: "TUI" +description: "Launch the modern terminal UI for Hermes — mouse-friendly, rich overlays, and non-blocking input." +--- + +# TUI + +The TUI is the modern front-end for Hermes — a terminal UI backed by the same Python runtime as the [Classic CLI](cli.md). Same agent, same sessions, same slash commands; a cleaner, more responsive surface for interacting with them. + +It's the recommended way to run Hermes interactively. + +## Launch + +```bash +# Launch the TUI +hermes --tui + +# Resume the latest TUI session (falls back to the latest classic session) +hermes --tui -c +hermes --tui --continue + +# Resume a specific session by ID or title +hermes --tui -r 20260409_000000_aa11bb +hermes --tui --resume "my t0p session" + +# Run source directly — skips the prebuild step (for TUI contributors) +hermes --tui --dev +``` + +You can also enable it via env var: + +```bash +export HERMES_TUI=1 +hermes # now uses the TUI +hermes chat # same +``` + +The classic CLI remains available as the default. Anything documented in [CLI Interface](cli.md) — slash commands, quick commands, skill preloading, personalities, multi-line input, interrupts — works in the TUI identically. + +## Why the TUI + +- **Instant first frame** — the banner paints before the app finishes loading, so the terminal never feels frozen while Hermes is starting. +- **Non-blocking input** — type and queue messages before the session is ready. Your first prompt sends the moment the agent comes online. +- **Rich overlays** — model picker, session picker, approval and clarification prompts all render as modal panels rather than inline flows. +- **Live session panel** — tools and skills fill in progressively as they initialize. +- **Mouse-friendly selection** — drag to highlight with a uniform background instead of SGR inverse. Copy with your terminal's normal copy gesture. +- **Alternate-screen rendering** — differential updates mean no flicker when streaming, no scrollback clutter after you quit. +- **Composer affordances** — inline paste-collapse for long snippets, image paste from the clipboard (`Alt+V`), bracketed-paste safety. + +Same [skins](features/skins.md) and [personalities](features/personality.md) apply. Switch mid-session with `/skin ares`, `/personality pirate`, and the UI repaints live. Skin keys are marked `(both)`, `(classic)`, or `(tui)` in [`example-skin.yaml`](https://github.com/NousResearch/hermes-agent/blob/main/docs/skins/example-skin.yaml) so you can see at a glance what applies where — the TUI honors the banner palette, UI colors, prompt glyph/color, session display, completion menu, selection bg, `tool_prefix`, and `help_header`. + +## Requirements + +- **Node.js** ≥ 20 — the TUI runs as a subprocess launched from the Python CLI. `hermes doctor` verifies this. +- **TTY** — like the classic CLI, piping stdin or running in non-interactive environments falls back to single-query mode. + +On first launch Hermes installs the TUI's Node dependencies into `ui-tui/node_modules` (one-time, a few seconds). Subsequent launches are fast. If you pull a new Hermes version, the TUI bundle is rebuilt automatically when sources are newer than the dist. + +### External prebuild + +Distributions that ship a prebuilt bundle (Nix, system packages) can point Hermes at it: + +```bash +export HERMES_TUI_DIR=/path/to/prebuilt/ui-tui +hermes --tui +``` + +The directory must contain `dist/entry.js` and an up-to-date `node_modules`. + +## Keybindings + +Keybindings match the [Classic CLI](cli.md#keybindings) exactly. The only behavioral differences: + +- **Mouse drag** highlights text with a uniform selection background. +- **`Ctrl+V`** pastes text from your clipboard directly into the composer; multi-line pastes stay on one row until you expand them. +- **Slash autocompletion** opens as a floating panel with descriptions, not an inline dropdown. + +## Slash commands + +All slash commands work unchanged. A few are TUI-owned — they produce richer output or render as overlays rather than inline panels: + +| Command | TUI behavior | +|---------|--------------| +| `/help` | Overlay with categorized commands, arrow-key navigable | +| `/sessions` | Modal session picker — preview, title, token totals, resume inline | +| `/model` | Modal model picker grouped by provider, with cost hints | +| `/skin` | Live preview — theme change applies as you browse | +| `/details` | Toggle verbose tool-call details in the transcript | +| `/usage` | Rich token / cost / context panel | + +Every other slash command (including installed skills, quick commands, and personality toggles) works identically to the classic CLI. See [Slash Commands Reference](../reference/slash-commands.md). + +## Status line + +The TUI's status line tracks agent state in real time: + +| Status | Meaning | +|--------|---------| +| `starting agent…` | Session ID is live; tools and skills still coming online. You can type — messages queue and send when ready. | +| `ready` | Agent is idle, accepting input. | +| `thinking…` / `running…` | Agent is reasoning or running a tool. | +| `interrupted` | Current turn was cancelled; press Enter to send again. | +| `forging session…` / `resuming…` | Initial connect or `--resume` handshake. | + +The per-skin status-bar colors and thresholds are shared with the classic CLI — see [Skins](features/skins.md) for customization. + +## Configuration + +The TUI respects all standard Hermes config: `~/.hermes/config.yaml`, profiles, personalities, skins, quick commands, credential pools, memory providers, tool/skill enablement. No TUI-specific config file exists. + +A handful of keys tune the TUI surface specifically: + +```yaml +display: + skin: default # any built-in or custom skin + personality: helpful + details_mode: compact # or "verbose" — default tool-call detail level + mouse_tracking: true # disable if your terminal conflicts with mouse reporting +``` + +`/details on` / `/details off` / `/details cycle` toggle this at runtime. + +## Sessions + +Sessions are shared between the TUI and the classic CLI — both write to the same `~/.hermes/state.db`. You can start a session in one, resume in the other. The session picker surfaces sessions from both sources, with a source tag. + +See [Sessions](sessions.md) for lifecycle, search, compression, and export. + +## Reverting to the classic CLI + +Launching `hermes` (without `--tui`) stays on the classic CLI. To make a machine prefer the TUI, set `HERMES_TUI=1` in your shell profile. To go back, unset it. + +If the TUI fails to launch (no Node, missing bundle, TTY issue), Hermes prints a diagnostic and falls back — rather than leaving you stuck. + +## See also + +- [CLI Interface](cli.md) — full slash command and keybinding reference (shared) +- [Sessions](sessions.md) — resume, branch, and history +- [Skins & Themes](features/skins.md) — theme the banner, status bar, and overlays +- [Voice Mode](features/voice-mode.md) — works in both interfaces +- [Configuration](configuration.md) — all config keys diff --git a/website/sidebars.ts b/website/sidebars.ts index b1f7fcf59a..c84184c4e6 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -21,6 +21,7 @@ const sidebars: SidebarsConfig = { collapsed: true, items: [ 'user-guide/cli', + 'user-guide/tui', 'user-guide/configuration', 'user-guide/sessions', 'user-guide/profiles',