From 270b228a964dc4f7fb55b211e23f7a2c7b7329f6 Mon Sep 17 00:00:00 2001 From: qingnian108 <44261124+qingnian108@users.noreply.github.com> Date: Wed, 4 Nov 2026 11:22:25 +0800 Subject: [PATCH] agent-console 1.2.0: Preview tab, chat links, file chips, font size/width settings, live magpie theme (#582) agent-console 1.2.0 by qingnian108 (#582): Preview tab, chat links, file chips, font size/width settings, live magpie theme. Reviewed and run at c459773107caa20f7063d12b2133c230f91c066c (mote, macOS, Node 22, sandbox HOME): - npm ci --workspaces=false; npm run check ok; npm test: 48 files, 339 passed, 17 skipped; npm run verify:build 5/5 OK; bun scripts/check.mjs agent-console ok. - Only test/v1/ws.test.ts changed since the last reviewed head 66d1070 (the new "preview.open returns host from previewHost()" test, through registerMethods). - Broke by hand: methods.ts `return { ...r, host: previewHost() }` -> `return r;` turns that test red (1 of 5); restored, green. Changing previewHost's body alone stays green, as the test compares to previewHost(); fix582.test.ts covers its values. - Earlier reviews' findings (per-listener key host, nonce/canary, gateway port + identity check, mentions path, Darwin major from the daemon) were checked in the earlier rounds. The proxy listens on 127.0.0.1 only and answers only the keyed Host. - Not run: preview-attack.mjs browser half at this head, Windows box. --- packages/agent-console/README.md | 21 +- packages/agent-console/app/app.css | 2 +- packages/agent-console/app/app.js | 175 +-- packages/agent-console/daemon/dist/main.js | 1374 +++++++++++++++-- .../agent-console/daemon/dist/main.js.map | 2 +- .../agent-console/daemon/src/agents/kinds.ts | 13 + .../daemon/src/agents/manager.ts | 36 +- packages/agent-console/daemon/src/config.ts | 6 + packages/agent-console/daemon/src/main.ts | 10 + .../agent-console/daemon/src/preview/host.ts | 22 + .../daemon/src/preview/inject.ts | 71 + .../agent-console/daemon/src/preview/ports.ts | 90 ++ .../agent-console/daemon/src/preview/proxy.ts | 656 ++++++++ .../agent-console/daemon/src/preview/url.ts | 123 ++ .../daemon/src/providers/acp/prompt.ts | 5 + .../daemon/src/providers/acp/session.ts | 2 +- .../daemon/src/providers/claude/map.ts | 4 +- .../daemon/src/providers/claude/session.ts | 4 +- .../daemon/src/providers/mock.ts | 22 + .../daemon/src/providers/types.ts | 3 +- .../daemon/src/store/settings.ts | 17 + .../agent-console/daemon/src/store/threads.ts | 2 + .../daemon/src/timeline/types.ts | 2 +- .../agent-console/daemon/src/util/i18n.ts | 8 + .../agent-console/daemon/src/util/mentions.ts | 84 + .../daemon/src/util/openExternal.ts | 44 + .../agent-console/daemon/src/ws/gateway.ts | 3 + .../agent-console/daemon/src/ws/methods.ts | 71 +- packages/agent-console/index.mjs | 4 + packages/agent-console/package-lock.json | 4 +- packages/agent-console/package.json | 5 +- .../agent-console/scripts/preview-attack.mjs | 210 +++ packages/agent-console/test/v1/ac12.test.ts | 488 ++++++ packages/agent-console/test/v1/fix582.test.ts | 463 ++++++ packages/agent-console/test/v1/ws.test.ts | 35 +- packages/agent-console/web/src/api/ws.ts | 5 + .../agent-console/web/src/components/Chat.tsx | 10 +- .../web/src/components/Composer.tsx | 64 +- .../web/src/components/Icons.tsx | 7 + .../web/src/components/Layout.tsx | 4 +- .../web/src/components/Markdown.tsx | 25 +- .../web/src/components/Panel.tsx | 31 + .../web/src/components/PreviewPanel.tsx | 186 +++ .../web/src/components/Settings.tsx | 23 + .../web/src/components/Sidebar.tsx | 14 + .../web/src/components/Timeline.tsx | 61 +- .../web/src/components/Topbar.tsx | 11 +- .../web/src/composer/mentions.ts | 49 + packages/agent-console/web/src/i18n/index.ts | 9 + .../agent-console/web/src/i18n/messages.ts | 44 +- .../web/src/layout/applyMagpieTokens.ts | 25 +- .../web/src/layout/chatLayout.ts | 32 + .../web/src/layout/magpieBridge.ts | 53 + .../agent-console/web/src/layout/theme.ts | 10 + packages/agent-console/web/src/main.tsx | 25 +- .../agent-console/web/src/preview/open.ts | 41 + .../agent-console/web/src/stores/preview.ts | 249 +++ packages/agent-console/web/src/stores/ui.ts | 21 +- .../agent-console/web/src/styles/chat.css | 76 +- .../agent-console/web/src/styles/composer.css | 7 +- .../agent-console/web/src/styles/layout.css | 43 +- .../agent-console/web/src/styles/tokens.css | 6 + .../agent-console/web/src/timeline/reducer.ts | 4 +- .../agent-console/web/src/timeline/types.ts | 2 +- .../agent-console/web/src/types/models.ts | 2 + .../agent-console/web/src/util/localLinks.ts | 133 ++ 66 files changed, 4995 insertions(+), 358 deletions(-) create mode 100644 packages/agent-console/daemon/src/preview/host.ts create mode 100644 packages/agent-console/daemon/src/preview/inject.ts create mode 100644 packages/agent-console/daemon/src/preview/ports.ts create mode 100644 packages/agent-console/daemon/src/preview/proxy.ts create mode 100644 packages/agent-console/daemon/src/preview/url.ts create mode 100644 packages/agent-console/daemon/src/util/mentions.ts create mode 100644 packages/agent-console/daemon/src/util/openExternal.ts create mode 100644 packages/agent-console/scripts/preview-attack.mjs create mode 100644 packages/agent-console/test/v1/ac12.test.ts create mode 100644 packages/agent-console/test/v1/fix582.test.ts create mode 100644 packages/agent-console/web/src/components/PreviewPanel.tsx create mode 100644 packages/agent-console/web/src/composer/mentions.ts create mode 100644 packages/agent-console/web/src/layout/chatLayout.ts create mode 100644 packages/agent-console/web/src/layout/magpieBridge.ts create mode 100644 packages/agent-console/web/src/preview/open.ts create mode 100644 packages/agent-console/web/src/stores/preview.ts create mode 100644 packages/agent-console/web/src/util/localLinks.ts diff --git a/packages/agent-console/README.md b/packages/agent-console/README.md index b1cb061..06993be 100644 --- a/packages/agent-console/README.md +++ b/packages/agent-console/README.md @@ -49,7 +49,12 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar - **Images**: attach or paste images (and text files). Only PNG, JPEG, GIF and WebP are sent as images. Claude Code and Codex take them natively; Claude Code gets a text file (up to 1 MB) as a plain-text document, Codex gets its path; any other file (SVG, binaries, images over Claude's 5 MB limit) goes by path, with a notice. An ACP Agent (Cursor, Copilot, OpenCode, Pi, Devin CLI, dsh) gets image blocks when its ACP `initialize` advertises `promptCapabilities.image`; otherwise it gets each image's file path (as text and a `resource_link`), so it can open it with its file tools, and the timeline says it can't see the image itself. The composer says so before you send once the Agent has been asked. dsh answers `initialize` for the route its ACP starts on (its `acp` config row, which ships as a model dsh's catalog doesn't have) and refuses image blocks otherwise, so Agent Console starts dsh with a `--patch` overlay that puts that row on the conversation's model: on a model that sees images (Magpie writes those as `input: [text, image]`) dsh then takes image blocks; after a switch to another model in the same chat, images go by path and dsh opens them with its `read_image` tool. Checked on 2026-10-31 with the real CLIs, a throwaway HOME, no sign-in and a local stand-in for the model API (`npm run test:real`, see `test/real/`): the image reaches the model request from Claude Code 2.1.316 (stream-json), Codex 0.165.0, Copilot 1.0.105 (BYOK), OpenCode 1.19.5, Pi (pi-acp 0.0.34 + pi 1.4.0) and dsh 0.2.1-rc.5; Devin CLI 3000.11.234 and Cursor 2026.10.22 advertise images and Devin gets the image block, but both need a sign-in to run a model. Inline media is capped at 10 MB per file and 16 MB per message (an ACP SDK peer refuses messages over 32 MB); larger images go by path - **Import history**: import matching sessions from `~/.claude/projects` and `~/.codex/sessions` as new threads (resumable) - **Thread management**: search (Ctrl+K), pin, rename, archive, delete (trash), export Markdown, thread info (usage / cost / session ID) -- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 8 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit`) so UI work does not burn tokens +- **Preview tab** (1.2): a small browser in the right panel for local dev servers (`localhost`, `127.0.0.1`, `[::1]`, `*.localhost`, `0.0.0.0`): address bar, back / forward, reload, open in the system browser, widen the panel. The address is remembered per conversation. Pages load through the daemon's local preview proxy (see the security model), so module scripts, `fetch` and HMR WebSockets work inside Magpie's sandboxed frame. Limits: popups, `alert` and native form posts don't run in the sandbox; `localStorage` / `sessionStorage` / `document.cookie` are in-memory and reset on reload, and cookies are not passed (use 用浏览器打开 / Open in browser for logins) +- **Links in chat** (1.2): local addresses in agent text, rendered Markdown and tool output (`localhost:5173`, `http://127.0.0.1:8080/x`, …) become links that open in the Preview tab; Ctrl/⌘+click, and any other `http(s)` link, opens the system browser through the daemon (`app.openExternal`: http/https only, re-serialized, run with `execFile` and no shell: `rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `xdg-open` on Linux; if that fails the link is copied). The terminal is not linkified +- **File chips** (1.2): drag a row from the Files tab into the composer, or right-click → 插入到聊天 / Add to chat, to attach a path chip. Chips are sent as project-relative paths, checked by the daemon (inside the project, no `..`, no symlink escape, must exist, at most 50), and reach the Agent as a "Referenced files" section with absolute paths after your text (plus `resource_link` blocks for ACP Agents). Dropping files from the OS file manager still uploads them as attachments +- **Layout settings** (1.2): content width (narrow 640 / default 720 / wide 880 / full) and chat font size (12–18 px, default 13; timeline, composer, tool cards, diffs and the file viewer scale together, code 1 px smaller); the sidebar collapses with the panel button at its top-left or Ctrl/⌘+B (collapses automatically in narrow windows); all persisted +- **Follows Magpie live** (1.2): light/dark, Magpie's neutral colours and its language follow Magpie while the page is open (and after a reconnect); the accent stays neutral grey +- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 9 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit` / `serve`) so UI work does not burn tokens ## Architecture @@ -84,6 +89,18 @@ The daemon can run Agents with full access to your machine, so the token that un - WebSocket connections must send `hello` with the token within 5 seconds, otherwise they are closed with code 4401. - **Coming back after a plugin host restart.** Magpie restarts its plugin host from time to time; the old host's daemon exits with it and the new host has a new gate key. `boot.js` passes its own page URL to the gate as `back`; the gate accepts it only if it is a loopback `/_magpie/plugin//index.html` URL and forwards it **only in the fragment** (`#t=…&b=…`). When the daemon page can't reconnect for 5 seconds (or on 重试 / Retry) it navigates back to that page, which reads the fresh `session.js` and opens the new gate. To tell a live host's `session.js` from one a killed host left behind (a hard kill can't delete it), the file carries `ts` and `beat`: from the first page open on, the host rewrites it every 4 s, and after a lost connection `boot.js` only takes a file written after the loss; a host that was never opened doesn't rewrite it, and a new host deletes a file whose writer (pid in `session-owner.json`, outside the page folder) is gone before Magpie serves the page. The daemon page checks the URL again before following it, so it is never an open redirect, and the token never leaves its own fragment. +### Preview proxy (1.2) + +The Preview tab can't frame a dev server directly: Magpie's frame is sandboxed without `allow-same-origin`, so the page would run with an opaque origin and module scripts, `fetch` and storage break. The daemon runs a small reverse proxy instead: + +- **Created only over the authenticated WebSocket** (`preview.open`); there is no HTTP route to start one. +- **Loopback targets only**: `localhost`, `*.localhost`, `127.0.0.0/8`, `0.0.0.0`, `::1`/`::`, `http:` or `https:`, no user-info, at most 2048 characters. Anything else is refused before a socket is opened. +- **Refused ports**: the daemon's own port, the gate (`--gate-port`, 3488), Magpie (3425, 3430, any port in `MAGPIE_ADDR` / `MAGPIE_WEB_ADDR` / `MAGPIE_URL`, and the gateway port saved in Magpie's own `settings.json`, read again on every open: the portable `data` folder beside Magpie, `$XDG_CONFIG_HOME/magpie`, `~/.config/magpie`), the proxy's own ports, plus `AGENT_CONSOLE_PREVIEW_DENY` (comma-separated). Whatever the port, a target whose `GET /` answers like Magpie's gateway (`{"name":"magpie",…}`), or that replies with `X-Magpie-*` headers, is refused; the check is repeated every minute and fails closed (no answer → nothing forwarded). +- **A key on every request**: each listener answers only at `http://ac<128-bit random key>.localhost:`. The preview frame is an opaque origin (Magpie's sandbox is inherited), so its requests carry `Origin: null` and no `Referer`, exactly what any other web page can send from a sandboxed iframe of its own, and the port can be found by scanning. The host name is the one thing the browser attaches to every request the frame makes (navigations, module scripts and their imports, `fetch`, CSS `url()`, workers, the HMR WebSocket) that another page can't know. A request with any other `Host` is refused before anything is forwarded and gets no CORS headers: `127.0.0.1:` / `localhost:` → 403, anything else → 421 (DNS rebinding). Responses carry `Referrer-Policy: no-referrer` so the key isn't sent on to other sites. `preview.open` also returns a per-open nonce over the authenticated WebSocket; `GET /__agent_console__/ping` must echo it exactly (a plain 200 `ok` from a hostile DNS answer is refused and the listener is released). Before the keyed name is looked up, the panel probes a keyless canary (`acprobe.localhost` on the same port) the same way. Apple WebKit before macOS 26 (Magpie's Mac app on 12–15, Safari with `magpie web`) asks network DNS for `*.localhost`, so it is refused before any such name is looked up and the listener is released. The macOS version doesn't come from the user agent (Apple froze it at `Mac OS X 10_15_7`, macOS 26+ included): `preview.open` reports the daemon's own `os.platform()` and the Darwin major of `os.release()` (25 = macOS 26), and the panel refuses only Apple WebKit on a Darwin host below 25, or when that answer is missing. The daemon listens on 127.0.0.1 only, so the page and the daemon run on the same machine; the keyless canary stays as the runtime check either way. Chromium / WebView2, WebKitGTK and WebKit on macOS 26+ resolve `*.localhost` to loopback themselves. Where the preview can't run, the panel offers the system browser instead. +- **One listener per target origin** on `127.0.0.1` with a random port (at most 8, least recently used closed first). Every request and upgrade checks `Host` (above) and `Origin` (absent, `null` or the proxy's own origin, else 403). +- **Headers**: upstream gets the target's `Host` and `Origin`; `Cookie`, `Forwarded` and `X-Forwarded-*` are dropped. Responses lose `X-Frame-Options`, the CSP `frame-ancestors` directive, `Set-Cookie` and upstream CORS headers; same-target redirects are rewritten to the proxy; CORS is answered for the opaque frame only, and only on requests that carry the key (`access-control-allow-origin: null`, no credentials). Cookies are dropped both ways because cookies for `127.0.0.1` are shared across ports. HTML gets one injected script (`/__agent_console__/preview.js`) that reports the address and title to the panel and accepts back / forward / reload from the parent frame only. +- **Closed when idle**: after 10 minutes without traffic (an open HMR socket counts as traffic), when the Preview tab closes or changes origin, when the last WebSocket client disconnects, and on daemon exit. + ## Lifecycle - Importing `index.mjs` has no side effects (no port, no process, no files). @@ -184,7 +201,7 @@ npm run shot:v1 # screenshot set (light/dark × scenes → _tmp/shots-v1/) # Mock (no real tokens) AGENT_CONSOLE_MOCK=1 npm run dev -# scripts: default /perm /plan /ask /slow /error /long (5000-event stress) /exit +# scripts: default /perm /plan /ask /slow /error /long (5000-event stress) /exit /serve (local links, 1.2) ``` | Env | Purpose | diff --git a/packages/agent-console/app/app.css b/packages/agent-console/app/app.css index 981b65a..f6d1e91 100644 --- a/packages/agent-console/app/app.css +++ b/packages/agent-console/app/app.css @@ -1,4 +1,4 @@ -:root{--own-bg: #ffffff;--own-sb: #f8f8f7;--own-fg: #1f1f1f;--own-muted: #737373;--own-line: #ececec;--bg: var(--own-bg);--sb-bg: var(--own-sb);--fg: var(--own-fg);--muted: var(--own-muted);--line: var(--own-line);--meta: #a3a3a3;--text: #262626;--accent: #262626;--accent-2: #525252;--accent-fg: #ffffff;--accent-soft: #f0f0f0;--surface: color-mix(in oklab, var(--fg) 3%, var(--bg));--surface-hover: color-mix(in oklab, var(--fg) 6%, var(--bg));--chip-bg: #f4f5f5;--chip-line: #ececec;--pill-fg: #525252;--search-bg: #efefee;--tile-bg: color-mix(in oklab, var(--fg) 90%, var(--bg));--tile-fg: var(--bg);--badge-bg: color-mix(in oklab, var(--fg) 7%, var(--bg));--badge-fg: color-mix(in oklab, var(--fg) 80%, var(--bg));--run-bg: #f0f0f0;--run-fg: #404040;--cp-line: color-mix(in oklab, var(--fg) 11%, var(--bg));--cp-focus: #a3a3a3;--cp-ring: rgb(0 0 0 / .06);--active-bg: #ffffff;--active-line: #e6e6e6;--ok: #16a34a;--warn: #d97706;--danger: #dc2626;--info: #2563eb;--code-bg: #f4f5f5;--code-line: #eaeceb;--code-fg: #404040;--add-bg: #ecfdf3;--del-bg: #fef2f2;--r-s: 6px;--r-m: 8px;--r-l: 12px;--r-full: 999px;--font-ui: var(--magpie-font, "Segoe UI Variable Text", "Segoe UI", -apple-system, "PingFang SC", "Microsoft YaHei UI", system-ui, sans-serif);--font-mono: var(--magpie-code, "Cascadia Code", "Cascadia Mono", "JetBrains Mono", ui-monospace, Consolas, monospace);--fs-s: 12px;--fs-m: 13px;--fs-l: 14px;--fs-hero: 18px;--lh: 1.6;--col: 720px;--row: 26px;--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .16), 0 0 0 1px var(--line);--term-bg: #ffffff;--term-fg: #1e1e1e;--ease: cubic-bezier(.2,.7,.2,1);--dur-1: .12s;--dur-2: .2s;color-scheme:light}:root[data-theme=dark]{--own-bg: #1a1a1a;--own-sb: #151515;--own-fg: #ececec;--own-muted: #9b9b9b;--own-line: #2c2c2c;--meta: #7c7c7c;--text: #e2e2e2;--accent: #e5e5e5;--accent-2: #b3b3b3;--accent-fg: #171717;--accent-soft: #2e2e2e;--chip-bg: #252727;--chip-line: #323434;--pill-fg: #bdbdbd;--search-bg: #242424;--run-bg: #2e2e2e;--run-fg: #d4d4d4;--cp-focus: #6b6b6b;--cp-ring: rgb(255 255 255 / .07);--active-bg: #242424;--active-line: #333333;--info: #60a5fa;--code-bg: #232323;--code-line: #303030;--code-fg: #d4d4d4;--add-bg: rgb(22 163 74 / .16);--del-bg: rgb(220 38 38 / .16);--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .5), 0 0 0 1px var(--line);--term-bg: #0c0c0c;--term-fg: #cccccc;color-scheme:dark}:root[data-host-colors]{--bg: var(--magpie-card, var(--magpie-bg, var(--own-bg)));--sb-bg: var(--magpie-bg, var(--own-sb));--fg: var(--magpie-fg, var(--own-fg));--muted: var(--magpie-muted, var(--own-muted));--line: var(--magpie-line, var(--own-line))}@layer reset{html,body{margin:0;padding:0;height:100%}body{background:var(--bg);color:var(--fg);font-family:var(--font-ui);font-size:var(--fs-m);line-height:var(--lh);-webkit-font-smoothing:antialiased}*{box-sizing:border-box}#root{height:100%}button{font:inherit;color:inherit;background:none;border:0;padding:0;cursor:pointer}input,textarea{font:inherit;color:inherit}a{color:var(--accent)}:focus-visible{outline:2px solid color-mix(in oklab,var(--accent) 55%,var(--bg));outline-offset:-1px}}*{scrollbar-width:thin;scrollbar-color:color-mix(in oklab,var(--fg) 18%,transparent) transparent}*::-webkit-scrollbar{width:8px;height:8px}*::-webkit-scrollbar-thumb{background:color-mix(in oklab,var(--fg) 18%,transparent);border-radius:4px}*::-webkit-scrollbar-thumb:hover{background:color-mix(in oklab,var(--fg) 30%,transparent)}*::-webkit-scrollbar-track{background:transparent}.ibtn{width:28px;height:28px;flex:none;display:inline-flex;align-items:center;justify-content:center;border-radius:var(--r-s);color:var(--muted);transition:background var(--dur-1),color var(--dur-1)}.ibtn:hover{background:var(--surface-hover);color:var(--fg)}.ibtn[disabled]{opacity:.35;cursor:default}.ibtn.on{color:var(--accent)}.ibtn svg{width:16px;height:16px}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:30px;padding:0 14px;border-radius:var(--r-s);font-size:var(--fs-m);background:var(--surface-hover);color:var(--fg);transition:background var(--dur-1),filter var(--dur-1)}.btn:hover{filter:brightness(1.03)}.btn[disabled]{opacity:.4;cursor:default}.btn.primary{background:var(--accent);color:var(--accent-fg)}.btn.primary:hover{filter:brightness(1.08)}.btn.danger{color:var(--danger)}.btn.ghost{background:none}.btn.ghost:hover{background:var(--surface-hover)}.tinput{width:100%;height:30px;padding:0 10px;border:1px solid var(--line);border-radius:var(--r-s);background:var(--bg);font-size:var(--fs-m);outline:none}.tinput:focus{border-color:color-mix(in oklab,var(--accent) 55%,var(--bg))}.tinput.err{border-color:var(--danger)}.tinput::placeholder{color:var(--muted)}textarea.tinput{height:auto;min-height:60px;padding:6px 10px;resize:vertical}.menu{position:fixed;z-index:60;min-width:160px;max-width:280px;background:var(--bg);border-radius:var(--r-m);box-shadow:var(--shadow-pop);padding:4px;font-size:var(--fs-m)}.mi{display:flex;align-items:center;gap:8px;width:100%;height:28px;padding:0 10px;border-radius:var(--r-s);text-align:left;color:var(--fg)}.mi:hover:not([disabled]){background:var(--surface-hover)}.mi[disabled]{color:var(--muted);cursor:default}.mi.danger{color:var(--danger)}.mi .mi-check{margin-left:auto;color:var(--accent)}.msep{height:1px;margin:4px 6px;background:var(--line)}.mlabel{padding:6px 10px 2px;font-size:var(--fs-s);color:var(--muted)}.dlg-scrim{position:fixed;inset:0;z-index:70;background:#00000052;display:flex;align-items:center;justify-content:center;padding:24px}.dlg{width:440px;max-width:100%;max-height:80vh;display:flex;flex-direction:column;background:var(--bg);border-radius:var(--r-l);box-shadow:var(--shadow-pop)}.dlg-title{flex:none;padding:14px 16px 4px;font-size:var(--fs-l);font-weight:600}.dlg-body{flex:1;min-height:0;overflow-y:auto;padding:8px 16px}.dlg-foot{flex:none;display:flex;justify-content:flex-end;gap:8px;padding:10px 16px 14px}.dlg-row{margin:10px 0}.dlg-row-top{align-items:flex-start}.dlg-row>label{display:block;margin-bottom:4px;font-size:var(--fs-s);color:var(--muted)}.provider-list{display:flex;flex-direction:column;gap:6px;width:100%;max-height:280px;overflow:auto}.provider-list{display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}.provider-redetect{align-self:flex-start;margin-bottom:4px}.provider-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px;padding:6px 8px;border-radius:var(--r-m);background:var(--bg-2)}.provider-row.open{padding-bottom:10px}.provider-head{display:flex;align-items:center;gap:10px;flex:1;min-width:0;border:0;background:none;text-align:left;cursor:pointer;color:inherit;padding:0}.provider-detail{flex:1 1 100%;display:flex;flex-direction:column;gap:6px;padding:4px 0 0 28px}.provider-hint-row{display:flex;gap:8px;align-items:flex-start;flex-wrap:wrap}.btn.sm{font-size:var(--fs-s);padding:4px 10px;height:auto}.provider-meta{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.provider-name{font-size:var(--fs-m);font-weight:500}.provider-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}.provider-dot-on{background:var(--ok, #3ecf8e)}.provider-dot-off{background:var(--muted);opacity:.5}.provider-dot-pending{background:var(--warn, #e6a817)}.provider-switch input{width:16px;height:16px;cursor:pointer}.dlg-hint{font-size:var(--fs-s);color:var(--muted)}.dlg-hint.err{color:var(--danger)}.toasts{position:fixed;left:50%;bottom:24px;transform:translate(-50%);z-index:80;display:flex;flex-direction:column;gap:8px;align-items:center}.toast{max-width:480px;padding:8px 14px;border-radius:var(--r-m);background:var(--fg);color:var(--bg);font-size:var(--fs-m);box-shadow:var(--shadow-pop);animation:toast-in var(--dur-2) var(--ease)}.toast.err{background:var(--danger);color:#fff}@keyframes toast-in{0%{opacity:0;transform:translateY(8px)}}.dot{width:6px;height:6px;border-radius:50%;flex:none;background:var(--muted)}.dot.run{background:var(--accent-2);animation:breathe 1.6s infinite}.dot.err{background:var(--danger)}.dot.wait{background:var(--warn);animation:breathe 1.6s infinite}@keyframes breathe{50%{opacity:.35}}.boot-screen{height:100%;display:flex;align-items:center;justify-content:center;gap:8px;color:var(--muted);font-size:var(--fs-m)}.boot-screen .btn{margin-top:12px}.boot-wrap{display:flex;flex-direction:column;align-items:center}.boot-dot{width:8px;height:8px;border-radius:50%;background:var(--muted)}.boot-dot[data-state=open]{background:var(--ok)}.boot-dot[data-state=reconnecting]{background:var(--warn)}.boot-dot[data-state=down]{background:var(--danger)}.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}.menu.select-menu{z-index:80;overflow-y:auto;outline:none;max-width:320px}.sm-opt{cursor:pointer;user-select:none;height:auto;min-height:28px;padding:4px 8px 4px 10px}.sm-opt.on{background:var(--surface-hover)}.sm-opt.off{color:var(--muted);cursor:default}.sm-opt.off:hover{background:none}.sm-text{display:flex;flex-direction:column;min-width:0;flex:1 1 auto}.sm-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sm-hint{font-size:var(--fs-s);color:var(--muted);white-space:normal;line-height:1.4}.sm-check{flex:none;width:14px;display:inline-flex;color:var(--accent)}.sm-opt[aria-selected=true] .sm-label{font-weight:500}.tinput.sm-field{display:flex;align-items:center;text-align:left;padding-right:26px;cursor:pointer;position:relative;color:var(--fg);background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - 14px) 50%,calc(100% - 10px) 50%;background-size:4px 4px;background-repeat:no-repeat}.tinput.sm-field[aria-expanded=true]{border-color:color-mix(in oklab,var(--accent) 55%,var(--bg))}.sm-field .sm-val{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.app{display:flex;height:100vh;min-width:480px;overflow:hidden}.sidebar{width:var(--sb-w, 248px);flex:none;display:flex;flex-direction:column;background:var(--sb-bg);border-right:1px solid var(--line)}.sb-row{display:flex;align-items:center;gap:2px;height:40px;padding:8px 8px 4px;flex:none}.sb-row-search{height:36px;padding:0 8px 4px}.sb-new{flex:1;display:flex;align-items:center;gap:8px;height:28px;min-width:0;padding:0 8px 0 5px;border-radius:var(--r-s);font-size:var(--fs-m);font-weight:500;text-align:left;transition:background var(--dur-1);white-space:nowrap;overflow:hidden}.sb-new-tile{width:18px;height:18px;flex:none;border-radius:5px;background:var(--tile-bg);color:var(--tile-fg);display:inline-flex;align-items:center;justify-content:center}.sb-new-tile svg{stroke-width:2.2}.sb-new:hover{background:var(--surface-hover)}.sb-row .ibtn{width:28px;height:28px}.sb-search{flex:1;display:flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:var(--r-s);background:var(--search-bg);color:var(--meta)}.sb-search input::placeholder{color:var(--meta)}.sb-search input{flex:1;min-width:0;border:0;background:none;font-size:var(--fs-s);outline:none;color:var(--fg)}.sb-list{flex:1;overflow-y:auto;padding:0 8px 8px}.pj-group{margin-top:2px}.pj{display:flex;align-items:center;gap:2px;height:var(--row);padding:0 4px 0 0;border-radius:var(--r-s)}.pj:hover{background:var(--surface-hover)}.pj-toggle{flex:1;min-width:0;height:100%;display:flex;align-items:center;gap:6px;padding-left:2px;text-align:left;font-size:var(--fs-m);font-weight:500}.pj-caret{width:14px;flex:none;display:inline-flex;justify-content:center;color:var(--muted);transition:transform var(--dur-1)}.pj-caret.open{transform:rotate(90deg)}.pj-badge{width:18px;height:18px;flex:none;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;background:var(--badge-bg);color:var(--badge-fg);font-size:11px;font-weight:600;line-height:1;text-transform:uppercase}.pj-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pj-count{flex:none;padding:0 6px;font-size:var(--fs-s);color:var(--meta)}.pj-act{width:22px;height:22px;flex:none;display:none;align-items:center;justify-content:center;border-radius:var(--r-s);color:var(--muted)}.pj:hover .pj-act,.pj-act:focus-visible{display:inline-flex}.pj:hover .pj-count{display:none}.pj-act:hover{background:var(--bg);color:var(--fg)}.pj-sessions{padding:1px 0 4px 22px;display:flex;flex-direction:column;gap:1px}.pj-more,.pj-empty{display:flex;align-items:center;width:100%;height:26px;padding:0 8px 0 21px;font-size:var(--fs-s);color:var(--muted);text-align:left;border-radius:var(--r-s)}.pj-more:hover{background:var(--surface-hover);color:var(--fg)}.t-item{display:flex;align-items:center;gap:8px;width:100%;height:var(--row);padding:0 4px 0 8px;border-radius:var(--r-s);position:relative;text-align:left;font-size:var(--fs-m);transition:background var(--dur-1)}.t-item:hover{background:var(--surface-hover)}.t-item.on{background:var(--active-bg);box-shadow:0 0 0 1px var(--active-line),0 1px 2px #0000000a;font-weight:500}.t-item.on:before{content:"";position:absolute;left:-1px;top:7px;bottom:7px;width:2px;border-radius:2px;background:var(--accent-2)}.t-item.archived{opacity:.55}.t-item.archived .t-title{font-style:italic}.t-item .dot{width:5px;height:5px}.t-pin{width:12px;flex:none;display:inline-flex;color:var(--muted)}.t-pin svg{width:10px;height:10px}.t-title{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.t-time{flex:none;font-size:11.5px;color:var(--meta);font-weight:400}.t-item:hover .t-time{display:none}.t-more{flex:none;width:22px;height:22px;display:none;align-items:center;justify-content:center;border-radius:var(--r-s);color:var(--muted)}.t-item:hover .t-more{display:inline-flex}.t-more:hover{background:var(--bg);color:var(--fg)}.t-rename{flex:1;min-width:0;height:24px;font-size:var(--fs-m);border:1px solid var(--accent);border-radius:var(--r-s);padding:0 6px;background:var(--bg)}.sb-empty{padding:20px 12px;text-align:center;color:var(--muted);font-size:var(--fs-s)}.sb-start{padding:28px 12px;text-align:center}.sb-start-t{font-size:var(--fs-m);font-weight:500}.sb-start-s{margin:4px 0 12px;font-size:var(--fs-s);color:var(--muted)}.rs{width:5px;flex:none;cursor:col-resize;position:relative}.rs:after{content:"";position:absolute;inset:0}.rs:hover:after,.rs.drag:after{background:color-mix(in oklab,var(--accent) 30%,transparent)}.rs-l{margin-left:-3px}.rs-r{margin-right:-3px}body.col-drag{cursor:col-resize;user-select:none}body.col-drag iframe,body.col-drag .xterm{pointer-events:none}.scrim{position:fixed;inset:0;z-index:45;background:#00000052;display:none}.scrim.show{display:block}.main{flex:1;min-width:0;display:flex;flex-direction:column;background:var(--bg);position:relative}.topbar{height:40px;flex:none;display:flex;align-items:center;gap:6px;padding:0 10px;border-bottom:1px solid var(--line)}.tb-menu-btn{display:none}.tb-crumb{flex:none;max-width:26%;font-size:var(--fs-m);color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.tb-sep{flex:none;color:var(--muted)}.tb-title{font-size:var(--fs-l);font-weight:500;max-width:40%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;border-radius:var(--r-s);padding:2px 6px;cursor:text}.tb-title:hover{background:var(--surface)}.tb-title.ghost{color:var(--muted);cursor:default}.tb-title.ghost:hover{background:none}.tb-rename{font-size:var(--fs-l);font-weight:500;border:1px solid var(--accent);border-radius:var(--r-s);padding:1px 6px;background:var(--bg);width:300px;max-width:46vw}.tb-pill{flex:none;display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 9px;border-radius:var(--r-full);font-size:var(--fs-s);background:var(--surface);color:var(--muted)}.tb-pill.run{background:var(--run-bg);color:var(--run-fg)}.tb-pill-dot{width:7px;height:7px;border-radius:50%;background:var(--accent-2);box-shadow:0 0 0 3px color-mix(in oklab,var(--accent-2) 20%,transparent);animation:breathe 1.6s infinite}.tb-pill.wait{color:var(--warn)}.tb-pill.err{color:var(--danger)}.tb-right{margin-left:auto;display:flex;align-items:center;gap:2px}.tb-model{font-size:var(--fs-s);color:var(--muted);margin-right:4px;white-space:nowrap;max-width:160px;overflow:hidden;text-overflow:ellipsis}.connbar{flex:none;height:26px;display:flex;align-items:center;justify-content:center;font-size:var(--fs-s);background:color-mix(in oklab,var(--warn) 14%,var(--bg));color:var(--warn)}.scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;position:relative}.tl-wrap{max-width:calc(var(--col) + 40px);min-width:0;margin:0 auto;padding:24px 20px 16px}.jump{position:absolute;right:24px;bottom:150px;width:34px;height:34px;border-radius:50%;background:var(--bg);box-shadow:var(--shadow-pop);display:flex;align-items:center;justify-content:center;color:var(--muted);z-index:5}.jump:hover{color:var(--fg)}.jump .jd{position:absolute;top:4px;right:4px;width:7px;height:7px;border-radius:50%;background:var(--accent)}.panel{width:var(--pn-w, 440px);flex:none;display:flex;flex-direction:column;background:var(--bg);border-left:1px solid var(--line)}.pn-head{flex:none;display:flex;align-items:center;gap:2px;height:40px;padding:0 6px;border-bottom:1px solid var(--line)}.pn-tabs{display:flex;gap:2px}.pn-tab{height:28px;padding:0 10px;border-radius:var(--r-s);font-size:var(--fs-m);color:var(--muted);display:inline-flex;align-items:center;gap:6px}.pn-tab:hover{background:var(--surface-hover);color:var(--fg)}.pn-tab.on{background:var(--surface-hover);color:var(--fg);font-weight:500}.pn-body{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}.pn-close{margin-left:auto}.pn-empty{padding:20px;color:var(--muted);font-size:var(--fs-m);text-align:center}.pn-empty-sub{margin-top:6px;font-size:var(--fs-s);opacity:.8}.chg-head{flex:none;display:flex;align-items:center;gap:6px;height:34px;padding:0 8px;border-bottom:1px solid var(--line);font-size:var(--fs-m)}.chg-branch{display:inline-flex;align-items:center;gap:5px;color:var(--muted);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.chg-head .ibtn{margin-left:auto}.chg-list{flex:none;max-height:40%;overflow-y:auto;border-bottom:1px solid var(--line)}.chg-list:empty{border-bottom:none}.chg-row{display:flex;align-items:center;gap:7px;padding:4px 8px;cursor:pointer;font-size:var(--fs-m);min-height:28px}.chg-row:hover,.chg-row.on{background:var(--surface-hover)}.chg-kind{flex:none;width:18px;height:18px;border-radius:var(--r-s);font-size:10px;display:inline-flex;align-items:center;justify-content:center;background:var(--surface);color:var(--muted)}.chg-kind.k-modified{color:var(--warn, #b45309)}.chg-kind.k-added,.chg-kind.k-untracked{color:var(--ok, #15803d)}.chg-kind.k-deleted{color:var(--danger)}.chg-kind.k-renamed{color:var(--accent)}.chg-path{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;direction:rtl;text-align:left}.chg-stat{flex:none;font-style:normal;font-size:var(--fs-s);font-variant-numeric:tabular-nums}.chg-stat .add{color:var(--ok, #15803d);font-style:normal}.chg-stat .del{color:var(--danger);font-style:normal}.chg-discard{flex:none;opacity:0}.chg-row:hover .chg-discard{opacity:1}.chg-diff{flex:1;min-height:0;overflow:auto}.ft-crumbs{flex:none;display:flex;align-items:center;gap:4px;min-height:34px;padding:0 8px;border-bottom:1px solid var(--line);font-size:var(--fs-m);overflow-x:auto;white-space:nowrap}.ft-crumb{color:var(--muted);font-size:var(--fs-m);padding:2px 4px;border-radius:var(--r-s)}.ft-crumb:hover{background:var(--surface-hover);color:var(--fg)}.ft-crumb-t{color:var(--fg)}.ft-crumb-t.muted{color:var(--muted)}.ft-tree{flex:none;max-height:45%;overflow-y:auto;padding:4px 0}.ft-row{display:flex;align-items:center;gap:5px;padding:3px 8px;cursor:pointer;font-size:var(--fs-m);min-height:24px}.ft-row:hover,.ft-row.on{background:var(--surface-hover)}.ft-row .caret{font-size:11px;color:var(--muted);display:inline-block;transition:transform var(--dur-1) var(--ease)}.ft-row .caret.open{transform:rotate(90deg)}.ft-dot{width:13px;flex:none}.ft-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ft-err{color:var(--danger);font-size:var(--fs-s);padding:2px 0}.ft-view{flex:1;min-height:0;overflow:auto;border-top:1px solid var(--line)}.ft-pre{margin:0;padding:10px 12px;font-family:var(--font-mono);font-size:var(--fs-s);line-height:1.55}.ft-pre code{background:none;padding:0;display:block;white-space:pre}.tm-tabs{flex:none;display:flex;align-items:center;gap:2px;padding:4px 6px;border-bottom:1px solid var(--line);overflow-x:auto}.tm-tab{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 6px 0 10px;border-radius:var(--r-s);font-size:var(--fs-m);color:var(--muted);white-space:nowrap}.tm-tab:hover,.tm-tab.on{background:var(--surface-hover);color:var(--fg)}.tm-x{color:var(--muted);padding:0 3px;border-radius:3px}.tm-x:hover{color:var(--danger);background:var(--surface-hover)}.tm-note{flex:none;padding:4px 10px;font-size:var(--fs-s);color:var(--warn);background:color-mix(in oklab,var(--warn) 10%,var(--bg));border-bottom:1px solid var(--line)}.tm-body{flex:1;min-height:0;position:relative;background:var(--term-bg)}.tm-view{position:absolute;inset:0;padding:6px 8px;background:var(--term-bg)}.tm-view .xterm{height:100%}.tm-view .xterm-viewport{background:var(--term-bg)!important}.tm-view .xterm-screen{padding:2px 0}.imp-list{max-height:320px;overflow-y:auto;display:flex;flex-direction:column;gap:2px}.imp-row{display:flex;align-items:center;gap:8px;padding:5px 6px;border-radius:var(--r-s);font-size:var(--fs-m);cursor:pointer}.imp-row:hover{background:var(--surface-hover)}.imp-row.done{opacity:.55;cursor:default}.imp-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.imp-meta{flex:none;color:var(--muted);font-size:var(--fs-s)}.info-grid{display:flex;flex-direction:column;gap:2px}.info-row{display:flex;align-items:center;gap:10px;padding:3px 2px;font-size:var(--fs-m)}.info-k{flex:none;width:74px;color:var(--muted)}.info-v{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--font-mono);font-size:var(--fs-s)}@media(min-width:760px){.sidebar.w-hide{display:none}.sidebar.w-hide+.rs-l{display:none}}@media(min-width:900px){.panel.w-hide{display:none}}@media(max-width:899px){.panel{position:fixed;right:0;top:0;bottom:0;z-index:46;width:min(var(--pn-w, 440px),92vw);transform:translate(100%);transition:transform var(--dur-2) var(--ease);box-shadow:var(--shadow-pop)}.panel.open{transform:none}.rs-r{display:none}}@media(max-width:759px){.sidebar{position:fixed;left:0;top:0;bottom:0;z-index:46;width:min(var(--sb-w, 248px),84vw);transform:translate(-100%);transition:transform var(--dur-2) var(--ease);box-shadow:var(--shadow-pop)}.sidebar.open{transform:none}.sidebar~.rs-l{display:none}.tb-menu-btn{display:inline-flex}.tl-wrap{padding:16px 14px 8px}.tb-model{display:none}}.dlg.cpal{width:520px;padding:6px}.cpal-in{width:100%;height:36px;padding:0 12px;border:0;background:none;outline:none;font-size:var(--fs-l);color:var(--fg)}.cpal-list{max-height:46vh;overflow-y:auto;padding:4px}.cpal-item{display:flex;align-items:center;gap:8px;width:100%;height:30px;padding:0 10px;border-radius:var(--r-s);text-align:left;font-size:var(--fs-m)}.cpal-item.on{background:var(--surface-hover)}.cpal-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cpal-hint{flex:none;font-size:var(--fs-s);color:var(--muted)}.um-row{display:flex;flex-direction:column;align-items:flex-end;margin:4px 0 16px}.um{position:relative;max-width:78%;background:var(--accent-soft);border-radius:14px 14px 4px;color:var(--fg);padding:6px 12px;font-size:var(--fs-l);line-height:1.6;white-space:pre-wrap;word-break:normal;overflow-wrap:break-word}.um:hover .um-act{display:flex}.um-act{position:absolute;left:-62px;top:4px;display:none;gap:2px}.um-act .ibtn{width:24px;height:24px}.um-img{display:block;max-width:200px;max-height:140px;border-radius:var(--r-s);margin-bottom:6px;cursor:zoom-in}.um-tag{font-size:var(--fs-s);color:var(--muted);margin-top:2px}.as{margin:4px 0}.md.streaming:after{content:"\258d";color:var(--accent);animation:breathe 1s infinite}.md{font-size:var(--fs-l);line-height:1.75;color:var(--text);word-break:normal;overflow-wrap:break-word}.md p{margin:0 0 8px}.md>:last-child{margin-bottom:0}.md a{color:var(--accent);text-decoration:underline;text-underline-offset:2px;text-decoration-color:color-mix(in oklab,var(--accent) 40%,transparent)}.md a:hover{text-decoration:underline}.md pre{position:relative;background:var(--code-bg);border:1px solid var(--code-line);border-radius:var(--r-m);padding:10px 12px;overflow-x:auto;font-family:var(--font-mono);font-size:var(--fs-s);line-height:1.55}.md code{font-family:var(--font-mono);font-size:12.5px;background:var(--code-bg);color:var(--code-fg);padding:1px 5px;border-radius:4px;border:1px solid var(--code-line)}.md pre code{background:none;padding:0;border:0;color:inherit}.md ul,.md ol{margin:6px 0;padding-left:22px}.md h1,.md h2,.md h3,.md h4{margin:12px 0 6px;font-size:var(--fs-l);font-weight:600}.md blockquote{margin:6px 0;padding-left:12px;border-left:3px solid var(--line);color:var(--muted)}.md table{border-collapse:collapse;margin:8px 0}.md th,.md td{border:1px solid var(--line);padding:4px 10px;font-size:var(--fs-s)}.cb-copy{position:absolute;top:6px;right:6px;font-size:var(--fs-s);color:var(--muted);padding:2px 8px;border-radius:var(--r-s);background:var(--bg);opacity:0;transition:opacity var(--dur-1)}.md pre:hover .cb-copy{opacity:1}.cb-copy:hover{color:var(--fg)}.rs-item{margin:4px 0 6px}.rs-head{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0;color:var(--meta);font-size:var(--fs-s)}.rs-head:hover{color:var(--fg)}.rs-head .caret{display:inline-block;transition:transform var(--dur-1)}.rs-head .caret.open{transform:rotate(90deg)}.rs-body{margin:2px 0 6px 5px;padding-left:12px;border-left:1px solid var(--line);color:var(--muted);font-size:var(--fs-s);line-height:1.65;white-space:pre-wrap}.todo-list{margin:2px 0 6px 5px;padding-left:12px;border-left:1px solid var(--line);list-style:none;font-size:var(--fs-s)}.todo{color:var(--muted)}.todo.in_progress{color:var(--fg)}.tg{margin:4px 0 10px}.tg-head{display:flex;align-items:center;gap:6px;width:100%;height:24px;padding:0;color:var(--meta);font-size:var(--fs-s);text-align:left}.tg-head:hover{color:var(--fg)}.tg-head .caret{transition:transform var(--dur-1)}.tg-head .caret.open{transform:rotate(90deg)}.tg-live{margin-left:auto;color:var(--accent);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.tg-list{margin:2px 0 0 5px;border-left:1px solid var(--line);padding-left:6px}.ts-head{display:flex;align-items:center;gap:8px;width:100%;height:26px;padding:0 6px;border-radius:var(--r-s);font-size:12.5px;text-align:left;color:var(--text)}.ts-head:hover{background:var(--surface-hover)}.ts-ic{width:14px;flex:none;text-align:center}.ts-ic.ok{color:var(--ok)}.ts-ic.fail{color:var(--danger)}.ts-ic.run{color:var(--accent-2);animation:breathe 1.2s infinite}.ts-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ts-meta{flex:none;color:var(--meta);font-variant-numeric:tabular-nums}.ts-meta.err{color:var(--danger)}.ts-out{margin:2px 8px 6px 30px}.ts-out pre{background:var(--code-bg);border-radius:var(--r-s);padding:8px 10px;font-family:var(--font-mono);font-size:var(--fs-s);line-height:1.5;overflow-x:auto;white-space:pre-wrap;word-break:break-all;margin:0}.ts-more{font-size:var(--fs-s);color:var(--accent);margin-bottom:4px}.diff{margin:2px 6px 6px 22px;border:1px solid var(--line);border-radius:var(--r-m);overflow:hidden}.diff-path{padding:4px 10px;font-size:var(--fs-s);color:var(--muted);background:var(--surface);border-bottom:1px solid var(--line);font-family:var(--font-mono)}.diff-pre{margin:0;padding:6px 0;font-family:var(--font-mono);font-size:var(--fs-s);line-height:1.5;overflow-x:auto}.dh-head{display:block;color:var(--muted);padding:0 10px}.dl{display:block;padding:0 10px;white-space:pre-wrap;word-break:break-all}.dl.add{background:var(--add-bg)}.dl.del{background:var(--del-bg)}.card{margin:8px 0;border-radius:10px;padding:12px 14px}.card.plan{border:1px solid var(--line)}.card.perm{border:1px solid color-mix(in oklab,var(--warn) 30%,var(--bg));background:color-mix(in oklab,var(--warn) 3%,var(--bg))}.card.perm.done{border-color:var(--line);opacity:.75}.card.ask{border:1px solid color-mix(in oklab,var(--info) 45%,var(--bg))}.card.ask.done{border-color:var(--line);opacity:.75}.err-card{border:1px solid color-mix(in oklab,var(--danger) 45%,var(--bg))}.err-line{color:var(--danger);font-size:var(--fs-m)}.perm-title{font-size:var(--fs-m);font-weight:500}.perm-cmd{margin:8px 0 0;background:var(--code-bg);border-radius:var(--r-s);padding:8px 10px;font-family:var(--font-mono);font-size:var(--fs-s);white-space:pre-wrap;word-break:break-all}.perm-path{margin-top:6px;font-family:var(--font-mono);font-size:var(--fs-s);color:var(--muted)}.perm-btns{display:flex;gap:8px;margin-top:10px}.perm-done{margin-top:8px;font-size:var(--fs-s);color:var(--muted)}.ask-q{margin-bottom:10px}.ask-t{font-size:var(--fs-m);font-weight:500;margin-bottom:6px}.ask-opts{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:6px}.ask-free,.ask .btn.primary{margin-top:4px}.nt{margin:8px 0;text-align:center;font-size:var(--fs-s);color:var(--muted)}.nt.warn{color:var(--warn)}.nt.error{color:var(--danger)}.te{display:flex;justify-content:flex-start;align-items:center;gap:2px;margin:4px 0 18px -6px;font-size:var(--fs-s);color:var(--meta)}.te-meta{padding:0 6px;font-variant-numeric:tabular-nums}.te-act{height:24px;min-width:24px;display:inline-flex;align-items:center;justify-content:center;gap:4px;padding:0 5px;border-radius:var(--r-s);color:var(--meta)}.te-act span{display:none}.te-act:hover{background:var(--surface-hover);color:var(--fg)}.te-files{color:var(--accent);font-size:var(--fs-s);margin-left:6px}.te-files:hover{text-decoration:underline}.empty-wrap{min-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;padding-bottom:14vh}.cp-hero-t{font-size:var(--fs-hero);font-weight:600}.cp-hero-s{margin-top:6px;font-size:var(--fs-s);color:var(--muted)}.empty-actions{margin-top:16px}.workspace-empty{padding-bottom:10vh}.q-list{max-width:var(--col);margin:0 auto 6px;display:flex;flex-direction:column;gap:4px}.q-item{display:flex;align-items:center;gap:8px;padding:4px 10px;background:var(--surface);border-radius:var(--r-s);font-size:var(--fs-s)}.q-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.q-item .ibtn{width:20px;height:20px}.composer{flex:none;padding:0 16px 16px}.cp-card{width:100%;max-width:var(--col);margin:0 auto;background:var(--bg);border-radius:14px;border:1px solid var(--cp-line);padding:12px 12px 8px 14px;box-shadow:0 1px 2px #0000000a;transition:border-color var(--dur-2) var(--ease),box-shadow var(--dur-2) var(--ease)}.cp-card:focus-within{border-color:var(--cp-focus);box-shadow:0 0 0 3px var(--cp-ring),0 1px 2px #0000000a}.cp-card.waiting{border-color:color-mix(in oklab,var(--warn) 45%,var(--bg))}.cp-card.danger{border-color:color-mix(in oklab,var(--danger) 40%,var(--bg))}.cp-danger{max-width:var(--col);margin:0 auto 6px;display:flex;align-items:center;gap:6px;color:var(--danger);font-size:var(--fs-s);padding:0 2px}.cp-hint{max-width:var(--col);margin:6px auto 0;font-size:11.5px;color:var(--meta);text-align:center}.att-note{padding:6px 10px 0;color:var(--muted);font-size:var(--fs-s)}.cp-ta-wrap{position:relative}.slash-pop{position:absolute;left:0;right:0;bottom:100%;margin-bottom:6px;max-height:min(240px,40vh);overflow:hidden;display:flex;flex-direction:column;z-index:20}.slash-pop .ap-scroll{max-height:inherit}.slash-pop .slash-h{padding:4px 10px 2px;font-size:var(--fs-xs);color:var(--muted);text-transform:uppercase;letter-spacing:.04em}.slash-pop .mi.slash-item{height:auto;min-height:28px;padding:4px 10px;flex-direction:column;align-items:flex-start;gap:0}.slash-pop .slash-name{font-weight:500}.slash-pop .slash-desc{font-size:var(--fs-xs);color:var(--muted);line-height:1.3}.slash-pop .slash-hint{font-size:var(--fs-xs);color:var(--muted);font-family:var(--mono, monospace)}.slash-pop .mi.slash-item.sel{background:var(--surface-hover)}.cp-ta{width:100%;border:0;resize:none;background:none;outline:none;color:var(--text);font-size:var(--fs-l);line-height:22px;min-height:34px;max-height:264px;overflow-y:auto;display:block;padding:0}.cp-ta::placeholder{color:var(--meta)}.cp-bar{display:flex;align-items:center;flex-wrap:wrap;gap:2px;margin:4px 0 0 -6px;min-width:0}.pill-wrap{position:relative;flex:0 1 auto;min-width:0;max-width:100%}.pill{position:relative;display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 8px;border-radius:7px;background:none;color:var(--pill-fg, var(--muted));border:1px solid transparent;font-size:var(--fs-s);max-width:min(240px,100%);min-width:0;white-space:nowrap;cursor:pointer;transition:background var(--dur-1)}.pill:hover{background:var(--surface-hover)}.pill svg{flex:none}.pill.chip{background:var(--chip-bg);border-color:var(--chip-line);padding:0 8px 0 4px;gap:6px;max-width:min(300px,100%)}.pill.chip:hover{background:var(--surface-hover)}.chip-logo{border-radius:5px}.chip-caret{color:var(--meta)}.pill .p-a{font-weight:500;color:var(--fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:0 0 auto;max-width:120px}.pill .p-t{color:var(--meta);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1 1 auto}.pill .p-t:before{content:"\b7";margin-right:5px}.ipill .ip-l{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.ipill:focus-visible{outline:2px solid color-mix(in oklab,var(--accent) 45%,var(--bg));outline-offset:-1px}.ipill[aria-expanded=true]{background:var(--surface-hover)}.ipill.danger{color:var(--danger)}.mode-menu{max-width:300px}.cp-div{width:1px;height:14px;background:var(--line);margin:0 4px;flex:none}.cp-bar>.ibtn{flex:none}.cp-attach{color:var(--pill-fg, var(--muted))}.cp-card{container-type:inline-size;container-name:composer}@container composer (max-width: 520px){.pill .p-t{display:none}.pill{max-width:min(160px,100%)}.ipill .ip-l{max-width:64px}}@container composer (max-width: 380px){.pill{max-width:min(120px,100%);padding:0 6px}.ipill .ip-l{display:none}}.pop{position:absolute;bottom:32px;left:0;z-index:55;width:260px;background:var(--bg);border-radius:var(--r-m);box-shadow:var(--shadow-pop);padding:4px;max-height:60vh;overflow-y:auto}.agent-picker{width:min(300px,calc(100vw - 32px));padding:0;overflow:hidden;display:flex;flex-direction:column;max-height:min(420px,60vh)}.agent-picker .ap-search{display:flex;align-items:center;gap:8px;padding:8px 10px;border-bottom:1px solid var(--line);flex:none;color:var(--muted)}.agent-picker .ap-search-in{flex:1;min-width:0;border:0;background:none;outline:none;font-size:var(--fs-s);color:var(--fg)}.agent-picker .ap-search-in::placeholder{color:var(--muted)}.agent-picker .ap-scroll{overflow-y:auto;padding:4px;flex:1;min-height:0}.agent-picker .ap-empty{padding:12px 10px;font-size:var(--fs-s);color:var(--muted);text-align:center}.agent-picker .ap-back{font-weight:600;margin-bottom:2px}.agent-picker .ap-back-icon{display:inline-flex;transform:rotate(180deg);margin-right:2px}.agent-picker .mi-row{display:flex;align-items:center;gap:6px;width:100%;text-align:left}.agent-picker .provider-pick-row{justify-content:space-between;gap:8px}.agent-picker .provider-pick-name{flex:0 1 auto;min-width:5.5rem;max-width:58%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:inherit}.agent-picker .provider-pick-meta{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:flex-end;gap:6px;min-width:0;margin-left:auto}.agent-picker .provider-pick-meta .dlg-hint{flex:none;font-size:10px;max-width:5rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .mi-row .mi-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .mi-row .mi-sub{flex:none;max-width:38%;font-size:11px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .model-pick-row{min-width:0}.agent-picker .model-pick-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .model-pick-default{flex:0 1 58%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .mi-meta{flex:none;font-size:11px;color:var(--muted);white-space:nowrap}.agent-picker .mi-tag{flex:none;font-size:10px;color:var(--accent)}.agent-picker .mi-caret{flex:none;color:var(--muted);display:inline-flex}.agent-picker .mi-check{flex:none;margin-left:auto;color:var(--accent)}.ap-sec{padding:4px 0}.ap-sec .tinput{height:26px;margin-bottom:4px}.ap-sec .mi{height:26px;font-size:var(--fs-s)}.att-bar{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 6px}.att{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 8px;background:var(--surface-hover);border-radius:var(--r-s);font-size:var(--fs-s)}.att img{width:22px;height:22px;object-fit:cover;border-radius:4px}.att.up{opacity:.6}.att-name{max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.att-x{color:var(--muted);font-size:14px;line-height:1}.att-x:hover{color:var(--fg)}.cp-right{margin-left:auto;flex:none;display:flex;align-items:center;gap:8px}.cp-clock{font-size:var(--fs-s);color:var(--meta);font-variant-numeric:tabular-nums}.cp-send,.cp-stop{width:30px;height:30px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;transition:filter var(--dur-1),opacity var(--dur-1)}.cp-send{background:var(--accent);color:var(--accent-fg)}.cp-send:hover{filter:brightness(1.08)}.cp-send[disabled]{opacity:.35;cursor:default;filter:none}.cp-stop{background:var(--fg);color:var(--bg)}.cp-stop:hover{filter:brightness(1.15)}@media(max-width:560px){.composer{padding:0 10px 10px}}.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;inset:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;inset:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset} +:root{--own-bg: #ffffff;--own-sb: #f8f8f7;--own-fg: #1f1f1f;--own-muted: #737373;--own-line: #ececec;--bg: var(--own-bg);--sb-bg: var(--own-sb);--fg: var(--own-fg);--muted: var(--own-muted);--line: var(--own-line);--meta: #a3a3a3;--text: #262626;--accent: #262626;--accent-2: #525252;--accent-fg: #ffffff;--accent-soft: #f0f0f0;--surface: color-mix(in oklab, var(--fg) 3%, var(--bg));--surface-hover: color-mix(in oklab, var(--fg) 6%, var(--bg));--chip-bg: #f4f5f5;--chip-line: #ececec;--pill-fg: #525252;--search-bg: #efefee;--tile-bg: color-mix(in oklab, var(--fg) 90%, var(--bg));--tile-fg: var(--bg);--badge-bg: color-mix(in oklab, var(--fg) 7%, var(--bg));--badge-fg: color-mix(in oklab, var(--fg) 80%, var(--bg));--run-bg: #f0f0f0;--run-fg: #404040;--cp-line: color-mix(in oklab, var(--fg) 11%, var(--bg));--cp-focus: #a3a3a3;--cp-ring: rgb(0 0 0 / .06);--active-bg: #ffffff;--active-line: #e6e6e6;--ok: #16a34a;--warn: #d97706;--danger: #dc2626;--info: #2563eb;--code-bg: #f4f5f5;--code-line: #eaeceb;--code-fg: #404040;--add-bg: #ecfdf3;--del-bg: #fef2f2;--r-s: 6px;--r-m: 8px;--r-l: 12px;--r-full: 999px;--font-ui: var(--magpie-font, "Segoe UI Variable Text", "Segoe UI", -apple-system, "PingFang SC", "Microsoft YaHei UI", system-ui, sans-serif);--font-mono: var(--magpie-code, "Cascadia Code", "Cascadia Mono", "JetBrains Mono", ui-monospace, Consolas, monospace);--fs-s: 12px;--fs-m: 13px;--fs-l: 14px;--fs-hero: 18px;--lh: 1.6;--col: 720px;--chat-fs: 13px;--chat-fs-s: max(12px, calc(var(--chat-fs) - 1px));--chat-code-fs: max(11.5px, calc(var(--chat-fs) - 1px));--chat-lh: 1.7;--row: 26px;--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .16), 0 0 0 1px var(--line);--term-bg: #ffffff;--term-fg: #1e1e1e;--ease: cubic-bezier(.2,.7,.2,1);--dur-1: .12s;--dur-2: .2s;color-scheme:light}:root[data-theme=dark]{--own-bg: #1a1a1a;--own-sb: #151515;--own-fg: #ececec;--own-muted: #9b9b9b;--own-line: #2c2c2c;--meta: #7c7c7c;--text: #e2e2e2;--accent: #e5e5e5;--accent-2: #b3b3b3;--accent-fg: #171717;--accent-soft: #2e2e2e;--chip-bg: #252727;--chip-line: #323434;--pill-fg: #bdbdbd;--search-bg: #242424;--run-bg: #2e2e2e;--run-fg: #d4d4d4;--cp-focus: #6b6b6b;--cp-ring: rgb(255 255 255 / .07);--active-bg: #242424;--active-line: #333333;--info: #60a5fa;--code-bg: #232323;--code-line: #303030;--code-fg: #d4d4d4;--add-bg: rgb(22 163 74 / .16);--del-bg: rgb(220 38 38 / .16);--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .5), 0 0 0 1px var(--line);--term-bg: #0c0c0c;--term-fg: #cccccc;color-scheme:dark}:root[data-host-colors]{--bg: var(--magpie-card, var(--magpie-bg, var(--own-bg)));--sb-bg: var(--magpie-bg, var(--own-sb));--fg: var(--magpie-fg, var(--own-fg));--muted: var(--magpie-muted, var(--own-muted));--line: var(--magpie-line, var(--own-line))}@layer reset{html,body{margin:0;padding:0;height:100%}body{background:var(--bg);color:var(--fg);font-family:var(--font-ui);font-size:var(--fs-m);line-height:var(--lh);-webkit-font-smoothing:antialiased}*{box-sizing:border-box}#root{height:100%}button{font:inherit;color:inherit;background:none;border:0;padding:0;cursor:pointer}input,textarea{font:inherit;color:inherit}a{color:var(--accent)}:focus-visible{outline:2px solid color-mix(in oklab,var(--accent) 55%,var(--bg));outline-offset:-1px}}*{scrollbar-width:thin;scrollbar-color:color-mix(in oklab,var(--fg) 18%,transparent) transparent}*::-webkit-scrollbar{width:8px;height:8px}*::-webkit-scrollbar-thumb{background:color-mix(in oklab,var(--fg) 18%,transparent);border-radius:4px}*::-webkit-scrollbar-thumb:hover{background:color-mix(in oklab,var(--fg) 30%,transparent)}*::-webkit-scrollbar-track{background:transparent}.ibtn{width:28px;height:28px;flex:none;display:inline-flex;align-items:center;justify-content:center;border-radius:var(--r-s);color:var(--muted);transition:background var(--dur-1),color var(--dur-1)}.ibtn:hover{background:var(--surface-hover);color:var(--fg)}.ibtn[disabled]{opacity:.35;cursor:default}.ibtn.on{color:var(--accent)}.ibtn svg{width:16px;height:16px}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:30px;padding:0 14px;border-radius:var(--r-s);font-size:var(--fs-m);background:var(--surface-hover);color:var(--fg);transition:background var(--dur-1),filter var(--dur-1)}.btn:hover{filter:brightness(1.03)}.btn[disabled]{opacity:.4;cursor:default}.btn.primary{background:var(--accent);color:var(--accent-fg)}.btn.primary:hover{filter:brightness(1.08)}.btn.danger{color:var(--danger)}.btn.ghost{background:none}.btn.ghost:hover{background:var(--surface-hover)}.tinput{width:100%;height:30px;padding:0 10px;border:1px solid var(--line);border-radius:var(--r-s);background:var(--bg);font-size:var(--fs-m);outline:none}.tinput:focus{border-color:color-mix(in oklab,var(--accent) 55%,var(--bg))}.tinput.err{border-color:var(--danger)}.tinput::placeholder{color:var(--muted)}textarea.tinput{height:auto;min-height:60px;padding:6px 10px;resize:vertical}.menu{position:fixed;z-index:60;min-width:160px;max-width:280px;background:var(--bg);border-radius:var(--r-m);box-shadow:var(--shadow-pop);padding:4px;font-size:var(--fs-m)}.mi{display:flex;align-items:center;gap:8px;width:100%;height:28px;padding:0 10px;border-radius:var(--r-s);text-align:left;color:var(--fg)}.mi:hover:not([disabled]){background:var(--surface-hover)}.mi[disabled]{color:var(--muted);cursor:default}.mi.danger{color:var(--danger)}.mi .mi-check{margin-left:auto;color:var(--accent)}.msep{height:1px;margin:4px 6px;background:var(--line)}.mlabel{padding:6px 10px 2px;font-size:var(--fs-s);color:var(--muted)}.dlg-scrim{position:fixed;inset:0;z-index:70;background:#00000052;display:flex;align-items:center;justify-content:center;padding:24px}.dlg{width:440px;max-width:100%;max-height:80vh;display:flex;flex-direction:column;background:var(--bg);border-radius:var(--r-l);box-shadow:var(--shadow-pop)}.dlg-title{flex:none;padding:14px 16px 4px;font-size:var(--fs-l);font-weight:600}.dlg-body{flex:1;min-height:0;overflow-y:auto;padding:8px 16px}.dlg-foot{flex:none;display:flex;justify-content:flex-end;gap:8px;padding:10px 16px 14px}.dlg-row{margin:10px 0}.dlg-row-top{align-items:flex-start}.dlg-row>label{display:block;margin-bottom:4px;font-size:var(--fs-s);color:var(--muted)}.provider-list{display:flex;flex-direction:column;gap:6px;width:100%;max-height:280px;overflow:auto}.provider-list{display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}.provider-redetect{align-self:flex-start;margin-bottom:4px}.provider-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px 10px;padding:6px 8px;border-radius:var(--r-m);background:var(--bg-2)}.provider-row.open{padding-bottom:10px}.provider-head{display:flex;align-items:center;gap:10px;flex:1;min-width:0;border:0;background:none;text-align:left;cursor:pointer;color:inherit;padding:0}.provider-detail{flex:1 1 100%;display:flex;flex-direction:column;gap:6px;padding:4px 0 0 28px}.provider-hint-row{display:flex;gap:8px;align-items:flex-start;flex-wrap:wrap}.btn.sm{font-size:var(--fs-s);padding:4px 10px;height:auto}.provider-meta{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.provider-name{font-size:var(--fs-m);font-weight:500}.provider-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}.provider-dot-on{background:var(--ok, #3ecf8e)}.provider-dot-off{background:var(--muted);opacity:.5}.provider-dot-pending{background:var(--warn, #e6a817)}.provider-switch input{width:16px;height:16px;cursor:pointer}.dlg-hint{font-size:var(--fs-s);color:var(--muted)}.dlg-hint.err{color:var(--danger)}.toasts{position:fixed;left:50%;bottom:24px;transform:translate(-50%);z-index:80;display:flex;flex-direction:column;gap:8px;align-items:center}.toast{max-width:480px;padding:8px 14px;border-radius:var(--r-m);background:var(--fg);color:var(--bg);font-size:var(--fs-m);box-shadow:var(--shadow-pop);animation:toast-in var(--dur-2) var(--ease)}.toast.err{background:var(--danger);color:#fff}@keyframes toast-in{0%{opacity:0;transform:translateY(8px)}}.dot{width:6px;height:6px;border-radius:50%;flex:none;background:var(--muted)}.dot.run{background:var(--accent-2);animation:breathe 1.6s infinite}.dot.err{background:var(--danger)}.dot.wait{background:var(--warn);animation:breathe 1.6s infinite}@keyframes breathe{50%{opacity:.35}}.boot-screen{height:100%;display:flex;align-items:center;justify-content:center;gap:8px;color:var(--muted);font-size:var(--fs-m)}.boot-screen .btn{margin-top:12px}.boot-wrap{display:flex;flex-direction:column;align-items:center}.boot-dot{width:8px;height:8px;border-radius:50%;background:var(--muted)}.boot-dot[data-state=open]{background:var(--ok)}.boot-dot[data-state=reconnecting]{background:var(--warn)}.boot-dot[data-state=down]{background:var(--danger)}.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}.menu.select-menu{z-index:80;overflow-y:auto;outline:none;max-width:320px}.sm-opt{cursor:pointer;user-select:none;height:auto;min-height:28px;padding:4px 8px 4px 10px}.sm-opt.on{background:var(--surface-hover)}.sm-opt.off{color:var(--muted);cursor:default}.sm-opt.off:hover{background:none}.sm-text{display:flex;flex-direction:column;min-width:0;flex:1 1 auto}.sm-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sm-hint{font-size:var(--fs-s);color:var(--muted);white-space:normal;line-height:1.4}.sm-check{flex:none;width:14px;display:inline-flex;color:var(--accent)}.sm-opt[aria-selected=true] .sm-label{font-weight:500}.tinput.sm-field{display:flex;align-items:center;text-align:left;padding-right:26px;cursor:pointer;position:relative;color:var(--fg);background-image:linear-gradient(45deg,transparent 50%,var(--muted) 50%),linear-gradient(135deg,var(--muted) 50%,transparent 50%);background-position:calc(100% - 14px) 50%,calc(100% - 10px) 50%;background-size:4px 4px;background-repeat:no-repeat}.tinput.sm-field[aria-expanded=true]{border-color:color-mix(in oklab,var(--accent) 55%,var(--bg))}.sm-field .sm-val{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.app{display:flex;height:100vh;min-width:480px;overflow:hidden}.sidebar{width:var(--sb-w, 248px);flex:none;display:flex;flex-direction:column;background:var(--sb-bg);border-right:1px solid var(--line)}.sb-row{display:flex;align-items:center;gap:2px;height:40px;padding:8px 8px 4px;flex:none}.sb-row-search{height:36px;padding:0 8px 4px}.sb-new{flex:1;display:flex;align-items:center;gap:8px;height:28px;min-width:0;padding:0 8px 0 5px;border-radius:var(--r-s);font-size:var(--fs-m);font-weight:500;text-align:left;transition:background var(--dur-1);white-space:nowrap;overflow:hidden}.sb-new-tile{width:18px;height:18px;flex:none;border-radius:5px;background:var(--tile-bg);color:var(--tile-fg);display:inline-flex;align-items:center;justify-content:center}.sb-new-tile svg{stroke-width:2.2}.sb-new:hover{background:var(--surface-hover)}.sb-row .ibtn{width:28px;height:28px}.sb-search{flex:1;display:flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:var(--r-s);background:var(--search-bg);color:var(--meta)}.sb-search input::placeholder{color:var(--meta)}.sb-search input{flex:1;min-width:0;border:0;background:none;font-size:var(--fs-s);outline:none;color:var(--fg)}.sb-list{flex:1;overflow-y:auto;padding:0 8px 8px}.pj-group{margin-top:2px}.pj{display:flex;align-items:center;gap:2px;height:var(--row);padding:0 4px 0 0;border-radius:var(--r-s)}.pj:hover{background:var(--surface-hover)}.pj-toggle{flex:1;min-width:0;height:100%;display:flex;align-items:center;gap:6px;padding-left:2px;text-align:left;font-size:var(--fs-m);font-weight:500}.pj-caret{width:14px;flex:none;display:inline-flex;justify-content:center;color:var(--muted);transition:transform var(--dur-1)}.pj-caret.open{transform:rotate(90deg)}.pj-badge{width:18px;height:18px;flex:none;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;background:var(--badge-bg);color:var(--badge-fg);font-size:11px;font-weight:600;line-height:1;text-transform:uppercase}.pj-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pj-count{flex:none;padding:0 6px;font-size:var(--fs-s);color:var(--meta)}.pj-act{width:22px;height:22px;flex:none;display:none;align-items:center;justify-content:center;border-radius:var(--r-s);color:var(--muted)}.pj:hover .pj-act,.pj-act:focus-visible{display:inline-flex}.pj:hover .pj-count{display:none}.pj-act:hover{background:var(--bg);color:var(--fg)}.pj-sessions{padding:1px 0 4px 22px;display:flex;flex-direction:column;gap:1px}.pj-more,.pj-empty{display:flex;align-items:center;width:100%;height:26px;padding:0 8px 0 21px;font-size:var(--fs-s);color:var(--muted);text-align:left;border-radius:var(--r-s)}.pj-more:hover{background:var(--surface-hover);color:var(--fg)}.t-item{display:flex;align-items:center;gap:8px;width:100%;height:var(--row);padding:0 4px 0 8px;border-radius:var(--r-s);position:relative;text-align:left;font-size:var(--fs-m);transition:background var(--dur-1)}.t-item:hover{background:var(--surface-hover)}.t-item.on{background:var(--active-bg);box-shadow:0 0 0 1px var(--active-line),0 1px 2px #0000000a;font-weight:500}.t-item.on:before{content:"";position:absolute;left:-1px;top:7px;bottom:7px;width:2px;border-radius:2px;background:var(--accent-2)}.t-item.archived{opacity:.55}.t-item.archived .t-title{font-style:italic}.t-item .dot{width:5px;height:5px}.t-pin{width:12px;flex:none;display:inline-flex;color:var(--muted)}.t-pin svg{width:10px;height:10px}.t-title{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.t-time{flex:none;font-size:11.5px;color:var(--meta);font-weight:400}.t-item:hover .t-time{display:none}.t-more{flex:none;width:22px;height:22px;display:none;align-items:center;justify-content:center;border-radius:var(--r-s);color:var(--muted)}.t-item:hover .t-more{display:inline-flex}.t-more:hover{background:var(--bg);color:var(--fg)}.t-rename{flex:1;min-width:0;height:24px;font-size:var(--fs-m);border:1px solid var(--accent);border-radius:var(--r-s);padding:0 6px;background:var(--bg)}.sb-empty{padding:20px 12px;text-align:center;color:var(--muted);font-size:var(--fs-s)}.sb-start{padding:28px 12px;text-align:center}.sb-start-t{font-size:var(--fs-m);font-weight:500}.sb-start-s{margin:4px 0 12px;font-size:var(--fs-s);color:var(--muted)}.rs{width:5px;flex:none;cursor:col-resize;position:relative}.rs:after{content:"";position:absolute;inset:0}.rs:hover:after,.rs.drag:after{background:color-mix(in oklab,var(--accent) 30%,transparent)}.rs-l{margin-left:-3px}.rs-r{margin-right:-3px}body.col-drag{cursor:col-resize;user-select:none}body.col-drag iframe,body.col-drag .xterm{pointer-events:none}.scrim{position:fixed;inset:0;z-index:45;background:#00000052;display:none}.scrim.show{display:block}.main{flex:1;min-width:0;display:flex;flex-direction:column;background:var(--bg);position:relative}.topbar{height:40px;flex:none;display:flex;align-items:center;gap:6px;padding:0 10px;border-bottom:1px solid var(--line)}.tb-menu-btn{display:none}.tb-menu-btn.tb-sb-collapsed{display:inline-flex;margin-right:2px}.tb-crumb{flex:none;max-width:26%;font-size:var(--fs-m);color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.tb-sep{flex:none;color:var(--muted)}.tb-title{font-size:var(--fs-l);font-weight:500;max-width:40%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;border-radius:var(--r-s);padding:2px 6px;cursor:text}.tb-title:hover{background:var(--surface)}.tb-title.ghost{color:var(--muted);cursor:default}.tb-title.ghost:hover{background:none}.tb-rename{font-size:var(--fs-l);font-weight:500;border:1px solid var(--accent);border-radius:var(--r-s);padding:1px 6px;background:var(--bg);width:300px;max-width:46vw}.tb-pill{flex:none;display:inline-flex;align-items:center;gap:6px;height:22px;padding:0 9px;border-radius:var(--r-full);font-size:var(--fs-s);background:var(--surface);color:var(--muted)}.tb-pill.run{background:var(--run-bg);color:var(--run-fg)}.tb-pill-dot{width:7px;height:7px;border-radius:50%;background:var(--accent-2);box-shadow:0 0 0 3px color-mix(in oklab,var(--accent-2) 20%,transparent);animation:breathe 1.6s infinite}.tb-pill.wait{color:var(--warn)}.tb-pill.err{color:var(--danger)}.tb-right{margin-left:auto;display:flex;align-items:center;gap:2px}.tb-model{font-size:var(--fs-s);color:var(--muted);margin-right:4px;white-space:nowrap;max-width:160px;overflow:hidden;text-overflow:ellipsis}.connbar{flex:none;height:26px;display:flex;align-items:center;justify-content:center;font-size:var(--fs-s);background:color-mix(in oklab,var(--warn) 14%,var(--bg));color:var(--warn)}.scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;position:relative}.tl-wrap{max-width:calc(var(--col) + 40px);min-width:0;margin:0 auto;padding:24px 20px 16px}.jump{position:absolute;right:24px;bottom:150px;width:34px;height:34px;border-radius:50%;background:var(--bg);box-shadow:var(--shadow-pop);display:flex;align-items:center;justify-content:center;color:var(--muted);z-index:5}.jump:hover{color:var(--fg)}.jump svg{transform:rotate(90deg)}.jump .jd{position:absolute;top:4px;right:4px;width:7px;height:7px;border-radius:50%;background:var(--accent)}.panel{width:var(--pn-w, 440px);flex:none;display:flex;flex-direction:column;background:var(--bg);border-left:1px solid var(--line)}.pn-head{flex:none;display:flex;align-items:center;gap:2px;height:40px;padding:0 6px;border-bottom:1px solid var(--line)}.pn-tabs{display:flex;gap:2px}.pn-tab{height:28px;padding:0 10px;border-radius:var(--r-s);font-size:var(--fs-m);color:var(--muted);display:inline-flex;align-items:center;gap:6px}.pn-tab:hover{background:var(--surface-hover);color:var(--fg)}.pn-tab.on{background:var(--surface-hover);color:var(--fg);font-weight:500}.pn-body{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden}.pn-close{margin-left:auto}.pn-empty{padding:20px;color:var(--muted);font-size:var(--fs-m);text-align:center}.pn-empty-sub{margin-top:6px;font-size:var(--fs-s);opacity:.8}.chg-head{flex:none;display:flex;align-items:center;gap:6px;height:34px;padding:0 8px;border-bottom:1px solid var(--line);font-size:var(--fs-m)}.chg-branch{display:inline-flex;align-items:center;gap:5px;color:var(--muted);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.chg-head .ibtn{margin-left:auto}.chg-list{flex:none;max-height:40%;overflow-y:auto;border-bottom:1px solid var(--line)}.chg-list:empty{border-bottom:none}.chg-row{display:flex;align-items:center;gap:7px;padding:4px 8px;cursor:pointer;font-size:var(--fs-m);min-height:28px}.chg-row:hover,.chg-row.on{background:var(--surface-hover)}.chg-kind{flex:none;width:18px;height:18px;border-radius:var(--r-s);font-size:10px;display:inline-flex;align-items:center;justify-content:center;background:var(--surface);color:var(--muted)}.chg-kind.k-modified{color:var(--warn, #b45309)}.chg-kind.k-added,.chg-kind.k-untracked{color:var(--ok, #15803d)}.chg-kind.k-deleted{color:var(--danger)}.chg-kind.k-renamed{color:var(--accent)}.chg-path{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;direction:rtl;text-align:left}.chg-stat{flex:none;font-style:normal;font-size:var(--fs-s);font-variant-numeric:tabular-nums}.chg-stat .add{color:var(--ok, #15803d);font-style:normal}.chg-stat .del{color:var(--danger);font-style:normal}.chg-discard{flex:none;opacity:0}.chg-row:hover .chg-discard{opacity:1}.chg-diff{flex:1;min-height:0;overflow:auto}.ft-crumbs{flex:none;display:flex;align-items:center;gap:4px;min-height:34px;padding:0 8px;border-bottom:1px solid var(--line);font-size:var(--fs-m);overflow-x:auto;white-space:nowrap}.ft-crumb{color:var(--muted);font-size:var(--fs-m);padding:2px 4px;border-radius:var(--r-s)}.ft-crumb:hover{background:var(--surface-hover);color:var(--fg)}.ft-crumb-t{color:var(--fg)}.ft-crumb-t.muted{color:var(--muted)}.ft-tree{flex:none;max-height:45%;overflow-y:auto;padding:4px 0}.ft-row{display:flex;align-items:center;gap:5px;padding:3px 8px;cursor:pointer;font-size:var(--fs-m);min-height:24px}.ft-row:hover,.ft-row.on{background:var(--surface-hover)}.ft-row .caret{font-size:11px;color:var(--muted);display:inline-block;transition:transform var(--dur-1) var(--ease)}.ft-row .caret.open{transform:rotate(90deg)}.ft-dot{width:13px;flex:none}.ft-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ft-err{color:var(--danger);font-size:var(--fs-s);padding:2px 0}.ft-view{flex:1;min-height:0;overflow:auto;border-top:1px solid var(--line)}.ft-pre{margin:0;padding:10px 12px;font-family:var(--font-mono);font-size:var(--chat-code-fs);line-height:1.55}.ft-pre code{background:none;padding:0;display:block;white-space:pre}.tm-tabs{flex:none;display:flex;align-items:center;gap:2px;padding:4px 6px;border-bottom:1px solid var(--line);overflow-x:auto}.tm-tab{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 6px 0 10px;border-radius:var(--r-s);font-size:var(--fs-m);color:var(--muted);white-space:nowrap}.tm-tab:hover,.tm-tab.on{background:var(--surface-hover);color:var(--fg)}.tm-x{color:var(--muted);padding:0 3px;border-radius:3px}.tm-x:hover{color:var(--danger);background:var(--surface-hover)}.tm-note{flex:none;padding:4px 10px;font-size:var(--fs-s);color:var(--warn);background:color-mix(in oklab,var(--warn) 10%,var(--bg));border-bottom:1px solid var(--line)}.tm-body{flex:1;min-height:0;position:relative;background:var(--term-bg)}.tm-view{position:absolute;inset:0;padding:6px 8px;background:var(--term-bg)}.tm-view .xterm{height:100%}.tm-view .xterm-viewport{background:var(--term-bg)!important}.tm-view .xterm-screen{padding:2px 0}.imp-list{max-height:320px;overflow-y:auto;display:flex;flex-direction:column;gap:2px}.imp-row{display:flex;align-items:center;gap:8px;padding:5px 6px;border-radius:var(--r-s);font-size:var(--fs-m);cursor:pointer}.imp-row:hover{background:var(--surface-hover)}.imp-row.done{opacity:.55;cursor:default}.imp-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.imp-meta{flex:none;color:var(--muted);font-size:var(--fs-s)}.info-grid{display:flex;flex-direction:column;gap:2px}.info-row{display:flex;align-items:center;gap:10px;padding:3px 2px;font-size:var(--fs-m)}.info-k{flex:none;width:74px;color:var(--muted)}.info-v{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--font-mono);font-size:var(--fs-s)}@media(min-width:760px){.sidebar{transition:margin-left var(--dur-2) var(--ease),visibility 0s linear 0s}.sidebar.w-hide{margin-left:calc(-1 * var(--sb-w, 248px));visibility:hidden;transition:margin-left var(--dur-2) var(--ease),visibility 0s linear var(--dur-2)}.sidebar.w-hide+.rs-l{display:none}}@media(prefers-reduced-motion:reduce){.sidebar,.sidebar.w-hide{transition:none}}.sb-row .sb-toggle{flex:none;color:var(--muted)}.sb-toggle:hover{color:var(--fg)}@media(min-width:900px){.panel.w-hide{display:none}}@media(max-width:899px){.panel{position:fixed;right:0;top:0;bottom:0;z-index:46;width:min(var(--pn-w, 440px),92vw);transform:translate(100%);transition:transform var(--dur-2) var(--ease);box-shadow:var(--shadow-pop)}.panel.open{transform:none}.rs-r{display:none}}@media(max-width:759px){.sidebar{position:fixed;left:0;top:0;bottom:0;z-index:46;width:min(var(--sb-w, 248px),84vw);transform:translate(-100%);transition:transform var(--dur-2) var(--ease);box-shadow:var(--shadow-pop)}.sidebar.open{transform:none}.sidebar~.rs-l{display:none}.tb-menu-btn{display:inline-flex}.tl-wrap{padding:16px 14px 8px}.tb-model{display:none}}.dlg.cpal{width:520px;padding:6px}.cpal-in{width:100%;height:36px;padding:0 12px;border:0;background:none;outline:none;font-size:var(--fs-l);color:var(--fg)}.cpal-list{max-height:46vh;overflow-y:auto;padding:4px}.cpal-item{display:flex;align-items:center;gap:8px;width:100%;height:30px;padding:0 10px;border-radius:var(--r-s);text-align:left;font-size:var(--fs-m)}.cpal-item.on{background:var(--surface-hover)}.cpal-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cpal-hint{flex:none;font-size:var(--fs-s);color:var(--muted)}.pv{flex:1;min-height:0;display:flex;flex-direction:column}.pv-bar{flex:none;display:flex;align-items:center;gap:2px;height:38px;padding:0 6px;border-bottom:1px solid var(--line)}.pv-bar .ibtn{width:26px;height:26px;flex:none;color:var(--muted)}.pv-bar .ibtn:hover:not(:disabled){color:var(--fg)}.pv-bar .ibtn:disabled{opacity:.35;cursor:default}.pv-addr{flex:1;min-width:0;height:26px;padding:0 8px;margin:0 2px;border-radius:var(--r-s);background:var(--search-bg);border:1px solid transparent;color:var(--fg);font-family:var(--font-mono);font-size:var(--fs-s);outline:none}.pv-addr:focus{border-color:var(--cp-focus);background:var(--bg)}.pv-addr.err{border-color:color-mix(in oklab,var(--danger) 60%,var(--bg))}.pv-note{flex:none;display:flex;align-items:center;gap:8px;padding:6px 10px;font-size:var(--fs-s);color:var(--muted);border-bottom:1px solid var(--line)}.pv-note.err{color:var(--danger)}.pv-note .btn{height:24px;font-size:var(--fs-s)}.pv-frame-wrap{flex:1;min-height:0;position:relative;background:var(--bg)}.pv-frame{position:absolute;inset:0;width:100%;height:100%;border:0;background:#fff}.pv-loading{position:absolute;top:0;left:0;right:0;height:2px;background:var(--accent-2);opacity:.5;animation:breathe 1s infinite}.pv-empty{padding:28px 22px;color:var(--muted);font-size:var(--fs-m);text-align:center;line-height:1.7}.pv-empty code{font-family:var(--font-mono);font-size:var(--fs-s);background:var(--code-bg);border:1px solid var(--code-line);border-radius:4px;padding:0 4px;color:var(--code-fg)}.pv-hint{margin-top:10px;font-size:var(--fs-s);color:var(--meta)}.ft-row[draggable=true]{cursor:default}.ft-row.dragging{opacity:.5}.um-row{display:flex;flex-direction:column;align-items:flex-end;margin:4px 0 16px}.um{position:relative;max-width:78%;background:var(--accent-soft);border-radius:14px 14px 4px;color:var(--fg);padding:6px 12px;font-size:var(--chat-fs);line-height:1.6;white-space:pre-wrap;word-break:normal;overflow-wrap:break-word}.um:hover .um-act{display:flex}.um-act{position:absolute;left:-62px;top:4px;display:none;gap:2px}.um-act .ibtn{width:24px;height:24px}.um-img{display:block;max-width:200px;max-height:140px;border-radius:var(--r-s);margin-bottom:6px;cursor:zoom-in}.um-tag{font-size:var(--chat-fs-s);color:var(--muted);margin-top:2px}.as{margin:4px 0}.md.streaming:after{content:"\258d";color:var(--accent);animation:breathe 1s infinite}.md{font-size:var(--chat-fs);line-height:var(--chat-lh);color:var(--text);word-break:normal;overflow-wrap:break-word}.md p{margin:0 0 .6em}.md>:last-child{margin-bottom:0}.md a{color:var(--accent);text-decoration:underline;text-underline-offset:2px;text-decoration-color:color-mix(in oklab,var(--accent) 40%,transparent)}.md a:hover{text-decoration:underline}.md pre{position:relative;background:var(--code-bg);border:1px solid var(--code-line);border-radius:var(--r-m);padding:10px 12px;overflow-x:auto;font-family:var(--font-mono);font-size:var(--chat-code-fs);line-height:1.55}.md code{font-family:var(--font-mono);font-size:var(--chat-code-fs);background:var(--code-bg);color:var(--code-fg);padding:1px 5px;border-radius:4px;border:1px solid var(--code-line)}.md pre code{background:none;padding:0;border:0;color:inherit;font-size:inherit}.md ul,.md ol{margin:.45em 0;padding-left:1.7em}.md li+li{margin-top:.15em}.md h1,.md h2,.md h3,.md h4{margin:.95em 0 .4em;font-weight:600;line-height:1.4}.md h1{font-size:calc(var(--chat-fs) + 4px)}.md h2{font-size:calc(var(--chat-fs) + 2px)}.md h3{font-size:calc(var(--chat-fs) + 1px)}.md h4{font-size:var(--chat-fs)}.md>h1:first-child,.md>h2:first-child,.md>h3:first-child,.md>h4:first-child{margin-top:.2em}.md blockquote{margin:6px 0;padding-left:12px;border-left:3px solid var(--line);color:var(--muted)}.md table{border-collapse:collapse;margin:8px 0}.md th,.md td{border:1px solid var(--line);padding:4px 10px;font-size:var(--chat-fs-s)}.cb-copy{position:absolute;top:6px;right:6px;font-size:var(--fs-s);color:var(--muted);padding:2px 8px;border-radius:var(--r-s);background:var(--bg);opacity:0;transition:opacity var(--dur-1)}.md pre:hover .cb-copy{opacity:1}.cb-copy:hover{color:var(--fg)}.rs-item{margin:4px 0 6px}.rs-head{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0;color:var(--meta);font-size:var(--chat-fs-s)}.rs-head:hover{color:var(--fg)}.rs-head .caret{display:inline-block;transition:transform var(--dur-1)}.rs-head .caret.open{transform:rotate(90deg)}.rs-body{margin:2px 0 6px 5px;padding-left:12px;border-left:1px solid var(--line);color:var(--muted);font-size:var(--chat-fs-s);line-height:1.65;white-space:pre-wrap}.todo-list{margin:2px 0 6px 5px;padding-left:12px;border-left:1px solid var(--line);list-style:none;font-size:var(--chat-fs-s)}.todo{color:var(--muted)}.todo.in_progress{color:var(--fg)}.tg{margin:4px 0 10px}.tg-head{display:flex;align-items:center;gap:6px;width:100%;height:24px;padding:0;color:var(--meta);font-size:var(--chat-fs-s);text-align:left}.tg-head:hover{color:var(--fg)}.tg-head .caret{transition:transform var(--dur-1)}.tg-head .caret.open{transform:rotate(90deg)}.tg-live{margin-left:auto;color:var(--accent);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.tg-list{margin:2px 0 0 5px;border-left:1px solid var(--line);padding-left:6px}.ts-head{display:flex;align-items:center;gap:8px;width:100%;height:26px;padding:0 6px;border-radius:var(--r-s);font-size:calc(var(--chat-fs) - .5px);text-align:left;color:var(--text)}.ts-head:hover{background:var(--surface-hover)}.ts-ic{width:14px;flex:none;text-align:center}.ts-ic.ok{color:var(--ok)}.ts-ic.fail{color:var(--danger)}.ts-ic.run{color:var(--accent-2);animation:breathe 1.2s infinite}.ts-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.ts-meta{flex:none;color:var(--meta);font-variant-numeric:tabular-nums}.ts-meta.err{color:var(--danger)}.ts-out{margin:2px 8px 6px 30px}.ts-out pre{background:var(--code-bg);border-radius:var(--r-s);padding:8px 10px;font-family:var(--font-mono);font-size:var(--chat-code-fs);line-height:1.5;overflow-x:auto;white-space:pre-wrap;word-break:break-all;margin:0}.ts-more{font-size:var(--chat-fs-s);color:var(--accent);margin-bottom:4px}.diff{margin:2px 6px 6px 22px;border:1px solid var(--line);border-radius:var(--r-m);overflow:hidden}.diff-path{padding:4px 10px;font-size:var(--chat-code-fs);color:var(--muted);background:var(--surface);border-bottom:1px solid var(--line);font-family:var(--font-mono)}.diff-pre{margin:0;padding:6px 0;font-family:var(--font-mono);font-size:var(--chat-code-fs);line-height:1.5;overflow-x:auto}.dh-head{display:block;color:var(--muted);padding:0 10px}.dl{display:block;padding:0 10px;white-space:pre-wrap;word-break:break-all}.dl.add{background:var(--add-bg)}.dl.del{background:var(--del-bg)}.card{margin:8px 0;border-radius:10px;padding:12px 14px}.card.plan{border:1px solid var(--line)}.card.perm{border:1px solid color-mix(in oklab,var(--warn) 30%,var(--bg));background:color-mix(in oklab,var(--warn) 3%,var(--bg))}.card.perm.done{border-color:var(--line);opacity:.75}.card.ask{border:1px solid color-mix(in oklab,var(--info) 45%,var(--bg))}.card.ask.done{border-color:var(--line);opacity:.75}.err-card{border:1px solid color-mix(in oklab,var(--danger) 45%,var(--bg))}.err-line{color:var(--danger);font-size:var(--chat-fs)}.perm-title{font-size:var(--chat-fs);font-weight:500}.perm-cmd{margin:8px 0 0;background:var(--code-bg);border-radius:var(--r-s);padding:8px 10px;font-family:var(--font-mono);font-size:var(--chat-code-fs);white-space:pre-wrap;word-break:break-all}.perm-path{margin-top:6px;font-family:var(--font-mono);font-size:var(--chat-code-fs);color:var(--muted)}.perm-btns{display:flex;gap:8px;margin-top:10px}.perm-done{margin-top:8px;font-size:var(--chat-fs-s);color:var(--muted)}.ask-q{margin-bottom:10px}.ask-t{font-size:var(--chat-fs);font-weight:500;margin-bottom:6px}.ask-opts{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:6px}.ask-free,.ask .btn.primary{margin-top:4px}.nt{margin:8px 0;text-align:center;font-size:var(--chat-fs-s);color:var(--muted)}.nt.warn{color:var(--warn)}.nt.error{color:var(--danger)}.te{display:flex;justify-content:flex-start;align-items:center;gap:2px;margin:4px 0 18px -6px;font-size:var(--chat-fs-s);color:var(--meta)}.te-meta{padding:0 6px;font-variant-numeric:tabular-nums}.te-act{height:24px;min-width:24px;display:inline-flex;align-items:center;justify-content:center;gap:4px;padding:0 5px;border-radius:var(--r-s);color:var(--meta)}.te-act span{display:none}.te-act:hover{background:var(--surface-hover);color:var(--fg)}.te-files{color:var(--accent);font-size:var(--fs-s);margin-left:6px}.te-files:hover{text-decoration:underline}.empty-wrap{min-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;padding-bottom:14vh}.cp-hero-t{font-size:var(--fs-hero);font-weight:600}.cp-hero-s{margin-top:6px;font-size:var(--fs-s);color:var(--muted)}.empty-actions{margin-top:16px}.workspace-empty{padding-bottom:10vh}.q-list{max-width:var(--col);margin:0 auto 6px;display:flex;flex-direction:column;gap:4px}.q-item{display:flex;align-items:center;gap:8px;padding:4px 10px;background:var(--surface);border-radius:var(--r-s);font-size:var(--fs-s)}.q-text{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.q-item .ibtn{width:20px;height:20px}a.ac-local{cursor:pointer}.ts-out pre a.ac-local,.md pre a.ac-local{color:inherit;text-decoration:underline;text-decoration-color:color-mix(in oklab,currentColor 45%,transparent);text-underline-offset:2px}.md code a.ac-local{color:inherit}.mention{display:inline-flex;align-items:center;gap:4px;max-width:260px;height:22px;padding:0 6px;border-radius:var(--r-s);background:var(--chip-bg);border:1px solid var(--chip-line);color:var(--pill-fg);font-size:var(--fs-s);font-family:var(--font-mono);white-space:nowrap;vertical-align:middle}.mention svg{flex:none}.mention-name{min-width:0;overflow:hidden;text-overflow:ellipsis}.um-mentions{display:flex;flex-wrap:wrap;gap:4px;margin:2px 0 4px;white-space:normal}.um .mention{background:color-mix(in oklab,var(--fg) 5%,var(--accent-soft))}.composer{flex:none;padding:0 16px 16px}.cp-card{width:100%;max-width:var(--col);margin:0 auto;background:var(--bg);border-radius:14px;border:1px solid var(--cp-line);padding:12px 12px 8px 14px;box-shadow:0 1px 2px #0000000a;transition:border-color var(--dur-2) var(--ease),box-shadow var(--dur-2) var(--ease)}.cp-card:focus-within{border-color:var(--cp-focus);box-shadow:0 0 0 3px var(--cp-ring),0 1px 2px #0000000a}.cp-card.waiting{border-color:color-mix(in oklab,var(--warn) 45%,var(--bg))}.cp-card.danger{border-color:color-mix(in oklab,var(--danger) 40%,var(--bg))}.cp-danger{max-width:var(--col);margin:0 auto 6px;display:flex;align-items:center;gap:6px;color:var(--danger);font-size:var(--fs-s);padding:0 2px}.cp-hint{max-width:var(--col);margin:6px auto 0;font-size:11.5px;color:var(--meta);text-align:center}.att-note{padding:6px 10px 0;color:var(--muted);font-size:var(--fs-s)}.cp-ta-wrap{position:relative}.slash-pop{position:absolute;left:0;right:0;bottom:100%;margin-bottom:6px;max-height:min(240px,40vh);overflow:hidden;display:flex;flex-direction:column;z-index:20}.slash-pop .ap-scroll{max-height:inherit}.slash-pop .slash-h{padding:4px 10px 2px;font-size:var(--fs-xs);color:var(--muted);text-transform:uppercase;letter-spacing:.04em}.slash-pop .mi.slash-item{height:auto;min-height:28px;padding:4px 10px;flex-direction:column;align-items:flex-start;gap:0}.slash-pop .slash-name{font-weight:500}.slash-pop .slash-desc{font-size:var(--fs-xs);color:var(--muted);line-height:1.3}.slash-pop .slash-hint{font-size:var(--fs-xs);color:var(--muted);font-family:var(--mono, monospace)}.slash-pop .mi.slash-item.sel{background:var(--surface-hover)}.cp-ta{width:100%;border:0;resize:none;background:none;outline:none;color:var(--text);font-size:var(--chat-fs);line-height:calc(var(--chat-fs) * 1.62);min-height:34px;max-height:calc(var(--chat-fs) * 1.62 * 12);overflow-y:auto;display:block;padding:0}.cp-ta::placeholder{color:var(--meta)}.cp-bar{display:flex;align-items:center;flex-wrap:wrap;gap:2px;margin:4px 0 0 -6px;min-width:0}.pill-wrap{position:relative;flex:0 1 auto;min-width:0;max-width:100%}.pill{position:relative;display:inline-flex;align-items:center;gap:5px;height:26px;padding:0 8px;border-radius:7px;background:none;color:var(--pill-fg, var(--muted));border:1px solid transparent;font-size:var(--fs-s);max-width:min(240px,100%);min-width:0;white-space:nowrap;cursor:pointer;transition:background var(--dur-1)}.pill:hover{background:var(--surface-hover)}.pill svg{flex:none}.pill.chip{background:var(--chip-bg);border-color:var(--chip-line);padding:0 8px 0 4px;gap:6px;max-width:min(300px,100%)}.pill.chip:hover{background:var(--surface-hover)}.chip-logo{border-radius:5px}.chip-caret{color:var(--meta)}.pill .p-a{font-weight:500;color:var(--fg);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:0 0 auto;max-width:120px}.pill .p-t{color:var(--meta);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1 1 auto}.pill .p-t:before{content:"\b7";margin-right:5px}.ipill .ip-l{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.ipill:focus-visible{outline:2px solid color-mix(in oklab,var(--accent) 45%,var(--bg));outline-offset:-1px}.ipill[aria-expanded=true]{background:var(--surface-hover)}.ipill.danger{color:var(--danger)}.mode-menu{max-width:300px}.cp-div{width:1px;height:14px;background:var(--line);margin:0 4px;flex:none}.cp-bar>.ibtn{flex:none}.cp-attach{color:var(--pill-fg, var(--muted))}.cp-card{container-type:inline-size;container-name:composer}@container composer (max-width: 520px){.pill .p-t{display:none}.pill{max-width:min(160px,100%)}.ipill .ip-l{max-width:64px}}@container composer (max-width: 380px){.pill{max-width:min(120px,100%);padding:0 6px}.ipill .ip-l{display:none}}.pop{position:absolute;bottom:32px;left:0;z-index:55;width:260px;background:var(--bg);border-radius:var(--r-m);box-shadow:var(--shadow-pop);padding:4px;max-height:60vh;overflow-y:auto}.agent-picker{width:min(300px,calc(100vw - 32px));padding:0;overflow:hidden;display:flex;flex-direction:column;max-height:min(420px,60vh)}.agent-picker .ap-search{display:flex;align-items:center;gap:8px;padding:8px 10px;border-bottom:1px solid var(--line);flex:none;color:var(--muted)}.agent-picker .ap-search-in{flex:1;min-width:0;border:0;background:none;outline:none;font-size:var(--fs-s);color:var(--fg)}.agent-picker .ap-search-in::placeholder{color:var(--muted)}.agent-picker .ap-scroll{overflow-y:auto;padding:4px;flex:1;min-height:0}.agent-picker .ap-empty{padding:12px 10px;font-size:var(--fs-s);color:var(--muted);text-align:center}.agent-picker .ap-back{font-weight:600;margin-bottom:2px}.agent-picker .ap-back-icon{display:inline-flex;transform:rotate(180deg);margin-right:2px}.agent-picker .mi-row{display:flex;align-items:center;gap:6px;width:100%;text-align:left}.agent-picker .provider-pick-row{justify-content:space-between;gap:8px}.agent-picker .provider-pick-name{flex:0 1 auto;min-width:5.5rem;max-width:58%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;color:inherit}.agent-picker .provider-pick-meta{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:flex-end;gap:6px;min-width:0;margin-left:auto}.agent-picker .provider-pick-meta .dlg-hint{flex:none;font-size:10px;max-width:5rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .mi-row .mi-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .mi-row .mi-sub{flex:none;max-width:38%;font-size:11px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .model-pick-row{min-width:0}.agent-picker .model-pick-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .model-pick-default{flex:0 1 58%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.agent-picker .mi-meta{flex:none;font-size:11px;color:var(--muted);white-space:nowrap}.agent-picker .mi-tag{flex:none;font-size:10px;color:var(--accent)}.agent-picker .mi-caret{flex:none;color:var(--muted);display:inline-flex}.agent-picker .mi-check{flex:none;margin-left:auto;color:var(--accent)}.ap-sec{padding:4px 0}.ap-sec .tinput{height:26px;margin-bottom:4px}.ap-sec .mi{height:26px;font-size:var(--fs-s)}.att-bar{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 6px}.att{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 8px;background:var(--surface-hover);border-radius:var(--r-s);font-size:var(--fs-s)}.att img{width:22px;height:22px;object-fit:cover;border-radius:4px}.att.up{opacity:.6}.att-name{max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.att-x{color:var(--muted);font-size:14px;line-height:1}.att-x:hover{color:var(--fg)}.cp-right{margin-left:auto;flex:none;display:flex;align-items:center;gap:8px}.cp-clock{font-size:var(--fs-s);color:var(--meta);font-variant-numeric:tabular-nums}.cp-send,.cp-stop{width:30px;height:30px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;transition:filter var(--dur-1),opacity var(--dur-1)}.cp-send{background:var(--accent);color:var(--accent-fg)}.cp-send:hover{filter:brightness(1.08)}.cp-send[disabled]{opacity:.35;cursor:default;filter:none}.cp-stop{background:var(--fg);color:var(--bg)}.cp-stop:hover{filter:brightness(1.15)}@media(max-width:560px){.composer{padding:0 10px 10px}}.cp-card.drop-on{outline:1.5px dashed var(--cp-focus);outline-offset:2px}.cp-drop-hint{padding:4px 10px 0;font-size:var(--fs-s);color:var(--muted)}.att-bar .mention{height:24px}.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;inset:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;inset:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{font-family:monospace;user-select:text;white-space:pre}.xterm .xterm-accessibility-tree>div{transform-origin:left;width:fit-content}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}.xterm .xterm-scrollable-element>.scrollbar{cursor:default}.xterm .xterm-scrollable-element>.scrollbar>.scra{cursor:pointer;font-size:11px!important}.xterm .xterm-scrollable-element>.visible{opacity:1;background:#0000;transition:opacity .1s linear;z-index:11}.xterm .xterm-scrollable-element>.invisible{opacity:0;pointer-events:none}.xterm .xterm-scrollable-element>.invisible.fade{transition:opacity .8s linear}.xterm .xterm-scrollable-element>.shadow{position:absolute;display:none}.xterm .xterm-scrollable-element>.shadow.top{display:block;top:0;left:3px;height:3px;width:100%;box-shadow:var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.left{display:block;top:3px;left:0;height:100%;width:3px;box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset}.xterm .xterm-scrollable-element>.shadow.top-left-corner{display:block;top:0;left:0;height:3px;width:3px}.xterm .xterm-scrollable-element>.shadow.top.left{box-shadow:var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset} /*! Bundled license information: @xterm/xterm/css/xterm.css: diff --git a/packages/agent-console/app/app.js b/packages/agent-console/app/app.js index 30f98b2..3d348db 100644 --- a/packages/agent-console/app/app.js +++ b/packages/agent-console/app/app.js @@ -1,104 +1,105 @@ -(()=>{var oR=Object.create;var Fu=Object.defineProperty;var lR=Object.getOwnPropertyDescriptor;var cR=Object.getOwnPropertyNames;var uR=Object.getPrototypeOf,hR=Object.prototype.hasOwnProperty;var u0=e=>{throw TypeError(e)};var dR=(e,t,i)=>t in e?Fu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var le=(e,t,i)=>()=>{if(i)throw i[0];try{return e&&(t=e(e=0)),t}catch(n){throw i=[n],n}};var me=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},fR=(e,t)=>{for(var i in t)Fu(e,i,{get:t[i],enumerable:!0})},pR=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of cR(t))!hR.call(e,s)&&s!==i&&Fu(e,s,{get:()=>t[s],enumerable:!(n=lR(t,s))||n.enumerable});return e};var ae=(e,t,i)=>(i=e!=null?oR(uR(e)):{},pR(t||!e||!e.__esModule?Fu(i,"default",{value:e,enumerable:!0}):i,e));var de=(e,t,i)=>dR(e,typeof t!="symbol"?t+"":t,i),mR=(e,t,i)=>t.has(e)||u0("Cannot "+i);var h0=(e,t,i)=>t.has(e)?u0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i);var dp=(e,t,i)=>(mR(e,t,"access private method"),i);var d0=le(()=>{});var f0=le(()=>{});var p0=le(()=>{});var m0=le(()=>{});var g0=le(()=>{});var k0=me(mt=>{"use strict";function gp(e,t){var i=e.length;e.push(t);e:for(;0>>1,s=e[n];if(0>>1;nqu(o,i))lqu(c,o)?(e[n]=c,e[l]=i,n=l):(e[n]=o,e[a]=i,n=a);else if(lqu(c,i))e[n]=c,e[l]=i,n=l;else break e}}return t}function qu(e,t){var i=e.sortIndex-t.sortIndex;return i!==0?i:e.id-t.id}mt.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(_0=performance,mt.unstable_now=function(){return _0.now()}):(fp=Date,v0=fp.now(),mt.unstable_now=function(){return fp.now()-v0});var _0,fp,v0,Ls=[],hr=[],gR=1,yn=null,wi=3,_p=!1,Hl=!1,Fl=!1,vp=!1,S0=typeof setTimeout=="function"?setTimeout:null,w0=typeof clearTimeout=="function"?clearTimeout:null,b0=typeof setImmediate<"u"?setImmediate:null;function Ku(e){for(var t=as(hr);t!==null;){if(t.callback===null)Wu(hr);else if(t.startTime<=e)Wu(hr),t.sortIndex=t.expirationTime,gp(Ls,t);else break;t=as(hr)}}function bp(e){if(Fl=!1,Ku(e),!Hl)if(as(Ls)!==null)Hl=!0,fo||(fo=!0,ho());else{var t=as(hr);t!==null&&yp(bp,t.startTime-e)}}var fo=!1,ql=-1,E0=5,x0=-1;function C0(){return vp?!0:!(mt.unstable_now()-x0e&&C0());){var n=yn.callback;if(typeof n=="function"){yn.callback=null,wi=yn.priorityLevel;var s=n(yn.expirationTime<=e);if(e=mt.unstable_now(),typeof s=="function"){yn.callback=s,Ku(e),t=!0;break t}yn===as(Ls)&&Wu(Ls),Ku(e)}else Wu(Ls);yn=as(Ls)}if(yn!==null)t=!0;else{var r=as(hr);r!==null&&yp(bp,r.startTime-e),t=!1}}break e}finally{yn=null,wi=i,_p=!1}t=void 0}}finally{t?ho():fo=!1}}}var ho;typeof b0=="function"?ho=function(){b0(pp)}:typeof MessageChannel<"u"?(mp=new MessageChannel,y0=mp.port2,mp.port1.onmessage=pp,ho=function(){y0.postMessage(null)}):ho=function(){S0(pp,0)};var mp,y0;function yp(e,t){ql=S0(function(){e(mt.unstable_now())},t)}mt.unstable_IdlePriority=5;mt.unstable_ImmediatePriority=1;mt.unstable_LowPriority=4;mt.unstable_NormalPriority=3;mt.unstable_Profiling=null;mt.unstable_UserBlockingPriority=2;mt.unstable_cancelCallback=function(e){e.callback=null};mt.unstable_forceFrameRate=function(e){0>e||125n?(e.sortIndex=i,gp(hr,e),as(Ls)===null&&e===as(hr)&&(Fl?(w0(ql),ql=-1):Fl=!0,yp(bp,i-n))):(e.sortIndex=s,gp(Ls,e),Hl||_p||(Hl=!0,fo||(fo=!0,ho()))),e};mt.unstable_shouldYield=C0;mt.unstable_wrapCallback=function(e){var t=wi;return function(){var i=wi;wi=t;try{return e.apply(this,arguments)}finally{wi=i}}}});var N0=me((IP,T0)=>{"use strict";T0.exports=k0()});var F0=me(be=>{"use strict";var Ep=Symbol.for("react.transitional.element"),_R=Symbol.for("react.portal"),vR=Symbol.for("react.fragment"),bR=Symbol.for("react.strict_mode"),yR=Symbol.for("react.profiler"),SR=Symbol.for("react.consumer"),wR=Symbol.for("react.context"),ER=Symbol.for("react.forward_ref"),xR=Symbol.for("react.suspense"),CR=Symbol.for("react.memo"),D0=Symbol.for("react.lazy"),kR=Symbol.for("react.activity"),TR=Symbol.for("react.view_transition"),A0=Symbol.iterator;function NR(e){return e===null||typeof e!="object"?null:(e=A0&&e[A0]||e["@@iterator"],typeof e=="function"?e:null)}var L0={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},B0=Object.assign,I0={};function mo(e,t,i){this.props=e,this.context=t,this.refs=I0,this.updater=i||L0}mo.prototype.isReactComponent={};mo.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};mo.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function z0(){}z0.prototype=mo.prototype;function xp(e,t,i){this.props=e,this.context=t,this.refs=I0,this.updater=i||L0}var Cp=xp.prototype=new z0;Cp.constructor=xp;B0(Cp,mo.prototype);Cp.isPureReactComponent=!0;var M0=Array.isArray;function wp(){}var rt={H:null,A:null,T:null,S:null},P0=Object.prototype.hasOwnProperty;function kp(e,t,i){var n=i.ref;return{$$typeof:Ep,type:e,key:t,ref:n!==void 0?n:null,props:i}}function AR(e,t){return kp(e.type,t,e.props)}function Tp(e){return typeof e=="object"&&e!==null&&e.$$typeof===Ep}function MR(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(i){return t[i]})}var R0=/\/+/g;function Sp(e,t){return typeof e=="object"&&e!==null&&e.key!=null?MR(""+e.key):t.toString(36)}function RR(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(wp,wp):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function po(e,t,i,n,s){var r=typeof e;(r==="undefined"||r==="boolean")&&(e=null);var a=!1;if(e===null)a=!0;else switch(r){case"bigint":case"string":case"number":a=!0;break;case"object":switch(e.$$typeof){case Ep:case _R:a=!0;break;case D0:return a=e._init,po(a(e._payload),t,i,n,s)}}if(a)return s=s(e),a=n===""?"."+Sp(e,0):n,M0(s)?(i="",a!=null&&(i=a.replace(R0,"$&/")+"/"),po(s,t,i,"",function(c){return c})):s!=null&&(Tp(s)&&(s=AR(s,i+(s.key==null||e&&e.key===s.key?"":(""+s.key).replace(R0,"$&/")+"/")+a)),t.push(s)),1;a=0;var o=n===""?".":n+":";if(M0(e))for(var l=0;l{"use strict";q0.exports=F0()});var $0=me(Ei=>{"use strict";var LR=Nt();function W0(e){var t="https://react.dev/errors/"+e;if(1{"use strict";function G0(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(G0)}catch(e){console.error(e)}}G0(),Y0.exports=$0()});var DE=me(Td=>{"use strict";var qt=N0(),OS=Nt(),PR=oa();function U(e){var t="https://react.dev/errors/"+e;if(1xo||(e.current=fm[xo],fm[xo]=null,xo--)}function lt(e,t){xo++,fm[xo]=e.current,e.current=t}var gs=bs(null),pc=bs(null),Cr=bs(null),Dh=bs(null);function Lh(e,t){switch(lt(Cr,t),lt(pc,e),lt(gs,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?hS(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=hS(t),e=lE(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}mi(gs),lt(gs,e)}function Wo(){mi(gs),mi(pc),mi(Cr)}function pm(e){var t=e.memoizedState;t!==null&&(el._currentValue=t.memoizedState,lt(Dh,e)),t=gs.current;var i=lE(t,e.type);t!==i&&(lt(pc,e),lt(gs,i))}function Bh(e){pc.current===e&&(mi(gs),mi(pc)),Dh.current===e&&(mi(Dh),el._currentValue=ma)}var Np,Q0;function pr(e){if(Np===void 0)try{throw Error()}catch(i){var t=i.stack.trim().match(/\n( *(at )?)/);Np=t&&t[1]||"",Q0=-1{var lO=Object.create;var sh=Object.defineProperty;var cO=Object.getOwnPropertyDescriptor;var uO=Object.getOwnPropertyNames;var hO=Object.getPrototypeOf,dO=Object.prototype.hasOwnProperty;var $0=e=>{throw TypeError(e)};var fO=(e,t,i)=>t in e?sh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var se=(e,t,i)=>()=>{if(i)throw i[0];try{return e&&(t=e(e=0)),t}catch(n){throw i=[n],n}};var ve=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},pO=(e,t)=>{for(var i in t)sh(e,i,{get:t[i],enumerable:!0})},mO=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of uO(t))!dO.call(e,r)&&r!==i&&sh(e,r,{get:()=>t[r],enumerable:!(n=cO(t,r))||n.enumerable});return e};var ae=(e,t,i)=>(i=e!=null?lO(hO(e)):{},mO(t||!e||!e.__esModule?sh(i,"default",{value:e,enumerable:!0}):i,e));var fe=(e,t,i)=>fO(e,typeof t!="symbol"?t+"":t,i),gO=(e,t,i)=>t.has(e)||$0("Cannot "+i);var G0=(e,t,i)=>t.has(e)?$0("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i);var Up=(e,t,i)=>(gO(e,t,"access private method"),i);var j0,Y0,Hp=se(()=>{j0=e=>{let t,i=new Set,n=(c,u)=>{let h=typeof c=="function"?c(t):c;if(!Object.is(h,t)){let d=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),i.forEach(f=>f(t,d))}},r=()=>t,o={setState:n,getState:r,getInitialState:()=>l,subscribe:c=>(i.add(c),()=>i.delete(c))},l=t=e(n,r,o);return o},Y0=(e=>e?j0(e):j0)});var oy=ve(xe=>{"use strict";var Kp=Symbol.for("react.transitional.element"),_O=Symbol.for("react.portal"),vO=Symbol.for("react.fragment"),bO=Symbol.for("react.strict_mode"),yO=Symbol.for("react.profiler"),SO=Symbol.for("react.consumer"),wO=Symbol.for("react.context"),xO=Symbol.for("react.forward_ref"),EO=Symbol.for("react.suspense"),CO=Symbol.for("react.memo"),J0=Symbol.for("react.lazy"),kO=Symbol.for("react.activity"),TO=Symbol.for("react.view_transition"),V0=Symbol.iterator;function NO(e){return e===null||typeof e!="object"?null:(e=V0&&e[V0]||e["@@iterator"],typeof e=="function"?e:null)}var ey={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ty=Object.assign,iy={};function ko(e,t,i){this.props=e,this.context=t,this.refs=iy,this.updater=i||ey}ko.prototype.isReactComponent={};ko.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ko.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ny(){}ny.prototype=ko.prototype;function Wp(e,t,i){this.props=e,this.context=t,this.refs=iy,this.updater=i||ey}var $p=Wp.prototype=new ny;$p.constructor=Wp;ty($p,ko.prototype);$p.isPureReactComponent=!0;var X0=Array.isArray;function qp(){}var ut={H:null,A:null,T:null,S:null},ry=Object.prototype.hasOwnProperty;function Gp(e,t,i){var n=i.ref;return{$$typeof:Kp,type:e,key:t,ref:n!==void 0?n:null,props:i}}function AO(e,t){return Gp(e.type,t,e.props)}function jp(e){return typeof e=="object"&&e!==null&&e.$$typeof===Kp}function MO(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(i){return t[i]})}var Z0=/\/+/g;function Fp(e,t){return typeof e=="object"&&e!==null&&e.key!=null?MO(""+e.key):t.toString(36)}function RO(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(qp,qp):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function Co(e,t,i,n,r){var s=typeof e;(s==="undefined"||s==="boolean")&&(e=null);var a=!1;if(e===null)a=!0;else switch(s){case"bigint":case"string":case"number":a=!0;break;case"object":switch(e.$$typeof){case Kp:case _O:a=!0;break;case J0:return a=e._init,Co(a(e._payload),t,i,n,r)}}if(a)return r=r(e),a=n===""?"."+Fp(e,0):n,X0(r)?(i="",a!=null&&(i=a.replace(Z0,"$&/")+"/"),Co(r,t,i,"",function(c){return c})):r!=null&&(jp(r)&&(r=AO(r,i+(r.key==null||e&&e.key===r.key?"":(""+r.key).replace(Z0,"$&/")+"/")+a)),t.push(r)),1;a=0;var o=n===""?".":n+":";if(X0(e))for(var l=0;l{"use strict";ly.exports=oy()});function IO(e,t=LO){let i=oh.default.useSyncExternalStore(e.subscribe,oh.default.useCallback(()=>t(e.getState()),[e,t]),()=>t(e.getInitialState()));return oh.default.useDebugValue(i),i}var oh,LO,cy,Mn,uy=se(()=>{oh=ae(kt(),1);Hp();LO=e=>e;cy=e=>{let t=Y0(e),i=n=>IO(t,n);return Object.assign(i,t),i},Mn=(e=>e?cy(e):cy)});var Sa=se(()=>{Hp();uy()});function BO(e){let t=e.toLowerCase().replace(/^\[|\]$/g,"");if(t==="localhost"||t.endsWith(".localhost"))return/^[a-z0-9.-]+$/.test(t)&&!t.includes("..");if(t==="0.0.0.0"||t==="::1"||t==="::")return!0;let i=/^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(t);return!!i&&i.slice(1).every(n=>Number(n)<=255)}function zO(e){return e==="localhost"||e.endsWith(".localhost")?["127.0.0.1","::1"]:e==="0.0.0.0"?["127.0.0.1"]:e==="::1"?["::1"]:e==="::"?["::1","127.0.0.1"]:[e]}function PO(e){let t=e.trim();return/^\d{1,5}$/.test(t)?`http://localhost:${t}/`:/^:\d{1,5}(?:[/?#].*)?$/.test(t)?`http://localhost${t}`:/^[a-z][a-z0-9+.-]*:\/\//i.test(t)||/^[a-z][a-z0-9+.-]*:(?!\d)/i.test(t)?t:`http://${t}`}function Wr(e){if(typeof e!="string"||!e.trim())return{ok:!1,reason:"empty"};if(e.length>2048)return{ok:!1,reason:"too_long"};let t;try{t=new URL(PO(e))}catch{return{ok:!1,reason:"bad_url"}}if(t.protocol!=="http:"&&t.protocol!=="https:")return{ok:!1,reason:"scheme"};if(t.username||t.password)return{ok:!1,reason:"userinfo"};let i=t.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(!BO(i))return{ok:!1,reason:"not_local"};let n=t.protocol==="https:",r=t.port?Number(t.port):n?443:80;if(!Number.isInteger(r)||r<1||r>65535)return{ok:!1,reason:"port"};let s=t.href;if(s.length>2048)return{ok:!1,reason:"too_long"};let a=i.includes(":")?`[${i}]`:i;return{ok:!0,target:{href:s,origin:`${t.protocol}//${a}:${r}`,path:`${t.pathname}${t.search}${t.hash}`,secure:n,hostname:i,port:r,connect:zO(i),hostHeader:`${a}:${r}`}}}function hy(e,t,i){return e.startsWith(t)?Yp(i)+e.slice(t.length):e}function Yp(e){return e.replace(/^http:\/\/(.+):80$/,"http://$1").replace(/^https:\/\/(.+):443$/,"https://$1")}function Vp(e){if(typeof e!="string"||!e||e.length>2048)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="http:"&&t.protocol!=="https:"||!t.hostname)return null;let i=t.href;return/[\s"'<>`\\^{|}]/.test(i)||i.length>2048?null:i}var lh=se(()=>{});var Xp,dy=se(()=>{Xp={zh:{app:{title:"Agent \u63A7\u5236\u53F0",subtitle:"\u5148\u5728\u5DE6\u4FA7\u65B0\u5EFA\u6216\u9009\u62E9\u4E00\u4E2A\u9879\u76EE"},common:{cancel:"\u53D6\u6D88",ok:"\u786E\u5B9A",save:"\u4FDD\u5B58",add:"\u6DFB\u52A0",browse:"\u6D4F\u89C8\u2026",more:"\u66F4\u591A",copy:"\u590D\u5236",copied:"\u5DF2\u590D\u5236",copyPath:"\u590D\u5236\u8DEF\u5F84",copiedPath:"\u5DF2\u590D\u5236\u8DEF\u5F84",search:"\u641C\u7D22",settings:"\u8BBE\u7F6E",remove:"\u79FB\u9664",close:"\u5173\u95ED",retry:"\u91CD\u8BD5",details:"\u8BE6\u60C5 \u203A",submit:"\u63D0\u4EA4",other:"\u5176\u4ED6\u2026",default:"\u9ED8\u8BA4",done:"\u5B8C\u6210",loading:"\u52A0\u8F7D\u4E2D\u2026",send:"\u53D1\u9001",stop:"\u505C\u6B62",refresh:"\u5237\u65B0",rename:"\u91CD\u547D\u540D",delete:"\u5220\u9664",discard:"\u653E\u5F03",notInstalled:"\uFF08\u672A\u5B89\u88C5\uFF09",notDetected:"\uFF08\u672A\u68C0\u6D4B\u5230\uFF09",current:"\uFF08\u5F53\u524D\uFF09",messages:"\u6761",imported:" \xB7 \u5DF2\u5BFC\u5165",justNow:"\u521A\u521A",minutesAgo:"{n} \u5206\u949F\u524D",hoursAgo:"{n} \u5C0F\u65F6\u524D",daysAgo:"{n} \u5929\u524D"},boot:{connecting:"\u6B63\u5728\u8FDE\u63A5\u2026",serviceDown:"\u672C\u5730\u670D\u52A1\u672A\u542F\u52A8",retry:"\u91CD\u8BD5",reconnecting:"\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u6B63\u5728\u91CD\u65B0\u8FDE\u63A5\u2026",starting:"\u6B63\u5728\u542F\u52A8\u672C\u5730\u670D\u52A1\u2026",reopening:"\u672C\u5730\u670D\u52A1\u5DF2\u91CD\u542F\uFF0C\u6B63\u5728\u91CD\u65B0\u8FDE\u63A5\u2026"},topbar:{pickThread:"\u9009\u62E9\u4E00\u4E2A\u5BF9\u8BDD",sidebar:"\u4FA7\u680F\uFF08Ctrl+B\uFF09",clickRename:"\u70B9\u51FB\u6539\u540D",waitAuth:"\u7B49\u5F85\u6388\u6743",running:"\u8FD0\u884C\u4E2D {s}s",error:"\u51FA\u9519",closedResume:"\u5DF2\u5173\u95ED \xB7 \u53D1\u9001\u6D88\u606F\u5C06\u7EED\u63A5",threadInfo:"\u5BF9\u8BDD\u4FE1\u606F",panelChanges:"\u6539\u52A8\uFF08Ctrl+J\uFF09",panelFiles:"\u6587\u4EF6",panelTerminal:"\u7EC8\u7AEF"},sidebar:{newProject:"\u65B0\u5EFA\u9879\u76EE",collapse:"\u6536\u8D77\u4FA7\u680F",expand:"\u5C55\u5F00\u4FA7\u680F",filterPlaceholder:"\u8FC7\u6EE4\u5BF9\u8BDD\u6807\u9898",searchTitle:"\u641C\u7D22\uFF08Ctrl+K\uFF09",noProjectsTitle:"\u8FD8\u6CA1\u6709\u9879\u76EE",noProjectsSub:"\u9879\u76EE\u5BF9\u5E94\u4E00\u4E2A\u672C\u673A\u76EE\u5F55\uFF0C\u5BF9\u8BDD\u90FD\u5728\u76EE\u5F55\u91CC\u5E72\u6D3B\u3002",newThread:"\u65B0\u5EFA\u5BF9\u8BDD",projectMenu:"\u9879\u76EE\u83DC\u5355",showAll:"\u663E\u793A\u5168\u90E8 {n} \u6761",noThreads:"\u8FD8\u6CA1\u6709\u5BF9\u8BDD",rename:"\u91CD\u547D\u540D",pin:"\u7F6E\u9876",unpin:"\u53D6\u6D88\u7F6E\u9876",archive:"\u5F52\u6863",unarchive:"\u53D6\u6D88\u5F52\u6863",exportMd:"\u5BFC\u51FA Markdown",deleteThread:"\u5220\u9664\u5BF9\u8BDD",deleteThreadBody:"\u300C{title}\u300D\u5C06\u88AB\u79FB\u5230\u56DE\u6536\u76EE\u5F55\uFF0C\u786E\u5B9A\u5417\uFF1F",importHist:"\u5BFC\u5165\u5DF2\u6709\u5BF9\u8BDD\u2026",openExplorer:"\u5728\u8D44\u6E90\u7BA1\u7406\u5668\u6253\u5F00",showArchived:"\u663E\u793A\u5DF2\u5F52\u6863",hideArchived:"\u9690\u85CF\u5DF2\u5F52\u6863",archivedN:"\u5DF2\u5F52\u6863 {n} \u6761",archivedHint:"\u5DF2\u5F52\u6863\uFF0C\u53EF\u5728\u9879\u76EE\u5217\u8868\u5E95\u90E8\u67E5\u770B",unarchived:"\u5DF2\u53D6\u6D88\u5F52\u6863",exportSaved:"\u5DF2\u5BFC\u51FA\u5230 {path}",removeProject:"\u79FB\u9664\u9879\u76EE",removeProjectBody:"\u300C{name}\u300D\u5C06\u4ECE\u5217\u8868\u79FB\u9664\uFF0C\u5176\u5BF9\u8BDD\u79FB\u5230\u56DE\u6536\u76EE\u5F55\uFF08\u6587\u4EF6\u4E0D\u4F1A\u88AB\u5220\u9664\uFF09\u3002",renameProject:"\u91CD\u547D\u540D\u9879\u76EE",projectName:"\u9879\u76EE\u540D",newProjectDlg:"\u65B0\u5EFA\u9879\u76EE",dirLabel:"\u9879\u76EE\u76EE\u5F55\uFF08\u5FC5\u987B\u662F\u5DF2\u5B58\u5728\u7684\u6587\u4EF6\u5939\uFF09",dirMissing:"\u76EE\u5F55\u4E0D\u5B58\u5728",notDir:"\u8FD9\u662F\u4E00\u4E2A\u6587\u4EF6\uFF0C\u4E0D\u662F\u76EE\u5F55",dirOk:"\u2713 \u76EE\u5F55\u53EF\u7528\uFF0C\u9879\u76EE\u540D\u53D6\u76EE\u5F55\u540D",recent:"\u6700\u8FD1\u4F7F\u7528",pickFolderUnsupported:"\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u5F39\u7A97\u9009\u76EE\u5F55\uFF0C\u8BF7\u624B\u52A8\u8F93\u5165",pickFolderFailed:"\u6253\u5F00\u6587\u4EF6\u5939\u9009\u62E9\u6846\u5931\u8D25",importTitle:"\u5BFC\u5165\u5DF2\u6709\u5BF9\u8BDD \u2014 {name}",scanning:"\u6B63\u5728\u626B\u63CF\u672C\u673A\u5386\u53F2\u4F1A\u8BDD\u2026",importEmpty:"\u6CA1\u6709\u627E\u5230\u5BF9\u5E94\u8FD9\u4E2A\u9879\u76EE\u76EE\u5F55\u7684\u5386\u53F2\u4F1A\u8BDD\u3002",importing:"\u5BFC\u5165\u4E2D\u2026",importN:"\u5BFC\u5165 {n} \u4E2A\u5BF9\u8BDD",importedN:"\u5DF2\u5BFC\u5165 {n} \u4E2A\u5BF9\u8BDD",failNewThread:"\u65B0\u5EFA\u5BF9\u8BDD\u5931\u8D25\uFF1A",failRename:"\u91CD\u547D\u540D\u5931\u8D25\uFF1A",failAddProject:"\u6DFB\u52A0\u9879\u76EE\u5931\u8D25\uFF1A",failImportList:"\u8BFB\u53D6\u5386\u53F2\u5931\u8D25\uFF1A",failImport:"\u5BFC\u5165\u5931\u8D25\uFF1A",failExport:"\u5BFC\u51FA\u5931\u8D25\uFF1A"},chat:{newInProject:"\u5728 {name} \u4E2D\u65B0\u5EFA\u5BF9\u8BDD",emptyHint:"\u5BF9\u8BDD\u8FD8\u6CA1\u6709\u6D88\u606F\uFF0C\u4E0B\u9762\u8F93\u5165\u5F00\u59CB\u3002",jumpBottom:"\u56DE\u5230\u5E95\u90E8",emptyPlaceholder:"\u8F93\u5165\u4EFB\u52A1\uFF0CEnter \u53D1\u9001",autoNewThread:"\u5C06\u81EA\u52A8\u65B0\u5EFA\u5BF9\u8BDD",pickProjectTitle:"\u9009\u62E9\u4E00\u4E2A\u9879\u76EE",pickProjectSub:"\u5728\u5DE6\u4FA7\u9009\u4E00\u4E2A\u9879\u76EE\uFF0C\u6216\u65B0\u5EFA\u4E00\u4E2A\uFF0C\u7136\u540E\u5F00\u59CB\u5BF9\u8BDD\u3002",failSend:"\u53D1\u9001\u5931\u8D25\uFF1A"},composer:{waitPerm:"\u7B49\u5F85\u4F60\u786E\u8BA4\u4E0A\u9762\u7684\u6388\u6743\u8BF7\u6C42",queuePlaceholder:"\u8F93\u5165\u6392\u961F\u6D88\u606F\uFF08Ctrl+Enter \u63D2\u8BDD\uFF09",queuePlaceholderNoSteer:"\u7EE7\u7EED\u8865\u5145\u8981\u6C42\uFF0C\u56DE\u8F66\u6392\u961F\u53D1\u9001\u2026",steerUnsupported:"{agent} \u4E0D\u652F\u6301\u63D2\u8BDD\uFF1A\u8FD0\u884C\u4E2D\u53D1\u7684\u6D88\u606F\u4F1A\u6392\u961F\uFF0C\u672C\u56DE\u5408\u7ED3\u675F\u540E\u518D\u53D1\u9001\u3002",queuedToast:"\u5DF2\u6392\u961F\uFF1A\u672C\u56DE\u5408\u7ED3\u675F\u540E\u53D1\u9001",steeredToast:"\u5DF2\u63D2\u8BDD",inputPlaceholder:"\u8F93\u5165\u6D88\u606F\u2026",bypassWarn:"Bypass\uFF1AAgent \u7684\u6240\u6709\u64CD\u4F5C\u4E0D\u4F1A\u518D\u95EE\u4F60\u3002",imagesByPath:"{agent} \u4E0D\u80FD\u76F4\u63A5\u770B\u56FE\u7247\uFF1A\u4F1A\u628A\u56FE\u7247\u7684\u6587\u4EF6\u8DEF\u5F84\u53D1\u7ED9\u5B83\uFF08\u5B83\u80FD\u7528\u6587\u4EF6\u5DE5\u5177\u6253\u5F00\uFF09\u3002",agentModel:"Agent & model",agentLocked:"Agent (locked)",agent:"Agent",model:"Model",searchModel:"Search",searchAllModels:"Search models\u2026",providers:"Agent",agentLockedHint:"\u5DF2\u5F00\u59CB\u7684\u5BF9\u8BDD\u4E0D\u80FD\u66F4\u6362 Agent\uFF1B\u8981\u7528\u522B\u7684 Agent \u8BF7\u65B0\u5EFA\u5BF9\u8BDD\u3002",providersLoading:"\u6B63\u5728\u68C0\u6D4B Agent\u2026",moreModels:"\u8FD8\u6709 {n} \u4E2A\u6A21\u578B\uFF0C\u8BF7\u7528\u4E0A\u65B9\u641C\u7D22",pickModel:"\u9009\u62E9\u6A21\u578B",noModelMatch:"\u6CA1\u6709\u5339\u914D\u7684\u6A21\u578B",defaultModel:"\u9ED8\u8BA4",defaultEffort:"\u9ED8\u8BA4",defaultEffortNamed:"\u9ED8\u8BA4\uFF08{level}\uFF09",effortTitle:"\u601D\u8003\u5F3A\u5EA6",modeTitle:"\u6743\u9650\u6A21\u5F0F",attachTitle:"\u9644\u4EF6\uFF08\u56FE\u7247/\u6587\u672C\uFF09",failSwitchAgent:"\u5207\u6362 Agent \u5931\u8D25\uFF1A",failSend:"\u53D1\u9001\u5931\u8D25\uFF1A",failUpload:"\u9644\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF1A",uploadFailed:"\u4E0A\u4F20\u5931\u8D25",steerTag:"\u63D2\u8BDD",cursorAutoReview:"\u81EA\u52A8\u63A5\u53D7\u6743\u9650\u63D0\u793A\uFF08Auto-review\uFF09",cursorFastOff:"\u6807\u51C6\u901F\u5EA6",cursorFastOn:"Fast",slashGroupCommand:"\u547D\u4EE4",slashGroupSkill:"Skill",slashNoCommands:"\u8BE5 Agent \u672A\u63D0\u4F9B\u547D\u4EE4",slashLoading:"\u6B63\u5728\u83B7\u53D6\u547D\u4EE4\u2026",mode:{plan:{label:"\u89C4\u5212",desc:"\u53EA\u5206\u6790\u4EE3\u7801\u5E93\uFF0C\u4E0D\u6267\u884C\u5DE5\u5177\u6216\u4FEE\u6539"},default:{label:"\u6BCF\u6B21\u8BE2\u95EE",desc:"\u9996\u6B21\u4F7F\u7528\u5DE5\u5177\u65F6\u4F1A\u8BF7\u6C42\u6388\u6743"},acceptEdits:{label:"\u63A5\u53D7\u7F16\u8F91",desc:"\u81EA\u52A8\u6279\u51C6\u7F16\u8F91\u7C7B\u5DE5\u5177\uFF0C\u4E0D\u518D\u9010\u9879\u8BE2\u95EE"},bypass:{label:"\u5168\u90E8\u653E\u884C",desc:"\u8DF3\u8FC7\u6240\u6709\u6388\u6743\u63D0\u793A\uFF08\u8BF7\u8C28\u614E\u4F7F\u7528\uFF09"},cursorAgent:{label:"Agent",desc:"\u5B8C\u6574 Agent\uFF1A\u53EF\u8BFB\u5199\u3001\u6267\u884C\u5DE5\u5177"},cursorPlan:{label:"\u89C4\u5212",desc:"\u53EA\u8BFB\u89C4\u5212\uFF1A\u5206\u6790\u5E76\u63D0\u51FA\u65B9\u6848\uFF0C\u4E0D\u6539\u6587\u4EF6"},cursorAsk:{label:"\u95EE\u7B54",desc:"\u95EE\u7B54\u6A21\u5F0F\uFF1A\u89E3\u91CA\u4E0E\u8BA8\u8BBA\uFF0C\u53EA\u8BFB"}},agentMode:{Plan:"\u89C4\u5212",Build:"\u6784\u5EFA",Ask:"\u8BE2\u95EE",Code:"\u7F16\u7801",Agent:"Agent","Allow All":"\u5168\u90E8\u5141\u8BB8","Bypass Permissions":"\u8DF3\u8FC7\u6388\u6743","Read Only":"\u53EA\u8BFB",Auto:"\u81EA\u52A8","Full Access":"\u5B8C\u5168\u8BBF\u95EE"},effort:{low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8",xhigh:"\u8D85\u9AD8",max:"\u6700\u9AD8",minimal:"\u6700\u4F4E",none:"\u5173\u95ED"}},settings:{contentWidth:"\u5185\u5BB9\u5BBD\u5EA6",widthNarrow:"\u7A84\uFF08640\uFF09",widthDefault:"\u9ED8\u8BA4\uFF08720\uFF09",widthWide:"\u5BBD\uFF08880\uFF09",widthFull:"\u94FA\u6EE1",chatFont:"\u804A\u5929\u5B57\u53F7",chatFontDefault:"\uFF08\u9ED8\u8BA4\uFF09",chatFontHint:"\u5BF9\u8BDD\u6B63\u6587\u3001\u8F93\u5165\u6846\u3001\u5DE5\u5177\u8F93\u51FA\u548C\u4EE3\u7801\u4E00\u8D77\u7F29\u653E\uFF08\u4EE3\u7801\u5C0F 1px\uFF09",title:"\u8BBE\u7F6E",defaultAgent:"\u9ED8\u8BA4 Agent",defaultMode:"\u9ED8\u8BA4\u6743\u9650\u6A21\u5F0F",theme:"\u4E3B\u9898",themeAuto:"\u8DDF\u968F\u7CFB\u7EDF",themeMagpie:"\u8DDF\u968F Magpie",themeLight:"\u6D45\u8272",themeDark:"\u6DF1\u8272",sendKey:"\u53D1\u9001\u952E",sendEnter:"Enter \u53D1\u9001 / Shift+Enter \u6362\u884C",sendCtrl:"Ctrl+Enter \u53D1\u9001 / Enter \u6362\u884C",runningSend:"\u8FD0\u884C\u4E2D\u518D\u53D1\u9001",queue:"\u6392\u961F\uFF08\u53D1\u5B8C\u81EA\u52A8\u7EE7\u7EED\uFF09",steer:"\u63D2\u8BDD\uFF08\u7ACB\u5373\u6253\u65AD\u5F53\u524D\u601D\u8DEF\uFF09",steerHint:"\u63D2\u8BDD\u53EA\u5BF9\u652F\u6301\u7684 Agent \u751F\u6548\uFF08\u76EE\u524D\u662F Codex\uFF09\uFF1B\u5176\u4ED6 Agent \u4ECD\u4F1A\u6392\u961F\uFF0C\u8F93\u5165\u6846\u4E0B\u65B9\u4F1A\u63D0\u793A\u3002",defaultModeHint:"\u65B0\u5BF9\u8BDD\u4F7F\u7528\uFF1B\u6BCF\u4E2A Agent \u4F1A\u6362\u6210\u81EA\u5DF1\u6700\u63A5\u8FD1\u7684\u6A21\u5F0F\uFF08\u4F8B\u5982 OpenCode \u53EA\u6709 Plan / Build\uFF0CBuild \u4F1A\u76F4\u63A5\u6539\u6587\u4EF6\uFF09\u3002",thinking:"\u601D\u8003\u8FC7\u7A0B",showThinking:"\u663E\u793A Agent \u7684\u601D\u8003/\u63A8\u7406\u5185\u5BB9",idleClose:"\u7A7A\u95F2\u56DE\u6536",idleMinutes:"\u5206\u949F\u540E\u81EA\u52A8\u5173\u95ED\u7A7A\u95F2\u4F1A\u8BDD\uFF085\u2013240\uFF1B\u6700\u591A\u4FDD\u7559 3 \u4E2A\u7A7A\u95F2 Agent \u8FDB\u7A0B\uFF09",idleInvalid:"\u8BF7\u8F93\u5165 5 \u5230 240 \u4E4B\u95F4\u7684\u6574\u6570",versionLine:"\u7248\u672C v{ver} \xB7 PID {pid}",dataDir:"\u6570\u636E\u76EE\u5F55\uFF1A",failSave:"\u4FDD\u5B58\u5931\u8D25\uFF1A",providers:"Agent",providerOn:"\u53EF\u7528",providerOff:"\u5DF2\u7981\u7528",providerPending:"\u5C1A\u672A\u63A5\u5165",providerVerified:"\u5DF2\u9A8C\u8BC1",providerExperimental:"\u5B9E\u9A8C\u6027",providerPlanned:"\u672A\u63A5\u5165",providerModels:"{n} \u4E2A Model",providerRedetect:"\u91CD\u65B0\u68C0\u6D4B",providerCopyHint:"\u590D\u5236\u5B89\u88C5\u63D0\u793A",providerLaunchCmd:"\u81EA\u5B9A\u4E49\u542F\u52A8\uFF08\u9AD8\u7EA7\uFF09",providerLaunchExe:"\u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84\uFF08\u7559\u7A7A = \u81EA\u52A8\u67E5\u627E\uFF09",providerLaunchArgs:"\u9644\u52A0\u53C2\u6570\uFF08JSON \u6570\u7EC4\uFF09",providerLaunchArgsHint:'\u8FFD\u52A0\u5728\u5185\u7F6E\u53C2\u6570\u4E4B\u540E\uFF0C\u4F8B\u5982 ["--foo"]\uFF1B\u56DE\u8F66\u6216\u79BB\u5F00\u8F93\u5165\u6846\u65F6\u4FDD\u5B58\u3002\u65B0\u5BF9\u8BDD\u751F\u6548\u3002',providerArgsInvalid:'\u9700\u8981 JSON \u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u4F8B\u5982 ["--foo"]',providerToggleFailed:"\u5207\u6362\u5931\u8D25\uFF0C\u5DF2\u6062\u590D\uFF1A"},palette:{aria:"\u547D\u4EE4\u9762\u677F",placeholder:"\u641C\u7D22\u5BF9\u8BDD\u3001\u9879\u76EE\u6216\u52A8\u4F5C\u2026",noMatch:"\u6CA1\u6709\u5339\u914D\u9879",hintAction:"\u52A8\u4F5C",hintThread:"\u5BF9\u8BDD",hintProject:"\u9879\u76EE",actNewThread:"\u65B0\u5EFA\u5BF9\u8BDD",actSettings:"\u6253\u5F00\u8BBE\u7F6E",actTheme:"\u5207\u6362\u4E3B\u9898",actChanges:"\u6253\u5F00\u6539\u52A8\u9762\u677F",actFiles:"\u6253\u5F00\u6587\u4EF6\u9762\u677F",actTerminal:"\u6253\u5F00\u7EC8\u7AEF\u9762\u677F",actImport:"\u5BFC\u5165\u5DF2\u6709\u5BF9\u8BDD\u2026",failNew:"\u65B0\u5EFA\u5931\u8D25\uFF1A"},panel:{changes:"\u6539\u52A8",files:"\u6587\u4EF6",terminal:"\u7EC8\u7AEF",closeTitle:"\u5173\u95ED\uFF08Ctrl+J\uFF09",pickProject:"\u5148\u9009\u4E00\u4E2A\u9879\u76EE",notGit:"\u8FD9\u4E2A\u9879\u76EE\u4E0D\u662F git \u4ED3\u5E93",clean:"\u5DE5\u4F5C\u533A\u5E72\u51C0",branch:"\u5F53\u524D\u5206\u652F",loadingDiff:"\u52A0\u8F7D diff\u2026",diffTooLarge:"diff \u8D85\u8FC7 1MB\uFF0C\u4E0D\u663E\u793A",discardTitle:"\u653E\u5F03\u6539\u52A8",discardUntracked:`\u653E\u5F03 {path} \u7684\u6539\u52A8\uFF1F +\u672A\u8DDF\u8E2A\u6587\u4EF6\u4F1A\u88AB\u79FB\u5230\u56DE\u6536\u76EE\u5F55\uFF08trash/discarded\uFF09\uFF0C\u4E0D\u4F1A\u76F4\u63A5\u5220\u9664\u3002`,discardTracked:"\u653E\u5F03 {path} \u7684\u6539\u52A8\uFF1F\u8BE5\u6587\u4EF6\u4F1A\u6062\u590D\u5230 git \u91CC\u7684\u7248\u672C\u3002",discardBtn:"\u653E\u5F03\u6539\u52A8",failDiscard:"\u653E\u5F03\u5931\u8D25\uFF1A",closePreview:"\u5173\u95ED\u9884\u89C8",reading:"\u8BFB\u53D6\u4E2D\u2026",binary:"\u4E8C\u8FDB\u5236\u6587\u4EF6\uFF0C\u4E0D\u9884\u89C8",tooLarge:"\u8D85\u8FC7 1MB\uFF0C\u4E0D\u9884\u89C8",gitKind:{modified:"\u6539",added:"\u589E",deleted:"\u5220",untracked:"\u65B0",renamed:"\u79FB"}},terminal:{new:"\u65B0\u5EFA\u7EC8\u7AEF",noTerm:"\u8FD8\u6CA1\u6709\u7EC8\u7AEF",closeTitle:"\u5173\u95ED\u7EC8\u7AEF",closeBody:"\u5173\u95ED\u300C{title}\u300D\uFF1F\u91CC\u9762\u8FD0\u884C\u7684\u8FDB\u7A0B\u4F1A\u88AB\u7ED3\u675F\u3002",closeOk:"\u5173\u95ED",simpleNote:"\u7B80\u5316\u7EC8\u7AEF\uFF08\u65E0\u4EA4\u4E92\u7A0B\u5E8F\u652F\u6301\uFF09",ended:"\uFF08\u7EC8\u7AEF\u5DF2\u7ED3\u675F\uFF09",failNew:"\u65B0\u5EFA\u7EC8\u7AEF\u5931\u8D25\uFF1A",failKill:"\u5173\u95ED\u5931\u8D25\uFF1A"},thread:{new:"\u65B0\u5BF9\u8BDD",info:"\u5BF9\u8BDD\u4FE1\u606F",agent:"Agent",model:"\u6A21\u578B",mode:"\u6A21\u5F0F",effort:"\u601D\u8003\u5F3A\u5EA6",sessionId:"\u4F1A\u8BDD ID",tokens:"\u7D2F\u8BA1 token",cost:"\u7D2F\u8BA1\u8D39\u7528",created:"\u521B\u5EFA\u4E8E",workdir:"\u5DE5\u4F5C\u76EE\u5F55",importedFrom:"\u5BFC\u5165\u81EA",sessionNone:"\uFF08\u672A\u5EFA\u7ACB\uFF09",tokensFmt:"{in} \u5165 / {out} \u51FA / {cache} \u7F13\u5B58"},timeline:{thinking:"\u601D\u8003 {s}s",todo:"\u5F85\u529E {done}/{total}",steer:"\u63D2\u8BDD",permAllowSession:"\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8",permDenied:"\u5DF2\u62D2\u7EDD",permAllowed:"\u5DF2\u5141\u8BB8",permCancelled:"\u5DF2\u53D6\u6D88",submitted:"\u5DF2\u63D0\u4EA4\uFF1A{ans}",turnError:"\u51FA\u9519\uFF1A{err}",unknownError:"\u672A\u77E5\u9519\u8BEF",interrupted:"\u5DF2\u6253\u65AD",filesChanged:"\u6539\u52A8 {n} \u4E2A\u6587\u4EF6 \u203A",editResend:"\u7F16\u8F91\u540E\u91CD\u53D1",tool:{read:"\u8BFB\u53D6",edit:"\u4FEE\u6539",write:"\u5199\u5165",bash:"\u8FD0\u884C",search:"\u641C\u7D22",glob:"\u641C\u7D22",web:"\u8054\u7F51",task:"\u5B50\u4EFB\u52A1",mcp:"\u5DE5\u5177",todo:"\u5F85\u529E",other:"\u5DE5\u5177",processing:"\u5904\u7406"},toolSummary:"\u5DF2\u6267\u884C {n} \u6B65 \xB7 {parts}",toolSummaryOne:"\u5DF2\u6267\u884C 1 \u6B65 \xB7 {parts}",toolRunning:"\u6B63\u5728{kind}\uFF1A{title}",showAllLines:"\u663E\u793A\u5168\u90E8 {n} \u884C",diffClip:"\uFF08\u53EA\u663E\u793A\u524D {n} \u884C\uFF09"},api:{requestFailed:"\u8BF7\u6C42\u5931\u8D25",bad_params:"\u53C2\u6570\u4E0D\u6B63\u786E",not_found:"\u672A\u627E\u5230",busy:"\u6B63\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",bad_path:"\u8DEF\u5F84\u65E0\u6548",connClosed:"\u8FDE\u63A5\u4E2D\u65AD",notConnected:"\u8FDE\u63A5\u672A\u5EFA\u7ACB",timeout:"\u8BF7\u6C42\u8D85\u65F6"},preview:{tab:"\u9884\u89C8",address:"\u9884\u89C8\u5730\u5740",placeholder:"localhost:5173",back:"\u540E\u9000",forward:"\u524D\u8FDB",reload:"\u5237\u65B0",openExternal:"\u7528\u7CFB\u7EDF\u6D4F\u89C8\u5668\u6253\u5F00",widen:"\u52A0\u5BBD\u9762\u677F",onlyLocal:"\u9884\u89C8\u53EA\u652F\u6301\u672C\u673A\u5730\u5740\uFF08localhost\u3001127.0.0.1 \u7B49\uFF09",failed:"\u6253\u4E0D\u5F00\u9884\u89C8\uFF1A",empty:"\u8FD8\u6CA1\u6709\u9884\u89C8\u5730\u5740\u3002\u5728\u5BF9\u8BDD\u91CC\u70B9 localhost \u94FE\u63A5\uFF0C\u6216\u5728\u4E0A\u65B9\u8F93\u5165\uFF0C\u4F8B\u5982 localhost:5173",limits:"\u9884\u89C8\u5728\u6C99\u7BB1\u91CC\u8FD0\u884C\uFF1A\u5F39\u7A97\u3001alert \u548C\u539F\u751F\u8868\u5355\u63D0\u4EA4\u4E0D\u53EF\u7528\uFF1BlocalStorage \u548C\u767B\u5F55 cookie \u5237\u65B0\u540E\u4F1A\u4E22\u5931\uFF0C\u9700\u8981\u65F6\u8BF7\u7528\u7CFB\u7EDF\u6D4F\u89C8\u5668\u6253\u5F00\u3002",noLocalhost:"\u8FD9\u53F0\u7535\u8111\u7684\u7F51\u9875\u5185\u6838\u6253\u4E0D\u5F00 *.localhost \u5730\u5740\uFF08macOS 26 \u4EE5\u524D\u7684\u7CFB\u7EDF\u4F1A\u8FD9\u6837\uFF09\u3002\u9884\u89C8\u9760\u8FD9\u4E2A\u5730\u5740\u6321\u4F4F\u522B\u7684\u7F51\u9875\u8BFB\u53D6\u4F60\u7684 dev server\uFF0C\u6240\u4EE5\u8FD9\u91CC\u4E0D\u80FD\u9884\u89C8\uFF0C\u8BF7\u7528\u7CFB\u7EDF\u6D4F\u89C8\u5668\u6253\u5F00\u3002"},links:{openPreviewTitle:"\u5728\u9884\u89C8\u4E2D\u6253\u5F00\uFF08Ctrl/\u2318+\u70B9\u51FB\u7528\u6D4F\u89C8\u5668\u6253\u5F00\uFF09",externalFailed:"\u6253\u4E0D\u5F00\u7CFB\u7EDF\u6D4F\u89C8\u5668\uFF0C\u5DF2\u590D\u5236\u94FE\u63A5"},mention:{drop:"\u677E\u5F00\u4EE5\u63D2\u5165\u5230\u804A\u5929",add:"\u63D2\u5165\u5230\u804A\u5929",copyRel:"\u590D\u5236\u76F8\u5BF9\u8DEF\u5F84",remove:"\u79FB\u9664",otherProject:"\u53EA\u80FD\u63D2\u5165\u5F53\u524D\u5BF9\u8BDD\u6240\u5728\u9879\u76EE\u91CC\u7684\u6587\u4EF6"}},en:{app:{title:"Agent Console",subtitle:"Create or select a project in the sidebar"},common:{cancel:"Cancel",ok:"OK",save:"Save",add:"Add",browse:"Browse\u2026",more:"More",copy:"Copy",copied:"Copied",copyPath:"Copy path",copiedPath:"Path copied",search:"Search",settings:"Settings",remove:"Remove",close:"Close",retry:"Retry",details:"Details \u203A",submit:"Submit",other:"Other\u2026",default:"Default",done:"Done",loading:"Loading\u2026",send:"Send",stop:"Stop",refresh:"Refresh",rename:"Rename",delete:"Delete",discard:"Discard",notInstalled:" (not installed)",notDetected:" (not detected)",current:" (current)",messages:" msgs",imported:" \xB7 imported",justNow:"Just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago"},boot:{connecting:"Connecting\u2026",serviceDown:"Local service is not running",retry:"Retry",reconnecting:"Connection lost. Reconnecting\u2026",starting:"Starting local service\u2026",reopening:"The local service restarted. Reconnecting\u2026"},topbar:{pickThread:"Select a conversation",sidebar:"Sidebar (Ctrl+B)",clickRename:"Click to rename",waitAuth:"Waiting for approval",running:"Running {s}s",error:"Error",closedResume:"Closed \xB7 send a message to resume",threadInfo:"Conversation info",panelChanges:"Changes (Ctrl+J)",panelFiles:"Files",panelTerminal:"Terminal"},sidebar:{newProject:"New project",collapse:"Collapse sidebar",expand:"Expand sidebar",filterPlaceholder:"Filter conversations",searchTitle:"Search (Ctrl+K)",noProjectsTitle:"No projects yet",noProjectsSub:"A project maps to a folder on this machine.",newThread:"New conversation",projectMenu:"Project menu",showAll:"Show all {n}",noThreads:"No conversations yet",rename:"Rename",pin:"Pin",unpin:"Unpin",archive:"Archive",unarchive:"Unarchive",exportMd:"Export Markdown",deleteThread:"Delete conversation",deleteThreadBody:"Move \u201C{title}\u201D to trash?",importHist:"Import existing conversations\u2026",openExplorer:"Open in Explorer",showArchived:"Show archived",hideArchived:"Hide archived",archivedN:"{n} archived",archivedHint:"Archived \u2014 see the bottom of the project list",unarchived:"Unarchived",exportSaved:"Exported to {path}",removeProject:"Remove project",removeProjectBody:"Remove \u201C{name}\u201D from the list? Conversations move to trash (files stay on disk).",renameProject:"Rename project",projectName:"Project name",newProjectDlg:"New project",dirLabel:"Project folder (must already exist)",dirMissing:"Folder does not exist",notDir:"This path is a file, not a folder",dirOk:"\u2713 Folder OK \u2014 name comes from the folder",recent:"Recent",pickFolderUnsupported:"Folder picker is not available \u2014 type the path",pickFolderFailed:"Could not open folder picker",importTitle:"Import conversations \u2014 {name}",scanning:"Scanning local history\u2026",importEmpty:"No history found for this project folder.",importing:"Importing\u2026",importN:"Import {n} conversation(s)",importedN:"Imported {n} conversation(s)",failNewThread:"Could not create conversation: ",failRename:"Rename failed: ",failAddProject:"Could not add project: ",failImportList:"Could not read history: ",failImport:"Import failed: ",failExport:"Export failed: "},chat:{newInProject:"New conversation in {name}",emptyHint:"No messages yet \u2014 type below to start.",jumpBottom:"Jump to bottom",emptyPlaceholder:"Describe a task \u2014 Enter to send",autoNewThread:"A new conversation will be created",failSend:"Send failed: ",pickProjectTitle:"Pick a project",pickProjectSub:"Choose a project in the sidebar, or create one, to start a conversation."},composer:{waitPerm:"Waiting for your approval above",queuePlaceholder:"Queue a message (Ctrl+Enter to steer)",queuePlaceholderNoSteer:"Add to the task \u2014 Enter queues it\u2026",steerUnsupported:"{agent} can't steer: messages sent while it runs are queued and sent after this turn.",queuedToast:"Queued \u2014 sends after this turn",steeredToast:"Steered",inputPlaceholder:"Message\u2026",bypassWarn:"Bypass: the agent will not ask for permission.",imagesByPath:"{agent} can't see images directly: it gets the image's file path instead (it can open it with its file tools).",agentModel:"Agent & model",agentLocked:"Agent (locked after first message)",agent:"Agent",model:"Model",searchModel:"Search",searchAllModels:"Search all models\u2026",providers:"Providers",agentLockedHint:"The agent can't change after the conversation starts. Start a new conversation to use another agent.",providersLoading:"Detecting agents\u2026",moreModels:"{n} more models \u2014 use search above",pickModel:"Choose model",noModelMatch:"No matching models",defaultModel:"Default",defaultEffort:"Default",defaultEffortNamed:"Default ({level})",effortTitle:"Reasoning effort",modeTitle:"Permission mode",attachTitle:"Attachments (images / text)",failSwitchAgent:"Could not switch agent: ",failSend:"Send failed: ",failUpload:"Upload failed: ",uploadFailed:"Upload failed",steerTag:"Steer",cursorAutoReview:"Auto accept permission prompts",cursorFastOff:"Off",cursorFastOn:"Fast",slashGroupCommand:"Commands",slashGroupSkill:"Skills",slashNoCommands:"This agent has no slash commands",slashLoading:"Loading commands\u2026",mode:{plan:{label:"Plan Mode",desc:"Analyze the codebase without running tools or edits"},default:{label:"Always Ask",desc:"Ask permission the first time a tool is used"},acceptEdits:{label:"Accept File Edits",desc:"Auto-approve edit tools without prompting"},bypass:{label:"Bypass",desc:"Skip all permission prompts (use with caution)"},cursorAgent:{label:"Agent",desc:"Full agent: tools and edits"},cursorPlan:{label:"Plan",desc:"Read-only planning and analysis"},cursorAsk:{label:"Ask",desc:"Q&A style explanations (read-only)"}},agentMode:{},effort:{low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max",minimal:"Minimal",none:"Off"}},settings:{contentWidth:"Content width",widthNarrow:"Narrow (640)",widthDefault:"Default (720)",widthWide:"Wide (880)",widthFull:"Full",chatFont:"Chat font size",chatFontDefault:" (default)",chatFontHint:"Scales the conversation, the input, tool output and code (code 1px smaller)",title:"Settings",defaultAgent:"Default agent",defaultMode:"Default permission mode",theme:"Theme",themeAuto:"System",themeMagpie:"Follow Magpie",themeLight:"Light",themeDark:"Dark",sendKey:"Send shortcut",sendEnter:"Enter sends / Shift+Enter newline",sendCtrl:"Ctrl+Enter sends / Enter newline",runningSend:"While running",queue:"Queue (run after current turn)",steer:"Steer (interrupt now)",steerHint:"Steer only works for agents that support it (Codex today); other agents still queue, and the composer says so.",defaultModeHint:"For new conversations. Each agent maps it to its own nearest mode (OpenCode only has Plan / Build, and Build edits without asking).",thinking:"Reasoning",showThinking:"Show agent reasoning/thinking",idleClose:"Idle cleanup",idleMinutes:"minutes before closing idle sessions (5\u2013240; at most 3 idle agent processes are kept)",idleInvalid:"Enter a whole number from 5 to 240",versionLine:"Version v{ver} \xB7 PID {pid}",dataDir:"Data: ",failSave:"Could not save: ",providers:"Providers",providerOn:"Available",providerOff:"Disabled",providerPending:"Not wired yet",providerVerified:"Verified",providerExperimental:"Experimental",providerPlanned:"Planned",providerModels:"{n} models",providerRedetect:"Re-detect",providerCopyHint:"Copy install hint",providerLaunchCmd:"Custom launch (advanced)",providerLaunchExe:"Executable path (empty = find it automatically)",providerLaunchArgs:"Extra args (JSON array)",providerLaunchArgsHint:'Added after the built-in arguments, e.g. ["--foo"]. Saved on Enter or when you leave the field. Applies to new sessions.',providerArgsInvalid:'Needs a JSON array of strings, e.g. ["--foo"]',providerToggleFailed:"Could not switch it; reverted: "},palette:{aria:"Command palette",placeholder:"Search conversations, projects, actions\u2026",noMatch:"No matches",hintAction:"Action",hintThread:"Conversation",hintProject:"Project",actNewThread:"New conversation",actSettings:"Open settings",actTheme:"Toggle theme",actChanges:"Open changes panel",actFiles:"Open files panel",actTerminal:"Open terminal panel",actImport:"Import existing conversations\u2026",failNew:"Could not create: "},panel:{changes:"Changes",files:"Files",terminal:"Terminal",closeTitle:"Close (Ctrl+J)",pickProject:"Select a project first",notGit:"This folder is not a git repository",clean:"Working tree clean",branch:"Current branch",loadingDiff:"Loading diff\u2026",diffTooLarge:"Diff is over 1MB \u2014 not shown",discardTitle:"Discard changes",discardUntracked:`Discard changes to {path}? +Untracked files move to trash/discarded.`,discardTracked:"Discard changes to {path}? The file reverts to the git version.",discardBtn:"Discard",failDiscard:"Discard failed: ",closePreview:"Close preview",reading:"Reading\u2026",binary:"Binary file \u2014 no preview",tooLarge:"Over 1MB \u2014 no preview",gitKind:{modified:"M",added:"A",deleted:"D",untracked:"?",renamed:"R"}},terminal:{new:"New terminal",noTerm:"No terminals yet",closeTitle:"Close terminal",closeBody:"Close \u201C{title}\u201D? Running processes will be killed.",closeOk:"Close",simpleNote:"Simple terminal (no full TTY programs)",ended:"(Terminal ended)",failNew:"Could not create terminal: ",failKill:"Could not close: "},thread:{new:"New chat",info:"Conversation info",agent:"Agent",model:"Model",mode:"Mode",effort:"Effort",sessionId:"Session ID",tokens:"Total tokens",cost:"Total cost",created:"Created",workdir:"Working directory",importedFrom:"Imported from",sessionNone:"(none)",tokensFmt:"{in} in / {out} out / {cache} cache"},timeline:{thinking:"Thinking {s}s",todo:"Todos {done}/{total}",steer:"Steer",permAllowSession:"Allowed for this chat",permDenied:"Denied",permAllowed:"Allowed",permCancelled:"Cancelled",submitted:"Submitted: {ans}",turnError:"Error: {err}",unknownError:"Unknown error",interrupted:"Interrupted",filesChanged:"{n} file(s) changed \u203A",editResend:"Edit and resend",tool:{read:"Read",edit:"Edit",write:"Write",bash:"Run",search:"Search",glob:"Search",web:"Web",task:"Subtask",mcp:"Tool",todo:"Todo",other:"Tool",processing:"Working"},toolSummary:"{n} steps \xB7 {parts}",toolSummaryOne:"1 step \xB7 {parts}",toolRunning:"{kind}: {title}",showAllLines:"Show all {n} lines",diffClip:"(first {n} lines only)"},api:{requestFailed:"Request failed",bad_params:"Invalid parameters",not_found:"Not found",busy:"Busy \u2014 try again later",bad_path:"Invalid path",connClosed:"Connection lost",notConnected:"Not connected",timeout:"Request timed out"},preview:{tab:"Preview",address:"Preview address",placeholder:"localhost:5173",back:"Back",forward:"Forward",reload:"Reload",openExternal:"Open in browser",widen:"Widen panel",onlyLocal:"Preview only supports local addresses (localhost, 127.0.0.1, \u2026)",failed:"Can't open the preview: ",empty:"Nothing to preview yet. Click a localhost link in the chat, or type an address above, e.g. localhost:5173",limits:"The preview runs sandboxed: popups, alert and native form posts don't work; localStorage and login cookies are lost on reload. Open it in your browser when you need them.",noLocalhost:"This system's web view can't open *.localhost addresses (macOS before 26 can't). The preview needs one to keep other web pages out of your dev server, so it can't run here: open it in your browser instead."},links:{openPreviewTitle:"Open in Preview (Ctrl/\u2318+click opens the browser)",externalFailed:"Couldn't open the browser; the link was copied"},mention:{drop:"Drop to add to the chat",add:"Add to chat",copyRel:"Copy relative path",remove:"Remove",otherProject:"Only files of this conversation's project can be added"}}}});function Zp(e){let t=String(e??"").trim().toLowerCase();return t?t==="zh"||t.startsWith("zh-")?"zh":"en":UO()}function UO(){let e=typeof navigator<"u"?navigator.language:"";return Zp(e||"zh")}function py(e){let t=new URLSearchParams(e).get("lang");pr=Zp(t);let i=pr==="zh"?"zh-CN":"en";return typeof document<"u"&&(document.documentElement.lang=i),pr}function my(e){let t=Zp(e);return t===pr?!1:(pr=t,typeof document<"u"&&(document.documentElement.lang=pr==="zh"?"zh-CN":"en"),!0)}function wa(){return pr}function ch(){return pr==="zh"?"zh-CN":"en-US"}function fy(e,t){let i=t.split("."),n=e;for(let r of i){if(typeof n!="object"||n==null||!(r in n))return;n=n[r]}return typeof n=="string"?n:void 0}function v(e){return fy(Xp[pr],e)??fy(Xp.en,e)??e}function Me(e,t){let i=v(e);for(let[n,r]of Object.entries(t))i=i.replaceAll(`{${n}}`,String(r));return i}function ht(e){let t=e,i=t?.code;if(i){let r=v(`api.${i}`);if(r!==`api.${i}`)return r}let n=String(t?.message??e);return $r(n)}function $r(e){if(pr==="zh")return e;if(e==="\u540E\u53F0\u5DF2\u91CD\u542F\uFF0C\u672C\u8F6E\u5DF2\u4E2D\u65AD")return"Daemon restarted \u2014 this turn was interrupted";if(e.startsWith("\u4F1A\u8BDD\u542F\u52A8\u5931\u8D25\uFF1A"))return"Session start failed: "+e.slice(7);if(e.startsWith("\u53D1\u9001\u5931\u8D25\uFF1A"))return"Send failed: "+e.slice(5);if(e==="Agent \u8FDB\u7A0B\u610F\u5916\u9000\u51FA")return"Agent process exited unexpectedly";let t=e.match(/^附件不存在或已失效((.+)),请重新上传$/);if(t)return`Attachment missing or expired (${t[1]}) \u2014 upload again`;let i=e.match(/^(.+) 不能直接看图片(它的 ACP 初始化未声明支持图片输入),已改为发送图片的文件路径:(.+)$/s);return i?`${i[1]} can't see images directly (its ACP initialize doesn't advertise image input); sent the image file path instead: ${i[2]}`:e.startsWith("\u9644\u4EF6\u95EE\u9898\uFF1A")?"Attachment issue: "+e.slice(5):e}function uh(e,t){return t&&(e==="\u65B0\u5BF9\u8BDD"||e==="New chat")?v("thread.new"):e}var pr,Pt=se(()=>{dy();pr="zh"});function qO(e=typeof navigator<"u"?navigator.userAgent:""){return/AppleWebKit\//i.test(e)&&/Macintosh|iPhone|iPad|iPod/i.test(e)&&!/Chrome\//i.test(e)&&!/Chromium\//i.test(e)&&!/Edg(?:e|A|iOS)?\//i.test(e)&&!/OPR\//i.test(e)&&!/CriOS\//i.test(e)&&!/FxiOS\//i.test(e)}function KO(e,t=typeof navigator<"u"?navigator.userAgent:""){if(!qO(t))return!1;if(!e||typeof e.platform!="string"||!e.platform)return!0;if(e.platform!=="darwin")return!1;let i=e.darwinMajor;return typeof i!="number"||!Number.isInteger(i)?!0:in.abort(),i);try{let s=await fetch(e+HO,{cache:"no-store",credentials:"omit",referrerPolicy:"no-referrer",signal:n.signal});return s.ok?await s.text()===t:!1}catch{return!1}finally{clearTimeout(r)}}async function WO(e,t=5e3){return await _y(e.canaryOrigin,e.canaryNonce,t)?_y(e.proxyOrigin,e.nonce,t):!1}function hh(e){let t=Wr(e);return t.ok?Yp(t.target.origin)+t.target.path:e}var gy,Jl,Qp,HO,FO,vi,dh=se(()=>{Sa();lh();Pt();gy=()=>v("preview.noLocalhost"),Jl=e=>e??"_",Qp=new Map,HO="/__agent_console__/ping",FO=25;vi=Mn((e,t)=>({byThread:{},navigate:async(i,n,r,s,a)=>{let o=Wr(s);if(!o.ok)return!1;let l=o.target,c=t().byThread[n],u=c&&c.origin===l.origin&&c.proxyOrigin,h=c?.stack??[],d=c?.idx??-1;if(a?.push!==!1?h[d]!==l.href&&(h=[...h.slice(0,d+1),l.href].slice(-50),d=h.length-1):h.length||(h=[l.href],d=0),u)return e(_=>({byThread:{..._.byThread,[n]:{...c,url:l.href,proxyHref:c.proxyOrigin+l.path,error:null,nonce:c.nonce+1,stack:h,idx:d}}})),r&&i("threads.update",{id:r,previewUrl:l.href}).catch(()=>{}),!0;e(_=>({byThread:{..._.byThread,[n]:{url:l.href,origin:l.origin,proxyOrigin:null,proxyHref:null,title:c?.origin===l.origin?c.title:"",loading:!0,error:null,nonce:(c?.nonce??0)+1,bridged:!1,stack:h,idx:d}}}));let f=`${n} +${l.href}`,p=Qp.get(f);return p||(p=(async()=>{try{let _=await i("preview.open",{url:l.href,...r?{threadId:r}:{}});if(KO(_?.host))throw i("preview.release",{url:l.origin}).catch(()=>{}),new Error(gy());if(!await WO(_))throw i("preview.release",{url:l.origin}).catch(()=>{}),new Error(gy());return e(S=>{let m=S.byThread[n];return!m||m.url!==l.href?S:{byThread:{...S.byThread,[n]:{...m,proxyOrigin:_.proxyOrigin,proxyHref:_.proxyHref,loading:!1,error:null}}}}),!0}catch(_){let S=String(_?.message??_);return e(m=>{let g=m.byThread[n];return!g||g.url!==l.href?m:{byThread:{...m.byThread,[n]:{...g,loading:!1,error:S}}}}),!1}finally{Qp.delete(f)}})(),Qp.set(f,p)),p},reported:(i,n,r)=>{e(s=>{let a=s.byThread[i];if(!a)return s;let{stack:o,idx:l}=a;return o[l]!==n&&(o[l-1]===n?l-=1:o[l+1]===n?l+=1:(o=[...o.slice(0,l+1),n].slice(-50),l=o.length-1)),{byThread:{...s.byThread,[i]:{...a,url:n,title:r,bridged:!0,stack:o,idx:l}}}})},detach:i=>{e(n=>{let r=n.byThread[i];return r?{byThread:{...n.byThread,[i]:{...r,proxyOrigin:null,proxyHref:null,bridged:!1}}}:n})},reload:i=>{e(n=>{let r=n.byThread[i];return r?{byThread:{...n.byThread,[i]:{...r,nonce:r.nonce+1,error:null}}}:n})},step:(i,n)=>{let r=t().byThread[i];if(!r)return null;let s=r.idx+n;return s<0||s>=r.stack.length?null:(e(a=>({byThread:{...a.byThread,[i]:{...r,idx:s}}})),r.stack[s])}}))});var vy=se(()=>{});var by=se(()=>{});var yy=se(()=>{});var Sy=se(()=>{});var wy=se(()=>{});var Oy=ve(yt=>{"use strict";function im(e,t){var i=e.length;e.push(t);e:for(;0>>1,r=e[n];if(0>>1;nfh(o,i))lfh(c,o)?(e[n]=c,e[l]=i,n=l):(e[n]=o,e[a]=i,n=a);else if(lfh(c,i))e[n]=c,e[l]=i,n=l;else break e}}return t}function fh(e,t){var i=e.sortIndex-t.sortIndex;return i!==0?i:e.id-t.id}yt.unstable_now=void 0;typeof performance=="object"&&typeof performance.now=="function"?(xy=performance,yt.unstable_now=function(){return xy.now()}):(Jp=Date,Ey=Jp.now(),yt.unstable_now=function(){return Jp.now()-Ey});var xy,Jp,Ey,Gr=[],ks=[],$O=1,Rn=null,Mi=3,nm=!1,ec=!1,tc=!1,rm=!1,Ty=typeof setTimeout=="function"?setTimeout:null,Ny=typeof clearTimeout=="function"?clearTimeout:null,Cy=typeof setImmediate<"u"?setImmediate:null;function ph(e){for(var t=mr(ks);t!==null;){if(t.callback===null)mh(ks);else if(t.startTime<=e)mh(ks),t.sortIndex=t.expirationTime,im(Gr,t);else break;t=mr(ks)}}function sm(e){if(tc=!1,ph(e),!ec)if(mr(Gr)!==null)ec=!0,No||(No=!0,To());else{var t=mr(ks);t!==null&&am(sm,t.startTime-e)}}var No=!1,ic=-1,Ay=5,My=-1;function Ry(){return rm?!0:!(yt.unstable_now()-Mye&&Ry());){var n=Rn.callback;if(typeof n=="function"){Rn.callback=null,Mi=Rn.priorityLevel;var r=n(Rn.expirationTime<=e);if(e=yt.unstable_now(),typeof r=="function"){Rn.callback=r,ph(e),t=!0;break t}Rn===mr(Gr)&&mh(Gr),ph(e)}else mh(Gr);Rn=mr(Gr)}if(Rn!==null)t=!0;else{var s=mr(ks);s!==null&&am(sm,s.startTime-e),t=!1}}break e}finally{Rn=null,Mi=i,nm=!1}t=void 0}}finally{t?To():No=!1}}}var To;typeof Cy=="function"?To=function(){Cy(em)}:typeof MessageChannel<"u"?(tm=new MessageChannel,ky=tm.port2,tm.port1.onmessage=em,To=function(){ky.postMessage(null)}):To=function(){Ty(em,0)};var tm,ky;function am(e,t){ic=Ty(function(){e(yt.unstable_now())},t)}yt.unstable_IdlePriority=5;yt.unstable_ImmediatePriority=1;yt.unstable_LowPriority=4;yt.unstable_NormalPriority=3;yt.unstable_Profiling=null;yt.unstable_UserBlockingPriority=2;yt.unstable_cancelCallback=function(e){e.callback=null};yt.unstable_forceFrameRate=function(e){0>e||125n?(e.sortIndex=i,im(ks,e),mr(Gr)===null&&e===mr(ks)&&(tc?(Ny(ic),ic=-1):tc=!0,am(sm,i-n))):(e.sortIndex=r,im(Gr,e),ec||nm||(ec=!0,No||(No=!0,To()))),e};yt.unstable_shouldYield=Ry;yt.unstable_wrapCallback=function(e){var t=Mi;return function(){var i=Mi;Mi=t;try{return e.apply(this,arguments)}finally{Mi=i}}}});var Ly=ve((bH,Dy)=>{"use strict";Dy.exports=Oy()});var zy=ve(Ri=>{"use strict";var GO=kt();function By(e){var t="https://react.dev/errors/"+e;if(1{"use strict";function Py(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Py)}catch(e){console.error(e)}}Py(),Uy.exports=zy()});var CE=ve(Zd=>{"use strict";var Xt=Ly(),Ew=kt(),XO=xa();function H(e){var t="https://react.dev/errors/"+e;if(1zo||(e.current=Gm[zo],Gm[zo]=null,zo--)}function pt(e,t){zo++,Gm[zo]=e.current,e.current=t}var Cr=Nr(null),Nc=Nr(null),Hs=Nr(null),nd=Nr(null);function rd(e,t){switch(pt(Hs,t),pt(Nc,e),pt(Cr,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?nw(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=nw(t),e=eE(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}wi(Cr),pt(Cr,e)}function nl(){wi(Cr),wi(Nc),wi(Hs)}function jm(e){var t=e.memoizedState;t!==null&&(fl._currentValue=t.memoizedState,pt(nd,e)),t=Cr.current;var i=eE(t,e.type);t!==i&&(pt(Nc,e),pt(Cr,i))}function sd(e){Nc.current===e&&(wi(Cr),wi(Nc)),nd.current===e&&(wi(nd),fl._currentValue=Ra)}var om,Wy;function As(e){if(om===void 0)try{throw Error()}catch(i){var t=i.stack.trim().match(/\n( *(at )?)/);om=t&&t[1]||"",Wy=-1)":-1s||l[n]!==c[s]){var u=` -`+l[n].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=n&&0<=s);break}}}finally{Ap=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?pr(i):""}function YR(e,t){switch(e.tag){case 26:case 27:case 5:return pr(e.type);case 16:return pr("Lazy");case 13:return e.child!==t&&t!==null?pr("Suspense Fallback"):pr("Suspense");case 19:return pr("SuspenseList");case 0:case 15:return Mp(e.type,!1);case 11:return Mp(e.type.render,!1);case 1:return Mp(e.type,!0);case 31:return pr("Activity");case 30:return pr("ViewTransition");default:return""}}function J0(e){try{var t="",i=null;do t+=YR(e,i),i=e,e=e.return;while(e);return t}catch(n){return` +`);for(r=n=0;nr||l[n]!==c[r]){var u=` +`+l[n].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=n&&0<=r);break}}}finally{lm=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?As(i):""}function s2(e,t){switch(e.tag){case 26:case 27:case 5:return As(e.type);case 16:return As("Lazy");case 13:return e.child!==t&&t!==null?As("Suspense Fallback"):As("Suspense");case 19:return As("SuspenseList");case 0:case 15:return cm(e.type,!1);case 11:return cm(e.type.render,!1);case 1:return cm(e.type,!0);case 31:return As("Activity");case 30:return As("ViewTransition");default:return""}}function $y(e){try{var t="",i=null;do t+=s2(e,i),i=e,e=e.return;while(e);return t}catch(n){return` Error generating stack: `+n.message+` -`+n.stack}}var mm=Object.prototype.hasOwnProperty,vg=qt.unstable_scheduleCallback,Rp=qt.unstable_cancelCallback,jR=qt.unstable_shouldYield,VR=qt.unstable_requestPaint,an=qt.unstable_now,XR=qt.unstable_getCurrentPriorityLevel,FS=qt.unstable_ImmediatePriority,qS=qt.unstable_UserBlockingPriority,Ih=qt.unstable_NormalPriority,ZR=qt.unstable_LowPriority,KS=qt.unstable_IdlePriority,QR=qt.log,JR=qt.unstable_setDisableYieldValue,Rc=null,on=null;function br(e){if(typeof QR=="function"&&JR(e),on&&typeof on.setStrictMode=="function")try{on.setStrictMode(Rc,e)}catch{}}var ln=Math.clz32?Math.clz32:iO,eO=Math.log,tO=Math.LN2;function iO(e){return e>>>=0,e===0?32:31-(eO(e)/tO|0)|0}var ju=256,Vu=262144,Xu=4194304;function ua(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function ld(e,t,i){var n=e.pendingLanes;if(n===0)return 0;var s=0,r=e.suspendedLanes,a=e.pingedLanes;e=e.warmLanes;var o=n&134217727;return o!==0?(n=o&~r,n!==0?s=ua(n):(a&=o,a!==0?s=ua(a):i||(i=o&~e,i!==0&&(s=ua(i))))):(o=n&~r,o!==0?s=ua(o):a!==0?s=ua(a):i||(i=n&~e,i!==0&&(s=ua(i)))),s===0?0:t!==0&&t!==s&&(t&r)===0&&(r=s&-s,i=t&-t,r>=i||r===32&&(i&4194048)!==0)?t:s}function Oc(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function WS(e,t){(t&8)!==0&&(t|=t&32);var i=e.entangledLanes;if(i!==0)for(e=e.entanglements,i&=t;0i;i++)t.push(e);return t}function Dc(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function sO(e,t,i,n,s,r){var a=e.pendingLanes;e.pendingLanes=i,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=i,e.entangledLanes&=i,e.errorRecoveryDisabledLanes&=i,e.shellSuspendCounter=0;var o=e.entanglements,l=e.expirationTimes,c=e.hiddenUpdates;for(i=a&~i;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),bm=!1;if(Fs)try{go={},Object.defineProperty(go,"passive",{get:function(){bm=!0}}),window.addEventListener("test",go,go),window.removeEventListener("test",go,go)}catch{bm=!1}var go,yr=null,Eg=null,gh=null;function aw(){if(gh)return gh;var e,t=Eg,i=t.length,n,s="value"in yr?yr.value:yr.textContent,r=s.length;for(e=0;e=tc),dy=" ",fy=!1;function lw(e,t){switch(e){case"keyup":return HO.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function cw(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ko=!1;function qO(e,t){switch(e){case"compositionend":return cw(t);case"keypress":return t.which!==32?null:(fy=!0,dy);case"textInput":return e=t.data,e===dy&&fy?null:e;default:return null}}function KO(e,t){if(ko)return e==="compositionend"||!Cg&&lw(e,t)?(e=aw(),gh=Eg=yr=null,ko=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function _y(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function vy(e,t){var i=_y(e);e=0;for(var n;i;){if(i.nodeType===3){if(n=e+i.textContent.length,e<=t&&n>=t)return{node:i,offset:t-e};e=n}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=_y(i)}}function fw(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?fw(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function pw(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=ym(e.document);t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=ym(e.document)}return t}function kg(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var ZO=Fs&&"documentMode"in document&&11>=document.documentMode,To=null,Sm=null,nc=null,wm=!1;function by(e,t,i){var n=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;wm||To==null||To!==ym(n)||(n=To,"selectionStart"in n&&kg(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),nc&&_c(nc,n)||(nc=n,n=rd(Sm,"onSelect"),0>=a,s-=a,ps=1<<32-ln(t)+s|i<T?(D=O,O=null):D=O.sibling;var F=d(g,O,v[T],S);if(F===null){O===null&&(O=D);break}e&&O&&F.alternate===null&&t(g,O),m=r(F,m,T),A===null?k=F:A.sibling=F,A=F,O=D}if(T===v.length)return i(g,O),Re&&zs(g,T),k;if(O===null){for(;TT?(D=O,O=null):D=O.sibling;var P=d(g,O,F.value,S);if(P===null){O===null&&(O=D);break}e&&O&&P.alternate===null&&t(g,O),m=r(P,m,T),A===null?k=P:A.sibling=P,A=P,O=D}if(F.done)return i(g,O),Re&&zs(g,T),k;if(O===null){for(;!F.done;T++,F=v.next())F=h(g,F.value,S),F!==null&&(m=r(F,m,T),A===null?k=F:A.sibling=F,A=F);return Re&&zs(g,T),k}for(O=n(O);!F.done;T++,F=v.next())F=f(O,g,T,F.value,S),F!==null&&(e&&(D=F.alternate,D!==null&&O.delete(D.key===null?T:D.key)),m=r(F,m,T),A===null?k=F:A.sibling=F,A=F);return e&&O.forEach(function(M){return t(g,M)}),Re&&zs(g,T),k}function w(g,m,v,S){if(typeof v=="object"&&v!==null&&v.type===Eo&&v.key===null&&v.props.ref===void 0&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Yu:e:{for(var k=v.key;m!==null;){if(m.key===k){if(k=v.type,k===Eo){if(m.tag===7){i(g,m.sibling),S=s(m,v.props.children),fr(S,v),S.return=g,g=S;break e}}else if(m.elementType===k||typeof k=="object"&&k!==null&&k.$$typeof===gr&&ha(k)===m.type){i(g,m.sibling),S=s(m,v.props),fr(S,v),S.return=g,g=S;break e}i(g,m);break}else t(g,m);m=m.sibling}v.type===Eo?(S=ga(v.props.children,g.mode,S,v.key),fr(S,v),S.return=g,g=S):(S=vh(v.type,v.key,v.props,null,g.mode,S),fr(S,v),S.return=g,g=S)}return a(g);case Xl:e:{for(k=v.key;m!==null;){if(m.key===k)if(m.tag===4&&m.stateNode.containerInfo===v.containerInfo&&m.stateNode.implementation===v.implementation){i(g,m.sibling),S=s(m,v.children||[]),S.return=g,g=S;break e}else{i(g,m);break}else t(g,m);m=m.sibling}S=Fp(v,g.mode,S),S.return=g,g=S}return a(g);case gr:return v=ha(v),w(g,m,v,S)}if(Zl(v))return p(g,m,v,S);if(Wl(v)){if(k=Wl(v),typeof k!="function")throw Error(U(150));return v=k.call(v),_(g,m,v,S)}if(typeof v.then=="function")return w(g,m,ih(v),S);if(v.$$typeof===ds)return w(g,m,th(g,v),S);nh(g,v)}return typeof v=="string"&&v!==""||typeof v=="number"||typeof v=="bigint"?(v=""+v,m!==null&&m.tag===6?(i(g,m.sibling),S=s(m,v),S.return=g,g=S):(i(g,m),S=Hp(v,g.mode,S),S.return=g,g=S),a(g)):i(g,m)}return function(g,m,v,S){try{yc=0;var k=w(g,m,v,S);return Po=null,k}catch(O){if(O===rl||O===gd)throw O;var A=Yi(29,O,null,g.mode);return A.lanes=S,A.return=g,A}}}var xa=Aw(!0),Mw=Aw(!1),_r=!1;function Lg(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Nm(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Tr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Nr(e,t,i){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,(Ke&2)!==0){var s=n.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),n.pending=t,t=Uh(e),Sw(e,null,i),t}return pd(e,n,t,i),Uh(e)}function rc(e,t,i){if(t=t.updateQueue,t!==null&&(t=t.shared,(i&4194048)!==0)){var n=t.lanes;n&=e.pendingLanes,i|=n,t.lanes=i,YS(e,i)}}function Kp(e,t){var i=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,i===n)){var s=null,r=null;if(i=i.firstBaseUpdate,i!==null){do{var a={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};r===null?s=r=a:r=r.next=a,i=i.next}while(i!==null);r===null?s=r=t:r=r.next=t}else s=r=t;i={baseState:n.baseState,firstBaseUpdate:s,lastBaseUpdate:r,shared:n.shared,callbacks:n.callbacks},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}var Am=!1;function ac(){if(Am){var e=zo;if(e!==null)throw e}}function oc(e,t,i,n){Am=!1;var s=e.updateQueue;_r=!1;var r=s.firstBaseUpdate,a=s.lastBaseUpdate,o=s.shared.pending;if(o!==null){s.shared.pending=null;var l=o,c=l.next;l.next=null,a===null?r=c:a.next=c,a=l;var u=e.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==a&&(o===null?u.firstBaseUpdate=c:o.next=c,u.lastBaseUpdate=l))}if(r!==null){var h=s.baseState;a=0,u=c=l=null,o=r;do{var d=o.lane&-536870913,f=d!==o.lane;if(f?(ze&d)===d:(n&d)===d){d!==0&&d===Ea&&(Am=!0),u!==null&&(u=u.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var p=e,_=o;d=t;var w=i;switch(_.tag){case 1:if(p=_.payload,typeof p=="function"){h=p.call(w,h,d);break e}h=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=_.payload,d=typeof p=="function"?p.call(w,h,d):p,d==null)break e;h=nt({},h,d);break e;case 2:_r=!0}}d=o.callback,d!==null&&(e.flags|=64,f&&(e.flags|=8192),f=s.callbacks,f===null?s.callbacks=[d]:f.push(d))}else f={lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(c=u=f,l=h):u=u.next=f,a|=d;if(o=o.next,o===null){if(o=s.shared.pending,o===null)break;f=o,o=f.next,f.next=null,s.lastBaseUpdate=f,s.shared.pending=null}}while(!0);u===null&&(l=h),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=u,r===null&&(s.shared.lanes=0),Ur|=a,e.lanes=a,e.memoizedState=h}}function Rw(e,t){if(typeof e!="function")throw Error(U(191,e));e.call(t)}function Ow(e,t){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;er?r:8;var a=ge.T,o={};o.types=a!==null?a.types:null,ge.T=o,jg(e,!1,t,i);try{var l=s(),c=ge.S;if(c!==null&&c(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=l2(l,n);lc(e,t,u,cn(e))}else lc(e,t,n,cn(e))}catch(h){lc(e,t,{then:function(){},status:"rejected",reason:h},cn())}finally{We.p=r,a!==null&&o.types!==null&&(a.types=o.types),ge.T=a}}function p2(){}function Lm(e,t,i,n){if(e.tag!==5)throw Error(U(476));var s=n1(e).queue;i1(e,s,t,ma,i===null?p2:function(){return s1(e),i(n)})}function n1(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ma,baseState:ma,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:ma},next:null};var i={};return t.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ws,lastRenderedState:i},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function s1(e){var t=n1(e);t.next===null&&(t=e.alternate.memoizedState),lc(e,t.next.queue,{},cn())}function Yg(){return pi(el)}function r1(){return At().memoizedState}function a1(){return At().memoizedState}function m2(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var i=cn();e=Tr(i);var n=Nr(t,e,i);n!==null&&(ji(n,t,i),rc(n,t,i)),t={cache:Rg()},e.payload=t;return}t=t.return}}function g2(e,t,i){var n=cn();i={lane:n,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},yd(e)?l1(t,i):(i=Ng(e,t,i,n),i!==null&&(ji(i,e,n),c1(i,t,n)))}function o1(e,t,i){var n=cn();lc(e,t,i,n)}function lc(e,t,i,n){var s={lane:n,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(yd(e))l1(t,s);else{var r=e.alternate;if(e.lanes===0&&(r===null||r.lanes===0)&&(r=t.lastRenderedReducer,r!==null))try{var a=t.lastRenderedState,o=r(a,i);if(s.hasEagerState=!0,s.eagerState=o,un(o,a))return pd(e,t,s,0),it===null&&fd(),!1}catch{}if(i=Ng(e,t,s,n),i!==null)return ji(i,e,n),c1(i,t,n),!0}return!1}function jg(e,t,i,n){if(n={lane:2,revertLane:r_(),gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},yd(e)){if(t)throw Error(U(479))}else t=Ng(e,i,n,2),t!==null&&ji(t,e,2)}function yd(e){var t=e.alternate;return e===we||t!==null&&t===we}function l1(e,t){Uo=Gh=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function c1(e,t,i){if((i&4194048)!==0){var n=t.lanes;n&=e.pendingLanes,i|=n,t.lanes=i,YS(e,i)}}var jh={readContext:pi,use:vd,useCallback:wt,useContext:wt,useEffect:wt,useImperativeHandle:wt,useLayoutEffect:wt,useInsertionEffect:wt,useMemo:wt,useReducer:wt,useRef:wt,useState:wt,useDebugValue:wt,useDeferredValue:wt,useTransition:wt,useSyncExternalStore:wt,useId:wt,useHostTransitionStatus:wt,useFormState:wt,useActionState:wt,useOptimistic:wt,useMemoCache:wt,useCacheRefresh:wt,useEffectEvent:wt},u1={readContext:pi,use:vd,useCallback:function(e,t){return Ii().memoizedState=[e,t===void 0?null:t],e},useContext:pi,useEffect:By,useImperativeHandle:function(e,t,i){i=i!=null?i.concat([e]):null,wh(4194308,4,Zw.bind(null,t,e),i)},useLayoutEffect:function(e,t){return wh(4194308,4,e,t)},useInsertionEffect:function(e,t){wh(4,2,e,t)},useMemo:function(e,t){var i=Ii();t=t===void 0?null:t;var n=e();if(Ca){br(!0);try{e()}finally{br(!1)}}return i.memoizedState=[n,t],n},useReducer:function(e,t,i){var n=Ii();if(i!==void 0){var s=i(t);if(Ca){br(!0);try{i(t)}finally{br(!1)}}}else s=t;return n.memoizedState=n.baseState=s,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:s},n.queue=e,e=e.dispatch=g2.bind(null,we,e),[n.memoizedState,e]},useRef:function(e){var t=Ii();return e={current:e},t.memoizedState=e},useState:function(e){e=Om(e);var t=e.queue,i=o1.bind(null,we,t);return t.dispatch=i,[e.memoizedState,i]},useDebugValue:$g,useDeferredValue:function(e,t){var i=Ii();return Gg(i,e,t)},useTransition:function(){var e=Om(!1);return e=i1.bind(null,we,e.queue,!0,!1),Ii().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,i){var n=we,s=Ii();if(Re){if(i===void 0)throw Error(U(407));i=i()}else{if(i=t(),it===null)throw Error(U(349));(ze&127)!==0||zw(n,t,i)}s.memoizedState=i;var r={value:i,getSnapshot:t};return s.queue=r,By(Uw.bind(null,n,r,e),[e]),n.flags|=2048,Yo(9,{destroy:void 0},Pw.bind(null,n,r,i,t),null),i},useId:function(){var e=Ii(),t=it.identifierPrefix;if(Re){var i=ms,n=ps;i=(n&~(1<<32-ln(n)-1)).toString(32)+i,t="_"+t+"R_"+i,i=Yh++,0<\/script>",r=r.removeChild(r.firstChild);break;case"select":r=typeof n.is=="string"?a.createElement("select",{is:n.is}):a.createElement("select"),n.multiple?r.multiple=!0:n.size&&(r.size=n.size);break;default:r=typeof n.is=="string"?a.createElement(s,{is:n.is}):a.createElement(s)}}r[fi]=t,r[Xi]=n;e:for(a=t.child;a!==null;){if(a.tag===5||a.tag===6)r.appendChild(a.stateNode);else if(a.tag!==4&&a.tag!==27&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===t)break e;for(;a.sibling===null;){if(a.return===null||a.return===t)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}t.stateNode=r;e:switch(_i(r,s,n),s){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}n&&Is(t)}}return at(t),t.subtreeFlags&=-33554433,Yp(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,i),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==n&&Is(t);else{if(typeof n!="string"&&t.stateNode===null)throw Error(U(166));if(e=Cr.current,_o(t)){if(e=t.stateNode,i=t.memoizedProps,n=null,s=Xt,s!==null)switch(s.tag){case 27:case 5:n=s.memoizedProps}e[fi]=t,e=!!(e.nodeValue===i||n!==null&&n.suppressHydrationWarning===!0||oE(e.nodeValue,i)),e||Ir(t,!0)}else e=Cc(e).createTextNode(n),e[fi]=t,t.stateNode=e}return at(t),null;case 31:if(i=t.memoizedState,e===null||e.memoizedState!==null){if(n=_o(t),i!==null){if(e===null){if(!n)throw Error(U(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(U(557));e[fi]=t}else ya(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;at(t),e=!1}else i=qp(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return t.flags&256?(nn(t),t):(nn(t),null);if((t.flags&128)!==0)throw Error(U(558))}return at(t),null;case 13:if(n=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(s=_o(t),n!==null&&n.dehydrated!==null){if(e===null){if(!s)throw Error(U(318));if(s=t.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(U(317));s[fi]=t}else ya(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;at(t),s=!1}else s=qp(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),s=!0;if(!s)return t.flags&256?(nn(t),t):(nn(t),null)}return nn(t),(t.flags&128)!==0?(t.lanes=i,t):(i=n!==null,e=e!==null&&e.memoizedState!==null,i&&(n=t.child,s=null,n.alternate!==null&&n.alternate.memoizedState!==null&&n.alternate.memoizedState.cachePool!==null&&(s=n.alternate.memoizedState.cachePool.pool),r=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(r=n.memoizedState.cachePool.pool),r!==s&&(n.flags|=2048)),i!==e&&i&&(t.child.flags|=8192),ah(t,t.updateQueue),at(t),null);case 4:return Wo(),e===null&&a_(t.stateNode.containerInfo),t.flags|=67108864,at(t),null;case 10:return Hs(t.type),at(t),null;case 19:if(Ig(t),n=t.memoizedState,n===null)return at(t),null;if(s=(t.flags&128)!==0,r=n.rendering,r===null)if(s)Gl(n,!1);else{if(Et!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(r=$h(e),r!==null){for(t.flags|=128,Gl(n,!1),e=r.updateQueue,t.updateQueue=e,ah(t,e),t.subtreeFlags=0,e=i,i=t.child;i!==null;)ww(i,e),i=i.sibling;return Sc(t,gi.current&1|2),Re&&zs(t,n.treeForkCount),t.child}e=e.sibling}n.tail!==null&&an()>td&&(t.flags|=128,s=!0,Gl(n,!1),t.lanes=4194304)}else{if(!s)if(e=$h(r),e!==null){if(t.flags|=128,s=!0,e=e.updateQueue,t.updateQueue=e,ah(t,e),Gl(n,!0),n.tail===null&&n.tailMode!=="collapsed"&&n.tailMode!=="visible"&&!r.alternate&&!Re)return at(t),null}else 2*an()-n.renderingStartTime>td&&i!==536870912&&(t.flags|=128,s=!0,Gl(n,!1),t.lanes=4194304);n.isBackwards?(r.sibling=t.child,t.child=r):(e=n.last,e!==null?e.sibling=r:t.child=r,n.last=r)}if(n.tail!==null){e=n.tail;e:{for(i=e;i!==null;){if(i.alternate!==null){i=!1;break e}i=i.sibling}i=!0}return n.rendering=e,n.tail=e.sibling,n.renderingStartTime=an(),e.sibling=null,r=gi.current,r=s?r&1|2:r&1,n.tailMode==="visible"||n.tailMode==="collapsed"||!i||Re?Sc(t,r):(i=r,lt(vi,t),lt(gi,i),xi===null&&(xi=t)),Re&&zs(t,n.treeForkCount),e}return at(t),null;case 22:case 23:return nn(t),Bg(),n=t.memoizedState!==null,e!==null?e.memoizedState!==null!==n&&(t.flags|=8192):n&&(t.flags|=8192),n?(i&536870912)!==0&&(t.flags&128)===0&&(at(t),t.subtreeFlags&6&&(t.flags|=8192)):at(t),i=t.updateQueue,i!==null&&ah(t,i.retryQueue),i=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),n=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),n!==i&&(t.flags|=2048),e!==null&&mi(_a),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),Hs(Lt),at(t),null;case 25:return null;case 30:return t.flags|=33554432,at(t),null}throw Error(U(156,t.tag))}function E2(e,t){switch(Mg(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Hs(Lt),Wo(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Bh(t),null;case 31:if(t.memoizedState!==null){if(nn(t),t.alternate===null)throw Error(U(340));ya()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(nn(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(U(340));ya()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ig(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return Wo(),null;case 10:return Hs(t.type),null;case 22:case 23:return nn(t),Bg(),e!==null&&mi(_a),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Hs(Lt),null;case 25:return null;default:return null}}function S1(e,t){switch(Mg(t),t.tag){case 3:Hs(Lt),Wo();break;case 26:case 27:case 5:Bh(t);break;case 4:Wo();break;case 31:t.memoizedState!==null&&nn(t);break;case 13:nn(t);break;case 19:Ig(t);break;case 10:Hs(t.type);break;case 22:case 23:nn(t),Bg(),e!==null&&mi(_a);break;case 24:Hs(Lt)}}function Pc(e,t){try{var i=t.updateQueue,n=i!==null?i.lastEffect:null;if(n!==null){var s=n.next;i=s;do{if((i.tag&e)===e){n=void 0;var r=i.create,a=i.inst;n=r(),a.destroy=n}i=i.next}while(i!==s)}}catch(o){Qe(t,t.return,o)}}function Pr(e,t,i){try{var n=t.updateQueue,s=n!==null?n.lastEffect:null;if(s!==null){var r=s.next;n=r;do{if((n.tag&e)===e){var a=n.inst,o=a.destroy;if(o!==void 0){a.destroy=void 0,s=t;var l=i,c=o;try{c()}catch(u){Qe(s,l,u)}}}n=n.next}while(n!==r)}}catch(u){Qe(t,t.return,u)}}function w1(e){var t=e.updateQueue;if(t!==null){var i=e.stateNode;try{Ow(t,i)}catch(n){Qe(e,e.return,n)}}}function E1(e,t,i){i.props=ka(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(n){Qe(e,t,n)}}function us(e,t){try{var i=e.ref;if(i!==null){switch(e.tag){case 26:case 27:case 5:var n=e.stateNode;break;case 30:var s=e.stateNode,r=qs(e.memoizedProps,s);(s.ref===null||s.ref.name!==r)&&(s.ref=fE(r)),n=s.ref;break;case 7:if(e.stateNode===null){var a=new hn(e);Vi(e.child,!1,hD,a,void 0,void 0),e.stateNode=a}n=e.stateNode;break;default:n=e.stateNode}typeof i=="function"?e.refCleanup=i(n):i.current=n}}catch(o){Qe(e,t,o)}}function di(e,t){var i=e.ref,n=e.refCleanup;if(i!==null)if(typeof n=="function")try{n()}catch(s){Qe(e,t,s)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(s){Qe(e,t,s)}else i.current=null}function Xh(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var i=0;i title"))),_i(n,t,i),n[fi]=e,Vt(n),t=n;break e;case"link":if(r=ES("link","href",s).get(t+(i.href||""))){for(a=0;aw&&(a=w,w=_,_=a);var g=vy(o,_),m=vy(o,w);if(g&&m&&(f.rangeCount!==1||f.anchorNode!==g.node||f.anchorOffset!==g.offset||f.focusNode!==m.node||f.focusOffset!==m.offset)){var v=h.createRange();v.setStart(g.node,g.offset),f.removeAllRanges(),_>w?(f.addRange(v),f.extend(m.node,m.offset)):(v.setEnd(m.node,m.offset),f.addRange(v))}}}}for(h=[],f=o;f=f.parentNode;)f.nodeType===1&&h.push({element:f,left:f.scrollLeft,top:f.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;oi?32:i,ge.T=null,i=Jm,Jm=null;var r=Gn,a=_s;if(yt=0,Ta=Gn=null,_s=0,(Ke&6)!==0)throw Error(U(331));var o=Ke;if(Ke|=4,q1(r.current),U1(r,r.current,a,i),Ke=o,Uc(0,!1),on&&typeof on.onPostCommitFiberRoot=="function")try{on.onPostCommitFiberRoot(Rc,r)}catch{}return!0}finally{We.p=s,ge.T=n,eE(e,t)}}function nS(e,t,i){t=kn(i,t),t=Im(e.stateNode,t,2),e=Nr(e,t,2),e!==null&&(Dc(e,2),ys(e))}function Qe(e,t,i){if(e.tag===3)nS(e,e,i);else for(;t!==null;){if(t.tag===3){nS(t,e,i);break}else if(t.tag===1){var n=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Rr===null||!Rr.has(n))){e=kn(i,e),i=m1(2),n=Nr(t,i,2),n!==null&&(g1(i,n,t,e),Dc(n,2),ys(n));break}}t=t.return}}function Qp(e,t,i){var n=e.pingCache;if(n===null){n=e.pingCache=new T2;var s=new Set;n.set(t,s)}else s=n.get(t),s===void 0&&(s=new Set,n.set(t,s));s.has(i)||(n_=!0,s.add(i),e=B2.bind(null,e,t,i),t.then(e,e))}function B2(e,t,i){var n=e.pingCache;n!==null&&n.delete(t),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,it===e&&(ze&i)===i&&((Et===4||Et===3&&(ze&62914560)===ze&&300>an()-wd)&&(Ke&2)===0?Xo(e,0):ed|=i,jo===ze&&(jo=0)),ys(e)}function tE(e,t){t===0&&(t=$S()),e=Ra(e,t),e!==null&&(Dc(e,t),ys(e))}function I2(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),tE(e,i)}function z2(e,t){var i=0;switch(e.tag){case 31:case 13:var n=e.stateNode,s=e.memoizedState;s!==null&&(i=s.retryLane);break;case 19:n=e.stateNode;break;case 22:n=e.stateNode._retryCache;break;default:throw Error(U(314))}n!==null&&n.delete(t),tE(e,i)}function P2(e,t){return vg(e,t)}var Zo=null,So=null,sg=!1,sd=!1,Jp=!1,xr=0;function ys(e){e!==So&&e.next===null&&(So===null?Zo=So=e:So=So.next=e),sd=!0,sg||(sg=!0,H2())}function Uc(e,t){if(!Jp&&sd){Jp=!0;do for(var i=!1,n=Zo;n!==null;){if(!t)if(e!==0){var s=n.pendingLanes;if(s===0)var r=0;else{var a=n.suspendedLanes,o=n.pingedLanes;r=(1<<31-ln(42|e)+1)-1,r&=s&~(a&~o),r=r&201326741?r&201326741|1:r?r|2:0}r!==0&&(i=!0,sS(n,r))}else r=ze,r=ld(n,n===it?r:0,n.cancelPendingCommit!==null||n.timeoutHandle!==-1),(r&3)===0||Oc(n,r)||(i=!0,sS(n,r));n=n.next}while(i);Jp=!1}}function U2(){iE()}function iE(){sd=sg=!1;var e=0;xr!==0&&V2()&&(e=xr);for(var t=an(),i=null,n=Zo;n!==null;){var s=n.next,r=nE(n,t);r===0?(n.next=null,i===null?Zo=s:i.next=s,s===null&&(So=i)):(i=n,(e!==0||(r&3)!==0)&&(sd=!0)),n=s}yt!==0&&yt!==5||Uc(e,!1),xr!==0&&(xr=0)}function nE(e,t){for(var i=e.suspendedLanes,n=e.pingedLanes,s=e.expirationTimes,r=e.pendingLanes&-62914561;0o)break;var u=l.transferSize,h=l.initiatorType;u&&uS(h)&&(l=l.responseEnd,a+=u*(lMh){_.length=p;break}v=new Promise(tD.bind(v)),_.push(v)}}}if(0<_.length)return d=Promise.race([Promise.all(_),new Promise(function(k){return setTimeout(k,500)})]).then(s,s),(f?Promise.allSettled([f.finished,d]):d).then(r,r);if(s(),f)return f.finished.then(r,r);r()},types:i});c.__reactViewTransition=u;var h=[];return u.ready.then(function(){for(var d=c.documentElement.getAnimations({subtree:!0}),f=0;f"u"?null:document;function SE(e,t,i){var n=ll;if(n&&typeof t=="string"&&t){var s=Cn(t);s='link[rel="'+e+'"][href="'+s+'"]',typeof i=="string"&&(s+='[crossorigin="'+i+'"]'),yS.has(s)||(yS.add(s),e={rel:e,crossOrigin:i,href:t},n.querySelector(s)===null&&(t=n.createElement("link"),_i(t,"link",e),Vt(t),n.head.appendChild(t)))}}function yD(e){Vs.D(e),SE("dns-prefetch",e,null)}function SD(e,t){Vs.C(e,t),SE("preconnect",e,t)}function wD(e,t,i){Vs.L(e,t,i);var n=ll;if(n&&e&&t){var s='link[rel="preload"][as="'+Cn(t)+'"]';t==="image"&&i&&i.imageSrcSet?(s+='[imagesrcset="'+Cn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(s+='[imagesizes="'+Cn(i.imageSizes)+'"]')):s+='[href="'+Cn(e)+'"]';var r=s;switch(t){case"style":r=Jo(e);break;case"script":r=cl(e)}if(!(An.has(r)||(e=nt({rel:"preload",href:t==="image"&&i&&i.imageSrcSet?void 0:e,as:t},i),An.set(r,e),n.querySelector(s)!==null||t==="style"&&n.querySelector(Hc(r))||t==="script"&&n.querySelector(Fc(r))))){var a=n.createElement("link");_i(a,"link",e),t==="style"&&(a[zh]=!0,a.onload=a.onerror=function(){XS(a)}),Vt(a),n.head.appendChild(a)}}}function ED(e,t){Vs.m(e,t);var i=ll;if(i&&e){var n=t&&typeof t.as=="string"?t.as:"script",s='link[rel="modulepreload"][as="'+Cn(n)+'"][href="'+Cn(e)+'"]',r=s;switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":r=cl(e)}if(!An.has(r)&&(e=nt({rel:"modulepreload",href:e},t),An.set(r,e),i.querySelector(s)===null)){switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Fc(r)))return}n=i.createElement("link"),_i(n,"link",e),Vt(n),i.head.appendChild(n)}}}function xD(e,t,i){Vs.S(e,t,i);var n=ll;if(n&&e){var s=Lo(n).hoistableStyles,r=Jo(e);t=t||"default";var a=s.get(r);if(!a){var o={loading:0,preload:null};if(a=n.querySelector(Hc(r)))o.loading=5;else{e=nt({rel:"stylesheet",href:e,"data-precedence":t},i),(i=An.get(r))&&u_(e,i);var l=a=n.createElement("link");Vt(l),_i(l,"link",e),l._p=new Promise(function(c,u){l.onload=c,l.onerror=u}),l.addEventListener("load",function(){o.loading|=1}),l.addEventListener("error",function(){o.loading|=2}),o.loading|=4,Nh(a,t,n)}a={type:"stylesheet",instance:a,count:1,state:o},s.set(r,a)}}}function CD(e,t){Vs.X(e,t);var i=ll;if(i&&e){var n=Lo(i).hoistableScripts,s=cl(e),r=n.get(s);r||(r=i.querySelector(Fc(s)),r||(e=nt({src:e,async:!0},t),(t=An.get(s))&&h_(e,t),r=i.createElement("script"),Vt(r),_i(r,"link",e),i.head.appendChild(r)),r={type:"script",instance:r,count:1,state:null},n.set(s,r))}}function kD(e,t){Vs.M(e,t);var i=ll;if(i&&e){var n=Lo(i).hoistableScripts,s=cl(e),r=n.get(s);r||(r=i.querySelector(Fc(s)),r||(e=nt({src:e,async:!0,type:"module"},t),(t=An.get(s))&&h_(e,t),r=i.createElement("script"),Vt(r),_i(r,"link",e),i.head.appendChild(r)),r={type:"script",instance:r,count:1,state:null},n.set(s,r))}}function SS(e,t,i,n){var s=(s=Cr.current)?kc(s):null;if(!s)throw Error(U(446));switch(e){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(i=Jo(i.href),t=Lo(s).hoistableStyles,n=t.get(i),n||(n={type:"style",instance:null,count:0,state:null},t.set(i,n)),n):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){e=Jo(i.href);var r=Lo(s).hoistableStyles,a=r.get(e);if(a||(s=s.ownerDocument||s,a={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},r.set(e,a),(r=s.querySelector(Hc(e)))?r._p||(a.instance=r,a.state.loading=5):(r=An.get(e),r||(r={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},An.set(e,r)),TD(s,e,r,a.state))),t&&n===null)throw Error(U(528,""));return a}if(t&&n!==null)throw Error(U(529,""));return null;case"script":return t=i.async,i=i.src,typeof i=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(i=cl(i),t=Lo(s).hoistableScripts,n=t.get(i),n||(n={type:"script",instance:null,count:0,state:null},t.set(i,n)),n):{type:"void",instance:null,count:0,state:null};default:throw Error(U(444,e))}}function Jo(e){return'href="'+Cn(e)+'"'}function Hc(e){return'link[rel="stylesheet"]['+e+"]"}function wE(e){return nt({},e,{"data-precedence":e.precedence,precedence:null})}function TD(e,t,i,n){if(t=e.querySelector('link[rel="preload"][as="style"]['+t+"]")){if(t[zh]!==!0){n.loading=1;return}}else t=e.createElement("link"),t[zh]=!0,t.onload=t.onerror=XS.bind(null,t),_i(t,"link",i),Vt(t),e.head.appendChild(t);n.preload=t,t.addEventListener("load",function(){return n.loading|=1}),t.addEventListener("error",function(){return n.loading|=2})}function cl(e){return'[src="'+Cn(e)+'"]'}function Fc(e){return"script[async]"+e}function wS(e,t,i){if(t.count++,t.instance===null)switch(t.type){case"style":var n=e.querySelector('style[data-href~="'+Cn(i.href)+'"]');if(n)return t.instance=n,Vt(n),n;var s=nt({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return n=(e.ownerDocument||e).createElement("style"),Vt(n),_i(n,"style",s),Nh(n,i.precedence,e),t.instance=n;case"stylesheet":s=Jo(i.href);var r=e.querySelector(Hc(s));if(r)return t.state.loading|=4,t.instance=r,Vt(r),r;n=wE(i),(s=An.get(s))&&u_(n,s),r=(e.ownerDocument||e).createElement("link"),Vt(r);var a=r;return a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),_i(r,"link",n),t.state.loading|=4,Nh(r,i.precedence,e),t.instance=r;case"script":return r=cl(i.src),(s=e.querySelector(Fc(r)))?(t.instance=s,Vt(s),s):(n=i,(s=An.get(r))&&(n=nt({},i),h_(n,s)),e=e.ownerDocument||e,s=e.createElement("script"),Vt(s),_i(s,"link",n),e.head.appendChild(s),t.instance=s);case"void":return null;default:throw Error(U(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(n=t.instance,t.state.loading|=4,Nh(n,i.precedence,e));return t.instance}function Nh(e,t,i){for(var n=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),s=n.length?n[n.length-1]:null,r=s,a=0;a title"):null)}function ND(e,t,i){if(i===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function xS(e,t){return e==="img"&&t.src!=null&&t.src!==""&&t.onLoad==null&&t.loading!=="lazy"}function EE(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function xE(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function CS(e,t){typeof t.decode=="function"&&(e.imgCount++,t.complete||(e.imgBytes+=xE(t),e.suspenseyImages.push(t)),e=RD.bind(e),t.decode().then(e,e))}function AD(e,t,i,n){if(i.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var s=Jo(n.href),r=t.querySelector(Hc(s));if(r){t=r._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Tc.bind(e),t.then(e,e)),i.state.loading|=4,i.instance=r,Vt(r);return}r=t.ownerDocument||t,n=wE(n),(s=An.get(s))&&u_(n,s),r=r.createElement("link"),Vt(r);var a=r;a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),_i(r,"link",n),i.instance=r}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(i,t),(t=i.state.preload)&&(i.state.loading&3)===0&&(e.count++,i=Tc.bind(e),t.addEventListener("load",i),t.addEventListener("error",i))}}var Mh=0;function MD(e,t){return e.stylesheets&&e.count===0&&Rh(e,e.stylesheets),0Mh?50:800)+t);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(n),clearTimeout(s)}}:null}function CE(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)Rh(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function Tc(){this.count--,CE(this)}function RD(){this.imgCount--,CE(this)}var ad=null;function Rh(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ad=new Map,t.forEach(OD,e),ad=null,Tc.call(e))}function OD(e,t){if(!(t.state.loading&4)){var i=ad.get(e);if(i)var n=i.get(null);else{i=new Map,ad.set(e,i);for(var s=e.querySelectorAll("link[data-precedence],style[data-precedence]"),r=0;r{"use strict";function LE(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(LE)}catch(e){console.error(e)}}LE(),BE.exports=DE()});function HD(e){return/^accent(-|$)/i.test(e.replace(/^--/,"").replace(/^magpie-/i,""))}function zE(e){let t=new URLSearchParams(e).get("tokens");if(!t)return;let i;try{i=JSON.parse(decodeURIComponent(escape(atob(t))))}catch{return}let n=document.documentElement;for(let[s,r]of Object.entries(i)){let a=String(r??"").trim();if(!a||HD(s))continue;let o=s.startsWith("--")?s:s.startsWith("magpie-")?`--${s}`:`--magpie-${s}`;n.style.setProperty(o,a)}}var PE=le(()=>{});function FD(){return typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function v_(e){return e==="light"||e==="dark"?e:"auto"}function qD(e,t,i){let n=e==="light"||e==="dark"?e:t??i;return{theme:n,hostColors:t!==null&&n===t}}function HE(e){let t=new URLSearchParams(e).get("theme");__=t==="light"||t==="dark"?t:null,Xs("auto"),typeof window<"u"&&window.matchMedia&&(UE=window.matchMedia("(prefers-color-scheme: dark)"),UE.addEventListener?.("change",()=>Xs(g_)))}function FE(){return __!==null}function Xs(e){g_=v_(e);let{theme:t,hostColors:i}=qD(g_,__,FD()),n=document.documentElement;n.dataset.theme=t,i?n.dataset.hostColors="1":delete n.dataset.hostColors}function qE(){return document.documentElement.dataset.theme==="dark"?"dark":"light"}var __,g_,UE,Nd=le(()=>{__=null,g_="auto",UE=null});function KD(e){if(typeof e!="string"||!e||e.length>2048)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password)return null;let i=t.hostname.toLowerCase();return i!=="127.0.0.1"&&i!=="localhost"&&i!=="[::1]"||!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(t.pathname)?null:`${t.protocol}//${t.host}${t.pathname}${t.search}`}function WD(e){let t=e.startsWith("#")?e.slice(1):e;return KD(new URLSearchParams(t).get("b"))}function $D(e,t){let i=WD(e);if(!i)return null;let n=new URL(i);return t>0&&n.searchParams.set("ac_lost",String(Math.floor(t))),n.toString()}function Md(){let e=$D(location.hash,Ad);return e?(location.replace(e),!0):!1}function KE(e,t,i=5e3){let n=null,s=e.onState(r=>{r==="reconnecting"||r==="down"?(Ad||(Ad=Date.now()),n||(n=setTimeout(()=>{n=null,e.getState()!=="open"&&t()},i))):r==="open"&&(Ad=0,n&&(clearTimeout(n),n=null))});return()=>{s(),n&&clearTimeout(n)}}var Ad,b_=le(()=>{Ad=0});var y_,WE=le(()=>{y_={zh:{app:{title:"Agent \u63A7\u5236\u53F0",subtitle:"\u5148\u5728\u5DE6\u4FA7\u65B0\u5EFA\u6216\u9009\u62E9\u4E00\u4E2A\u9879\u76EE"},common:{cancel:"\u53D6\u6D88",ok:"\u786E\u5B9A",save:"\u4FDD\u5B58",add:"\u6DFB\u52A0",browse:"\u6D4F\u89C8\u2026",more:"\u66F4\u591A",copy:"\u590D\u5236",copied:"\u5DF2\u590D\u5236",copyPath:"\u590D\u5236\u8DEF\u5F84",copiedPath:"\u5DF2\u590D\u5236\u8DEF\u5F84",search:"\u641C\u7D22",settings:"\u8BBE\u7F6E",remove:"\u79FB\u9664",close:"\u5173\u95ED",retry:"\u91CD\u8BD5",details:"\u8BE6\u60C5 \u203A",submit:"\u63D0\u4EA4",other:"\u5176\u4ED6\u2026",default:"\u9ED8\u8BA4",done:"\u5B8C\u6210",loading:"\u52A0\u8F7D\u4E2D\u2026",send:"\u53D1\u9001",stop:"\u505C\u6B62",refresh:"\u5237\u65B0",rename:"\u91CD\u547D\u540D",delete:"\u5220\u9664",discard:"\u653E\u5F03",notInstalled:"\uFF08\u672A\u5B89\u88C5\uFF09",notDetected:"\uFF08\u672A\u68C0\u6D4B\u5230\uFF09",current:"\uFF08\u5F53\u524D\uFF09",messages:"\u6761",imported:" \xB7 \u5DF2\u5BFC\u5165",justNow:"\u521A\u521A",minutesAgo:"{n} \u5206\u949F\u524D",hoursAgo:"{n} \u5C0F\u65F6\u524D",daysAgo:"{n} \u5929\u524D"},boot:{connecting:"\u6B63\u5728\u8FDE\u63A5\u2026",serviceDown:"\u672C\u5730\u670D\u52A1\u672A\u542F\u52A8",retry:"\u91CD\u8BD5",reconnecting:"\u8FDE\u63A5\u4E2D\u65AD\uFF0C\u6B63\u5728\u91CD\u65B0\u8FDE\u63A5\u2026",starting:"\u6B63\u5728\u542F\u52A8\u672C\u5730\u670D\u52A1\u2026",reopening:"\u672C\u5730\u670D\u52A1\u5DF2\u91CD\u542F\uFF0C\u6B63\u5728\u91CD\u65B0\u8FDE\u63A5\u2026"},topbar:{pickThread:"\u9009\u62E9\u4E00\u4E2A\u5BF9\u8BDD",sidebar:"\u4FA7\u680F\uFF08Ctrl+B\uFF09",clickRename:"\u70B9\u51FB\u6539\u540D",waitAuth:"\u7B49\u5F85\u6388\u6743",running:"\u8FD0\u884C\u4E2D {s}s",error:"\u51FA\u9519",closedResume:"\u5DF2\u5173\u95ED \xB7 \u53D1\u9001\u6D88\u606F\u5C06\u7EED\u63A5",threadInfo:"\u5BF9\u8BDD\u4FE1\u606F",panelChanges:"\u6539\u52A8\uFF08Ctrl+J\uFF09",panelFiles:"\u6587\u4EF6",panelTerminal:"\u7EC8\u7AEF"},sidebar:{newProject:"\u65B0\u5EFA\u9879\u76EE",filterPlaceholder:"\u8FC7\u6EE4\u5BF9\u8BDD\u6807\u9898",searchTitle:"\u641C\u7D22\uFF08Ctrl+K\uFF09",noProjectsTitle:"\u8FD8\u6CA1\u6709\u9879\u76EE",noProjectsSub:"\u9879\u76EE\u5BF9\u5E94\u4E00\u4E2A\u672C\u673A\u76EE\u5F55\uFF0C\u5BF9\u8BDD\u90FD\u5728\u76EE\u5F55\u91CC\u5E72\u6D3B\u3002",newThread:"\u65B0\u5EFA\u5BF9\u8BDD",projectMenu:"\u9879\u76EE\u83DC\u5355",showAll:"\u663E\u793A\u5168\u90E8 {n} \u6761",noThreads:"\u8FD8\u6CA1\u6709\u5BF9\u8BDD",rename:"\u91CD\u547D\u540D",pin:"\u7F6E\u9876",unpin:"\u53D6\u6D88\u7F6E\u9876",archive:"\u5F52\u6863",unarchive:"\u53D6\u6D88\u5F52\u6863",exportMd:"\u5BFC\u51FA Markdown",deleteThread:"\u5220\u9664\u5BF9\u8BDD",deleteThreadBody:"\u300C{title}\u300D\u5C06\u88AB\u79FB\u5230\u56DE\u6536\u76EE\u5F55\uFF0C\u786E\u5B9A\u5417\uFF1F",importHist:"\u5BFC\u5165\u5DF2\u6709\u5BF9\u8BDD\u2026",openExplorer:"\u5728\u8D44\u6E90\u7BA1\u7406\u5668\u6253\u5F00",showArchived:"\u663E\u793A\u5DF2\u5F52\u6863",hideArchived:"\u9690\u85CF\u5DF2\u5F52\u6863",archivedN:"\u5DF2\u5F52\u6863 {n} \u6761",archivedHint:"\u5DF2\u5F52\u6863\uFF0C\u53EF\u5728\u9879\u76EE\u5217\u8868\u5E95\u90E8\u67E5\u770B",unarchived:"\u5DF2\u53D6\u6D88\u5F52\u6863",exportSaved:"\u5DF2\u5BFC\u51FA\u5230 {path}",removeProject:"\u79FB\u9664\u9879\u76EE",removeProjectBody:"\u300C{name}\u300D\u5C06\u4ECE\u5217\u8868\u79FB\u9664\uFF0C\u5176\u5BF9\u8BDD\u79FB\u5230\u56DE\u6536\u76EE\u5F55\uFF08\u6587\u4EF6\u4E0D\u4F1A\u88AB\u5220\u9664\uFF09\u3002",renameProject:"\u91CD\u547D\u540D\u9879\u76EE",projectName:"\u9879\u76EE\u540D",newProjectDlg:"\u65B0\u5EFA\u9879\u76EE",dirLabel:"\u9879\u76EE\u76EE\u5F55\uFF08\u5FC5\u987B\u662F\u5DF2\u5B58\u5728\u7684\u6587\u4EF6\u5939\uFF09",dirMissing:"\u76EE\u5F55\u4E0D\u5B58\u5728",notDir:"\u8FD9\u662F\u4E00\u4E2A\u6587\u4EF6\uFF0C\u4E0D\u662F\u76EE\u5F55",dirOk:"\u2713 \u76EE\u5F55\u53EF\u7528\uFF0C\u9879\u76EE\u540D\u53D6\u76EE\u5F55\u540D",recent:"\u6700\u8FD1\u4F7F\u7528",pickFolderUnsupported:"\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u5F39\u7A97\u9009\u76EE\u5F55\uFF0C\u8BF7\u624B\u52A8\u8F93\u5165",pickFolderFailed:"\u6253\u5F00\u6587\u4EF6\u5939\u9009\u62E9\u6846\u5931\u8D25",importTitle:"\u5BFC\u5165\u5DF2\u6709\u5BF9\u8BDD \u2014 {name}",scanning:"\u6B63\u5728\u626B\u63CF\u672C\u673A\u5386\u53F2\u4F1A\u8BDD\u2026",importEmpty:"\u6CA1\u6709\u627E\u5230\u5BF9\u5E94\u8FD9\u4E2A\u9879\u76EE\u76EE\u5F55\u7684\u5386\u53F2\u4F1A\u8BDD\u3002",importing:"\u5BFC\u5165\u4E2D\u2026",importN:"\u5BFC\u5165 {n} \u4E2A\u5BF9\u8BDD",importedN:"\u5DF2\u5BFC\u5165 {n} \u4E2A\u5BF9\u8BDD",failNewThread:"\u65B0\u5EFA\u5BF9\u8BDD\u5931\u8D25\uFF1A",failRename:"\u91CD\u547D\u540D\u5931\u8D25\uFF1A",failAddProject:"\u6DFB\u52A0\u9879\u76EE\u5931\u8D25\uFF1A",failImportList:"\u8BFB\u53D6\u5386\u53F2\u5931\u8D25\uFF1A",failImport:"\u5BFC\u5165\u5931\u8D25\uFF1A",failExport:"\u5BFC\u51FA\u5931\u8D25\uFF1A"},chat:{newInProject:"\u5728 {name} \u4E2D\u65B0\u5EFA\u5BF9\u8BDD",emptyHint:"\u5BF9\u8BDD\u8FD8\u6CA1\u6709\u6D88\u606F\uFF0C\u4E0B\u9762\u8F93\u5165\u5F00\u59CB\u3002",jumpBottom:"\u56DE\u5230\u5E95\u90E8",emptyPlaceholder:"\u8F93\u5165\u4EFB\u52A1\uFF0CEnter \u53D1\u9001",autoNewThread:"\u5C06\u81EA\u52A8\u65B0\u5EFA\u5BF9\u8BDD",pickProjectTitle:"\u9009\u62E9\u4E00\u4E2A\u9879\u76EE",pickProjectSub:"\u5728\u5DE6\u4FA7\u9009\u4E00\u4E2A\u9879\u76EE\uFF0C\u6216\u65B0\u5EFA\u4E00\u4E2A\uFF0C\u7136\u540E\u5F00\u59CB\u5BF9\u8BDD\u3002",failSend:"\u53D1\u9001\u5931\u8D25\uFF1A"},composer:{waitPerm:"\u7B49\u5F85\u4F60\u786E\u8BA4\u4E0A\u9762\u7684\u6388\u6743\u8BF7\u6C42",queuePlaceholder:"\u8F93\u5165\u6392\u961F\u6D88\u606F\uFF08Ctrl+Enter \u63D2\u8BDD\uFF09",queuePlaceholderNoSteer:"\u7EE7\u7EED\u8865\u5145\u8981\u6C42\uFF0C\u56DE\u8F66\u6392\u961F\u53D1\u9001\u2026",steerUnsupported:"{agent} \u4E0D\u652F\u6301\u63D2\u8BDD\uFF1A\u8FD0\u884C\u4E2D\u53D1\u7684\u6D88\u606F\u4F1A\u6392\u961F\uFF0C\u672C\u56DE\u5408\u7ED3\u675F\u540E\u518D\u53D1\u9001\u3002",queuedToast:"\u5DF2\u6392\u961F\uFF1A\u672C\u56DE\u5408\u7ED3\u675F\u540E\u53D1\u9001",steeredToast:"\u5DF2\u63D2\u8BDD",inputPlaceholder:"\u8F93\u5165\u6D88\u606F\u2026",bypassWarn:"Bypass\uFF1AAgent \u7684\u6240\u6709\u64CD\u4F5C\u4E0D\u4F1A\u518D\u95EE\u4F60\u3002",imagesByPath:"{agent} \u4E0D\u80FD\u76F4\u63A5\u770B\u56FE\u7247\uFF1A\u4F1A\u628A\u56FE\u7247\u7684\u6587\u4EF6\u8DEF\u5F84\u53D1\u7ED9\u5B83\uFF08\u5B83\u80FD\u7528\u6587\u4EF6\u5DE5\u5177\u6253\u5F00\uFF09\u3002",agentModel:"Agent & model",agentLocked:"Agent (locked)",agent:"Agent",model:"Model",searchModel:"Search",searchAllModels:"Search models\u2026",providers:"Agent",agentLockedHint:"\u5DF2\u5F00\u59CB\u7684\u5BF9\u8BDD\u4E0D\u80FD\u66F4\u6362 Agent\uFF1B\u8981\u7528\u522B\u7684 Agent \u8BF7\u65B0\u5EFA\u5BF9\u8BDD\u3002",providersLoading:"\u6B63\u5728\u68C0\u6D4B Agent\u2026",moreModels:"\u8FD8\u6709 {n} \u4E2A\u6A21\u578B\uFF0C\u8BF7\u7528\u4E0A\u65B9\u641C\u7D22",pickModel:"\u9009\u62E9\u6A21\u578B",noModelMatch:"\u6CA1\u6709\u5339\u914D\u7684\u6A21\u578B",defaultModel:"\u9ED8\u8BA4",defaultEffort:"\u9ED8\u8BA4",defaultEffortNamed:"\u9ED8\u8BA4\uFF08{level}\uFF09",effortTitle:"\u601D\u8003\u5F3A\u5EA6",modeTitle:"\u6743\u9650\u6A21\u5F0F",attachTitle:"\u9644\u4EF6\uFF08\u56FE\u7247/\u6587\u672C\uFF09",failSwitchAgent:"\u5207\u6362 Agent \u5931\u8D25\uFF1A",failSend:"\u53D1\u9001\u5931\u8D25\uFF1A",failUpload:"\u9644\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF1A",uploadFailed:"\u4E0A\u4F20\u5931\u8D25",steerTag:"\u63D2\u8BDD",cursorAutoReview:"\u81EA\u52A8\u63A5\u53D7\u6743\u9650\u63D0\u793A\uFF08Auto-review\uFF09",cursorFastOff:"\u6807\u51C6\u901F\u5EA6",cursorFastOn:"Fast",slashGroupCommand:"\u547D\u4EE4",slashGroupSkill:"Skill",slashNoCommands:"\u8BE5 Agent \u672A\u63D0\u4F9B\u547D\u4EE4",slashLoading:"\u6B63\u5728\u83B7\u53D6\u547D\u4EE4\u2026",mode:{plan:{label:"\u89C4\u5212",desc:"\u53EA\u5206\u6790\u4EE3\u7801\u5E93\uFF0C\u4E0D\u6267\u884C\u5DE5\u5177\u6216\u4FEE\u6539"},default:{label:"\u6BCF\u6B21\u8BE2\u95EE",desc:"\u9996\u6B21\u4F7F\u7528\u5DE5\u5177\u65F6\u4F1A\u8BF7\u6C42\u6388\u6743"},acceptEdits:{label:"\u63A5\u53D7\u7F16\u8F91",desc:"\u81EA\u52A8\u6279\u51C6\u7F16\u8F91\u7C7B\u5DE5\u5177\uFF0C\u4E0D\u518D\u9010\u9879\u8BE2\u95EE"},bypass:{label:"\u5168\u90E8\u653E\u884C",desc:"\u8DF3\u8FC7\u6240\u6709\u6388\u6743\u63D0\u793A\uFF08\u8BF7\u8C28\u614E\u4F7F\u7528\uFF09"},cursorAgent:{label:"Agent",desc:"\u5B8C\u6574 Agent\uFF1A\u53EF\u8BFB\u5199\u3001\u6267\u884C\u5DE5\u5177"},cursorPlan:{label:"\u89C4\u5212",desc:"\u53EA\u8BFB\u89C4\u5212\uFF1A\u5206\u6790\u5E76\u63D0\u51FA\u65B9\u6848\uFF0C\u4E0D\u6539\u6587\u4EF6"},cursorAsk:{label:"\u95EE\u7B54",desc:"\u95EE\u7B54\u6A21\u5F0F\uFF1A\u89E3\u91CA\u4E0E\u8BA8\u8BBA\uFF0C\u53EA\u8BFB"}},agentMode:{Plan:"\u89C4\u5212",Build:"\u6784\u5EFA",Ask:"\u8BE2\u95EE",Code:"\u7F16\u7801",Agent:"Agent","Allow All":"\u5168\u90E8\u5141\u8BB8","Bypass Permissions":"\u8DF3\u8FC7\u6388\u6743","Read Only":"\u53EA\u8BFB",Auto:"\u81EA\u52A8","Full Access":"\u5B8C\u5168\u8BBF\u95EE"},effort:{low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8",xhigh:"\u8D85\u9AD8",max:"\u6700\u9AD8",minimal:"\u6700\u4F4E",none:"\u5173\u95ED"}},settings:{title:"\u8BBE\u7F6E",defaultAgent:"\u9ED8\u8BA4 Agent",defaultMode:"\u9ED8\u8BA4\u6743\u9650\u6A21\u5F0F",theme:"\u4E3B\u9898",themeAuto:"\u8DDF\u968F\u7CFB\u7EDF",themeMagpie:"\u8DDF\u968F Magpie",themeLight:"\u6D45\u8272",themeDark:"\u6DF1\u8272",sendKey:"\u53D1\u9001\u952E",sendEnter:"Enter \u53D1\u9001 / Shift+Enter \u6362\u884C",sendCtrl:"Ctrl+Enter \u53D1\u9001 / Enter \u6362\u884C",runningSend:"\u8FD0\u884C\u4E2D\u518D\u53D1\u9001",queue:"\u6392\u961F\uFF08\u53D1\u5B8C\u81EA\u52A8\u7EE7\u7EED\uFF09",steer:"\u63D2\u8BDD\uFF08\u7ACB\u5373\u6253\u65AD\u5F53\u524D\u601D\u8DEF\uFF09",steerHint:"\u63D2\u8BDD\u53EA\u5BF9\u652F\u6301\u7684 Agent \u751F\u6548\uFF08\u76EE\u524D\u662F Codex\uFF09\uFF1B\u5176\u4ED6 Agent \u4ECD\u4F1A\u6392\u961F\uFF0C\u8F93\u5165\u6846\u4E0B\u65B9\u4F1A\u63D0\u793A\u3002",defaultModeHint:"\u65B0\u5BF9\u8BDD\u4F7F\u7528\uFF1B\u6BCF\u4E2A Agent \u4F1A\u6362\u6210\u81EA\u5DF1\u6700\u63A5\u8FD1\u7684\u6A21\u5F0F\uFF08\u4F8B\u5982 OpenCode \u53EA\u6709 Plan / Build\uFF0CBuild \u4F1A\u76F4\u63A5\u6539\u6587\u4EF6\uFF09\u3002",thinking:"\u601D\u8003\u8FC7\u7A0B",showThinking:"\u663E\u793A Agent \u7684\u601D\u8003/\u63A8\u7406\u5185\u5BB9",idleClose:"\u7A7A\u95F2\u56DE\u6536",idleMinutes:"\u5206\u949F\u540E\u81EA\u52A8\u5173\u95ED\u7A7A\u95F2\u4F1A\u8BDD\uFF085\u2013240\uFF1B\u6700\u591A\u4FDD\u7559 3 \u4E2A\u7A7A\u95F2 Agent \u8FDB\u7A0B\uFF09",idleInvalid:"\u8BF7\u8F93\u5165 5 \u5230 240 \u4E4B\u95F4\u7684\u6574\u6570",versionLine:"\u7248\u672C v{ver} \xB7 PID {pid}",dataDir:"\u6570\u636E\u76EE\u5F55\uFF1A",failSave:"\u4FDD\u5B58\u5931\u8D25\uFF1A",providers:"Agent",providerOn:"\u53EF\u7528",providerOff:"\u5DF2\u7981\u7528",providerPending:"\u5C1A\u672A\u63A5\u5165",providerVerified:"\u5DF2\u9A8C\u8BC1",providerExperimental:"\u5B9E\u9A8C\u6027",providerPlanned:"\u672A\u63A5\u5165",providerModels:"{n} \u4E2A Model",providerRedetect:"\u91CD\u65B0\u68C0\u6D4B",providerCopyHint:"\u590D\u5236\u5B89\u88C5\u63D0\u793A",providerLaunchCmd:"\u81EA\u5B9A\u4E49\u542F\u52A8\uFF08\u9AD8\u7EA7\uFF09",providerLaunchExe:"\u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84\uFF08\u7559\u7A7A = \u81EA\u52A8\u67E5\u627E\uFF09",providerLaunchArgs:"\u9644\u52A0\u53C2\u6570\uFF08JSON \u6570\u7EC4\uFF09",providerLaunchArgsHint:'\u8FFD\u52A0\u5728\u5185\u7F6E\u53C2\u6570\u4E4B\u540E\uFF0C\u4F8B\u5982 ["--foo"]\uFF1B\u56DE\u8F66\u6216\u79BB\u5F00\u8F93\u5165\u6846\u65F6\u4FDD\u5B58\u3002\u65B0\u5BF9\u8BDD\u751F\u6548\u3002',providerArgsInvalid:'\u9700\u8981 JSON \u5B57\u7B26\u4E32\u6570\u7EC4\uFF0C\u4F8B\u5982 ["--foo"]',providerToggleFailed:"\u5207\u6362\u5931\u8D25\uFF0C\u5DF2\u6062\u590D\uFF1A"},palette:{aria:"\u547D\u4EE4\u9762\u677F",placeholder:"\u641C\u7D22\u5BF9\u8BDD\u3001\u9879\u76EE\u6216\u52A8\u4F5C\u2026",noMatch:"\u6CA1\u6709\u5339\u914D\u9879",hintAction:"\u52A8\u4F5C",hintThread:"\u5BF9\u8BDD",hintProject:"\u9879\u76EE",actNewThread:"\u65B0\u5EFA\u5BF9\u8BDD",actSettings:"\u6253\u5F00\u8BBE\u7F6E",actTheme:"\u5207\u6362\u4E3B\u9898",actChanges:"\u6253\u5F00\u6539\u52A8\u9762\u677F",actFiles:"\u6253\u5F00\u6587\u4EF6\u9762\u677F",actTerminal:"\u6253\u5F00\u7EC8\u7AEF\u9762\u677F",actImport:"\u5BFC\u5165\u5DF2\u6709\u5BF9\u8BDD\u2026",failNew:"\u65B0\u5EFA\u5931\u8D25\uFF1A"},panel:{changes:"\u6539\u52A8",files:"\u6587\u4EF6",terminal:"\u7EC8\u7AEF",closeTitle:"\u5173\u95ED\uFF08Ctrl+J\uFF09",pickProject:"\u5148\u9009\u4E00\u4E2A\u9879\u76EE",notGit:"\u8FD9\u4E2A\u9879\u76EE\u4E0D\u662F git \u4ED3\u5E93",clean:"\u5DE5\u4F5C\u533A\u5E72\u51C0",branch:"\u5F53\u524D\u5206\u652F",loadingDiff:"\u52A0\u8F7D diff\u2026",diffTooLarge:"diff \u8D85\u8FC7 1MB\uFF0C\u4E0D\u663E\u793A",discardTitle:"\u653E\u5F03\u6539\u52A8",discardUntracked:`\u653E\u5F03 {path} \u7684\u6539\u52A8\uFF1F -\u672A\u8DDF\u8E2A\u6587\u4EF6\u4F1A\u88AB\u79FB\u5230\u56DE\u6536\u76EE\u5F55\uFF08trash/discarded\uFF09\uFF0C\u4E0D\u4F1A\u76F4\u63A5\u5220\u9664\u3002`,discardTracked:"\u653E\u5F03 {path} \u7684\u6539\u52A8\uFF1F\u8BE5\u6587\u4EF6\u4F1A\u6062\u590D\u5230 git \u91CC\u7684\u7248\u672C\u3002",discardBtn:"\u653E\u5F03\u6539\u52A8",failDiscard:"\u653E\u5F03\u5931\u8D25\uFF1A",closePreview:"\u5173\u95ED\u9884\u89C8",reading:"\u8BFB\u53D6\u4E2D\u2026",binary:"\u4E8C\u8FDB\u5236\u6587\u4EF6\uFF0C\u4E0D\u9884\u89C8",tooLarge:"\u8D85\u8FC7 1MB\uFF0C\u4E0D\u9884\u89C8",gitKind:{modified:"\u6539",added:"\u589E",deleted:"\u5220",untracked:"\u65B0",renamed:"\u79FB"}},terminal:{new:"\u65B0\u5EFA\u7EC8\u7AEF",noTerm:"\u8FD8\u6CA1\u6709\u7EC8\u7AEF",closeTitle:"\u5173\u95ED\u7EC8\u7AEF",closeBody:"\u5173\u95ED\u300C{title}\u300D\uFF1F\u91CC\u9762\u8FD0\u884C\u7684\u8FDB\u7A0B\u4F1A\u88AB\u7ED3\u675F\u3002",closeOk:"\u5173\u95ED",simpleNote:"\u7B80\u5316\u7EC8\u7AEF\uFF08\u65E0\u4EA4\u4E92\u7A0B\u5E8F\u652F\u6301\uFF09",ended:"\uFF08\u7EC8\u7AEF\u5DF2\u7ED3\u675F\uFF09",failNew:"\u65B0\u5EFA\u7EC8\u7AEF\u5931\u8D25\uFF1A",failKill:"\u5173\u95ED\u5931\u8D25\uFF1A"},thread:{new:"\u65B0\u5BF9\u8BDD",info:"\u5BF9\u8BDD\u4FE1\u606F",agent:"Agent",model:"\u6A21\u578B",mode:"\u6A21\u5F0F",effort:"\u601D\u8003\u5F3A\u5EA6",sessionId:"\u4F1A\u8BDD ID",tokens:"\u7D2F\u8BA1 token",cost:"\u7D2F\u8BA1\u8D39\u7528",created:"\u521B\u5EFA\u4E8E",workdir:"\u5DE5\u4F5C\u76EE\u5F55",importedFrom:"\u5BFC\u5165\u81EA",sessionNone:"\uFF08\u672A\u5EFA\u7ACB\uFF09",tokensFmt:"{in} \u5165 / {out} \u51FA / {cache} \u7F13\u5B58"},timeline:{thinking:"\u601D\u8003 {s}s",todo:"\u5F85\u529E {done}/{total}",steer:"\u63D2\u8BDD",permAllowSession:"\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8",permDenied:"\u5DF2\u62D2\u7EDD",permAllowed:"\u5DF2\u5141\u8BB8",permCancelled:"\u5DF2\u53D6\u6D88",submitted:"\u5DF2\u63D0\u4EA4\uFF1A{ans}",turnError:"\u51FA\u9519\uFF1A{err}",unknownError:"\u672A\u77E5\u9519\u8BEF",interrupted:"\u5DF2\u6253\u65AD",filesChanged:"\u6539\u52A8 {n} \u4E2A\u6587\u4EF6 \u203A",editResend:"\u7F16\u8F91\u540E\u91CD\u53D1",tool:{read:"\u8BFB\u53D6",edit:"\u4FEE\u6539",write:"\u5199\u5165",bash:"\u8FD0\u884C",search:"\u641C\u7D22",glob:"\u641C\u7D22",web:"\u8054\u7F51",task:"\u5B50\u4EFB\u52A1",mcp:"\u5DE5\u5177",todo:"\u5F85\u529E",other:"\u5DE5\u5177",processing:"\u5904\u7406"},toolSummary:"\u5DF2\u6267\u884C {n} \u6B65 \xB7 {parts}",toolRunning:"\u6B63\u5728{kind}\uFF1A{title}",showAllLines:"\u663E\u793A\u5168\u90E8 {n} \u884C",diffClip:"\uFF08\u53EA\u663E\u793A\u524D {n} \u884C\uFF09"},api:{requestFailed:"\u8BF7\u6C42\u5931\u8D25",bad_params:"\u53C2\u6570\u4E0D\u6B63\u786E",not_found:"\u672A\u627E\u5230",busy:"\u6B63\u5FD9\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5",bad_path:"\u8DEF\u5F84\u65E0\u6548",connClosed:"\u8FDE\u63A5\u4E2D\u65AD",notConnected:"\u8FDE\u63A5\u672A\u5EFA\u7ACB",timeout:"\u8BF7\u6C42\u8D85\u65F6"}},en:{app:{title:"Agent Console",subtitle:"Create or select a project in the sidebar"},common:{cancel:"Cancel",ok:"OK",save:"Save",add:"Add",browse:"Browse\u2026",more:"More",copy:"Copy",copied:"Copied",copyPath:"Copy path",copiedPath:"Path copied",search:"Search",settings:"Settings",remove:"Remove",close:"Close",retry:"Retry",details:"Details \u203A",submit:"Submit",other:"Other\u2026",default:"Default",done:"Done",loading:"Loading\u2026",send:"Send",stop:"Stop",refresh:"Refresh",rename:"Rename",delete:"Delete",discard:"Discard",notInstalled:" (not installed)",notDetected:" (not detected)",current:" (current)",messages:" msgs",imported:" \xB7 imported",justNow:"Just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago"},boot:{connecting:"Connecting\u2026",serviceDown:"Local service is not running",retry:"Retry",reconnecting:"Connection lost. Reconnecting\u2026",starting:"Starting local service\u2026",reopening:"The local service restarted. Reconnecting\u2026"},topbar:{pickThread:"Select a conversation",sidebar:"Sidebar (Ctrl+B)",clickRename:"Click to rename",waitAuth:"Waiting for approval",running:"Running {s}s",error:"Error",closedResume:"Closed \xB7 send a message to resume",threadInfo:"Conversation info",panelChanges:"Changes (Ctrl+J)",panelFiles:"Files",panelTerminal:"Terminal"},sidebar:{newProject:"New project",filterPlaceholder:"Filter conversations",searchTitle:"Search (Ctrl+K)",noProjectsTitle:"No projects yet",noProjectsSub:"A project maps to a folder on this machine.",newThread:"New conversation",projectMenu:"Project menu",showAll:"Show all {n}",noThreads:"No conversations yet",rename:"Rename",pin:"Pin",unpin:"Unpin",archive:"Archive",unarchive:"Unarchive",exportMd:"Export Markdown",deleteThread:"Delete conversation",deleteThreadBody:"Move \u201C{title}\u201D to trash?",importHist:"Import existing conversations\u2026",openExplorer:"Open in Explorer",showArchived:"Show archived",hideArchived:"Hide archived",archivedN:"{n} archived",archivedHint:"Archived \u2014 see the bottom of the project list",unarchived:"Unarchived",exportSaved:"Exported to {path}",removeProject:"Remove project",removeProjectBody:"Remove \u201C{name}\u201D from the list? Conversations move to trash (files stay on disk).",renameProject:"Rename project",projectName:"Project name",newProjectDlg:"New project",dirLabel:"Project folder (must already exist)",dirMissing:"Folder does not exist",notDir:"This path is a file, not a folder",dirOk:"\u2713 Folder OK \u2014 name comes from the folder",recent:"Recent",pickFolderUnsupported:"Folder picker is not available \u2014 type the path",pickFolderFailed:"Could not open folder picker",importTitle:"Import conversations \u2014 {name}",scanning:"Scanning local history\u2026",importEmpty:"No history found for this project folder.",importing:"Importing\u2026",importN:"Import {n} conversation(s)",importedN:"Imported {n} conversation(s)",failNewThread:"Could not create conversation: ",failRename:"Rename failed: ",failAddProject:"Could not add project: ",failImportList:"Could not read history: ",failImport:"Import failed: ",failExport:"Export failed: "},chat:{newInProject:"New conversation in {name}",emptyHint:"No messages yet \u2014 type below to start.",jumpBottom:"Jump to bottom",emptyPlaceholder:"Describe a task \u2014 Enter to send",autoNewThread:"A new conversation will be created",failSend:"Send failed: ",pickProjectTitle:"Pick a project",pickProjectSub:"Choose a project in the sidebar, or create one, to start a conversation."},composer:{waitPerm:"Waiting for your approval above",queuePlaceholder:"Queue a message (Ctrl+Enter to steer)",queuePlaceholderNoSteer:"Add to the task \u2014 Enter queues it\u2026",steerUnsupported:"{agent} can't steer: messages sent while it runs are queued and sent after this turn.",queuedToast:"Queued \u2014 sends after this turn",steeredToast:"Steered",inputPlaceholder:"Message\u2026",bypassWarn:"Bypass: the agent will not ask for permission.",imagesByPath:"{agent} can't see images directly: it gets the image's file path instead (it can open it with its file tools).",agentModel:"Agent & model",agentLocked:"Agent (locked after first message)",agent:"Agent",model:"Model",searchModel:"Search",searchAllModels:"Search all models\u2026",providers:"Providers",agentLockedHint:"The agent can't change after the conversation starts. Start a new conversation to use another agent.",providersLoading:"Detecting agents\u2026",moreModels:"{n} more models \u2014 use search above",pickModel:"Choose model",noModelMatch:"No matching models",defaultModel:"Default",defaultEffort:"Default",defaultEffortNamed:"Default ({level})",effortTitle:"Reasoning effort",modeTitle:"Permission mode",attachTitle:"Attachments (images / text)",failSwitchAgent:"Could not switch agent: ",failSend:"Send failed: ",failUpload:"Upload failed: ",uploadFailed:"Upload failed",steerTag:"Steer",cursorAutoReview:"Auto accept permission prompts",cursorFastOff:"Off",cursorFastOn:"Fast",slashGroupCommand:"Commands",slashGroupSkill:"Skills",slashNoCommands:"This agent has no slash commands",slashLoading:"Loading commands\u2026",mode:{plan:{label:"Plan Mode",desc:"Analyze the codebase without running tools or edits"},default:{label:"Always Ask",desc:"Ask permission the first time a tool is used"},acceptEdits:{label:"Accept File Edits",desc:"Auto-approve edit tools without prompting"},bypass:{label:"Bypass",desc:"Skip all permission prompts (use with caution)"},cursorAgent:{label:"Agent",desc:"Full agent: tools and edits"},cursorPlan:{label:"Plan",desc:"Read-only planning and analysis"},cursorAsk:{label:"Ask",desc:"Q&A style explanations (read-only)"}},agentMode:{},effort:{low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max",minimal:"Minimal",none:"Off"}},settings:{title:"Settings",defaultAgent:"Default agent",defaultMode:"Default permission mode",theme:"Theme",themeAuto:"System",themeMagpie:"Follow Magpie",themeLight:"Light",themeDark:"Dark",sendKey:"Send shortcut",sendEnter:"Enter sends / Shift+Enter newline",sendCtrl:"Ctrl+Enter sends / Enter newline",runningSend:"While running",queue:"Queue (run after current turn)",steer:"Steer (interrupt now)",steerHint:"Steer only works for agents that support it (Codex today); other agents still queue, and the composer says so.",defaultModeHint:"For new conversations. Each agent maps it to its own nearest mode (OpenCode only has Plan / Build, and Build edits without asking).",thinking:"Reasoning",showThinking:"Show agent reasoning/thinking",idleClose:"Idle cleanup",idleMinutes:"minutes before closing idle sessions (5\u2013240; at most 3 idle agent processes are kept)",idleInvalid:"Enter a whole number from 5 to 240",versionLine:"Version v{ver} \xB7 PID {pid}",dataDir:"Data: ",failSave:"Could not save: ",providers:"Providers",providerOn:"Available",providerOff:"Disabled",providerPending:"Not wired yet",providerVerified:"Verified",providerExperimental:"Experimental",providerPlanned:"Planned",providerModels:"{n} models",providerRedetect:"Re-detect",providerCopyHint:"Copy install hint",providerLaunchCmd:"Custom launch (advanced)",providerLaunchExe:"Executable path (empty = find it automatically)",providerLaunchArgs:"Extra args (JSON array)",providerLaunchArgsHint:'Added after the built-in arguments, e.g. ["--foo"]. Saved on Enter or when you leave the field. Applies to new sessions.',providerArgsInvalid:'Needs a JSON array of strings, e.g. ["--foo"]',providerToggleFailed:"Could not switch it; reverted: "},palette:{aria:"Command palette",placeholder:"Search conversations, projects, actions\u2026",noMatch:"No matches",hintAction:"Action",hintThread:"Conversation",hintProject:"Project",actNewThread:"New conversation",actSettings:"Open settings",actTheme:"Toggle theme",actChanges:"Open changes panel",actFiles:"Open files panel",actTerminal:"Open terminal panel",actImport:"Import existing conversations\u2026",failNew:"Could not create: "},panel:{changes:"Changes",files:"Files",terminal:"Terminal",closeTitle:"Close (Ctrl+J)",pickProject:"Select a project first",notGit:"This folder is not a git repository",clean:"Working tree clean",branch:"Current branch",loadingDiff:"Loading diff\u2026",diffTooLarge:"Diff is over 1MB \u2014 not shown",discardTitle:"Discard changes",discardUntracked:`Discard changes to {path}? -Untracked files move to trash/discarded.`,discardTracked:"Discard changes to {path}? The file reverts to the git version.",discardBtn:"Discard",failDiscard:"Discard failed: ",closePreview:"Close preview",reading:"Reading\u2026",binary:"Binary file \u2014 no preview",tooLarge:"Over 1MB \u2014 no preview",gitKind:{modified:"M",added:"A",deleted:"D",untracked:"?",renamed:"R"}},terminal:{new:"New terminal",noTerm:"No terminals yet",closeTitle:"Close terminal",closeBody:"Close \u201C{title}\u201D? Running processes will be killed.",closeOk:"Close",simpleNote:"Simple terminal (no full TTY programs)",ended:"(Terminal ended)",failNew:"Could not create terminal: ",failKill:"Could not close: "},thread:{new:"New chat",info:"Conversation info",agent:"Agent",model:"Model",mode:"Mode",effort:"Effort",sessionId:"Session ID",tokens:"Total tokens",cost:"Total cost",created:"Created",workdir:"Working directory",importedFrom:"Imported from",sessionNone:"(none)",tokensFmt:"{in} in / {out} out / {cache} cache"},timeline:{thinking:"Thinking {s}s",todo:"Todos {done}/{total}",steer:"Steer",permAllowSession:"Allowed for this chat",permDenied:"Denied",permAllowed:"Allowed",permCancelled:"Cancelled",submitted:"Submitted: {ans}",turnError:"Error: {err}",unknownError:"Unknown error",interrupted:"Interrupted",filesChanged:"{n} file(s) changed \u203A",editResend:"Edit and resend",tool:{read:"Read",edit:"Edit",write:"Write",bash:"Run",search:"Search",glob:"Search",web:"Web",task:"Subtask",mcp:"Tool",todo:"Todo",other:"Tool",processing:"Working"},toolSummary:"{n} step(s) \xB7 {parts}",toolRunning:"{kind}: {title}",showAllLines:"Show all {n} lines",diffClip:"(first {n} lines only)"},api:{requestFailed:"Request failed",bad_params:"Invalid parameters",not_found:"Not found",busy:"Busy \u2014 try again later",bad_path:"Invalid path",connClosed:"Connection lost",notConnected:"Not connected",timeout:"Request timed out"}}}});function GE(e){let t=String(e??"").trim().toLowerCase();return t?t==="zh"||t.startsWith("zh-")?"zh":"en":GD()}function GD(){let e=typeof navigator<"u"?navigator.language:"";return GE(e||"zh")}function YE(e){let t=new URLSearchParams(e).get("lang");Da=GE(t);let i=Da==="zh"?"zh-CN":"en";return typeof document<"u"&&(document.documentElement.lang=i),Da}function Rd(){return Da}function Od(){return Da==="zh"?"zh-CN":"en-US"}function $E(e,t){let i=t.split("."),n=e;for(let s of i){if(typeof n!="object"||n==null||!(s in n))return;n=n[s]}return typeof n=="string"?n:void 0}function y(e){return $E(y_[Da],e)??$E(y_.en,e)??e}function Ce(e,t){let i=y(e);for(let[n,s]of Object.entries(t))i=i.replaceAll(`{${n}}`,String(s));return i}function ct(e){let t=e,i=t?.code;if(i){let s=y(`api.${i}`);if(s!==`api.${i}`)return s}let n=String(t?.message??e);return La(n)}function La(e){if(Da==="zh")return e;if(e==="\u540E\u53F0\u5DF2\u91CD\u542F\uFF0C\u672C\u8F6E\u5DF2\u4E2D\u65AD")return"Daemon restarted \u2014 this turn was interrupted";if(e.startsWith("\u4F1A\u8BDD\u542F\u52A8\u5931\u8D25\uFF1A"))return"Session start failed: "+e.slice(7);if(e.startsWith("\u53D1\u9001\u5931\u8D25\uFF1A"))return"Send failed: "+e.slice(5);if(e==="Agent \u8FDB\u7A0B\u610F\u5916\u9000\u51FA")return"Agent process exited unexpectedly";let t=e.match(/^附件不存在或已失效((.+)),请重新上传$/);if(t)return`Attachment missing or expired (${t[1]}) \u2014 upload again`;let i=e.match(/^(.+) 不能直接看图片(它的 ACP 初始化未声明支持图片输入),已改为发送图片的文件路径:(.+)$/s);return i?`${i[1]} can't see images directly (its ACP initialize doesn't advertise image input); sent the image file path instead: ${i[2]}`:e.startsWith("\u9644\u4EF6\u95EE\u9898\uFF1A")?"Attachment issue: "+e.slice(5):e}function Dd(e,t){return t&&(e==="\u65B0\u5BF9\u8BDD"||e==="New chat")?y("thread.new"):e}var Da,Ci=le(()=>{WE();Da="zh"});var Ld,jE=le(()=>{Ci();Ld=class{constructor(t,i="zh"){de(this,"token",t);de(this,"lang",i);de(this,"ws",null);de(this,"seq",0);de(this,"pending",new Map);de(this,"subs",new Map);de(this,"binHandlers",[]);de(this,"stateListeners",new Set);de(this,"state","connecting");de(this,"retry",0);de(this,"closed",!1);de(this,"helloOk",null);de(this,"helloWaiters",[])}onState(t){return this.stateListeners.add(t),t(this.state),()=>this.stateListeners.delete(t)}getState(){return this.state}setState(t){this.state=t;for(let i of this.stateListeners)i(t)}connect(){if(this.closed)return;this.setState(this.retry===0?"connecting":"reconnecting");let t=new WebSocket(`ws://${location.host}/ws`);t.binaryType="arraybuffer",this.ws=t,t.onopen=()=>{t.send(JSON.stringify({t:"hello",token:this.token,v:1,lang:this.lang}))},t.onmessage=i=>{if(typeof i.data!="string"){this.onBinary(new Uint8Array(i.data));return}let n;try{n=JSON.parse(i.data)}catch{return}if(n.t==="hello.ok"){this.retry=0,this.helloOk=n,this.setState("open");let s=this.helloWaiters.splice(0);for(let r of s)r(n);for(let[r,a]of this.subs)this.call("sub.add",{ch:r,afterSeq:a.afterSeq?.()}).catch(()=>{});return}if(n.t==="res"){let s=n.id,r=this.pending.get(s);if(r)if(this.pending.delete(s),clearTimeout(r.timer),n.ok)r.res(n.r);else{let a=n.e,o=new Error(a?.message??y("api.requestFailed"));o.code=a?.code,r.rej(o)}return}if(n.t==="evt"){this.subs.get(n.ch)?.handler(n.ch,n.d);return}},t.onclose=()=>{this.ws=null;for(let[n,s]of this.pending)clearTimeout(s.timer),s.rej(new Error(y("api.connClosed"))),this.pending.delete(n);if(this.closed)return;this.retry++;let i=Math.min(1e3*Math.pow(2,this.retry-1),1e4);this.setState(this.retry>20?"down":"reconnecting"),setTimeout(()=>this.connect(),i)},t.onerror=()=>{}}waitHello(){return this.helloOk?Promise.resolve(this.helloOk):new Promise(t=>this.helloWaiters.push(t))}call(t,i,n=6e4){return new Promise((s,r)=>{let a=this.ws;if(!a||a.readyState!==WebSocket.OPEN){r(new Error(y("api.notConnected")));return}let o=++this.seq,l=setTimeout(()=>{this.pending.delete(o),r(new Error(y("api.timeout")))},n);this.pending.set(o,{res:s,rej:r,timer:l}),a.send(JSON.stringify({t:"req",id:o,m:t,p:i??{}}))})}subscribe(t,i,n){return this.subs.set(t,{handler:i,afterSeq:n}),this.state==="open"&&this.call("sub.add",{ch:t,afterSeq:n?.()}).catch(()=>{}),()=>{this.subs.delete(t),this.state==="open"&&this.call("sub.remove",{ch:t}).catch(()=>{})}}onBinaryFrame(t){return this.binHandlers.push(t),()=>{this.binHandlers=this.binHandlers.filter(i=>i!==t)}}onBinary(t){if(t.length<3)return;let i=t[0],n=t[1]<<8|t[2];for(let s of this.binHandlers)s(i,n,t.subarray(3))}sendBinary(t,i,n){let s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return;let r=new Uint8Array(3+n.length);r[0]=t,r[1]=i>>8&255,r[2]=i&255,r.set(n,3),s.send(r)}ping(){try{this.ws?.send(JSON.stringify({t:"ping"}))}catch{}}close(){this.closed=!0,this.ws?.close()}}});var VE,XE,S_=le(()=>{VE=e=>{let t,i=new Set,n=(c,u)=>{let h=typeof c=="function"?c(t):c;if(!Object.is(h,t)){let d=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),i.forEach(f=>f(t,d))}},s=()=>t,o={setState:n,getState:s,getInitialState:()=>l,subscribe:c=>(i.add(c),()=>i.delete(c))},l=t=e(n,s,o);return o},XE=(e=>e?VE(e):VE)});function jD(e,t=YD){let i=Bd.default.useSyncExternalStore(e.subscribe,Bd.default.useCallback(()=>t(e.getState()),[e,t]),()=>t(e.getInitialState()));return Bd.default.useDebugValue(i),i}var Bd,YD,ZE,Ss,QE=le(()=>{Bd=ae(Nt(),1);S_();YD=e=>e;ZE=e=>{let t=XE(e),i=n=>jD(t,n);return Object.assign(i,t),i},Ss=(e=>e?ZE(e):ZE)});var ul=le(()=>{S_();QE()});var ws,qc=le(()=>{ul();ws=Ss(e=>({state:"connecting",version:null,set:t=>e(t)}))});function Ba(e,t=window.innerWidth){if(t<900)return E_;let i=e.sbHidden?0:e.sidebarWidth;return hl(t-i-ex-JE,qr,E_)}function dl(e,t=window.innerWidth){if(t<760)return w_;let i=e.panelOpen?e.panelWidth:0;return hl(t-i-ex-JE,Ia,w_)}function Id(e,t=window.innerWidth){let i=hl(e.sidebarWidth,Ia,dl(e,t)),n=hl(e.panelWidth,qr,Ba({...e,sidebarWidth:i},t));return i=hl(i,Ia,dl({...e,sidebarWidth:i,panelWidth:n},t)),n=hl(n,qr,Ba({...e,sidebarWidth:i,panelWidth:n},t)),{sidebarWidth:i,panelWidth:n}}var JE,ex,hl,x_=le(()=>{dn();JE=300,ex=10,hl=(e,t,i)=>Math.max(t,Math.min(i,e))});function za(e,t){let i=e().ws;i&&i.call("settings.set",{patch:t}).catch(()=>{})}var Ia,w_,qr,E_,C_,fe,dn=le(()=>{ul();x_();Ia=200,w_=360,qr=320,E_=900,C_=(e,t,i)=>Math.max(t,Math.min(i,e));fe=Ss((e,t)=>({ws:null,sidebarWidth:248,sbHidden:!1,sbOpen:!1,panelOpen:!1,panelTab:"changes",panelWidth:440,collapsed:{},currentProjectId:null,currentThreadId:null,bind:i=>e({ws:i}),hydrate:i=>{let n={};for(let a of i.collapsedProjects??[])n[a]=!0;let s={sidebarWidth:i.sidebarWidth??248,panelWidth:i.panel?.width??440,panelOpen:i.panel?.open??!1,sbHidden:!1},r=Id(s);e({sidebarWidth:r.sidebarWidth,panelOpen:s.panelOpen,panelTab:i.panel?.tab??"changes",panelWidth:r.panelWidth,collapsed:n,currentProjectId:i.lastProjectId??null,currentThreadId:i.lastThreadId??null})},setSidebarWidth:i=>{let n=t(),s=dl(n);i=C_(Math.round(i),Ia,s),e({sidebarWidth:i}),za(t,{sidebarWidth:i})},setPanelWidth:i=>{let n=t(),s=Ba(n);i=C_(Math.round(i),qr,s),e({panelWidth:i}),za(t,{panel:{open:t().panelOpen,tab:t().panelTab,width:i}})},openPanel:i=>{let n=i??t().panelTab,s=t(),r=C_(s.panelWidth,qr,Ba({...s,panelOpen:!0}));e({panelOpen:!0,panelTab:n,panelWidth:r}),za(t,{panel:{open:!0,tab:n,width:r}})},closePanel:()=>{e({panelOpen:!1}),za(t,{panel:{open:!1,tab:t().panelTab,width:t().panelWidth}})},setPanelTab:i=>{e({panelTab:i}),za(t,{panel:{open:t().panelOpen,tab:i,width:t().panelWidth}})},toggleSidebarHidden:()=>e(i=>({sbHidden:!i.sbHidden})),setSbOpen:i=>e({sbOpen:i}),toggleCollapsed:i=>{let n={...t().collapsed};n[i]?delete n[i]:n[i]=!0,e({collapsed:n}),za(t,{collapsedProjects:Object.keys(n)})},select:(i,n)=>{e({currentProjectId:i,currentThreadId:n,sbOpen:!1}),za(t,{lastProjectId:i,lastThreadId:n})},reconcileSelection:(i,n)=>{let{currentProjectId:s,currentThreadId:r}=t();if(i.length===0){(s||r)&&t().select(null,null);return}let a=s;(!a||!i.some(l=>l.id===a))&&(a=null);let o=r;if(o){let l=n.find(c=>c.id===o);!l||!i.some(c=>c.id===l.projectId)||a&&l.projectId!==a?o=null:a||(a=l.projectId)}(a!==s||o!==r)&&t().select(a,o)}}))});async function fl(){let e="claude";try{e=(await ut.getState().ws.call("settings.get")).defaultProvider??"claude"}catch{}let t=ut.getState().providers;return t.length?t.find(i=>i.id===e&&tx(i))?.id??t.find(i=>tx(i))?.id??e:e}function tx(e){return e.enabled===!1||!e.available||e.status==="planned"?!1:e.status==="verified"||e.status==="experimental"?!0:e.ready!==!1}var ut,jn=le(()=>{ul();dn();ut=Ss((e,t)=>({ws:null,loaded:!1,projects:[],threads:[],providers:[],bind:async i=>{if(t().ws===i&&t().loaded)return;e({ws:i}),i.subscribe("sidebar",(l,c)=>{let u=c;!u||typeof u!="object"||(u.type==="project.upsert"?t().upsertProject(u.project):u.type==="project.remove"?(e({projects:t().projects.filter(h=>h.id!==u.id)}),fe.getState().reconcileSelection(t().projects,t().threads)):u.type==="thread.upsert"?t().upsertThread(u.thread):u.type==="thread.remove"&&(e({threads:t().threads.filter(h=>h.id!==u.id)}),fe.getState().reconcileSelection(t().projects,t().threads)))}),i.call("providers.list").then(l=>e({providers:l})).catch(()=>{});let[n,s]=await Promise.all([i.call("projects.list"),i.call("threads.list")]),r=t(),a=new Map(n.map(l=>[l.id,l]));for(let l of r.projects)a.set(l.id,l);let o=new Map(s.map(l=>[l.id,l]));for(let l of r.threads)o.set(l.id,l);e({projects:[...a.values()].sort((l,c)=>l.createdAt-c.createdAt),threads:[...o.values()],loaded:!0}),fe.getState().reconcileSelection(t().projects,t().threads)},upsertProject:i=>{let n=t().projects.filter(s=>s.id!==i.id);e({projects:[...n,i].sort((s,r)=>s.createdAt-r.createdAt)})},upsertThread:i=>{let n=t().threads.filter(s=>s.id!==i.id);e({threads:[...n,i]})}}))});var nx=me(zd=>{"use strict";var VD=Symbol.for("react.transitional.element"),XD=Symbol.for("react.fragment");function ix(e,t,i){var n=null;if(i!==void 0&&(n=""+i),t.key!==void 0&&(n=""+t.key),"key"in t){i={};for(var s in t)s!=="key"&&(i[s]=t[s])}else i=t;return t=i.ref,{$$typeof:VD,type:e,key:n,ref:t!==void 0?t:null,props:i}}zd.Fragment=XD;zd.jsx=ix;zd.jsxs=ix});var ke=me((mU,sx)=>{"use strict";sx.exports=nx()});function ax(e){let[t,i]=(0,xt.useState)(()=>window.matchMedia?.(e).matches??!1);return(0,xt.useEffect)(()=>{let n=window.matchMedia?.(e);if(!n)return;let s=()=>i(n.matches);return n.addEventListener?.("change",s),s(),()=>n.removeEventListener?.("change",s)},[e]),t}function ox(e,t,i){let n=(0,xt.useRef)(0),s=(0,xt.useRef)(0),[r,a]=(0,xt.useState)(!1),o=(0,xt.useCallback)(l=>{l.preventDefault(),n.current=l.clientX,s.current=e(),a(!0),document.body.classList.add("col-drag");let c=h=>t(s.current,h.clientX-n.current),u=()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",u),document.body.classList.remove("col-drag"),a(!1),i()};window.addEventListener("pointermove",c),window.addEventListener("pointerup",u)},[e,t,i]);return{drag:r,down:o}}function lx({sidebar:e,topbar:t,children:i,panel:n}){let s=fe(),r=ax("(max-width: 759px)"),a=ax("(max-width: 899px)"),o=(0,xt.useRef)(!1),l=(0,xt.useRef)(!1),c=ox((0,xt.useCallback)(()=>fe.getState().sidebarWidth,[]),(0,xt.useCallback)((d,f)=>{o.current=!0;let p=fe.getState(),_=dl(p);fe.setState({sidebarWidth:rx(Math.round(d+f),Ia,_)})},[]),(0,xt.useCallback)(()=>{o.current&&(o.current=!1,fe.getState().setSidebarWidth(fe.getState().sidebarWidth))},[])),u=ox((0,xt.useCallback)(()=>fe.getState().panelWidth,[]),(0,xt.useCallback)((d,f)=>{l.current=!0;let p=fe.getState(),_=Ba(p);fe.setState({panelWidth:rx(Math.round(d-f),qr,_)})},[]),(0,xt.useCallback)(()=>{l.current&&(l.current=!1,fe.getState().setPanelWidth(fe.getState().panelWidth))},[]));(0,xt.useEffect)(()=>{let d=f=>{if(!(f.ctrlKey||f.metaKey))return;let p=f.key.toLowerCase();if(p==="b"){f.preventDefault();let _=fe.getState();window.matchMedia("(max-width: 759px)").matches?_.setSbOpen(!_.sbOpen):_.toggleSidebarHidden()}else if(p==="j"){f.preventDefault();let _=fe.getState();_.panelOpen?_.closePanel():_.openPanel()}};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[]),(0,xt.useEffect)(()=>{document.documentElement.style.setProperty("--sb-w",`${s.sidebarWidth}px`)},[s.sidebarWidth]),(0,xt.useEffect)(()=>{document.documentElement.style.setProperty("--pn-w",`${s.panelWidth}px`)},[s.panelWidth]),(0,xt.useEffect)(()=>{let d=()=>{let f=fe.getState(),p=Id(f);p.sidebarWidth!==f.sidebarWidth&&fe.getState().setSidebarWidth(p.sidebarWidth),p.panelWidth!==f.panelWidth&&fe.getState().setPanelWidth(p.panelWidth)};return window.addEventListener("resize",d),d(),()=>window.removeEventListener("resize",d)},[]);let h=s.sbOpen||s.panelOpen&&a;return(0,Zs.jsxs)("div",{className:"app",children:[(0,Zs.jsx)("aside",{className:`sidebar${s.sbHidden&&!r?" w-hide":""}${s.sbOpen?" open":""}`,children:e}),(0,Zs.jsx)("div",{className:`rs rs-l${c.drag?" drag":""}`,onPointerDown:c.down}),(0,Zs.jsxs)("main",{className:"main",children:[t,i]}),(0,Zs.jsx)("div",{className:`rs rs-r${u.drag?" drag":""}`,onPointerDown:u.down}),(0,Zs.jsx)("section",{className:`panel${s.panelOpen?" open":" w-hide"}`,"aria-hidden":!s.panelOpen,children:n}),(0,Zs.jsx)("div",{className:`scrim${h?" show":""}`,onClick:()=>{fe.getState().setSbOpen(!1),fe.getState().panelOpen&&a&&fe.getState().closePanel()}})]})}var xt,Zs,rx,cx=le(()=>{xt=ae(Nt(),1);dn();x_();Zs=ae(ke(),1),rx=(e,t,i)=>Math.max(t,Math.min(i,e))});function Mn(e){return!!e.isComposing||e.keyCode===229}var pl=le(()=>{});function k_(e,t=Date.now()){let i=Math.max(0,t-e),n=Math.floor(i/6e4);if(n<1)return y("common.justNow");if(n<60)return Ce("common.minutesAgo",{n});let s=Math.floor(n/60);if(s<24)return Ce("common.hoursAgo",{n:s});let r=Math.floor(s/24);if(r<7)return Ce("common.daysAgo",{n:r});let a=new Date(e),o=Od();return Rd()==="zh"?`${a.getMonth()+1}/${a.getDate()}`:a.toLocaleDateString(o,{month:"short",day:"numeric"})}function ml(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Pd(e){return`$${e.toFixed(2)}`}function T_(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60?` ${t%60}s`:""}`}var Ud=le(()=>{Ci()});function Kc({x:e,y:t,items:i,onClose:n}){let s=(0,Qs.useRef)(null),[r,a]=(0,Qs.useState)({left:e,top:t});return(0,Qs.useLayoutEffect)(()=>{let o=s.current;if(!o)return;let l=o.getBoundingClientRect(),{left:c,top:u}=r;c+l.width>window.innerWidth-8&&(c=Math.max(8,window.innerWidth-l.width-8)),u+l.height>window.innerHeight-8&&(u=Math.max(8,window.innerHeight-l.height-8)),(c!==r.left||u!==r.top)&&a({left:c,top:u})},[e,t]),(0,Qs.useEffect)(()=>{let o=c=>{s.current&&!s.current.contains(c.target)&&n()},l=c=>{c.key==="Escape"&&(c.stopPropagation(),n())};return window.addEventListener("pointerdown",o,!0),window.addEventListener("keydown",l,!0),()=>{window.removeEventListener("pointerdown",o,!0),window.removeEventListener("keydown",l,!0)}},[n]),(0,ux.createPortal)((0,Kr.jsx)("div",{ref:s,className:"menu",style:r,role:"menu",children:i.map((o,l)=>o.kind==="sep"?(0,Kr.jsx)("div",{className:"msep"},l):o.kind==="label"?(0,Kr.jsx)("div",{className:"mlabel",children:o.text},l):(0,Kr.jsxs)("button",{className:`mi${o.danger?" danger":""}`,disabled:o.disabled,role:"menuitem",onClick:()=>{n(),o.onClick()},children:[(0,Kr.jsx)("span",{children:o.label}),o.checked&&(0,Kr.jsx)("span",{className:"mi-check",children:"\u2713"})]},l))}),document.body)}function Wc(){let[e,t]=(0,Qs.useState)(null);return[e,n=>{n.preventDefault(),n.stopPropagation(),t({x:n.clientX,y:n.clientY})},()=>t(null)]}var Qs,ux,Kr,N_=le(()=>{Qs=ae(Nt(),1),ux=ae(oa(),1),Kr=ae(ke(),1)});function Es({title:e,children:t,footer:i,onClose:n,wide:s}){return(0,hx.useEffect)(()=>{let r=a=>{a.key==="Escape"&&!document.querySelector("[data-select-menu]")&&(a.stopPropagation(),n())};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[n]),(0,dx.createPortal)((0,Zi.jsx)("div",{className:"dlg-scrim",onPointerDown:r=>{r.target===r.currentTarget&&n()},children:(0,Zi.jsxs)("div",{className:"dlg",style:s?{width:560}:void 0,role:"dialog","aria-label":e,children:[(0,Zi.jsx)("div",{className:"dlg-title",children:e}),(0,Zi.jsx)("div",{className:"dlg-body",children:t}),i&&(0,Zi.jsx)("div",{className:"dlg-foot",children:i})]})}),document.body)}function gl({title:e,body:t,okLabel:i,danger:n,onOk:s,onClose:r}){let a=i??y("common.ok");return(0,Zi.jsx)(Es,{title:e,onClose:r,footer:(0,Zi.jsxs)(Zi.Fragment,{children:[(0,Zi.jsx)("button",{className:"btn ghost",onClick:r,children:y("common.cancel")}),(0,Zi.jsx)("button",{className:`btn${n?" danger":" primary"}`,onClick:()=>{r(),s()},children:a})]}),children:(0,Zi.jsx)("div",{className:"dlg-hint",style:{fontSize:"var(--fs-m)",color:"var(--fg)"},children:t})})}var hx,dx,Zi,_l=le(()=>{hx=ae(Nt(),1),dx=ae(oa(),1);Ci();Zi=ae(ke(),1)});function ye({name:e,size:t=16}){let i=ZD[e];return i?(0,A_.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:QD.has(e)?"currentColor":"none",stroke:"currentColor",strokeWidth:JD.has(e)?"2.2":"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,A_.jsx)("path",{d:i})}):null}var A_,ZD,QD,JD,Wr=le(()=>{A_=ae(ke(),1),ZD={plus:"M12 5v14M5 12h14",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm10 17-4.5-4.5",caret:"M9 6l6 6-6 6",dots:"M5 12h.01M12 12h.01M19 12h.01",pin:"M9 4h6l1 7 3 3v2H5v-2l3-3 1-7Zm3 12v4",send:"M4 12 20 4l-4 8 4 8-16-8Zm0 0h8",stop:"M7 7h10v10H7z",attach:"M8 12l6-6a3.5 3.5 0 0 1 5 5l-7 7a5 5 0 0 1-7-7l6-6",menu:"M4 6h16M4 12h16M4 18h16",changes:"M7 4v13m0 0a3 3 0 1 0 .01 0M7 17a3 3 0 1 1-.01 0M17 7v13m0-13a3 3 0 1 0 .01 0M17 7a3 3 0 1 1-.01 0",files:"M4 4h6l2 3h8v13H4V4Z",term:"M4 5h16v14H4zM7 9l3 3-3 3m5 0h5",x:"M6 6l12 12M18 6 6 18",refresh:"M20 11a8 8 0 1 0-2.3 6.3M20 5v6h-6",copy:"M8 8h11v12H8zM5 16V4h11",check:"M5 13l4 4L19 7",gauge:"M5.6 18.4a9 9 0 1 1 12.8 0M12 13l3.5-3.5M12 13h.01",arrowUp:"M12 19V5m-6 6 6-6 6 6",stopFill:"M8 8h8v8H8z",shield:"M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3z",zap:"M13 2L4 14h7l-1 8 9-12h-7l1-8z",settings:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"},QD=new Set(["stopFill"]),JD=new Set(["arrowUp"])});function px(){let e=fx(t=>t.list);return e.length===0?null:(0,M_.jsx)("div",{className:"toasts",children:e.map(t=>(0,M_.jsx)("div",{className:`toast${t.err?" err":""}`,children:t.text},t.id))})}var M_,eL,fx,Te,Vn=le(()=>{ul();M_=ae(ke(),1),eL=0,fx=Ss(e=>({list:[],push:(t,i)=>{let n=++eL;e(s=>({list:[...s.list,{id:n,text:t,err:i}]})),setTimeout(()=>e(s=>({list:s.list.filter(r=>r.id!==n)})),3500)}})),Te=(e,t=!1)=>fx.getState().push(e,t)});function tL(e,t){return t.has(e.id)?"dot wait":e.status==="running"||e.status==="initializing"?"dot run":e.status==="error"||e.lastTurnStatus==="failed"?"dot err":"dot"}function gx({pendingByThread:e}){let{projects:t,threads:i}=ut(),n=fe(),[s,r]=(0,je.useState)(""),[a,o]=(0,je.useState)({}),[l,c]=(0,je.useState)({}),[u,h]=(0,je.useState)(null),[d,f]=(0,je.useState)(""),[p,_]=(0,je.useState)(!1),[w,g]=(0,je.useState)(null),[m,v]=(0,je.useState)(null),[S,k]=(0,je.useState)(null),[A,O,T]=Wc(),[D,F,P]=Wc(),M=(0,je.useRef)({}),B=(0,je.useRef)(null);(0,je.useEffect)(()=>{let z=Ee=>{let ue=Ee.detail?.projectId,De=t.find(J=>J.id===ue)??t[0];De&&g(De)},X=()=>_(!0);return window.addEventListener("open-import",z),window.addEventListener("open-new-project",X),()=>{window.removeEventListener("open-import",z),window.removeEventListener("open-new-project",X)}},[t]);let E=(0,je.useMemo)(()=>{let z=s.trim().toLowerCase();return z?i.filter(X=>X.title.toLowerCase().includes(z)):i},[i,s]),I=(0,je.useMemo)(()=>{let z=new Map;for(let X of E)(!X.archived||a[X.projectId])&&(z.get(X.projectId)??z.set(X.projectId,[]).get(X.projectId)).push(X);for(let X of z.values())X.sort((Ee,ue)=>Number(Ee.archived)-Number(ue.archived)||Number(ue.pinned)-Number(Ee.pinned)||ue.updatedAt-Ee.updatedAt);return z},[E,a]),C=(0,je.useMemo)(()=>{let z=new Map;for(let X of E)X.archived&&z.set(X.projectId,(z.get(X.projectId)??0)+1);return z},[E]);async function L(z){try{let X=await nL(),Ee=await fl(),ue=await te.call("threads.create",{projectId:z,provider:Ee,model:null,mode:X.defaultMode??"default"});n.select(z,ue.id)}catch(X){Te(y("sidebar.failNewThread")+ct(X),!0)}}function R(z){return[{kind:"item",label:y("common.rename"),onClick:()=>{h(z.id),f(z.title)}},{kind:"item",label:z.pinned?y("sidebar.unpin"):y("sidebar.pin"),onClick:()=>{te.call("threads.update",{id:z.id,pinned:!z.pinned})}},{kind:"item",label:z.archived?y("sidebar.unarchive"):y("sidebar.archive"),onClick:()=>{$(z)}},{kind:"item",label:y("sidebar.exportMd"),onClick:()=>{aL(z)}},{kind:"sep"},{kind:"item",label:y("common.delete"),danger:!0,onClick:()=>v({title:y("sidebar.deleteThread"),body:Ce("sidebar.deleteThreadBody",{title:z.title}),onOk:()=>{te.call("threads.delete",{id:z.id})}})}]}async function $(z){try{await te.call("threads.update",{id:z.id,archived:!z.archived}),z.archived?Te(y("sidebar.unarchived")):(o(X=>({...X,[z.projectId]:!0})),Te(y("sidebar.archivedHint")))}catch(X){Te(ct(X),!0)}}function ee(z){return[{kind:"item",label:y("sidebar.newThread"),onClick:()=>{L(z.id)}},{kind:"item",label:y("sidebar.importHist"),onClick:()=>g(z)},{kind:"item",label:y("common.rename"),onClick:()=>k(z)},{kind:"item",label:y("sidebar.openExplorer"),onClick:()=>{te.call("projects.open",{id:z.id})}},{kind:"sep"},{kind:"item",label:a[z.id]?y("sidebar.hideArchived"):y("sidebar.showArchived"),onClick:()=>o(X=>({...X,[z.id]:!X[z.id]}))},{kind:"sep"},{kind:"item",label:y("sidebar.removeProject"),danger:!0,onClick:()=>v({title:y("sidebar.removeProject"),body:Ce("sidebar.removeProjectBody",{name:z.name}),onOk:()=>{te.call("projects.remove",{id:z.id})}})}]}return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)("div",{className:"sb-row",children:[(0,V.jsxs)("button",{className:"sb-new",onClick:()=>_(!0),children:[(0,V.jsx)("span",{className:"sb-new-tile",children:(0,V.jsx)(ye,{name:"plus",size:12})}),y("sidebar.newProject")]}),(0,V.jsx)("button",{className:"ibtn",title:y("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings")),children:(0,V.jsx)(ye,{name:"settings"})}),(0,V.jsx)("button",{className:"ibtn",title:y("sidebar.searchTitle"),onClick:()=>B.current?.focus(),children:(0,V.jsx)(ye,{name:"search"})})]}),(0,V.jsx)("div",{className:"sb-row sb-row-search",children:(0,V.jsxs)("div",{className:"sb-search",children:[(0,V.jsx)(ye,{name:"search",size:13}),(0,V.jsx)("input",{ref:B,placeholder:y("sidebar.filterPlaceholder"),value:s,onChange:z=>r(z.target.value),onKeyDown:z=>{z.key==="Escape"&&r("")}})]})}),(0,V.jsxs)("div",{className:"sb-list",children:[t.length===0&&(0,V.jsxs)("div",{className:"sb-start",children:[(0,V.jsx)("div",{className:"sb-start-t",children:y("sidebar.noProjectsTitle")}),(0,V.jsx)("div",{className:"sb-start-s",children:y("sidebar.noProjectsSub")}),(0,V.jsx)("button",{className:"btn primary",onClick:()=>_(!0),children:y("sidebar.newProject")})]}),t.map(z=>{let X=I.get(z.id)??[],Ee=n.collapsed[z.id],ue=C.get(z.id)??0,De=l[z.id]?X:X.slice(0,mx);return(0,V.jsxs)("div",{className:"pj-group",children:[(0,V.jsxs)("div",{className:"pj",onContextMenu:J=>{M.current.project=z,O(J)},children:[(0,V.jsxs)("button",{className:"pj-toggle",onClick:()=>n.toggleCollapsed(z.id),children:[(0,V.jsx)("span",{className:`pj-caret${Ee?"":" open"}`,children:(0,V.jsx)(ye,{name:"caret"})}),(0,V.jsx)("span",{className:"pj-badge",children:z.name.slice(0,1)}),(0,V.jsx)("span",{className:"pj-name",children:z.name})]}),(0,V.jsx)("span",{className:"pj-count",children:X.length||""}),(0,V.jsx)("button",{className:"pj-act",title:y("sidebar.newThread"),onClick:()=>{L(z.id)},children:(0,V.jsx)(ye,{name:"plus"})}),(0,V.jsx)("button",{className:"pj-act",title:y("sidebar.projectMenu"),onClick:J=>{M.current.project=z,O(J)},children:(0,V.jsx)(ye,{name:"dots"})})]}),!Ee&&(0,V.jsxs)("div",{className:"pj-sessions",children:[De.map(J=>u===J.id?(0,V.jsx)("div",{className:"t-item",children:(0,V.jsx)("input",{className:"t-rename",autoFocus:!0,value:d,onChange:qe=>f(qe.target.value),onBlur:()=>h(null),onKeyDown:qe=>{qe.key==="Enter"&&!Mn(qe.nativeEvent)&&d.trim()?(te.call("threads.update",{id:J.id,title:d.trim()}),h(null)):qe.key==="Escape"&&h(null)}})},J.id):(0,V.jsxs)("button",{className:`t-item${n.currentThreadId===J.id?" on":""}${J.archived?" archived":""}`,onClick:()=>n.select(z.id,J.id),onContextMenu:qe=>{M.current.thread=J,F(qe)},children:[(0,V.jsx)("span",{className:tL(J,e)}),J.pinned&&(0,V.jsx)("span",{className:"t-pin",children:(0,V.jsx)(ye,{name:"pin"})}),(0,V.jsx)("span",{className:"t-title",children:Dd(J.title,J.titleAuto)}),(0,V.jsx)("span",{className:"t-time",children:k_(J.updatedAt)}),(0,V.jsx)("span",{className:"t-more",role:"button",onClick:qe=>{qe.stopPropagation(),M.current.thread=J,F(qe)},children:(0,V.jsx)(ye,{name:"dots"})})]},J.id)),X.length>mx&&!l[z.id]&&(0,V.jsx)("button",{className:"pj-more",onClick:()=>c(J=>({...J,[z.id]:!0})),children:Ce("sidebar.showAll",{n:X.length})}),ue>0&&(0,V.jsx)("button",{className:"pj-more",onClick:()=>o(J=>({...J,[z.id]:!J[z.id]})),children:a[z.id]?y("sidebar.hideArchived"):Ce("sidebar.archivedN",{n:ue})}),X.length===0&&ue===0&&(0,V.jsx)("div",{className:"pj-empty",children:y("sidebar.noThreads")})]})]},z.id)})]}),A&&M.current.project&&(0,V.jsx)(Kc,{x:A.x,y:A.y,items:ee(M.current.project),onClose:T}),D&&M.current.thread&&(0,V.jsx)(Kc,{x:D.x,y:D.y,items:R(M.current.thread),onClose:P}),p&&(0,V.jsx)(sL,{onClose:()=>_(!1)}),w&&(0,V.jsx)(rL,{project:w,onClose:()=>g(null)}),m&&(0,V.jsx)(gl,{title:m.title,body:m.body,danger:!0,onOk:m.onOk,onClose:()=>v(null)}),S&&(0,V.jsx)(iL,{project:S,onClose:()=>k(null)})]})}function iL({project:e,onClose:t}){let[i,n]=(0,je.useState)(e.name),s=i.trim().length>0&&i.trim()!==e.name,r=()=>{s&&te.call("projects.rename",{id:e.id,name:i.trim()}).then(t).catch(a=>Te(y("sidebar.failRename")+ct(a),!0))};return(0,V.jsx)(Es,{title:y("sidebar.renameProject"),onClose:t,footer:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)("button",{className:"btn ghost",onClick:t,children:y("common.cancel")}),(0,V.jsx)("button",{className:"btn primary",disabled:!s,onClick:r,children:y("common.save")})]}),children:(0,V.jsxs)("div",{className:"dlg-row",children:[(0,V.jsx)("label",{children:y("sidebar.projectName")}),(0,V.jsx)("input",{className:"tinput",autoFocus:!0,value:i,onChange:a=>n(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!Mn(a.nativeEvent)&&r()}})]})})}function nL(){return te.call("settings.get").then(e=>e).catch(()=>({}))}function sL({onClose:e}){let[t,i]=(0,je.useState)(""),[n,s]=(0,je.useState)(null),[r,a]=(0,je.useState)([]),[o,l]=(0,je.useState)(!1),c=fe();(0,je.useEffect)(()=>{te.call("fs.recentDirs").then(d=>a(d)).catch(()=>{})},[]),(0,je.useEffect)(()=>{let d=t.trim();if(!d){s(null);return}let f=setTimeout(()=>{te.call("fs.check",{path:d}).then(p=>s(p)).catch(()=>s(null))},200);return()=>clearTimeout(f)},[t]);let u=n?.exists&&n.isDir;async function h(){if(!(!u||o)){l(!0);try{let d=await te.call("projects.create",{path:t.trim()});c.select(d.id,null),e()}catch(d){Te(y("sidebar.failAddProject")+ct(d),!0),l(!1)}}}return(0,V.jsxs)(Es,{title:y("sidebar.newProjectDlg"),onClose:e,footer:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)("button",{className:"btn ghost",onClick:e,children:y("common.cancel")}),(0,V.jsx)("button",{className:"btn primary",disabled:!u||o,onClick:()=>{h()},children:y("common.add")})]}),children:[(0,V.jsxs)("div",{className:"dlg-row",children:[(0,V.jsx)("label",{children:y("sidebar.dirLabel")}),(0,V.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,V.jsx)("input",{className:`tinput${n&&!u?" err":""}`,style:{flex:1},autoFocus:!0,placeholder:"D:\\\\path\\\\to\\\\project",value:t,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!Mn(d.nativeEvent)&&h()}}),(0,V.jsx)("button",{className:"btn",style:{flex:"none",whiteSpace:"nowrap"},onClick:()=>{te.call("fs.pickFolder",{initial:t.trim()||void 0}).then(d=>{let f=d;f?.path?i(f.path):f&&!f.available&&Te(y("sidebar.pickFolderUnsupported"))}).catch(()=>Te(y("sidebar.pickFolderFailed")))},children:y("common.browse")})]}),n&&!n.exists&&(0,V.jsx)("div",{className:"dlg-hint err",children:y("sidebar.dirMissing")}),n&&n.exists&&!n.isDir&&(0,V.jsx)("div",{className:"dlg-hint err",children:y("sidebar.notDir")}),u&&(0,V.jsx)("div",{className:"dlg-hint",children:y("sidebar.dirOk")})]}),r.length>0&&(0,V.jsxs)("div",{className:"dlg-row",children:[(0,V.jsx)("label",{children:y("sidebar.recent")}),r.map(d=>(0,V.jsx)("button",{className:"mi",style:{height:26},onClick:()=>i(d),children:d},d))]})]})}function rL({project:e,onClose:t}){let[i,n]=(0,je.useState)(null),[s,r]=(0,je.useState)(new Set),[a,o]=(0,je.useState)(!1),l=fe();(0,je.useEffect)(()=>{te.call("history.list",{projectId:e.id}).then(h=>n(h)).catch(h=>{Te(y("sidebar.failImportList")+ct(h),!0),n([])})},[e.id]);let c=h=>{r(d=>{let f=new Set(d);return f.has(h)?f.delete(h):f.add(h),f})};async function u(){if(!(a||s.size===0||!i)){o(!0);try{let h=i.filter(f=>s.has(f.sessionId)&&!f.imported),d=await te.call("history.import",{projectId:e.id,items:h.map(f=>({provider:f.provider,sessionId:f.sessionId,title:f.title}))});Te(Ce("sidebar.importedN",{n:d.length})),d.length>0&&l.select(e.id,d[d.length-1].id),t()}catch(h){Te(y("sidebar.failImport")+ct(h),!0)}finally{o(!1)}}}return(0,V.jsxs)(Es,{title:Ce("sidebar.importTitle",{name:e.name}),onClose:t,wide:!0,footer:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)("button",{className:"btn ghost",onClick:t,children:y("common.cancel")}),(0,V.jsx)("button",{className:"btn primary",disabled:a||s.size===0,onClick:()=>{u()},children:a?y("sidebar.importing"):Ce("sidebar.importN",{n:s.size||0})})]}),children:[i===null&&(0,V.jsx)("div",{className:"dlg-hint",children:y("sidebar.scanning")}),i!==null&&i.length===0&&(0,V.jsx)("div",{className:"dlg-hint",children:y("sidebar.importEmpty")}),i!==null&&i.length>0&&(0,V.jsx)("div",{className:"imp-list",children:i.map(h=>(0,V.jsxs)("label",{className:`imp-row${h.imported?" done":""}`,children:[(0,V.jsx)("input",{type:"checkbox",disabled:h.imported,checked:s.has(h.sessionId),onChange:()=>c(h.sessionId)}),(0,V.jsx)("span",{className:"imp-title",children:h.title}),(0,V.jsxs)("span",{className:"imp-meta",children:[h.provider," \xB7 ",h.messageCount,y("common.messages")," \xB7 ",k_(h.updatedAt),h.imported?y("common.imported"):""]})]},h.sessionId))})]})}async function aL(e){try{let t=await te.call("thread.exportMarkdown",{id:e.id});if(t.path){Te(Ce("sidebar.exportSaved",{path:t.path}));return}let i=new Blob([t.markdown],{type:"text/markdown;charset=utf-8"}),n=document.createElement("a");n.href=URL.createObjectURL(i),n.download=t.filename||`${e.title}.md`,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{URL.revokeObjectURL(n.href),n.remove()},5e3)}catch(t){Te(y("sidebar.failExport")+ct(t),!0)}}var je,V,mx,_x=le(()=>{je=ae(Nt(),1);pl();jn();dn();Rn();Ud();N_();_l();Wr();Vn();Ci();V=ae(ke(),1),mx=10});function D_(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function Nx(e){Ka=e}function Pa(e){let t=[];return i=>{let n=Math.max(0,Math.min(3,i-1)),s=t[n];return s||(s=e(n),t[n]=s),s}}function Se(e,t=""){let i=typeof e=="string"?e:e.source,n={replace:(s,r)=>{let a=typeof r=="string"?r:r.source;return a=a.replace(Zt.caret,"$1"),i=i.replace(s,a),n},getRegex:()=>new RegExp(i,t)};return n}function fn(e,t){if(t){if(Zt.escapeTest.test(e))return e.replace(Zt.escapeReplace,Sx)}else if(Zt.escapeTestNoEncode.test(e))return e.replace(Zt.escapeReplaceNoEncode,Sx);return e}function r3(e){return Zt.numericCharacterReference.test(e)?e.replace(Zt.numericCharacterReferenceOrAmpersand,(t,i,n)=>{if(i===void 0&&n===void 0)return"&";let s=i===void 0?Number.parseInt(n,16):Number.parseInt(i,10);return s===0||s>1114111||s>=55296&&s<=57343?"\uFFFD":s===38?"&":String.fromCodePoint(s)}):e}function wx(e){try{e=encodeURI(e).replace(Zt.percentDecode,"%")}catch{return null}return e}function Ex(e,t){let i=e.replace(Zt.findPipe,(r,a,o)=>{let l=!1,c=a;for(;--c>=0&&o[c]==="\\";)l=!l;return l?"|":" |"}),n=i.split(Zt.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length=0&&Zt.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(` -`)}function Wd(e){return e.trim().toLowerCase().toUpperCase().toLowerCase()}function Cx(e,t){if(e.indexOf(t[0])===-1&&e.indexOf(t[1])===-1)return-1;let i=0;for(let n=0;n0?-2:-1}function Fd(e,t=0){let i=t,n="";for(let s of e)if(s===" "){let r=4-i%4;n+=" ".repeat(r),i+=r}else n+=s,i++;return n}function kx(e,t,i,n,s){let r=t.href,a=t.title||null,o=e[1].replace(s.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!",c=n.state.inLink,u=n.state.linkEmitted,h=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(o),f=n.state.linkEmitted;if(n.state.linkEmitted=u,n.state.inLink=c,!l){if(f){n.state.inRawBlock=h;return}n.state.linkEmitted=!0}return{type:l?"image":"link",raw:i,href:r,title:a,text:o,tokens:d}}function a3(e,t,i){let n=e.match(i.other.indentCodeCompensation);if(n===null)return t;let s=n[1];return t.split(` -`).map(r=>{let a=r.match(i.other.beginningSpace);if(a===null)return r;let[o]=a;return r.slice(Math.min(o.length,s.length))}).join(` -`)}function Tx(e,t,i,n){if(!t.includes("<"))return!1;for(let s=0;st.length-s)return!0;s+=a[0].length-1}}return!1}function Ua(e,t){if(Array.isArray(t))for(let i=0;i{Ka=D_();Ha={exec:()=>null};oL=((e="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)([ \t]+)/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Pa(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Pa(e=>new RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:Pa(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Pa(e=>new RegExp(`^ {0,${e}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:Pa(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Pa(e=>new RegExp(`^ {0,${e}}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|new RegExp(`^ {0,${e}}>`))},lL=/^(?:[ \t]*(?:\n|$))+/,cL=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,uL=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Yc=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,hL=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,L_=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ax=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Mx=Se(Ax).replace(/bull/g,L_).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),dL=Se(Ax).replace(/bull/g,L_).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),B_=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,fL=/^[^\n]+/,I_=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,pL=Se(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",I_).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),mL=Se(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,L_).getRegex(),jc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",z_=/|$))/,gL=Se("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|[^\\n]*\\n*|$)|[^\\n]*\\n*|$)||$)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",z_).replace("tag",jc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Rx=e=>Se(B_).replace("hr",Yc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?| ?(?:(?![ \t]*(?:\n|$))(paragraph)|[^\n]*)(?:\n|$))+/).replace("paragraph",vL).getRegex(),P_={blockquote:bL,code:cL,def:pL,fences:uL,heading:hL,hr:Yc,html:gL,lheading:Mx,list:mL,newline:lL,paragraph:_L,table:Ha,text:fL},vx=Se("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Yc).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?| *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",z_).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ha,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Se(B_).replace("hr",Yc).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",Mx).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},wL=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,EL=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ox=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,xL=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",oL?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Lx=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ML=Se(Lx,"u").replace(/punct/g,xs).getRegex(),RL=Se(Lx,"u").replace(/punct/g,Dx).getRegex(),OL=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,DL=Se(OL,"u").replace(/openQuote/g,kL).replace(/punct/g,xs).getRegex(),Bx="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",LL=Se(Bx,"gu").replace(/notPunctSpace/g,Vc).replace(/punctSpace/g,yl).replace(/punct/g,xs).getRegex(),BL=Se(Bx,"gu").replace(/notPunctSpace/g,NL).replace(/punctSpace/g,TL).replace(/punct/g,Dx).getRegex(),IL="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",zL=Se(IL,"gu").replace(/notPunctSpace/g,Vc).replace(/punctSpace/g,yl).replace(/punct/g,xs).getRegex(),PL=Se("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Vc).replace(/punctSpace/g,yl).replace(/punct/g,xs).getRegex(),UL="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",HL=Se(UL,"gu").replace(/notPunctSpace/g,Vc).replace(/punctSpace/g,yl).replace(/punct/g,xs).getRegex(),FL=Se(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,xs).getRegex(),qL="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",KL=Se(qL,"gu").replace(/notPunctSpace/g,Vc).replace(/punctSpace/g,yl).replace(/punct/g,xs).getRegex(),WL=Se(/\\(punct)/,"gu").replace(/punct/g,xs).getRegex(),$L=Se(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,xs).getRegex(),GL=Se(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),YL=Se(z_).replace("(?:-->|$)","-->").getRegex(),jL=Se("^comment|^|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",YL).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ix=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,Kd=Se(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Ix).getRegex(),VL=Se(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",Kd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),XL=Se(/^!?\[(label)\]\[(ref)\]/).replace("label",Kd).replace("ref",I_).getRegex(),ZL=Se(/^!?\[(ref)\](?:\[\])?/).replace("ref",I_).getRegex(),bx=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,QL=Se(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",Ix).getRegex(),JL=Se("reflink|nolink(?!\\()","g").replace("reflink",Se(/^!?\[(label)\]\[(ref)\]/).replace("label",QL).replace("ref",bx).getRegex()).replace("nolink",Se(/^!?\[(ref)\](?:\[\])?/).replace("ref",bx).getRegex()).getRegex(),yx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,e3=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,t3=Se(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,e3).getRegex(),U_={_backpedal:Ha,anyPunctuation:WL,anyPunctuationOutsideCode:$L,autolink:GL,blockSkip:AL,br:Ox,code:EL,del:Ha,delLDelim:Ha,delRDelim:Ha,emStrongLDelim:ML,emStrongRDelimAst:LL,emStrongRDelimUnd:PL,escape:wL,link:VL,nolink:ZL,punctuation:CL,reflink:XL,reflinkSearch:JL,tag:jL,text:xL,url:Ha},i3={...U_,emStrongLDelim:DL,emStrongRDelimAst:zL,emStrongRDelimUnd:HL,link:Se(/^!?\[(label)\]\((.*?)\)/).replace("label",Kd).getRegex(),reflink:Se(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Kd).getRegex()},R_={...U_,emStrongRDelimAst:BL,emStrongLDelim:RL,delLDelim:FL,delRDelim:KL,url:Se(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",t3).replace("protocol",yx).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Se(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Sx=e=>s3[e];vl=class{constructor(e){de(this,"options");de(this,"rules");de(this,"lexer");this.options=e||Ka}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:xx(t[0]),n=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],n=a3(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let n=$r(i,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceTabChar.test(n))&&(i=n.trim())}return{type:"heading",raw:$r(t[0],` -`),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:$r(t[0],` -`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=$r(t[0],` +`+n.stack}}var Ym=Object.prototype.hasOwnProperty,Zg=Xt.unstable_scheduleCallback,um=Xt.unstable_cancelCallback,a2=Xt.unstable_shouldYield,o2=Xt.unstable_requestPaint,gn=Xt.unstable_now,l2=Xt.unstable_getCurrentPriorityLevel,Dw=Xt.unstable_ImmediatePriority,Lw=Xt.unstable_UserBlockingPriority,ad=Xt.unstable_NormalPriority,c2=Xt.unstable_LowPriority,Iw=Xt.unstable_IdlePriority,u2=Xt.log,h2=Xt.unstable_setDisableYieldValue,$c=null,_n=null;function Ls(e){if(typeof u2=="function"&&h2(e),_n&&typeof _n.setStrictMode=="function")try{_n.setStrictMode($c,e)}catch{}}var vn=Math.clz32?Math.clz32:p2,d2=Math.log,f2=Math.LN2;function p2(e){return e>>>=0,e===0?32:31-(d2(e)/f2|0)|0}var vh=256,bh=262144,yh=4194304;function ka(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&-e;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Od(e,t,i){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,a=e.pingedLanes;e=e.warmLanes;var o=n&134217727;return o!==0?(n=o&~s,n!==0?r=ka(n):(a&=o,a!==0?r=ka(a):i||(i=o&~e,i!==0&&(r=ka(i))))):(o=n&~s,o!==0?r=ka(o):a!==0?r=ka(a):i||(i=n&~e,i!==0&&(r=ka(i)))),r===0?0:t!==0&&t!==r&&(t&s)===0&&(s=r&-r,i=t&-t,s>=i||s===32&&(i&4194048)!==0)?t:r}function Gc(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Bw(e,t){(t&8)!==0&&(t|=t&32);var i=e.entangledLanes;if(i!==0)for(e=e.entanglements,i&=t;0i;i++)t.push(e);return t}function jc(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function g2(e,t,i,n,r,s){var a=e.pendingLanes;e.pendingLanes=i,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=i,e.entangledLanes&=i,e.errorRecoveryDisabledLanes&=i,e.shellSuspendCounter=0;var o=e.entanglements,l=e.expirationTimes,c=e.hiddenUpdates;for(i=a&~i;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Qm=!1;if(Jr)try{Ao={},Object.defineProperty(Ao,"passive",{get:function(){Qm=!0}}),window.addEventListener("test",Ao,Ao),window.removeEventListener("test",Ao,Ao)}catch{Qm=!1}var Ao,Is=null,i_=null,Hh=null;function Qw(){if(Hh)return Hh;var e,t=i_,i=t.length,n,r="value"in Is?Is.value:Is.textContent,s=r.length;for(e=0;e=mc),rS=" ",sS=!1;function e1(e,t){switch(e){case"keyup":return Q2.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function t1(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Uo=!1;function eD(e,t){switch(e){case"compositionend":return t1(t);case"keypress":return t.which!==32?null:(sS=!0,rS);case"textInput":return e=t.data,e===rS&&sS?null:e;default:return null}}function tD(e,t){if(Uo)return e==="compositionend"||!r_&&e1(e,t)?(e=Qw(),Hh=i_=Is=null,Uo=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function cS(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function uS(e,t){var i=cS(e);e=0;for(var n;i;){if(i.nodeType===3){if(n=e+i.textContent.length,e<=t&&n>=t)return{node:i,offset:t-e};e=n}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=cS(i)}}function s1(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?s1(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function a1(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Jm(e.document);t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=Jm(e.document)}return t}function s_(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var cD=Jr&&"documentMode"in document&&11>=document.documentMode,Ho=null,eg=null,_c=null,tg=!1;function hS(e,t,i){var n=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;tg||Ho==null||Ho!==Jm(n)||(n=Ho,"selectionStart"in n&&s_(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),_c&&Rc(_c,n)||(_c=n,n=Ad(eg,"onSelect"),0>=a,r-=a,xr=1<<32-vn(t)+r|i<k?(D=O,O=null):D=O.sibling;var L=d(m,O,b[k],w);if(L===null){O===null&&(O=D);break}e&&O&&L.alternate===null&&t(m,O),g=s(L,g,k),A===null?E=L:A.sibling=L,A=L,O=D}if(k===b.length)return i(m,O),De&&Vr(m,k),E;if(O===null){for(;kk?(D=O,O=null):D=O.sibling;var P=d(m,O,L.value,w);if(P===null){O===null&&(O=D);break}e&&O&&P.alternate===null&&t(m,O),g=s(P,g,k),A===null?E=P:A.sibling=P,A=P,O=D}if(L.done)return i(m,O),De&&Vr(m,k),E;if(O===null){for(;!L.done;k++,L=b.next())L=h(m,L.value,w),L!==null&&(g=s(L,g,k),A===null?E=L:A.sibling=L,A=L);return De&&Vr(m,k),E}for(O=n(O);!L.done;k++,L=b.next())L=f(O,m,k,L.value,w),L!==null&&(e&&(D=L.alternate,D!==null&&O.delete(D.key===null?k:D.key)),g=s(L,g,k),A===null?E=L:A.sibling=L,A=L);return e&&O.forEach(function(I){return t(m,I)}),De&&Vr(m,k),E}function S(m,g,b,w){if(typeof b=="object"&&b!==null&&b.type===Bo&&b.key===null&&b.props.ref===void 0&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case _h:e:{for(var E=b.key;g!==null;){if(g.key===E){if(E=b.type,E===Bo){if(g.tag===7){i(m,g.sibling),w=r(g,b.props.children),Ns(w,b),w.return=m,m=w;break e}}else if(g.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Rs&&Ta(E)===g.type){i(m,g.sibling),w=r(g,b.props),Ns(w,b),w.return=m,m=w;break e}i(m,g);break}else t(m,g);g=g.sibling}b.type===Bo?(w=Oa(b.props.children,m.mode,w,b.key),Ns(w,b),w.return=m,m=w):(w=qh(b.type,b.key,b.props,null,m.mode,w),Ns(w,b),w.return=m,m=w)}return a(m);case uc:e:{for(E=b.key;g!==null;){if(g.key===E)if(g.tag===4&&g.stateNode.containerInfo===b.containerInfo&&g.stateNode.implementation===b.implementation){i(m,g.sibling),w=r(g,b.children||[]),w.return=m,m=w;break e}else{i(m,g);break}else t(m,g);g=g.sibling}w=ym(b,m.mode,w),w.return=m,m=w}return a(m);case Rs:return b=Ta(b),S(m,g,b,w)}if(hc(b))return p(m,g,b,w);if(rc(b)){if(E=rc(b),typeof E!="function")throw Error(H(150));return b=E.call(b),_(m,g,b,w)}if(typeof b.then=="function")return S(m,g,kh(b),w);if(b.$$typeof===Sr)return S(m,g,Ch(m,b),w);Th(m,b)}return typeof b=="string"&&b!==""||typeof b=="number"||typeof b=="bigint"?(b=""+b,g!==null&&g.tag===6?(i(m,g.sibling),w=r(g,b),w.return=m,m=w):(i(m,g),w=bm(b,m.mode,w),w.return=m,m=w),a(m)):i(m,g)}return function(m,g,b,w){try{Lc=0;var E=S(m,g,b,w);return Zo=null,E}catch(O){if(O===vl||O===Hd)throw O;var A=en(29,O,null,m.mode);return A.lanes=w,A.return=m,A}}}var Ha=S1(!0),w1=S1(!1),Os=!1;function f_(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function og(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function qs(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Ks(e,t,i){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,($e&2)!==0){var r=n.pending;return r===null?t.next=t:(t.next=r.next,r.next=t),n.pending=t,t=cd(e),f1(e,null,i),t}return Pd(e,n,t,i),cd(e)}function bc(e,t,i){if(t=t.updateQueue,t!==null&&(t=t.shared,(i&4194048)!==0)){var n=t.lanes;n&=e.pendingLanes,i|=n,t.lanes=i,Uw(e,i)}}function wm(e,t){var i=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,i===n)){var r=null,s=null;if(i=i.firstBaseUpdate,i!==null){do{var a={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};s===null?r=s=a:s=s.next=a,i=i.next}while(i!==null);s===null?r=s=t:s=s.next=t}else r=s=t;i={baseState:n.baseState,firstBaseUpdate:r,lastBaseUpdate:s,shared:n.shared,callbacks:n.callbacks},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}var lg=!1;function yc(){if(lg){var e=Xo;if(e!==null)throw e}}function Sc(e,t,i,n){lg=!1;var r=e.updateQueue;Os=!1;var s=r.firstBaseUpdate,a=r.lastBaseUpdate,o=r.shared.pending;if(o!==null){r.shared.pending=null;var l=o,c=l.next;l.next=null,a===null?s=c:a.next=c,a=l;var u=e.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==a&&(o===null?u.firstBaseUpdate=c:o.next=c,u.lastBaseUpdate=l))}if(s!==null){var h=r.baseState;a=0,u=c=l=null,o=s;do{var d=o.lane&-536870913,f=d!==o.lane;if(f?(Pe&d)===d:(n&d)===d){d!==0&&d===Ua&&(lg=!0),u!==null&&(u=u.next={lane:0,tag:o.tag,payload:o.payload,callback:null,next:null});e:{var p=e,_=o;d=t;var S=i;switch(_.tag){case 1:if(p=_.payload,typeof p=="function"){h=p.call(S,h,d);break e}h=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=_.payload,d=typeof p=="function"?p.call(S,h,d):p,d==null)break e;h=ct({},h,d);break e;case 2:Os=!0}}d=o.callback,d!==null&&(e.flags|=64,f&&(e.flags|=8192),f=r.callbacks,f===null?r.callbacks=[d]:f.push(d))}else f={lane:d,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(c=u=f,l=h):u=u.next=f,a|=d;if(o=o.next,o===null){if(o=r.shared.pending,o===null)break;f=o,o=f.next,f.next=null,r.lastBaseUpdate=f,r.shared.pending=null}}while(!0);u===null&&(l=h),r.baseState=l,r.firstBaseUpdate=c,r.lastBaseUpdate=u,s===null&&(r.shared.lanes=0),ea|=a,e.lanes=a,e.memoizedState=h}}function x1(e,t){if(typeof e!="function")throw Error(H(191,e));e.call(t)}function E1(e,t){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;es?s:8;var a=be.T,o={};o.types=a!==null?a.types:null,be.T=o,T_(e,!1,t,i);try{var l=r(),c=be.S;if(c!==null&&c(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=yD(l,n);wc(e,t,u,bn(e))}else wc(e,t,n,bn(e))}catch(h){wc(e,t,{then:function(){},status:"rejected",reason:h},bn())}finally{Ge.p=s,a!==null&&o.types!==null&&(a.types=o.types),be.T=a}}function kD(){}function fg(e,t,i,n){if(e.tag!==5)throw Error(H(476));var r=V1(e).queue;Y1(e,r,t,Ra,i===null?kD:function(){return X1(e),i(n)})}function V1(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:Ra,baseState:Ra,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:is,lastRenderedState:Ra},next:null};var i={};return t.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:is,lastRenderedState:i},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function X1(e){var t=V1(e);t.next===null&&(t=e.alternate.memoizedState),wc(e,t.next.queue,{},bn())}function k_(){return Si(fl)}function Z1(){return Dt().memoizedState}function Q1(){return Dt().memoizedState}function TD(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var i=bn();e=qs(i);var n=Ks(t,e,i);n!==null&&(tn(n,t,i),bc(n,t,i)),t={cache:u_()},e.payload=t;return}t=t.return}}function ND(e,t,i){var n=bn();i={lane:n,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Wd(e)?ex(t,i):(i=o_(e,t,i,n),i!==null&&(tn(i,e,n),tx(i,t,n)))}function J1(e,t,i){var n=bn();wc(e,t,i,n)}function wc(e,t,i,n){var r={lane:n,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Wd(e))ex(t,r);else{var s=e.alternate;if(e.lanes===0&&(s===null||s.lanes===0)&&(s=t.lastRenderedReducer,s!==null))try{var a=t.lastRenderedState,o=s(a,i);if(r.hasEagerState=!0,r.eagerState=o,yn(o,a))return Pd(e,t,r,0),lt===null&&zd(),!1}catch{}if(i=o_(e,t,r,n),i!==null)return tn(i,e,n),tx(i,t,n),!0}return!1}function T_(e,t,i,n){if(n={lane:2,revertLane:P_(),gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Wd(e)){if(t)throw Error(H(479))}else t=o_(e,i,n,2),t!==null&&tn(t,e,2)}function Wd(e){var t=e.alternate;return e===Ne||t!==null&&t===Ne}function ex(e,t){Qo=gd=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function tx(e,t,i){if((i&4194048)!==0){var n=t.lanes;n&=e.pendingLanes,i|=n,t.lanes=i,Uw(e,i)}}var vd={readContext:Si,use:qd,useCallback:Tt,useContext:Tt,useEffect:Tt,useImperativeHandle:Tt,useLayoutEffect:Tt,useInsertionEffect:Tt,useMemo:Tt,useReducer:Tt,useRef:Tt,useState:Tt,useDebugValue:Tt,useDeferredValue:Tt,useTransition:Tt,useSyncExternalStore:Tt,useId:Tt,useHostTransitionStatus:Tt,useFormState:Tt,useActionState:Tt,useOptimistic:Tt,useMemoCache:Tt,useCacheRefresh:Tt,useEffectEvent:Tt},ix={readContext:Si,use:qd,useCallback:function(e,t){return Ki().memoizedState=[e,t===void 0?null:t],e},useContext:Si,useEffect:TS,useImperativeHandle:function(e,t,i){i=i!=null?i.concat([e]):null,Gh(4194308,4,K1.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Gh(4194308,4,e,t)},useInsertionEffect:function(e,t){Gh(4,2,e,t)},useMemo:function(e,t){var i=Ki();t=t===void 0?null:t;var n=e();if(Fa){Ls(!0);try{e()}finally{Ls(!1)}}return i.memoizedState=[n,t],n},useReducer:function(e,t,i){var n=Ki();if(i!==void 0){var r=i(t);if(Fa){Ls(!0);try{i(t)}finally{Ls(!1)}}}else r=t;return n.memoizedState=n.baseState=r,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:r},n.queue=e,e=e.dispatch=ND.bind(null,Ne,e),[n.memoizedState,e]},useRef:function(e){var t=Ki();return e={current:e},t.memoizedState=e},useState:function(e){e=hg(e);var t=e.queue,i=J1.bind(null,Ne,t);return t.dispatch=i,[e.memoizedState,i]},useDebugValue:E_,useDeferredValue:function(e,t){var i=Ki();return C_(i,e,t)},useTransition:function(){var e=hg(!1);return e=Y1.bind(null,Ne,e.queue,!0,!1),Ki().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,i){var n=Ne,r=Ki();if(De){if(i===void 0)throw Error(H(407));i=i()}else{if(i=t(),lt===null)throw Error(H(349));(Pe&127)!==0||A1(n,t,i)}r.memoizedState=i;var s={value:i,getSnapshot:t};return r.queue=s,TS(R1.bind(null,n,s,e),[e]),n.flags|=2048,al(9,{destroy:void 0},M1.bind(null,n,s,i,t),null),i},useId:function(){var e=Ki(),t=lt.identifierPrefix;if(De){var i=Er,n=xr;i=(n&~(1<<32-vn(n)-1)).toString(32)+i,t="_"+t+"R_"+i,i=_d++,0<\/script>",s=s.removeChild(s.firstChild);break;case"select":s=typeof n.is=="string"?a.createElement("select",{is:n.is}):a.createElement("select"),n.multiple?s.multiple=!0:n.size&&(s.size=n.size);break;default:s=typeof n.is=="string"?a.createElement(r,{is:n.is}):a.createElement(r)}}s[yi]=t,s[rn]=n;e:for(a=t.child;a!==null;){if(a.tag===5||a.tag===6)s.appendChild(a.stateNode);else if(a.tag!==4&&a.tag!==27&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===t)break e;for(;a.sibling===null;){if(a.return===null||a.return===t)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}t.stateNode=s;e:switch(Ei(s,r,n),r){case"button":case"input":case"select":case"textarea":n=!!n.autoFocus;break e;case"img":n=!0;break e;default:n=!1}n&&Yr(t)}}return dt(t),t.subtreeFlags&=-33554433,km(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,i),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==n&&Yr(t);else{if(typeof n!="string"&&t.stateNode===null)throw Error(H(166));if(e=Hs.current,Mo(t)){if(e=t.stateNode,i=t.memoizedProps,n=null,r=ri,r!==null)switch(r.tag){case 27:case 5:n=r.memoizedProps}e[yi]=t,e=!!(e.nodeValue===i||n!==null&&n.suppressHydrationWarning===!0||Jx(e.nodeValue,i)),e||Zs(t,!0)}else e=Uc(e).createTextNode(n),e[yi]=t,t.stateNode=e}return dt(t),null;case 31:if(i=t.memoizedState,e===null||e.memoizedState!==null){if(n=Mo(t),i!==null){if(e===null){if(!n)throw Error(H(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(H(557));e[yi]=t}else Ba(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;dt(t),e=!1}else i=Sm(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return t.flags&256?(fn(t),t):(fn(t),null);if((t.flags&128)!==0)throw Error(H(558))}return dt(t),null;case 13:if(n=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(r=Mo(t),n!==null&&n.dehydrated!==null){if(e===null){if(!r)throw Error(H(318));if(r=t.memoizedState,r=r!==null?r.dehydrated:null,!r)throw Error(H(317));r[yi]=t}else Ba(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;dt(t),r=!1}else r=Sm(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=r),r=!0;if(!r)return t.flags&256?(fn(t),t):(fn(t),null)}return fn(t),(t.flags&128)!==0?(t.lanes=i,t):(i=n!==null,e=e!==null&&e.memoizedState!==null,i&&(n=t.child,r=null,n.alternate!==null&&n.alternate.memoizedState!==null&&n.alternate.memoizedState.cachePool!==null&&(r=n.alternate.memoizedState.cachePool.pool),s=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(s=n.memoizedState.cachePool.pool),s!==r&&(n.flags|=2048)),i!==e&&i&&(t.child.flags|=8192),Mh(t,t.updateQueue),dt(t),null);case 4:return nl(),e===null&&U_(t.stateNode.containerInfo),t.flags|=67108864,dt(t),null;case 10:return Qr(t.type),dt(t),null;case 19:if(m_(t),n=t.memoizedState,n===null)return dt(t),null;if(r=(t.flags&128)!==0,s=n.rendering,s===null)if(r)ac(n,!1);else{if(Nt!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(s=md(e),s!==null){for(t.flags|=128,ac(n,!1),e=s.updateQueue,t.updateQueue=e,Mh(t,e),t.subtreeFlags=0,e=i,i=t.child;i!==null;)p1(i,e),i=i.sibling;return Ic(t,xi.current&1|2),De&&Vr(t,n.treeForkCount),t.child}e=e.sibling}n.tail!==null&&gn()>Cd&&(t.flags|=128,r=!0,ac(n,!1),t.lanes=4194304)}else{if(!r)if(e=md(s),e!==null){if(t.flags|=128,r=!0,e=e.updateQueue,t.updateQueue=e,Mh(t,e),ac(n,!0),n.tail===null&&n.tailMode!=="collapsed"&&n.tailMode!=="visible"&&!s.alternate&&!De)return dt(t),null}else 2*gn()-n.renderingStartTime>Cd&&i!==536870912&&(t.flags|=128,r=!0,ac(n,!1),t.lanes=4194304);n.isBackwards?(s.sibling=t.child,t.child=s):(e=n.last,e!==null?e.sibling=s:t.child=s,n.last=s)}if(n.tail!==null){e=n.tail;e:{for(i=e;i!==null;){if(i.alternate!==null){i=!1;break e}i=i.sibling}i=!0}return n.rendering=e,n.tail=e.sibling,n.renderingStartTime=gn(),e.sibling=null,s=xi.current,s=r?s&1|2:s&1,n.tailMode==="visible"||n.tailMode==="collapsed"||!i||De?Ic(t,s):(i=s,pt(Ci,t),pt(xi,i),Oi===null&&(Oi=t)),De&&Vr(t,n.treeForkCount),e}return dt(t),null;case 22:case 23:return fn(t),p_(),n=t.memoizedState!==null,e!==null?e.memoizedState!==null!==n&&(t.flags|=8192):n&&(t.flags|=8192),n?(i&536870912)!==0&&(t.flags&128)===0&&(dt(t),t.subtreeFlags&6&&(t.flags|=8192)):dt(t),i=t.updateQueue,i!==null&&Mh(t,i.retryQueue),i=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),n=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(n=t.memoizedState.cachePool.pool),n!==i&&(t.flags|=2048),e!==null&&wi(Da),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),Qr(Ht),dt(t),null;case 25:return null;case 30:return t.flags|=33554432,dt(t),null}throw Error(H(156,t.tag))}function ID(e,t){switch(c_(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Qr(Ht),nl(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return sd(t),null;case 31:if(t.memoizedState!==null){if(fn(t),t.alternate===null)throw Error(H(340));Ba()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(fn(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(H(340));Ba()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return m_(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return nl(),null;case 10:return Qr(t.type),null;case 22:case 23:return fn(t),p_(),e!==null&&wi(Da),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Qr(Ht),null;case 25:return null;default:return null}}function fx(e,t){switch(c_(t),t.tag){case 3:Qr(Ht),nl();break;case 26:case 27:case 5:sd(t);break;case 4:nl();break;case 31:t.memoizedState!==null&&fn(t);break;case 13:fn(t);break;case 19:m_(t);break;case 10:Qr(t.type);break;case 22:case 23:fn(t),p_(),e!==null&&wi(Da);break;case 24:Qr(Ht)}}function Qc(e,t){try{var i=t.updateQueue,n=i!==null?i.lastEffect:null;if(n!==null){var r=n.next;i=r;do{if((i.tag&e)===e){n=void 0;var s=i.create,a=i.inst;n=s(),a.destroy=n}i=i.next}while(i!==r)}}catch(o){et(t,t.return,o)}}function Js(e,t,i){try{var n=t.updateQueue,r=n!==null?n.lastEffect:null;if(r!==null){var s=r.next;n=s;do{if((n.tag&e)===e){var a=n.inst,o=a.destroy;if(o!==void 0){a.destroy=void 0,r=t;var l=i,c=o;try{c()}catch(u){et(r,l,u)}}}n=n.next}while(n!==s)}}catch(u){et(t,t.return,u)}}function px(e){var t=e.updateQueue;if(t!==null){var i=e.stateNode;try{E1(t,i)}catch(n){et(e,e.return,n)}}}function mx(e,t,i){i.props=qa(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(n){et(e,t,n)}}function br(e,t){try{var i=e.ref;if(i!==null){switch(e.tag){case 26:case 27:case 5:var n=e.stateNode;break;case 30:var r=e.stateNode,s=es(e.memoizedProps,r);(r.ref===null||r.ref.name!==s)&&(r.ref=sE(s)),n=r.ref;break;case 7:if(e.stateNode===null){var a=new Sn(e);nn(e.child,!1,xL,a,void 0,void 0),e.stateNode=a}n=e.stateNode;break;default:n=e.stateNode}typeof i=="function"?e.refCleanup=i(n):i.current=n}}catch(o){et(e,t,o)}}function bi(e,t){var i=e.ref,n=e.refCleanup;if(i!==null)if(typeof n=="function")try{n()}catch(r){et(e,t,r)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(r){et(e,t,r)}else i.current=null}function yd(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var i=0;i title"))),Ei(n,t,i),n[yi]=e,ni(n),t=n;break e;case"link":if(s=mw("link","href",r).get(t+(i.href||""))){for(a=0;aS&&(a=S,S=_,_=a);var m=uS(o,_),g=uS(o,S);if(m&&g&&(f.rangeCount!==1||f.anchorNode!==m.node||f.anchorOffset!==m.offset||f.focusNode!==g.node||f.focusOffset!==g.offset)){var b=h.createRange();b.setStart(m.node,m.offset),f.removeAllRanges(),_>S?(f.addRange(b),f.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),f.addRange(b))}}}}for(h=[],f=o;f=f.parentNode;)f.nodeType===1&&h.push({element:f,left:f.scrollLeft,top:f.scrollTop});for(typeof o.focus=="function"&&o.focus(),o=0;oi?32:i,be.T=null,i=Og,Og=null;var s=rr,a=kr;if(Et=0,Ka=rr=null,kr=0,($e&6)!==0)throw Error(H(331));var o=$e;if($e|=4,Lx(s.current),Rx(s,s.current,a,i),$e=o,Jc(0,!1),_n&&typeof _n.onPostCommitFiberRoot=="function")try{_n.onPostCommitFiberRoot($c,s)}catch{}return!0}finally{Ge.p=r,be.T=n,Gx(e,t)}}function VS(e,t,i){t=zn(i,t),t=mg(e.stateNode,t,2),e=Ks(e,t,2),e!==null&&(jc(e,2),Ar(e))}function et(e,t,i){if(e.tag===3)VS(e,e,i);else for(;t!==null;){if(t.tag===3){VS(t,e,i);break}else if(t.tag===1){var n=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(Gs===null||!Gs.has(n))){e=zn(i,e),i=ox(2),n=Ks(t,i,2),n!==null&&(lx(i,n,t,e),jc(n,2),Ar(n));break}}t=t.return}}function Rm(e,t,i){var n=e.pingCache;if(n===null){n=e.pingCache=new UD;var r=new Set;n.set(t,r)}else r=n.get(t),r===void 0&&(r=new Set,n.set(t,r));r.has(i)||(B_=!0,r.add(i),e=jD.bind(null,e,t,i),t.then(e,e))}function jD(e,t,i){var n=e.pingCache;n!==null&&n.delete(t),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,lt===e&&(Pe&i)===i&&((Nt===4||Nt===3&&(Pe&62914560)===Pe&&300>gn()-Gd)&&($e&2)===0?cl(e,0):Ed|=i,ol===Pe&&(ol=0)),Ar(e)}function jx(e,t){t===0&&(t=zw()),e=ja(e,t),e!==null&&(jc(e,t),Ar(e))}function YD(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),jx(e,i)}function VD(e,t){var i=0;switch(e.tag){case 31:case 13:var n=e.stateNode,r=e.memoizedState;r!==null&&(i=r.retryLane);break;case 19:n=e.stateNode;break;case 22:n=e.stateNode._retryCache;break;default:throw Error(H(314))}n!==null&&n.delete(t),jx(e,i)}function XD(e,t){return Zg(e,t)}var ul=null,Lo=null,zg=!1,Nd=!1,Om=!1,Us=0;function Ar(e){e!==Lo&&e.next===null&&(Lo===null?ul=Lo=e:Lo=Lo.next=e),Nd=!0,zg||(zg=!0,QD())}function Jc(e,t){if(!Om&&Nd){Om=!0;do for(var i=!1,n=ul;n!==null;){if(!t)if(e!==0){var r=n.pendingLanes;if(r===0)var s=0;else{var a=n.suspendedLanes,o=n.pingedLanes;s=(1<<31-vn(42|e)+1)-1,s&=r&~(a&~o),s=s&201326741?s&201326741|1:s?s|2:0}s!==0&&(i=!0,XS(n,s))}else s=Pe,s=Od(n,n===lt?s:0,n.cancelPendingCommit!==null||n.timeoutHandle!==-1),(s&3)===0||Gc(n,s)||(i=!0,XS(n,s));n=n.next}while(i);Om=!1}}function ZD(){Yx()}function Yx(){Nd=zg=!1;var e=0;Us!==0&&oL()&&(e=Us);for(var t=gn(),i=null,n=ul;n!==null;){var r=n.next,s=Vx(n,t);s===0?(n.next=null,i===null?ul=r:i.next=r,r===null&&(Lo=i)):(i=n,(e!==0||(s&3)!==0)&&(Nd=!0)),n=r}Et!==0&&Et!==5||Jc(e,!1),Us!==0&&(Us=0)}function Vx(e,t){for(var i=e.suspendedLanes,n=e.pingedLanes,r=e.expirationTimes,s=e.pendingLanes&-62914561;0o)break;var u=l.transferSize,h=l.initiatorType;u&&iw(h)&&(l=l.responseEnd,a+=u*(led){_.length=p;break}b=new Promise(fL.bind(b)),_.push(b)}}}if(0<_.length)return d=Promise.race([Promise.all(_),new Promise(function(E){return setTimeout(E,500)})]).then(r,r),(f?Promise.allSettled([f.finished,d]):d).then(s,s);if(r(),f)return f.finished.then(s,s);s()},types:i});c.__reactViewTransition=u;var h=[];return u.ready.then(function(){for(var d=c.documentElement.getAnimations({subtree:!0}),f=0;f"u"?null:document;function fE(e,t,i){var n=Sl;if(n&&typeof t=="string"&&t){var r=Bn(t);r='link[rel="'+e+'"][href="'+r+'"]',typeof i=="string"&&(r+='[crossorigin="'+i+'"]'),dw.has(r)||(dw.add(r),e={rel:e,crossOrigin:i,href:t},n.querySelector(r)===null&&(t=n.createElement("link"),Ei(t,"link",e),ni(t),n.head.appendChild(t)))}}function OL(e){os.D(e),fE("dns-prefetch",e,null)}function DL(e,t){os.C(e,t),fE("preconnect",e,t)}function LL(e,t,i){os.L(e,t,i);var n=Sl;if(n&&e&&t){var r='link[rel="preload"][as="'+Bn(t)+'"]';t==="image"&&i&&i.imageSrcSet?(r+='[imagesrcset="'+Bn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(r+='[imagesizes="'+Bn(i.imageSizes)+'"]')):r+='[href="'+Bn(e)+'"]';var s=r;switch(t){case"style":s=dl(e);break;case"script":s=wl(e)}if(!(Hn.has(s)||(e=ct({rel:"preload",href:t==="image"&&i&&i.imageSrcSet?void 0:e,as:t},i),Hn.set(s,e),n.querySelector(r)!==null||t==="style"&&n.querySelector(eu(s))||t==="script"&&n.querySelector(tu(s))))){var a=n.createElement("link");Ei(a,"link",e),t==="style"&&(a[od]=!0,a.onload=a.onerror=function(){qw(a)}),ni(a),n.head.appendChild(a)}}}function IL(e,t){os.m(e,t);var i=Sl;if(i&&e){var n=t&&typeof t.as=="string"?t.as:"script",r='link[rel="modulepreload"][as="'+Bn(n)+'"][href="'+Bn(e)+'"]',s=r;switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":s=wl(e)}if(!Hn.has(s)&&(e=ct({rel:"modulepreload",href:e},t),Hn.set(s,e),i.querySelector(r)===null)){switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(tu(s)))return}n=i.createElement("link"),Ei(n,"link",e),ni(n),i.head.appendChild(n)}}}function BL(e,t,i){os.S(e,t,i);var n=Sl;if(n&&e){var r=jo(n).hoistableStyles,s=dl(e);t=t||"default";var a=r.get(s);if(!a){var o={loading:0,preload:null};if(a=n.querySelector(eu(s)))o.loading=5;else{e=ct({rel:"stylesheet",href:e,"data-precedence":t},i),(i=Hn.get(s))&&K_(e,i);var l=a=n.createElement("link");ni(l),Ei(l,"link",e),l._p=new Promise(function(c,u){l.onload=c,l.onerror=u}),l.addEventListener("load",function(){o.loading|=1}),l.addEventListener("error",function(){o.loading|=2}),o.loading|=4,Qh(a,t,n)}a={type:"stylesheet",instance:a,count:1,state:o},r.set(s,a)}}}function zL(e,t){os.X(e,t);var i=Sl;if(i&&e){var n=jo(i).hoistableScripts,r=wl(e),s=n.get(r);s||(s=i.querySelector(tu(r)),s||(e=ct({src:e,async:!0},t),(t=Hn.get(r))&&W_(e,t),s=i.createElement("script"),ni(s),Ei(s,"link",e),i.head.appendChild(s)),s={type:"script",instance:s,count:1,state:null},n.set(r,s))}}function PL(e,t){os.M(e,t);var i=Sl;if(i&&e){var n=jo(i).hoistableScripts,r=wl(e),s=n.get(r);s||(s=i.querySelector(tu(r)),s||(e=ct({src:e,async:!0,type:"module"},t),(t=Hn.get(r))&&W_(e,t),s=i.createElement("script"),ni(s),Ei(s,"link",e),i.head.appendChild(s)),s={type:"script",instance:s,count:1,state:null},n.set(r,s))}}function fw(e,t,i,n){var r=(r=Hs.current)?Hc(r):null;if(!r)throw Error(H(446));switch(e){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(i=dl(i.href),t=jo(r).hoistableStyles,n=t.get(i),n||(n={type:"style",instance:null,count:0,state:null},t.set(i,n)),n):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){e=dl(i.href);var s=jo(r).hoistableStyles,a=s.get(e);if(a||(r=r.ownerDocument||r,a={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},s.set(e,a),(s=r.querySelector(eu(e)))?s._p||(a.instance=s,a.state.loading=5):(s=Hn.get(e),s||(s={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},Hn.set(e,s)),UL(r,e,s,a.state))),t&&n===null)throw Error(H(528,""));return a}if(t&&n!==null)throw Error(H(529,""));return null;case"script":return t=i.async,i=i.src,typeof i=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(i=wl(i),t=jo(r).hoistableScripts,n=t.get(i),n||(n={type:"script",instance:null,count:0,state:null},t.set(i,n)),n):{type:"void",instance:null,count:0,state:null};default:throw Error(H(444,e))}}function dl(e){return'href="'+Bn(e)+'"'}function eu(e){return'link[rel="stylesheet"]['+e+"]"}function pE(e){return ct({},e,{"data-precedence":e.precedence,precedence:null})}function UL(e,t,i,n){if(t=e.querySelector('link[rel="preload"][as="style"]['+t+"]")){if(t[od]!==!0){n.loading=1;return}}else t=e.createElement("link"),t[od]=!0,t.onload=t.onerror=qw.bind(null,t),Ei(t,"link",i),ni(t),e.head.appendChild(t);n.preload=t,t.addEventListener("load",function(){return n.loading|=1}),t.addEventListener("error",function(){return n.loading|=2})}function wl(e){return'[src="'+Bn(e)+'"]'}function tu(e){return"script[async]"+e}function pw(e,t,i){if(t.count++,t.instance===null)switch(t.type){case"style":var n=e.querySelector('style[data-href~="'+Bn(i.href)+'"]');if(n)return t.instance=n,ni(n),n;var r=ct({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return n=(e.ownerDocument||e).createElement("style"),ni(n),Ei(n,"style",r),Qh(n,i.precedence,e),t.instance=n;case"stylesheet":r=dl(i.href);var s=e.querySelector(eu(r));if(s)return t.state.loading|=4,t.instance=s,ni(s),s;n=pE(i),(r=Hn.get(r))&&K_(n,r),s=(e.ownerDocument||e).createElement("link"),ni(s);var a=s;return a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),Ei(s,"link",n),t.state.loading|=4,Qh(s,i.precedence,e),t.instance=s;case"script":return s=wl(i.src),(r=e.querySelector(tu(s)))?(t.instance=r,ni(r),r):(n=i,(r=Hn.get(s))&&(n=ct({},i),W_(n,r)),e=e.ownerDocument||e,r=e.createElement("script"),ni(r),Ei(r,"link",n),e.head.appendChild(r),t.instance=r);case"void":return null;default:throw Error(H(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(n=t.instance,t.state.loading|=4,Qh(n,i.precedence,e));return t.instance}function Qh(e,t,i){for(var n=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),r=n.length?n[n.length-1]:null,s=r,a=0;a title"):null)}function HL(e,t,i){if(i===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function gw(e,t){return e==="img"&&t.src!=null&&t.src!==""&&t.onLoad==null&&t.loading!=="lazy"}function mE(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function gE(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function _w(e,t){typeof t.decode=="function"&&(e.imgCount++,t.complete||(e.imgBytes+=gE(t),e.suspenseyImages.push(t)),e=KL.bind(e),t.decode().then(e,e))}function FL(e,t,i,n){if(i.type==="stylesheet"&&(typeof n.media!="string"||matchMedia(n.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var r=dl(n.href),s=t.querySelector(eu(r));if(s){t=s._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Fc.bind(e),t.then(e,e)),i.state.loading|=4,i.instance=s,ni(s);return}s=t.ownerDocument||t,n=pE(n),(r=Hn.get(r))&&K_(n,r),s=s.createElement("link"),ni(s);var a=s;a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),Ei(s,"link",n),i.instance=s}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(i,t),(t=i.state.preload)&&(i.state.loading&3)===0&&(e.count++,i=Fc.bind(e),t.addEventListener("load",i),t.addEventListener("error",i))}}var ed=0;function qL(e,t){return e.stylesheets&&e.count===0&&td(e,e.stylesheets),0ed?50:800)+t);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(n),clearTimeout(r)}}:null}function _E(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)td(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function Fc(){this.count--,_E(this)}function KL(){this.imgCount--,_E(this)}var Md=null;function td(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Md=new Map,t.forEach(WL,e),Md=null,Fc.call(e))}function WL(e,t){if(!(t.state.loading&4)){var i=Md.get(e);if(i)var n=i.get(null);else{i=new Map,Md.set(e,i);for(var r=e.querySelectorAll("link[data-precedence],style[data-precedence]"),s=0;s{"use strict";function kE(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(kE)}catch(e){console.error(e)}}kE(),TE.exports=CE()});function QL(e){return/^accent(-|$)/i.test(e.replace(/^--/,"").replace(/^magpie-/i,""))}function AE(e){let t=new URLSearchParams(e).get("tokens");if(!t)return;let i;try{i=JSON.parse(decodeURIComponent(escape(atob(t))))}catch{return}V_(i)}function JL(e){let t={};if(!e||typeof e!="object")return t;for(let[i,n]of Object.entries(e)){if(typeof n!="string"&&typeof n!="number")continue;let r=String(n).trim();if(!r||r.length>300||/[;{}<>]/.test(r)||QL(i))continue;let s=i.replace(/^--/,"").replace(/^magpie-/i,"");/^[a-zA-Z0-9-]{1,48}$/.test(s)&&(t[`--magpie-${s}`]=r)}return t}function V_(e){let t=document.documentElement;for(let[i,n]of Object.entries(JL(e)))t.style.setProperty(i,n)}var X_=se(()=>{});function e3(){return typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function Z_(e){return e==="light"||e==="dark"?e:"auto"}function t3(e,t,i){let n=e==="light"||e==="dark"?e:t??i;return{theme:n,hostColors:t!==null&&n===t}}function RE(e){let t=new URLSearchParams(e).get("theme");Jd=t==="light"||t==="dark"?t:null,Mr("auto"),typeof window<"u"&&window.matchMedia&&(ME=window.matchMedia("(prefers-color-scheme: dark)"),ME.addEventListener?.("change",()=>Mr(Qd)))}function OE(){return Jd!==null}function DE(e){Jd=e,Mr(Qd)}function Mr(e){Qd=Z_(e);let{theme:t,hostColors:i}=t3(Qd,Jd,e3()),n=document.documentElement;n.dataset.theme=t,i?n.dataset.hostColors="1":delete n.dataset.hostColors}function LE(){return document.documentElement.dataset.theme==="dark"?"dark":"light"}var Jd,Qd,ME,iu=se(()=>{Jd=null,Qd="auto",ME=null});function IE(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.dark!="boolean")return null;let i=t.tokens&&typeof t.tokens=="object"&&!Array.isArray(t.tokens)?t.tokens:{},n={dark:t.dark,tokens:i};return typeof t.lang=="string"&&t.lang.length<=32&&(n.lang=t.lang),n}function i3(e,t){if(!e||typeof e!="object")return null;let i=e;return i.magpie!==1?null:i.event==="theme"?IE(i.data):i.id===t&&i.result?IE(i.result):null}function zE(e){if(BE||typeof window>"u")return;let t=window.parent;if(!t||t===window)return;BE=!0;let i=1e6+Math.floor(Math.random()*1e6);window.addEventListener("message",n=>{if(n.source!==t)return;let r=i3(n.data,i);r&&(V_(r.tokens),DE(r.dark?"dark":"light"),e?.(r))});try{t.postMessage({magpie:1,id:i,method:"hello"},"*")}catch{}}var BE,PE=se(()=>{X_();iu();BE=!1});function tf(e){return e==="narrow"||e==="wide"||e==="full"?e:"default"}function r3(e){let t=tf(e);return t==="full"?"100%":`${n3[t]}px`}function ev(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(Q_,Math.max(ef,Math.round(t))):J_}function nu(e){let t=document.documentElement;t.style.setProperty("--col",r3(e.contentWidth)),t.style.setProperty("--chat-fs",`${ev(e.chatFontSize)}px`),t.dataset.contentWidth=tf(e.contentWidth)}var n3,ef,Q_,J_,tv=se(()=>{n3={narrow:640,default:720,wide:880},ef=12,Q_=18,J_=13});function s3(e){if(typeof e!="string"||!e||e.length>2048)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password)return null;let i=t.hostname.toLowerCase();return i!=="127.0.0.1"&&i!=="localhost"&&i!=="[::1]"||!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(t.pathname)?null:`${t.protocol}//${t.host}${t.pathname}${t.search}`}function a3(e){let t=e.startsWith("#")?e.slice(1):e;return s3(new URLSearchParams(t).get("b"))}function o3(e,t){let i=a3(e);if(!i)return null;let n=new URL(i);return t>0&&n.searchParams.set("ac_lost",String(Math.floor(t))),n.toString()}function rf(){let e=o3(location.hash,nf);return e?(location.replace(e),!0):!1}function UE(e,t,i=5e3){let n=null,r=e.onState(s=>{s==="reconnecting"||s==="down"?(nf||(nf=Date.now()),n||(n=setTimeout(()=>{n=null,e.getState()!=="open"&&t()},i))):s==="open"&&(nf=0,n&&(clearTimeout(n),n=null))});return()=>{r(),n&&clearTimeout(n)}}var nf,iv=se(()=>{nf=0});var sf,HE=se(()=>{Pt();sf=class{constructor(t,i="zh"){fe(this,"token",t);fe(this,"lang",i);fe(this,"ws",null);fe(this,"seq",0);fe(this,"pending",new Map);fe(this,"subs",new Map);fe(this,"binHandlers",[]);fe(this,"stateListeners",new Set);fe(this,"state","connecting");fe(this,"retry",0);fe(this,"closed",!1);fe(this,"helloOk",null);fe(this,"helloWaiters",[])}setLang(t){this.lang=t}onState(t){return this.stateListeners.add(t),t(this.state),()=>this.stateListeners.delete(t)}getState(){return this.state}setState(t){this.state=t;for(let i of this.stateListeners)i(t)}connect(){if(this.closed)return;this.setState(this.retry===0?"connecting":"reconnecting");let t=new WebSocket(`ws://${location.host}/ws`);t.binaryType="arraybuffer",this.ws=t,t.onopen=()=>{t.send(JSON.stringify({t:"hello",token:this.token,v:1,lang:this.lang}))},t.onmessage=i=>{if(typeof i.data!="string"){this.onBinary(new Uint8Array(i.data));return}let n;try{n=JSON.parse(i.data)}catch{return}if(n.t==="hello.ok"){this.retry=0,this.helloOk=n,this.setState("open");let r=this.helloWaiters.splice(0);for(let s of r)s(n);for(let[s,a]of this.subs)this.call("sub.add",{ch:s,afterSeq:a.afterSeq?.()}).catch(()=>{});return}if(n.t==="res"){let r=n.id,s=this.pending.get(r);if(s)if(this.pending.delete(r),clearTimeout(s.timer),n.ok)s.res(n.r);else{let a=n.e,o=new Error(a?.message??v("api.requestFailed"));o.code=a?.code,s.rej(o)}return}if(n.t==="evt"){this.subs.get(n.ch)?.handler(n.ch,n.d);return}},t.onclose=()=>{this.ws=null;for(let[n,r]of this.pending)clearTimeout(r.timer),r.rej(new Error(v("api.connClosed"))),this.pending.delete(n);if(this.closed)return;this.retry++;let i=Math.min(1e3*Math.pow(2,this.retry-1),1e4);this.setState(this.retry>20?"down":"reconnecting"),setTimeout(()=>this.connect(),i)},t.onerror=()=>{}}waitHello(){return this.helloOk?Promise.resolve(this.helloOk):new Promise(t=>this.helloWaiters.push(t))}call(t,i,n=6e4){return new Promise((r,s)=>{let a=this.ws;if(!a||a.readyState!==WebSocket.OPEN){s(new Error(v("api.notConnected")));return}let o=++this.seq,l=setTimeout(()=>{this.pending.delete(o),s(new Error(v("api.timeout")))},n);this.pending.set(o,{res:r,rej:s,timer:l}),a.send(JSON.stringify({t:"req",id:o,m:t,p:i??{}}))})}subscribe(t,i,n){return this.subs.set(t,{handler:i,afterSeq:n}),this.state==="open"&&this.call("sub.add",{ch:t,afterSeq:n?.()}).catch(()=>{}),()=>{this.subs.delete(t),this.state==="open"&&this.call("sub.remove",{ch:t}).catch(()=>{})}}onBinaryFrame(t){return this.binHandlers.push(t),()=>{this.binHandlers=this.binHandlers.filter(i=>i!==t)}}onBinary(t){if(t.length<3)return;let i=t[0],n=t[1]<<8|t[2];for(let r of this.binHandlers)r(i,n,t.subarray(3))}sendBinary(t,i,n){let r=this.ws;if(!r||r.readyState!==WebSocket.OPEN)return;let s=new Uint8Array(3+n.length);s[0]=t,s[1]=i>>8&255,s[2]=i&255,s.set(n,3),r.send(s)}ping(){try{this.ws?.send(JSON.stringify({t:"ping"}))}catch{}}close(){this.closed=!0,this.ws?.close()}}});var Rr,ru=se(()=>{Sa();Rr=Mn(e=>({state:"connecting",version:null,set:t=>e(t)}))});function ls(e,t=window.innerWidth){if(t<900)return su;let i=e.sbHidden?0:e.sidebarWidth;return xl(t-i-qE-FE,na,su)}function El(e,t=window.innerWidth){if(t<760)return nv;let i=e.panelOpen?e.panelWidth:0;return xl(t-i-qE-FE,Va,nv)}function af(e,t=window.innerWidth){let i=xl(e.sidebarWidth,Va,El(e,t)),n=xl(e.panelWidth,na,ls({...e,sidebarWidth:i},t));return i=xl(i,Va,El({...e,sidebarWidth:i,panelWidth:n},t)),n=xl(n,na,ls({...e,sidebarWidth:i,panelWidth:n},t)),{sidebarWidth:i,panelWidth:n}}var FE,qE,xl,of=se(()=>{$i();FE=300,qE=10,xl=(e,t,i)=>Math.max(t,Math.min(i,e))});function ra(e,t){let i=e().ws;i&&i.call("settings.set",{patch:t}).catch(()=>{})}var l3,Va,nv,na,su,rv,le,$i=se(()=>{Sa();of();l3=["changes","files","terminal","preview"],Va=200,nv=360,na=320,su=900,rv=(e,t,i)=>Math.max(t,Math.min(i,e));le=Mn((e,t)=>({ws:null,sidebarWidth:248,sbHidden:!1,sbOpen:!1,panelOpen:!1,panelTab:"changes",panelWidth:440,collapsed:{},currentProjectId:null,currentThreadId:null,bind:i=>e({ws:i}),hydrate:i=>{let n={};for(let a of i.collapsedProjects??[])n[a]=!0;let r={sidebarWidth:i.sidebarWidth??248,panelWidth:i.panel?.width??440,panelOpen:i.panel?.open??!1,sbHidden:i.sidebarHidden===!0},s=af(r);e({sidebarWidth:s.sidebarWidth,sbHidden:r.sbHidden,panelOpen:r.panelOpen,panelTab:l3.includes(i.panel?.tab)?i.panel.tab:"changes",panelWidth:s.panelWidth,collapsed:n,currentProjectId:i.lastProjectId??null,currentThreadId:i.lastThreadId??null})},setSidebarWidth:i=>{let n=t(),r=El(n);i=rv(Math.round(i),Va,r),e({sidebarWidth:i}),ra(t,{sidebarWidth:i})},setPanelWidth:i=>{let n=t(),r=ls(n);i=rv(Math.round(i),na,r),e({panelWidth:i}),ra(t,{panel:{open:t().panelOpen,tab:t().panelTab,width:i}})},openPanel:i=>{let n=i??t().panelTab,r=t(),s=rv(r.panelWidth,na,ls({...r,panelOpen:!0}));e({panelOpen:!0,panelTab:n,panelWidth:s}),ra(t,{panel:{open:!0,tab:n,width:s}})},closePanel:()=>{e({panelOpen:!1}),ra(t,{panel:{open:!1,tab:t().panelTab,width:t().panelWidth}})},setPanelTab:i=>{e({panelTab:i}),ra(t,{panel:{open:t().panelOpen,tab:i,width:t().panelWidth}})},toggleSidebarHidden:()=>{let i=!t().sbHidden;e({sbHidden:i}),ra(t,{sidebarHidden:i})},toggleSidebar:()=>{typeof window<"u"&&window.matchMedia?.("(max-width: 759px)").matches?t().setSbOpen(!t().sbOpen):t().toggleSidebarHidden()},setSbOpen:i=>e({sbOpen:i}),toggleCollapsed:i=>{let n={...t().collapsed};n[i]?delete n[i]:n[i]=!0,e({collapsed:n}),ra(t,{collapsedProjects:Object.keys(n)})},select:(i,n)=>{e({currentProjectId:i,currentThreadId:n,sbOpen:!1}),ra(t,{lastProjectId:i,lastThreadId:n})},reconcileSelection:(i,n)=>{let{currentProjectId:r,currentThreadId:s}=t();if(i.length===0){(r||s)&&t().select(null,null);return}let a=r;(!a||!i.some(l=>l.id===a))&&(a=null);let o=s;if(o){let l=n.find(c=>c.id===o);!l||!i.some(c=>c.id===l.projectId)||a&&l.projectId!==a?o=null:a||(a=l.projectId)}(a!==r||o!==s)&&t().select(a,o)}}))});async function Cl(){let e="claude";try{e=(await rt.getState().ws.call("settings.get")).defaultProvider??"claude"}catch{}let t=rt.getState().providers;return t.length?t.find(i=>i.id===e&&KE(i))?.id??t.find(i=>KE(i))?.id??e:e}function KE(e){return e.enabled===!1||!e.available||e.status==="planned"?!1:e.status==="verified"||e.status==="experimental"?!0:e.ready!==!1}var rt,Fn=se(()=>{Sa();$i();rt=Mn((e,t)=>({ws:null,loaded:!1,projects:[],threads:[],providers:[],bind:async i=>{if(t().ws===i&&t().loaded)return;e({ws:i}),i.subscribe("sidebar",(l,c)=>{let u=c;!u||typeof u!="object"||(u.type==="project.upsert"?t().upsertProject(u.project):u.type==="project.remove"?(e({projects:t().projects.filter(h=>h.id!==u.id)}),le.getState().reconcileSelection(t().projects,t().threads)):u.type==="thread.upsert"?t().upsertThread(u.thread):u.type==="thread.remove"&&(e({threads:t().threads.filter(h=>h.id!==u.id)}),le.getState().reconcileSelection(t().projects,t().threads)))}),i.call("providers.list").then(l=>e({providers:l})).catch(()=>{});let[n,r]=await Promise.all([i.call("projects.list"),i.call("threads.list")]),s=t(),a=new Map(n.map(l=>[l.id,l]));for(let l of s.projects)a.set(l.id,l);let o=new Map(r.map(l=>[l.id,l]));for(let l of s.threads)o.set(l.id,l);e({projects:[...a.values()].sort((l,c)=>l.createdAt-c.createdAt),threads:[...o.values()],loaded:!0}),le.getState().reconcileSelection(t().projects,t().threads)},upsertProject:i=>{let n=t().projects.filter(r=>r.id!==i.id);e({projects:[...n,i].sort((r,s)=>r.createdAt-s.createdAt)})},upsertThread:i=>{let n=t().threads.filter(r=>r.id!==i.id);e({threads:[...n,i]})}}))});var $E=ve(lf=>{"use strict";var c3=Symbol.for("react.transitional.element"),u3=Symbol.for("react.fragment");function WE(e,t,i){var n=null;if(i!==void 0&&(n=""+i),t.key!==void 0&&(n=""+t.key),"key"in t){i={};for(var r in t)r!=="key"&&(i[r]=t[r])}else i=t;return t=i.ref,{$$typeof:c3,type:e,key:n,ref:t!==void 0?t:null,props:i}}lf.Fragment=u3;lf.jsx=WE;lf.jsxs=WE});var ke=ve(($H,GE)=>{"use strict";GE.exports=$E()});function YE(e){let[t,i]=(0,At.useState)(()=>window.matchMedia?.(e).matches??!1);return(0,At.useEffect)(()=>{let n=window.matchMedia?.(e);if(!n)return;let r=()=>i(n.matches);return n.addEventListener?.("change",r),r(),()=>n.removeEventListener?.("change",r)},[e]),t}function VE(e,t,i){let n=(0,At.useRef)(0),r=(0,At.useRef)(0),[s,a]=(0,At.useState)(!1),o=(0,At.useCallback)(l=>{l.preventDefault(),n.current=l.clientX,r.current=e(),a(!0),document.body.classList.add("col-drag");let c=h=>t(r.current,h.clientX-n.current),u=()=>{window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",u),document.body.classList.remove("col-drag"),a(!1),i()};window.addEventListener("pointermove",c),window.addEventListener("pointerup",u)},[e,t,i]);return{drag:s,down:o}}function XE({sidebar:e,topbar:t,children:i,panel:n}){let r=le(),s=YE("(max-width: 759px)"),a=YE("(max-width: 899px)"),o=(0,At.useRef)(!1),l=(0,At.useRef)(!1),c=VE((0,At.useCallback)(()=>le.getState().sidebarWidth,[]),(0,At.useCallback)((d,f)=>{o.current=!0;let p=le.getState(),_=El(p);le.setState({sidebarWidth:jE(Math.round(d+f),Va,_)})},[]),(0,At.useCallback)(()=>{o.current&&(o.current=!1,le.getState().setSidebarWidth(le.getState().sidebarWidth))},[])),u=VE((0,At.useCallback)(()=>le.getState().panelWidth,[]),(0,At.useCallback)((d,f)=>{l.current=!0;let p=le.getState(),_=ls(p);le.setState({panelWidth:jE(Math.round(d-f),na,_)})},[]),(0,At.useCallback)(()=>{l.current&&(l.current=!1,le.getState().setPanelWidth(le.getState().panelWidth))},[]));(0,At.useEffect)(()=>{let d=f=>{if(!(f.ctrlKey||f.metaKey))return;let p=f.key.toLowerCase();if(p==="b")f.preventDefault(),le.getState().toggleSidebar();else if(p==="j"){f.preventDefault();let _=le.getState();_.panelOpen?_.closePanel():_.openPanel()}};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[]),(0,At.useEffect)(()=>{document.documentElement.style.setProperty("--sb-w",`${r.sidebarWidth}px`)},[r.sidebarWidth]),(0,At.useEffect)(()=>{document.documentElement.style.setProperty("--pn-w",`${r.panelWidth}px`)},[r.panelWidth]),(0,At.useEffect)(()=>{let d=()=>{let f=le.getState(),p=af(f);p.sidebarWidth!==f.sidebarWidth&&le.getState().setSidebarWidth(p.sidebarWidth),p.panelWidth!==f.panelWidth&&le.getState().setPanelWidth(p.panelWidth)};return window.addEventListener("resize",d),d(),()=>window.removeEventListener("resize",d)},[]);let h=r.sbOpen||r.panelOpen&&a;return(0,cs.jsxs)("div",{className:"app",children:[(0,cs.jsx)("aside",{className:`sidebar${r.sbHidden&&!s?" w-hide":""}${r.sbOpen?" open":""}`,children:e}),(0,cs.jsx)("div",{className:`rs rs-l${c.drag?" drag":""}`,onPointerDown:c.down}),(0,cs.jsxs)("main",{className:"main",children:[t,i]}),(0,cs.jsx)("div",{className:`rs rs-r${u.drag?" drag":""}`,onPointerDown:u.down}),(0,cs.jsx)("section",{className:`panel${r.panelOpen?" open":" w-hide"}`,"aria-hidden":!r.panelOpen,children:n}),(0,cs.jsx)("div",{className:`scrim${h?" show":""}`,onClick:()=>{le.getState().setSbOpen(!1),le.getState().panelOpen&&a&&le.getState().closePanel()}})]})}var At,cs,jE,ZE=se(()=>{At=ae(kt(),1);$i();of();cs=ae(ke(),1),jE=(e,t,i)=>Math.max(t,Math.min(i,e))});function qn(e){return!!e.isComposing||e.keyCode===229}var kl=se(()=>{});function sv(e,t=Date.now()){let i=Math.max(0,t-e),n=Math.floor(i/6e4);if(n<1)return v("common.justNow");if(n<60)return Me("common.minutesAgo",{n});let r=Math.floor(n/60);if(r<24)return Me("common.hoursAgo",{n:r});let s=Math.floor(r/24);if(s<7)return Me("common.daysAgo",{n:s});let a=new Date(e),o=ch();return wa()==="zh"?`${a.getMonth()+1}/${a.getDate()}`:a.toLocaleDateString(o,{month:"short",day:"numeric"})}function Tl(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function cf(e){return`$${e.toFixed(2)}`}function av(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60?` ${t%60}s`:""}`}var uf=se(()=>{Pt()});function Xa({x:e,y:t,items:i,onClose:n}){let r=(0,us.useRef)(null),[s,a]=(0,us.useState)({left:e,top:t});return(0,us.useLayoutEffect)(()=>{let o=r.current;if(!o)return;let l=o.getBoundingClientRect(),{left:c,top:u}=s;c+l.width>window.innerWidth-8&&(c=Math.max(8,window.innerWidth-l.width-8)),u+l.height>window.innerHeight-8&&(u=Math.max(8,window.innerHeight-l.height-8)),(c!==s.left||u!==s.top)&&a({left:c,top:u})},[e,t]),(0,us.useEffect)(()=>{let o=c=>{r.current&&!r.current.contains(c.target)&&n()},l=c=>{c.key==="Escape"&&(c.stopPropagation(),n())};return window.addEventListener("pointerdown",o,!0),window.addEventListener("keydown",l,!0),()=>{window.removeEventListener("pointerdown",o,!0),window.removeEventListener("keydown",l,!0)}},[n]),(0,QE.createPortal)((0,sa.jsx)("div",{ref:r,className:"menu",style:s,role:"menu",children:i.map((o,l)=>o.kind==="sep"?(0,sa.jsx)("div",{className:"msep"},l):o.kind==="label"?(0,sa.jsx)("div",{className:"mlabel",children:o.text},l):(0,sa.jsxs)("button",{className:`mi${o.danger?" danger":""}`,disabled:o.disabled,role:"menuitem",onClick:()=>{n(),o.onClick()},children:[(0,sa.jsx)("span",{children:o.label}),o.checked&&(0,sa.jsx)("span",{className:"mi-check",children:"\u2713"})]},l))}),document.body)}function au(){let[e,t]=(0,us.useState)(null);return[e,n=>{n.preventDefault(),n.stopPropagation(),t({x:n.clientX,y:n.clientY})},()=>t(null)]}var us,QE,sa,hf=se(()=>{us=ae(kt(),1),QE=ae(xa(),1),sa=ae(ke(),1)});function Or({title:e,children:t,footer:i,onClose:n,wide:r}){return(0,JE.useEffect)(()=>{let s=a=>{a.key==="Escape"&&!document.querySelector("[data-select-menu]")&&(a.stopPropagation(),n())};return window.addEventListener("keydown",s,!0),()=>window.removeEventListener("keydown",s,!0)},[n]),(0,eC.createPortal)((0,sn.jsx)("div",{className:"dlg-scrim",onPointerDown:s=>{s.target===s.currentTarget&&n()},children:(0,sn.jsxs)("div",{className:"dlg",style:r?{width:560}:void 0,role:"dialog","aria-label":e,children:[(0,sn.jsx)("div",{className:"dlg-title",children:e}),(0,sn.jsx)("div",{className:"dlg-body",children:t}),i&&(0,sn.jsx)("div",{className:"dlg-foot",children:i})]})}),document.body)}function Nl({title:e,body:t,okLabel:i,danger:n,onOk:r,onClose:s}){let a=i??v("common.ok");return(0,sn.jsx)(Or,{title:e,onClose:s,footer:(0,sn.jsxs)(sn.Fragment,{children:[(0,sn.jsx)("button",{className:"btn ghost",onClick:s,children:v("common.cancel")}),(0,sn.jsx)("button",{className:`btn${n?" danger":" primary"}`,onClick:()=>{s(),r()},children:a})]}),children:(0,sn.jsx)("div",{className:"dlg-hint",style:{fontSize:"var(--fs-m)",color:"var(--fg)"},children:t})})}var JE,eC,sn,Al=se(()=>{JE=ae(kt(),1),eC=ae(xa(),1);Pt();sn=ae(ke(),1)});function pe({name:e,size:t=16}){let i=h3[e];return i?(0,ov.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:d3.has(e)?"currentColor":"none",stroke:"currentColor",strokeWidth:f3.has(e)?"2.2":"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,ov.jsx)("path",{d:i})}):null}var ov,h3,d3,f3,hs=se(()=>{ov=ae(ke(),1),h3={plus:"M12 5v14M5 12h14",file:"M6 3h8l4 4v14H6zM14 3v4h4",arrowLeft:"M19 12H5m6-6-6 6 6 6",arrowRight:"M5 12h14m-6-6 6 6-6 6",external:"M14 4h6v6M20 4l-9 9M18 14v6H4V6h6",globe:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-9 9h18M12 3c2.5 2.6 3.8 5.6 3.8 9s-1.3 6.4-3.8 9c-2.5-2.6-3.8-5.6-3.8-9S9.5 5.6 12 3Z",panelLeft:"M4 5h16v14H4zM9.5 5v14",widen:"M4 12h16M8 8l-4 4 4 4M16 8l4 4-4 4",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm10 17-4.5-4.5",caret:"M9 6l6 6-6 6",dots:"M5 12h.01M12 12h.01M19 12h.01",pin:"M9 4h6l1 7 3 3v2H5v-2l3-3 1-7Zm3 12v4",send:"M4 12 20 4l-4 8 4 8-16-8Zm0 0h8",stop:"M7 7h10v10H7z",attach:"M8 12l6-6a3.5 3.5 0 0 1 5 5l-7 7a5 5 0 0 1-7-7l6-6",menu:"M4 6h16M4 12h16M4 18h16",changes:"M7 4v13m0 0a3 3 0 1 0 .01 0M7 17a3 3 0 1 1-.01 0M17 7v13m0-13a3 3 0 1 0 .01 0M17 7a3 3 0 1 1-.01 0",files:"M4 4h6l2 3h8v13H4V4Z",term:"M4 5h16v14H4zM7 9l3 3-3 3m5 0h5",x:"M6 6l12 12M18 6 6 18",refresh:"M20 11a8 8 0 1 0-2.3 6.3M20 5v6h-6",copy:"M8 8h11v12H8zM5 16V4h11",check:"M5 13l4 4L19 7",gauge:"M5.6 18.4a9 9 0 1 1 12.8 0M12 13l3.5-3.5M12 13h.01",arrowUp:"M12 19V5m-6 6 6-6 6 6",stopFill:"M8 8h8v8H8z",shield:"M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3z",zap:"M13 2L4 14h7l-1 8 9-12h-7l1-8z",settings:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"},d3=new Set(["stopFill"]),f3=new Set(["arrowUp"])});function iC(){let e=tC(t=>t.list);return e.length===0?null:(0,lv.jsx)("div",{className:"toasts",children:e.map(t=>(0,lv.jsx)("div",{className:`toast${t.err?" err":""}`,children:t.text},t.id))})}var lv,p3,tC,we,Kn=se(()=>{Sa();lv=ae(ke(),1),p3=0,tC=Mn(e=>({list:[],push:(t,i)=>{let n=++p3;e(r=>({list:[...r.list,{id:n,text:t,err:i}]})),setTimeout(()=>e(r=>({list:r.list.filter(s=>s.id!==n)})),3500)}})),we=(e,t=!1)=>tC.getState().push(e,t)});function m3(e,t){return t.has(e.id)?"dot wait":e.status==="running"||e.status==="initializing"?"dot run":e.status==="error"||e.lastTurnStatus==="failed"?"dot err":"dot"}function rC({pendingByThread:e}){let{projects:t,threads:i}=rt(),n=le(),[r,s]=(0,Xe.useState)(""),[a,o]=(0,Xe.useState)({}),[l,c]=(0,Xe.useState)({}),[u,h]=(0,Xe.useState)(null),[d,f]=(0,Xe.useState)(""),[p,_]=(0,Xe.useState)(!1),[S,m]=(0,Xe.useState)(null),[g,b]=(0,Xe.useState)(null),[w,E]=(0,Xe.useState)(null),[A,O,k]=au(),[D,L,P]=au(),I=(0,Xe.useRef)({}),B=(0,Xe.useRef)(null);(0,Xe.useEffect)(()=>{let U=Ee=>{let he=Ee.detail?.projectId,Ke=t.find(J=>J.id===he)??t[0];Ke&&m(Ke)},Q=()=>_(!0);return window.addEventListener("open-import",U),window.addEventListener("open-new-project",Q),()=>{window.removeEventListener("open-import",U),window.removeEventListener("open-new-project",Q)}},[t]);let x=(0,Xe.useMemo)(()=>{let U=r.trim().toLowerCase();return U?i.filter(Q=>Q.title.toLowerCase().includes(U)):i},[i,r]),z=(0,Xe.useMemo)(()=>{let U=new Map;for(let Q of x)(!Q.archived||a[Q.projectId])&&(U.get(Q.projectId)??U.set(Q.projectId,[]).get(Q.projectId)).push(Q);for(let Q of U.values())Q.sort((Ee,he)=>Number(Ee.archived)-Number(he.archived)||Number(he.pinned)-Number(Ee.pinned)||he.updatedAt-Ee.updatedAt);return U},[x,a]),C=(0,Xe.useMemo)(()=>{let U=new Map;for(let Q of x)Q.archived&&U.set(Q.projectId,(U.get(Q.projectId)??0)+1);return U},[x]);async function N(U){try{let Q=await _3(),Ee=await Cl(),he=await V.call("threads.create",{projectId:U,provider:Ee,model:null,mode:Q.defaultMode??"default"});n.select(U,he.id)}catch(Q){we(v("sidebar.failNewThread")+ht(Q),!0)}}function R(U){return[{kind:"item",label:v("common.rename"),onClick:()=>{h(U.id),f(U.title)}},{kind:"item",label:U.pinned?v("sidebar.unpin"):v("sidebar.pin"),onClick:()=>{V.call("threads.update",{id:U.id,pinned:!U.pinned})}},{kind:"item",label:U.archived?v("sidebar.unarchive"):v("sidebar.archive"),onClick:()=>{W(U)}},{kind:"item",label:v("sidebar.exportMd"),onClick:()=>{y3(U)}},{kind:"sep"},{kind:"item",label:v("common.delete"),danger:!0,onClick:()=>b({title:v("sidebar.deleteThread"),body:Me("sidebar.deleteThreadBody",{title:U.title}),onOk:()=>{V.call("threads.delete",{id:U.id})}})}]}async function W(U){try{await V.call("threads.update",{id:U.id,archived:!U.archived}),U.archived?we(v("sidebar.unarchived")):(o(Q=>({...Q,[U.projectId]:!0})),we(v("sidebar.archivedHint")))}catch(Q){we(ht(Q),!0)}}function X(U){return[{kind:"item",label:v("sidebar.newThread"),onClick:()=>{N(U.id)}},{kind:"item",label:v("sidebar.importHist"),onClick:()=>m(U)},{kind:"item",label:v("common.rename"),onClick:()=>E(U)},{kind:"item",label:v("sidebar.openExplorer"),onClick:()=>{V.call("projects.open",{id:U.id})}},{kind:"sep"},{kind:"item",label:a[U.id]?v("sidebar.hideArchived"):v("sidebar.showArchived"),onClick:()=>o(Q=>({...Q,[U.id]:!Q[U.id]}))},{kind:"sep"},{kind:"item",label:v("sidebar.removeProject"),danger:!0,onClick:()=>b({title:v("sidebar.removeProject"),body:Me("sidebar.removeProjectBody",{name:U.name}),onOk:()=>{V.call("projects.remove",{id:U.id})}})}]}return(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)("div",{className:"sb-row",children:[(0,Y.jsx)(cv,{}),(0,Y.jsxs)("button",{className:"sb-new",onClick:()=>_(!0),children:[(0,Y.jsx)("span",{className:"sb-new-tile",children:(0,Y.jsx)(pe,{name:"plus",size:12})}),v("sidebar.newProject")]}),(0,Y.jsx)("button",{className:"ibtn",title:v("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings")),children:(0,Y.jsx)(pe,{name:"settings"})}),(0,Y.jsx)("button",{className:"ibtn",title:v("sidebar.searchTitle"),onClick:()=>B.current?.focus(),children:(0,Y.jsx)(pe,{name:"search"})})]}),(0,Y.jsx)("div",{className:"sb-row sb-row-search",children:(0,Y.jsxs)("div",{className:"sb-search",children:[(0,Y.jsx)(pe,{name:"search",size:13}),(0,Y.jsx)("input",{ref:B,placeholder:v("sidebar.filterPlaceholder"),value:r,onChange:U=>s(U.target.value),onKeyDown:U=>{U.key==="Escape"&&s("")}})]})}),(0,Y.jsxs)("div",{className:"sb-list",children:[t.length===0&&(0,Y.jsxs)("div",{className:"sb-start",children:[(0,Y.jsx)("div",{className:"sb-start-t",children:v("sidebar.noProjectsTitle")}),(0,Y.jsx)("div",{className:"sb-start-s",children:v("sidebar.noProjectsSub")}),(0,Y.jsx)("button",{className:"btn primary",onClick:()=>_(!0),children:v("sidebar.newProject")})]}),t.map(U=>{let Q=z.get(U.id)??[],Ee=n.collapsed[U.id],he=C.get(U.id)??0,Ke=l[U.id]?Q:Q.slice(0,nC);return(0,Y.jsxs)("div",{className:"pj-group",children:[(0,Y.jsxs)("div",{className:"pj",onContextMenu:J=>{I.current.project=U,O(J)},children:[(0,Y.jsxs)("button",{className:"pj-toggle",onClick:()=>n.toggleCollapsed(U.id),children:[(0,Y.jsx)("span",{className:`pj-caret${Ee?"":" open"}`,children:(0,Y.jsx)(pe,{name:"caret"})}),(0,Y.jsx)("span",{className:"pj-badge",children:U.name.slice(0,1)}),(0,Y.jsx)("span",{className:"pj-name",children:U.name})]}),(0,Y.jsx)("span",{className:"pj-count",children:Q.length||""}),(0,Y.jsx)("button",{className:"pj-act",title:v("sidebar.newThread"),onClick:()=>{N(U.id)},children:(0,Y.jsx)(pe,{name:"plus"})}),(0,Y.jsx)("button",{className:"pj-act",title:v("sidebar.projectMenu"),onClick:J=>{I.current.project=U,O(J)},children:(0,Y.jsx)(pe,{name:"dots"})})]}),!Ee&&(0,Y.jsxs)("div",{className:"pj-sessions",children:[Ke.map(J=>u===J.id?(0,Y.jsx)("div",{className:"t-item",children:(0,Y.jsx)("input",{className:"t-rename",autoFocus:!0,value:d,onChange:je=>f(je.target.value),onBlur:()=>h(null),onKeyDown:je=>{je.key==="Enter"&&!qn(je.nativeEvent)&&d.trim()?(V.call("threads.update",{id:J.id,title:d.trim()}),h(null)):je.key==="Escape"&&h(null)}})},J.id):(0,Y.jsxs)("button",{className:`t-item${n.currentThreadId===J.id?" on":""}${J.archived?" archived":""}`,onClick:()=>n.select(U.id,J.id),onContextMenu:je=>{I.current.thread=J,L(je)},children:[(0,Y.jsx)("span",{className:m3(J,e)}),J.pinned&&(0,Y.jsx)("span",{className:"t-pin",children:(0,Y.jsx)(pe,{name:"pin"})}),(0,Y.jsx)("span",{className:"t-title",children:uh(J.title,J.titleAuto)}),(0,Y.jsx)("span",{className:"t-time",children:sv(J.updatedAt)}),(0,Y.jsx)("span",{className:"t-more",role:"button",onClick:je=>{je.stopPropagation(),I.current.thread=J,L(je)},children:(0,Y.jsx)(pe,{name:"dots"})})]},J.id)),Q.length>nC&&!l[U.id]&&(0,Y.jsx)("button",{className:"pj-more",onClick:()=>c(J=>({...J,[U.id]:!0})),children:Me("sidebar.showAll",{n:Q.length})}),he>0&&(0,Y.jsx)("button",{className:"pj-more",onClick:()=>o(J=>({...J,[U.id]:!J[U.id]})),children:a[U.id]?v("sidebar.hideArchived"):Me("sidebar.archivedN",{n:he})}),Q.length===0&&he===0&&(0,Y.jsx)("div",{className:"pj-empty",children:v("sidebar.noThreads")})]})]},U.id)})]}),A&&I.current.project&&(0,Y.jsx)(Xa,{x:A.x,y:A.y,items:X(I.current.project),onClose:k}),D&&I.current.thread&&(0,Y.jsx)(Xa,{x:D.x,y:D.y,items:R(I.current.thread),onClose:P}),p&&(0,Y.jsx)(v3,{onClose:()=>_(!1)}),S&&(0,Y.jsx)(b3,{project:S,onClose:()=>m(null)}),g&&(0,Y.jsx)(Nl,{title:g.title,body:g.body,danger:!0,onOk:g.onOk,onClose:()=>b(null)}),w&&(0,Y.jsx)(g3,{project:w,onClose:()=>E(null)})]})}function g3({project:e,onClose:t}){let[i,n]=(0,Xe.useState)(e.name),r=i.trim().length>0&&i.trim()!==e.name,s=()=>{r&&V.call("projects.rename",{id:e.id,name:i.trim()}).then(t).catch(a=>we(v("sidebar.failRename")+ht(a),!0))};return(0,Y.jsx)(Or,{title:v("sidebar.renameProject"),onClose:t,footer:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)("button",{className:"btn ghost",onClick:t,children:v("common.cancel")}),(0,Y.jsx)("button",{className:"btn primary",disabled:!r,onClick:s,children:v("common.save")})]}),children:(0,Y.jsxs)("div",{className:"dlg-row",children:[(0,Y.jsx)("label",{children:v("sidebar.projectName")}),(0,Y.jsx)("input",{className:"tinput",autoFocus:!0,value:i,onChange:a=>n(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!qn(a.nativeEvent)&&s()}})]})})}function _3(){return V.call("settings.get").then(e=>e).catch(()=>({}))}function v3({onClose:e}){let[t,i]=(0,Xe.useState)(""),[n,r]=(0,Xe.useState)(null),[s,a]=(0,Xe.useState)([]),[o,l]=(0,Xe.useState)(!1),c=le();(0,Xe.useEffect)(()=>{V.call("fs.recentDirs").then(d=>a(d)).catch(()=>{})},[]),(0,Xe.useEffect)(()=>{let d=t.trim();if(!d){r(null);return}let f=setTimeout(()=>{V.call("fs.check",{path:d}).then(p=>r(p)).catch(()=>r(null))},200);return()=>clearTimeout(f)},[t]);let u=n?.exists&&n.isDir;async function h(){if(!(!u||o)){l(!0);try{let d=await V.call("projects.create",{path:t.trim()});c.select(d.id,null),e()}catch(d){we(v("sidebar.failAddProject")+ht(d),!0),l(!1)}}}return(0,Y.jsxs)(Or,{title:v("sidebar.newProjectDlg"),onClose:e,footer:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)("button",{className:"btn ghost",onClick:e,children:v("common.cancel")}),(0,Y.jsx)("button",{className:"btn primary",disabled:!u||o,onClick:()=>{h()},children:v("common.add")})]}),children:[(0,Y.jsxs)("div",{className:"dlg-row",children:[(0,Y.jsx)("label",{children:v("sidebar.dirLabel")}),(0,Y.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,Y.jsx)("input",{className:`tinput${n&&!u?" err":""}`,style:{flex:1},autoFocus:!0,placeholder:"D:\\\\path\\\\to\\\\project",value:t,onChange:d=>i(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!qn(d.nativeEvent)&&h()}}),(0,Y.jsx)("button",{className:"btn",style:{flex:"none",whiteSpace:"nowrap"},onClick:()=>{V.call("fs.pickFolder",{initial:t.trim()||void 0}).then(d=>{let f=d;f?.path?i(f.path):f&&!f.available&&we(v("sidebar.pickFolderUnsupported"))}).catch(()=>we(v("sidebar.pickFolderFailed")))},children:v("common.browse")})]}),n&&!n.exists&&(0,Y.jsx)("div",{className:"dlg-hint err",children:v("sidebar.dirMissing")}),n&&n.exists&&!n.isDir&&(0,Y.jsx)("div",{className:"dlg-hint err",children:v("sidebar.notDir")}),u&&(0,Y.jsx)("div",{className:"dlg-hint",children:v("sidebar.dirOk")})]}),s.length>0&&(0,Y.jsxs)("div",{className:"dlg-row",children:[(0,Y.jsx)("label",{children:v("sidebar.recent")}),s.map(d=>(0,Y.jsx)("button",{className:"mi",style:{height:26},onClick:()=>i(d),children:d},d))]})]})}function b3({project:e,onClose:t}){let[i,n]=(0,Xe.useState)(null),[r,s]=(0,Xe.useState)(new Set),[a,o]=(0,Xe.useState)(!1),l=le();(0,Xe.useEffect)(()=>{V.call("history.list",{projectId:e.id}).then(h=>n(h)).catch(h=>{we(v("sidebar.failImportList")+ht(h),!0),n([])})},[e.id]);let c=h=>{s(d=>{let f=new Set(d);return f.has(h)?f.delete(h):f.add(h),f})};async function u(){if(!(a||r.size===0||!i)){o(!0);try{let h=i.filter(f=>r.has(f.sessionId)&&!f.imported),d=await V.call("history.import",{projectId:e.id,items:h.map(f=>({provider:f.provider,sessionId:f.sessionId,title:f.title}))});we(Me("sidebar.importedN",{n:d.length})),d.length>0&&l.select(e.id,d[d.length-1].id),t()}catch(h){we(v("sidebar.failImport")+ht(h),!0)}finally{o(!1)}}}return(0,Y.jsxs)(Or,{title:Me("sidebar.importTitle",{name:e.name}),onClose:t,wide:!0,footer:(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)("button",{className:"btn ghost",onClick:t,children:v("common.cancel")}),(0,Y.jsx)("button",{className:"btn primary",disabled:a||r.size===0,onClick:()=>{u()},children:a?v("sidebar.importing"):Me("sidebar.importN",{n:r.size||0})})]}),children:[i===null&&(0,Y.jsx)("div",{className:"dlg-hint",children:v("sidebar.scanning")}),i!==null&&i.length===0&&(0,Y.jsx)("div",{className:"dlg-hint",children:v("sidebar.importEmpty")}),i!==null&&i.length>0&&(0,Y.jsx)("div",{className:"imp-list",children:i.map(h=>(0,Y.jsxs)("label",{className:`imp-row${h.imported?" done":""}`,children:[(0,Y.jsx)("input",{type:"checkbox",disabled:h.imported,checked:r.has(h.sessionId),onChange:()=>c(h.sessionId)}),(0,Y.jsx)("span",{className:"imp-title",children:h.title}),(0,Y.jsxs)("span",{className:"imp-meta",children:[h.provider," \xB7 ",h.messageCount,v("common.messages")," \xB7 ",sv(h.updatedAt),h.imported?v("common.imported"):""]})]},h.sessionId))})]})}async function y3(e){try{let t=await V.call("thread.exportMarkdown",{id:e.id});if(t.path){we(Me("sidebar.exportSaved",{path:t.path}));return}let i=new Blob([t.markdown],{type:"text/markdown;charset=utf-8"}),n=document.createElement("a");n.href=URL.createObjectURL(i),n.download=t.filename||`${e.title}.md`,n.style.display="none",document.body.appendChild(n),n.click(),setTimeout(()=>{URL.revokeObjectURL(n.href),n.remove()},5e3)}catch(t){we(v("sidebar.failExport")+ht(t),!0)}}function cv({className:e=""}){let t=le(r=>r.sbHidden),i=le(r=>r.sbOpen),n=v(t&&!i?"sidebar.expand":"sidebar.collapse");return(0,Y.jsx)("button",{type:"button",className:`ibtn sb-toggle ${e}`,title:`${n} (Ctrl+B)`,"aria-label":n,"aria-expanded":!t||i,onClick:()=>le.getState().toggleSidebar(),children:(0,Y.jsx)(pe,{name:"panelLeft"})})}var Xe,Y,nC,uv=se(()=>{Xe=ae(kt(),1);kl();Fn();$i();an();uf();hf();Al();hs();Kn();Pt();Y=ae(ke(),1),nC=10});function fv(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function mC(e){io=e}function Za(e){let t=[];return i=>{let n=Math.max(0,Math.min(3,i-1)),r=t[n];return r||(r=e(n),t[n]=r),r}}function Te(e,t=""){let i=typeof e=="string"?e:e.source,n={replace:(r,s)=>{let a=typeof s=="string"?s:s.source;return a=a.replace(si.caret,"$1"),i=i.replace(r,a),n},getRegex:()=>new RegExp(i,t)};return n}function wn(e,t){if(t){if(si.escapeTest.test(e))return e.replace(si.escapeReplace,lC)}else if(si.escapeTestNoEncode.test(e))return e.replace(si.escapeReplaceNoEncode,lC);return e}function bI(e){return si.numericCharacterReference.test(e)?e.replace(si.numericCharacterReferenceOrAmpersand,(t,i,n)=>{if(i===void 0&&n===void 0)return"&";let r=i===void 0?Number.parseInt(n,16):Number.parseInt(i,10);return r===0||r>1114111||r>=55296&&r<=57343?"\uFFFD":r===38?"&":String.fromCodePoint(r)}):e}function cC(e){try{e=encodeURI(e).replace(si.percentDecode,"%")}catch{return null}return e}function uC(e,t){let i=e.replace(si.findPipe,(s,a,o)=>{let l=!1,c=a;for(;--c>=0&&o[c]==="\\";)l=!l;return l?"|":" |"}),n=i.split(si.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length=0&&si.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(` +`)}function gf(e){return e.trim().toLowerCase().toUpperCase().toLowerCase()}function dC(e,t){if(e.indexOf(t[0])===-1&&e.indexOf(t[1])===-1)return-1;let i=0;for(let n=0;n0?-2:-1}function ff(e,t=0){let i=t,n="";for(let r of e)if(r===" "){let s=4-i%4;n+=" ".repeat(s),i+=s}else n+=r,i++;return n}function fC(e,t,i,n,r){let s=t.href,a=t.title||null,o=e[1].replace(r.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!",c=n.state.inLink,u=n.state.linkEmitted,h=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(o),f=n.state.linkEmitted;if(n.state.linkEmitted=u,n.state.inLink=c,!l){if(f){n.state.inRawBlock=h;return}n.state.linkEmitted=!0}return{type:l?"image":"link",raw:i,href:s,title:a,text:o,tokens:d}}function yI(e,t,i){let n=e.match(i.other.indentCodeCompensation);if(n===null)return t;let r=n[1];return t.split(` +`).map(s=>{let a=s.match(i.other.beginningSpace);if(a===null)return s;let[o]=a;return s.slice(Math.min(o.length,r.length))}).join(` +`)}function pC(e,t,i,n){if(!t.includes("<"))return!1;for(let r=0;rt.length-r)return!0;r+=a[0].length-1}}return!1}function Qa(e,t){if(Array.isArray(t))for(let i=0;i{io=fv();Ja={exec:()=>null};S3=((e="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)([ \t]+)/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Za(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Za(e=>new RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:Za(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Za(e=>new RegExp(`^ {0,${e}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:Za(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Za(e=>new RegExp(`^ {0,${e}}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|new RegExp(`^ {0,${e}}>`))},w3=/^(?:[ \t]*(?:\n|$))+/,x3=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,E3=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,cu=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,C3=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,pv=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,gC=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,_C=Te(gC).replace(/bull/g,pv).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),k3=Te(gC).replace(/bull/g,pv).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),mv=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,T3=/^[^\n]+/,gv=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,N3=Te(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",gv).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),A3=Te(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,pv).getRegex(),uu="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",_v=/|$))/,M3=Te("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|[^\\n]*\\n*|$)|[^\\n]*\\n*|$)||$)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_v).replace("tag",uu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),vC=e=>Te(mv).replace("hr",cu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?| ?(?:(?![ \t]*(?:\n|$))(paragraph)|[^\n]*)(?:\n|$))+/).replace("paragraph",O3).getRegex(),vv={blockquote:D3,code:x3,def:N3,fences:E3,heading:C3,hr:cu,html:M3,lheading:_C,list:A3,newline:w3,paragraph:R3,table:Ja,text:T3},sC=Te("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",cu).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?| *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_v).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ja,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Te(mv).replace("hr",cu).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",_C).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},B3=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,z3=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,bC=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,P3=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",S3?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),SC=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,W3=Te(SC,"u").replace(/punct/g,Dr).getRegex(),$3=Te(SC,"u").replace(/punct/g,yC).getRegex(),G3=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,j3=Te(G3,"u").replace(/openQuote/g,H3).replace(/punct/g,Dr).getRegex(),wC="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Y3=Te(wC,"gu").replace(/notPunctSpace/g,hu).replace(/punctSpace/g,Ol).replace(/punct/g,Dr).getRegex(),V3=Te(wC,"gu").replace(/notPunctSpace/g,q3).replace(/punctSpace/g,F3).replace(/punct/g,yC).getRegex(),X3="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Z3=Te(X3,"gu").replace(/notPunctSpace/g,hu).replace(/punctSpace/g,Ol).replace(/punct/g,Dr).getRegex(),Q3=Te("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,hu).replace(/punctSpace/g,Ol).replace(/punct/g,Dr).getRegex(),J3="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",eI=Te(J3,"gu").replace(/notPunctSpace/g,hu).replace(/punctSpace/g,Ol).replace(/punct/g,Dr).getRegex(),tI=Te(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Dr).getRegex(),iI="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",nI=Te(iI,"gu").replace(/notPunctSpace/g,hu).replace(/punctSpace/g,Ol).replace(/punct/g,Dr).getRegex(),rI=Te(/\\(punct)/,"gu").replace(/punct/g,Dr).getRegex(),sI=Te(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,Dr).getRegex(),aI=Te(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),oI=Te(_v).replace("(?:-->|$)","-->").getRegex(),lI=Te("^comment|^|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",oI).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xC=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,mf=Te(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",xC).getRegex(),cI=Te(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",mf).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),uI=Te(/^!?\[(label)\]\[(ref)\]/).replace("label",mf).replace("ref",gv).getRegex(),hI=Te(/^!?\[(ref)\](?:\[\])?/).replace("ref",gv).getRegex(),aC=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,dI=Te(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",xC).getRegex(),fI=Te("reflink|nolink(?!\\()","g").replace("reflink",Te(/^!?\[(label)\]\[(ref)\]/).replace("label",dI).replace("ref",aC).getRegex()).replace("nolink",Te(/^!?\[(ref)\](?:\[\])?/).replace("ref",aC).getRegex()).getRegex(),oC=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,pI=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,mI=Te(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,pI).getRegex(),bv={_backpedal:Ja,anyPunctuation:rI,anyPunctuationOutsideCode:sI,autolink:aI,blockSkip:K3,br:bC,code:z3,del:Ja,delLDelim:Ja,delRDelim:Ja,emStrongLDelim:W3,emStrongRDelimAst:Y3,emStrongRDelimUnd:Q3,escape:B3,link:cI,nolink:hI,punctuation:U3,reflink:uI,reflinkSearch:fI,tag:lI,text:P3,url:Ja},gI={...bv,emStrongLDelim:j3,emStrongRDelimAst:Z3,emStrongRDelimUnd:eI,link:Te(/^!?\[(label)\]\((.*?)\)/).replace("label",mf).getRegex(),reflink:Te(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",mf).getRegex()},hv={...bv,emStrongRDelimAst:V3,emStrongLDelim:$3,delLDelim:tI,delRDelim:nI,url:Te(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",mI).replace("protocol",oC).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Te(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},lC=e=>vI[e];Ml=class{constructor(e){fe(this,"options");fe(this,"rules");fe(this,"lexer");this.options=e||io}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:hC(t[0]),n=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],n=yI(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let n=aa(i,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceTabChar.test(n))&&(i=n.trim())}return{type:"heading",raw:aa(t[0],` +`),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:aa(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=aa(t[0],` `).split(` -`),n="",s="",r=[];for(;i.length>0;){let a=!1,o=[],l;for(l=0;lp+Fd(_,p.length)).replace(this.rules.other.blockquoteSetextReplace,` +`),n="",r="",s=[];for(;i.length>0;){let a=!1,o=[],l;for(l=0;lp+ff(_,p.length)).replace(this.rules.other.blockquoteSetextReplace,` $1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n} -${c}`:c,s=s?`${s} -${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let d=r.at(-1);if(d?.type==="code"||d?.type==="heading"||d?.type==="hr"||d?.type==="html")break;if(d?.type==="blockquote"){let f=d,p=i.join(` +${c}`:c,r=r?`${r} +${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,s,!0),this.lexer.state.top=h,i.length===0)break;let d=s.at(-1);if(d?.type==="code"||d?.type==="heading"||d?.type==="hr"||d?.type==="html")break;if(d?.type==="blockquote"){let f=d,p=i.join(` `),_=f.raw+` -`+p.replace(this.rules.other.blockquoteSetextReplace2,""),w=this.blockquote(_);r[r.length-1]=w;let g=_.substring(w.raw.length).replace(/^\n/,""),m=g?g.split(` -`).length:0,v=m?i.slice(0,-m):i;v.length>0&&(n=`${n} -${v.join(` -`)}`),s=s.substring(0,s.length-f.text.length)+w.text;break}else if(d?.type==="list"){let f=d,p=f.raw+` +`+p.replace(this.rules.other.blockquoteSetextReplace2,""),S=this.blockquote(_);s[s.length-1]=S;let m=_.substring(S.raw.length).replace(/^\n/,""),g=m?m.split(` +`).length:0,b=g?i.slice(0,-g):i;b.length>0&&(n=`${n} +${b.join(` +`)}`),r=r.substring(0,r.length-f.text.length)+S.text;break}else if(d?.type==="list"){let f=d,p=f.raw+` `+i.join(` -`),_=this.list(p);r[r.length-1]=_;let w=_.raw.length>f.raw.length?p.slice(f.raw.length+1,_.raw.length).split(` -`).length:0;if(w>0){let g=i.slice(0,w).join(` +`),_=this.list(p);s[s.length-1]=_;let S=_.raw.length>f.raw.length?p.slice(f.raw.length+1,_.raw.length).split(` +`).length:0;if(S>0){let m=i.slice(0,S).join(` `);n=`${n} -${g}`,s=`${s} -${g}`}i=i.slice(w);continue}}return{type:"blockquote",raw:n,tokens:r,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=e,n=()=>i.length-e.length,s=t[1].trim(),r=s.length>1,a={type:"list",raw:"",ordered:r,start:r?+s.slice(0,-1):"",loose:!1,items:[]};s=r?`\\d{1,9}\\${s.slice(-1)}`:`\\${s}`,this.options.pedantic&&(s=r?s:"[*+-]");let o=this.rules.other.listItemRegex(s),l=!1;for(;e;){let u=!1,h="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;let d=n();e=e.substring(t[0].length);let f=t[2].split(` -`,1)[0],p=t[1].length,_=this.options.pedantic?Fd(f,p):f.replace(this.rules.other.leadingSpaceTab,S=>Fd(S,p)),w=e.split(` -`,1)[0],g=!_.trim(),m=0;if(this.options.pedantic?(m=2,h=_.trimStart()):g?m=p+1:(m=_.search(this.rules.other.nonSpaceChar),m=m>4?1:m,h=_.slice(m),m+=p),g&&this.rules.other.blankLine.test(w)&&(e=e.substring(w.length+1),u=!0),!u){let S=this.rules.other.nextBulletRegex(m),k=this.rules.other.hrRegex(m),A=this.rules.other.fencesBeginRegex(m),O=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(m):this.rules.other.headingBeginRegex(m),T=this.rules.other.htmlBeginRegex(m),D=this.rules.other.blockquoteBeginRegex(m);for(;e;){let F=e.split(` -`,1)[0],P;if(w=F,this.options.pedantic?(w=w.replace(this.rules.other.listReplaceNesting," "),P=w):P=w.replace(this.rules.other.leadingSpaceTab,M=>Fd(M)),A.test(w)||O.test(w)||T.test(w)||D.test(w)||S.test(w)||k.test(w))break;if(P.search(this.rules.other.nonSpaceChar)>=m||!w.trim())h+=` -`+P.slice(m);else{if(g||_.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||A.test(_)||O.test(_)||k.test(_))break;let M=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(w)&&this.rules.block.lheading.test(`${_} -${w}`)?` ${P.replace(/^ {0,3}/,"")}`:w;h+=` -`+M}g=!w.trim(),e=e.substring(F.length+1),_=P.slice(m)}}let v=i.slice(d,n());a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(v)&&(l=!0)),a.items.push({type:"list_item",raw:v,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]})}let c=a.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;a.raw=i.slice(0,n()).trimEnd();for(let u of a.items)if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),!a.loose){let h=u.tokens.filter(f=>f.type==="space"),d=h.length>0&&h.some(f=>this.rules.other.anyLine.test(f.raw));a.loose=d}for(let u of a.items){let h=u.tokens[0];if(u.task&&(h?.type==="text"||h?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),h.raw=h.raw.replace(this.rules.other.listReplaceTask,""),h.text=h.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let d=this.rules.other.listTaskCheckbox.exec(u.raw);if(d){let f={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};u.checked=f.checked,a.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=f.raw+u.tokens[0].raw,u.tokens[0].text=f.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(f)):u.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):u.tokens.unshift(f)}}else u.task&&(u.task=!1)}if(a.loose)for(let u of a.items){u.loose=!0;for(let h of u.tokens)h.type==="text"&&(h.type="paragraph")}return a}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=xx(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&Cx(t[2],"()")!==-1)return;let i=Wd(t[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:$r(t[0],` -`),href:n,title:s}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Ex(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),s=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` -`):[],r={type:"table",raw:$r(t[0],` -`),header:[],align:[],rows:[]};if(i.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?r.align.push("right"):this.rules.other.tableAlignCenter.test(a)?r.align.push("center"):this.rules.other.tableAlignLeft.test(a)?r.align.push("left"):r.align.push(null);for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:r.align[l]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:$r(t[0],` +${m}`,r=`${r} +${m}`}i=i.slice(S);continue}}return{type:"blockquote",raw:n,tokens:s,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=e,n=()=>i.length-e.length,r=t[1].trim(),s=r.length>1,a={type:"list",raw:"",ordered:s,start:s?+r.slice(0,-1):"",loose:!1,items:[]};r=s?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=s?r:"[*+-]");let o=this.rules.other.listItemRegex(r),l=!1;for(;e;){let u=!1,h="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;let d=n();e=e.substring(t[0].length);let f=t[2].split(` +`,1)[0],p=t[1].length,_=this.options.pedantic?ff(f,p):f.replace(this.rules.other.leadingSpaceTab,w=>ff(w,p)),S=e.split(` +`,1)[0],m=!_.trim(),g=0;if(this.options.pedantic?(g=2,h=_.trimStart()):m?g=p+1:(g=_.search(this.rules.other.nonSpaceChar),g=g>4?1:g,h=_.slice(g),g+=p),m&&this.rules.other.blankLine.test(S)&&(e=e.substring(S.length+1),u=!0),!u){let w=this.rules.other.nextBulletRegex(g),E=this.rules.other.hrRegex(g),A=this.rules.other.fencesBeginRegex(g),O=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(g):this.rules.other.headingBeginRegex(g),k=this.rules.other.htmlBeginRegex(g),D=this.rules.other.blockquoteBeginRegex(g);for(;e;){let L=e.split(` +`,1)[0],P;if(S=L,this.options.pedantic?(S=S.replace(this.rules.other.listReplaceNesting," "),P=S):P=S.replace(this.rules.other.leadingSpaceTab,I=>ff(I)),A.test(S)||O.test(S)||k.test(S)||D.test(S)||w.test(S)||E.test(S))break;if(P.search(this.rules.other.nonSpaceChar)>=g||!S.trim())h+=` +`+P.slice(g);else{if(m||_.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||A.test(_)||O.test(_)||E.test(_))break;let I=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(S)&&this.rules.block.lheading.test(`${_} +${S}`)?` ${P.replace(/^ {0,3}/,"")}`:S;h+=` +`+I}m=!S.trim(),e=e.substring(L.length+1),_=P.slice(g)}}let b=i.slice(d,n());a.loose||(l?a.loose=!0:this.rules.other.doubleBlankLine.test(b)&&(l=!0)),a.items.push({type:"list_item",raw:b,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]})}let c=a.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;a.raw=i.slice(0,n()).trimEnd();for(let u of a.items)if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),!a.loose){let h=u.tokens.filter(f=>f.type==="space"),d=h.length>0&&h.some(f=>this.rules.other.anyLine.test(f.raw));a.loose=d}for(let u of a.items){let h=u.tokens[0];if(u.task&&(h?.type==="text"||h?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),h.raw=h.raw.replace(this.rules.other.listReplaceTask,""),h.text=h.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let d=this.rules.other.listTaskCheckbox.exec(u.raw);if(d){let f={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};u.checked=f.checked,a.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=f.raw+u.tokens[0].raw,u.tokens[0].text=f.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(f)):u.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):u.tokens.unshift(f)}}else u.task&&(u.task=!1)}if(a.loose)for(let u of a.items){u.loose=!0;for(let h of u.tokens)h.type==="text"&&(h.type="paragraph")}return a}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=hC(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&dC(t[2],"()")!==-1)return;let i=gf(t[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:aa(t[0],` +`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=uC(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],s={type:"table",raw:aa(t[0],` +`),header:[],align:[],rows:[]};if(i.length===n.length){for(let a of n)this.rules.other.tableAlignRight.test(a)?s.align.push("right"):this.rules.other.tableAlignCenter.test(a)?s.align.push("center"):this.rules.other.tableAlignLeft.test(a)?s.align.push("left"):s.align.push(null);for(let a=0;a({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[l]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:aa(t[0],` `),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===` -`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let i=t[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Tx(e,t[1],i,this.rules))return;let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=$r(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=Cx(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(s);a&&(s=a[1],r=a[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),kx(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let n=i[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Tx(e,i[1],n,this.rules))return;let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[Wd(s)];if(!r){let a=i[0].charAt(0);return{type:"text",raw:a,text:a}}return kx(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!n||!n[1]&&!n[2]&&!n[3]&&!n[4])return;let s=n[0][0],r=i===s,a=t.length-e.length,o=a;for(;!this.options.pedantic&&o>0&&t[o-1]===s;)o--;let l=[...t.slice(Math.max(0,o-2),o)].at(-1)??"",c=l==="*"||l==="_"||!!this.rules.inline.punctuation.exec(l);o0)continue;p=Math.min(p,p+_+w);let S=[...n[0]][0].length,k=e.slice(0,d+n.index+S+p);if(Math.min(d,p)%2){let O=k.slice(1,-1);return{type:"em",raw:k,text:O,tokens:this.lexer.inlineTokens(O)}}let A=k.slice(2,-2);return{type:"strong",raw:k,text:A,tokens:this.lexer.inlineTokens(A)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(i),s=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return n&&s&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!i||this.rules.inline.punctuation.exec(i))){let s=[...n[0]].length-1,r,a,o=s,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+s);(n=l.exec(t))!==null;){if(r=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!r||(a=[...r].length,a!==s))continue;if(n[3]||n[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let c=[...n[0]][0].length,u=e.slice(0,s+n.index+c+a),h=u.slice(s,-s);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,n;return t[2]==="@"?(i=t[1],n="mailto:"+i):(i=t[1],n=i),{type:"link",raw:t[0],text:i,href:n,autolink:!0,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,n;if(t[2]==="@")i=t[0],n="mailto:"+i;else{let s;do s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(s!==t[0]);i=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:i,href:n,autolink:!0,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:i?t[0]:r3(t[0]),escaped:i}}}},Xn=(Fa=class{constructor(t){h0(this,bl);de(this,"tokens");de(this,"options");de(this,"state");de(this,"inlineQueue");de(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ka,this.options.tokenizer=this.options.tokenizer||new vl,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let i={other:Zt,block:Hd.normal,inline:$c.normal};this.options.pedantic?(i.block=Hd.pedantic,i.inline=$c.pedantic):this.options.gfm&&(i.block=Hd.gfm,this.options.breaks?i.inline=$c.breaks:i.inline=$c.gfm),this.tokenizer.rules=i}static get rules(){return{block:Hd,inline:$c}}static lex(t,i){return new Fa(i).lex(t)}static lexInline(t,i){return new Fa(i).inlineTokens(t)}lex(t){t=t.replace(Zt.carriageReturn,` -`),this.blockTokens(t,this.tokens);for(let i=0;i(r=o.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let o=i.at(-1);r.raw.length===1&&o!==void 0?o.raw+=` -`:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let o=i.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let i=t[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&pC(e,t[1],i,this.rules))return;let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let a=aa(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=dC(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],s="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(r);a&&(r=a[1],s=a[3])}else s=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),fC(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let n=i[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&pC(e,i[1],n,this.rules))return;let r=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[gf(r)];if(!s){let a=i[0].charAt(0);return{type:"text",raw:a,text:a}}return fC(i,s,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!n||!n[1]&&!n[2]&&!n[3]&&!n[4])return;let r=n[0][0],s=i===r,a=t.length-e.length,o=a;for(;!this.options.pedantic&&o>0&&t[o-1]===r;)o--;let l=[...t.slice(Math.max(0,o-2),o)].at(-1)??"",c=l==="*"||l==="_"||!!this.rules.inline.punctuation.exec(l);o0)continue;p=Math.min(p,p+_+S);let w=[...n[0]][0].length,E=e.slice(0,d+n.index+w+p);if(Math.min(d,p)%2){let O=E.slice(1,-1);return{type:"em",raw:E,text:O,tokens:this.lexer.inlineTokens(O)}}let A=E.slice(2,-2);return{type:"strong",raw:E,text:A,tokens:this.lexer.inlineTokens(A)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return n&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...n[0]].length-1,s,a,o=r,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+r);(n=l.exec(t))!==null;){if(s=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!s||(a=[...s].length,a!==r))continue;if(n[3]||n[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let c=[...n[0]][0].length,u=e.slice(0,r+n.index+c+a),h=u.slice(r,-r);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,n;return t[2]==="@"?(i=t[1],n="mailto:"+i):(i=t[1],n=i),{type:"link",raw:t[0],text:i,href:n,autolink:!0,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,n;if(t[2]==="@")i=t[0],n="mailto:"+i;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:i,href:n,autolink:!0,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:i?t[0]:bI(t[0]),escaped:i}}}},ar=(eo=class{constructor(t){G0(this,Rl);fe(this,"tokens");fe(this,"options");fe(this,"state");fe(this,"inlineQueue");fe(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||io,this.options.tokenizer=this.options.tokenizer||new Ml,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let i={other:si,block:df.normal,inline:ou.normal};this.options.pedantic?(i.block=df.pedantic,i.inline=ou.pedantic):this.options.gfm&&(i.block=df.gfm,this.options.breaks?i.inline=ou.breaks:i.inline=ou.gfm),this.tokenizer.rules=i}static get rules(){return{block:df,inline:ou}}static lex(t,i){return new eo(i).lex(t)}static lexInline(t,i){return new eo(i).inlineTokens(t)}lex(t){t=t.replace(si.carriageReturn,` +`),this.blockTokens(t,this.tokens);for(let i=0;i(s=o.call({lexer:this},t,i))?(t=t.substring(s.raw.length),i.push(s),!0):!1))continue;if(s=this.tokenizer.space(t)){t=t.substring(s.raw.length);let o=i.at(-1);s.raw.length===1&&o!==void 0?o.raw+=` +`:i.push(s);continue}if(s=this.tokenizer.code(t)){t=t.substring(s.raw.length);let o=i.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` `)?"":` -`)+r.raw,o.text+=` -`+r.text,this.inlineQueue.at(-1).src=o.text):i.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let o=i.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)+s.raw,o.text+=` +`+s.text,this.inlineQueue.at(-1).src=o.text):i.push(s);continue}if(s=this.tokenizer.fences(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.heading(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.hr(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.blockquote(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.list(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.html(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.def(t)){t=t.substring(s.raw.length);let o=i.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` `)?"":` -`)+r.raw,o.text+=` -`+r.raw,this.inlineQueue.at(-1).src=o.text):(this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title}),i.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),i.push(r);continue}let a=t;if(this.options.extensions?.startBlock){let o=1/0,l=t.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(o=Math.min(o,c))}),o<1/0&&o>=0&&(a=t.substring(0,o+1))}if(this.state.top&&(r=this.tokenizer.paragraph(a))){let o=i.at(-1);n&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` +`)+s.raw,o.text+=` +`+s.raw,this.inlineQueue.at(-1).src=o.text):(this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title}),i.push(s));continue}if(s=this.tokenizer.table(t)){t=t.substring(s.raw.length),i.push(s);continue}if(s=this.tokenizer.lheading(t)){t=t.substring(s.raw.length),i.push(s);continue}let a=t;if(this.options.extensions?.startBlock){let o=1/0,l=t.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(o=Math.min(o,c))}),o<1/0&&o>=0&&(a=t.substring(0,o+1))}if(this.state.top&&(s=this.tokenizer.paragraph(a))){let o=i.at(-1);n&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` `)?"":` -`)+r.raw,o.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):i.push(r),n=a.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let o=i.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)+s.raw,o.text+=` +`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):i.push(s),n=a.length!==t.length,t=t.substring(s.raw.length);continue}if(s=this.tokenizer.text(t)){t=t.substring(s.raw.length);let o=i.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` `)?"":` -`)+r.raw,o.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}linkInText(t){if(!t.includes("["))return!1;let i=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(i.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let s=n[0],r=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,Wd(s.slice(r+1,-1))))&&!(r>1&&this.linkInText(s.slice(1,r-1))))return!0}return!1}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&t.includes(")");try{return dp(this,bl,zx).call(this,t,i)}finally{this.state.linkParenPossible=n}}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},bl=new WeakSet,zx=function(t,i){let n=t.includes("*")||t.includes("_")||t.includes("~")||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==vl.prototype.emStrong||this.tokenizer.del!==vl.prototype.del?dp(this,bl,Px).call(this,t):t,s=!1,r="",a=1/0;for(;t;){if(t.length(o=c.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.escape(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.tag(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.link(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(o.raw.length);let c=i.at(-1);o.type==="text"&&c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):i.push(o);continue}if(o=this.tokenizer.emStrong(t,n,r)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.codespan(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.br(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.del(t,n,r)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.autolink(t)){t=t.substring(o.raw.length),i.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(t))){t=t.substring(o.raw.length),i.push(o);continue}let l=t;if(this.options.extensions?.startInline){let c=1/0,u=t.slice(1),h;this.options.extensions.startInline.forEach(d=>{h=d.call({lexer:this},u),typeof h=="number"&&h>=0&&(c=Math.min(c,h))}),c<1/0&&c>=0&&(l=t.substring(0,c+1))}if(o=this.tokenizer.inlineText(l)){t=t.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(r=o.raw.slice(-1)),s=!0;let c=i.at(-1);c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i},Px=function(t){let i=t;if(this.tokens.links&&t.includes("[")){let n=this.tokenizer.rules.inline.reflinkSearch,s=r=>{let a=r.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,Wd(r.slice(a+1,-1))))return r;if(a>1&&r.charAt(0)!=="!"){let o=r.slice(1,a-1);if(this.linkInText(o))return"["+o.replace(n,s)+"]["+"a".repeat(r.length-a-2)+"]"}return"["+"a".repeat(r.length-2)+"]"};i=i.replace(n,s)}return i=i.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,s,r)=>r?"+".repeat(n.length):s?s+n.slice(s.length,-s.length).replace(/`/g,"+")+s:n),i=i.replace(this.tokenizer.rules.inline.blockSkip,(n,s,r)=>{let a=r?r.length:0;return n.slice(0,a)+"["+"a".repeat(n.length-a-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i,i},Fa),$d=class{constructor(e){de(this,"options");de(this,"parser");this.options=e||Ka}space(e){return""}code({text:e,lang:t,escaped:i}){let n=(t||"").match(Zt.notSpaceStart)?.[0],s=e?e.replace(Zt.endingNewline,"")+` -`:"";return n?'
'+(i?s:fn(s,!0))+`
-`:"
"+(i?s:fn(s,!0))+`
+`)+s.raw,o.text+=` +`+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):i.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}linkInText(t){if(!t.includes("["))return!1;let i=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(i.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let r=n[0],s=r.lastIndexOf("[");if(!(r.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,gf(r.slice(s+1,-1))))&&!(s>1&&this.linkInText(r.slice(1,s-1))))return!0}return!1}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&t.includes(")");try{return Up(this,Rl,EC).call(this,t,i)}finally{this.state.linkParenPossible=n}}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},Rl=new WeakSet,EC=function(t,i){let n=t.includes("*")||t.includes("_")||t.includes("~")||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==Ml.prototype.emStrong||this.tokenizer.del!==Ml.prototype.del?Up(this,Rl,CC).call(this,t):t,r=!1,s="",a=1/0;for(;t;){if(t.length(o=c.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.escape(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.tag(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.link(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(o.raw.length);let c=i.at(-1);o.type==="text"&&c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):i.push(o);continue}if(o=this.tokenizer.emStrong(t,n,s)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.codespan(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.br(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.del(t,n,s)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.autolink(t)){t=t.substring(o.raw.length),i.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(t))){t=t.substring(o.raw.length),i.push(o);continue}let l=t;if(this.options.extensions?.startInline){let c=1/0,u=t.slice(1),h;this.options.extensions.startInline.forEach(d=>{h=d.call({lexer:this},u),typeof h=="number"&&h>=0&&(c=Math.min(c,h))}),c<1/0&&c>=0&&(l=t.substring(0,c+1))}if(o=this.tokenizer.inlineText(l)){t=t.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(s=o.raw.slice(-1)),r=!0;let c=i.at(-1);c?.type==="text"?(c.raw+=o.raw,c.text+=o.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i},CC=function(t){let i=t;if(this.tokens.links&&t.includes("[")){let n=this.tokenizer.rules.inline.reflinkSearch,r=s=>{let a=s.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,gf(s.slice(a+1,-1))))return s;if(a>1&&s.charAt(0)!=="!"){let o=s.slice(1,a-1);if(this.linkInText(o))return"["+o.replace(n,r)+"]["+"a".repeat(s.length-a-2)+"]"}return"["+"a".repeat(s.length-2)+"]"};i=i.replace(n,r)}return i=i.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,r,s)=>s?"+".repeat(n.length):r?r+n.slice(r.length,-r.length).replace(/`/g,"+")+r:n),i=i.replace(this.tokenizer.rules.inline.blockSkip,(n,r,s)=>{let a=s?s.length:0;return n.slice(0,a)+"["+"a".repeat(n.length-a-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i,i},eo),_f=class{constructor(e){fe(this,"options");fe(this,"parser");this.options=e||io}space(e){return""}code({text:e,lang:t,escaped:i}){let n=(t||"").match(si.notSpaceStart)?.[0],r=e?e.replace(si.endingNewline,"")+` +`:"";return n?'
'+(i?r:wn(r,!0))+`
+`:"
"+(i?r:wn(r,!0))+`
`}blockquote({tokens:e}){return`
${this.parser.parse(e)}
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} `}hr(e){return`
-`}list(e){let t=e.ordered,i=e.start,n="";for(let a=0;a -`+n+" +`}list(e){let t=e.ordered,i=e.start,n="";for(let a=0;a +`+n+" `}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • `}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    -`}table(e){let t="",i="";for(let s=0;s${n}`),` +`}table(e){let t="",i="";for(let r=0;r${n}`),`
    `+t+` `+n+`
    `}tablerow({text:e}){return` ${e} `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+` -`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${fn(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,text:i,tokens:n,autolink:s}){let r=s?fn(i,!0):this.parser.parseInline(n),a=wx(e);if(a===null)return r;e=fn(a,s);let o='
    ",o}image({href:e,title:t,text:i,tokens:n}){n&&(i=this.parser.parseInline(n,this.parser.textRenderer));let s=wx(e);if(s===null)return fn(i);e=s;let r=`${fn(i)}{let a=s[r].flat(1/0);Ua(i,this.walkTokens(a,t))}):s.tokens&&Ua(i,this.walkTokens(s.tokens,t))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let n={...i};if(n.async=this.defaults.async||n.async||!1,i.extensions&&(i.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let r=t.renderers[s.name];r?t.renderers[s.name]=function(...a){let o=s.renderer.apply(this,a);return o===!1&&(o=r.apply(this,a)),o}:t.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[s.level];r?r.unshift(s.tokenizer):t[s.level]=[s.tokenizer],s.start&&(s.level==="block"?t.startBlock?t.startBlock.push(s.start):t.startBlock=[s.start]:s.level==="inline"&&(t.startInline?t.startInline.push(s.start):t.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(t.childTokens[s.name]=s.childTokens)}),n.extensions=t),i.renderer){let s=this.defaults.renderer||new $d(this.defaults);for(let r in i.renderer){if(!(r in s))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let a=r,o=i.renderer[a],l=s[a];s[a]=(...c)=>{let u=o.apply(s,c);return u===!1&&(u=l.apply(s,c)),u||""}}n.renderer=s}if(i.tokenizer){let s=this.defaults.tokenizer||new vl(this.defaults);for(let r in i.tokenizer){if(!(r in s))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let a=r,o=i.tokenizer[a],l=s[a];s[a]=(...c)=>{let u=o.apply(s,c);return u===!1&&(u=l.apply(s,c)),u}}n.tokenizer=s}if(i.hooks){let s=this.defaults.hooks||new Gc;for(let r in i.hooks){if(!(r in s))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let a=r,o=i.hooks[a],l=s[a];Gc.passThroughHooks.has(r)?s[a]=c=>{if(s.options.async&&Gc.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await o.call(s,c);return l.call(s,h)})();let u=o.call(s,c);return l.call(s,u)}:s[a]=(...c)=>{if(s.options.async)return(async()=>{let h=await o.apply(s,c);return h===!1&&(h=await l.apply(s,c)),h})();let u=o.apply(s,c);return u===!1&&(u=l.apply(s,c)),u}}n.hooks=s}if(i.walkTokens){let s=this.defaults.walkTokens,r=i.walkTokens;n.walkTokens=function(a){let o=[];return o.push(r.call(this,a)),s&&Ua(o,s.call(this,a)),o}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Xn.lex(e,t??this.defaults)}parser(e,t){return Zn.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let n={...i},s={...this.defaults,...n},r=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&n.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let a=s.hooks?await s.hooks.preprocess(t):t,o=await(s.hooks?await s.hooks.provideLexer(e):e?Xn.lex:Xn.lexInline)(a,s),l=s.hooks?await s.hooks.processAllTokens(o):o;s.walkTokens&&await Promise.all(this.walkTokens(l,s.walkTokens));let c=await(s.hooks?await s.hooks.provideParser(e):e?Zn.parse:Zn.parseInline)(l,s);return s.hooks?await s.hooks.postprocess(c):c})().catch(r);try{s.hooks&&(t=s.hooks.preprocess(t));let a=(s.hooks?s.hooks.provideLexer(e):e?Xn.lex:Xn.lexInline)(t,s);s.hooks&&(a=s.hooks.processAllTokens(a)),s.walkTokens&&this.walkTokens(a,s.walkTokens);let o=(s.hooks?s.hooks.provideParser(e):e?Zn.parse:Zn.parseInline)(a,s);return s.hooks&&(o=s.hooks.postprocess(o)),o}catch(a){return r(a)}}}onError(e,t){return i=>{if(i.message+=` -Please report this to https://github.com/markedjs/marked.`,e){let n="

    An error occurred:

    "+fn(i.message+"",!0)+"
    ";return t?Promise.resolve(n):n}if(t)return Promise.reject(i);throw i}}},qa=new o3;Ve.options=Ve.setOptions=function(e){return qa.setOptions(e),Ve.defaults=qa.defaults,Nx(Ve.defaults),Ve};Ve.getDefaults=D_;Ve.defaults=Ka;Ve.use=l3;Ve.walkTokens=function(e,t){return qa.walkTokens(e,t)};Ve.parseInline=qa.parseInline;Ve.Parser=Zn;Ve.parser=Zn.parse;Ve.Renderer=$d;Ve.TextRenderer=H_;Ve.Lexer=Xn;Ve.lexer=Xn.lex;Ve.Tokenizer=vl;Ve.Hooks=Gc;Ve.parse=Ve;UU=Ve.options,HU=Ve.setOptions,FU=Ve.walkTokens,qU=Ve.parseInline,KU=Zn.parse,WU=Xn.lex});function c3(e,t){this.v=e,this.k=t}function Hx(e,t){(t==null||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i1?i-1:0),s=1;s2&&arguments[2]!==void 0?arguments[2]:Wa;if(Fx&&Fx(e,null),!wl(t))return e;let n=t.length;for(;n--;){let s=t[n];if(typeof s=="string"){let r=i(s);r!==s&&(m3(t)||(t[n]=r),s=r)}e[s]=!0}return e}function w3(e){for(let t=0;t0&&arguments[0]!==void 0?arguments[0]:U3(),t=G=>aC(G);if(t.version="3.4.17",t.removed=[],!e||!e.document||e.document.nodeType!==It.document||!e.Element)return t.isSupported=!1,t;let i=e.document,n=i,s=n.currentScript;e.DocumentFragment;let r=e.HTMLTemplateElement,a=e.Node,o=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let c=e.DOMParser,u=e.trustedTypes,h=o.prototype,d=On(h,"cloneNode"),f=On(h,"remove"),p=On(h,"removeAttributeNode"),_=On(h,"nextSibling"),w=On(h,"childNodes"),g=On(h,"parentNode"),m=On(h,"shadowRoot"),v=On(h,"attributes"),S=a&&a.prototype?On(a.prototype,"nodeType"):null,k=a&&a.prototype?On(a.prototype,"nodeName"):null,A=a&&a.prototype?On(a.prototype,"ownerDocument"):null,O=function(b){return S?S(b):b.nodeType},T=function(b){return k?k(b):b.nodeName},D=x3(h,"namespaceURI"),F=function(b){return D?D(b):b.namespaceURI};if(typeof r=="function"){let G=i.createElement("template");G.content&&G.content.ownerDocument&&(i=G.content.ownerDocument)}let P,M="",B,E=!1,I=0,C=function(){if(I>0)throw er('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},L=function(b){C(),I++;try{return P.createHTML(b)}finally{I--}},R=function(b){C(),I++;try{return P.createScriptURL(b)}finally{I--}},$=function(){return E||(B=H3(u,s),E=!0),B},ee=i,z=ee.implementation,X=ee.createNodeIterator,Ee=ee.createDocumentFragment,ue=ee.getElementsByTagName,De=n.importNode,J=eC();t.isSupported=typeof tC=="function"&&typeof g=="function"&&z&&z.createHTMLDocument!==void 0;let qe=N3,dt=A3,oi=M3,Mi=R3,Ri=O3,li=D3,xe=L3,ci=I3,ui=Zx,he=null,hi=He({},[...Yx,...W_,...$_,...G_,...jx]),ne=null,ts=He({},[...Vx,...Y_,...Xx,...Yd]),Ge=Object.seal(Sl(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ue=null,Hn=null,Ot=Object.seal(Sl(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),is=!0,Ds=!0,ie=!1,x=!0,W=!1,Z=!0,oe=!1,Me=!1,Fi=null,ns=null,Vf=!1,so=!1,Lu=!1,Bu=!1,Hb=!0,Fb=!1,qb="user-content-",Xf=!0,Zf=!1,ra=null,ro={},aa=null,Kb=He({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),Wb=null,$b=He({},["audio","video","img","source","image","track"]),Gb=null,Yb=He({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Iu="http://www.w3.org/1998/Math/MathML",zu="http://www.w3.org/2000/svg",ss="http://www.w3.org/1999/xhtml",ao=ss,Qf=!1,Jf=null,FM=He({},[Iu,zu,ss],K_),jb=Qt(["mi","mo","mn","ms","mtext"]),ep=He({},jb),Vb=Qt(["annotation-xml"]),tp=He({},Vb),qM=He({},["title","style","font","a","script"]),zl=null,KM=["application/xhtml+xml","text/html"],WM="text/html",Tt=null,oo=null,$M=i.createElement("form"),Xb=function(b){return b instanceof RegExp||b instanceof Function},ip=function(){let b=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(oo&&oo===b)return;(!b||typeof b!="object")&&(b={}),b=pn(b),zl=KM.indexOf(b.PARSER_MEDIA_TYPE)===-1?WM:b.PARSER_MEDIA_TYPE,Tt=zl==="application/xhtml+xml"?K_:Wa,he=Gr(b,"ALLOWED_TAGS",hi,{transform:Tt}),ne=Gr(b,"ALLOWED_ATTR",ts,{transform:Tt}),Jf=Gr(b,"ALLOWED_NAMESPACES",FM,{transform:K_}),Gb=Gr(b,"ADD_URI_SAFE_ATTR",Yb,{transform:Tt,base:Yb}),Wb=Gr(b,"ADD_DATA_URI_TAGS",$b,{transform:Tt,base:$b}),aa=Gr(b,"FORBID_CONTENTS",Kb,{transform:Tt}),Ue=Gr(b,"FORBID_TAGS",pn({}),{transform:Tt}),Hn=Gr(b,"FORBID_ATTR",pn({}),{transform:Tt}),ro=Qi(b,"USE_PROFILES")?b.USE_PROFILES&&typeof b.USE_PROFILES=="object"?pn(b.USE_PROFILES):b.USE_PROFILES:!1,is=b.ALLOW_ARIA_ATTR!==!1,Ds=b.ALLOW_DATA_ATTR!==!1,ie=b.ALLOW_UNKNOWN_PROTOCOLS||!1,x=b.ALLOW_SELF_CLOSE_IN_ATTR!==!1,W=b.SAFE_FOR_TEMPLATES||!1,Z=b.SAFE_FOR_XML!==!1,oe=b.WHOLE_DOCUMENT||!1,so=b.RETURN_DOM||!1,Lu=b.RETURN_DOM_FRAGMENT||!1,Bu=b.RETURN_TRUSTED_TYPE||!1,Vf=b.FORCE_BODY||!1,Hb=b.SANITIZE_DOM!==!1,Fb=b.SANITIZE_NAMED_PROPS||!1,Xf=b.KEEP_CONTENT!==!1,Zf=b.IN_PLACE||!1,ui=C3(b.ALLOWED_URI_REGEXP)?b.ALLOWED_URI_REGEXP:Zx,ao=typeof b.NAMESPACE=="string"?b.NAMESPACE:ss,ep=V_(b,"MATHML_TEXT_INTEGRATION_POINTS",()=>He({},jb)),tp=V_(b,"HTML_INTEGRATION_POINTS",()=>He({},Vb));let N=V_(b,"CUSTOM_ELEMENT_HANDLING",()=>Sl(null));if(Ge=Sl(null),Qi(N,"tagNameCheck")&&Xb(N.tagNameCheck)&&(Ge.tagNameCheck=N.tagNameCheck),Qi(N,"attributeNameCheck")&&Xb(N.attributeNameCheck)&&(Ge.attributeNameCheck=N.attributeNameCheck),Qi(N,"allowCustomizedBuiltInElements")&&typeof N.allowCustomizedBuiltInElements=="boolean"&&(Ge.allowCustomizedBuiltInElements=N.allowCustomizedBuiltInElements),yi(Ge),W&&(Ds=!1),Lu&&(so=!0),ro&&(he=He({},jx),ne=Sl(null),ro.html===!0&&(He(he,Yx),He(ne,Vx)),ro.svg===!0&&(He(he,W_),He(ne,Y_),He(ne,Yd)),ro.svgFilters===!0&&(He(he,$_),He(ne,Y_),He(ne,Yd)),ro.mathMl===!0&&(He(he,G_),He(ne,Xx),He(ne,Yd))),Ot.tagCheck=null,Ot.attributeCheck=null,Qi(b,"ADD_TAGS")&&(typeof b.ADD_TAGS=="function"?Ot.tagCheck=b.ADD_TAGS:wl(b.ADD_TAGS)&&(he===hi&&(he=pn(he)),He(he,b.ADD_TAGS,Tt))),Qi(b,"ADD_ATTR")&&(typeof b.ADD_ATTR=="function"?Ot.attributeCheck=b.ADD_ATTR:wl(b.ADD_ATTR)&&(ne===ts&&(ne=pn(ne)),He(ne,b.ADD_ATTR,Tt))),Qi(b,"ADD_FORBID_CONTENTS")&&wl(b.ADD_FORBID_CONTENTS)&&(aa===Kb&&(aa=pn(aa)),He(aa,b.ADD_FORBID_CONTENTS,Tt)),Xf&&(he["#text"]=!0),oe&&He(he,["html","head","body"]),he.table&&(He(he,["tbody"]),delete Ue.tbody),b.TRUSTED_TYPES_POLICY){if(typeof b.TRUSTED_TYPES_POLICY.createHTML!="function")throw er('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof b.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw er('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let q=P;P=b.TRUSTED_TYPES_POLICY;try{M=L("")}catch(K){throw P=q,K}}else b.TRUSTED_TYPES_POLICY===null?(P=void 0,M=""):(P===void 0&&(P=$()),P&&typeof M=="string"&&(M=L("")));Qt&&Qt(b),oo=b},Zb=He({},[...W_,...$_,...k3]),Qb=He({},[...G_,...T3]),GM=function(b,N,q){return N.namespaceURI===ss?b==="svg":N.namespaceURI===Iu?b==="svg"&&(q==="annotation-xml"||ep[q]):!!Zb[b]},YM=function(b,N,q){return N.namespaceURI===ss?b==="math":N.namespaceURI===zu?b==="math"&&tp[q]:!!Qb[b]},jM=function(b,N,q){return N.namespaceURI===zu&&!tp[q]||N.namespaceURI===Iu&&!ep[q]?!1:!Qb[b]&&(qM[b]||!Zb[b])},VM=function(b){let N=F(b),q=Wa(T(b)),K=g(b),ce,pe;return K&&O(K)===It.element?(ce={namespaceURI:F(K)},pe=Wa(T(K))):(ce={namespaceURI:ao},pe="template"),Jf[N]?N===zu?GM(q,ce,pe):N===Iu?YM(q,ce,pe):N===ss?jM(q,ce,pe):!!(zl==="application/xhtml+xml"&&Jf[N]):!1},cr=function(b){Xc(t.removed,{element:b});try{g(b).removeChild(b)}catch{if(f(b),!g(b))throw er("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Jb=function(b,N,q){try{p(b,N)}catch{try{b.removeAttribute(q)}catch{}}},np=function(b){rp(b);let N=w(b);N&&Js(_3(N),K=>{try{f(K)}catch{}});let q=O(b)===It.element?v(b):null;if(q)for(let K=q.length-1;K>=0;--K){let ce=q[K],pe=ce&&ce.name;typeof pe=="string"&&Jb(b,ce,pe)}},lo=function(b,N,q){if(!q)try{q=N.getAttributeNode(b)}catch{q=null}Xc(t.removed,{attribute:q||null,from:N});try{q?p(N,q):N.removeAttribute(b)}catch{try{N.removeAttribute(b)}catch{}}if(b==="is")if(so||Lu)try{cr(N)}catch{}else try{N.setAttribute(b,"")}catch{}},e0=function(b){let N=v(b);if(N)for(let q=N.length-1;q>=0;--q){let K=N[q],ce=K&&K.name;typeof ce!="string"||ne[Tt(ce)]||Jb(b,K,ce)}},sp=function(b,N){let q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,K=[b];for(;K.length>0;){let ce=K.pop();if(N(ce)===!1)continue;if(q&&O(ce)===It.element){let Le=m(ce);ur(Le)&&K.push(Le)}let pe=w(ce);if(pe)for(let Le=pe.length-1;Le>=0;--Le)K.push(pe[Le])}},rp=function(b){sp(b,N=>{O(N)===It.element&&e0(N)})},ap=function(b){let N=[];return sp(b,q=>{N.push(q)},!0),N},XM=function(b,N){let q=F_();Js(ap(b),K=>{O(K)===It.element&&q_(q,K)}),Js(N,K=>{O(K)===It.element&&!Zc(q,K)&&e0(K)})},t0=function(b,N){let q=!1;return Js(t.removed,K=>{K.element&&(q=q||K.element===b,rp(K.element))}),XM(b,N),q},ZM=8,QM=function(b,N){let q=ra,K=null,ce=()=>(K||(K=F_(),Js(N,pe=>{q_(K,pe)})),K);for(let pe=0;;pe++){let Le=ap(b),Ut=[b],rs=!1;if(Js(Le,Oi=>{O(Oi)===It.documentFragment?Xc(Ut,Oi):!rs&&!Zc(q,Oi)&&(rs=Zc(ce(),Oi))}),!rs)return;if(pe>=ZM)throw er("the tree kept changing during in-place sanitization; refusing to return it");Js(Ut,(Oi,qi)=>{JM(Oi,qi>0,b,ce())})}},JM=function(b,N,q,K){let ce=op(b),pe;for(;pe=ce.nextNode();)!Zc(K,pe)||Zc(ra,pe)||(N&&Fn(J.uponSanitizeShadowNode,pe,null),cp(pe,q),up(pe,q),ur(pe.content)&&Ul(pe.content))},eR=function(b){ra&&q_(ra,b)},i0=function(b,N){return Z?b==="patchsrc"?!0:b==="for"&&N!=="label"&&N!=="output":!1},tR=function(b){Z&&sp(b,N=>{let q=O(N);if(q===It.processingInstruction||q===It.comment&&bi(Qx,N.data)){try{f(N)}catch{}return!1}if(q===It.element){let K=N,ce=Tt(T(N));try{K.hasAttribute&&K.hasAttribute("patchsrc")&&K.removeAttribute("patchsrc"),K.hasAttribute&&K.hasAttribute("for")&&i0("for",ce)&&K.removeAttribute("for")}catch{}}return!0})},n0=function(b){let N=null,q=null;if(Vf)b=""+b;else{let pe=Kx(b,/^[\r\n\t ]+/);q=pe&&pe[0]}zl==="application/xhtml+xml"&&ao===ss&&(b=''+b+"");let K=P?L(b):b;if(ao===ss)try{N=new c().parseFromString(K,zl)}catch{}if(!N||!N.documentElement){N=z.createDocument(ao,"template",null);try{N.documentElement.innerHTML=Qf?M:K}catch{}}let ce=N.body||N.documentElement;return b&&q&&ce.insertBefore(i.createTextNode(q),ce.childNodes[0]||null),ao===ss?ue.call(N,oe?"html":"body")[0]:oe?N.documentElement:ce},op=function(b){let N=A?A(b):b.ownerDocument;return X.call(N||b,b,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Pu=function(b){return b=Qc(b,qe," "),b=Qc(b,dt," "),b=Qc(b,oi," "),b},lp=function(b){var N;s0(b);let q=(N=b.querySelectorAll)===null||N===void 0?void 0:N.call(b,"template");q&&Js(q,K=>{ur(K.content)&&lp(K.content)})},s0=function(b){b.normalize();let N=A?A(b):b.ownerDocument,q=X.call(N||b,b,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),K=q.nextNode();for(;K;)K.data=Pu(K.data),K=q.nextNode()},Uu=function(b){let N=k?k(b):null;return typeof N!="string"||Tt(N)!=="form"?!1:typeof b.nodeName!="string"||typeof b.textContent!="string"||typeof b.removeChild!="function"||b.attributes!==v(b)||typeof b.removeAttribute!="function"||typeof b.removeAttributeNode!="function"||typeof b.getAttributeNode!="function"||typeof b.setAttribute!="function"||typeof b.namespaceURI!="string"||typeof b.insertBefore!="function"||typeof b.hasChildNodes!="function"||b.nodeType!==S(b)||b.childNodes!==w(b)},ur=function(b){if(!S||typeof b!="object"||b===null)return!1;try{return S(b)===It.documentFragment}catch{return!1}},Pl=function(b){if(!S||typeof b!="object"||b===null)return!1;try{return typeof S(b)=="number"}catch{return!1}};function Fn(G,b,N){G.length!==0&&Js(G,q=>{q.call(t,b,N,oo)})}let iR=function(b,N){return!!(Z&&b.hasChildNodes()&&!Pl(b.firstElementChild)&&bi(j_,b.textContent)&&bi(j_,b.innerHTML)||Z&&P3[N]&&O(b)===It.element&&F(b)===ss&&(Pl(b.firstElementChild)||typeof b.textContent=="string"&&bi(j_,b.textContent))||b.nodeType===It.processingInstruction||Z&&b.nodeType===It.comment&&bi(Qx,b.data))},Hu=function(b,N){if(b instanceof RegExp)return bi(b,N);if(b instanceof Function){for(var q=arguments.length,K=new Array(q>2?q-2:0),ce=2;ce=0;--Le){let Ut=b===q?d(ce[Le],!0):ce[Le];K.insertBefore(Ut,_(b))}}}return cr(b),!0},r0=function(b,N,q,K){return b.length===0?N:N===q||N===K?pn(N):N},co=function(b,N){return b===N||g(b)!==null?!1:(Zf&&rp(b),!0)},cp=function(b,N){if(eR(b),Fn(J.beforeSanitizeElements,b,null),co(b,N))return!0;if(Uu(b))return cr(b),!0;let q=Tt(T(b));if(he=r0(J.uponSanitizeElement,he,hi,Fi),Fn(J.uponSanitizeElement,b,{tagName:q,allowedTags:he}),co(b,N))return!0;if(iR(b,q))return cr(b),!0;if(Ue[q]||!(Ot.tagCheck instanceof Function&&Ot.tagCheck(q))&&!he[q]){let K=nR(b,q,N);return K===!1&&(Fn(J.afterSanitizeElements,b,null),co(b,N))?!0:K}if(O(b)===It.element&&!VM(b)||(q==="noscript"||q==="noembed"||q==="noframes")&&bi(z3,b.innerHTML))return cr(b),!0;if(W&&b.nodeType===It.text){let K=Pu(b.textContent);b.textContent!==K&&(Xc(t.removed,{element:b.cloneNode()}),b.textContent=K)}return Fn(J.afterSanitizeElements,b,null),co(b,N)},a0=function(b,N,q){if(Hn[N]||i0(N,b)||Hb&&(N==="id"||N==="name")&&(q in i||q in $M))return!1;let K=ne[N]||Ot.attributeCheck instanceof Function&&Ot.attributeCheck(N,b);return Ds&&bi(Mi,N)||is&&bi(Ri,N)?!0:K?Gb[N]||bi(ui,Qc(q,xe,""))||(N==="src"||N==="xlink:href"||N==="href")&&b!=="script"&&Wx(q,"data:")===0&&Wb[b]||ie&&!bi(li,Qc(q,xe,""))?!0:!q:o0(b)&&Hu(Ge.tagNameCheck,b)&&Hu(Ge.attributeNameCheck,N,b)||N==="is"&&Ge.allowCustomizedBuiltInElements&&Hu(Ge.tagNameCheck,q)},sR=He({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),o0=function(b){return!sR[Wa(b)]&&bi(ci,b)},rR=function(b,N,q,K){if(P&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!q)switch(u.getAttributeType(b,N)){case"TrustedHTML":return L(K);case"TrustedScriptURL":return R(K)}return K},aR=function(b,N,q,K){try{return q?b.setAttributeNS(q,N,K):b.setAttribute(N,K),Uu(b)?(cr(b),!1):!0}catch{return lo(N,b),!1}},l0=function(b,N){return Z&&bi(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,N)?!0:Wa(b)==="attributename"&&Kx(N,"href")!==null},up=function(b,N){if(Fn(J.beforeSanitizeAttributes,b,null),co(b,N))return;let q=b.attributes;if(!q||Uu(b))return;ne=r0(J.uponSanitizeAttribute,ne,ts,ns);let K={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0},ce=q.length,pe=Tt(b.nodeName);for(;ce--;){let Le=q[ce],Ut=Le.name,rs=Le.namespaceURI,Oi=Le.value,qi=Tt(Ut),uo=Oi,Ki=Ut==="value"?uo:b3(uo),c0=!1;if(K.attrName=qi,K.attrValue=Ki,K.keepAttr=!0,K.forceKeepAttr=void 0,Fn(J.uponSanitizeAttribute,b,K),Ki=K.attrValue,Fb&&(qi==="id"||qi==="name")&&Wx(Ki,qb)!==0&&(lo(Ut,b,Le),Ki=qb+Ki,c0=!0),l0(Ut,Ki)){lo(Ut,b,Le);continue}if(!K.forceKeepAttr){if(!K.keepAttr){lo(Ut,b,Le);continue}if(!x&&bi(Jx,Ki)){lo(Ut,b,Le);continue}if(W&&(Ki=Pu(Ki)),!a0(pe,qi,Ki)){lo(Ut,b,Le);continue}Ki=rR(pe,qi,rs,Ki),Ki!==uo&&aR(b,Ut,rs,Ki)&&c0&&qx(t.removed)}}Fn(J.afterSanitizeAttributes,b,null),co(b,N)},Ul=function(b){let N=null,q=op(b);for(Fn(J.beforeSanitizeShadowDOM,b,null);N=q.nextNode();)if(Fn(J.uponSanitizeShadowNode,N,null),cp(N,b),up(N,b),ur(N.content)&&Ul(N.content),O(N)===It.element){let K=m(N);ur(K)&&(hp(K),Ul(K))}W&&s0(b),Fn(J.afterSanitizeShadowDOM,b,null)},hp=function(b){let N=[{node:b,shadow:null}];for(;N.length>0;){let q=N.pop();if(q.shadow){Ul(q.shadow);continue}let K=q.node,ce=O(K)===It.element,pe=w(K);if(pe)for(let Le=pe.length-1;Le>=0;--Le)N.push({node:pe[Le],shadow:null});if(ce){let Le=k?k(K):null;if(typeof Le=="string"&&Tt(Le)==="template"){let Ut=K.content;ur(Ut)&&N.push({node:Ut,shadow:null})}}if(ce){let Le=m(K);ur(Le)&&N.push({node:null,shadow:Le},{node:Le,shadow:null})}}};return t.sanitize=function(G){let b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},N=null,q=null,K=null,ce=null;if(Qf=!G,Qf&&(G=""),typeof G!="string"&&!Pl(G)&&(G=E3(G),typeof G!="string"))throw er("dirty is not a string, aborting");if(!t.isSupported)return G;Me?(he=Fi,ne=ns):ip(b),(J.uponSanitizeElement.length>0||J.uponSanitizeAttribute.length>0)&&(he=pn(he)),J.uponSanitizeAttribute.length>0&&(ne=pn(ne)),t.removed=[];let pe=Zf&&typeof G!="string"&&Pl(G),Le=[],Ut=ra;if(pe){tR(G);let qi=T(G);if(typeof qi=="string"){let uo=Tt(qi);if(!he[uo]||Ue[uo])throw np(G),er("root node is forbidden and cannot be sanitized in-place")}if(Uu(G))throw np(G),er("root node is clobbered and cannot be sanitized in-place");Le=ap(G),ra=F_()}else if(Pl(G))N=n0(""),q=N.ownerDocument.importNode(G,!0),q.nodeType===It.element&&q.nodeName==="BODY"||q.nodeName==="HTML"?N=q:N.appendChild(q),hp(N);else{if(!so&&!W&&!oe&&G.indexOf("<")===-1)return P&&Bu?L(G):G;if(N=n0(G),!N)return so?null:Bu?M:""}N&&Vf&&cr(N.firstChild);let rs=pe?G:N;try{pe&&hp(G);let qi=op(rs);for(;K=qi.nextNode();)cp(K,rs),up(K,rs),ur(K.content)&&Ul(K.content);pe&&QM(G,Le)}catch(qi){throw pe&&(np(G),t0(G,Le)),qi}finally{ra=Ut}if(pe){if(t0(G,Le))throw er("a node selected for removal could not be safely returned; refusing to sanitize in place");return W&&lp(G),G}if(so){if(W&&lp(N),Lu)for(ce=Ee.call(N.ownerDocument);N.firstChild;)ce.appendChild(N.firstChild);else ce=N;return(ne.shadowroot||ne.shadowrootmode)&&(ce=De.call(n,ce,!0)),ce}let Oi=oe?N.outerHTML:N.innerHTML;return oe&&he["!doctype"]&&N.ownerDocument&&N.ownerDocument.doctype&&N.ownerDocument.doctype.name&&bi(B3,N.ownerDocument.doctype.name)&&(Oi=" -`+Oi),W&&(Oi=Pu(Oi)),P&&Bu?L(Oi):Oi},t.setConfig=function(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ip(G),Me=!0,Fi=he,ns=ne},t.clearConfig=function(){oo=null,Me=!1,Fi=null,ns=null,P=B,M=""},t.isValidAttribute=function(G,b,N){oo||ip({});let q=Tt(G),K=Tt(b);return typeof N=="string"&&(l0(b,N)||!x&&bi(Jx,N))?!1:a0(q,K,N)},t.addHook=function(G,b){typeof b=="function"&&Qi(J,G)&&Xc(J[G],b)},t.removeHook=function(G,b){if(Qi(J,G)){if(b!==void 0){let N=g3(J[G],b);return N===-1?void 0:v3(J[G],N,1)[0]}return qx(J[G])}},t.removeHooks=function(G){Qi(J,G)&&(J[G]=[])},t.removeAllHooks=function(){J=eC()},t}var tC,Fx,m3,iC,nC,Qt,yi,Sl,sC,X_,Z_,Js,g3,qx,Xc,_3,v3,wl,F_,q_,Zc,Wa,K_,Kx,Qc,Wx,b3,y3,S3,$x,Gx,Qi,Jc,bi,er,Yx,W_,$_,k3,G_,T3,jx,Vx,Y_,Xx,Yd,N3,A3,M3,R3,O3,Zx,D3,L3,B3,I3,j_,Qx,z3,Jx,It,P3,U3,H3,eC,Gr,V_,oC,lC=le(()=>{Gd.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Gd.prototype.next=function(e){return this._invoke("next",e)},Gd.prototype.throw=function(e){return this._invoke("throw",e)},Gd.prototype.return=function(e){return this._invoke("return",e)};tC=Object.entries,Fx=Object.setPrototypeOf,m3=Object.isFrozen,iC=Object.getPrototypeOf,nC=Object.getOwnPropertyDescriptor,Qt=Object.freeze,yi=Object.seal,Sl=Object.create,sC=typeof Reflect<"u"&&Reflect,X_=sC.apply,Z_=sC.construct;Qt||(Qt=function(t){return t});yi||(yi=function(t){return t});X_||(X_=function(t,i){for(var n=arguments.length,s=new Array(n>2?n-2:0),r=2;r1?i-1:0),s=1;s"u"?null:_t(BigInt.prototype.toString),Gx=typeof Symbol>"u"?null:_t(Symbol.prototype.toString),Qi=_t(Object.prototype.hasOwnProperty),Jc=_t(Object.prototype.toString),bi=_t(RegExp.prototype.test),er=rC(TypeError);Yx=Qt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),W_=Qt(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),$_=Qt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),k3=Qt(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),G_=Qt(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),T3=Qt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),jx=Qt(["#text"]),Vx=Qt(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Y_=Qt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Xx=Qt(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Yd=Qt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),N3=yi(/{{[\w\W]*|^[\w\W]*}}/g),A3=yi(/<%[\w\W]*|^[\w\W]*%>/g),M3=yi(/\${[\w\W]*/g),R3=yi(/^data-[\-\w.\u00B7-\uFFFF]+$/),O3=yi(/^aria-[\-\w]+$/),Zx=yi(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),D3=yi(/^(?:\w+script|data):/i),L3=yi(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),B3=yi(/^html$/i),I3=yi(/^[a-z][.\w]*(-[.\w]+)+$/i),j_=yi(/<[/\w!]/g),Qx=yi(/<[/\w]/g),z3=yi(/<\/no(script|embed|frames)/i),Jx=yi(/\/>/i),It={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},P3=Qt(He({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),U3=function(){return typeof window>"u"?null:window},H3=function(t,i){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null,s="data-tt-policy-suffix";i&&i.hasAttribute(s)&&(n=i.getAttribute(s));let r="dompurify"+(n?"#"+n:"");try{return t.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},eC=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Gr=function(t,i,n,s){return Qi(t,i)&&wl(t[i])?He(s.base?pn(s.base):{},t[i],s.transform):n},V_=function(t,i,n){let s=Qi(t,i)?t[i]:void 0;return s&&typeof s=="object"?pn(s):n()};oC=aC()});var NC=me((JU,TC)=>{function mC(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw new Error("map is read-only")}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw new Error("set is read-only")}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{let i=e[t],n=typeof i;(n==="object"||n==="function")&&!Object.isFrozen(i)&&mC(i)}),e}var Vd=class{constructor(t){t.data===void 0&&(t.data={}),this.data=t.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}};function gC(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function Yr(e,...t){let i=Object.create(null);for(let n in e)i[n]=e[n];return t.forEach(function(n){for(let s in n)i[s]=n[s]}),i}var F3="",cC=e=>!!e.scope,q3=(e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){let i=e.split(".");return[`${t}${i.shift()}`,...i.map((n,s)=>`${n}${"_".repeat(s+1)}`)].join(" ")}return`${t}${e}`},J_=class{constructor(t,i){this.buffer="",this.classPrefix=i.classPrefix,t.walk(this)}addText(t){this.buffer+=gC(t)}openNode(t){if(!cC(t))return;let i=q3(t.scope,{prefix:this.classPrefix});this.span(i)}closeNode(t){cC(t)&&(this.buffer+=F3)}value(){return this.buffer}span(t){this.buffer+=``}},uC=(e={})=>{let t={children:[]};return Object.assign(t,e),t},ev=class e{constructor(){this.rootNode=uC(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(t){this.top.children.push(t)}openNode(t){let i=uC({scope:t});this.add(i),this.stack.push(i)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(t){return this.constructor._walk(t,this.rootNode)}static _walk(t,i){return typeof i=="string"?t.addText(i):i.children&&(t.openNode(i),i.children.forEach(n=>this._walk(t,n)),t.closeNode(i)),t}static _collapse(t){typeof t!="string"&&t.children&&(t.children.every(i=>typeof i=="string")?t.children=[t.children.join("")]:t.children.forEach(i=>{e._collapse(i)}))}},tv=class extends ev{constructor(t){super(),this.options=t}addText(t){t!==""&&this.add(t)}startScope(t){this.openNode(t)}endScope(){this.closeNode()}__addSublanguage(t,i){let n=t.root;i&&(n.scope=`language:${i}`),this.add(n)}toHTML(){return new J_(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}};function eu(e){return e?typeof e=="string"?e:e.source:null}function _C(e){return Ga("(?=",e,")")}function K3(e){return Ga("(?:",e,")*")}function W3(e){return Ga("(?:",e,")?")}function Ga(...e){return e.map(i=>eu(i)).join("")}function $3(e){let t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function Zd(...e){return"("+($3(e).capture?"":"?:")+e.map(n=>eu(n)).join("|")+")"}function vC(e){return new RegExp(e.toString()+"|").exec("").length-1}function G3(e,t){let i=e&&e.exec(t);return i&&i.index===0}var Y3=new RegExp(Zd(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));function nv(e,{joinWith:t}){let i=0;return e.map(n=>{i+=1;let s=i,r=eu(n),a="";for(;r.length>0;){let o=Y3.exec(r);if(!o){a+=r;break}a+=r.substring(0,o.index),r=r.substring(o.index+o[0].length),o[0][0]==="\\"&&o[1]?a+="\\"+String(Number(o[1])+s):(a+=o[0],(o[0]==="("||/^\(\?[<']/.test(o[0]))&&i++)}return a}).map(n=>`(${n})`).join(t)}var j3=/\b\B/,bC="[a-zA-Z]\\w*",sv="[a-zA-Z_]\\w*",yC="\\b\\d+(\\.\\d+)?",SC="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",wC="\\b(0b[01]+)",V3="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",X3=(e={})=>{let t=/^#![ ]*\//;return e.binary&&(e.begin=Ga(t,/.*\b/,e.binary,/\b.*/)),Yr({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(i,n)=>{i.index!==0&&n.ignoreMatch()}},e)},tu={begin:"\\\\[\\s\\S]",relevance:0},Z3={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[tu]},Q3={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[tu]},J3={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},Qd=function(e,t,i={}){let n=Yr({scope:"comment",begin:e,end:t,contains:[]},i);n.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});let s=Zd("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return n.contains.push({begin:Ga(/[ ]+/,"(",s,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),n},eB=Qd("//","$"),tB=Qd("/\\*","\\*/"),iB=Qd("#","$"),nB={scope:"number",begin:yC,relevance:0},sB={scope:"number",begin:SC,relevance:0},rB={scope:"number",begin:wC,relevance:0},aB={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[tu,{begin:/\[/,end:/\]/,relevance:0,contains:[tu]}]},oB={scope:"title",begin:bC,relevance:0},lB={scope:"title",begin:sv,relevance:0},cB={begin:"\\.\\s*"+sv,relevance:0},uB=function(e){return Object.assign(e,{"on:begin":(t,i)=>{i.data._beginMatch=t[1]},"on:end":(t,i)=>{i.data._beginMatch!==t[1]&&i.ignoreMatch()}})},jd=Object.freeze({__proto__:null,APOS_STRING_MODE:Z3,BACKSLASH_ESCAPE:tu,BINARY_NUMBER_MODE:rB,BINARY_NUMBER_RE:wC,COMMENT:Qd,C_BLOCK_COMMENT_MODE:tB,C_LINE_COMMENT_MODE:eB,C_NUMBER_MODE:sB,C_NUMBER_RE:SC,END_SAME_AS_BEGIN:uB,HASH_COMMENT_MODE:iB,IDENT_RE:bC,MATCH_NOTHING_RE:j3,METHOD_GUARD:cB,NUMBER_MODE:nB,NUMBER_RE:yC,PHRASAL_WORDS_MODE:J3,QUOTE_STRING_MODE:Q3,REGEXP_MODE:aB,RE_STARTERS_RE:V3,SHEBANG:X3,TITLE_MODE:oB,UNDERSCORE_IDENT_RE:sv,UNDERSCORE_TITLE_MODE:lB});function hB(e,t){e.input[e.index-1]==="."&&t.ignoreMatch()}function dB(e,t){e.className!==void 0&&(e.scope=e.className,delete e.className)}function fB(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=hB,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function pB(e,t){Array.isArray(e.illegal)&&(e.illegal=Zd(...e.illegal))}function mB(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function gB(e,t){e.relevance===void 0&&(e.relevance=1)}var _B=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");let i=Object.assign({},e);Object.keys(e).forEach(n=>{delete e[n]}),e.keywords=i.keywords,e.begin=Ga(i.beforeMatch,_C(i.begin)),e.starts={relevance:0,contains:[Object.assign(i,{endsParent:!0})]},e.relevance=0,delete i.beforeMatch},vB=["of","and","for","in","not","or","if","then","parent","list","value"],bB="keyword";function EC(e,t,i=bB){let n=Object.create(null);return typeof e=="string"?s(i,e.split(" ")):Array.isArray(e)?s(i,e):Object.keys(e).forEach(function(r){Object.assign(n,EC(e[r],t,r))}),n;function s(r,a){t&&(a=a.map(o=>o.toLowerCase())),a.forEach(function(o){let l=o.split("|");n[l[0]]=[r,yB(l[0],l[1])]})}}function yB(e,t){return t?Number(t):SB(e)?0:1}function SB(e){return vB.includes(e.toLowerCase())}var hC={},$a=e=>{console.error(e)},dC=(e,...t)=>{console.log(`WARN: ${e}`,...t)},El=(e,t)=>{hC[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),hC[`${e}/${t}`]=!0)},Xd=new Error;function xC(e,t,{key:i}){let n=0,s=e[i],r={},a={};for(let o=1;o<=t.length;o++)a[o+n]=s[o],r[o+n]=!0,n+=vC(t[o-1]);e[i]=a,e[i]._emit=r,e[i]._multi=!0}function wB(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw $a("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),Xd;if(typeof e.beginScope!="object"||e.beginScope===null)throw $a("beginScope must be object"),Xd;xC(e,e.begin,{key:"beginScope"}),e.begin=nv(e.begin,{joinWith:""})}}function EB(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw $a("skip, excludeEnd, returnEnd not compatible with endScope: {}"),Xd;if(typeof e.endScope!="object"||e.endScope===null)throw $a("endScope must be object"),Xd;xC(e,e.end,{key:"endScope"}),e.end=nv(e.end,{joinWith:""})}}function xB(e){e.scope&&typeof e.scope=="object"&&e.scope!==null&&(e.beginScope=e.scope,delete e.scope)}function CB(e){xB(e),typeof e.beginScope=="string"&&(e.beginScope={_wrap:e.beginScope}),typeof e.endScope=="string"&&(e.endScope={_wrap:e.endScope}),wB(e),EB(e)}function kB(e){function t(a,o){return new RegExp(eu(a),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(o?"g":""))}class i{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(o,l){l.position=this.position++,this.matchIndexes[this.matchAt]=l,this.regexes.push([l,o]),this.matchAt+=vC(o)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);let o=this.regexes.map(l=>l[1]);this.matcherRe=t(nv(o,{joinWith:"|"}),!0),this.lastIndex=0}exec(o){this.matcherRe.lastIndex=this.lastIndex;let l=this.matcherRe.exec(o);if(!l)return null;let c=l.findIndex((h,d)=>d>0&&h!==void 0),u=this.matchIndexes[c];return l.splice(0,c),Object.assign(l,u)}}class n{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(o){if(this.multiRegexes[o])return this.multiRegexes[o];let l=new i;return this.rules.slice(o).forEach(([c,u])=>l.addRule(c,u)),l.compile(),this.multiRegexes[o]=l,l}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(o,l){this.rules.push([o,l]),l.type==="begin"&&this.count++}exec(o){let l=this.getMatcher(this.regexIndex);l.lastIndex=this.lastIndex;let c=l.exec(o);if(this.resumingScanAtSamePosition()&&!(c&&c.index===this.lastIndex)){let u=this.getMatcher(0);u.lastIndex=this.lastIndex+1,c=u.exec(o)}return c&&(this.regexIndex+=c.position+1,this.regexIndex===this.count&&this.considerAll()),c}}function s(a){let o=new n;return a.contains.forEach(l=>o.addRule(l.begin,{rule:l,type:"begin"})),a.terminatorEnd&&o.addRule(a.terminatorEnd,{type:"end"}),a.illegal&&o.addRule(a.illegal,{type:"illegal"}),o}function r(a,o){let l=a;if(a.isCompiled)return l;[dB,mB,CB,_B].forEach(u=>u(a,o)),e.compilerExtensions.forEach(u=>u(a,o)),a.__beforeBegin=null,[fB,pB,gB].forEach(u=>u(a,o)),a.isCompiled=!0;let c=null;return typeof a.keywords=="object"&&a.keywords.$pattern&&(a.keywords=Object.assign({},a.keywords),c=a.keywords.$pattern,delete a.keywords.$pattern),c=c||/\w+/,a.keywords&&(a.keywords=EC(a.keywords,e.case_insensitive)),l.keywordPatternRe=t(c,!0),o&&(a.begin||(a.begin=/\B|\b/),l.beginRe=t(l.begin),!a.end&&!a.endsWithParent&&(a.end=/\B|\b/),a.end&&(l.endRe=t(l.end)),l.terminatorEnd=eu(l.end)||"",a.endsWithParent&&o.terminatorEnd&&(l.terminatorEnd+=(a.end?"|":"")+o.terminatorEnd)),a.illegal&&(l.illegalRe=t(a.illegal)),a.contains||(a.contains=[]),a.contains=[].concat(...a.contains.map(function(u){return TB(u==="self"?a:u)})),a.contains.forEach(function(u){r(u,l)}),a.starts&&r(a.starts,o),l.matcher=s(l),l}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=Yr(e.classNameAliases||{}),r(e)}function CC(e){return e?e.endsWithParent||CC(e.starts):!1}function TB(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return Yr(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:CC(e)?Yr(e,{starts:e.starts?Yr(e.starts):null}):Object.isFrozen(e)?Yr(e):e}var NB="11.12.0",iv=class extends Error{constructor(t,i){super(t),this.name="HTMLInjectionError",this.html=i}},Q_=gC,fC=Yr,pC=Symbol("nomatch"),AB=7,kC=function(e){let t=Object.create(null),i=Object.create(null),n=[],s=!0,r="Could not find the language '{}', did you forget to load/include a language module?",a={disableAutodetect:!0,name:"Plain text",contains:[]},o={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:tv};function l(C){return o.noHighlightRe.test(C)}function c(C){let L=C.className+" ";L+=C.parentNode?C.parentNode.className:"";let R=o.languageDetectRe.exec(L);if(R){let $=T(R[1]);return $||(dC(r.replace("{}",R[1])),dC("Falling back to no-highlight mode for this block.",C)),$?R[1]:"no-highlight"}return L.split(/\s+/).find($=>l($)||T($))}function u(C,L,R){let $="",ee="";typeof L=="object"?($=C,R=L.ignoreIllegals,ee=L.language):(El("10.7.0","highlight(lang, code, ...args) has been deprecated."),El("10.7.0",`Please use highlight(code, options) instead. -https://github.com/highlightjs/highlight.js/issues/2277`),ee=C,$=L),R===void 0&&(R=!0);let z={code:$,language:ee};E("before:highlight",z);let X=z.result?z.result:h(z.language,z.code,R);return X.code=z.code,E("after:highlight",X),X}function h(C,L,R,$){let ee=Object.create(null);function z(ie,x){return ie.keywords[x]}function X(){if(!ne.keywords){Ge.addText(Ue);return}let ie=0;ne.keywordPatternRe.lastIndex=0;let x=ne.keywordPatternRe.exec(Ue),W="";for(;x;){W+=Ue.substring(ie,x.index);let Z=ui.case_insensitive?x[0].toLowerCase():x[0],oe=z(ne,Z);if(oe){let[Me,Fi]=oe;if(Ge.addText(W),W="",ee[Z]=(ee[Z]||0)+1,ee[Z]<=AB&&(Hn+=Fi),Me.startsWith("_"))W+=x[0];else{let ns=ui.classNameAliases[Me]||Me;De(x[0],ns)}}else W+=x[0];ie=ne.keywordPatternRe.lastIndex,x=ne.keywordPatternRe.exec(Ue)}W+=Ue.substring(ie),Ge.addText(W)}function Ee(){if(Ue==="")return;let ie=null;if(typeof ne.subLanguage=="string"){if(!t[ne.subLanguage]){Ge.addText(Ue);return}ie=h(ne.subLanguage,Ue,!0,ts[ne.subLanguage]),ts[ne.subLanguage]=ie._top}else ie=f(Ue,ne.subLanguage.length?ne.subLanguage:null);ne.relevance>0&&(Hn+=ie.relevance),Ge.__addSublanguage(ie._emitter,ie.language)}function ue(){ne.subLanguage!=null?Ee():X(),Ue=""}function De(ie,x){ie!==""&&(Ge.startScope(x),Ge.addText(ie),Ge.endScope())}function J(ie,x){let W=1,Z=x.length-1;for(;W<=Z;){if(!ie._emit[W]){W++;continue}let oe=ui.classNameAliases[ie[W]]||ie[W],Me=x[W];oe?De(Me,oe):(Ue=Me,X(),Ue=""),W++}}function qe(ie,x){return ie.scope&&typeof ie.scope=="string"&&Ge.openNode(ui.classNameAliases[ie.scope]||ie.scope),ie.beginScope&&(ie.beginScope._wrap?(De(Ue,ui.classNameAliases[ie.beginScope._wrap]||ie.beginScope._wrap),Ue=""):ie.beginScope._multi&&(J(ie.beginScope,x),Ue="")),ne=Object.create(ie,{parent:{value:ne}}),ne}function dt(ie,x,W){let Z=G3(ie.endRe,W);if(Z){if(ie["on:end"]){let oe=new Vd(ie);ie["on:end"](x,oe),oe.isMatchIgnored&&(Z=!1)}if(Z){for(;ie.endsParent&&ie.parent;)ie=ie.parent;return ie}}if(ie.endsWithParent)return dt(ie.parent,x,W)}function oi(ie){return ne.matcher.regexIndex===0?(Ue+=ie[0],1):(Ds=!0,0)}function Mi(ie){let x=ie[0],W=ie.rule,Z=new Vd(W),oe=[W.__beforeBegin,W["on:begin"]];for(let Me of oe)if(Me&&(Me(ie,Z),Z.isMatchIgnored))return oi(x);return W.skip?Ue+=x:(W.excludeBegin&&(Ue+=x),ue(),!W.returnBegin&&!W.excludeBegin&&(Ue=x)),qe(W,ie),W.returnBegin?0:x.length}function Ri(ie){let x=ie[0],W=L.substring(ie.index),Z=dt(ne,ie,W);if(!Z)return pC;let oe=ne;ne.endScope&&ne.endScope._wrap?(ue(),De(x,ne.endScope._wrap)):ne.endScope&&ne.endScope._multi?(ue(),J(ne.endScope,ie)):oe.skip?Ue+=x:(oe.returnEnd||oe.excludeEnd||(Ue+=x),ue(),oe.excludeEnd&&(Ue=x));do ne.scope&&Ge.closeNode(),!ne.skip&&!ne.subLanguage&&(Hn+=ne.relevance),ne=ne.parent;while(ne!==Z.parent);return Z.starts&&qe(Z.starts,ie),oe.returnEnd?0:x.length}function li(){let ie=[];for(let x=ne;x!==ui;x=x.parent)x.scope&&ie.unshift(x.scope);ie.forEach(x=>Ge.openNode(x))}let xe={};function ci(ie,x){let W=x&&x[0];if(Ue+=ie,W==null)return ue(),0;if(xe.type==="begin"&&x.type==="end"&&xe.index===x.index&&W===""){if(Ue+=L.slice(x.index,x.index+1),!s){let Z=new Error(`0 width match regex (${C})`);throw Z.languageName=C,Z.badRule=xe.rule,Z}return 1}if(xe=x,x.type==="begin")return Mi(x);if(x.type==="illegal"&&!R){let Z=new Error('Illegal lexeme "'+W+'" for mode "'+(ne.scope||"")+'"');throw Z.mode=ne,Z}else if(x.type==="end"){let Z=Ri(x);if(Z!==pC)return Z}if(x.type==="illegal"&&W==="")return x.index===L.length||(Ue+=` -`),1;if(is>1e5&&is>x.index*3)throw new Error("potential infinite loop, way more iterations than matches");return Ue+=W,W.length}let ui=T(C);if(!ui)throw $a(r.replace("{}",C)),new Error('Unknown language: "'+C+'"');let he=kB(ui),hi="",ne=$||he,ts={},Ge=new o.__emitter(o);li();let Ue="",Hn=0,Ot=0,is=0,Ds=!1;try{if(ui.__emitTokens)ui.__emitTokens(L,Ge);else{for(ne.matcher.considerAll();;){is++,Ds?Ds=!1:ne.matcher.considerAll(),ne.matcher.lastIndex=Ot;let ie=ne.matcher.exec(L);if(!ie)break;let x=L.substring(Ot,ie.index),W=ci(x,ie);Ot=ie.index+W}ci(L.substring(Ot))}return Ge.finalize(),hi=Ge.toHTML(),{language:C,value:hi,relevance:Hn,illegal:!1,_emitter:Ge,_top:ne}}catch(ie){if(ie.message&&ie.message.includes("Illegal"))return{language:C,value:Q_(L),illegal:!0,relevance:0,_illegalBy:{message:ie.message,index:Ot,context:L.slice(Ot-100,Ot+100),mode:ie.mode,resultSoFar:hi},_emitter:Ge};if(s)return{language:C,value:Q_(L),illegal:!1,relevance:0,errorRaised:ie,_emitter:Ge,_top:ne};throw ie}}function d(C){let L={value:Q_(C),illegal:!1,relevance:0,_top:a,_emitter:new o.__emitter(o)};return L._emitter.addText(C),L}function f(C,L){L=L||o.languages||Object.keys(t);let R=d(C),$=L.filter(T).filter(F).map(ue=>h(ue,C,!1));$.unshift(R);let ee=$.sort((ue,De)=>{if(ue.relevance!==De.relevance)return De.relevance-ue.relevance;if(ue.language&&De.language){if(T(ue.language).supersetOf===De.language)return 1;if(T(De.language).supersetOf===ue.language)return-1}return 0}),[z,X]=ee,Ee=z;return Ee.secondBest=X,Ee}function p(C,L,R){let $=L&&i[L]||R;C.classList.add("hljs"),C.classList.add(`language-${$}`)}function _(C){let L=null,R=c(C);if(l(R))return;if(E("before:highlightElement",{el:C,language:R}),C.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",C);return}if(C.children.length>0&&(o.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(C)),o.throwUnescapedHTML))throw new iv("One of your code blocks includes unescaped HTML.",C.innerHTML);L=C;let $=L.textContent,ee=R?u($,{language:R,ignoreIllegals:!0}):f($);C.innerHTML=ee.value,C.dataset.highlighted="yes",p(C,R,ee.language),C.result={language:ee.language,re:ee.relevance,relevance:ee.relevance},ee.secondBest&&(C.secondBest={language:ee.secondBest.language,relevance:ee.secondBest.relevance}),E("after:highlightElement",{el:C,result:ee,text:$})}function w(C){o=fC(o,C)}let g=()=>{S(),El("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function m(){S(),El("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let v=!1;function S(){function C(){S()}if(document.readyState==="loading"){v||window.addEventListener("DOMContentLoaded",C,!1),v=!0;return}document.querySelectorAll(o.cssSelector).forEach(_)}function k(C,L){let R=null;try{R=L(e)}catch($){if($a("Language definition for '{}' could not be registered.".replace("{}",C)),s)$a($);else throw $;R=a}R.name||(R.name=C),t[C]=R,R.rawDefinition=L.bind(null,e),R.aliases&&D(R.aliases,{languageName:C})}function A(C){delete t[C];for(let L of Object.keys(i))i[L]===C&&delete i[L]}function O(){return Object.keys(t)}function T(C){return C=(C||"").toLowerCase(),t[C]||t[i[C]]}function D(C,{languageName:L}){typeof C=="string"&&(C=[C]),C.forEach(R=>{i[R.toLowerCase()]=L})}function F(C){let L=T(C);return L&&!L.disableAutodetect}function P(C){C["before:highlightBlock"]&&!C["before:highlightElement"]&&(C["before:highlightElement"]=L=>{C["before:highlightBlock"](Object.assign({block:L.el},L))}),C["after:highlightBlock"]&&!C["after:highlightElement"]&&(C["after:highlightElement"]=L=>{C["after:highlightBlock"](Object.assign({block:L.el},L))})}function M(C){P(C),n.push(C)}function B(C){let L=n.indexOf(C);L!==-1&&n.splice(L,1)}function E(C,L){let R=C;n.forEach(function($){$[R]&&$[R](L)})}function I(C){return El("10.7.0","highlightBlock will be removed entirely in v12.0"),El("10.7.0","Please use highlightElement now."),_(C)}Object.assign(e,{highlight:u,highlightAuto:f,highlightAll:S,highlightElement:_,highlightBlock:I,configure:w,initHighlighting:g,initHighlightingOnLoad:m,registerLanguage:k,unregisterLanguage:A,listLanguages:O,getLanguage:T,registerAliases:D,autoDetection:F,inherit:fC,addPlugin:M,removePlugin:B}),e.debugMode=function(){s=!1},e.safeMode=function(){s=!0},e.versionString=NB,e.regex={concat:Ga,lookahead:_C,either:Zd,optional:W3,anyNumberOfTimes:K3};for(let C in jd)typeof jd[C]=="object"&&mC(jd[C]);return Object.assign(e,jd),e},xl=kC({});xl.newInstance=()=>kC({});TC.exports=xl;xl.HighlightJS=xl;xl.default=xl});var MC=me((eH,AC)=>{function MB(e){let t=e.regex,i=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),n=/[\p{L}0-9._:-]+/u,s={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},r={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},a=e.inherit(r,{begin:/\(/,end:/\)/}),o=e.inherit(e.APOS_STRING_MODE,{className:"string"}),l=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[r,l,o,a,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[r,a,l,o]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},s,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[l]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:"css"}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:"javascript"}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:i,relevance:0,starts:c}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(i,/>/))),contains:[{className:"name",begin:i,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}AC.exports=MB});var OC=me((tH,RC)=>{function RB(e){let t=e.regex,i={},n={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[i]}]};Object.assign(i,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},n]});let s={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},r=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),a={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},o={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,i,s]};s.contains.push(o);let l={match:/\\"/},c={className:"string",begin:/'/,end:/'/},u={match:/\\'/},h={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,i]},d=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],f=e.SHEBANG({binary:`(${d.join("|")})`,relevance:10}),p={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},_=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],w=["true","false"],g={match:/(\/[a-z._-]+)+/},m=["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset"],v=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],S=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],k=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:_,literal:w,built_in:[...m,...v,"set","shopt",...S,...k]},contains:[f,e.SHEBANG(),p,h,r,a,g,o,l,c,u,i]}}RC.exports=RB});var LC=me((iH,DC)=>{function OB(e){let t=e.regex,i=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",s="[a-zA-Z_]\\w*::",a="("+n+"|"+t.optional(s)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o=t.concat(/\batomic_/,t.either("bool","char","schar","uchar","short","ushort","int","uint","long","ulong","llong","ullong","char16_t","char32_t","wchar_t","int_least8_t","uint_least8_t","int_least16_t","uint_least16_t","int_least32_t","uint_least32_t","int_least64_t","uint_least64_t","int_fast8_t","uint_fast8_t","int_fast16_t","uint_fast16_t","int_fast32_t","uint_fast32_t","int_fast64_t","uint_fast64_t","intptr_t","uintptr_t","size_t","ptrdiff_t","intmax_t","uintmax_t"),/\b/),l={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:o}]},u={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},h={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},d={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"},contains:[{begin:/\\\n/},u,{scope:"string",begin:/<.*?>/},i,e.C_BLOCK_COMMENT_MODE]},f={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(u,{className:"string"}),i,e.C_BLOCK_COMMENT_MODE]},p=[d,f],_={className:"title",begin:t.optional(s)+e.IDENT_RE,relevance:0},w=t.optional(s)+e.IDENT_RE+"\\s*\\(",g=12,S={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},k=[...p,l,i,e.C_BLOCK_COMMENT_MODE,h,u],A={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:S,contains:k.concat([{begin:/\(/,end:/\)/,keywords:S,contains:k.concat(["self"]),relevance:0}]),relevance:0},O={begin:"("+a+"[\\*&\\s]+){1,"+g+"}"+w,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:S,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:S,relevance:0},{begin:w,returnBegin:!0,contains:[e.inherit(_,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:S,relevance:0,contains:[i,e.C_BLOCK_COMMENT_MODE,u,h,l,{begin:/\(/,end:/\)/,keywords:S,relevance:0,contains:["self",i,e.C_BLOCK_COMMENT_MODE,u,h,l]}]},l,i,e.C_BLOCK_COMMENT_MODE,...p]};return{name:"C",aliases:["h"],keywords:S,disableAutodetect:!0,illegal:"=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:f,strings:u,keywords:S}}}DC.exports=OB});var IC=me((nH,BC)=>{function DB(e){let t=e.regex,i=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",s="[a-zA-Z_]\\w*::",a="(?!struct)("+n+"|"+t.optional(s)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},u={className:"number",variants:[{begin:"[+-]?(?:(?:\\b[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|\\b[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|\\b0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},h={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"},contains:[{begin:/\\\n/},c,{scope:"string",begin:/<.*?>/},i,e.C_BLOCK_COMMENT_MODE]},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),i,e.C_BLOCK_COMMENT_MODE]},f=[h,d],p={className:"title",begin:t.optional(s)+e.IDENT_RE,relevance:0},_=t.optional(s)+e.IDENT_RE+"\\s*\\(",w=12,g=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],m=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],v=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],S=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],O={type:m,keyword:g,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:v},T={className:"function.dispatch",relevance:0,keywords:{_hint:S},begin:t.concat(/\b/,`(?!${g.join("|")})`,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},D=[T,...f,o,i,e.C_BLOCK_COMMENT_MODE,u,c],F={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:O,contains:D.concat([{begin:/\(/,end:/\)/,keywords:O,contains:D.concat(["self"]),relevance:0}]),relevance:0},P={className:"function",begin:"("+a+"[\\*&\\s]+){1,"+w+"}"+_,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:O,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:O,relevance:0},{begin:_,returnBegin:!0,contains:[p],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,u]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:O,relevance:0,contains:[i,e.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:O,relevance:0,contains:["self",i,e.C_BLOCK_COMMENT_MODE,c,u,o]}]},o,i,e.C_BLOCK_COMMENT_MODE,...f]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:O,illegal:"",keywords:O,contains:["self",o]},{begin:e.IDENT_RE+"::",keywords:O},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}BC.exports=DB});var PC=me((sH,zC)=>{function LB(e){let t=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],i=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],n=["default","false","null","true"],s=["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],r=["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],a={keyword:s.concat(r),built_in:t,literal:n},o=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),l="\\d(_*\\d)*",c="([uU][lL]?|[lL][uU]?)?",h={className:"number",variants:[{begin:"\\b0[bB]_*[01](_*[01])*"+c},{begin:"(-?)\\b0[xX]_*[a-fA-F0-9](_*[a-fA-F0-9])*"+c},{begin:"(-?)(\\b"+l+"(\\.("+l+")?)?|\\."+l+")([eE][-+]?"+l+")?"+"([fFdDmM]|[uU][lL]?|[lL][uU]?)?"}],relevance:0},d={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},f={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},p=e.inherit(f,{illegal:/\n/}),_={className:"subst",begin:/\{/,end:/\}/,keywords:a},w=e.inherit(_,{illegal:/\n/}),g={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,w]},m={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},_]},v=e.inherit(m,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},w]});_.contains=[m,g,f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,e.C_BLOCK_COMMENT_MODE],w.contains=[v,g,p,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];let S={variants:[d,m,g,f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},k={begin:"<",end:">",contains:[{beginKeywords:"in out"},o]},A=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",O={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:a,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:""},{begin:""}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},S,h,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},o,k,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[o,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[o,k,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+A+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:a,contains:[{beginKeywords:i.join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,k],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:a,relevance:0,contains:[S,h,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},O]}}zC.exports=LB});var HC=me((rH,UC)=>{var BB=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),IB=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],zB=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],PB=[...IB,...zB],UB=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),HB=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),FB=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),qB=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function KB(e){let t=e.regex,i=BB(e),n={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},s="and or not only",r=/@-?\w[\w]*(-\w+)*/,a="[a-zA-Z-][a-zA-Z0-9_-]*",o=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[i.BLOCK_COMMENT,n,i.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+a,relevance:0},i.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+HB.join("|")+")"},{begin:":(:)?("+FB.join("|")+")"}]},i.CSS_VARIABLE,{className:"attribute",begin:"\\b("+qB.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[i.BLOCK_COMMENT,i.HEXCOLOR,i.IMPORTANT,i.CSS_NUMBER_MODE,i.UNICODE_RANGE,...o,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...o,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},i.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:r},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:s,attribute:UB.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...o,i.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+PB.join("|")+")\\b"}]}}UC.exports=KB});var qC=me((aH,FC)=>{function WB(e){let t=e.regex,i={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},n={match:/^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/},s={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},r={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},a={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},o=/[A-Za-z][A-Za-z0-9+.-]*/,l={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,o,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},c={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},u={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},h=e.inherit(c,{contains:[]}),d=e.inherit(u,{contains:[]});c.contains.push(d),u.contains.push(h);let f=[i,l];return[c,u,h,d].forEach(g=>{g.contains=g.contains.concat(f)}),f=f.concat(c,u),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:f},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:f}]}]},i,r,n,c,u,{className:"quote",begin:"^>\\s+",contains:f,end:"$"},s,l,a,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}FC.exports=WB});var WC=me((oH,KC)=>{function $B(e){let t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}KC.exports=$B});var GC=me((lH,$C)=>{function GB(e){let t=e.regex,i="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",n=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),s=t.concat(n,/(::\w+)*/),a={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},o={className:"doctag",begin:"@[A-Za-z]+"},l={begin:"#<",end:">"},c=[e.COMMENT("#","$",{contains:[o]}),e.COMMENT("^=begin","^=end",{contains:[o],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],u={className:"subst",begin:/#\{/,end:/\}/,keywords:a},h={className:"string",contains:[e.BACKSLASH_ESCAPE,u],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,u]})]}]},d="[1-9](_?[0-9])*|0",f="[0-9](_?[0-9])*",p={className:"number",relevance:0,variants:[{begin:`\\b(${d})(\\.(${f}))?([eE][+-]?(${f})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},_={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:a}]},A=[h,{variants:[{match:[/class\s+/,s,/\s+<\s+/,s]},{match:[/\b(class|module)\s+/,s]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:a},{match:[/(include|extend)\s+/,s],scope:{2:"title.class"},keywords:a},{relevance:0,match:[s,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:n,scope:"title.class"},{match:[/def/,/\s+/,i],scope:{1:"keyword",3:"title.function"},contains:[_]},{begin:"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[h,{begin:i}],relevance:0},p,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:a},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,u],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(l,c),relevance:0}].concat(l,c);u.contains=A,_.contains=A;let F=[{begin:/^\s*=>/,starts:{end:"$",contains:A}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:a,contains:A}}];return c.unshift(l),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:a,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(F).concat(c).concat(A)}}$C.exports=GB});var jC=me((cH,YC)=>{function YB(e){let r={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:r,illegal:"{function jB(e){let t=e.regex,i=/[_A-Za-z][_0-9A-Za-z]*/;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:t.concat(i,t.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}}VC.exports=jB});var QC=me((hH,ZC)=>{function VB(e){let t=e.regex,i={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:e.NUMBER_RE}]},n=e.COMMENT();n.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];let s={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},r={className:"literal",begin:/\bon|off|true|false|yes|no\b/},a={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},o={begin:/\[/,end:/\]/,contains:[n,r,s,a,i,"self"],relevance:0},l=/[A-Za-z0-9_-]+/,c=/"(\\"|[^"])*"/,u=/'[^']*'/,h=t.either(l,c,u),d=t.concat(h,"(\\s*\\.\\s*",h,")*",t.lookahead(/\s*=\s*[^#\s]/));return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[n,{className:"section",begin:/\[+/,end:/\]+/},{begin:d,className:"attr",starts:{end:/$/,contains:[n,o,r,s,a,i]}}]}}ZC.exports=VB});var ik=me((dH,tk)=>{var Cl="[0-9](_*[0-9])*",Jd=`\\.(${Cl})`,ef="[0-9a-fA-F](_*[0-9a-fA-F])*",JC={className:"number",variants:[{begin:`(\\b(${Cl})((${Jd})|\\.)?|(${Jd}))[eE][+-]?(${Cl})[fFdD]?\\b`},{begin:`\\b(${Cl})((${Jd})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Jd})[fFdD]?\\b`},{begin:`\\b(${Cl})[fFdD]\\b`},{begin:`\\b0[xX]((${ef})\\.?|(${ef})?\\.(${ef}))[pP][+-]?(${Cl})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${ef})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function ek(e,t,i){return i===-1?"":e.replace(t,n=>ek(e,t,i-1))}function XB(e){let t=e.regex,i="[\xC0-\u02B8a-zA-Z_$][\xC0-\u02B8a-zA-Z_$0-9]*",n="(?:(?:\\s*\\[\\s*])+)?",s=i+"<@@@>"+n,a="(?:"+("\\?(?:\\s+(?:extends|super)\\s+"+s+")?")+"|"+s+")",o=ek("(?:\\s*<\\s*"+a+"(?:\\s*,\\s*"+a+")*\\s*>)?",/<@@@>/g,2),d={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},f={className:"meta",begin:"@"+i,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},p={className:"params",begin:/\(/,end:/\)/,keywords:d,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:d,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,i],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{beginKeywords:"new throw return else yield assert",relevance:0},{begin:[i,t.concat(o,n,/\s+/),i,n,/\s*/,/=(?!=)/],className:{1:"type",3:"variable",6:"operator"}},{begin:[/record/,/\s+/,i],className:{1:"keyword",3:"title.class"},contains:[p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{begin:[i,t.concat(o,n,/\s+/),i,/\s*(?=\()/],className:{1:"type",3:"title.function"},keywords:d,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:d,relevance:0,contains:[f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,JC,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},JC,f]}}tk.exports=XB});var lk=me((fH,ok)=>{var nk="[A-Za-z$_][0-9A-Za-z$_]*",ZB=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],QB=["true","false","null","undefined","NaN","Infinity"],sk=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],rk=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],ak=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],JB=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],eI=[].concat(ak,sk,rk);function tI(e){let t=e.regex,i=(R,{after:$})=>{let ee="",end:""},r=/<[A-Za-z0-9\\._:-]+\s*\/>/,a={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(R,$)=>{let ee=R[0].length+R.index,z=R.input[ee];if(z==="<"||z===","){$.ignoreMatch();return}z===">"&&(i(R,{after:ee})||$.ignoreMatch());let X,Ee=R.input.substring(ee);if(X=Ee.match(/^\s*=/)){$.ignoreMatch();return}if((X=Ee.match(/^\s+extends\s+/))&&X.index===0){$.ignoreMatch();return}}},o={$pattern:nk,keyword:ZB,literal:QB,built_in:eI,"variable.language":JB},l="[0-9](_?[0-9])*",c=`\\.(${l})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${u})((${c})|\\.)?|(${c}))[eE][+-]?(${l})\\b`},{begin:`\\b(${u})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},p={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},_={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},w={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},m={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,w,{match:/\$\d+/},h];d.contains=v.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(v)});let S=[].concat(m,d.contains),k=S.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(S)}]),A={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:k},O={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},T={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...sk,...rk]}},D={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},F={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[A],illegal:/%/},P={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function M(R){return t.concat("(?!",R.join("|"),")")}let B={match:t.concat(/\b/,M([...ak,"super","import","await"].map(R=>`${R}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},E={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},I={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},A]},C="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",L={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(C)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[A]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:k,CLASS_REFERENCE:T},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),D,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,w,m,{match:/\$\d+/},h,T,{scope:"attr",match:n+t.lookahead(":"),relevance:0},L,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[m,e.REGEXP_MODE,{className:"function",begin:C,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:k}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:s.begin,end:s.end},{match:r},{begin:a.begin,"on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},F,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[A,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},E,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[A]},B,P,O,I,{match:/\$[(.]/}]}}ok.exports=tI});var uk=me((pH,ck)=>{var iI="([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity",nI={scope:"number",match:iI,relevance:0};function sI(e){let t={className:"attr",begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},i={match:/[{}[\],:]/,className:"punctuation",relevance:0},n=["true","false","null"],s={scope:"literal",beginKeywords:n.join(" ")};return{name:"JSON",aliases:["jsonc","json5"],keywords:{literal:n},contains:[t,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,s,nI,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}ck.exports=sI});var dk=me((mH,hk)=>{var kl="[0-9](_*[0-9])*",tf=`\\.(${kl})`,nf="[0-9a-fA-F](_*[0-9a-fA-F])*",rI={className:"number",variants:[{begin:`(\\b(${kl})((${tf})|\\.)?|(${tf}))[eE][+-]?(${kl})[fFdD]?\\b`},{begin:`\\b(${kl})((${tf})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${tf})[fFdD]?\\b`},{begin:`\\b(${kl})[fFdD]\\b`},{begin:`\\b0[xX]((${nf})\\.?|(${nf})?\\.(${nf}))[pP][+-]?(${kl})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${nf})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function aI(e){let t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},i={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},n={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},s={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},r={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},a={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[r,s]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,r,s]}]};s.contains.push(a);let o={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},l={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(a,{className:"string"}),"self"]}]},c=rI,u=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),h={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},d=h;return d.variants[1].contains=[h],h.variants[1].contains=[d],{name:"Kotlin",aliases:["kt","kts","ktm","ktx"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,u,i,n,o,l,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[h,e.C_LINE_COMMENT_MODE,u],relevance:0},e.C_LINE_COMMENT_MODE,u,o,l,a,e.C_NUMBER_MODE]},u]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},o,l]},a,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:` -`},c]}}hk.exports=aI});var gk=me((gH,mk)=>{var oI=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),lI=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],cI=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],uI=[...lI,...cI],hI=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),fk=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),pk=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),dI=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),fI=fk.concat(pk).sort().reverse();function pI(e){let t=oI(e),i=fI,n="and or not only",s="[\\w-]+",r="("+s+"|@\\{"+s+"\\})",a=[],o=[],l=function(v){return{className:"string",begin:"~?"+v+".*?"+v}},c=function(v,S,k){return{className:v,begin:S,relevance:k}},u={$pattern:/[a-z-]+/,keyword:n,attribute:hI.join(" ")},h={begin:"\\(",end:"\\)",contains:o,keywords:u,relevance:0};o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,l("'"),l('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},t.UNICODE_RANGE,t.HEXCOLOR,h,c("variable","@@?"+s,10),c("variable","@\\{"+s+"\\}"),c("built_in","~?`[^`]*?`"),{className:"attribute",begin:s+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);let d=o.concat({begin:/\{/,end:/\}/,contains:a}),f={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(o)},p={begin:r+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+dI.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:o}}]},_={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:u,returnEnd:!0,contains:o,relevance:0}},w={className:"variable",variants:[{begin:"@"+s+"\\s*:",relevance:15},{begin:"@"+s}],starts:{end:"[;}]",returnEnd:!0,contains:d}},g={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:r,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,f,c("keyword","all\\b"),c("variable","@\\{"+s+"\\}"),{begin:"\\b("+uI.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,c("selector-tag",r,0),c("selector-id","#"+r),c("selector-class","\\."+r,0),c("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+fk.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+pk.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:d},{begin:"!important"},t.FUNCTION_DISPATCH]},m={begin:s+`:(:)?(${i.join("|")})`,returnBegin:!0,contains:[g]};return a.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,_,w,m,p,g,f,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:a}}mk.exports=pI});var vk=me((_H,_k)=>{function mI(e){let t="\\[=*\\[",i="\\]=*\\]",n={begin:t,end:i,contains:["self"]},s=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,i,{contains:[n],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local global not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:s.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:s}].concat(s)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:i,contains:[n],relevance:5}])}}_k.exports=mI});var yk=me((vH,bk)=>{function gI(e){let t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%{function _I(e){let t=e.regex,i=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],n=/[dualxmsipngr]{0,12}/,s={$pattern:/[\w.]+/,keyword:i.join(" ")},r={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:s},a={begin:/->\{/,end:/\}/},o={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},l={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[o]},c={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},u=[e.BACKSLASH_ESCAPE,r,l],h=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],d=(_,w,g="\\1")=>{let m=g==="\\1"?g:t.concat(g,w);return t.concat(t.concat("(?:",_,")"),w,/(?:\\.|[^\\\/])*?/,m,/(?:\\.|[^\\\/])*?/,g,n)},f=(_,w,g)=>t.concat(t.concat("(?:",_,")"),w,/(?:\\.|[^\\\/])*?/,g,n),p=[l,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),a,{className:"string",contains:u,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},c,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:d("s|tr|y",t.either(...h,{capture:!0}))},{begin:d("s|tr|y","\\(","\\)")},{begin:d("s|tr|y","\\[","\\]")},{begin:d("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:f("(?:m|qr)?",/\//,/\//)},{begin:f("m|qr",t.either(...h,{capture:!0}),/\1/)},{begin:f("m|qr",/\(/,/\)/)},{begin:f("m|qr",/\[/,/\]/)},{begin:f("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,o]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,o,c]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return r.contains=p,a.contains=p,{name:"Perl",aliases:["pl","pm"],keywords:s,contains:p}}Sk.exports=_I});var xk=me((yH,Ek)=>{function vI(e){let t={className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},i=/[a-zA-Z@][a-zA-Z0-9_]*/,o={"variable.language":["this","super"],$pattern:i,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},l={$pattern:i,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:o,illegal:"/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+l.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:l,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}}Ek.exports=vI});var kk=me((SH,Ck)=>{function bI(e){let t=e.regex,i=/(?![A-Za-z0-9])(?![$])/,n=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,i),s=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,i),r=t.concat(/[A-Z]+/,i),a={scope:"variable",match:"\\$+"+n},o={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},l={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},c=e.inherit(e.APOS_STRING_MODE,{illegal:null}),u=e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(l)}),h={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(l),"on:begin":(E,I)=>{I.data._beginMatch=E[1]||E[2]},"on:end":(E,I)=>{I.data._beginMatch!==E[1]&&I.ignoreMatch()}},d=e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),f=`[ -]`,p={scope:"string",variants:[u,c,h,d]},_={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},w=["false","null","true"],g=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],m=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],S={keyword:g,literal:(E=>{let I=[];return E.forEach(C=>{I.push(C),C.toLowerCase()===C?I.push(C.toUpperCase()):I.push(C.toLowerCase())}),I})(w),built_in:m},k=E=>E.map(I=>I.replace(/\|\d+$/,"")),A={variants:[{match:[/new/,t.concat(f,"+"),t.concat("(?!",k(m).join("\\b|"),"\\b)"),s],scope:{1:"keyword",4:"title.class"}}]},O=t.concat(n,"\\b(?!\\()"),T={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),O],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[s,t.concat(/::/,t.lookahead(/(?!class\b)/)),O],scope:{1:"title.class",3:"variable.constant"}},{match:[s,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[s,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},D={scope:"attr",match:t.concat(n,t.lookahead(":"),t.lookahead(/(?!::)/))},F={relevance:0,begin:/\(/,end:/\)/,keywords:S,contains:[D,a,T,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_,A]},P={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",k(g).join("\\b|"),"|",k(m).join("\\b|"),"\\b)"),n,t.concat(f,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[F]};F.contains.push(P);let M=[D,T,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_,A],B={begin:t.concat(/#\[\s*\\?/,t.either(s,r)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:w,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:w,keyword:["new","array"]},contains:["self",...M]},...M,{scope:"meta",variants:[{match:s},{match:r}]}]};return{case_insensitive:!1,keywords:S,contains:[B,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},o,{scope:"variable.language",match:/\$this\b/},a,P,T,{match:[/const/,/\s/,n],scope:{1:"keyword",3:"variable.constant"}},A,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:S,contains:["self",B,a,T,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},p,_]}}Ck.exports=bI});var Nk=me((wH,Tk)=>{function yI(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}Tk.exports=yI});var Mk=me((EH,Ak)=>{function SI(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}Ak.exports=SI});var Ok=me((xH,Rk)=>{function wI(e){let t=e.regex,i=/[\p{XID_Start}_]\p{XID_Continue}*/u,n=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","lazy","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],o={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:n,built_in:["__import__","abs","aiter","all","anext","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozendict","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","sentinel","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},l={className:"meta",begin:/^(>>>|\.\.\.) /},c={className:"subst",begin:/\{/,end:/\}/,keywords:o,illegal:/#/},u={begin:/\{\{/,relevance:0},h={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,l],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,l],relevance:10},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,l,u,c]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,l,u,c]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,u,c]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,u,c]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},d="[0-9](_?[0-9])*",f=`(\\b(${d}))?\\.(${d})|\\b(${d})\\.`,p=`\\b|${n.join("|")}`,_={className:"number",relevance:0,variants:[{begin:`(\\b(${d})|(${f}))[eE][+-]?(${d})[jJ]?(?=${p})`},{begin:`(${f})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${p})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${p})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${p})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${p})`},{begin:`\\b(${d})[jJ](?=${p})`}]},w={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:o,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},g={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:["self",l,_,h,e.HASH_COMMENT_MODE]}]};return c.contains=[h,_,l],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:o,illegal:/(<\/|\?)|=>/,contains:[l,_,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},h,w,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,i],scope:{1:"keyword",3:"title.function"},contains:[g]},{variants:[{match:[/\bclass/,/\s+/,i,/\s*/,/\(\s*/,i,/\s*\)/]},{match:[/\bclass/,/\s+/,i]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[_,g,h]}]}}Rk.exports=wI});var Lk=me((CH,Dk)=>{function EI(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}Dk.exports=EI});var Ik=me((kH,Bk)=>{function xI(e){let t=e.regex,i=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,n=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),s=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,r=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:i,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:i},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[s,n]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,n]},{scope:{1:"punctuation",2:"number"},match:[r,n]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,n]}]},{scope:{3:"operator"},match:[i,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:s},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:r},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}Bk.exports=xI});var Pk=me((TH,zk)=>{function CI(e){let t=e.regex,i=/(r#)?/,n=t.concat(i,e.UNDERSCORE_IDENT_RE),s=t.concat(i,e.IDENT_RE),r={scope:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!(?:let|for|while|if|else|match)\b)/,s,t.lookahead(/\s*\(/))},a="([ui](8|16|32|64|128|size)|f(16|32|64|128))?",o=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","raw","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],l=["true","false","Some","None","Ok","Err"],c=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],u=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f16","f32","f64","f128","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:u,keyword:o,literal:l,built_in:c},illegal:""},r]}}zk.exports=CI});var Hk=me((NH,Uk)=>{var kI=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),TI=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],NI=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],AI=[...TI,...NI],MI=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),RI=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),OI=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),DI=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function LI(e){let t=kI(e),i=OI,n=RI,s="@[a-z-]+",r="and or not only",o={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+AI.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+n.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+i.join("|")+")"},o,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+DI.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,o,t.HEXCOLOR,t.CSS_NUMBER_MODE,t.UNICODE_RANGE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:s,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:r,attribute:MI.join(" ")},contains:[{begin:s,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},o,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}}Uk.exports=LI});var qk=me((AH,Fk)=>{function BI(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[./~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}Fk.exports=BI});var Wk=me((MH,Kk)=>{function II(e){let t=e.regex,i=e.COMMENT("--","$"),n={scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},s={begin:/"/,end:/"/,contains:[{match:/""/}]},r=["true","false","unknown"],a=["double precision","large object","with timezone","without timezone"],o=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],l=["add","asc","collation","desc","final","first","last","view"],c=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year"],u=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],h=["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"],d=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],f=u,p=[...c,...l].filter(k=>!u.includes(k)),_={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},w={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},g={match:t.concat(/\b/,t.either(...f),/\s*\(/),relevance:0,keywords:{built_in:f}};function m(k){return t.concat(/\b/,t.either(...k.map(A=>A.replace(/\s+/,"\\s+"))),/\b/)}let v={scope:"keyword",match:m(d),relevance:0};function S(k,{exceptions:A,when:O}={}){let T=O;return A=A||[],k.map(D=>D.match(/\|\d+$/)||A.includes(D)?D:T(D)?`${D}|0`:D)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:S(p,{when:k=>k.length<3}),literal:r,type:o,built_in:h},contains:[{scope:"type",match:m(a)},v,g,_,n,s,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,i,w]}}Kk.exports=II});var Jk=me((RH,Qk)=>{function jk(e){return e?typeof e=="string"?e:e.source:null}function iu(e){return et("(?=",e,")")}function et(...e){return e.map(i=>jk(i)).join("")}function zI(e){let t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function ki(...e){return"("+(zI(e).capture?"":"?:")+e.map(n=>jk(n)).join("|")+")"}new RegExp(ki(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));var ov=e=>et(/\b/,e,/\w$/.test(e)?/\b/:/\B/),PI=["Protocol","Type"].map(ov),$k=["init","self"].map(ov),UI=["Any","Self"],rv=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],Gk=["false","nil","true"],HI=["assignment","associativity","higherThan","left","lowerThan","none","right"],FI=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],Yk=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],Vk=ki(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),Xk=ki(Vk,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),av=et(Vk,Xk,"*"),Zk=ki(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),rf=ki(Zk,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Cs=et(Zk,rf,"*"),sf=et(/[A-Z]/,rf,"*"),qI=["attached","autoclosure",et(/convention\(/,ki("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",et(/objc\(/,Cs,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],KI=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function WI(e){let t={match:/\s+/,relevance:0},i=e.COMMENT("/\\*","\\*/",{contains:["self"]}),n=[e.C_LINE_COMMENT_MODE,i],s={match:[/\./,ki(...PI,...$k)],className:{2:"keyword"}},r={match:et(/\./,ki(...rv)),relevance:0},a=rv.filter(he=>typeof he=="string").concat(["_|0"]),o=rv.filter(he=>typeof he!="string").concat(UI).map(ov),l={variants:[{className:"keyword",match:ki(...o,...$k)}]},c={$pattern:ki(/\b\w+/,/#\w+/),keyword:a.concat(FI),literal:Gk},u=[s,r,l],h={match:et(/\./,ki(...Yk)),relevance:0},d={className:"built_in",match:et(/\b/,ki(...Yk),/(?=\()/)},f=[h,d],p={match:/->/,relevance:0},_={className:"operator",relevance:0,variants:[{match:av},{match:`\\.(\\.|${Xk})+`}]},w=[p,_],g="([0-9]_*)+",m="([0-9a-fA-F]_*)+",v={className:"number",relevance:0,variants:[{match:`\\b(${g})(\\.(${g}))?([eE][+-]?(${g}))?\\b`},{match:`\\b0x(${m})(\\.(${m}))?([pP][+-]?(${g}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},S=(he="")=>({className:"subst",variants:[{match:et(/\\/,he,/[0\\tnr"']/)},{match:et(/\\/,he,/u\{[0-9a-fA-F]{1,8}\}/)}]}),k=(he="")=>({className:"subst",match:et(/\\/,he,/[\t ]*(?:[\r\n]|\r\n)/)}),A=(he="")=>({className:"subst",label:"interpol",begin:et(/\\/,he,/\(/),end:/\)/}),O=(he="")=>({begin:et(he,/"""/),end:et(/"""/,he),contains:[S(he),k(he),A(he)]}),T=(he="")=>({begin:et(he,/"/),end:et(/"/,he),contains:[S(he),A(he)]}),D={className:"string",variants:[O(),O("#"),O("##"),O("###"),T(),T("#"),T("##"),T("###")]},F=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],P={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:F},M=he=>{let hi=et(he,/\//),ne=et(/\//,he);return{begin:hi,end:ne,contains:[...F,{scope:"comment",begin:`#(?!.*${ne})`,end:/$/}]}},B={scope:"regexp",variants:[M("###"),M("##"),M("#"),P]},E={match:et(/`/,Cs,/`/)},I={className:"variable",match:/\$\d+/},C={className:"variable",match:`\\$${rf}+`},L=[E,I,C],R={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:KI,contains:[...w,v,D]}]}},$={scope:"keyword",match:et(/@/,ki(...qI),iu(ki(/\(/,/\s+/)))},ee={scope:"meta",match:et(/@/,Cs)},z=[R,$,ee],X={match:iu(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:et(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,rf,"+")},{className:"type",match:sf,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:et(/\s+&\s+/,iu(sf)),relevance:0}]},Ee={begin://,keywords:c,contains:[...n,...u,...z,p,X]};X.contains.push(Ee);let ue={match:et(Cs,/\s*:/),keywords:"_|0",relevance:0},De={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",ue,...n,B,...u,...f,...w,v,D,...L,...z,X]},J={begin://,keywords:"repeat each",contains:[...n,X]},qe={begin:ki(iu(et(Cs,/\s*:/)),iu(et(Cs,/\s+/,Cs,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Cs}]},dt={begin:/\(/,end:/\)/,keywords:c,contains:[qe,...n,...u,...w,v,D,...z,X,De],endsParent:!0,illegal:/["']/},oi={match:[/(func|macro)/,/\s+/,ki(E.match,Cs,av)],className:{1:"keyword",3:"title.function"},contains:[J,dt,t],illegal:[/\[/,/%/]},Mi={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[J,dt,t],illegal:/\[|%/},Ri={match:[/operator/,/\s+/,av],className:{1:"keyword",3:"title"}},li={begin:[/precedencegroup/,/\s+/,sf],className:{1:"keyword",3:"title"},contains:[X],keywords:[...HI,...Gk],end:/}/},xe={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},ci={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},ui={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Cs,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[J,...u,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:sf},...u],relevance:0}]};for(let he of D.variants){let hi=he.contains.find(ts=>ts.label==="interpol");hi.keywords=c;let ne=[...u,...f,...w,v,D,...L];hi.contains=[...ne,{begin:/\(/,end:/\)/,contains:["self",...ne]}]}return{name:"Swift",keywords:c,contains:[...n,oi,Mi,xe,ci,ui,Ri,li,{beginKeywords:"import",end:/$/,contains:[...n],relevance:0},B,...u,...f,...w,v,D,...L,...z,X,De]}}Qk.exports=WI});var tT=me((OH,eT)=>{function $I(e){let t="true false yes no null",i="[\\w#;/?:@&=+$,.~*'()[\\]]+",n={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},s={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},r={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},a={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,s]},o=e.inherit(a,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),d={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},f={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},p={begin:/\{/,end:/\}/,contains:[f],illegal:"\\n",relevance:0},_={begin:"\\[",end:"\\]",contains:[f],illegal:"\\n",relevance:0},w=[n,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+i},{className:"type",begin:"!<"+i+">"},{className:"type",begin:"!"+i},{className:"type",begin:"!!"+i},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},d,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},p,_,r,a],g=[...w];return g.pop(),g.push(o),f.contains=g,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:w}}eT.exports=$I});var uT=me((DH,cT)=>{var af="[A-Za-z$_][0-9A-Za-z$_]*",iT=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],nT=["true","false","null","undefined","NaN","Infinity"],sT=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],rT=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],aT=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],oT=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],lT=[].concat(aT,sT,rT);function GI(e){let t=e.regex,i=(R,{after:$})=>{let ee="",end:""},r=/<[A-Za-z0-9\\._:-]+\s*\/>/,a={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(R,$)=>{let ee=R[0].length+R.index,z=R.input[ee];if(z==="<"||z===","){$.ignoreMatch();return}z===">"&&(i(R,{after:ee})||$.ignoreMatch());let X,Ee=R.input.substring(ee);if(X=Ee.match(/^\s*=/)){$.ignoreMatch();return}if((X=Ee.match(/^\s+extends\s+/))&&X.index===0){$.ignoreMatch();return}}},o={$pattern:af,keyword:iT,literal:nT,built_in:lT,"variable.language":oT},l="[0-9](_?[0-9])*",c=`\\.(${l})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${u})((${c})|\\.)?|(${c}))[eE][+-]?(${l})\\b`},{begin:`\\b(${u})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},p={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},_={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},w={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},m={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,w,{match:/\$\d+/},h];d.contains=v.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(v)});let S=[].concat(m,d.contains),k=S.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(S)}]),A={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:k},O={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},T={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...sT,...rT]}},D={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},F={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[A],illegal:/%/},P={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function M(R){return t.concat("(?!",R.join("|"),")")}let B={match:t.concat(/\b/,M([...aT,"super","import","await"].map(R=>`${R}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},E={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},I={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},A]},C="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",L={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(C)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[A]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:k,CLASS_REFERENCE:T},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),D,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,w,m,{match:/\$\d+/},h,T,{scope:"attr",match:n+t.lookahead(":"),relevance:0},L,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[m,e.REGEXP_MODE,{className:"function",begin:C,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:k}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:s.begin,end:s.end},{match:r},{begin:a.begin,"on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},F,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[A,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},E,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[A]},B,P,O,I,{match:/\$[(.]/}]}}function YI(e){let t=e.regex,i=GI(e),n=af,s=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],r={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},a={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:s},contains:[i.exports.CLASS_REFERENCE]},o={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},l=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],c={$pattern:af,keyword:iT.concat(l),literal:nT,built_in:lT.concat(s),"variable.language":oT},u={className:"meta",begin:"@"+n},h=(_,w,g)=>{let m=_.contains.findIndex(v=>v.label===w);if(m===-1)throw new Error("can not find mode to replace");_.contains.splice(m,1,g)};Object.assign(i.keywords,c),i.exports.PARAMS_CONTAINS.push(u);let d=i.contains.find(_=>_.scope==="attr"),f=Object.assign({},d,{match:t.concat(n,t.lookahead(/\s*\?:/))});i.exports.PARAMS_CONTAINS.push([i.exports.CLASS_REFERENCE,d,f]),i.contains=i.contains.concat([u,r,a,f]),h(i,"shebang",e.SHEBANG()),h(i,"use_strict",o);let p=i.contains.find(_=>_.label==="func.def");return p.relevance=0,Object.assign(i,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),i}cT.exports=YI});var dT=me((LH,hT)=>{function jI(e){let t=e.regex,i={className:"string",begin:/"(""|[^/n])"C\b/},n={className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},s=/\d{1,2}\/\d{1,2}\/\d{4}/,r=/\d{4}-\d{1,2}-\d{1,2}/,a=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,o=/\d{1,2}(:\d{1,2}){1,2}/,l={className:"literal",variants:[{begin:t.concat(/# */,t.either(r,s),/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,a,/ *#/)},{begin:t.concat(/# */,t.either(r,s),/ +/,t.either(a,o),/ *#/)}]},c={className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},u={className:"label",begin:/^\w+:/},h=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),d=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[i,n,l,c,u,h,d,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[d]}]}}hT.exports=jI});var pT=me((BH,fT)=>{function VI(e){e.regex;let t=e.COMMENT(/\(;/,/;\)/);t.contains.push("self");let i=e.COMMENT(/;;/,/$/),n=["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"],s={begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},r={className:"variable",begin:/\$[\w_]+/},a={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},o={className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/},l={match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},c={className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/};return{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:n},contains:[i,t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},r,a,s,e.QUOTE_STRING_MODE,l,c,o]}}fT.exports=VI});var gT=me((IH,mT)=>{var Ne=NC();Ne.registerLanguage("xml",MC());Ne.registerLanguage("bash",OC());Ne.registerLanguage("c",LC());Ne.registerLanguage("cpp",IC());Ne.registerLanguage("csharp",PC());Ne.registerLanguage("css",HC());Ne.registerLanguage("markdown",qC());Ne.registerLanguage("diff",WC());Ne.registerLanguage("ruby",GC());Ne.registerLanguage("go",jC());Ne.registerLanguage("graphql",XC());Ne.registerLanguage("ini",QC());Ne.registerLanguage("java",ik());Ne.registerLanguage("javascript",lk());Ne.registerLanguage("json",uk());Ne.registerLanguage("kotlin",dk());Ne.registerLanguage("less",gk());Ne.registerLanguage("lua",vk());Ne.registerLanguage("makefile",yk());Ne.registerLanguage("perl",wk());Ne.registerLanguage("objectivec",xk());Ne.registerLanguage("php",kk());Ne.registerLanguage("php-template",Nk());Ne.registerLanguage("plaintext",Mk());Ne.registerLanguage("python",Ok());Ne.registerLanguage("python-repl",Lk());Ne.registerLanguage("r",Ik());Ne.registerLanguage("rust",Pk());Ne.registerLanguage("scss",Hk());Ne.registerLanguage("shell",qk());Ne.registerLanguage("sql",Wk());Ne.registerLanguage("swift",Jk());Ne.registerLanguage("yaml",tT());Ne.registerLanguage("typescript",uT());Ne.registerLanguage("vbnet",dT());Ne.registerLanguage("wasm",pT());Ne.HighlightJS=Ne;Ne.default=Ne;mT.exports=Ne});var _T,of,lv=le(()=>{_T=ae(gT(),1),of=_T.default});function ZI(e){return XI(Ve.parse(e,{async:!1}))}function cv({text:e,streaming:t}){let i=(0,Tl.useRef)(null),n=(0,Tl.useMemo)(()=>ZI(e),[e]);return(0,Tl.useEffect)(()=>{let s=i.current;if(s){for(let r of s.querySelectorAll("a[href^='http']"))r.target="_blank",r.rel="noopener";for(let r of s.querySelectorAll("pre")){let a=r.querySelector("code");if(a&&!a.dataset.hl){a.dataset.hl="1";try{of.highlightElement(a)}catch{}}if(!r.querySelector(".cb-copy")){let o=document.createElement("button");o.className="cb-copy",o.textContent="\u590D\u5236",o.onclick=()=>{let l=a?.textContent??"";jr(l).then(()=>{o.textContent="\u5DF2\u590D\u5236",setTimeout(()=>o.textContent="\u590D\u5236",1200)})},r.appendChild(o)}}}},[n]),(0,vT.jsx)("div",{ref:i,className:`md${t?" streaming":""}`,dangerouslySetInnerHTML:{__html:n}})}async function jr(e){try{await navigator.clipboard.writeText(e);return}catch{}try{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove()}catch{}}var Tl,vT,XI,lf=le(()=>{Tl=ae(Nt(),1);Ux();lC();lv();vT=ae(ke(),1);Ve.setOptions({gfm:!0,breaks:!0});XI=e=>oC.sanitize(e,{USE_PROFILES:{html:!0},ADD_ATTR:["target","rel"]})});function QI(e){let[t,i]=(0,Ya.useState)(Date.now());return(0,Ya.useEffect)(()=>{if(!e)return;let n=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(n)},[e]),t}function bT({pendingCount:e}){let{projects:t,threads:i}=ut(),n=fe(),{version:s}=ws(),[r,a]=(0,Ya.useState)(!1),[o,l]=(0,Ya.useState)(!1),[c,u]=(0,Ya.useState)(""),[h,d,f]=Wc(),p=i.find(A=>A.id===n.currentThreadId)??null,_=p?t.find(A=>A.id===p.projectId):t.find(A=>A.id===n.currentProjectId),w=p?.status==="running"||p?.status==="initializing",g=QI(w),m=w&&p?Math.max(0,g-p.updatedAt):0,v=p?e>0?{cls:"wait",text:y("topbar.waitAuth")}:w?{cls:"run",text:Ce("topbar.running",{s:Math.floor(m/1e3)})}:p.status==="error"?{cls:"err",text:y("topbar.error")}:p.status==="closed"?{cls:"",text:y("topbar.closedResume")}:null:null,S=[{tab:"changes",icon:"changes",title:y("topbar.panelChanges")},{tab:"files",icon:"files",title:y("topbar.panelFiles")},{tab:"terminal",icon:"term",title:y("topbar.panelTerminal")}],k=p?[{kind:"item",label:y("common.rename"),onClick:()=>{u(p.title),a(!0)}},{kind:"item",label:y("topbar.threadInfo"),onClick:()=>l(!0)},{kind:"sep"},{kind:"item",label:y("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings"))},{kind:"label",text:s?`v${s}`:""}]:[{kind:"item",label:y("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings"))},{kind:"label",text:s?`v${s}`:""}];return(0,st.jsxs)("header",{className:"topbar",children:[(0,st.jsx)("button",{className:"ibtn tb-menu-btn",title:y("topbar.sidebar"),onClick:()=>n.setSbOpen(!n.sbOpen),children:(0,st.jsx)(ye,{name:"menu"})}),_&&(0,st.jsx)("span",{className:"tb-crumb",children:_.name}),_&&p&&(0,st.jsx)("span",{className:"tb-sep",children:"/"}),p?r?(0,st.jsx)("input",{className:"tb-rename",autoFocus:!0,value:c,onChange:A=>u(A.target.value),onBlur:()=>a(!1),onKeyDown:A=>{A.key==="Enter"&&!Mn(A.nativeEvent)&&c.trim()?(te.call("threads.update",{id:p.id,title:c.trim()}),a(!1)):A.key==="Escape"&&a(!1)}}):(0,st.jsx)("span",{className:"tb-title",title:y("topbar.clickRename"),onClick:()=>{u(p.title),a(!0)},children:Dd(p.title,p.titleAuto)}):(0,st.jsx)("span",{className:"tb-title ghost",children:_?y("topbar.pickThread"):y("app.title")}),v&&(0,st.jsxs)("span",{className:`tb-pill ${v.cls}`,children:[v.cls==="run"&&(0,st.jsx)("span",{className:"tb-pill-dot"}),v.text]}),(0,st.jsxs)("div",{className:"tb-right",children:[p?.model&&(0,st.jsx)("span",{className:"tb-model",children:p.model}),S.map(A=>(0,st.jsx)("button",{className:`ibtn${n.panelOpen&&n.panelTab===A.tab?" on":""}`,title:A.title,onClick:()=>n.panelOpen&&n.panelTab===A.tab?n.closePanel():n.openPanel(A.tab),children:(0,st.jsx)(ye,{name:A.icon})},A.tab)),(0,st.jsx)("button",{className:"ibtn",title:y("common.more"),onClick:A=>d(A),children:(0,st.jsx)(ye,{name:"dots"})})]}),h&&(0,st.jsx)(Kc,{x:h.x,y:h.y,items:k,onClose:f}),o&&p&&(0,st.jsx)(JI,{thread:p,project:_,onClose:()=>l(!1)})]})}function JI({thread:e,project:t,onClose:i}){let n=e.usage,s=Od(),r=[[y("thread.agent"),e.provider],[y("thread.model"),e.model??y("common.default")],[y("thread.mode"),e.mode],[y("thread.effort"),e.effort??y("common.default")],[y("thread.sessionId"),e.providerSessionId??y("thread.sessionNone")],[y("thread.tokens"),Ce("thread.tokensFmt",{in:ml(n.inputTokens),out:ml(n.outputTokens),cache:ml(n.cacheReadTokens)})],[y("thread.cost"),n.costUsd>0?Pd(n.costUsd):"\u2014"],[y("thread.created"),new Date(e.createdAt).toLocaleString(s)],[y("thread.workdir"),t?.path??"\u2014"]];e.importedFrom&&r.push([y("thread.importedFrom"),`${e.importedFrom.provider} / ${e.importedFrom.sessionId.slice(0,8)}\u2026`]);let a=new Set([y("thread.sessionId"),y("thread.workdir")]);return(0,st.jsx)(Es,{title:y("thread.info"),onClose:i,children:(0,st.jsx)("div",{className:"info-grid",children:r.map(([o,l])=>(0,st.jsxs)("div",{className:"info-row",children:[(0,st.jsx)("span",{className:"info-k",children:o}),(0,st.jsx)("span",{className:"info-v",title:l,children:l}),a.has(o)&&l!=="\u2014"&&l!==y("thread.sessionNone")&&(0,st.jsx)("button",{className:"ibtn",title:y("common.copy"),onClick:()=>{jr(l),Te(y("common.copied"))},children:(0,st.jsx)(ye,{name:"copy",size:12})})]},o))})})}var Ya,st,yT=le(()=>{Ya=ae(Nt(),1);pl();jn();dn();qc();Rn();Wr();N_();_l();lf();Vn();Ud();Ci();st=ae(ke(),1)});function ST(e){return typeof e=="object"?e.key:e}function wT(e,t){let i=e.length;return new Proxy(e,{get(n,s,r){if(typeof s=="string"){let a=s.charCodeAt(0);if(a>=48&&a<=57){let o=+s;if(Number.isInteger(o)&&o>=0&&o{});function ja(e,t,i){let n=i.initialDeps??[],s,r=!0;function a(){var o;let c=0,u=e();if(!(u.length!==n.length||u.some((f,p)=>n[p]!==f)))return s;n=u;let d=0;return s=t(...u),i?.onChange&&!(r&&i.skipInitialOnChange)&&i.onChange(s),r=!1,s}return a.updateDeps=o=>{n=o},a}function uv(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var tr,xT,hv=le(()=>{tr=(e,t)=>Math.abs(e-t)<1.01,xT=(e,t,i)=>{let n;return Object.assign(function(...s){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,s),i)},{cancel:()=>{e.clearTimeout(n)}})}});function CT({offset:e,isScrolling:t,elementMax:i,holdOffset:n,scrollOffset:s,pendingWrite:r,clampedMaxAtWrite:a}){var o;return t&&r===null&&e===s?"spurious":r!==null&&Math.abs(e-r.target)<1.5?"readBack":r!==null&&!r.smooth&&i!==null&&r.target>i+n+.5&&Math.abs(e-(i+n))<1.5||r!==null&&!r.smooth&&((o=r.lowMaxes)!=null&&o.some(l=>Math.abs(e-l)<1.5))?"clampedReadBack":a!==null&&Math.abs(e-a)<1.5?"clampedEcho":"external"}function kT({kind:e,offset:t,command:i,target:n}){return e!=="spurious"&&e!=="readBack"&&e!=="clampedReadBack"&&i?.index!=null&&i.phase!=="queued"&&!ez(i.phase)&&!tr(t,i.lastTargetOffset)&&!tr(t,n())&&e!=="clampedEcho"}function TT(e){let t=e[e.length-1];if(t===void 0)return!1;let i=e.length-2;for(;i>=0&&t.t-e[i].t=0&&n.t-e[s].t=0&&Math.abs(a)>=2*Math.abs(o)&&Math.abs(a)-Math.abs(o)>=.8}function NT(e){let t=e[e.length-1];if(t===void 0)return!1;let i=e.length-2;for(;i>=0&&t.t-e[i].t=.05}var ez,dv,AT=le(()=>{hv();ez=e=>e==="smooth"||e==="smoothFinishing";dv=40});var nu,su,fv,tz,MT,Nl,cf,RT=le(()=>{su=()=>{if(nu!==void 0)return nu;if(typeof navigator>"u")return nu=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return nu=!0;let e=navigator.maxTouchPoints;return nu=navigator.platform==="MacIntel"&&e!==void 0&&e>0},tz=()=>fv!==void 0?fv:fv=su()&&typeof CSS<"u"&&typeof CSS.supports=="function"&&CSS.supports("overflow-anchor: auto"),MT=()=>!su()||tz(),Nl={capture:!0,passive:!0},cf=class{constructor(t){this.host=t,this._touch=null,this.inMotion=()=>this._touch!==null&&this._touch.phase!=="lateFling",this.dragging=()=>{var i;return((i=this._touch)==null?void 0:i.phase)==="down"&&this._touch.moved},this.tail=()=>{var i;return((i=this._touch)==null?void 0:i.phase)==="tail"?this._touch.moved?"fling":"tap":null},this.onScroll=({isScrolling:i,ownReadBack:n,moved:s,external:r})=>{var a,o,l;return i&&((a=this._touch)==null?void 0:a.phase)==="tail"?this._openTail(this._touch.moved||!n,!1):((o=this._touch)==null?void 0:o.phase)==="lateFling"&&(this.host.now()>this._touch.until?this._touch=null:r&&i&&s&&this._openTail(!0,!1)),!n&&i&&s&&((l=this._touch)==null?void 0:l.phase)==="down"?(this._touch.moved=!0,!0):!1},this.touchStart=()=>{this.end(),this._touch={phase:"down",moved:!1}},this.touchEnd=()=>{var i;let n=((i=this._touch)==null?void 0:i.phase)==="down"&&this._touch.moved;this.end(),this._openTail(n,n)},this.end=()=>{var i;let n=this.host.getWindow();((i=this._touch)==null?void 0:i.phase)==="tail"&&n!=null&&n.clearTimeout(this._touch.timerId),this._touch=null},this.listen=i=>{let n=()=>this.touchStart(),s=()=>this.touchEnd();return i.addEventListener("touchstart",n,Nl),i.addEventListener("touchend",s,Nl),i.addEventListener("touchcancel",s,Nl),()=>{i.removeEventListener("touchstart",n,Nl),i.removeEventListener("touchend",s,Nl),i.removeEventListener("touchcancel",s,Nl),this.end()}},this._openTail=(i,n)=>{let s=this.host.getWindow();if(s==null)return;this.end();let r={phase:"tail",moved:i,awaitingFling:n,timerId:s.setTimeout(()=>{if(this.host.tailStillMoving()){this._openTail(r.moved,r.awaitingFling);return}this._touch=r.awaitingFling?{phase:"lateFling",until:this.host.now()+1e3}:null,this.host.onTailClosed()},150)};this._touch=r}}get touch(){return this._touch}}});function lz(e,t,i,n){if(t===0)return!1;let s=n(0),r=new Set,a=0;for(;a=t)return!1;for(let l=0;li)t=s-1;else return s}return n>0?n-1:0}function uz(e,t,i,n,s){let r=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:r};if(n===1&&s!==null){let c=cz(s,r,i),u=c,h=i+t;for(;ue[c].start,i),l=o;if(n===1)for(;l1){let c=Array(n).fill(0);for(;lh=0&&u.some(h=>h>=i);){let h=e[o];u[h.lane]=h.start,o--}o=Math.max(0,o-o%n),l=Math.min(r,l+(n-1-l%n))}return{startIndex:o,endIndex:l}}var OT,BT,iz,nz,IT,DT,sz,rz,zT,az,oz,PT,LT,ru,uf,UT,pv=le(()=>{ET();hv();AT();RT();OT=e=>{let{clientWidth:t,clientHeight:i}=e;return{width:t,height:i}},BT=e=>{let t=new Set;return{schedule:i=>{let n=e.requestAnimationFrame(()=>{t.delete(n),i()});t.add(n)},cancel:()=>{t.forEach(i=>e.cancelAnimationFrame(i)),t.clear()}}},iz=e=>e,nz=e=>{let t=e.overscan*Math.max(e.lanes??1,1),i=Math.max(e.startIndex-t,0),s=Math.min(e.endIndex+t,e.count-1)-i+1,r=new Array(s);for(let a=0;a{let i=e.scrollElement;if(!i)return;let n=e.targetWindow;if(!n)return;let s=o=>{let{width:l,height:c}=o;t({width:Math.round(l),height:Math.round(c)})};if(s(OT(i)),!n.ResizeObserver)return()=>{};let r=BT(n),a=new n.ResizeObserver(()=>{let o=()=>{s(OT(i))};e.options.useAnimationFrameWithResizeObserver?r.schedule(o):o()});return a.observe(i,{box:"content-box"}),()=>{a.unobserve(i),r.cancel()}},DT={passive:!0},sz=typeof window>"u"?!0:"onscrollend"in window,rz=(e,t,i)=>{let n=e.scrollElement;if(!n)return;let s=e.targetWindow;if(!s)return;let r=e.options.useScrollendEvent&&sz,a=0,o=r?null:xT(s,()=>t(i(n),!1),e.options.isScrollingResetDelay),l=h=>()=>{a=i(n),o?.(),t(a,h)},c=l(!0),u=l(!1);return n.addEventListener("scroll",c,DT),r&&n.addEventListener("scrollend",u,DT),()=>{n.removeEventListener("scroll",c),r&&n.removeEventListener("scrollend",u),o?.cancel()}},zT=(e,t)=>rz(e,t,i=>{let{horizontal:n,isRtl:s}=e.options;return n?i.scrollLeft*(s&&-1||1):i.scrollTop}),az=(e,t,i)=>{if(i.options.useCachedMeasurements){let n=i.indexFromElement(e),s=i.options.getItemKey(n);return i.itemSizeCache.get(s)??i.options.estimateSize(n)}if(t?.borderBoxSize){let n=t.borderBoxSize[0];if(n)return Math.round(n[i.options.horizontal?"inlineSize":"blockSize"])}if(!t){let n=i.indexFromElement(e),s=i.options.getItemKey(n),r=i.itemSizeCache.get(s);if(r!==void 0)return r}return e[i.options.horizontal?"offsetWidth":"offsetHeight"]},oz=(e,{adjustments:t=0,behavior:i},n)=>{var s,r;(r=(s=n.scrollElement)==null?void 0:s.scrollTo)==null||r.call(s,{[n.options.horizontal?"left":"top"]:e+t,behavior:i})},PT=oz,LT=(e,t)=>e==="smooth"?t?"smoothLanded":"smooth":"instant",ru=e=>e?.phase==="smooth"||e?.phase==="smoothLanded";uf=class{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this._holdOffset=0,this._reportedOverscroll=!1,this._iosGesture=new cf({getWindow:()=>this.targetWindow,now:()=>this.now(),tailStillMoving:()=>{let i=this.scrollState;if(i?.phase!=="queued"||this.pendingWrite!==null)return!1;let n=this._readElementOffset();return n===null||this._lastElementOffset===null||Math.abs(n-this._lastElementOffset)<1?!1:(this._lastElementOffset=n,i.samples=[...i.samples??[],{t:this.now(),offset:n}],!0)},onTailClosed:()=>{let i=this.scrollState;i?.phase==="queued"&&NT(i.samples??[])&&(this.scrollState=null),this._flushHoldIfReady(!0),this._writeAwaitingCommand(),this._retryClampedAdjustment()}}),this._lastElementOffset=null,this.pendingWrite=null,this._clampedAdjustment=null,this.elementsCache=new Map,this._resizeBatch=null,this.now=()=>{var i,n,s;return((s=(n=(i=this.targetWindow)==null?void 0:i.performance)==null?void 0:n.now)==null?void 0:s.call(n))??Date.now()},this.observer=(()=>{let i=null,n=null,s=!1,r=!1,a=new Set,o=()=>{if(i)return i;let c=this.targetWindow;if(!c||!c.ResizeObserver)return null;let u=n=BT(c);return i=new c.ResizeObserver(h=>{let d=()=>{let f={sync:!1};this._resizeBatch=f;try{h.forEach(l)}finally{this._resizeBatch=null,f.notify&&(this.notify(f.sync),this._noteClampMax(),this._flushHoldIfReady(!0),this._retryClampedAdjustment(),this.measureElement(null))}};if(this.options.useAnimationFrameWithResizeObserver)u.schedule(d);else{s=!0;try{d()}finally{s=!1}}})},l=c=>{let u=c.target,h=this.indexFromElement(u);if(!u.isConnected){this.observer.unobserve(u);for(let[d,f]of this.elementsCache)if(f===u){this.elementsCache.delete(d);break}return}this.isIndexInRange(h)&&this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(u,c,this))};return{disconnect:()=>{var c;(c=o())==null||c.disconnect(),n?.cancel(),a.clear(),r=!1,i=null,n=null},observe:c=>{let u=o();if(u){if(!s){u.observe(c,{box:"border-box"});return}a.add(c),r||(r=!0,n?.schedule(()=>{r=!1,a.forEach(h=>{h.isConnected&&i?.observe(h,{box:"border-box"})}),a.clear()}))}},unobserve:c=>{var u;a.delete(c),(u=o())==null||u.unobserve(c)}}})(),this.range=null,this.setOptions=i=>{var n;let s={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:iz,rangeExtractor:nz,onChange:()=>{},measureElement:az,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(let u in i){let h=i[u];h!==void 0&&(s[u]=h)}let r=this.options,a=null,o=null,l=!1;if(r!==void 0&&r.enabled&&s.enabled&&s.anchorTo==="end"&&this.scrollElement!==null){let u=r.count,h=s.count,d=this.getMeasurements(),f=((n=this._singleLaneMeasurements)==null?void 0:n.items)??d,p=v=>ST(f[v]),_=u>0?p(0):null,w=u>0?p(u-1):null;if(h!==u||u>0&&h>0&&(s.getItemKey(0)!==_||s.getItemKey(h-1)!==w)){l=!0;let v=u>0?this.getVirtualItemForOffset(this.getScrollOffset())??d[0]:null;v&&(a=[v.key,this.getScrollOffset()-v.start]);let S=s.followOnAppend===!0?"auto":s.followOnAppend||null;S&&h>0&&this.isAtEnd(r.scrollEndThreshold)&&(u===0||s.getItemKey(h-1)!==w)&&(h>u||lz(u,h,p,s.getItemKey))&&(o=S)}}this.options=s,l&&(this.pendingMin=0,this.itemSizeCacheVersion++);let c=null;if(a&&this.scrollOffset!==null&&!this._awaitingCommandReadBack()){let[u,h]=a,d=this.getMeasurements(),{count:f,getItemKey:p}=this.options,_=0;for(;_{var n,s;(s=(n=this.options).onChange)==null||s.call(n,this,i)},this.maybeNotify=ja(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),i=>{this.notify(i)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{var i;this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,(i=this._momentumStop)==null||i.restore(),this._momentumStop=null,this.isScrolling=!1,this.scrollDirection=null,this._holdOffset=0,this._reportedOverscroll=!1,this._clampedAdjustment=null,this.pendingWrite=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var i;let n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((i=this.scrollElement)==null?void 0:i.window)??null,this.elementsCache.forEach(r=>{this.observer.observe(r)}),this.unsubs.push(this.options.observeElementRect(this,r=>{this.scrollRect=r,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(r,a)=>{var o,l,c,u;let h=a?this._elementMaxScrollOffset():null,d=this._reportedOverscroll;this._reportedOverscroll=r<0||h!==null&&r>h+1;let f=r;this._lastElementOffset=f,r=this._toLayoutOffset(r);let p=this._classifyScrollEvent(r,a,h);if(p==="spurious")return;p==="readBack"?r=this.pendingWrite.target:p==="clampedReadBack"&&((o=this.scrollState)==null?void 0:o.index)!=null&&rthis.getScrollStateTarget(this.scrollState)})&&(this.scrollState=null),this.pendingWrite=null,this._clampedAdjustment!==null&&Math.abs(r-this._clampedAdjustment.maxAtWrite)>=1.5&&(this._clampedAdjustment=null);let _=this.getScrollOffset(),w=this.scrollDirection;this.scrollDirection=a?_===r?this.scrollDirection:_m-v.t<=200),{t:m,offset:f}],(w!==null&&this.scrollDirection!==w||TT(g.samples))&&(this.scrollState=null)}this._iosGesture.onScroll({isScrolling:a,ownReadBack:p==="readBack",moved:r!==_,external:p==="external"&&((l=this.scrollState)==null?void 0:l.phase)!=="smooth"&&((c=this.scrollState)==null?void 0:c.phase)!=="smoothFinishing"})&&((u=this.scrollState)==null?void 0:u.phase)==="queued"&&(this.scrollState=null),this._flushHoldIfReady(!0),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement&&this.unsubs.push(this._iosGesture.listen(this.scrollElement)),this._scrollToOffset(this.getScrollOffset())}this._noteClampMax();let s=this.pendingScrollAnchor;this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled&&(s.kind==="anchor"?this._canWriteScroll()?ru(this.scrollState)&&!tr(this.getScrollOffset()-s.delta,this.scrollState.lastTargetOffset)||(this._followOffsetTarget(s.delta),this._scrollToOffset(this.getScrollOffset())):(this._holdOffset+=s.delta,this._followOffsetTarget(s.delta),this.notify(!1)):this.scrollToEnd({behavior:s.behavior})),this._flushHoldIfReady(!1),this._retryClampedAdjustment()},this._classifyScrollEvent=(i,n,s)=>{var r;return CT({offset:i,isScrolling:n,elementMax:s,holdOffset:this._holdOffset,scrollOffset:this.scrollOffset,pendingWrite:this.pendingWrite,clampedMaxAtWrite:((r=this._clampedAdjustment)==null?void 0:r.maxAtWrite)??null})},this._retryClampedAdjustment=()=>{if(this._clampedAdjustment===null||!this.scrollElement||!this.options.enabled||!this._canWriteScroll())return;let{target:i,maxAtWrite:n}=this._clampedAdjustment,s=this.getMaxScrollOffset();s>n+.5&&(this._clampedAdjustment=i>s+.5?{target:i,maxAtWrite:s}:null,this._scrollToOffset(i))},this._writeAwaitingCommand=()=>{let i=this.scrollState;if(i===null||i.phase!=="queued")return;let{behavior:n}=i;this.getMeasurements();let s=this.getScrollStateTarget(i);i.lastTargetOffset=s,this._clampedAdjustment=null,i.phase=LT(n,i.index!=null&&tr(s,this.getScrollOffset())),this._scrollToOffset(s,{behavior:n}),this.scheduleScrollReconcile()},this._readElementOffset=()=>{let i=this.scrollElement;if(i==null)return null;let{horizontal:n,isRtl:s}=this.options;return typeof i.scrollTop=="number"?n?i.scrollLeft*(s&&-1||1):i.scrollTop:typeof i.scrollY=="number"?n?i.scrollX:i.scrollY:null},this._canWriteScroll=()=>!(su()&&this._iosGesture.inMotion())&&!this._reportedOverscroll,this._flushHoldIfReady=i=>{var n;if(this._holdOffset===0||!this.scrollElement||!this.options.enabled||!this._canWriteScroll()||((n=this.scrollState)==null?void 0:n.phase)==="smooth")return;this._holdOffset=0,this.scrollOffset!==null&&this.scrollOffset<0&&(this.scrollOffset=0),this.notify(i);let s=this.getCommandWrittenOffset()??this.getScrollOffset();this._clampedAdjustment=this._clampedBy(s),this._scrollToOffset(s)},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=ja(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(i,n,s,r,a,o,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMin=null,{count:i,paddingStart:n,scrollMargin:s,getItemKey:r,enabled:a,lanes:o,laneAssignmentMode:l,gap:c}),{key:!1}),this.isIndexInRange=i=>i>=0&&i[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:i,paddingStart:n,scrollMargin:s,getItemKey:r,enabled:a,lanes:o,laneAssignmentMode:l,gap:c},u)=>{var h;let d=this.itemSizeCache;if(!a)return this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>i)for(let m of this.laneAssignments.keys())m>=i&&this.laneAssignments.delete(m);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(m=>{this.itemSizeCache.set(m.key,m.size)}));let f=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===i&&(this.lanesSettling=!1),o===1){let m=i*2,v=(h=this._singleLaneMeasurements)==null?void 0:h.flat;if(!v||v.length0&&O.set(v.subarray(0,f*2)),v=O}let S=f===0?new Array(i):this._singleLaneMeasurements.items.slice(),k;if(f===0)k=n+s;else{let O=f-1;k=v[O*2]+v[O*2+1]+c}for(let O=f;O1){k=S;let P=_[k],M=P!==void 0?p[P]:void 0;A=M?M.end+c:n+s}else if(g===o){let P=0,M=w[0],B=_[0];for(let E=1;Ethis.options.debug}),this.calculateRange=ja(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(i,n,s,r)=>i.length===0||n===0?(this.range=null,null):(this.range=uz(i,n,s,r,r===1&&this._singleLaneMeasurements!==null?this._singleLaneMeasurements.flat:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ja(()=>{let i=null,n=null,s=this.calculateRange();return s&&(i=s.startIndex,n=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,i,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,i,n,this.options.lanes]},(i,n,s,r,a,o)=>r===null||a===null?[]:i({startIndex:r,endIndex:a,overscan:n,count:s,lanes:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=i=>{let n=this.options.indexAttribute,s=i.getAttribute(n);return s?parseInt(s,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=i=>{var n;if(!ru(this.scrollState))return!0;let s=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(s!==void 0&&this.range){let r=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,s-r),o=Math.min(this.options.count-1,s+r);return i>=a&&i<=o}return!0},this.measureElement=i=>{if(!i){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}let n=this.indexFromElement(i);if(!this.isIndexInRange(n))return;let s=this.options.getItemKey(n),r=this.elementsCache.get(s);r!==i&&(r&&this.observer.unobserve(r),this.observer.observe(i),this.elementsCache.set(s,i)),i.isConnected&&(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(i,void 0,this))},this.resizeItem=(i,n)=>{var s,r,a;if(!this.isIndexInRange(i))return;(s=this._resizeBatch)!=null&&s.sync&&this.getMeasurements();let o,l,c,u=(r=this._singleLaneMeasurements)==null?void 0:r.flat;if(this.options.lanes===1&&u!=null)c=this.options.getItemKey(i),l=u[i*2],o=u[i*2+1];else{let f=this.measurementsCache[i];if(!f)return;c=f.key,l=f.start,o=f.size}let h=this.itemSizeCache.get(c)??o,d=n-h;if(d!==0){let f=this.options.anchorTo==="end"&&!ru(this.scrollState)&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,p=f?this._getLayoutTotalSize():0,_=this.getScrollOffset(),g=!this.itemSizeCache.has(c)?l<_:l+h<=_&&this.scrollDirection!=="backward",m=!ru(this.scrollState)&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[i]??{index:i,key:c,start:l,size:o,end:l+o,lane:0},d,this):g);(this.pendingMin===null||i[this.getVirtualIndexes(),this.getMeasurements(),this._holdOffset],(i,n,s)=>{let r=[];for(let a=0,o=i.length;athis.options.debug}),this.getVirtualItemForOffset=i=>{var n;let s=this.getMeasurements();if(s.length===0)return;let r=(n=this._singleLaneMeasurements)==null?void 0:n.flat,a=this.options.lanes===1&&r!=null,o=UT(0,s.length-1,a?l=>r[l*2]:l=>uv(s[l]).start,i);return uv(s[o])},this._noteClampMax=()=>{if(!this._awaitingCommandReadBack())return;let i=this._elementMaxScrollOffset();if(i===null)return;let n=this.pendingWrite,s=Math.max(i,0)+this._holdOffset;if(s>=n.target)return;let r=n.lowMaxes??(n.lowMaxes=[]);r[r.length-1]!==s&&r.push(s)},this.getMaxScrollOffset=()=>(this._elementMaxScrollOffset()??0)+this._holdOffset,this._toLayoutOffset=i=>{var n;let s=i+this._holdOffset;return((n=this.pendingScrollAnchor)==null?void 0:n.kind)==="anchor"&&(s+=this.pendingScrollAnchor.delta),s},this._elementMaxScrollOffset=()=>{let i=this.scrollElement;if(i===null)return null;if("scrollHeight"in i)return this.options.horizontal?i.scrollWidth-i.clientWidth:i.scrollHeight-i.clientHeight;if("document"in i){let n=i.document.documentElement;return this.options.horizontal?n.scrollWidth-i.innerWidth:n.scrollHeight-i.innerHeight}return null},this._momentumStop=null,this._stopMomentum=i=>{let n=this.scrollElement,s=this.targetWindow;if(n===null||s===null)return;let r="document"in n?n.document.scrollingElement:n;if(!r?.style)return;if(this._momentumStop){this._momentumStop.done=i;return}let{style:a}=r,o=this.options.horizontal?"overflow-x":"overflow-y",l=a.getPropertyValue(o),c=a.getPropertyPriority(o),u=()=>this.options.horizontal?r.clientHeight:r.clientWidth,h=u();if(a.setProperty(o,"hidden","important"),u()!==h){a.setProperty(o,l,c);return}let d={restore:()=>a.getPropertyValue(o)!=="hidden"||a.getPropertyPriority(o)!=="important"?!1:(a.setProperty(o,l,c),!0),done:i};this._momentumStop=d,s.requestAnimationFrame(()=>s.requestAnimationFrame(()=>{this._momentumStop===d&&(this._momentumStop=null,d.restore()&&d.done())}))},this._clampedBy=i=>{let n=this._elementMaxScrollOffset();if(n===null)return null;let s=n+this._holdOffset;return i>s+.5?{target:i,maxAtWrite:s}:null},this.getVirtualDistanceFromEnd=()=>Math.max(this._getLayoutTotalSize()+this.options.scrollMargin-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(i=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=i,this.getOffsetForAlignment=(i,n,s=0)=>{if(!this.scrollElement)return 0;let r=this.getSize(),a=this.getScrollOffset();n==="auto"&&(n=i>=a+r?"end":"start"),n==="center"?i+=(s-r)/2:n==="end"&&(i-=r);let o=this.getMaxScrollOffset();return Math.max(Math.min(o,i),0)},this.getOffsetForIndex=(i,n="auto")=>{i=Math.max(0,Math.min(i,this.options.count-1));let s=this.getSize(),r=this.getScrollOffset(),a=this.measurementsCache[i];if(!a)return;if(n==="auto")if(a.end>=r+s-this.options.scrollPaddingEnd)n="end";else if(a.start<=r+this.options.scrollPaddingStart)n="start";else return[r,n];if(n==="end"&&i===this.options.count-1){let l=this.getMaxScrollOffset(),c=l-this.options.paddingEnd+this.options.scrollPaddingEnd;return[Math.max(Math.min(c,l),0),n]}let o=n==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,n,a.size),n]},this.scrollToOffset=(i,{align:n="start",behavior:s="auto"}={})=>{this._startScroll({index:null,align:n},this.getOffsetForAlignment(i,n),s,"absolute")},this.scrollToIndex=(i,{align:n="auto",behavior:s="auto"}={})=>{i=Math.max(0,Math.min(i,this.options.count-1));let r=this.getOffsetForIndex(i,n);if(!r)return;let[a,o]=r;this._startScroll({index:i,align:o},a,s,"absolute")},this.scrollBy=(i,{behavior:n="auto"}={})=>{let s=this.getOffsetForAlignment((this.getCommandWrittenOffset()??this.getScrollOffset())+i,"start");this._startScroll({index:null,align:"start"},s,n,"relative")},this.scrollToEnd=({behavior:i="auto"}={})=>{if(this.options.count>0){this._startScroll({index:this.options.count-1,align:"end",toEnd:!0},Math.max(this.getMaxScrollOffset(),0),i,"absolute");return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:i})},this.cancelScroll=()=>{this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null},this.getTotalSize=()=>Math.max(this._getLayoutTotalSize()-this._holdOffset,0),this._getLayoutTotalSize=()=>{var i,n;let s=this.getMeasurements(),r;if(s.length===0)r=this.options.paddingStart;else if(this.options.lanes===1){let a=s.length-1,o=(i=this._singleLaneMeasurements)==null?void 0:i.flat;o!=null?r=o[a*2]+o[a*2+1]:r=((n=s[a])==null?void 0:n.end)??0}else{let a=Array(this.options.lanes).fill(null),o=s.length-1;for(;o>=0&&a.some(l=>l===null);){let l=s[o];a[l.lane]===null&&(a[l.lane]=l.end),o--}r=Math.max(...a.filter(l=>l!==null))}return Math.max(r-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let i=[];if(this.itemSizeCache.size===0)return i;let n=this.getMeasurements();for(let s of n)s&&this.itemSizeCache.has(s.key)&&i.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return i},this._scrollToOffset=(i,{adjustments:n,behavior:s}={})=>{let r={target:i+(n??0),smooth:s==="smooth"};return this.pendingWrite=r,this.options.scrollToFn(i-this._holdOffset,{behavior:s,adjustments:n},this),r},this.getCommandWrittenOffset=()=>this.scrollState!==null&&this.pendingWrite!==null&&!this.pendingWrite.smooth?this.pendingWrite.target:null,this._awaitingCommandReadBack=()=>{let i=this.getCommandWrittenOffset();return!(su()&&this._iosGesture.dragging())&&i!==null&&!tr(i,this.getScrollOffset())},this._followOffsetTarget=i=>{this.scrollState!==null&&this.scrollState.index==null&&(this.scrollState.lastTargetOffset+=i)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}get scrollAdjustments(){return 0}applyScrollAdjustment(t,i){if(t===0)return!1;if(this._followOffsetTarget(t),this._canWriteScroll()){let n=this.getScrollOffset();this._clampedAdjustment=this._clampedBy(n+t);let s=this._scrollToOffset(n,{adjustments:t,behavior:i});return this.scrollOffset!==null&&(this.pendingWrite===s&&(this.scrollOffset+=t),this.scrollOffset<0&&(this.scrollOffset=0)),!0}else return this._holdOffset+=t,this.scrollOffset!==null&&(this.scrollOffset+=t),!0}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}getScrollStateTarget(t){let i=t.toEnd?[Math.max(this.getMaxScrollOffset(),0)]:t.index!=null?this.getOffsetForIndex(t.index,t.align):void 0;return i?i[0]:t.lastTargetOffset}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}if(this.scrollState.phase==="queued"){this.scheduleScrollReconcile();return}this.getMeasurements();let n=this.getScrollStateTarget(this.scrollState),s=this.scrollState.index==null?1:this.options.useAnimationFrameWithResizeObserver?3:2,r=n!==this.scrollState.lastTargetOffset;if(!r&&tr(n,this.getScrollOffset())){if(this.scrollState.phase==="smooth"?this.scrollState.phase="smoothLanded":this.scrollState.phase==="smoothFinishing"&&(this.scrollState.phase="instant"),this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.getScrollOffset()!==n&&this._scrollToOffset(n,{behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,r){let a=this.getSize()||600,o=Math.abs(n-this.getScrollOffset()),l=ru(this.scrollState)&&o>a;this.scrollState.lastTargetOffset=n,l?this.scrollState.phase="smooth":this.scrollState.phase==="smooth"?this.scrollState.phase="smoothFinishing":this.scrollState.phase==="smoothLanded"&&(this.scrollState.phase="instant"),this._scrollToOffset(n,{behavior:l?"smooth":"auto"})}this.scheduleScrollReconcile()}_startScroll(t,i,n,s){this.pendingScrollAnchor=null,this._clampedAdjustment=null;let r=this._iosGesture.tail();if(s==="absolute"&&r!==null){if(r==="fling"&&MT()){this._stopMomentum(()=>{let a=this.scrollState;a?.phase!=="queued"||this._iosGesture.tail()!=="fling"||this._reportedOverscroll||(this._iosGesture.end(),this._flushHoldIfReady(!0),this._writeAwaitingCommand())}),this.scrollState={...t,startedAt:this.now(),lastTargetOffset:i,stableFrames:0,phase:"queued",behavior:n,samples:[]},this.scheduleScrollReconcile();return}this._iosGesture.end()}this.scrollState={...t,startedAt:this.now(),lastTargetOffset:i,stableFrames:0,behavior:n,phase:LT(n,t.index!=null&&tr(i,this.getScrollOffset()))},this._scrollToOffset(i,{behavior:n}),this.scheduleScrollReconcile()}},UT=(e,t,i,n)=>{for(;e<=t;){let s=(e+t)/2|0,r=i(s);if(rn)t=s-1;else return s}return e>0?e-1:0}});function hz({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:i="transform",...n}){let s=Qn.useReducer(d=>d+1,0)[1],r=Qn.useRef({enabled:t,mode:i,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});r.current.enabled=t,r.current.mode=i;let a=Qn.useRef(!1),o=d=>{let f=r.current;if(!f.enabled||!f.container)return;let p=d.getTotalSize();if(p!==f.lastSize){f.lastSize=p;let _=d.options.horizontal?"width":"height";f.container.style[_]=`${p}px`}},l=(d,f,p)=>{let _=r.current,w=!!d.options.horizontal,g=f.start-d.options.scrollMargin;_.lastPositions.get(p)!==g&&(_.lastPositions.set(p,g),_.mode==="transform"?p.style.transform=w?`translate3d(${g}px, 0, 0)`:`translate3d(0, ${g}px, 0)`:p.style[w?"left":"top"]=`${g}px`)},c=d=>{let f=r.current;if(!(!f.enabled||!f.container)){o(d);for(let p of d.getVirtualItems()){let _=d.elementsCache.get(p.key);_&&l(d,p,_)}}},u={...n,onChange:(d,f)=>{var p;let _=r.current,w=!0;if(_.enabled){c(d);let g=d.range,m=_.prevRange;w=!m||m.isScrolling!==d.isScrolling||m.startIndex!==g?.startIndex||m.endIndex!==g?.endIndex,w&&(_.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:d.isScrolling}:null)}w&&(e&&f&&!a.current?(0,HT.flushSync)(s):s()),(p=n.onChange)==null||p.call(n,d,f)}},[h]=Qn.useState(()=>{let d=new uf(u),f=d.measureElement;return d.measureElement=p=>{a.current=!0;try{f(p)}finally{a.current=!1}let _=r.current;if(p!==null&&_.enabled&&_.container){let w=d.measurementsCache[d.indexFromElement(p)];w&&l(d,w,p)}},Object.assign(d,{containerRef:p=>{let _=r.current;_.container=p,_.lastSize=null,p!==null&&c(d)}})});return h.setOptions(u),mv(()=>h._didMount(),[]),mv(()=>(o(h),h._willUpdate())),mv(()=>{c(h)}),h}function FT(e){return hz({observeElementRect:IT,observeElementOffset:zT,scrollToFn:PT,...e})}var Qn,HT,mv,qT=le(()=>{Qn=ae(Nt(),1),HT=ae(oa(),1);pv();pv();mv=typeof document<"u"?Qn.useLayoutEffect:Qn.useEffect});function Al(){return{items:[],seenSeq:new Set,byItemId:new Map,toolLoc:new Map,openGroup:null,reqLoc:new Map,turnUsage:new Map,lastUserIdx:new Map,turnStart:new Map}}function ir(e){e.openGroup=null}function KT(e,t,i,n){let s=e.byItemId.get(t);if(s){let o=e.items[s.idx];o.text+=n,o.streaming=!0;return}ir(e);let r=`${i}:${t}`,a=i==="assistant"?{kind:"assistant",key:r,itemId:t,text:n,streaming:!0}:{kind:"reasoning",key:r,itemId:t,text:n,streaming:!0};e.byItemId.set(t,{idx:e.items.length,field:i}),e.items.push(a)}function dz(e,t,i){let n=/^(.*):[ktx]\d+$/.exec(t);if(!n)return;let s=n[1]+":";for(let[r,a]of[...e.byItemId])a.field===i&&r.startsWith(s)&&r!==t&&(e.items[a.idx]={kind:"gone",key:`gone:${r}`},e.byItemId.delete(r))}function WT(e,t,i,n){dz(e,t,i);let s=e.byItemId.get(t);if(s){let o=e.items[s.idx];o.text=n,o.streaming=!1;return}ir(e);let r=`${i}:${t}`,a=i==="assistant"?{kind:"assistant",key:r,itemId:t,text:n,streaming:!1}:{kind:"reasoning",key:r,itemId:t,text:n,streaming:!1};e.byItemId.set(t,{idx:e.items.length,field:i}),e.items.push(a)}function fz(e,t){let i=e.toolLoc.get(t.itemId);if(i){let a=e.items[i.group];if(a?.kind==="toolgroup"){let o=a.steps[i.step];a.steps[i.step]={...o,kind:t.kind==="other"&&o.kind!=="other"?o.kind:t.kind,title:t.title||o.title,status:t.status,input:t.input??o.input,detail:t.detail??o.detail,output:t.output??o.output,exitCode:t.exitCode??o.exitCode,durationMs:t.durationMs??o.durationMs}}return}let n={itemId:t.itemId,kind:t.kind,title:t.title,status:t.status,input:t.input,detail:t.detail,output:t.output,exitCode:t.exitCode,durationMs:t.durationMs},s=e.openGroup;(s==null||e.items[s]?.kind!=="toolgroup")&&(s=e.items.length,e.items.push({kind:"toolgroup",key:`tg:${t.itemId}`,steps:[]}),e.openGroup=s);let r=e.items[s];e.toolLoc.set(t.itemId,{group:s,step:r.steps.length}),r.steps.push(n)}function hf(e,t){if(t.seq!=null&&t.seq>0){if(e.seenSeq.has(t.seq))return;e.seenSeq.add(t.seq)}switch(t.type){case"user_message":ir(e),e.lastUserIdx.set(t.turnId??"",e.items.length),e.items.push({kind:"user",key:`u:${t.seq}`,text:t.text,attachments:t.attachments,steered:t.steered,ts:t.ts});return;case"assistant_delta":KT(e,t.itemId,"assistant",t.text);return;case"reasoning_delta":KT(e,t.itemId,"reasoning",t.text);return;case"assistant_message":WT(e,t.itemId,"assistant",t.text);return;case"reasoning":WT(e,t.itemId,"reasoning",t.text);return;case"tool_output_delta":{let i=e.toolLoc.get(t.itemId);if(i){let n=e.items[i.group];if(n?.kind==="toolgroup"){let s=n.steps[i.step];s.output=(s.output??"")+t.text}}return}case"tool_call":fz(e,t);return;case"plan":ir(e),e.items.push({kind:"plan",key:`plan:${t.itemId}`,itemId:t.itemId,markdown:t.markdown});return;case"todo":ir(e),e.items.push({kind:"todo",key:`todo:${t.seq}`,items:t.items});return;case"permission_request":ir(e),e.reqLoc.set(t.requestId,e.items.length),e.items.push({kind:"permission",key:`perm:${t.requestId}`,requestId:t.requestId,title:t.title,kindStr:t.kind,detail:t.detail,options:t.options,status:"pending"});return;case"permission_resolved":{let i=e.reqLoc.get(t.requestId),n=i!=null?e.items[i]:null;n?.kind==="permission"&&(n.status=t.cancelled?"cancelled":"resolved",n.choice=t.optionId);return}case"question":ir(e),e.reqLoc.set(t.requestId,e.items.length),e.items.push({kind:"question",key:`q:${t.requestId}`,requestId:t.requestId,questions:t.questions,status:"pending"});return;case"question_answered":{let i=e.reqLoc.get(t.requestId),n=i!=null?e.items[i]:null;n?.kind==="question"&&(n.status="answered",n.answers=t.answers);return}case"usage":{let i=t.turnId??"",n=e.turnUsage.get(i)??{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0};n.inputTokens+=t.inputTokens,n.outputTokens+=t.outputTokens,n.cacheReadTokens+=t.cacheReadTokens,n.costUsd+=t.costUsd,e.turnUsage.set(i,n);return}case"notice":ir(e),e.items.push({kind:"notice",key:`n:${t.seq}`,level:t.level,message:t.message});return;case"turn_ended":ir(e),e.items.push({kind:"turnend",key:`te:${t.seq}`,status:t.status,durationMs:t.durationMs??(e.turnStart.has(t.turnId)?Math.max(0,t.ts-e.turnStart.get(t.turnId)):void 0),error:t.error,filesChanged:t.filesChanged,usage:e.turnUsage.get(t.turnId)});return;case"turn_started":e.turnStart.set(t.turnId,t.ts);return;case"status":return;default:return}}function $T(e,t={}){let i=Al();for(let r of e)hf(i,r);let n=t.runtimeStatus!=="running"&&t.runtimeStatus!=="initializing",s=null;for(let r of i.items){if(r.kind==="user"&&(s=r.text),n&&r.kind==="permission"&&r.status==="pending"&&(r.status="cancelled"),n&&r.kind==="question"&&r.status==="pending"&&(r.status="cancelled"),n&&r.kind==="toolgroup")for(let a of r.steps)a.status==="running"&&(a.status="failed");(r.kind==="assistant"||r.kind==="reasoning")&&n&&r.streaming&&(r.streaming=!1)}return{items:i.items,lastUserText:s}}var GT=le(()=>{});var jT={};fR(jT,{useTimeline:()=>Dn});function YT(){let e=Vr!=="running"&&Vr!=="initializing";for(let t of ks.items)if(e&&t.kind==="permission"&&t.status==="pending"&&(t.status="cancelled"),e&&t.kind==="question"&&t.status==="pending"&&(t.status="cancelled"),e&&(t.kind==="assistant"||t.kind==="reasoning")&&t.streaming&&(t.streaming=!1),e&&t.kind==="toolgroup")for(let i of t.steps)i.status==="running"&&(i.status="failed")}var ks,Va,Vr,df,Dn,Ml=le(()=>{ul();GT();Rn();ks=Al(),Va=0,Vr="idle",df=null;Dn=Ss((e,t)=>{let i=n=>{df?.(),df=te.subscribe(`thread:${n}`,(s,r)=>{let a=r;if(t().threadId===n){if(a.type==="event"&&a.event){let o=a.event;if(o.seq!=null&&o.seq>0){if(o.seq<=Va)return;Va=Math.max(Va,o.seq)}o.type==="user_message"&&e({lastUserText:o.text}),hf(ks,o);let l=ks.items.filter(c=>(c.kind==="permission"||c.kind==="question")&&c.status==="pending").map(c=>({requestId:c.requestId,kind:c.kind}));e({items:ks.items.slice(),pending:l});return}if(a.type==="status"&&a.status){Vr=a.status,YT(),e({status:Vr,items:ks.items.slice()});return}if(a.type==="queue"&&a.queue){e({queue:a.queue});return}if(a.type==="pending"&&a.pending){e({pending:a.pending});return}if(a.type==="commands"&&a.commands){e({slashCommands:a.commands});return}}},()=>Va)};return{threadId:null,status:"idle",items:[],queue:[],pending:[],lastUserText:null,error:null,slashCommands:[],open:n=>{t().threadId!==n&&(t().close(),e({threadId:n,status:"initializing",items:[],queue:[],pending:[],lastUserText:null,error:null,slashCommands:[]}),ks=Al(),Va=0,Vr="initializing",(async()=>{try{let s=await te.call("threads.get",{id:n});if(t().threadId!==n)return;Vr=s.runtimeStatus??s.meta.status;let r=$T(s.events,{runtimeStatus:Vr});ks=Al();for(let a of s.events)hf(ks,a);Va=Math.max(0,...s.events.map(a=>a.seq??0)),YT(),e({items:ks.items.slice(),status:Vr,queue:s.queue??[],pending:s.pending??[],lastUserText:r.lastUserText}),t().threadId===n&&i(n)}catch(s){t().threadId===n&&e({error:String(s?.message??s),status:"error"})}})())},close:()=>{df?.(),df=null,ks=Al(),Va=0,e({threadId:null,items:[],queue:[],pending:[],lastUserText:null,error:null,status:"idle",slashCommands:[]})}}})});var ff,VT=le(()=>{ff=class{constructor(t,i=2,n=8){de(this,"render",t);de(this,"minStep",i);de(this,"frac",n);de(this,"target","");de(this,"shown","");de(this,"raf",0);de(this,"running",!1);de(this,"tick",()=>{if(this.shown===this.target){this.running=!1;return}let t=this.target.length-this.shown.length,i=Math.max(this.minStep,Math.ceil(t/this.frac));this.shown=this.target.slice(0,this.shown.length+i),this.render(this.shown),this.raf=requestAnimationFrame(this.tick)})}push(t){this.target=t,this.shown.length>t.length&&(this.shown=t),this.running||(this.running=!0,this.tick())}flush(){this.shown=this.target,this.render(this.shown),this.running=!1,this.raf&&cancelAnimationFrame(this.raf)}stop(){this.running=!1,this.raf&&cancelAnimationFrame(this.raf)}}});function Rl(){let e=location.hash.startsWith("#")?location.hash.slice(1):location.hash;return new URLSearchParams(e).get("t")??""}var pf=le(()=>{});function pz(e){return e==="+"||e==="-"?e:" "}function XT(e){if(!Array.isArray(e))return[];let t=[];for(let i of e){if(!i||typeof i!="object")continue;let n=i,s=[];for(let a of Array.isArray(n.lines)?n.lines:[]){if(!a||typeof a!="object")continue;let o=typeof a.text=="string"?a.text:typeof a.s=="string"?a.s:"";s.push({t:pz(a.t),text:o})}let r=typeof n.head=="string"?n.head:void 0;r===void 0&&Number.isInteger(n.oldStart)&&Number.isInteger(n.newStart)&&(r=`@@ -${n.oldStart} +${n.newStart} @@`),t.push({head:r,lines:s})}return t}var ZT=le(()=>{});function JT(e){return`/attachments/${e}?t=${QT()}`}function mz({it:e,onRetry:t}){return(0,j.jsxs)("div",{className:"um-row",children:[(0,j.jsxs)("div",{className:"um",children:[e.attachments?.map(i=>(0,j.jsx)("img",{className:"um-img",src:`/attachments/${i.id}?t=${QT()}`,alt:i.name},i.id)),(0,j.jsx)("span",{className:"um-text",children:e.text}),(0,j.jsxs)("div",{className:"um-act",children:[(0,j.jsx)("button",{className:"ibtn",title:y("common.copy"),onClick:()=>{jr(e.text)},children:(0,j.jsx)(ye,{name:"copy",size:13})}),t&&(0,j.jsx)("button",{className:"ibtn",title:y("timeline.editResend"),onClick:()=>t(e.text),children:(0,j.jsx)(ye,{name:"send",size:13})})]})]}),e.steered&&(0,j.jsx)("div",{className:"um-tag",children:y("timeline.steer")})]})}function gz({it:e}){let[t,i]=(0,zt.useState)(e.streaming?"":e.text),n=(0,zt.useRef)(null);return(0,zt.useEffect)(()=>{n.current||(n.current=new ff(i)),n.current.push(e.text),e.streaming||n.current.flush()},[e.text,e.streaming]),(0,zt.useEffect)(()=>()=>n.current?.stop(),[]),(0,j.jsx)(cv,{text:t,streaming:e.streaming})}function _z({it:e}){let[t,i]=(0,zt.useState)(!1),n=Math.max(1,Math.round(e.text.length/40));return(0,j.jsxs)("div",{className:"rs-item",children:[(0,j.jsxs)("button",{className:"rs-head",onClick:()=>i(!t),children:[(0,j.jsx)("span",{className:`caret${t?" open":""}`,children:"\u203A"})," ",Ce("timeline.thinking",{s:n})]}),t&&(0,j.jsx)("div",{className:"rs-body",children:e.text})]})}function gv(e){let t=`timeline.tool.${e}`,i=y(t);return i.startsWith("timeline.tool.")?y("timeline.tool.other"):i}function vz({it:e}){let t=e.steps.some(l=>l.status==="failed"),i=e.steps.some(l=>{let c=l.detail,u=c?.hunks??c?.diff?.hunks;return Array.isArray(u)&&u.length>0}),[n,s]=(0,zt.useState)(t||i),r=(0,zt.useRef)(!1);(0,zt.useEffect)(()=>{!r.current&&(t||i)&&s(!0)},[t,i]);let a=(0,zt.useMemo)(()=>{let l=new Map;for(let u of e.steps)l.set(u.kind,(l.get(u.kind)??0)+1);let c=[...l.entries()].map(([u,h])=>`${gv(u)} ${h}`);return Ce("timeline.toolSummary",{n:e.steps.length,parts:c.join(" \xB7 ")})},[e.steps]),o=e.steps.find(l=>l.status==="running");return(0,j.jsxs)("div",{className:"tg",children:[(0,j.jsxs)("button",{className:"tg-head",onClick:()=>{r.current=!0,s(!n)},children:[(0,j.jsx)("span",{className:`caret${n?" open":""}`,children:"\u203A"}),(0,j.jsx)("span",{children:a}),o&&(0,j.jsx)("span",{className:"tg-live",children:Ce("timeline.toolRunning",{kind:gv(o.kind),title:o.title})})]}),n&&(0,j.jsx)("div",{className:"tg-list",children:e.steps.map(l=>(0,j.jsx)(bz,{s:l},l.itemId))})]})}function bz({s:e}){let t=e.detail,[i,n]=(0,zt.useState)(e.status==="failed"||Array.isArray(t?.hunks)&&t.hunks.length>0),s=e.status==="running"?"\u2026":e.status==="ok"?"\u2713":"\u2717",r=e.status==="running"?"run":e.status==="ok"?"ok":"fail",a=e.output||e.detail;return(0,j.jsxs)("div",{className:"ts",children:[(0,j.jsxs)("button",{className:"ts-head",onClick:()=>a&&n(!i),children:[(0,j.jsx)("span",{className:`ts-ic ${r}`,children:s}),(0,j.jsx)("span",{className:"ts-title",children:e.title||gv(e.kind)}),e.durationMs!=null&&(0,j.jsx)("span",{className:"ts-meta",children:T_(e.durationMs)}),e.exitCode!=null&&e.exitCode!==0&&(0,j.jsxs)("span",{className:"ts-meta err",children:["exit ",e.exitCode]})]}),i&&(0,j.jsx)(yz,{s:e})]})}function yz({s:e}){let[t,i]=(0,zt.useState)(!1),n=e.detail,s=n?.hunks??n?.diff?.hunks;if(s)return(0,j.jsx)(mf,{hunks:XT(s),path:n?.diff?.path??n?.path});if(e.output!=null){let r=e.output.split(` -`),a=r.length>50&&!t,o=a?r.slice(-50).join(` -`):e.output;return(0,j.jsxs)("div",{className:"ts-out",children:[a&&(0,j.jsx)("button",{className:"ts-more",onClick:()=>i(!0),children:Ce("timeline.showAllLines",{n:r.length})}),(0,j.jsx)("pre",{children:o})]})}return e.input!=null?(0,j.jsx)("pre",{className:"ts-out",children:JSON.stringify(e.input,null,2).slice(0,4e3)}):null}function mf({hunks:e,path:t,max:i=3e3}){let n=0,s=!1;return(0,j.jsxs)("div",{className:"diff",children:[t&&(0,j.jsx)("div",{className:"diff-path",children:t}),(0,j.jsx)("pre",{className:"diff-pre",children:e.map((r,a)=>(0,j.jsxs)("span",{className:"dh",children:[(0,j.jsx)("span",{className:"dh-head",children:r.head??"@@"}),r.lines.map((o,l)=>(n++,n>i?(s=!0,null):(0,j.jsxs)("span",{className:`dl ${o.t==="+"?"add":o.t==="-"?"del":""}`,children:[o.t," ",o.text,` -`]},l)))]},a))}),s&&(0,j.jsx)("div",{className:"dlg-hint",children:Ce("timeline.diffClip",{n:i})})]})}function Sz({it:e}){return(0,j.jsx)("div",{className:"card plan",children:(0,j.jsx)(cv,{text:e.markdown})})}function wz({it:e}){let[t,i]=(0,zt.useState)(!1),n=e.items.filter(s=>s.status==="done"||s.status==="completed").length;return(0,j.jsxs)("div",{className:"rs-item",children:[(0,j.jsxs)("button",{className:"rs-head",onClick:()=>i(!t),children:[(0,j.jsx)("span",{className:`caret${t?" open":""}`,children:"\u203A"})," ",Ce("timeline.todo",{done:n,total:e.items.length})]}),t&&(0,j.jsx)("ul",{className:"todo-list",children:e.items.map((s,r)=>(0,j.jsxs)("li",{className:`todo ${s.status}`,children:[s.status==="done"||s.status==="completed"?"\u2611":s.status==="in_progress"?"\u25D0":"\u2610"," ",s.text]},r))})]})}function Ez({it:e,threadId:t}){let[i,n]=(0,zt.useState)(!1),s=l=>{n(!0),te.call("thread.respond",{id:t,requestId:e.requestId,optionId:l}).catch(()=>n(!1))},r=e.detail,a=r?.hunks??r?.diff?.hunks,o=e.status==="resolved"?e.choice==="allow_always"||e.choice==="acceptForSession"?y("timeline.permAllowSession"):e.choice==="deny"||e.choice==="reject"||e.choice==="decline"?y("timeline.permDenied"):e.choice==="implement"?y("timeline.permAllowed"):y("timeline.permAllowed"):y("timeline.permCancelled");return(0,j.jsxs)("div",{className:`card perm${e.status!=="pending"?" done":""}`,children:[(0,j.jsx)("div",{className:"perm-title",children:e.title}),r?.command&&(0,j.jsx)("pre",{className:"perm-cmd",children:r.command}),r?.path&&(0,j.jsx)("div",{className:"perm-path",children:r.path}),a&&(0,j.jsx)(mf,{hunks:a,path:r?.diff?.path??r?.path,max:200}),e.status==="pending"?(0,j.jsx)("div",{className:"perm-btns",children:e.options.map(l=>(0,j.jsx)("button",{className:`btn ${l.kind==="allow_once"?"primary":l.kind==="reject_once"?"danger":""}`,disabled:i,onClick:()=>s(l.id),children:l.label},l.id))}):(0,j.jsx)("div",{className:"perm-done",children:o})]})}function xz({it:e,threadId:t}){let[i,n]=(0,zt.useState)({}),[s,r]=(0,zt.useState)({}),a=e.questions,o=(c,u)=>c.id??c.question??c.header??`q${u}`,l=()=>{let c={};a.forEach((u,h)=>{c[o(u,h)]=i[h]?.trim()||s[h]||""}),te.call("thread.respond",{id:t,requestId:e.requestId,answers:c})};return(0,j.jsxs)("div",{className:`card ask${e.status!=="pending"?" done":""}`,children:[a.map((c,u)=>(0,j.jsxs)("div",{className:"ask-q",children:[(0,j.jsx)("div",{className:"ask-t",children:c.header??c.question}),e.status==="pending"?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)("div",{className:"ask-opts",children:c.options?.map(h=>(0,j.jsx)("button",{className:`btn${s[u]===h.label?" primary":""}`,onClick:()=>r(d=>({...d,[u]:h.label})),children:h.label},h.label))}),(0,j.jsx)("input",{className:"tinput ask-free",placeholder:y("common.other"),value:i[u]??"",onChange:h=>n(d=>({...d,[u]:h.target.value}))})]}):(0,j.jsx)("div",{className:"perm-done",children:e.answers?Ce("timeline.submitted",{ans:Object.values(e.answers).join("\u3001")}):y("timeline.permCancelled")})]},u)),e.status==="pending"&&(0,j.jsx)("button",{className:"btn primary",onClick:l,children:y("common.submit")})]})}function Cz({it:e,onRetry:t,replyText:i}){let n=fe(),[s,r]=(0,zt.useState)(!1);if(e.status==="failed")return(0,j.jsxs)("div",{className:"card err-card",children:[(0,j.jsx)("div",{className:"err-line",children:Ce("timeline.turnError",{err:La(e.error??y("timeline.unknownError"))})}),(0,j.jsxs)("div",{className:"perm-btns",children:[t&&(0,j.jsx)("button",{className:"btn",onClick:t,children:y("common.retry")}),e.error&&e.error.length>60&&(0,j.jsx)("button",{className:"btn ghost",onClick:()=>r(!s),children:y("common.details")})]}),s&&(0,j.jsx)("pre",{className:"perm-cmd",children:La(e.error??"")})]});let a=[];if(e.durationMs!=null&&a.push(T_(e.durationMs)),e.usage){let o=e.usage.inputTokens+e.usage.outputTokens;o&&a.push(`${ml(o)} tokens`),e.usage.costUsd&&a.push(Pd(e.usage.costUsd))}return e.status==="interrupted"&&a.push(y("timeline.interrupted")),(0,j.jsxs)("div",{className:"te",children:[a.length>0&&(0,j.jsx)("span",{className:"te-meta",children:a.join(" \xB7 ")}),i&&(0,j.jsxs)("button",{className:"te-act",title:y("common.copy"),onClick:()=>{jr(i).then(()=>Te(y("common.copied")))},children:[(0,j.jsx)(ye,{name:"copy",size:13}),(0,j.jsx)("span",{children:y("common.copy")})]}),t&&(0,j.jsxs)("button",{className:"te-act",title:y("common.retry"),onClick:t,children:[(0,j.jsx)(ye,{name:"refresh",size:13}),(0,j.jsx)("span",{children:y("common.retry")})]}),e.filesChanged!=null&&e.filesChanged>0&&(0,j.jsx)("button",{className:"te-files",onClick:()=>n.openPanel("changes"),children:Ce("timeline.filesChanged",{n:e.filesChanged})})]})}function eN({it:e,threadId:t,onEditResend:i,onRetryLast:n,replyText:s}){switch(e.kind){case"user":return(0,j.jsx)(mz,{it:e,onRetry:i});case"assistant":return(0,j.jsx)("div",{className:"as",children:(0,j.jsx)(gz,{it:e})});case"reasoning":return(0,j.jsx)(_z,{it:e});case"toolgroup":return(0,j.jsx)(vz,{it:e});case"plan":return(0,j.jsx)(Sz,{it:e});case"todo":return(0,j.jsx)(wz,{it:e});case"permission":return(0,j.jsx)(Ez,{it:e,threadId:t});case"question":return(0,j.jsx)(xz,{it:e,threadId:t});case"notice":return(0,j.jsx)("div",{className:`nt ${e.level}`,children:La(e.message)});case"turnend":return(0,j.jsx)(Cz,{it:e,onRetry:n,replyText:s});case"gone":return null;default:return null}}var zt,j,QT,gf=le(()=>{zt=ae(Nt(),1);lf();VT();Wr();Rn();pf();ZT();Ud();dn();Ci();Vn();j=ae(ke(),1),QT=()=>Rl()});function Ln({value:e,options:t,onChange:i,ariaLabel:n,title:s,className:r,children:a,prefer:o="down",matchWidth:l=!1,menuClassName:c,upAnchor:u}){let[h,d]=(0,Si.useState)(!1),[f,p]=(0,Si.useState)(-1),[_,w]=(0,Si.useState)(null),g=(0,Si.useRef)(null),m=(0,Si.useRef)(null),v=(0,Si.useId)(),S=t.find(M=>M.value===e),k=M=>M>=0&&M{for(let E=1;E<=t.length;E++){let I=(M+B*E+t.length*2)%t.length;if(!t[I].disabled)return I}return M},[t]),O=M=>{let B=t.findIndex(I=>I.value===e),E=M==="first"?A(-1,1):M==="last"?A(0,-1):B;k(E)||(E=A(-1,1)),p(E),w(null),d(!0)},T=M=>{d(!1),M&&g.current?.focus()},D=M=>{k(M)&&(T(!0),t[M].value!==e&&i(t[M].value))};(0,Si.useLayoutEffect)(()=>{if(!h)return;let M=g.current?.getBoundingClientRect(),B=m.current;if(!M||!B)return;let E=window.innerWidth,I=window.innerHeight,C=l?M.width:0;B.style.minWidth=`${C}px`;let L=B.offsetWidth,R=B.scrollHeight,$=I-M.bottom-_f-au,ee=u&&g.current?.closest(u)?.getBoundingClientRect().top||M.top,z=ee-_f-au,X=o==="up"?!(zz):$$,Ee=X?z:$,ue=Math.min(R,Ee),De=X?ee-_f-ue:M.bottom+_f,J=Math.max(au,Math.min(M.left,E-L-au));w({left:J,top:Math.max(au,De),minWidth:C,maxHeight:Math.max(80,Ee)})},[h,o,l,t.length,u]),(0,Si.useEffect)(()=>{h&&_&&m.current?.focus({preventScroll:!0})},[h,_]),(0,Si.useEffect)(()=>{!h||f<0||m.current?.querySelector(`[data-i="${f}"]`)?.scrollIntoView({block:"nearest"})},[h,f]),(0,Si.useEffect)(()=>{if(!h)return;let M=E=>{let I=E.target;m.current?.contains(I)||g.current?.contains(I)||T(!1)},B=()=>T(!1);return window.addEventListener("pointerdown",M,!0),window.addEventListener("resize",B),window.addEventListener("blur",B),()=>{window.removeEventListener("pointerdown",M,!0),window.removeEventListener("resize",B),window.removeEventListener("blur",B)}},[h]);let F=M=>{(M.key==="ArrowDown"||M.key==="ArrowUp"||M.key==="Enter"||M.key===" ")&&(M.preventDefault(),h?T(!1):O(M.key==="ArrowUp"?"last":void 0))},P=M=>{let B=M.key;if(B==="ArrowDown")p(E=>A(E<0?-1:E,1));else if(B==="ArrowUp")p(E=>A(E<0?0:E,-1));else if(B==="Home")p(A(-1,1));else if(B==="End")p(A(0,-1));else if(B==="Enter"||B===" ")D(f);else if(B==="Escape")T(!0);else if(B==="Tab"){T(!0);return}else if(B.length===1&&/\S/.test(B)){let E=B.toLowerCase();for(let I=1;I<=t.length;I++){let C=(Math.max(f,0)+I)%t.length;if(!t[C].disabled&&t[C].label.toLowerCase().startsWith(E)){p(C);break}}}else return;M.preventDefault(),M.stopPropagation()};return(0,Pi.jsxs)(Pi.Fragment,{children:[(0,Pi.jsx)("button",{ref:g,type:"button",className:r,title:s,"aria-label":n,"aria-haspopup":"listbox","aria-expanded":h,"aria-controls":h?`${v}-lb`:void 0,onClick:()=>h?T(!1):O(),onKeyDown:F,children:a??(0,Pi.jsx)("span",{className:"sm-val",children:S?.label??""})}),h&&(0,tN.createPortal)((0,Pi.jsx)("div",{ref:m,id:`${v}-lb`,className:`menu select-menu${c?` ${c}`:""}`,role:"listbox","aria-label":n,"aria-activedescendant":f>=0?`${v}-o${f}`:void 0,tabIndex:-1,"data-select-menu":"",style:_?{left:_.left,top:_.top,minWidth:_.minWidth,maxHeight:_.maxHeight}:{left:-9999,top:0,visibility:"hidden"},onKeyDown:P,children:t.map((M,B)=>(0,Pi.jsxs)("div",{id:`${v}-o${B}`,"data-i":B,role:"option","aria-selected":M.value===e,"aria-disabled":M.disabled||void 0,className:`mi sm-opt${B===f?" on":""}${M.disabled?" off":""}${M.danger?" danger":""}${M.hint?" has-hint":""}`,onPointerMove:()=>{!M.disabled&&f!==B&&p(B)},onClick:()=>D(B),children:[(0,Pi.jsxs)("span",{className:"sm-text",children:[(0,Pi.jsx)("span",{className:"sm-label",children:M.label}),M.hint&&(0,Pi.jsx)("span",{className:"sm-hint",children:M.hint})]}),(0,Pi.jsx)("span",{className:"sm-check","aria-hidden":"true",children:M.value===e?(0,Pi.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",children:(0,Pi.jsx)("path",{d:"M2.5 6.2 5 8.6l4.5-5",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}):null})]},M.value))}),document.body)]})}var Si,tN,Pi,_f,au,vf=le(()=>{Si=ae(Nt(),1),tN=ae(oa(),1),Pi=ae(ke(),1),_f=4,au=8});function _v(){return[{id:"plan",label:y("composer.mode.plan.label"),desc:y("composer.mode.plan.desc")},{id:"default",label:y("composer.mode.default.label"),desc:y("composer.mode.default.desc")},{id:"acceptEdits",label:y("composer.mode.acceptEdits.label"),desc:y("composer.mode.acceptEdits.desc")},{id:"bypassPermissions",label:y("composer.mode.bypass.label"),desc:y("composer.mode.bypass.desc"),danger:!0}]}function kz(){return[{id:"default",label:y("composer.mode.cursorAgent.label"),desc:y("composer.mode.cursorAgent.desc")},{id:"plan",label:y("composer.mode.cursorPlan.label"),desc:y("composer.mode.cursorPlan.desc")},{id:"ask",label:y("composer.mode.cursorAsk.label"),desc:y("composer.mode.cursorAsk.desc")}]}function iN(e,t,i){return(e==="cursor"?kz():_v()).filter(s=>t.includes(s.id)).map(s=>i?.[s.id]?{...s,label:Tz(i[s.id])}:s)}function Tz(e){let t=y(`composer.agentMode.${e}`);return t.startsWith("composer.agentMode.")?e:t}function bf(e,t){let i=y(`composer.effort.${e}`);return i.startsWith("composer.effort.")?t??e:i}var vv=le(()=>{Ci()});function bv(e){let t=e.trim();if(t){try{let i=JSON.parse(t);if(Array.isArray(i)&&i.every(n=>typeof n=="string"))return i}catch{}return null}}function yv(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let i=Number(t);return i>=5&&i<=240?i:null}var nN=le(()=>{});function sN(e){return!(e.enabled===!1||!e.available||e.status==="planned")}function Mz(e){return e.status==="verified"?y("settings.providerVerified"):e.status==="experimental"?y("settings.providerExperimental"):e.status==="planned"?y("settings.providerPlanned"):y("settings.providerPending")}function rN(){te.call("providers.list").then(e=>{ut.setState({providers:e})}).catch(()=>{})}function oN({onClose:e,providers:t}){let[i,n]=(0,mn.useState)(null),[s,r]=(0,mn.useState)({}),[a,o]=(0,mn.useState)(null),[l,c]=(0,mn.useState)({}),[u,h]=(0,mn.useState)({}),[d,f]=(0,mn.useState)({}),[p,_]=(0,mn.useState)({}),[w,g]=(0,mn.useState)(null),m=_v();(0,mn.useEffect)(()=>{te.call("settings.get").then(E=>n(E)),te.call("app.info").then(E=>r(E)).catch(()=>{})},[]);let v=async E=>{let I=i,C={...i,...E};n(C),E.theme&&Xs(E.theme);try{return await te.call("settings.set",{patch:E}),window.dispatchEvent(new CustomEvent("settings-changed",{detail:C})),!0}catch(L){return n(I),E.theme&&Xs(I?.theme),Te(y("settings.failSave")+ct(L),!0),!1}},S=async(E,I)=>{c($=>({...$,[E]:I}));let C=i?.providerEnabled??{},L=i,R={...i,providerEnabled:{...C,[E]:I}};n(R);try{await te.call("settings.set",{patch:{providerEnabled:R.providerEnabled}}),window.dispatchEvent(new CustomEvent("settings-changed",{detail:R})),I||ut.setState($=>({providers:$.providers.map(ee=>ee.id===E?{...ee,enabled:!1}:ee)})),rN()}catch($){n(L),Te(y("settings.providerToggleFailed")+ct($),!0)}finally{c($=>{let ee={...$};return delete ee[E],ee})}},k=()=>{te.call("providers.list",{refresh:!0}).then(E=>{ut.setState({providers:E}),Te(y("settings.providerRedetect")+" \u2713")}).catch(E=>Te(ct(E),!0))},A=async(E,I)=>{let C={...i?.providerCommand??{}},L={...C[E],...I};L.executable||delete L.executable,(!L.args||L.args.length===0)&&delete L.args,JSON.stringify(C[E]??{})!==JSON.stringify(L)&&(C[E]=L,await v({providerCommand:C})&&rN())},O=E=>{let I=u[E];I!==void 0&&(A(E,{executable:I.trim()||void 0}),h(C=>{let L={...C};return delete L[E],L}))},T=E=>{let I=d[E];if(I===void 0)return;let C=bv(I);if(C===null){_(L=>({...L,[E]:!0}));return}_(L=>({...L,[E]:!1})),A(E,{args:C}),f(L=>{let R={...L};return delete R[E],R})},D=()=>{if(w===null)return;let E=yv(w);E!==null&&(g(null),E!==i?.idleCloseMinutes&&v({idleCloseMinutes:E}))},F=(E,I)=>{if(!I)return{dot:"off",text:y("settings.providerOff")};if(E.enabled===!1)return{dot:"pending",text:y("settings.providerPending")};if(!E.available)return{dot:"off",text:E.reason??y("common.notDetected")};let C=E.models?.length??0,L=Mz(E),R=C>0?` \xB7 ${Ce("settings.providerModels",{n:String(C)})}`:"";return{dot:E.status==="verified"?"on":"pending",text:L+R}};if(!i)return(0,ve.jsx)(Es,{title:y("settings.title"),onClose:e,children:(0,ve.jsx)("div",{className:"dlg-hint",children:y("common.loading")})});let P=(E,I,C)=>(0,ve.jsxs)("div",{className:"dlg-row",children:[(0,ve.jsx)("label",{children:E}),I,C&&(0,ve.jsx)("div",{className:"dlg-hint",style:{marginTop:4},children:C})]}),M=w!==null&&yv(w)===null,B=E=>I=>{I.key==="Enter"&&(I.preventDefault(),E())};return(0,ve.jsxs)(Es,{title:y("settings.title"),onClose:e,wide:!0,footer:(0,ve.jsx)("button",{className:"btn primary",onClick:e,children:y("common.done")}),children:[P(y("settings.defaultAgent"),(0,ve.jsx)(Ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:y("settings.defaultAgent"),value:i.defaultProvider??"claude",onChange:E=>{v({defaultProvider:E})},options:t.map(E=>({value:E.id,label:E.name+(sN(E)?"":y("common.notInstalled")),disabled:!sN(E)}))})),(0,ve.jsxs)("div",{className:"dlg-row dlg-row-top",children:[(0,ve.jsx)("label",{children:y("settings.providers")}),(0,ve.jsxs)("div",{className:"provider-list",children:[(0,ve.jsx)("button",{type:"button",className:"btn sm provider-redetect",onClick:k,children:y("settings.providerRedetect")}),t.map(E=>{let I=l[E.id]??i.providerEnabled?.[E.id]??E.enabled!==!1,C=F(E,I),L=a===E.id,R=i.providerCommand?.[E.id],$=d[E.id]??(R?.args?.length?JSON.stringify(R.args):"");return(0,ve.jsxs)("div",{className:`provider-row${L?" open":""}`,children:[(0,ve.jsxs)("button",{type:"button",className:"provider-head",onClick:()=>o(L?null:E.id),children:[(0,ve.jsx)("span",{className:`provider-dot provider-dot-${C.dot}`,"aria-hidden":!0}),(0,ve.jsxs)("div",{className:"provider-meta",children:[(0,ve.jsx)("span",{className:"provider-name",children:E.name}),(0,ve.jsx)("span",{className:"dlg-hint",children:C.text})]}),(0,ve.jsx)("span",{className:"mi-caret",children:L?"\u25BE":"\u25B8"})]}),(0,ve.jsx)("label",{className:"provider-switch",title:E.name,children:(0,ve.jsx)("input",{type:"checkbox",checked:I,disabled:l[E.id]!==void 0,onChange:ee=>{S(E.id,ee.target.checked)}})}),L&&(0,ve.jsxs)("div",{className:"provider-detail",children:[E.bin&&(0,ve.jsxs)("div",{className:"dlg-hint",children:[E.bin,E.version?` \xB7 ${E.version}`:""]}),E.installHint&&(0,ve.jsxs)("div",{className:"provider-hint-row",children:[(0,ve.jsx)("code",{className:"dlg-hint",children:E.installHint}),(0,ve.jsx)("button",{type:"button",className:"te-files",onClick:()=>{navigator.clipboard?.writeText(E.installHint??"").then(()=>Te(y("common.copied")))},children:y("settings.providerCopyHint")})]}),(0,ve.jsx)("div",{className:"dlg-hint",children:y("settings.providerLaunchCmd")}),(0,ve.jsx)("input",{className:"tinput",placeholder:y("settings.providerLaunchExe"),"aria-label":y("settings.providerLaunchExe"),value:u[E.id]??R?.executable??"",onChange:ee=>{let z=ee.target.value;h(X=>({...X,[E.id]:z}))},onBlur:()=>O(E.id),onKeyDown:B(()=>O(E.id))}),(0,ve.jsx)("input",{className:`tinput${p[E.id]?" err":""}`,placeholder:'["--foo"]',"aria-label":y("settings.providerLaunchArgs"),value:$,onChange:ee=>{let z=ee.target.value;f(X=>({...X,[E.id]:z})),p[E.id]&&_(X=>({...X,[E.id]:bv(z)===null}))},onBlur:()=>T(E.id),onKeyDown:B(()=>T(E.id))}),(0,ve.jsx)("div",{className:`dlg-hint${p[E.id]?" err":""}`,children:p[E.id]?y("settings.providerArgsInvalid"):y("settings.providerLaunchArgsHint")})]})]},E.id)})]})]}),P(y("settings.defaultMode"),(0,ve.jsx)(Ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:y("settings.defaultMode"),value:i.defaultMode??"default",onChange:E=>{v({defaultMode:E})},options:m.map(E=>({value:E.id,label:E.label,hint:E.desc})),children:(0,ve.jsx)("span",{className:"sm-val",children:(()=>{let E=m.find(I=>I.id===(i.defaultMode??"default"));return E?`${E.label} \u2014 ${E.desc}`:""})()})}),y("settings.defaultModeHint")),P(y("settings.theme"),(0,ve.jsx)(Ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:y("settings.theme"),value:v_(i.theme),onChange:E=>{v({theme:E})},options:[{value:"auto",label:FE()?y("settings.themeMagpie"):y("settings.themeAuto")},{value:"light",label:y("settings.themeLight")},{value:"dark",label:y("settings.themeDark")}]})),P(y("settings.sendKey"),(0,ve.jsx)(Ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:y("settings.sendKey"),value:i.sendKey??"enter",onChange:E=>{v({sendKey:E})},options:[{value:"enter",label:y("settings.sendEnter")},{value:"ctrlEnter",label:y("settings.sendCtrl")}]})),P(y("settings.runningSend"),(0,ve.jsx)(Ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:y("settings.runningSend"),value:i.runningSend??"queue",onChange:E=>{v({runningSend:E})},options:[{value:"queue",label:y("settings.queue")},{value:"steer",label:y("settings.steer")}]}),y("settings.steerHint")),P(y("settings.thinking"),(0,ve.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"center",fontSize:"var(--fs-m)",color:"var(--fg)"},children:[(0,ve.jsx)("input",{type:"checkbox",checked:i.showThinking!==!1,onChange:E=>{v({showThinking:E.target.checked})}}),y("settings.showThinking")]})),P(y("settings.idleClose"),(0,ve.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[(0,ve.jsx)("input",{className:`tinput${M?" err":""}`,type:"number",min:5,max:240,step:1,style:{width:90,flex:"none"},"aria-label":y("settings.idleClose"),value:w??String(i.idleCloseMinutes??30),onChange:E=>g(E.target.value),onBlur:D,onKeyDown:B(D)}),(0,ve.jsx)("span",{className:"dlg-hint",children:y("settings.idleMinutes")})]}),M?y("settings.idleInvalid"):void 0),(0,ve.jsx)("div",{className:"msep"}),(0,ve.jsxs)("div",{className:"dlg-hint",children:[Ce("settings.versionLine",{ver:s.version??"?",pid:s.pid??"?"}),(0,ve.jsx)("br",{}),y("settings.dataDir"),s.dataDir??"?"," ",(0,ve.jsx)("button",{className:"te-files",onClick:()=>{navigator.clipboard?.writeText(s.dataDir??"").catch(()=>{})},children:y("common.copy")})]})]})}function aN(e){return{sendKey:e?.sendKey==="ctrlEnter"?"ctrlEnter":"enter",runningSend:e?.runningSend==="steer"?"steer":"queue",showThinking:e?.showThinking!==!1}}function ou(){let[e,t]=(0,mn.useState)(Rz);return(0,mn.useEffect)(()=>{te.call("settings.get").then(n=>t(aN(n))).catch(()=>{});let i=n=>t(aN(n.detail));return window.addEventListener("settings-changed",i),()=>window.removeEventListener("settings-changed",i)},[]),e}var mn,ve,Rz,yf=le(()=>{mn=ae(Nt(),1);_l();vf();Rn();Vn();vv();Ci();jn();nN();Nd();ve=ae(ke(),1);Rz={sendKey:"enter",runningSend:"queue",showThinking:!0}});function lN({size:e=18,className:t}){return(0,Xr.jsxs)("svg",{className:t,width:e,height:e,viewBox:"0 0 64 64","aria-hidden":"true",children:[(0,Xr.jsx)("rect",{width:"64",height:"64",rx:"15",fill:"#26292b"}),(0,Xr.jsxs)("g",{fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"5.2",children:[(0,Xr.jsx)("path",{d:"M14 20.5 25 31 14 41.5",stroke:"#fff"}),(0,Xr.jsx)("path",{d:"M29.14 23.61A12 12 0 1 1 46.63 39.92L48.6 47.6 39.85 42.93A12 12 0 0 1 29.14 38.39",stroke:"#fff"}),(0,Xr.jsx)("path",{d:"M35.6 35.4h6",stroke:"#2dd4bf"})]})]})}var Xr,cN=le(()=>{Xr=ae(ke(),1)});function uN(e,t=!1){if(t||!e.startsWith("/"))return{open:!1,query:""};let i=e.slice(1);return i.includes(` -`)||i.includes(" ")?{open:!1,query:""}:{open:!0,query:i}}function hN(e,t){let i=t.trim().toLowerCase();return i?e.filter(n=>n.name.toLowerCase().includes(i)||n.description.toLowerCase().includes(i)||(n.argumentHint??"").toLowerCase().includes(i)):e}function dN(e){let t=e.filter(s=>s.kind==="command"),i=e.filter(s=>s.kind==="skill"),n=[];if(t.length){n.push({type:"heading",id:"h-cmd",labelKey:"slashGroupCommand"});for(let s of t)n.push({type:"item",id:`c:${s.name}`,command:s})}if(i.length){n.push({type:"heading",id:"h-skill",labelKey:"slashGroupSkill"});for(let s of i)n.push({type:"item",id:`s:${s.name}`,command:s})}return n}function fN(e){return e.filter(t=>t.type==="item").map(t=>t.command)}function Sv(e){return`/${e} `}function pN(e,t){return!!t&&e.trim()===`/${t}`}function wv(e,t){return t<=0?0:e<0?t-1:e>=t?0:e}var mN=le(()=>{});function gN(){let e=fe(),{threads:t,providers:i}=ut(),n=Dn(),[s,r]=(0,$e.useState)(""),[a,o]=(0,$e.useState)([]),[l,c]=(0,$e.useState)(!1),[u,h]=(0,$e.useState)(null),[d,f]=(0,$e.useState)(""),p=(0,$e.useRef)(null),_=(0,$e.useRef)(null),w=(0,$e.useRef)(null),[g,m]=(0,$e.useState)([]),[v,S]=(0,$e.useState)(0),[k,A]=(0,$e.useState)(0),O=(0,$e.useRef)(!1),T=(0,$e.useRef)(new Set),[D,F]=(0,$e.useState)(!1),P=ou(),M=t.find(x=>x.id===e.currentThreadId),B=i.find(x=>x.id===M?.provider),E=n.status==="running"||n.status==="initializing",I=n.pending.length>0,C=B?.capabilities.steer??!1,L=!!B&&!B.capabilities.images&&B.capabilities.imagesKnown!==!1,R=M?.mode??"default",$=iN(M?.provider,B?.capabilities.modes??[],B?.capabilities.modeLabels),ee=$.find(x=>x.id===R),z=n.items.some(x=>x.kind==="user"),X=(0,$e.useMemo)(()=>uN(s,O.current),[s]),Ee=(0,$e.useMemo)(()=>hN(n.slashCommands,X.query),[n.slashCommands,X.query]),ue=(0,$e.useMemo)(()=>dN(Ee),[Ee]),De=(0,$e.useMemo)(()=>fN(ue),[ue]),J=X.open&&!I;(0,$e.useEffect)(()=>{A(0)},[X.query,J]),(0,$e.useEffect)(()=>{let x=M?.id;!J||!x||T.current.has(x)||(T.current.add(x),F(!0),te.call("thread.commands",{id:x,load:!0},3e4).then(W=>{let Z=W.commands??[];(Z.length||!Dn.getState().slashCommands.length)&&Dn.setState({slashCommands:Z})}).catch(()=>{}).finally(()=>F(!1)))},[J,M?.id]);let qe=(0,$e.useMemo)(()=>i.filter(x=>x.enabled!==!1||x.id===M?.provider),[i,M?.provider]),dt=qe.find(x=>x.id===(u??M?.provider)),oi=x=>x.enabled!==!1&&x.available&&x.status!=="planned",Mi=x=>{c(x),x&&(h(null),f(""))};(0,$e.useEffect)(()=>{if(!l)return;let x=Z=>{p.current&&!p.current.contains(Z.target)&&Mi(!1)},W=Z=>{Z.key==="Escape"&&(Z.stopPropagation(),Mi(!1))};return document.addEventListener("pointerdown",x,!0),window.addEventListener("keydown",W,!0),()=>{document.removeEventListener("pointerdown",x,!0),window.removeEventListener("keydown",W,!0)}},[l]);let Ri=async(x,W)=>{if(M){Mi(!1);try{!z&&x!==M.provider&&await te.call("thread.setProvider",{id:M.id,provider:x}),await te.call("thread.setModel",{id:M.id,model:W})}catch(Z){Te(y("composer.failSwitchAgent")+ct(Z),!0)}}},li=(0,$e.useMemo)(()=>{let x=d.trim().toLowerCase();if(!x)return[];let W=[];for(let Z of qe)if(oi(Z))for(let oe of Z.models??[])(oe.name.toLowerCase().includes(x)||oe.id.toLowerCase().includes(x))&&W.push({providerId:Z.id,providerName:Z.name,model:oe});return W.slice(0,100)},[d,qe]),xe=!!(u&&!d.trim());(0,$e.useEffect)(()=>{if(!E)return;let x=Date.now(),W=setInterval(()=>S(Math.floor((Date.now()-x)/1e3)),1e3);return()=>clearInterval(W)},[E]),(0,$e.useEffect)(()=>{let x=_.current;x&&(x.style.height="auto",x.style.height=Math.min(x.scrollHeight,264)+"px")},[s]);let ci=(0,$e.useCallback)(async(x="queue")=>{let W=e.currentThreadId,Z=s.trim();if(!(!W||!Z&&a.length===0)){E&&x==="queue"&&m(oe=>[...oe,Z]),r("");try{let oe=await te.call("thread.send",{id:W,text:Z,attachments:a.map(Me=>({path:Me.path,mime:Me.mime,name:Me.name})),behavior:E&&x==="steer"&&C?"steer":"queue"});o([]),oe?.delivered==="queued"&&E?Te(y("composer.queuedToast")):oe?.delivered==="steered"&&Te(y("composer.steeredToast")),E||m(Me=>[...Me.slice(-9),Z])}catch(oe){r(Z),Te(y("composer.failSend")+ct(oe),!0)}}},[s,a,e.currentThreadId,E,C]),ui=x=>{if(Mn(x.nativeEvent))return;if(J&&De.length>0){if(x.key==="ArrowDown"){x.preventDefault(),A(Fi=>wv(Fi+1,De.length));return}if(x.key==="ArrowUp"){x.preventDefault(),A(Fi=>wv(Fi-1,De.length));return}if(x.key==="Escape"){x.preventDefault(),O.current=!0,A(0);return}let oe=De[k]??De[0],Me=x.key==="Enter"&&pN(s,oe?.name);if((x.key==="Enter"&&!x.shiftKey||x.key==="Tab")&&!Me){x.preventDefault(),oe&&(O.current=!1,r(Sv(oe.name)));return}}let W=x.ctrlKey||x.metaKey;if(P.sendKey==="ctrlEnter"?x.key==="Enter"&&W:x.key==="Enter"&&!x.shiftKey&&!W){x.preventDefault(),E&&P.runningSend==="steer"&&C?ci("steer"):ci("queue");return}if(P.sendKey==="enter"&&x.key==="Enter"&&W&&E){x.preventDefault(),ci(C?"steer":"queue");return}x.key==="ArrowUp"&&s===""&&g.length>0&&(x.preventDefault(),r(g[g.length-1]))},he=async x=>{let W=x.clipboardData?.items;if(!W)return;for(let oe of W)if(oe.type.startsWith("image/")){x.preventDefault();let Me=oe.getAsFile();Me&&await hi(Me);return}let Z=x.clipboardData.getData("text/plain");if(Z&&Z.length>32*1024){x.preventDefault();let oe=new File([Z],"paste.txt",{type:"text/plain"});await hi(oe)}},hi=async x=>{let W=Rl(),Z={path:"",name:x.name,mime:x.type||"application/octet-stream",uploading:!0};o(oe=>[...oe,Z]);try{let Me=await(await fetch(`/api/upload?name=${encodeURIComponent(x.name)}`,{method:"POST",headers:{"x-agent-console":W},body:x})).json();if(!Me.ok)throw new Error(Me.e?.message??y("composer.uploadFailed"));o(Fi=>Fi.map(ns=>ns===Z?{...ns,path:Me.id,name:Me.name??x.name,uploading:!1}:ns))}catch(oe){o(Me=>Me.filter(Fi=>Fi!==Z)),Te(y("composer.failUpload")+ct(oe),!0)}},ne=async x=>{x.preventDefault();for(let W of x.dataTransfer.files)(W.type.startsWith("image/")||W.type.startsWith("text/"))&&await hi(W)},ts=x=>{M&&te.call("thread.setMode",{id:M.id,mode:x})},Ge=x=>{M&&te.call("thread.setEffort",{id:M.id,effort:x})},Ue=x=>{M&&te.call("thread.setCursorOpts",{id:M.id,...x}).catch(W=>Te(ct(W),!0))},Hn=M?.model?B?.models?.find(x=>x.id===M.model):B?.models?.find(x=>x.isDefault)??B?.models?.[0],Ot=(Hn?.thinkingOptions??[]).map(x=>{let W=x,Z=typeof W.id=="string"?W.id:typeof W.reasoningEffort=="string"?W.reasoningEffort:null,oe=W.id,Me=Z??(oe&&typeof oe.reasoningEffort=="string"?oe.reasoningEffort:null);return Me?{id:Me,label:typeof W.label=="string"?W.label:Me}:null}).filter(x=>x!==null),is=typeof Hn?.defaultThinking=="string"?Hn.defaultThinking:null,Ds=Ot.length>0,ie=(()=>{if(!M?.model){let Z=B?.models?.find(oe=>oe.isDefault);return Z?Z.name:y("composer.defaultModel")}let W=B?.models?.find(Z=>Z.id===M.model)?.name??M.model;return M.cursorFast&&(W+=" \xB7 Fast"),W})();return e.currentThreadId?(0,Y.jsxs)("div",{className:`composer${I?" waiting":""}`,onDrop:ne,onDragOver:x=>x.preventDefault(),children:[n.queue.length>0&&(0,Y.jsx)("div",{className:"q-list",children:n.queue.map(x=>(0,Y.jsxs)("div",{className:"q-item",children:[(0,Y.jsx)("span",{className:"q-text",children:x.text}),(0,Y.jsx)("button",{className:"ibtn",title:y("common.remove"),onClick:()=>{te.call("thread.queueRemove",{id:M?.id,queueId:x.id}).catch(()=>{})},children:(0,Y.jsx)(ye,{name:"x",size:12})})]},x.id))}),R==="bypassPermissions"&&(0,Y.jsx)("div",{className:"cp-danger",children:y("composer.bypassWarn")}),(0,Y.jsxs)("div",{className:`cp-card${I?" waiting":""}${R==="bypassPermissions"?" danger":""}`,children:[L&&a.some(x=>x.mime.startsWith("image/"))&&(0,Y.jsx)("div",{className:"att-note",children:Ce("composer.imagesByPath",{agent:B?.name??""})}),a.length>0&&(0,Y.jsx)("div",{className:"att-bar",children:a.map((x,W)=>(0,Y.jsxs)("span",{className:`att${x.uploading?" up":""}`,children:[x.mime.startsWith("image/")&&x.path?(0,Y.jsx)("img",{src:JT(x.path),alt:x.name}):(0,Y.jsx)(ye,{name:"attach",size:12}),(0,Y.jsx)("span",{className:"att-name",children:x.name}),x.uploading&&(0,Y.jsx)("span",{className:"att-prog",children:"\u2026"}),(0,Y.jsx)("button",{className:"att-x",onClick:()=>o(Z=>Z.filter((oe,Me)=>Me!==W)),children:"\xD7"})]},W))}),(0,Y.jsxs)("div",{className:"cp-ta-wrap",children:[J&&(0,Y.jsx)("div",{className:"pop agent-picker slash-pop",role:"listbox",children:(0,Y.jsx)("div",{className:"ap-scroll",children:ue.length===0?(0,Y.jsx)("div",{className:"ap-empty",children:y(D?"composer.slashLoading":"composer.slashNoCommands")}):ue.map(x=>{if(x.type==="heading")return(0,Y.jsx)("div",{className:"slash-h",children:x.labelKey==="slashGroupCommand"?y("composer.slashGroupCommand"):y("composer.slashGroupSkill")},x.id);let Z=De.indexOf(x.command)===k;return(0,Y.jsxs)("button",{type:"button",role:"option","aria-selected":Z,className:`mi slash-item${Z?" sel":""}`,onMouseDown:oe=>oe.preventDefault(),onClick:()=>{O.current=!1,r(Sv(x.command.name))},children:[(0,Y.jsxs)("span",{className:"slash-name",children:["/",x.command.name]}),(0,Y.jsx)("span",{className:"slash-desc",children:x.command.description}),x.command.argumentHint?(0,Y.jsx)("span",{className:"slash-hint",children:x.command.argumentHint}):null]},x.id)})})}),(0,Y.jsx)("textarea",{ref:_,className:"cp-ta",rows:1,placeholder:I?y("composer.waitPerm"):E?y(C?"composer.queuePlaceholder":"composer.queuePlaceholderNoSteer"):y("composer.inputPlaceholder"),value:s,disabled:I,onChange:x=>{O.current=!1,r(x.target.value)},onKeyDown:ui,onPaste:he})]}),(0,Y.jsxs)("div",{className:"cp-bar",children:[(0,Y.jsxs)("div",{className:"pill-wrap",ref:p,children:[(0,Y.jsxs)("button",{className:"pill chip",onClick:()=>Mi(!l),title:y("composer.agentModel"),children:[(0,Y.jsx)(lN,{size:18,className:"chip-logo"}),(0,Y.jsx)("span",{className:"p-a",children:B?.name??M?.provider??y("composer.agent")}),(0,Y.jsx)("span",{className:"p-t",children:ie}),(0,Y.jsx)("svg",{className:"chip-caret",width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:(0,Y.jsx)("path",{d:"M2.5 4l2.5 2.5L7.5 4",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l&&(0,Y.jsxs)("div",{className:"pop agent-pop agent-picker",children:[(0,Y.jsxs)("div",{className:"ap-search",children:[(0,Y.jsx)(ye,{name:"search",size:14}),(0,Y.jsx)("input",{className:"ap-search-in",autoFocus:!0,placeholder:y("composer.searchAllModels"),value:d,onChange:x=>f(x.target.value)})]}),d.trim()?(0,Y.jsxs)("div",{className:"ap-scroll",children:[li.length===0&&(0,Y.jsx)("div",{className:"ap-empty",children:y("composer.noModelMatch")}),li.map(({providerId:x,providerName:W,model:Z})=>{let oe=z&&x!==M?.provider;return(0,Y.jsxs)("button",{className:"mi mi-row",disabled:oe,onClick:()=>{Ri(x,Z.id)},children:[(0,Y.jsx)("span",{className:"mi-sub",children:W}),(0,Y.jsx)("span",{className:"mi-name",children:Z.name}),M?.provider===x&&M?.model===Z.id&&(0,Y.jsx)("span",{className:"mi-check",children:"\u2713"})]},`${x}:${Z.id}`)})]}):xe&&dt?(0,Y.jsxs)("div",{className:"ap-scroll",children:[(0,Y.jsxs)("button",{type:"button",className:"ap-back mi",onClick:()=>h(null),children:[(0,Y.jsx)("span",{className:"ap-back-icon",children:(0,Y.jsx)(ye,{name:"caret",size:14})}),dt.name]}),(0,Y.jsxs)("button",{className:"mi model-pick-row",title:dt.models?.find(x=>x.isDefault)?.name??y("composer.defaultModel"),onClick:()=>{Ri(dt.id,null)},children:[(0,Y.jsx)("span",{className:"model-pick-name",children:y("composer.defaultModel")}),(()=>{let x=dt.models?.find(W=>W.isDefault);return x?(0,Y.jsxs)("span",{className:"mi-sub model-pick-default",children:[" (",x.name,")"]}):null})(),M?.provider===dt.id&&!M?.model?(0,Y.jsx)("span",{className:"mi-check",children:"\u2713"}):""]}),(dt.models??[]).filter(x=>!x.isDefault).slice(0,Ev).map(x=>(0,Y.jsxs)("button",{className:"mi model-pick-row",title:x.name,onClick:()=>{Ri(dt.id,x.id)},children:[(0,Y.jsx)("span",{className:"model-pick-name",children:x.name}),M?.provider===dt.id&&M?.model===x.id?(0,Y.jsx)("span",{className:"mi-check",children:"\u2713"}):""]},x.id)),(dt.models?.length??0)>Ev&&(0,Y.jsx)("div",{className:"ap-empty",children:Ce("composer.moreModels",{n:String((dt.models?.length??0)-Ev)})})]}):(0,Y.jsxs)("div",{className:"ap-scroll",children:[(0,Y.jsx)("div",{className:"mlabel",children:z?y("composer.agentLocked"):y("composer.providers")}),z&&(0,Y.jsx)("div",{className:"ap-empty",children:y("composer.agentLockedHint")}),qe.length===0&&(0,Y.jsx)("div",{className:"ap-empty",children:y("composer.providersLoading")}),qe.map(x=>{let Z=oi(x)&&(!z||x.id===M?.provider),oe=x.models?.length??0,Me=x.name?.trim()||x.id;return(0,Y.jsxs)("button",{className:"mi mi-row provider-pick-row",disabled:!Z,onClick:()=>{Z&&h(x.id)},children:[(0,Y.jsx)("span",{className:"provider-pick-name",children:Me}),(0,Y.jsxs)("span",{className:"provider-pick-meta",children:[x.id===M?.provider&&(0,Y.jsx)("span",{className:"mi-tag",children:"Current"}),(0,Y.jsx)("span",{className:"mi-meta",children:oe===1?"1 model":`${oe} models`}),Z&&(0,Y.jsx)("span",{className:"mi-caret",children:(0,Y.jsx)(ye,{name:"caret",size:14})}),x.enabled===!1&&(0,Y.jsx)("span",{className:"dlg-hint",children:"Disabled"}),x.enabled!==!1&&x.status==="planned"&&(0,Y.jsx)("span",{className:"dlg-hint",children:"Not available"}),x.enabled!==!1&&x.status!=="planned"&&!x.available&&(0,Y.jsx)("span",{className:"dlg-hint",children:"Not detected"})]})]},x.id)})]})]})]}),Ds&&(0,Y.jsxs)(Ln,{className:"pill ipill",title:y("composer.effortTitle"),ariaLabel:y("composer.effortTitle"),prefer:"up",upAnchor:".cp-card",value:M?.effort??"",onChange:x=>Ge(x||null),options:[{value:"",label:is?Ce("composer.defaultEffortNamed",{level:bf(is)}):y("composer.defaultEffort")},...Ot.filter(x=>x.id!=="default").map(x=>({value:x.id,label:bf(x.id,x.label)}))],children:[(0,Y.jsx)(ye,{name:"gauge",size:14}),(0,Y.jsx)("span",{className:"ip-l",children:(()=>{let x=M?.effort??is;return x?bf(x,Ot.find(W=>W.id===x)?.label):y("composer.defaultEffort")})()})]}),$.length>1&&(()=>{let x=$.find(W=>W.id===R)??$[0];return(0,Y.jsxs)(Ln,{className:`pill ipill${x.danger?" danger":""}`,title:x.desc,ariaLabel:y("composer.modeTitle"),prefer:"up",upAnchor:".cp-card",menuClassName:"mode-menu",value:x.id,onChange:W=>ts(W),options:$.map(W=>({value:W.id,label:W.label,hint:W.desc,danger:W.danger})),children:[(0,Y.jsx)(ye,{name:"shield",size:14}),(0,Y.jsx)("span",{className:"ip-l",children:x.label})]})})(),M?.provider==="cursor"&&(0,Y.jsx)(Ln,{className:"pill ipill cursor-fast",title:"Fast",ariaLabel:"Fast",prefer:"up",upAnchor:".cp-card",value:M.cursorFast?"fast":"off",onChange:x=>Ue({cursorFast:x==="fast"}),options:[{value:"off",label:"Fast: Off"},{value:"fast",label:"Fast: On"}],children:(0,Y.jsx)("span",{className:"ip-l",children:M.cursorFast?"Fast: On":"Fast: Off"})}),(0,Y.jsx)("span",{className:"cp-div","aria-hidden":"true"}),(0,Y.jsx)("button",{className:"ibtn cp-attach",title:y("composer.attachTitle"),onClick:()=>w.current?.click(),children:(0,Y.jsx)(ye,{name:"attach"})}),(0,Y.jsx)("input",{ref:w,type:"file",hidden:!0,multiple:!0,accept:"image/*,.txt,.md,.log,.json,.csv",onChange:x=>{for(let W of x.target.files??[])hi(W);x.target.value=""}}),(0,Y.jsx)("div",{className:"cp-right",children:E?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsxs)("span",{className:"cp-clock",children:[v,"s"]}),(s.trim()||a.length>0)&&(0,Y.jsx)("button",{className:"cp-send",title:y(C&&P.runningSend==="steer"?"settings.steer":"settings.queue"),disabled:I||a.some(x=>x.uploading),onClick:()=>{ci(P.runningSend==="steer"&&C?"steer":"queue")},children:(0,Y.jsx)(ye,{name:"arrowUp"})}),(0,Y.jsx)("button",{className:"cp-stop",title:y("common.stop"),onClick:()=>{te.call("thread.interrupt",{id:M?.id})},children:(0,Y.jsx)(ye,{name:"stopFill"})})]}):(0,Y.jsx)("button",{className:"cp-send",title:y("common.send"),disabled:I||!s.trim()&&a.length===0||a.some(x=>x.uploading),onClick:()=>{ci("queue")},children:(0,Y.jsx)(ye,{name:"arrowUp"})})})]})]}),E&&!C&&P.runningSend==="steer"&&(0,Y.jsx)("div",{className:"cp-hint",children:Ce("composer.steerUnsupported",{agent:B?.name??M?.provider??""})})]}):null}var $e,Y,Ev,_N=le(()=>{$e=ae(Nt(),1);pl();dn();jn();Ml();Rn();pf();Wr();gf();Vn();yf();vv();cN();vf();Ci();mN();Y=ae(ke(),1),Ev=150});function bN(){let e=fe(),{projects:t,threads:i}=ut(),n=Dn(),r=ou().showThinking?n.items:n.items.filter(T=>T.kind!=="reasoning"),a=(0,Bn.useRef)(null),[o,l]=(0,Bn.useState)(!0),[c,u]=(0,Bn.useState)(!1),h=t.find(T=>T.id===e.currentProjectId)??null,d=e.currentThreadId,f=d?i.find(T=>T.id===d)??null:null,p=h&&f&&f.projectId===h.id?f.id:null;(0,Bn.useEffect)(()=>{p?n.open(p):n.close(),l(!0),u(!1)},[p]);let _=(0,Bn.useCallback)(T=>{let D=r[T];if(!D)return 80;switch(D.kind){case"user":return 60;case"assistant":case"reasoning":return 120;case"toolgroup":return 30+D.steps.length*26;case"plan":return 200;case"permission":case"question":return 120;case"todo":return 30;case"turnend":case"notice":return 30;default:return 60}},[r]),w=FT({count:r.length,getScrollElement:()=>a.current,estimateSize:_,getItemKey:T=>r[T]?.key??T,overscan:8,measureElement:T=>T.getBoundingClientRect().height}),g=r.length;(0,Bn.useEffect)(()=>{let T=a.current;T&&(o?T.scrollTop=T.scrollHeight:u(!0))},[g,o]);let m=()=>{let T=a.current;if(!T)return;let D=T.scrollHeight-T.scrollTop-T.clientHeight<60;l(D),D&&u(!1)},v=()=>{a.current?.scrollTo({top:a.current.scrollHeight,behavior:"smooth"}),l(!0),u(!1)},S=T=>{p&&te.call("thread.send",{id:p,text:T})},k=()=>{n.lastUserText&&S(n.lastUserText)};if(t.length===0)return(0,Pe.jsx)("div",{className:"scroll",ref:a,children:(0,Pe.jsx)(vN,{kind:"no-projects"})});if(!p)return(0,Pe.jsx)("div",{className:"scroll",ref:a,children:h?(0,Pe.jsxs)("div",{className:"empty-wrap",children:[(0,Pe.jsx)("div",{className:"cp-hero-t",children:Ce("chat.newInProject",{name:h.name})}),(0,Pe.jsx)(Oz,{projectId:h.id})]}):(0,Pe.jsx)(vN,{kind:"pick-project"})});let A=-1;for(let T=r.length-1;T>=0;T--)if(r[T].kind==="turnend"){A=T;break}let O=T=>{let D=[];for(let F=T-1;F>=0;F--){let P=r[F];if(P.kind==="user"||P.kind==="turnend")break;P.kind==="assistant"&&D.unshift(P.text)}return D.join(` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${wn(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,text:i,tokens:n,autolink:r}){let s=r?wn(i,!0):this.parser.parseInline(n),a=cC(e);if(a===null)return s;e=wn(a,r);let o='
    ",o}image({href:e,title:t,text:i,tokens:n}){n&&(i=this.parser.parseInline(n,this.parser.textRenderer));let r=cC(e);if(r===null)return wn(i);e=r;let s=`${wn(i)}{let a=r[s].flat(1/0);Qa(i,this.walkTokens(a,t))}):r.tokens&&Qa(i,this.walkTokens(r.tokens,t))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let n={...i};if(n.async=this.defaults.async||n.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let s=t.renderers[r.name];s?t.renderers[r.name]=function(...a){let o=r.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[r.level];s?s.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),n.extensions=t),i.renderer){let r=this.defaults.renderer||new _f(this.defaults);for(let s in i.renderer){if(!(s in r))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,o=i.renderer[a],l=r[a];r[a]=(...c)=>{let u=o.apply(r,c);return u===!1&&(u=l.apply(r,c)),u||""}}n.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Ml(this.defaults);for(let s in i.tokenizer){if(!(s in r))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,o=i.tokenizer[a],l=r[a];r[a]=(...c)=>{let u=o.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}n.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new lu;for(let s in i.hooks){if(!(s in r))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,o=i.hooks[a],l=r[a];lu.passThroughHooks.has(s)?r[a]=c=>{if(r.options.async&&lu.passThroughHooksRespectAsync.has(s))return(async()=>{let h=await o.call(r,c);return l.call(r,h)})();let u=o.call(r,c);return l.call(r,u)}:r[a]=(...c)=>{if(r.options.async)return(async()=>{let h=await o.apply(r,c);return h===!1&&(h=await l.apply(r,c)),h})();let u=o.apply(r,c);return u===!1&&(u=l.apply(r,c)),u}}n.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,s=i.walkTokens;n.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),r&&Qa(o,r.call(this,a)),o}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ar.lex(e,t??this.defaults)}parser(e,t){return or.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let n={...i},r={...this.defaults,...n},s=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&n.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let a=r.hooks?await r.hooks.preprocess(t):t,o=await(r.hooks?await r.hooks.provideLexer(e):e?ar.lex:ar.lexInline)(a,r),l=r.hooks?await r.hooks.processAllTokens(o):o;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(e):e?or.parse:or.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(s);try{r.hooks&&(t=r.hooks.preprocess(t));let a=(r.hooks?r.hooks.provideLexer(e):e?ar.lex:ar.lexInline)(t,r);r.hooks&&(a=r.hooks.processAllTokens(a)),r.walkTokens&&this.walkTokens(a,r.walkTokens);let o=(r.hooks?r.hooks.provideParser(e):e?or.parse:or.parseInline)(a,r);return r.hooks&&(o=r.hooks.postprocess(o)),o}catch(a){return s(a)}}}onError(e,t){return i=>{if(i.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let n="

    An error occurred:

    "+wn(i.message+"",!0)+"
    ";return t?Promise.resolve(n):n}if(t)return Promise.reject(i);throw i}}},to=new SI;Ze.options=Ze.setOptions=function(e){return to.setOptions(e),Ze.defaults=to.defaults,mC(Ze.defaults),Ze};Ze.getDefaults=fv;Ze.defaults=io;Ze.use=wI;Ze.walkTokens=function(e,t){return to.walkTokens(e,t)};Ze.parseInline=to.parseInline;Ze.Parser=or;Ze.parser=or.parse;Ze.Renderer=_f;Ze.TextRenderer=yv;Ze.Lexer=ar;Ze.lexer=ar.lex;Ze.Tokenizer=Ml;Ze.Hooks=lu;Ze.parse=Ze;m8=Ze.options,g8=Ze.setOptions,_8=Ze.walkTokens,v8=Ze.parseInline,b8=or.parse,y8=ar.lex});function xI(e,t){this.v=e,this.k=t}function TC(e,t){(t==null||t>e.length)&&(t=e.length);for(var i=0,n=Array(t);i1?i-1:0),r=1;r2&&arguments[2]!==void 0?arguments[2]:no;if(NC&&NC(e,null),!Ll(t))return e;let n=t.length;for(;n--;){let r=t[n];if(typeof r=="string"){let s=i(r);s!==r&&(AI(t)||(t[n]=s),r=s)}e[r]=!0}return e}function BI(e){for(let t=0;t0&&arguments[0]!==void 0?arguments[0]:JI(),t=G=>jC(G);if(t.version="3.4.17",t.removed=[],!e||!e.document||e.document.nodeType!==qt.document||!e.Element)return t.isSupported=!1,t;let i=e.document,n=i,r=n.currentScript;e.DocumentFragment;let s=e.HTMLTemplateElement,a=e.Node,o=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let c=e.DOMParser,u=e.trustedTypes,h=o.prototype,d=Wn(h,"cloneNode"),f=Wn(h,"remove"),p=Wn(h,"removeAttributeNode"),_=Wn(h,"nextSibling"),S=Wn(h,"childNodes"),m=Wn(h,"parentNode"),g=Wn(h,"shadowRoot"),b=Wn(h,"attributes"),w=a&&a.prototype?Wn(a.prototype,"nodeType"):null,E=a&&a.prototype?Wn(a.prototype,"nodeName"):null,A=a&&a.prototype?Wn(a.prototype,"ownerDocument"):null,O=function(y){return w?w(y):y.nodeType},k=function(y){return E?E(y):y.nodeName},D=PI(h,"namespaceURI"),L=function(y){return D?D(y):y.namespaceURI};if(typeof s=="function"){let G=i.createElement("template");G.content&&G.content.ownerDocument&&(i=G.content.ownerDocument)}let P,I="",B,x=!1,z=0,C=function(){if(z>0)throw fs('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},N=function(y){C(),z++;try{return P.createHTML(y)}finally{z--}},R=function(y){C(),z++;try{return P.createScriptURL(y)}finally{z--}},W=function(){return x||(B=eB(u,r),x=!0),B},X=i,U=X.implementation,Q=X.createNodeIterator,Ee=X.createDocumentFragment,he=X.getElementsByTagName,Ke=n.importNode,J=FC();t.isSupported=typeof qC=="function"&&typeof m=="function"&&U&&U.createHTMLDocument!==void 0;let je=qI,Ai=KI,$t=WI,mi=$I,gi=GI,Bt=jI,me=YI,un=XI,zt=PC,ce=null,zi=qe({},[...LC,...Ev,...Cv,...kv,...IC]),ie=null,Pi=qe({},[...BC,...Tv,...zC,...bf]),Ye=Object.seal(Dl(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Fe=null,An=null,Gt=Object.seal(Dl(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),qr=!0,Kr=!0,te=!1,oe=!0,ge=!1,Ae=!0,tt=!1,_i=!1,ws=null,xs=null,T=!1,ee=!1,ue=!1,Ce=!1,it=!0,hr=!1,vo="user-content-",xp=!0,Ep=!1,ba=null,bo={},ya=null,E0=qe({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),C0=null,k0=qe({},["audio","video","img","source","image","track"]),T0=null,N0=qe({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),eh="http://www.w3.org/1998/Math/MathML",th="http://www.w3.org/2000/svg",dr="http://www.w3.org/1999/xhtml",yo=dr,Cp=!1,kp=null,qR=qe({},[eh,th,dr],xv),A0=ai(["mi","mo","mn","ms","mtext"]),Tp=qe({},A0),M0=ai(["annotation-xml"]),Np=qe({},M0),KR=qe({},["title","style","font","a","script"]),Xl=null,WR=["application/xhtml+xml","text/html"],$R="text/html",Ot=null,So=null,GR=i.createElement("form"),R0=function(y){return y instanceof RegExp||y instanceof Function},Ap=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(So&&So===y)return;(!y||typeof y!="object")&&(y={}),y=xn(y),Xl=WR.indexOf(y.PARSER_MEDIA_TYPE)===-1?$R:y.PARSER_MEDIA_TYPE,Ot=Xl==="application/xhtml+xml"?xv:no,ce=oa(y,"ALLOWED_TAGS",zi,{transform:Ot}),ie=oa(y,"ALLOWED_ATTR",Pi,{transform:Ot}),kp=oa(y,"ALLOWED_NAMESPACES",qR,{transform:xv}),T0=oa(y,"ADD_URI_SAFE_ATTR",N0,{transform:Ot,base:N0}),C0=oa(y,"ADD_DATA_URI_TAGS",k0,{transform:Ot,base:k0}),ya=oa(y,"FORBID_CONTENTS",E0,{transform:Ot}),Fe=oa(y,"FORBID_TAGS",xn({}),{transform:Ot}),An=oa(y,"FORBID_ATTR",xn({}),{transform:Ot}),bo=on(y,"USE_PROFILES")?y.USE_PROFILES&&typeof y.USE_PROFILES=="object"?xn(y.USE_PROFILES):y.USE_PROFILES:!1,qr=y.ALLOW_ARIA_ATTR!==!1,Kr=y.ALLOW_DATA_ATTR!==!1,te=y.ALLOW_UNKNOWN_PROTOCOLS||!1,oe=y.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ge=y.SAFE_FOR_TEMPLATES||!1,Ae=y.SAFE_FOR_XML!==!1,tt=y.WHOLE_DOCUMENT||!1,ee=y.RETURN_DOM||!1,ue=y.RETURN_DOM_FRAGMENT||!1,Ce=y.RETURN_TRUSTED_TYPE||!1,T=y.FORCE_BODY||!1,it=y.SANITIZE_DOM!==!1,hr=y.SANITIZE_NAMED_PROPS||!1,xp=y.KEEP_CONTENT!==!1,Ep=y.IN_PLACE||!1,zt=UI(y.ALLOWED_URI_REGEXP)?y.ALLOWED_URI_REGEXP:PC,yo=typeof y.NAMESPACE=="string"?y.NAMESPACE:dr,Tp=Av(y,"MATHML_TEXT_INTEGRATION_POINTS",()=>qe({},A0)),Np=Av(y,"HTML_INTEGRATION_POINTS",()=>qe({},M0));let M=Av(y,"CUSTOM_ELEMENT_HANDLING",()=>Dl(null));if(Ye=Dl(null),on(M,"tagNameCheck")&&R0(M.tagNameCheck)&&(Ye.tagNameCheck=M.tagNameCheck),on(M,"attributeNameCheck")&&R0(M.attributeNameCheck)&&(Ye.attributeNameCheck=M.attributeNameCheck),on(M,"allowCustomizedBuiltInElements")&&typeof M.allowCustomizedBuiltInElements=="boolean"&&(Ye.allowCustomizedBuiltInElements=M.allowCustomizedBuiltInElements),Ti(Ye),ge&&(Kr=!1),ue&&(ee=!0),bo&&(ce=qe({},IC),ie=Dl(null),bo.html===!0&&(qe(ce,LC),qe(ie,BC)),bo.svg===!0&&(qe(ce,Ev),qe(ie,Tv),qe(ie,bf)),bo.svgFilters===!0&&(qe(ce,Cv),qe(ie,Tv),qe(ie,bf)),bo.mathMl===!0&&(qe(ce,kv),qe(ie,zC),qe(ie,bf))),Gt.tagCheck=null,Gt.attributeCheck=null,on(y,"ADD_TAGS")&&(typeof y.ADD_TAGS=="function"?Gt.tagCheck=y.ADD_TAGS:Ll(y.ADD_TAGS)&&(ce===zi&&(ce=xn(ce)),qe(ce,y.ADD_TAGS,Ot))),on(y,"ADD_ATTR")&&(typeof y.ADD_ATTR=="function"?Gt.attributeCheck=y.ADD_ATTR:Ll(y.ADD_ATTR)&&(ie===Pi&&(ie=xn(ie)),qe(ie,y.ADD_ATTR,Ot))),on(y,"ADD_FORBID_CONTENTS")&&Ll(y.ADD_FORBID_CONTENTS)&&(ya===E0&&(ya=xn(ya)),qe(ya,y.ADD_FORBID_CONTENTS,Ot)),xp&&(ce["#text"]=!0),tt&&qe(ce,["html","head","body"]),ce.table&&(qe(ce,["tbody"]),delete Fe.tbody),y.TRUSTED_TYPES_POLICY){if(typeof y.TRUSTED_TYPES_POLICY.createHTML!="function")throw fs('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof y.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw fs('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let q=P;P=y.TRUSTED_TYPES_POLICY;try{I=N("")}catch(K){throw P=q,K}}else y.TRUSTED_TYPES_POLICY===null?(P=void 0,I=""):(P===void 0&&(P=W()),P&&typeof I=="string"&&(I=N("")));ai&&ai(y),So=y},O0=qe({},[...Ev,...Cv,...HI]),D0=qe({},[...kv,...FI]),jR=function(y,M,q){return M.namespaceURI===dr?y==="svg":M.namespaceURI===eh?y==="svg"&&(q==="annotation-xml"||Tp[q]):!!O0[y]},YR=function(y,M,q){return M.namespaceURI===dr?y==="math":M.namespaceURI===th?y==="math"&&Np[q]:!!D0[y]},VR=function(y,M,q){return M.namespaceURI===th&&!Np[q]||M.namespaceURI===eh&&!Tp[q]?!1:!D0[y]&&(KR[y]||!O0[y])},XR=function(y){let M=L(y),q=no(k(y)),K=m(y),de,_e;return K&&O(K)===qt.element?(de={namespaceURI:L(K)},_e=no(k(K))):(de={namespaceURI:yo},_e="template"),kp[M]?M===th?jR(q,de,_e):M===eh?YR(q,de,_e):M===dr?VR(q,de,_e):!!(Xl==="application/xhtml+xml"&&kp[M]):!1},Es=function(y){du(t.removed,{element:y});try{m(y).removeChild(y)}catch{if(f(y),!m(y))throw fs("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},L0=function(y,M,q){try{p(y,M)}catch{try{y.removeAttribute(q)}catch{}}},Mp=function(y){Op(y);let M=S(y);M&&ds(RI(M),K=>{try{f(K)}catch{}});let q=O(y)===qt.element?b(y):null;if(q)for(let K=q.length-1;K>=0;--K){let de=q[K],_e=de&&de.name;typeof _e=="string"&&L0(y,de,_e)}},wo=function(y,M,q){if(!q)try{q=M.getAttributeNode(y)}catch{q=null}du(t.removed,{attribute:q||null,from:M});try{q?p(M,q):M.removeAttribute(y)}catch{try{M.removeAttribute(y)}catch{}}if(y==="is")if(ee||ue)try{Es(M)}catch{}else try{M.setAttribute(y,"")}catch{}},I0=function(y){let M=b(y);if(M)for(let q=M.length-1;q>=0;--q){let K=M[q],de=K&&K.name;typeof de!="string"||ie[Ot(de)]||L0(y,K,de)}},Rp=function(y,M){let q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,K=[y];for(;K.length>0;){let de=K.pop();if(M(de)===!1)continue;if(q&&O(de)===qt.element){let Ie=g(de);Cs(Ie)&&K.push(Ie)}let _e=S(de);if(_e)for(let Ie=_e.length-1;Ie>=0;--Ie)K.push(_e[Ie])}},Op=function(y){Rp(y,M=>{O(M)===qt.element&&I0(M)})},Dp=function(y){let M=[];return Rp(y,q=>{M.push(q)},!0),M},ZR=function(y,M){let q=Sv();ds(Dp(y),K=>{O(K)===qt.element&&wv(q,K)}),ds(M,K=>{O(K)===qt.element&&!fu(q,K)&&I0(K)})},B0=function(y,M){let q=!1;return ds(t.removed,K=>{K.element&&(q=q||K.element===y,Op(K.element))}),ZR(y,M),q},QR=8,JR=function(y,M){let q=ba,K=null,de=()=>(K||(K=Sv(),ds(M,_e=>{wv(K,_e)})),K);for(let _e=0;;_e++){let Ie=Dp(y),jt=[y],fr=!1;if(ds(Ie,Ui=>{O(Ui)===qt.documentFragment?du(jt,Ui):!fr&&!fu(q,Ui)&&(fr=fu(de(),Ui))}),!fr)return;if(_e>=QR)throw fs("the tree kept changing during in-place sanitization; refusing to return it");ds(jt,(Ui,Vi)=>{eO(Ui,Vi>0,y,de())})}},eO=function(y,M,q,K){let de=Lp(y),_e;for(;_e=de.nextNode();)!fu(K,_e)||fu(ba,_e)||(M&&Jn(J.uponSanitizeShadowNode,_e,null),Bp(_e,q),zp(_e,q),Cs(_e.content)&&Ql(_e.content))},tO=function(y){ba&&wv(ba,y)},z0=function(y,M){return Ae?y==="patchsrc"?!0:y==="for"&&M!=="label"&&M!=="output":!1},iO=function(y){Ae&&Rp(y,M=>{let q=O(M);if(q===qt.processingInstruction||q===qt.comment&&ki(UC,M.data)){try{f(M)}catch{}return!1}if(q===qt.element){let K=M,de=Ot(k(M));try{K.hasAttribute&&K.hasAttribute("patchsrc")&&K.removeAttribute("patchsrc"),K.hasAttribute&&K.hasAttribute("for")&&z0("for",de)&&K.removeAttribute("for")}catch{}}return!0})},P0=function(y){let M=null,q=null;if(T)y=""+y;else{let _e=MC(y,/^[\r\n\t ]+/);q=_e&&_e[0]}Xl==="application/xhtml+xml"&&yo===dr&&(y=''+y+"");let K=P?N(y):y;if(yo===dr)try{M=new c().parseFromString(K,Xl)}catch{}if(!M||!M.documentElement){M=U.createDocument(yo,"template",null);try{M.documentElement.innerHTML=Cp?I:K}catch{}}let de=M.body||M.documentElement;return y&&q&&de.insertBefore(i.createTextNode(q),de.childNodes[0]||null),yo===dr?he.call(M,tt?"html":"body")[0]:tt?M.documentElement:de},Lp=function(y){let M=A?A(y):y.ownerDocument;return Q.call(M||y,y,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ih=function(y){return y=pu(y,je," "),y=pu(y,Ai," "),y=pu(y,$t," "),y},Ip=function(y){var M;U0(y);let q=(M=y.querySelectorAll)===null||M===void 0?void 0:M.call(y,"template");q&&ds(q,K=>{Cs(K.content)&&Ip(K.content)})},U0=function(y){y.normalize();let M=A?A(y):y.ownerDocument,q=Q.call(M||y,y,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),K=q.nextNode();for(;K;)K.data=ih(K.data),K=q.nextNode()},nh=function(y){let M=E?E(y):null;return typeof M!="string"||Ot(M)!=="form"?!1:typeof y.nodeName!="string"||typeof y.textContent!="string"||typeof y.removeChild!="function"||y.attributes!==b(y)||typeof y.removeAttribute!="function"||typeof y.removeAttributeNode!="function"||typeof y.getAttributeNode!="function"||typeof y.setAttribute!="function"||typeof y.namespaceURI!="string"||typeof y.insertBefore!="function"||typeof y.hasChildNodes!="function"||y.nodeType!==w(y)||y.childNodes!==S(y)},Cs=function(y){if(!w||typeof y!="object"||y===null)return!1;try{return w(y)===qt.documentFragment}catch{return!1}},Zl=function(y){if(!w||typeof y!="object"||y===null)return!1;try{return typeof w(y)=="number"}catch{return!1}};function Jn(G,y,M){G.length!==0&&ds(G,q=>{q.call(t,y,M,So)})}let nO=function(y,M){return!!(Ae&&y.hasChildNodes()&&!Zl(y.firstElementChild)&&ki(Nv,y.textContent)&&ki(Nv,y.innerHTML)||Ae&&QI[M]&&O(y)===qt.element&&L(y)===dr&&(Zl(y.firstElementChild)||typeof y.textContent=="string"&&ki(Nv,y.textContent))||y.nodeType===qt.processingInstruction||Ae&&y.nodeType===qt.comment&&ki(UC,y.data))},rh=function(y,M){if(y instanceof RegExp)return ki(y,M);if(y instanceof Function){for(var q=arguments.length,K=new Array(q>2?q-2:0),de=2;de=0;--Ie){let jt=y===q?d(de[Ie],!0):de[Ie];K.insertBefore(jt,_(y))}}}return Es(y),!0},H0=function(y,M,q,K){return y.length===0?M:M===q||M===K?xn(M):M},xo=function(y,M){return y===M||m(y)!==null?!1:(Ep&&Op(y),!0)},Bp=function(y,M){if(tO(y),Jn(J.beforeSanitizeElements,y,null),xo(y,M))return!0;if(nh(y))return Es(y),!0;let q=Ot(k(y));if(ce=H0(J.uponSanitizeElement,ce,zi,ws),Jn(J.uponSanitizeElement,y,{tagName:q,allowedTags:ce}),xo(y,M))return!0;if(nO(y,q))return Es(y),!0;if(Fe[q]||!(Gt.tagCheck instanceof Function&&Gt.tagCheck(q))&&!ce[q]){let K=rO(y,q,M);return K===!1&&(Jn(J.afterSanitizeElements,y,null),xo(y,M))?!0:K}if(O(y)===qt.element&&!XR(y)||(q==="noscript"||q==="noembed"||q==="noframes")&&ki(ZI,y.innerHTML))return Es(y),!0;if(ge&&y.nodeType===qt.text){let K=ih(y.textContent);y.textContent!==K&&(du(t.removed,{element:y.cloneNode()}),y.textContent=K)}return Jn(J.afterSanitizeElements,y,null),xo(y,M)},F0=function(y,M,q){if(An[M]||z0(M,y)||it&&(M==="id"||M==="name")&&(q in i||q in GR))return!1;let K=ie[M]||Gt.attributeCheck instanceof Function&&Gt.attributeCheck(M,y);return Kr&&ki(mi,M)||qr&&ki(gi,M)?!0:K?T0[M]||ki(zt,pu(q,me,""))||(M==="src"||M==="xlink:href"||M==="href")&&y!=="script"&&RC(q,"data:")===0&&C0[y]||te&&!ki(Bt,pu(q,me,""))?!0:!q:q0(y)&&rh(Ye.tagNameCheck,y)&&rh(Ye.attributeNameCheck,M,y)||M==="is"&&Ye.allowCustomizedBuiltInElements&&rh(Ye.tagNameCheck,q)},sO=qe({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),q0=function(y){return!sO[no(y)]&&ki(un,y)},aO=function(y,M,q,K){if(P&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!q)switch(u.getAttributeType(y,M)){case"TrustedHTML":return N(K);case"TrustedScriptURL":return R(K)}return K},oO=function(y,M,q,K){try{return q?y.setAttributeNS(q,M,K):y.setAttribute(M,K),nh(y)?(Es(y),!1):!0}catch{return wo(M,y),!1}},K0=function(y,M){return Ae&&ki(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,M)?!0:no(y)==="attributename"&&MC(M,"href")!==null},zp=function(y,M){if(Jn(J.beforeSanitizeAttributes,y,null),xo(y,M))return;let q=y.attributes;if(!q||nh(y))return;ie=H0(J.uponSanitizeAttribute,ie,Pi,xs);let K={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ie,forceKeepAttr:void 0},de=q.length,_e=Ot(y.nodeName);for(;de--;){let Ie=q[de],jt=Ie.name,fr=Ie.namespaceURI,Ui=Ie.value,Vi=Ot(jt),Eo=Ui,Xi=jt==="value"?Eo:DI(Eo),W0=!1;if(K.attrName=Vi,K.attrValue=Xi,K.keepAttr=!0,K.forceKeepAttr=void 0,Jn(J.uponSanitizeAttribute,y,K),Xi=K.attrValue,hr&&(Vi==="id"||Vi==="name")&&RC(Xi,vo)!==0&&(wo(jt,y,Ie),Xi=vo+Xi,W0=!0),K0(jt,Xi)){wo(jt,y,Ie);continue}if(!K.forceKeepAttr){if(!K.keepAttr){wo(jt,y,Ie);continue}if(!oe&&ki(HC,Xi)){wo(jt,y,Ie);continue}if(ge&&(Xi=ih(Xi)),!F0(_e,Vi,Xi)){wo(jt,y,Ie);continue}Xi=aO(_e,Vi,fr,Xi),Xi!==Eo&&oO(y,jt,fr,Xi)&&W0&&AC(t.removed)}}Jn(J.afterSanitizeAttributes,y,null),xo(y,M)},Ql=function(y){let M=null,q=Lp(y);for(Jn(J.beforeSanitizeShadowDOM,y,null);M=q.nextNode();)if(Jn(J.uponSanitizeShadowNode,M,null),Bp(M,y),zp(M,y),Cs(M.content)&&Ql(M.content),O(M)===qt.element){let K=g(M);Cs(K)&&(Pp(K),Ql(K))}ge&&U0(y),Jn(J.afterSanitizeShadowDOM,y,null)},Pp=function(y){let M=[{node:y,shadow:null}];for(;M.length>0;){let q=M.pop();if(q.shadow){Ql(q.shadow);continue}let K=q.node,de=O(K)===qt.element,_e=S(K);if(_e)for(let Ie=_e.length-1;Ie>=0;--Ie)M.push({node:_e[Ie],shadow:null});if(de){let Ie=E?E(K):null;if(typeof Ie=="string"&&Ot(Ie)==="template"){let jt=K.content;Cs(jt)&&M.push({node:jt,shadow:null})}}if(de){let Ie=g(K);Cs(Ie)&&M.push({node:null,shadow:Ie},{node:Ie,shadow:null})}}};return t.sanitize=function(G){let y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,q=null,K=null,de=null;if(Cp=!G,Cp&&(G=""),typeof G!="string"&&!Zl(G)&&(G=zI(G),typeof G!="string"))throw fs("dirty is not a string, aborting");if(!t.isSupported)return G;_i?(ce=ws,ie=xs):Ap(y),(J.uponSanitizeElement.length>0||J.uponSanitizeAttribute.length>0)&&(ce=xn(ce)),J.uponSanitizeAttribute.length>0&&(ie=xn(ie)),t.removed=[];let _e=Ep&&typeof G!="string"&&Zl(G),Ie=[],jt=ba;if(_e){iO(G);let Vi=k(G);if(typeof Vi=="string"){let Eo=Ot(Vi);if(!ce[Eo]||Fe[Eo])throw Mp(G),fs("root node is forbidden and cannot be sanitized in-place")}if(nh(G))throw Mp(G),fs("root node is clobbered and cannot be sanitized in-place");Ie=Dp(G),ba=Sv()}else if(Zl(G))M=P0(""),q=M.ownerDocument.importNode(G,!0),q.nodeType===qt.element&&q.nodeName==="BODY"||q.nodeName==="HTML"?M=q:M.appendChild(q),Pp(M);else{if(!ee&&!ge&&!tt&&G.indexOf("<")===-1)return P&&Ce?N(G):G;if(M=P0(G),!M)return ee?null:Ce?I:""}M&&T&&Es(M.firstChild);let fr=_e?G:M;try{_e&&Pp(G);let Vi=Lp(fr);for(;K=Vi.nextNode();)Bp(K,fr),zp(K,fr),Cs(K.content)&&Ql(K.content);_e&&JR(G,Ie)}catch(Vi){throw _e&&(Mp(G),B0(G,Ie)),Vi}finally{ba=jt}if(_e){if(B0(G,Ie))throw fs("a node selected for removal could not be safely returned; refusing to sanitize in place");return ge&&Ip(G),G}if(ee){if(ge&&Ip(M),ue)for(de=Ee.call(M.ownerDocument);M.firstChild;)de.appendChild(M.firstChild);else de=M;return(ie.shadowroot||ie.shadowrootmode)&&(de=Ke.call(n,de,!0)),de}let Ui=tt?M.outerHTML:M.innerHTML;return tt&&ce["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&ki(VI,M.ownerDocument.doctype.name)&&(Ui=" +`+Ui),ge&&(Ui=ih(Ui)),P&&Ce?N(Ui):Ui},t.setConfig=function(){let G=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ap(G),_i=!0,ws=ce,xs=ie},t.clearConfig=function(){So=null,_i=!1,ws=null,xs=null,P=B,I=""},t.isValidAttribute=function(G,y,M){So||Ap({});let q=Ot(G),K=Ot(y);return typeof M=="string"&&(K0(y,M)||!oe&&ki(HC,M))?!1:F0(q,K,M)},t.addHook=function(G,y){typeof y=="function"&&on(J,G)&&du(J[G],y)},t.removeHook=function(G,y){if(on(J,G)){if(y!==void 0){let M=MI(J[G],y);return M===-1?void 0:OI(J[G],M,1)[0]}return AC(J[G])}},t.removeHooks=function(G){on(J,G)&&(J[G]=[])},t.removeAllHooks=function(){J=FC()},t}var qC,NC,AI,KC,WC,ai,Ti,Dl,$C,Mv,Rv,ds,MI,AC,du,RI,OI,Ll,Sv,wv,fu,no,xv,MC,pu,RC,DI,LI,II,OC,DC,on,mu,ki,fs,LC,Ev,Cv,HI,kv,FI,IC,BC,Tv,zC,bf,qI,KI,WI,$I,GI,PC,jI,YI,VI,XI,Nv,UC,ZI,HC,qt,QI,JI,eB,FC,oa,Av,YC,VC=se(()=>{vf.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},vf.prototype.next=function(e){return this._invoke("next",e)},vf.prototype.throw=function(e){return this._invoke("throw",e)},vf.prototype.return=function(e){return this._invoke("return",e)};qC=Object.entries,NC=Object.setPrototypeOf,AI=Object.isFrozen,KC=Object.getPrototypeOf,WC=Object.getOwnPropertyDescriptor,ai=Object.freeze,Ti=Object.seal,Dl=Object.create,$C=typeof Reflect<"u"&&Reflect,Mv=$C.apply,Rv=$C.construct;ai||(ai=function(t){return t});Ti||(Ti=function(t){return t});Mv||(Mv=function(t,i){for(var n=arguments.length,r=new Array(n>2?n-2:0),s=2;s1?i-1:0),r=1;r"u"?null:wt(BigInt.prototype.toString),DC=typeof Symbol>"u"?null:wt(Symbol.prototype.toString),on=wt(Object.prototype.hasOwnProperty),mu=wt(Object.prototype.toString),ki=wt(RegExp.prototype.test),fs=GC(TypeError);LC=ai(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ev=ai(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Cv=ai(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),HI=ai(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),kv=ai(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),FI=ai(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),IC=ai(["#text"]),BC=ai(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Tv=ai(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","pointer-events","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","vector-effect","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),zC=ai(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),bf=ai(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),qI=Ti(/{{[\w\W]*|^[\w\W]*}}/g),KI=Ti(/<%[\w\W]*|^[\w\W]*%>/g),WI=Ti(/\${[\w\W]*/g),$I=Ti(/^data-[\-\w.\u00B7-\uFFFF]+$/),GI=Ti(/^aria-[\-\w]+$/),PC=Ti(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),jI=Ti(/^(?:\w+script|data):/i),YI=Ti(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),VI=Ti(/^html$/i),XI=Ti(/^[a-z][.\w]*(-[.\w]+)+$/i),Nv=Ti(/<[/\w!]/g),UC=Ti(/<[/\w]/g),ZI=Ti(/<\/no(script|embed|frames)/i),HC=Ti(/\/>/i),qt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},QI=ai(qe({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),JI=function(){return typeof window>"u"?null:window},eB=function(t,i){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null,r="data-tt-policy-suffix";i&&i.hasAttribute(r)&&(n=i.getAttribute(r));let s="dompurify"+(n?"#"+n:"");try{return t.createPolicy(s,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},FC=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},oa=function(t,i,n,r){return on(t,i)&&Ll(t[i])?qe(r.base?xn(r.base):{},t[i],r.transform):n},Av=function(t,i,n){let r=on(t,i)?t[i]:void 0;return r&&typeof r=="object"?xn(r):n()};YC=jC()});var mk=ve((A8,pk)=>{function ik(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw new Error("map is read-only")}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw new Error("set is read-only")}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{let i=e[t],n=typeof i;(n==="object"||n==="function")&&!Object.isFrozen(i)&&ik(i)}),e}var Sf=class{constructor(t){t.data===void 0&&(t.data={}),this.data=t.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}};function nk(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function la(e,...t){let i=Object.create(null);for(let n in e)i[n]=e[n];return t.forEach(function(n){for(let r in n)i[r]=n[r]}),i}var tB="",XC=e=>!!e.scope,iB=(e,{prefix:t})=>{if(e.startsWith("language:"))return e.replace("language:","language-");if(e.includes(".")){let i=e.split(".");return[`${t}${i.shift()}`,...i.map((n,r)=>`${n}${"_".repeat(r+1)}`)].join(" ")}return`${t}${e}`},Dv=class{constructor(t,i){this.buffer="",this.classPrefix=i.classPrefix,t.walk(this)}addText(t){this.buffer+=nk(t)}openNode(t){if(!XC(t))return;let i=iB(t.scope,{prefix:this.classPrefix});this.span(i)}closeNode(t){XC(t)&&(this.buffer+=tB)}value(){return this.buffer}span(t){this.buffer+=``}},ZC=(e={})=>{let t={children:[]};return Object.assign(t,e),t},Lv=class e{constructor(){this.rootNode=ZC(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(t){this.top.children.push(t)}openNode(t){let i=ZC({scope:t});this.add(i),this.stack.push(i)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(t){return this.constructor._walk(t,this.rootNode)}static _walk(t,i){return typeof i=="string"?t.addText(i):i.children&&(t.openNode(i),i.children.forEach(n=>this._walk(t,n)),t.closeNode(i)),t}static _collapse(t){typeof t!="string"&&t.children&&(t.children.every(i=>typeof i=="string")?t.children=[t.children.join("")]:t.children.forEach(i=>{e._collapse(i)}))}},Iv=class extends Lv{constructor(t){super(),this.options=t}addText(t){t!==""&&this.add(t)}startScope(t){this.openNode(t)}endScope(){this.closeNode()}__addSublanguage(t,i){let n=t.root;i&&(n.scope=`language:${i}`),this.add(n)}toHTML(){return new Dv(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}};function gu(e){return e?typeof e=="string"?e:e.source:null}function rk(e){return so("(?=",e,")")}function nB(e){return so("(?:",e,")*")}function rB(e){return so("(?:",e,")?")}function so(...e){return e.map(i=>gu(i)).join("")}function sB(e){let t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function xf(...e){return"("+(sB(e).capture?"":"?:")+e.map(n=>gu(n)).join("|")+")"}function sk(e){return new RegExp(e.toString()+"|").exec("").length-1}function aB(e,t){let i=e&&e.exec(t);return i&&i.index===0}var oB=new RegExp(xf(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));function zv(e,{joinWith:t}){let i=0;return e.map(n=>{i+=1;let r=i,s=gu(n),a="";for(;s.length>0;){let o=oB.exec(s);if(!o){a+=s;break}a+=s.substring(0,o.index),s=s.substring(o.index+o[0].length),o[0][0]==="\\"&&o[1]?a+="\\"+String(Number(o[1])+r):(a+=o[0],(o[0]==="("||/^\(\?[<']/.test(o[0]))&&i++)}return a}).map(n=>`(${n})`).join(t)}var lB=/\b\B/,ak="[a-zA-Z]\\w*",Pv="[a-zA-Z_]\\w*",ok="\\b\\d+(\\.\\d+)?",lk="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",ck="\\b(0b[01]+)",cB="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",uB=(e={})=>{let t=/^#![ ]*\//;return e.binary&&(e.begin=so(t,/.*\b/,e.binary,/\b.*/)),la({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(i,n)=>{i.index!==0&&n.ignoreMatch()}},e)},_u={begin:"\\\\[\\s\\S]",relevance:0},hB={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[_u]},dB={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[_u]},fB={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},Ef=function(e,t,i={}){let n=la({scope:"comment",begin:e,end:t,contains:[]},i);n.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});let r=xf("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return n.contains.push({begin:so(/[ ]+/,"(",r,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),n},pB=Ef("//","$"),mB=Ef("/\\*","\\*/"),gB=Ef("#","$"),_B={scope:"number",begin:ok,relevance:0},vB={scope:"number",begin:lk,relevance:0},bB={scope:"number",begin:ck,relevance:0},yB={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[_u,{begin:/\[/,end:/\]/,relevance:0,contains:[_u]}]},SB={scope:"title",begin:ak,relevance:0},wB={scope:"title",begin:Pv,relevance:0},xB={begin:"\\.\\s*"+Pv,relevance:0},EB=function(e){return Object.assign(e,{"on:begin":(t,i)=>{i.data._beginMatch=t[1]},"on:end":(t,i)=>{i.data._beginMatch!==t[1]&&i.ignoreMatch()}})},yf=Object.freeze({__proto__:null,APOS_STRING_MODE:hB,BACKSLASH_ESCAPE:_u,BINARY_NUMBER_MODE:bB,BINARY_NUMBER_RE:ck,COMMENT:Ef,C_BLOCK_COMMENT_MODE:mB,C_LINE_COMMENT_MODE:pB,C_NUMBER_MODE:vB,C_NUMBER_RE:lk,END_SAME_AS_BEGIN:EB,HASH_COMMENT_MODE:gB,IDENT_RE:ak,MATCH_NOTHING_RE:lB,METHOD_GUARD:xB,NUMBER_MODE:_B,NUMBER_RE:ok,PHRASAL_WORDS_MODE:fB,QUOTE_STRING_MODE:dB,REGEXP_MODE:yB,RE_STARTERS_RE:cB,SHEBANG:uB,TITLE_MODE:SB,UNDERSCORE_IDENT_RE:Pv,UNDERSCORE_TITLE_MODE:wB});function CB(e,t){e.input[e.index-1]==="."&&t.ignoreMatch()}function kB(e,t){e.className!==void 0&&(e.scope=e.className,delete e.className)}function TB(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=CB,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function NB(e,t){Array.isArray(e.illegal)&&(e.illegal=xf(...e.illegal))}function AB(e,t){if(e.match){if(e.begin||e.end)throw new Error("begin & end are not supported with match");e.begin=e.match,delete e.match}}function MB(e,t){e.relevance===void 0&&(e.relevance=1)}var RB=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw new Error("beforeMatch cannot be used with starts");let i=Object.assign({},e);Object.keys(e).forEach(n=>{delete e[n]}),e.keywords=i.keywords,e.begin=so(i.beforeMatch,rk(i.begin)),e.starts={relevance:0,contains:[Object.assign(i,{endsParent:!0})]},e.relevance=0,delete i.beforeMatch},OB=["of","and","for","in","not","or","if","then","parent","list","value"],DB="keyword";function uk(e,t,i=DB){let n=Object.create(null);return typeof e=="string"?r(i,e.split(" ")):Array.isArray(e)?r(i,e):Object.keys(e).forEach(function(s){Object.assign(n,uk(e[s],t,s))}),n;function r(s,a){t&&(a=a.map(o=>o.toLowerCase())),a.forEach(function(o){let l=o.split("|");n[l[0]]=[s,LB(l[0],l[1])]})}}function LB(e,t){return t?Number(t):IB(e)?0:1}function IB(e){return OB.includes(e.toLowerCase())}var QC={},ro=e=>{console.error(e)},JC=(e,...t)=>{console.log(`WARN: ${e}`,...t)},Il=(e,t)=>{QC[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),QC[`${e}/${t}`]=!0)},wf=new Error;function hk(e,t,{key:i}){let n=0,r=e[i],s={},a={};for(let o=1;o<=t.length;o++)a[o+n]=r[o],s[o+n]=!0,n+=sk(t[o-1]);e[i]=a,e[i]._emit=s,e[i]._multi=!0}function BB(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw ro("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),wf;if(typeof e.beginScope!="object"||e.beginScope===null)throw ro("beginScope must be object"),wf;hk(e,e.begin,{key:"beginScope"}),e.begin=zv(e.begin,{joinWith:""})}}function zB(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw ro("skip, excludeEnd, returnEnd not compatible with endScope: {}"),wf;if(typeof e.endScope!="object"||e.endScope===null)throw ro("endScope must be object"),wf;hk(e,e.end,{key:"endScope"}),e.end=zv(e.end,{joinWith:""})}}function PB(e){e.scope&&typeof e.scope=="object"&&e.scope!==null&&(e.beginScope=e.scope,delete e.scope)}function UB(e){PB(e),typeof e.beginScope=="string"&&(e.beginScope={_wrap:e.beginScope}),typeof e.endScope=="string"&&(e.endScope={_wrap:e.endScope}),BB(e),zB(e)}function HB(e){function t(a,o){return new RegExp(gu(a),"m"+(e.case_insensitive?"i":"")+(e.unicodeRegex?"u":"")+(o?"g":""))}class i{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(o,l){l.position=this.position++,this.matchIndexes[this.matchAt]=l,this.regexes.push([l,o]),this.matchAt+=sk(o)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);let o=this.regexes.map(l=>l[1]);this.matcherRe=t(zv(o,{joinWith:"|"}),!0),this.lastIndex=0}exec(o){this.matcherRe.lastIndex=this.lastIndex;let l=this.matcherRe.exec(o);if(!l)return null;let c=l.findIndex((h,d)=>d>0&&h!==void 0),u=this.matchIndexes[c];return l.splice(0,c),Object.assign(l,u)}}class n{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(o){if(this.multiRegexes[o])return this.multiRegexes[o];let l=new i;return this.rules.slice(o).forEach(([c,u])=>l.addRule(c,u)),l.compile(),this.multiRegexes[o]=l,l}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(o,l){this.rules.push([o,l]),l.type==="begin"&&this.count++}exec(o){let l=this.getMatcher(this.regexIndex);l.lastIndex=this.lastIndex;let c=l.exec(o);if(this.resumingScanAtSamePosition()&&!(c&&c.index===this.lastIndex)){let u=this.getMatcher(0);u.lastIndex=this.lastIndex+1,c=u.exec(o)}return c&&(this.regexIndex+=c.position+1,this.regexIndex===this.count&&this.considerAll()),c}}function r(a){let o=new n;return a.contains.forEach(l=>o.addRule(l.begin,{rule:l,type:"begin"})),a.terminatorEnd&&o.addRule(a.terminatorEnd,{type:"end"}),a.illegal&&o.addRule(a.illegal,{type:"illegal"}),o}function s(a,o){let l=a;if(a.isCompiled)return l;[kB,AB,UB,RB].forEach(u=>u(a,o)),e.compilerExtensions.forEach(u=>u(a,o)),a.__beforeBegin=null,[TB,NB,MB].forEach(u=>u(a,o)),a.isCompiled=!0;let c=null;return typeof a.keywords=="object"&&a.keywords.$pattern&&(a.keywords=Object.assign({},a.keywords),c=a.keywords.$pattern,delete a.keywords.$pattern),c=c||/\w+/,a.keywords&&(a.keywords=uk(a.keywords,e.case_insensitive)),l.keywordPatternRe=t(c,!0),o&&(a.begin||(a.begin=/\B|\b/),l.beginRe=t(l.begin),!a.end&&!a.endsWithParent&&(a.end=/\B|\b/),a.end&&(l.endRe=t(l.end)),l.terminatorEnd=gu(l.end)||"",a.endsWithParent&&o.terminatorEnd&&(l.terminatorEnd+=(a.end?"|":"")+o.terminatorEnd)),a.illegal&&(l.illegalRe=t(a.illegal)),a.contains||(a.contains=[]),a.contains=[].concat(...a.contains.map(function(u){return FB(u==="self"?a:u)})),a.contains.forEach(function(u){s(u,l)}),a.starts&&s(a.starts,o),l.matcher=r(l),l}if(e.compilerExtensions||(e.compilerExtensions=[]),e.contains&&e.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=la(e.classNameAliases||{}),s(e)}function dk(e){return e?e.endsWithParent||dk(e.starts):!1}function FB(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return la(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:dk(e)?la(e,{starts:e.starts?la(e.starts):null}):Object.isFrozen(e)?la(e):e}var qB="11.12.0",Bv=class extends Error{constructor(t,i){super(t),this.name="HTMLInjectionError",this.html=i}},Ov=nk,ek=la,tk=Symbol("nomatch"),KB=7,fk=function(e){let t=Object.create(null),i=Object.create(null),n=[],r=!0,s="Could not find the language '{}', did you forget to load/include a language module?",a={disableAutodetect:!0,name:"Plain text",contains:[]},o={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:Iv};function l(C){return o.noHighlightRe.test(C)}function c(C){let N=C.className+" ";N+=C.parentNode?C.parentNode.className:"";let R=o.languageDetectRe.exec(N);if(R){let W=k(R[1]);return W||(JC(s.replace("{}",R[1])),JC("Falling back to no-highlight mode for this block.",C)),W?R[1]:"no-highlight"}return N.split(/\s+/).find(W=>l(W)||k(W))}function u(C,N,R){let W="",X="";typeof N=="object"?(W=C,R=N.ignoreIllegals,X=N.language):(Il("10.7.0","highlight(lang, code, ...args) has been deprecated."),Il("10.7.0",`Please use highlight(code, options) instead. +https://github.com/highlightjs/highlight.js/issues/2277`),X=C,W=N),R===void 0&&(R=!0);let U={code:W,language:X};x("before:highlight",U);let Q=U.result?U.result:h(U.language,U.code,R);return Q.code=U.code,x("after:highlight",Q),Q}function h(C,N,R,W){let X=Object.create(null);function U(te,oe){return te.keywords[oe]}function Q(){if(!ie.keywords){Ye.addText(Fe);return}let te=0;ie.keywordPatternRe.lastIndex=0;let oe=ie.keywordPatternRe.exec(Fe),ge="";for(;oe;){ge+=Fe.substring(te,oe.index);let Ae=zt.case_insensitive?oe[0].toLowerCase():oe[0],tt=U(ie,Ae);if(tt){let[_i,ws]=tt;if(Ye.addText(ge),ge="",X[Ae]=(X[Ae]||0)+1,X[Ae]<=KB&&(An+=ws),_i.startsWith("_"))ge+=oe[0];else{let xs=zt.classNameAliases[_i]||_i;Ke(oe[0],xs)}}else ge+=oe[0];te=ie.keywordPatternRe.lastIndex,oe=ie.keywordPatternRe.exec(Fe)}ge+=Fe.substring(te),Ye.addText(ge)}function Ee(){if(Fe==="")return;let te=null;if(typeof ie.subLanguage=="string"){if(!t[ie.subLanguage]){Ye.addText(Fe);return}te=h(ie.subLanguage,Fe,!0,Pi[ie.subLanguage]),Pi[ie.subLanguage]=te._top}else te=f(Fe,ie.subLanguage.length?ie.subLanguage:null);ie.relevance>0&&(An+=te.relevance),Ye.__addSublanguage(te._emitter,te.language)}function he(){ie.subLanguage!=null?Ee():Q(),Fe=""}function Ke(te,oe){te!==""&&(Ye.startScope(oe),Ye.addText(te),Ye.endScope())}function J(te,oe){let ge=1,Ae=oe.length-1;for(;ge<=Ae;){if(!te._emit[ge]){ge++;continue}let tt=zt.classNameAliases[te[ge]]||te[ge],_i=oe[ge];tt?Ke(_i,tt):(Fe=_i,Q(),Fe=""),ge++}}function je(te,oe){return te.scope&&typeof te.scope=="string"&&Ye.openNode(zt.classNameAliases[te.scope]||te.scope),te.beginScope&&(te.beginScope._wrap?(Ke(Fe,zt.classNameAliases[te.beginScope._wrap]||te.beginScope._wrap),Fe=""):te.beginScope._multi&&(J(te.beginScope,oe),Fe="")),ie=Object.create(te,{parent:{value:ie}}),ie}function Ai(te,oe,ge){let Ae=aB(te.endRe,ge);if(Ae){if(te["on:end"]){let tt=new Sf(te);te["on:end"](oe,tt),tt.isMatchIgnored&&(Ae=!1)}if(Ae){for(;te.endsParent&&te.parent;)te=te.parent;return te}}if(te.endsWithParent)return Ai(te.parent,oe,ge)}function $t(te){return ie.matcher.regexIndex===0?(Fe+=te[0],1):(Kr=!0,0)}function mi(te){let oe=te[0],ge=te.rule,Ae=new Sf(ge),tt=[ge.__beforeBegin,ge["on:begin"]];for(let _i of tt)if(_i&&(_i(te,Ae),Ae.isMatchIgnored))return $t(oe);return ge.skip?Fe+=oe:(ge.excludeBegin&&(Fe+=oe),he(),!ge.returnBegin&&!ge.excludeBegin&&(Fe=oe)),je(ge,te),ge.returnBegin?0:oe.length}function gi(te){let oe=te[0],ge=N.substring(te.index),Ae=Ai(ie,te,ge);if(!Ae)return tk;let tt=ie;ie.endScope&&ie.endScope._wrap?(he(),Ke(oe,ie.endScope._wrap)):ie.endScope&&ie.endScope._multi?(he(),J(ie.endScope,te)):tt.skip?Fe+=oe:(tt.returnEnd||tt.excludeEnd||(Fe+=oe),he(),tt.excludeEnd&&(Fe=oe));do ie.scope&&Ye.closeNode(),!ie.skip&&!ie.subLanguage&&(An+=ie.relevance),ie=ie.parent;while(ie!==Ae.parent);return Ae.starts&&je(Ae.starts,te),tt.returnEnd?0:oe.length}function Bt(){let te=[];for(let oe=ie;oe!==zt;oe=oe.parent)oe.scope&&te.unshift(oe.scope);te.forEach(oe=>Ye.openNode(oe))}let me={};function un(te,oe){let ge=oe&&oe[0];if(Fe+=te,ge==null)return he(),0;if(me.type==="begin"&&oe.type==="end"&&me.index===oe.index&&ge===""){if(Fe+=N.slice(oe.index,oe.index+1),!r){let Ae=new Error(`0 width match regex (${C})`);throw Ae.languageName=C,Ae.badRule=me.rule,Ae}return 1}if(me=oe,oe.type==="begin")return mi(oe);if(oe.type==="illegal"&&!R){let Ae=new Error('Illegal lexeme "'+ge+'" for mode "'+(ie.scope||"")+'"');throw Ae.mode=ie,Ae}else if(oe.type==="end"){let Ae=gi(oe);if(Ae!==tk)return Ae}if(oe.type==="illegal"&&ge==="")return oe.index===N.length||(Fe+=` +`),1;if(qr>1e5&&qr>oe.index*3)throw new Error("potential infinite loop, way more iterations than matches");return Fe+=ge,ge.length}let zt=k(C);if(!zt)throw ro(s.replace("{}",C)),new Error('Unknown language: "'+C+'"');let ce=HB(zt),zi="",ie=W||ce,Pi={},Ye=new o.__emitter(o);Bt();let Fe="",An=0,Gt=0,qr=0,Kr=!1;try{if(zt.__emitTokens)zt.__emitTokens(N,Ye);else{for(ie.matcher.considerAll();;){qr++,Kr?Kr=!1:ie.matcher.considerAll(),ie.matcher.lastIndex=Gt;let te=ie.matcher.exec(N);if(!te)break;let oe=N.substring(Gt,te.index),ge=un(oe,te);Gt=te.index+ge}un(N.substring(Gt))}return Ye.finalize(),zi=Ye.toHTML(),{language:C,value:zi,relevance:An,illegal:!1,_emitter:Ye,_top:ie}}catch(te){if(te.message&&te.message.includes("Illegal"))return{language:C,value:Ov(N),illegal:!0,relevance:0,_illegalBy:{message:te.message,index:Gt,context:N.slice(Gt-100,Gt+100),mode:te.mode,resultSoFar:zi},_emitter:Ye};if(r)return{language:C,value:Ov(N),illegal:!1,relevance:0,errorRaised:te,_emitter:Ye,_top:ie};throw te}}function d(C){let N={value:Ov(C),illegal:!1,relevance:0,_top:a,_emitter:new o.__emitter(o)};return N._emitter.addText(C),N}function f(C,N){N=N||o.languages||Object.keys(t);let R=d(C),W=N.filter(k).filter(L).map(he=>h(he,C,!1));W.unshift(R);let X=W.sort((he,Ke)=>{if(he.relevance!==Ke.relevance)return Ke.relevance-he.relevance;if(he.language&&Ke.language){if(k(he.language).supersetOf===Ke.language)return 1;if(k(Ke.language).supersetOf===he.language)return-1}return 0}),[U,Q]=X,Ee=U;return Ee.secondBest=Q,Ee}function p(C,N,R){let W=N&&i[N]||R;C.classList.add("hljs"),C.classList.add(`language-${W}`)}function _(C){let N=null,R=c(C);if(l(R))return;if(x("before:highlightElement",{el:C,language:R}),C.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",C);return}if(C.children.length>0&&(o.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(C)),o.throwUnescapedHTML))throw new Bv("One of your code blocks includes unescaped HTML.",C.innerHTML);N=C;let W=N.textContent,X=R?u(W,{language:R,ignoreIllegals:!0}):f(W);C.innerHTML=X.value,C.dataset.highlighted="yes",p(C,R,X.language),C.result={language:X.language,re:X.relevance,relevance:X.relevance},X.secondBest&&(C.secondBest={language:X.secondBest.language,relevance:X.secondBest.relevance}),x("after:highlightElement",{el:C,result:X,text:W})}function S(C){o=ek(o,C)}let m=()=>{w(),Il("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function g(){w(),Il("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let b=!1;function w(){function C(){w()}if(document.readyState==="loading"){b||window.addEventListener("DOMContentLoaded",C,!1),b=!0;return}document.querySelectorAll(o.cssSelector).forEach(_)}function E(C,N){let R=null;try{R=N(e)}catch(W){if(ro("Language definition for '{}' could not be registered.".replace("{}",C)),r)ro(W);else throw W;R=a}R.name||(R.name=C),t[C]=R,R.rawDefinition=N.bind(null,e),R.aliases&&D(R.aliases,{languageName:C})}function A(C){delete t[C];for(let N of Object.keys(i))i[N]===C&&delete i[N]}function O(){return Object.keys(t)}function k(C){return C=(C||"").toLowerCase(),t[C]||t[i[C]]}function D(C,{languageName:N}){typeof C=="string"&&(C=[C]),C.forEach(R=>{i[R.toLowerCase()]=N})}function L(C){let N=k(C);return N&&!N.disableAutodetect}function P(C){C["before:highlightBlock"]&&!C["before:highlightElement"]&&(C["before:highlightElement"]=N=>{C["before:highlightBlock"](Object.assign({block:N.el},N))}),C["after:highlightBlock"]&&!C["after:highlightElement"]&&(C["after:highlightElement"]=N=>{C["after:highlightBlock"](Object.assign({block:N.el},N))})}function I(C){P(C),n.push(C)}function B(C){let N=n.indexOf(C);N!==-1&&n.splice(N,1)}function x(C,N){let R=C;n.forEach(function(W){W[R]&&W[R](N)})}function z(C){return Il("10.7.0","highlightBlock will be removed entirely in v12.0"),Il("10.7.0","Please use highlightElement now."),_(C)}Object.assign(e,{highlight:u,highlightAuto:f,highlightAll:w,highlightElement:_,highlightBlock:z,configure:S,initHighlighting:m,initHighlightingOnLoad:g,registerLanguage:E,unregisterLanguage:A,listLanguages:O,getLanguage:k,registerAliases:D,autoDetection:L,inherit:ek,addPlugin:I,removePlugin:B}),e.debugMode=function(){r=!1},e.safeMode=function(){r=!0},e.versionString=qB,e.regex={concat:so,lookahead:rk,either:xf,optional:rB,anyNumberOfTimes:nB};for(let C in yf)typeof yf[C]=="object"&&ik(yf[C]);return Object.assign(e,yf),e},Bl=fk({});Bl.newInstance=()=>fk({});pk.exports=Bl;Bl.HighlightJS=Bl;Bl.default=Bl});var _k=ve((M8,gk)=>{function WB(e){let t=e.regex,i=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),n=/[\p{L}0-9._:-]+/u,r={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},s={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},a=e.inherit(s,{begin:/\(/,end:/\)/}),o=e.inherit(e.APOS_STRING_MODE,{className:"string"}),l=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),c={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin://,relevance:10,contains:[s,l,o,a,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[s,a,l,o]}]}]},e.COMMENT(//,{relevance:10}),{begin://,relevance:10},r,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[l]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[c],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:"css"}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[c],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:"javascript"}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:i,relevance:0,starts:c}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(i,/>/))),contains:[{className:"name",begin:i,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}gk.exports=WB});var bk=ve((R8,vk)=>{function $B(e){let t=e.regex,i={},n={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[i]}]};Object.assign(i,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},n]});let r={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},s=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),a={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},o={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,i,r]};r.contains.push(o);let l={match:/\\"/},c={className:"string",begin:/'/,end:/'/},u={match:/\\'/},h={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,i]},d=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],f=e.SHEBANG({binary:`(${d.join("|")})`,relevance:10}),p={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},_=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],S=["true","false"],m={match:/(\/[a-z._-]+)+/},g=["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset"],b=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],w=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],E=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:_,literal:S,built_in:[...g,...b,"set","shopt",...w,...E]},contains:[f,e.SHEBANG(),p,h,s,a,m,o,l,c,u,i]}}vk.exports=$B});var Sk=ve((O8,yk)=>{function GB(e){let t=e.regex,i=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",r="[a-zA-Z_]\\w*::",a="("+n+"|"+t.optional(r)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o=t.concat(/\batomic_/,t.either("bool","char","schar","uchar","short","ushort","int","uint","long","ulong","llong","ullong","char16_t","char32_t","wchar_t","int_least8_t","uint_least8_t","int_least16_t","uint_least16_t","int_least32_t","uint_least32_t","int_least64_t","uint_least64_t","int_fast8_t","uint_fast8_t","int_fast16_t","uint_fast16_t","int_fast32_t","uint_fast32_t","int_fast64_t","uint_fast64_t","intptr_t","uintptr_t","size_t","ptrdiff_t","intmax_t","uintmax_t"),/\b/),l={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:o}]},u={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},h={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},d={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"},contains:[{begin:/\\\n/},u,{scope:"string",begin:/<.*?>/},i,e.C_BLOCK_COMMENT_MODE]},f={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(u,{className:"string"}),i,e.C_BLOCK_COMMENT_MODE]},p=[d,f],_={className:"title",begin:t.optional(r)+e.IDENT_RE,relevance:0},S=t.optional(r)+e.IDENT_RE+"\\s*\\(",m=12,w={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},E=[...p,l,i,e.C_BLOCK_COMMENT_MODE,h,u],A={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:w,contains:E.concat([{begin:/\(/,end:/\)/,keywords:w,contains:E.concat(["self"]),relevance:0}]),relevance:0},O={begin:"("+a+"[\\*&\\s]+){1,"+m+"}"+S,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:w,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:w,relevance:0},{begin:S,returnBegin:!0,contains:[e.inherit(_,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:w,relevance:0,contains:[i,e.C_BLOCK_COMMENT_MODE,u,h,l,{begin:/\(/,end:/\)/,keywords:w,relevance:0,contains:["self",i,e.C_BLOCK_COMMENT_MODE,u,h,l]}]},l,i,e.C_BLOCK_COMMENT_MODE,...p]};return{name:"C",aliases:["h"],keywords:w,disableAutodetect:!0,illegal:"=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:f,strings:u,keywords:w}}}yk.exports=GB});var xk=ve((D8,wk)=>{function jB(e){let t=e.regex,i=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),n="decltype\\(auto\\)",r="[a-zA-Z_]\\w*::",a="(?!struct)("+n+"|"+t.optional(r)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",o={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},c={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},u={className:"number",variants:[{begin:"[+-]?(?:(?:\\b[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|\\b[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|\\b0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},h={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"},contains:[{begin:/\\\n/},c,{scope:"string",begin:/<.*?>/},i,e.C_BLOCK_COMMENT_MODE]},d={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(c,{className:"string"}),i,e.C_BLOCK_COMMENT_MODE]},f=[h,d],p={className:"title",begin:t.optional(r)+e.IDENT_RE,relevance:0},_=t.optional(r)+e.IDENT_RE+"\\s*\\(",S=12,m=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],g=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],b=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],w=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],O={type:g,keyword:m,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:b},k={className:"function.dispatch",relevance:0,keywords:{_hint:w},begin:t.concat(/\b/,`(?!${m.join("|")})`,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},D=[k,...f,o,i,e.C_BLOCK_COMMENT_MODE,u,c],L={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:O,contains:D.concat([{begin:/\(/,end:/\)/,keywords:O,contains:D.concat(["self"]),relevance:0}]),relevance:0},P={className:"function",begin:"("+a+"[\\*&\\s]+){1,"+S+"}"+_,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:O,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:O,relevance:0},{begin:_,returnBegin:!0,contains:[p],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[c,u]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:O,relevance:0,contains:[i,e.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:O,relevance:0,contains:["self",i,e.C_BLOCK_COMMENT_MODE,c,u,o]}]},o,i,e.C_BLOCK_COMMENT_MODE,...f]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:O,illegal:"",keywords:O,contains:["self",o]},{begin:e.IDENT_RE+"::",keywords:O},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}wk.exports=jB});var Ck=ve((L8,Ek)=>{function YB(e){let t=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],i=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],n=["default","false","null","true"],r=["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],s=["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],a={keyword:r.concat(s),built_in:t,literal:n},o=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),l="\\d(_*\\d)*",c="([uU][lL]?|[lL][uU]?)?",h={className:"number",variants:[{begin:"\\b0[bB]_*[01](_*[01])*"+c},{begin:"(-?)\\b0[xX]_*[a-fA-F0-9](_*[a-fA-F0-9])*"+c},{begin:"(-?)(\\b"+l+"(\\.("+l+")?)?|\\."+l+")([eE][-+]?"+l+")?"+"([fFdDmM]|[uU][lL]?|[lL][uU]?)?"}],relevance:0},d={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},f={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},p=e.inherit(f,{illegal:/\n/}),_={className:"subst",begin:/\{/,end:/\}/,keywords:a},S=e.inherit(_,{illegal:/\n/}),m={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,S]},g={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},_]},b=e.inherit(g,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},S]});_.contains=[g,m,f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,e.C_BLOCK_COMMENT_MODE],S.contains=[b,m,p,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];let w={variants:[d,g,m,f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},E={begin:"<",end:">",contains:[{beginKeywords:"in out"},o]},A=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",O={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:a,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:""},{begin:""}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},w,h,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},o,E,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[o,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[o,E,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+A+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:a,contains:[{beginKeywords:i.join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,E],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:a,relevance:0,contains:[w,h,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},O]}}Ek.exports=YB});var Tk=ve((I8,kk)=>{var VB=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),XB=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],ZB=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],QB=[...XB,...ZB],JB=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),ez=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),tz=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),iz=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function nz(e){let t=e.regex,i=VB(e),n={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},r="and or not only",s=/@-?\w[\w]*(-\w+)*/,a="[a-zA-Z-][a-zA-Z0-9_-]*",o=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[i.BLOCK_COMMENT,n,i.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+a,relevance:0},i.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+ez.join("|")+")"},{begin:":(:)?("+tz.join("|")+")"}]},i.CSS_VARIABLE,{className:"attribute",begin:"\\b("+iz.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[i.BLOCK_COMMENT,i.HEXCOLOR,i.IMPORTANT,i.CSS_NUMBER_MODE,i.UNICODE_RANGE,...o,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...o,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},i.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:s},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:r,attribute:JB.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...o,i.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+QB.join("|")+")\\b"}]}}kk.exports=nz});var Ak=ve((B8,Nk)=>{function rz(e){let t=e.regex,i={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},n={match:/^ {0,3}([-*_])[ \t]*(?:\1[ \t]*){2,}$/},r={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},s={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},a={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},o=/[A-Za-z][A-Za-z0-9+.-]*/,l={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,o,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},c={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},u={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},h=e.inherit(c,{contains:[]}),d=e.inherit(u,{contains:[]});c.contains.push(d),u.contains.push(h);let f=[i,l];return[c,u,h,d].forEach(m=>{m.contains=m.contains.concat(f)}),f=f.concat(c,u),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:f},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:f}]}]},i,s,n,c,u,{className:"quote",begin:"^>\\s+",contains:f,end:"$"},r,l,a,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}Nk.exports=rz});var Rk=ve((z8,Mk)=>{function sz(e){let t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}Mk.exports=sz});var Dk=ve((P8,Ok)=>{function az(e){let t=e.regex,i="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",n=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),r=t.concat(n,/(::\w+)*/),a={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},o={className:"doctag",begin:"@[A-Za-z]+"},l={begin:"#<",end:">"},c=[e.COMMENT("#","$",{contains:[o]}),e.COMMENT("^=begin","^=end",{contains:[o],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],u={className:"subst",begin:/#\{/,end:/\}/,keywords:a},h={className:"string",contains:[e.BACKSLASH_ESCAPE,u],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,u]})]}]},d="[1-9](_?[0-9])*|0",f="[0-9](_?[0-9])*",p={className:"number",relevance:0,variants:[{begin:`\\b(${d})(\\.(${f}))?([eE][+-]?(${f})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},_={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:a}]},A=[h,{variants:[{match:[/class\s+/,r,/\s+<\s+/,r]},{match:[/\b(class|module)\s+/,r]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:a},{match:[/(include|extend)\s+/,r],scope:{2:"title.class"},keywords:a},{relevance:0,match:[r,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:n,scope:"title.class"},{match:[/def/,/\s+/,i],scope:{1:"keyword",3:"title.function"},contains:[_]},{begin:"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[h,{begin:i}],relevance:0},p,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:a},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,u],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(l,c),relevance:0}].concat(l,c);u.contains=A,_.contains=A;let L=[{begin:/^\s*=>/,starts:{end:"$",contains:A}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:a,contains:A}}];return c.unshift(l),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:a,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(L).concat(c).concat(A)}}Ok.exports=az});var Ik=ve((U8,Lk)=>{function oz(e){let s={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:s,illegal:"{function lz(e){let t=e.regex,i=/[_A-Za-z][_0-9A-Za-z]*/;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:t.concat(i,t.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}}Bk.exports=lz});var Uk=ve((F8,Pk)=>{function cz(e){let t=e.regex,i={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:e.NUMBER_RE}]},n=e.COMMENT();n.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];let r={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},s={className:"literal",begin:/\bon|off|true|false|yes|no\b/},a={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},o={begin:/\[/,end:/\]/,contains:[n,s,r,a,i,"self"],relevance:0},l=/[A-Za-z0-9_-]+/,c=/"(\\"|[^"])*"/,u=/'[^']*'/,h=t.either(l,c,u),d=t.concat(h,"(\\s*\\.\\s*",h,")*",t.lookahead(/\s*=\s*[^#\s]/));return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[n,{className:"section",begin:/\[+/,end:/\]+/},{begin:d,className:"attr",starts:{end:/$/,contains:[n,o,s,r,a,i]}}]}}Pk.exports=cz});var Kk=ve((q8,qk)=>{var zl="[0-9](_*[0-9])*",Cf=`\\.(${zl})`,kf="[0-9a-fA-F](_*[0-9a-fA-F])*",Hk={className:"number",variants:[{begin:`(\\b(${zl})((${Cf})|\\.)?|(${Cf}))[eE][+-]?(${zl})[fFdD]?\\b`},{begin:`\\b(${zl})((${Cf})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Cf})[fFdD]?\\b`},{begin:`\\b(${zl})[fFdD]\\b`},{begin:`\\b0[xX]((${kf})\\.?|(${kf})?\\.(${kf}))[pP][+-]?(${zl})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${kf})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function Fk(e,t,i){return i===-1?"":e.replace(t,n=>Fk(e,t,i-1))}function uz(e){let t=e.regex,i="[\xC0-\u02B8a-zA-Z_$][\xC0-\u02B8a-zA-Z_$0-9]*",n="(?:(?:\\s*\\[\\s*])+)?",r=i+"<@@@>"+n,a="(?:"+("\\?(?:\\s+(?:extends|super)\\s+"+r+")?")+"|"+r+")",o=Fk("(?:\\s*<\\s*"+a+"(?:\\s*,\\s*"+a+")*\\s*>)?",/<@@@>/g,2),d={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},f={className:"meta",begin:"@"+i,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},p={className:"params",begin:/\(/,end:/\)/,keywords:d,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:d,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,i],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{beginKeywords:"new throw return else yield assert",relevance:0},{begin:[i,t.concat(o,n,/\s+/),i,n,/\s*/,/=(?!=)/],className:{1:"type",3:"variable",6:"operator"}},{begin:[/record/,/\s+/,i],className:{1:"keyword",3:"title.class"},contains:[p,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{begin:[i,t.concat(o,n,/\s+/),i,/\s*(?=\()/],className:{1:"type",3:"title.function"},keywords:d,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:d,relevance:0,contains:[f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,Hk,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},Hk,f]}}qk.exports=uz});var Vk=ve((K8,Yk)=>{var Wk="[A-Za-z$_][0-9A-Za-z$_]*",hz=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],dz=["true","false","null","undefined","NaN","Infinity"],$k=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],Gk=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],jk=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],fz=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],pz=[].concat(jk,$k,Gk);function mz(e){let t=e.regex,i=(R,{after:W})=>{let X="",end:""},s=/<[A-Za-z0-9\\._:-]+\s*\/>/,a={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(R,W)=>{let X=R[0].length+R.index,U=R.input[X];if(U==="<"||U===","){W.ignoreMatch();return}U===">"&&(i(R,{after:X})||W.ignoreMatch());let Q,Ee=R.input.substring(X);if(Q=Ee.match(/^\s*=/)){W.ignoreMatch();return}if((Q=Ee.match(/^\s+extends\s+/))&&Q.index===0){W.ignoreMatch();return}}},o={$pattern:Wk,keyword:hz,literal:dz,built_in:pz,"variable.language":fz},l="[0-9](_?[0-9])*",c=`\\.(${l})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${u})((${c})|\\.)?|(${c}))[eE][+-]?(${l})\\b`},{begin:`\\b(${u})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},p={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},_={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},S={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},g={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},b=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,S,{match:/\$\d+/},h];d.contains=b.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(b)});let w=[].concat(g,d.contains),E=w.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(w)}]),A={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:E},O={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},k={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...$k,...Gk]}},D={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},L={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[A],illegal:/%/},P={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function I(R){return t.concat("(?!",R.join("|"),")")}let B={match:t.concat(/\b/,I([...jk,"super","import","await"].map(R=>`${R}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},x={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},z={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},A]},C="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",N={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(C)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[A]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:E,CLASS_REFERENCE:k},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),D,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,S,g,{match:/\$\d+/},h,k,{scope:"attr",match:n+t.lookahead(":"),relevance:0},N,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[g,e.REGEXP_MODE,{className:"function",begin:C,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:E}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r.begin,end:r.end},{match:s},{begin:a.begin,"on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},L,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[A,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},x,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[A]},B,P,O,z,{match:/\$[(.]/}]}}Yk.exports=mz});var Zk=ve((W8,Xk)=>{var gz="([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity",_z={scope:"number",match:gz,relevance:0};function vz(e){let t={className:"attr",begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},i={match:/[{}[\],:]/,className:"punctuation",relevance:0},n=["true","false","null"],r={scope:"literal",beginKeywords:n.join(" ")};return{name:"JSON",aliases:["jsonc","json5"],keywords:{literal:n},contains:[t,i,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,r,_z,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}Xk.exports=vz});var Jk=ve(($8,Qk)=>{var Pl="[0-9](_*[0-9])*",Tf=`\\.(${Pl})`,Nf="[0-9a-fA-F](_*[0-9a-fA-F])*",bz={className:"number",variants:[{begin:`(\\b(${Pl})((${Tf})|\\.)?|(${Tf}))[eE][+-]?(${Pl})[fFdD]?\\b`},{begin:`\\b(${Pl})((${Tf})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Tf})[fFdD]?\\b`},{begin:`\\b(${Pl})[fFdD]\\b`},{begin:`\\b0[xX]((${Nf})\\.?|(${Nf})?\\.(${Nf}))[pP][+-]?(${Pl})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${Nf})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function yz(e){let t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},i={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},n={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},r={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},s={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},a={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[s,r]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,s,r]}]};r.contains.push(a);let o={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},l={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(a,{className:"string"}),"self"]}]},c=bz,u=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),h={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},d=h;return d.variants[1].contains=[h],h.variants[1].contains=[d],{name:"Kotlin",aliases:["kt","kts","ktm","ktx"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,u,i,n,o,l,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin://,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[h,e.C_LINE_COMMENT_MODE,u],relevance:0},e.C_LINE_COMMENT_MODE,u,o,l,a,e.C_NUMBER_MODE]},u]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin://,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},o,l]},a,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:` +`},c]}}Qk.exports=yz});var nT=ve((G8,iT)=>{var Sz=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),wz=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],xz=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Ez=[...wz,...xz],Cz=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),eT=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),tT=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),kz=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),Tz=eT.concat(tT).sort().reverse();function Nz(e){let t=Sz(e),i=Tz,n="and or not only",r="[\\w-]+",s="("+r+"|@\\{"+r+"\\})",a=[],o=[],l=function(b){return{className:"string",begin:"~?"+b+".*?"+b}},c=function(b,w,E){return{className:b,begin:w,relevance:E}},u={$pattern:/[a-z-]+/,keyword:n,attribute:Cz.join(" ")},h={begin:"\\(",end:"\\)",contains:o,keywords:u,relevance:0};o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,l("'"),l('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}},t.UNICODE_RANGE,t.HEXCOLOR,h,c("variable","@@?"+r,10),c("variable","@\\{"+r+"\\}"),c("built_in","~?`[^`]*?`"),{className:"attribute",begin:r+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);let d=o.concat({begin:/\{/,end:/\}/,contains:a}),f={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(o)},p={begin:s+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+kz.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:o}}]},_={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:u,returnEnd:!0,contains:o,relevance:0}},S={className:"variable",variants:[{begin:"@"+r+"\\s*:",relevance:15},{begin:"@"+r}],starts:{end:"[;}]",returnEnd:!0,contains:d}},m={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:s,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,f,c("keyword","all\\b"),c("variable","@\\{"+r+"\\}"),{begin:"\\b("+Ez.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,c("selector-tag",s,0),c("selector-id","#"+s),c("selector-class","\\."+s,0),c("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+eT.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+tT.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:d},{begin:"!important"},t.FUNCTION_DISPATCH]},g={begin:r+`:(:)?(${i.join("|")})`,returnBegin:!0,contains:[m]};return a.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,_,S,g,p,m,f,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:a}}iT.exports=Nz});var sT=ve((j8,rT)=>{function Az(e){let t="\\[=*\\[",i="\\]=*\\]",n={begin:t,end:i,contains:["self"]},r=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,i,{contains:[n],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local global not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:r.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:r}].concat(r)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:i,contains:[n],relevance:5}])}}rT.exports=Az});var oT=ve((Y8,aT)=>{function Mz(e){let t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%{function Rz(e){let t=e.regex,i=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],n=/[dualxmsipngr]{0,12}/,r={$pattern:/[\w.]+/,keyword:i.join(" ")},s={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:r},a={begin:/->\{/,end:/\}/},o={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},l={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[o]},c={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},u=[e.BACKSLASH_ESCAPE,s,l],h=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],d=(_,S,m="\\1")=>{let g=m==="\\1"?m:t.concat(m,S);return t.concat(t.concat("(?:",_,")"),S,/(?:\\.|[^\\\/])*?/,g,/(?:\\.|[^\\\/])*?/,m,n)},f=(_,S,m)=>t.concat(t.concat("(?:",_,")"),S,/(?:\\.|[^\\\/])*?/,m,n),p=[l,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),a,{className:"string",contains:u,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},c,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:d("s|tr|y",t.either(...h,{capture:!0}))},{begin:d("s|tr|y","\\(","\\)")},{begin:d("s|tr|y","\\[","\\]")},{begin:d("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:f("(?:m|qr)?",/\//,/\//)},{begin:f("m|qr",t.either(...h,{capture:!0}),/\1/)},{begin:f("m|qr",/\(/,/\)/)},{begin:f("m|qr",/\[/,/\]/)},{begin:f("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,o]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,o,c]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return s.contains=p,a.contains=p,{name:"Perl",aliases:["pl","pm"],keywords:r,contains:p}}lT.exports=Rz});var hT=ve((X8,uT)=>{function Oz(e){let t={className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},i=/[a-zA-Z@][a-zA-Z0-9_]*/,o={"variable.language":["this","super"],$pattern:i,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},l={$pattern:i,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:o,illegal:"/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+l.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:l,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}}uT.exports=Oz});var fT=ve((Z8,dT)=>{function Dz(e){let t=e.regex,i=/(?![A-Za-z0-9])(?![$])/,n=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,i),r=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,i),s=t.concat(/[A-Z]+/,i),a={scope:"variable",match:"\\$+"+n},o={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},l={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},c=e.inherit(e.APOS_STRING_MODE,{illegal:null}),u=e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(l)}),h={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(l),"on:begin":(x,z)=>{z.data._beginMatch=x[1]||x[2]},"on:end":(x,z)=>{z.data._beginMatch!==x[1]&&z.ignoreMatch()}},d=e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),f=`[ +]`,p={scope:"string",variants:[u,c,h,d]},_={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},S=["false","null","true"],m=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],g=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],w={keyword:m,literal:(x=>{let z=[];return x.forEach(C=>{z.push(C),C.toLowerCase()===C?z.push(C.toUpperCase()):z.push(C.toLowerCase())}),z})(S),built_in:g},E=x=>x.map(z=>z.replace(/\|\d+$/,"")),A={variants:[{match:[/new/,t.concat(f,"+"),t.concat("(?!",E(g).join("\\b|"),"\\b)"),r],scope:{1:"keyword",4:"title.class"}}]},O=t.concat(n,"\\b(?!\\()"),k={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),O],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[r,t.concat(/::/,t.lookahead(/(?!class\b)/)),O],scope:{1:"title.class",3:"variable.constant"}},{match:[r,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[r,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},D={scope:"attr",match:t.concat(n,t.lookahead(":"),t.lookahead(/(?!::)/))},L={relevance:0,begin:/\(/,end:/\)/,keywords:w,contains:[D,a,k,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_,A]},P={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",E(m).join("\\b|"),"|",E(g).join("\\b|"),"\\b)"),n,t.concat(f,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[L]};L.contains.push(P);let I=[D,k,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_,A],B={begin:t.concat(/#\[\s*\\?/,t.either(r,s)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:S,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:S,keyword:["new","array"]},contains:["self",...I]},...I,{scope:"meta",variants:[{match:r},{match:s}]}]};return{case_insensitive:!1,keywords:w,contains:[B,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},o,{scope:"variable.language",match:/\$this\b/},a,P,k,{match:[/const/,/\s/,n],scope:{1:"keyword",3:"variable.constant"}},A,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:w,contains:["self",B,a,k,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},p,_]}}dT.exports=Dz});var mT=ve((Q8,pT)=>{function Lz(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}pT.exports=Lz});var _T=ve((J8,gT)=>{function Iz(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}gT.exports=Iz});var bT=ve((e9,vT)=>{function Bz(e){let t=e.regex,i=/[\p{XID_Start}_]\p{XID_Continue}*/u,n=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","lazy","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],o={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:n,built_in:["__import__","abs","aiter","all","anext","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozendict","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","sentinel","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},l={className:"meta",begin:/^(>>>|\.\.\.) /},c={className:"subst",begin:/\{/,end:/\}/,keywords:o,illegal:/#/},u={begin:/\{\{/,relevance:0},h={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,l],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,l],relevance:10},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,l,u,c]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,l,u,c]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,u,c]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,u,c]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},d="[0-9](_?[0-9])*",f=`(\\b(${d}))?\\.(${d})|\\b(${d})\\.`,p=`\\b|${n.join("|")}`,_={className:"number",relevance:0,variants:[{begin:`(\\b(${d})|(${f}))[eE][+-]?(${d})[jJ]?(?=${p})`},{begin:`(${f})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${p})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${p})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${p})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${p})`},{begin:`\\b(${d})[jJ](?=${p})`}]},S={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:o,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:["self",l,_,h,e.HASH_COMMENT_MODE]}]};return c.contains=[h,_,l],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:o,illegal:/(<\/|\?)|=>/,contains:[l,_,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},h,S,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,i],scope:{1:"keyword",3:"title.function"},contains:[m]},{variants:[{match:[/\bclass/,/\s+/,i,/\s*/,/\(\s*/,i,/\s*\)/]},{match:[/\bclass/,/\s+/,i]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[_,m,h]}]}}vT.exports=Bz});var ST=ve((t9,yT)=>{function zz(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}yT.exports=zz});var xT=ve((i9,wT)=>{function Pz(e){let t=e.regex,i=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,n=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),r=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,s=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:i,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:i},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[r,n]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,n]},{scope:{1:"punctuation",2:"number"},match:[s,n]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,n]}]},{scope:{3:"operator"},match:[i,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:r},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:s},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}wT.exports=Pz});var CT=ve((n9,ET)=>{function Uz(e){let t=e.regex,i=/(r#)?/,n=t.concat(i,e.UNDERSCORE_IDENT_RE),r=t.concat(i,e.IDENT_RE),s={scope:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!(?:let|for|while|if|else|match)\b)/,r,t.lookahead(/\s*\(/))},a="([ui](8|16|32|64|128|size)|f(16|32|64|128))?",o=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","raw","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],l=["true","false","Some","None","Ok","Err"],c=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],u=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f16","f32","f64","f128","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:u,keyword:o,literal:l,built_in:c},illegal:""},s]}}ET.exports=Uz});var TT=ve((r9,kT)=>{var Hz=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Fz=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],qz=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],Kz=[...Fz,...qz],Wz=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),$z=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),Gz=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),jz=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","corner-bottom-left-shape","corner-bottom-right-shape","corner-shape","corner-top-left-shape","corner-top-right-shape","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function Yz(e){let t=Hz(e),i=Gz,n=$z,r="@[a-z-]+",s="and or not only",o={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0},{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+Kz.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+n.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+i.join("|")+")"},o,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+jz.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,o,t.HEXCOLOR,t.CSS_NUMBER_MODE,t.UNICODE_RANGE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:r,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:s,attribute:Wz.join(" ")},contains:[{begin:r,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},o,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}}kT.exports=Yz});var AT=ve((s9,NT)=>{function Vz(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[./~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}NT.exports=Vz});var RT=ve((a9,MT)=>{function Xz(e){let t=e.regex,i=e.COMMENT("--","$"),n={scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},r={begin:/"/,end:/"/,contains:[{match:/""/}]},s=["true","false","unknown"],a=["double precision","large object","with timezone","without timezone"],o=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],l=["add","asc","collation","desc","final","first","last","view"],c=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","versioning","when","whenever","where","width_bucket","window","with","within","without","year"],u=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],h=["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"],d=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],f=u,p=[...c,...l].filter(E=>!u.includes(E)),_={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},S={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},m={match:t.concat(/\b/,t.either(...f),/\s*\(/),relevance:0,keywords:{built_in:f}};function g(E){return t.concat(/\b/,t.either(...E.map(A=>A.replace(/\s+/,"\\s+"))),/\b/)}let b={scope:"keyword",match:g(d),relevance:0};function w(E,{exceptions:A,when:O}={}){let k=O;return A=A||[],E.map(D=>D.match(/\|\d+$/)||A.includes(D)?D:k(D)?`${D}|0`:D)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:w(p,{when:E=>E.length<3}),literal:s,type:o,built_in:h},contains:[{scope:"type",match:g(a)},b,m,_,n,r,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,i,S]}}MT.exports=Xz});var HT=ve((o9,UT)=>{function IT(e){return e?typeof e=="string"?e:e.source:null}function vu(e){return st("(?=",e,")")}function st(...e){return e.map(i=>IT(i)).join("")}function Zz(e){let t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function Di(...e){return"("+(Zz(e).capture?"":"?:")+e.map(n=>IT(n)).join("|")+")"}new RegExp(Di(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));var Fv=e=>st(/\b/,e,/\w$/.test(e)?/\b/:/\B/),Qz=["Protocol","Type"].map(Fv),OT=["init","self"].map(Fv),Jz=["Any","Self"],Uv=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],DT=["false","nil","true"],e5=["assignment","associativity","higherThan","left","lowerThan","none","right"],t5=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],LT=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","withoutActuallyEscaping","zip"],BT=Di(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),zT=Di(BT,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Hv=st(BT,zT,"*"),PT=Di(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),Mf=Di(PT,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Lr=st(PT,Mf,"*"),Af=st(/[A-Z]/,Mf,"*"),i5=["attached","autoclosure",st(/convention\(/,Di("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",st(/objc\(/,Lr,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],n5=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function r5(e){let t={match:/\s+/,relevance:0},i=e.COMMENT("/\\*","\\*/",{contains:["self"]}),n=[e.C_LINE_COMMENT_MODE,i],r={match:[/\./,Di(...Qz,...OT)],className:{2:"keyword"}},s={match:st(/\./,Di(...Uv)),relevance:0},a=Uv.filter(ce=>typeof ce=="string").concat(["_|0"]),o=Uv.filter(ce=>typeof ce!="string").concat(Jz).map(Fv),l={variants:[{className:"keyword",match:Di(...o,...OT)}]},c={$pattern:Di(/\b\w+/,/#\w+/),keyword:a.concat(t5),literal:DT},u=[r,s,l],h={match:st(/\./,Di(...LT)),relevance:0},d={className:"built_in",match:st(/\b/,Di(...LT),/(?=\()/)},f=[h,d],p={match:/->/,relevance:0},_={className:"operator",relevance:0,variants:[{match:Hv},{match:`\\.(\\.|${zT})+`}]},S=[p,_],m="([0-9]_*)+",g="([0-9a-fA-F]_*)+",b={className:"number",relevance:0,variants:[{match:`\\b(${m})(\\.(${m}))?([eE][+-]?(${m}))?\\b`},{match:`\\b0x(${g})(\\.(${g}))?([pP][+-]?(${m}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},w=(ce="")=>({className:"subst",variants:[{match:st(/\\/,ce,/[0\\tnr"']/)},{match:st(/\\/,ce,/u\{[0-9a-fA-F]{1,8}\}/)}]}),E=(ce="")=>({className:"subst",match:st(/\\/,ce,/[\t ]*(?:[\r\n]|\r\n)/)}),A=(ce="")=>({className:"subst",label:"interpol",begin:st(/\\/,ce,/\(/),end:/\)/}),O=(ce="")=>({begin:st(ce,/"""/),end:st(/"""/,ce),contains:[w(ce),E(ce),A(ce)]}),k=(ce="")=>({begin:st(ce,/"/),end:st(/"/,ce),contains:[w(ce),A(ce)]}),D={className:"string",variants:[O(),O("#"),O("##"),O("###"),k(),k("#"),k("##"),k("###")]},L=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],P={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:L},I=ce=>{let zi=st(ce,/\//),ie=st(/\//,ce);return{begin:zi,end:ie,contains:[...L,{scope:"comment",begin:`#(?!.*${ie})`,end:/$/}]}},B={scope:"regexp",variants:[I("###"),I("##"),I("#"),P]},x={match:st(/`/,Lr,/`/)},z={className:"variable",match:/\$\d+/},C={className:"variable",match:`\\$${Mf}+`},N=[x,z,C],R={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:n5,contains:[...S,b,D]}]}},W={scope:"keyword",match:st(/@/,Di(...i5),vu(Di(/\(/,/\s+/)))},X={scope:"meta",match:st(/@/,Lr)},U=[R,W,X],Q={match:vu(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:st(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,Mf,"+")},{className:"type",match:Af,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:st(/\s+&\s+/,vu(Af)),relevance:0}]},Ee={begin://,keywords:c,contains:[...n,...u,...U,p,Q]};Q.contains.push(Ee);let he={match:st(Lr,/\s*:/),keywords:"_|0",relevance:0},Ke={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",he,...n,B,...u,...f,...S,b,D,...N,...U,Q]},J={begin://,keywords:"repeat each",contains:[...n,Q]},je={begin:Di(vu(st(Lr,/\s*:/)),vu(st(Lr,/\s+/,Lr,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Lr}]},Ai={begin:/\(/,end:/\)/,keywords:c,contains:[je,...n,...u,...S,b,D,...U,Q,Ke],endsParent:!0,illegal:/["']/},$t={match:[/(func|macro)/,/\s+/,Di(x.match,Lr,Hv)],className:{1:"keyword",3:"title.function"},contains:[J,Ai,t],illegal:[/\[/,/%/]},mi={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[J,Ai,t],illegal:/\[|%/},gi={match:[/operator/,/\s+/,Hv],className:{1:"keyword",3:"title"}},Bt={begin:[/precedencegroup/,/\s+/,Af],className:{1:"keyword",3:"title"},contains:[Q],keywords:[...e5,...DT],end:/}/},me={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},un={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},zt={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Lr,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[J,...u,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:Af},...u],relevance:0}]};for(let ce of D.variants){let zi=ce.contains.find(Pi=>Pi.label==="interpol");zi.keywords=c;let ie=[...u,...f,...S,b,D,...N];zi.contains=[...ie,{begin:/\(/,end:/\)/,contains:["self",...ie]}]}return{name:"Swift",keywords:c,contains:[...n,$t,mi,me,un,zt,gi,Bt,{beginKeywords:"import",end:/$/,contains:[...n],relevance:0},B,...u,...f,...S,b,D,...N,...U,Q,Ke]}}UT.exports=r5});var qT=ve((l9,FT)=>{function s5(e){let t="true false yes no null",i="[\\w#;/?:@&=+$,.~*'()[\\]]+",n={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},r={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},s={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},a={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,r]},o=e.inherit(a,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),d={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},f={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},p={begin:/\{/,end:/\}/,contains:[f],illegal:"\\n",relevance:0},_={begin:"\\[",end:"\\]",contains:[f],illegal:"\\n",relevance:0},S=[n,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+i},{className:"type",begin:"!<"+i+">"},{className:"type",begin:"!"+i},{className:"type",begin:"!!"+i},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},d,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},p,_,s,a],m=[...S];return m.pop(),m.push(o),f.contains=m,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:S}}FT.exports=s5});var ZT=ve((c9,XT)=>{var Rf="[A-Za-z$_][0-9A-Za-z$_]*",KT=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],WT=["true","false","null","undefined","NaN","Infinity"],$T=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],GT=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],jT=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],YT=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],VT=[].concat(jT,$T,GT);function a5(e){let t=e.regex,i=(R,{after:W})=>{let X="",end:""},s=/<[A-Za-z0-9\\._:-]+\s*\/>/,a={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(R,W)=>{let X=R[0].length+R.index,U=R.input[X];if(U==="<"||U===","){W.ignoreMatch();return}U===">"&&(i(R,{after:X})||W.ignoreMatch());let Q,Ee=R.input.substring(X);if(Q=Ee.match(/^\s*=/)){W.ignoreMatch();return}if((Q=Ee.match(/^\s+extends\s+/))&&Q.index===0){W.ignoreMatch();return}}},o={$pattern:Rf,keyword:KT,literal:WT,built_in:VT,"variable.language":YT},l="[0-9](_?[0-9])*",c=`\\.(${l})`,u="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${u})((${c})|\\.)?|(${c}))[eE][+-]?(${l})\\b`},{begin:`\\b(${u})\\b((${c})\\b|\\.)?|(${c})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},d={className:"subst",begin:"\\$\\{",end:"\\}",keywords:o,contains:[]},f={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"xml"}},p={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"css"}},_={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,d],subLanguage:"graphql"}},S={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,d]},g={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},b=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,S,{match:/\$\d+/},h];d.contains=b.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(b)});let w=[].concat(g,d.contains),E=w.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(w)}]),A={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:E},O={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,t.concat(n,"(",t.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},k={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...$T,...GT]}},D={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},L={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[A],illegal:/%/},P={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function I(R){return t.concat("(?!",R.join("|"),")")}let B={match:t.concat(/\b/,I([...jT,"super","import","await"].map(R=>`${R}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},x={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},z={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},A]},C="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",N={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(C)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[A]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:E,CLASS_REFERENCE:k},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),D,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,S,g,{match:/\$\d+/},h,k,{scope:"attr",match:n+t.lookahead(":"),relevance:0},N,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[g,e.REGEXP_MODE,{className:"function",begin:C,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:E}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:r.begin,end:r.end},{match:s},{begin:a.begin,"on:begin":a.isTrulyOpeningTag,end:a.end}],subLanguage:"xml",contains:[{begin:a.begin,end:a.end,skip:!0,contains:["self"]}]}]},L,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[A,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},x,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[A]},B,P,O,z,{match:/\$[(.]/}]}}function o5(e){let t=e.regex,i=a5(e),n=Rf,r=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],s={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},a={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:r},contains:[i.exports.CLASS_REFERENCE]},o={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},l=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],c={$pattern:Rf,keyword:KT.concat(l),literal:WT,built_in:VT.concat(r),"variable.language":YT},u={className:"meta",begin:"@"+n},h=(_,S,m)=>{let g=_.contains.findIndex(b=>b.label===S);if(g===-1)throw new Error("can not find mode to replace");_.contains.splice(g,1,m)};Object.assign(i.keywords,c),i.exports.PARAMS_CONTAINS.push(u);let d=i.contains.find(_=>_.scope==="attr"),f=Object.assign({},d,{match:t.concat(n,t.lookahead(/\s*\?:/))});i.exports.PARAMS_CONTAINS.push([i.exports.CLASS_REFERENCE,d,f]),i.contains=i.contains.concat([u,s,a,f]),h(i,"shebang",e.SHEBANG()),h(i,"use_strict",o);let p=i.contains.find(_=>_.label==="func.def");return p.relevance=0,Object.assign(i,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),i}XT.exports=o5});var JT=ve((u9,QT)=>{function l5(e){let t=e.regex,i={className:"string",begin:/"(""|[^/n])"C\b/},n={className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},r=/\d{1,2}\/\d{1,2}\/\d{4}/,s=/\d{4}-\d{1,2}-\d{1,2}/,a=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,o=/\d{1,2}(:\d{1,2}){1,2}/,l={className:"literal",variants:[{begin:t.concat(/# */,t.either(s,r),/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,a,/ *#/)},{begin:t.concat(/# */,t.either(s,r),/ +/,t.either(a,o),/ *#/)}]},c={className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},u={className:"label",begin:/^\w+:/},h=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),d=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[i,n,l,c,u,h,d,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[d]}]}}QT.exports=l5});var tN=ve((h9,eN)=>{function c5(e){e.regex;let t=e.COMMENT(/\(;/,/;\)/);t.contains.push("self");let i=e.COMMENT(/;;/,/$/),n=["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"],r={begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},s={className:"variable",begin:/\$[\w_]+/},a={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},o={className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/},l={match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},c={className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/};return{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:n},contains:[i,t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},s,a,r,e.QUOTE_STRING_MODE,l,c,o]}}eN.exports=c5});var nN=ve((d9,iN)=>{var Re=mk();Re.registerLanguage("xml",_k());Re.registerLanguage("bash",bk());Re.registerLanguage("c",Sk());Re.registerLanguage("cpp",xk());Re.registerLanguage("csharp",Ck());Re.registerLanguage("css",Tk());Re.registerLanguage("markdown",Ak());Re.registerLanguage("diff",Rk());Re.registerLanguage("ruby",Dk());Re.registerLanguage("go",Ik());Re.registerLanguage("graphql",zk());Re.registerLanguage("ini",Uk());Re.registerLanguage("java",Kk());Re.registerLanguage("javascript",Vk());Re.registerLanguage("json",Zk());Re.registerLanguage("kotlin",Jk());Re.registerLanguage("less",nT());Re.registerLanguage("lua",sT());Re.registerLanguage("makefile",oT());Re.registerLanguage("perl",cT());Re.registerLanguage("objectivec",hT());Re.registerLanguage("php",fT());Re.registerLanguage("php-template",mT());Re.registerLanguage("plaintext",_T());Re.registerLanguage("python",bT());Re.registerLanguage("python-repl",ST());Re.registerLanguage("r",xT());Re.registerLanguage("rust",CT());Re.registerLanguage("scss",TT());Re.registerLanguage("shell",AT());Re.registerLanguage("sql",RT());Re.registerLanguage("swift",HT());Re.registerLanguage("yaml",qT());Re.registerLanguage("typescript",ZT());Re.registerLanguage("vbnet",JT());Re.registerLanguage("wasm",tN());Re.HighlightJS=Re;Re.default=Re;iN.exports=Re});var rN,Of,qv=se(()=>{rN=ae(nN(),1),Of=rN.default});function lN(e){let t=[];if(!e)return t;Kv.lastIndex=0;let i;for(;i=Kv.exec(e);){let n=i.index,r=i[0],s=i[1],a=i[2],o=n>0?e[n-1]:"";if(o&&/[\w.@/\\:-]/.test(o)||!s&&!a)continue;let l=r.replace(sN,"");for(;/[)\]]$/.test(l);){let u=l.endsWith(")")?")":"]",h=u===")"?"(":"[",d=l.split(h).length-1;if(l.split(u).length-1>d)l=l.slice(0,-1).replace(sN,"");else break}r=l;let c=Wr(r);c.ok&&(t.push({start:n,end:n+r.length,text:r,url:c.target.href}),Kv.lastIndex=n+Math.max(1,r.length))}return t}function cN(e){let t=lN(e);if(!t.length)return[e];let i=[],n=0;for(let r of t)r.start>n&&i.push(e.slice(n,r.start)),i.push(r),n=r.end;return n{if(n.nodeType===3){t.push(n);return}if(n.nodeType===1&&!h5.has(n.tagName))for(let r=n.firstChild;r;r=r.nextSibling)i(r)};return i(e),t}function oN(e,t){let i=t.map(l=>l.data).join(""),n=lN(i);if(!n.length)return;let r=[],s=0;for(let l of t)r.push(s),s+=l.data.length;let a=(l,c)=>{for(let u=t.length-1;u>=0;u--){let h=r[u];if(c?l>h:l>=h)return[t[u],l-h]}return[t[0],0]},o=e.ownerDocument??document;for(let l of[...n].reverse()){let[c,u]=a(l.start,!1),[h,d]=a(l.end,!0),f=o.createRange();f.setStart(c,u),f.setEnd(h,d);let p=o.createElement("a");p.href=l.url,p.dataset.acLocal=l.url,p.className="ac-local",p.appendChild(f.extractContents()),f.insertNode(p)}}function uN(e,t){for(let i of Array.from(e.querySelectorAll("a[href]"))){let n=Wv(i.getAttribute("href"));n&&(i.dataset.acLocal=n,i.classList.add("ac-local"))}for(let i of Array.from(e.querySelectorAll("pre")))i.dataset.acLinked||(i.dataset.acLinked="1",oN(i,aN(i)));for(let i of aN(e))i.parentElement?.closest("pre")||i.parentNode&&oN(i.parentNode,[i]);if(t)for(let i of Array.from(e.querySelectorAll("a.ac-local")))i.title=t}var u5,Kv,sN,h5,Df=se(()=>{lh();u5=String.raw`(?:localhost|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1?\])`,Kv=new RegExp(String.raw`(https?:\/\/)?${u5}(:\d{1,5})?((?:[/?#][^\s<>"'\`)】」』,。;!?、]*)?)`,"gi"),sN=/[.,;:!?。,;:!?…'"’”]+$/;h5=new Set(["A","BUTTON","SCRIPT","STYLE","TEXTAREA"])});function d5(e){let t=le.getState(),i=t.currentThreadId;t.openPanel("preview"),vi.getState().navigate((n,r)=>V.call(n,r),Jl(i),i,e,{push:!0})}async function bu(e){try{if((await V.call("app.openExternal",{url:e}))?.ok)return}catch{}await $n(e),we(v("links.externalFailed"))}function Lf(e){let i=e.target?.closest?.("a");if(!i)return;let n=i.getAttribute("href")??"";e.preventDefault();let r=i.dataset.acLocal||Wv(n),s=e.ctrlKey||e.metaKey;if(r&&!s){d5(r);return}/^https?:\/\//i.test(r||n)&&bu(r||n)}var If=se(()=>{an();$i();dh();Df();yu();Kn();Pt()});function p5(e){return f5(Ze.parse(e,{async:!1}))}function $v({text:e,streaming:t}){let i=(0,Ul.useRef)(null),n=(0,Ul.useMemo)(()=>p5(e),[e]);return(0,Ul.useEffect)(()=>{let r=i.current;if(r){for(let s of r.querySelectorAll("pre")){let a=s.querySelector("code");if(a&&!a.dataset.hl){a.dataset.hl="1";try{Of.highlightElement(a)}catch{}}if(!s.querySelector(".cb-copy")){let o=document.createElement("button");o.className="cb-copy",o.type="button",o.textContent=v("common.copy"),o.onclick=()=>{let l=a?.textContent??"";$n(l).then(()=>{o.textContent=v("common.copied"),setTimeout(()=>o.textContent=v("common.copy"),1200)})},s.appendChild(o)}}t||uN(r,v("links.openPreviewTitle"))}},[n,t]),(0,hN.jsx)("div",{ref:i,className:`md${t?" streaming":""}`,onClick:Lf,dangerouslySetInnerHTML:{__html:n}})}async function $n(e){try{await navigator.clipboard.writeText(e);return}catch{}try{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove()}catch{}}var Ul,hN,f5,yu=se(()=>{Ul=ae(kt(),1);kC();VC();qv();Df();If();Pt();hN=ae(ke(),1);Ze.setOptions({gfm:!0,breaks:!0});f5=e=>YC.sanitize(e,{USE_PROFILES:{html:!0}})});function m5(e){let[t,i]=(0,ao.useState)(Date.now());return(0,ao.useEffect)(()=>{if(!e)return;let n=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(n)},[e]),t}function dN({pendingCount:e}){let{projects:t,threads:i}=rt(),n=le(),{version:r}=Rr(),[s,a]=(0,ao.useState)(!1),[o,l]=(0,ao.useState)(!1),[c,u]=(0,ao.useState)(""),[h,d,f]=au(),p=i.find(A=>A.id===n.currentThreadId)??null,_=p?t.find(A=>A.id===p.projectId):t.find(A=>A.id===n.currentProjectId),S=p?.status==="running"||p?.status==="initializing",m=m5(S),g=S&&p?Math.max(0,m-p.updatedAt):0,b=p?e>0?{cls:"wait",text:v("topbar.waitAuth")}:S?{cls:"run",text:Me("topbar.running",{s:Math.floor(g/1e3)})}:p.status==="error"?{cls:"err",text:v("topbar.error")}:p.status==="closed"?{cls:"",text:v("topbar.closedResume")}:null:null,w=[{tab:"changes",icon:"changes",title:v("topbar.panelChanges")},{tab:"files",icon:"files",title:v("topbar.panelFiles")},{tab:"terminal",icon:"term",title:v("topbar.panelTerminal")},{tab:"preview",icon:"globe",title:v("preview.tab")}],E=p?[{kind:"item",label:v("common.rename"),onClick:()=>{u(p.title),a(!0)}},{kind:"item",label:v("topbar.threadInfo"),onClick:()=>l(!0)},{kind:"sep"},{kind:"item",label:v("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings"))},{kind:"label",text:r?`v${r}`:""}]:[{kind:"item",label:v("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings"))},{kind:"label",text:r?`v${r}`:""}];return(0,mt.jsxs)("header",{className:"topbar",children:[(0,mt.jsx)(cv,{className:`tb-menu-btn${n.sbHidden?" tb-sb-collapsed":""}`}),_&&(0,mt.jsx)("span",{className:"tb-crumb",children:_.name}),_&&p&&(0,mt.jsx)("span",{className:"tb-sep",children:"/"}),p?s?(0,mt.jsx)("input",{className:"tb-rename",autoFocus:!0,value:c,onChange:A=>u(A.target.value),onBlur:()=>a(!1),onKeyDown:A=>{A.key==="Enter"&&!qn(A.nativeEvent)&&c.trim()?(V.call("threads.update",{id:p.id,title:c.trim()}),a(!1)):A.key==="Escape"&&a(!1)}}):(0,mt.jsx)("span",{className:"tb-title",title:v("topbar.clickRename"),onClick:()=>{u(p.title),a(!0)},children:uh(p.title,p.titleAuto)}):(0,mt.jsx)("span",{className:"tb-title ghost",children:_?v("topbar.pickThread"):v("app.title")}),b&&(0,mt.jsxs)("span",{className:`tb-pill ${b.cls}`,children:[b.cls==="run"&&(0,mt.jsx)("span",{className:"tb-pill-dot"}),b.text]}),(0,mt.jsxs)("div",{className:"tb-right",children:[p?.model&&(0,mt.jsx)("span",{className:"tb-model",children:p.model}),w.map(A=>(0,mt.jsx)("button",{className:`ibtn${n.panelOpen&&n.panelTab===A.tab?" on":""}`,title:A.title,onClick:()=>n.panelOpen&&n.panelTab===A.tab?n.closePanel():n.openPanel(A.tab),children:(0,mt.jsx)(pe,{name:A.icon})},A.tab)),(0,mt.jsx)("button",{className:"ibtn",title:v("common.more"),onClick:A=>d(A),children:(0,mt.jsx)(pe,{name:"dots"})})]}),h&&(0,mt.jsx)(Xa,{x:h.x,y:h.y,items:E,onClose:f}),o&&p&&(0,mt.jsx)(g5,{thread:p,project:_,onClose:()=>l(!1)})]})}function g5({thread:e,project:t,onClose:i}){let n=e.usage,r=ch(),s=[[v("thread.agent"),e.provider],[v("thread.model"),e.model??v("common.default")],[v("thread.mode"),e.mode],[v("thread.effort"),e.effort??v("common.default")],[v("thread.sessionId"),e.providerSessionId??v("thread.sessionNone")],[v("thread.tokens"),Me("thread.tokensFmt",{in:Tl(n.inputTokens),out:Tl(n.outputTokens),cache:Tl(n.cacheReadTokens)})],[v("thread.cost"),n.costUsd>0?cf(n.costUsd):"\u2014"],[v("thread.created"),new Date(e.createdAt).toLocaleString(r)],[v("thread.workdir"),t?.path??"\u2014"]];e.importedFrom&&s.push([v("thread.importedFrom"),`${e.importedFrom.provider} / ${e.importedFrom.sessionId.slice(0,8)}\u2026`]);let a=new Set([v("thread.sessionId"),v("thread.workdir")]);return(0,mt.jsx)(Or,{title:v("thread.info"),onClose:i,children:(0,mt.jsx)("div",{className:"info-grid",children:s.map(([o,l])=>(0,mt.jsxs)("div",{className:"info-row",children:[(0,mt.jsx)("span",{className:"info-k",children:o}),(0,mt.jsx)("span",{className:"info-v",title:l,children:l}),a.has(o)&&l!=="\u2014"&&l!==v("thread.sessionNone")&&(0,mt.jsx)("button",{className:"ibtn",title:v("common.copy"),onClick:()=>{$n(l),we(v("common.copied"))},children:(0,mt.jsx)(pe,{name:"copy",size:12})})]},o))})})}var ao,mt,fN=se(()=>{ao=ae(kt(),1);kl();Fn();$i();ru();an();hs();uv();hf();Al();yu();Kn();uf();Pt();mt=ae(ke(),1)});function pN(e){return typeof e=="object"?e.key:e}function mN(e,t){let i=e.length;return new Proxy(e,{get(n,r,s){if(typeof r=="string"){let a=r.charCodeAt(0);if(a>=48&&a<=57){let o=+r;if(Number.isInteger(o)&&o>=0&&o{});function oo(e,t,i){let n=i.initialDeps??[],r,s=!0;function a(){var o;let c=0,u=e();if(!(u.length!==n.length||u.some((f,p)=>n[p]!==f)))return r;n=u;let d=0;return r=t(...u),i?.onChange&&!(s&&i.skipInitialOnChange)&&i.onChange(r),s=!1,r}return a.updateDeps=o=>{n=o},a}function Gv(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var ps,_N,jv=se(()=>{ps=(e,t)=>Math.abs(e-t)<1.01,_N=(e,t,i)=>{let n;return Object.assign(function(...r){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,r),i)},{cancel:()=>{e.clearTimeout(n)}})}});function vN({offset:e,isScrolling:t,elementMax:i,holdOffset:n,scrollOffset:r,pendingWrite:s,clampedMaxAtWrite:a}){var o;return t&&s===null&&e===r?"spurious":s!==null&&Math.abs(e-s.target)<1.5?"readBack":s!==null&&!s.smooth&&i!==null&&s.target>i+n+.5&&Math.abs(e-(i+n))<1.5||s!==null&&!s.smooth&&((o=s.lowMaxes)!=null&&o.some(l=>Math.abs(e-l)<1.5))?"clampedReadBack":a!==null&&Math.abs(e-a)<1.5?"clampedEcho":"external"}function bN({kind:e,offset:t,command:i,target:n}){return e!=="spurious"&&e!=="readBack"&&e!=="clampedReadBack"&&i?.index!=null&&i.phase!=="queued"&&!_5(i.phase)&&!ps(t,i.lastTargetOffset)&&!ps(t,n())&&e!=="clampedEcho"}function yN(e){let t=e[e.length-1];if(t===void 0)return!1;let i=e.length-2;for(;i>=0&&t.t-e[i].t=0&&n.t-e[r].t=0&&Math.abs(a)>=2*Math.abs(o)&&Math.abs(a)-Math.abs(o)>=.8}function SN(e){let t=e[e.length-1];if(t===void 0)return!1;let i=e.length-2;for(;i>=0&&t.t-e[i].t=.05}var _5,Yv,wN=se(()=>{jv();_5=e=>e==="smooth"||e==="smoothFinishing";Yv=40});var Su,wu,Vv,v5,xN,Hl,Bf,EN=se(()=>{wu=()=>{if(Su!==void 0)return Su;if(typeof navigator>"u")return Su=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Su=!0;let e=navigator.maxTouchPoints;return Su=navigator.platform==="MacIntel"&&e!==void 0&&e>0},v5=()=>Vv!==void 0?Vv:Vv=wu()&&typeof CSS<"u"&&typeof CSS.supports=="function"&&CSS.supports("overflow-anchor: auto"),xN=()=>!wu()||v5(),Hl={capture:!0,passive:!0},Bf=class{constructor(t){this.host=t,this._touch=null,this.inMotion=()=>this._touch!==null&&this._touch.phase!=="lateFling",this.dragging=()=>{var i;return((i=this._touch)==null?void 0:i.phase)==="down"&&this._touch.moved},this.tail=()=>{var i;return((i=this._touch)==null?void 0:i.phase)==="tail"?this._touch.moved?"fling":"tap":null},this.onScroll=({isScrolling:i,ownReadBack:n,moved:r,external:s})=>{var a,o,l;return i&&((a=this._touch)==null?void 0:a.phase)==="tail"?this._openTail(this._touch.moved||!n,!1):((o=this._touch)==null?void 0:o.phase)==="lateFling"&&(this.host.now()>this._touch.until?this._touch=null:s&&i&&r&&this._openTail(!0,!1)),!n&&i&&r&&((l=this._touch)==null?void 0:l.phase)==="down"?(this._touch.moved=!0,!0):!1},this.touchStart=()=>{this.end(),this._touch={phase:"down",moved:!1}},this.touchEnd=()=>{var i;let n=((i=this._touch)==null?void 0:i.phase)==="down"&&this._touch.moved;this.end(),this._openTail(n,n)},this.end=()=>{var i;let n=this.host.getWindow();((i=this._touch)==null?void 0:i.phase)==="tail"&&n!=null&&n.clearTimeout(this._touch.timerId),this._touch=null},this.listen=i=>{let n=()=>this.touchStart(),r=()=>this.touchEnd();return i.addEventListener("touchstart",n,Hl),i.addEventListener("touchend",r,Hl),i.addEventListener("touchcancel",r,Hl),()=>{i.removeEventListener("touchstart",n,Hl),i.removeEventListener("touchend",r,Hl),i.removeEventListener("touchcancel",r,Hl),this.end()}},this._openTail=(i,n)=>{let r=this.host.getWindow();if(r==null)return;this.end();let s={phase:"tail",moved:i,awaitingFling:n,timerId:r.setTimeout(()=>{if(this.host.tailStillMoving()){this._openTail(s.moved,s.awaitingFling);return}this._touch=s.awaitingFling?{phase:"lateFling",until:this.host.now()+1e3}:null,this.host.onTailClosed()},150)};this._touch=s}}get touch(){return this._touch}}});function C5(e,t,i,n){if(t===0)return!1;let r=n(0),s=new Set,a=0;for(;a=t)return!1;for(let l=0;li)t=r-1;else return r}return n>0?n-1:0}function T5(e,t,i,n,r){let s=e.length-1;if(e.length<=n)return{startIndex:0,endIndex:s};if(n===1&&r!==null){let c=k5(r,s,i),u=c,h=i+t;for(;ue[c].start,i),l=o;if(n===1)for(;l1){let c=Array(n).fill(0);for(;lh=0&&u.some(h=>h>=i);){let h=e[o];u[h.lane]=h.start,o--}o=Math.max(0,o-o%n),l=Math.min(s,l+(n-1-l%n))}return{startIndex:o,endIndex:l}}var CN,NN,b5,y5,AN,kN,S5,w5,MN,x5,E5,RN,TN,xu,zf,ON,Xv=se(()=>{gN();jv();wN();EN();CN=e=>{let{clientWidth:t,clientHeight:i}=e;return{width:t,height:i}},NN=e=>{let t=new Set;return{schedule:i=>{let n=e.requestAnimationFrame(()=>{t.delete(n),i()});t.add(n)},cancel:()=>{t.forEach(i=>e.cancelAnimationFrame(i)),t.clear()}}},b5=e=>e,y5=e=>{let t=e.overscan*Math.max(e.lanes??1,1),i=Math.max(e.startIndex-t,0),r=Math.min(e.endIndex+t,e.count-1)-i+1,s=new Array(r);for(let a=0;a{let i=e.scrollElement;if(!i)return;let n=e.targetWindow;if(!n)return;let r=o=>{let{width:l,height:c}=o;t({width:Math.round(l),height:Math.round(c)})};if(r(CN(i)),!n.ResizeObserver)return()=>{};let s=NN(n),a=new n.ResizeObserver(()=>{let o=()=>{r(CN(i))};e.options.useAnimationFrameWithResizeObserver?s.schedule(o):o()});return a.observe(i,{box:"content-box"}),()=>{a.unobserve(i),s.cancel()}},kN={passive:!0},S5=typeof window>"u"?!0:"onscrollend"in window,w5=(e,t,i)=>{let n=e.scrollElement;if(!n)return;let r=e.targetWindow;if(!r)return;let s=e.options.useScrollendEvent&&S5,a=0,o=s?null:_N(r,()=>t(i(n),!1),e.options.isScrollingResetDelay),l=h=>()=>{a=i(n),o?.(),t(a,h)},c=l(!0),u=l(!1);return n.addEventListener("scroll",c,kN),s&&n.addEventListener("scrollend",u,kN),()=>{n.removeEventListener("scroll",c),s&&n.removeEventListener("scrollend",u),o?.cancel()}},MN=(e,t)=>w5(e,t,i=>{let{horizontal:n,isRtl:r}=e.options;return n?i.scrollLeft*(r&&-1||1):i.scrollTop}),x5=(e,t,i)=>{if(i.options.useCachedMeasurements){let n=i.indexFromElement(e),r=i.options.getItemKey(n);return i.itemSizeCache.get(r)??i.options.estimateSize(n)}if(t?.borderBoxSize){let n=t.borderBoxSize[0];if(n)return Math.round(n[i.options.horizontal?"inlineSize":"blockSize"])}if(!t){let n=i.indexFromElement(e),r=i.options.getItemKey(n),s=i.itemSizeCache.get(r);if(s!==void 0)return s}return e[i.options.horizontal?"offsetWidth":"offsetHeight"]},E5=(e,{adjustments:t=0,behavior:i},n)=>{var r,s;(s=(r=n.scrollElement)==null?void 0:r.scrollTo)==null||s.call(r,{[n.options.horizontal?"left":"top"]:e+t,behavior:i})},RN=E5,TN=(e,t)=>e==="smooth"?t?"smoothLanded":"smooth":"instant",xu=e=>e?.phase==="smooth"||e?.phase==="smoothLanded";zf=class{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this._holdOffset=0,this._reportedOverscroll=!1,this._iosGesture=new Bf({getWindow:()=>this.targetWindow,now:()=>this.now(),tailStillMoving:()=>{let i=this.scrollState;if(i?.phase!=="queued"||this.pendingWrite!==null)return!1;let n=this._readElementOffset();return n===null||this._lastElementOffset===null||Math.abs(n-this._lastElementOffset)<1?!1:(this._lastElementOffset=n,i.samples=[...i.samples??[],{t:this.now(),offset:n}],!0)},onTailClosed:()=>{let i=this.scrollState;i?.phase==="queued"&&SN(i.samples??[])&&(this.scrollState=null),this._flushHoldIfReady(!0),this._writeAwaitingCommand(),this._retryClampedAdjustment()}}),this._lastElementOffset=null,this.pendingWrite=null,this._clampedAdjustment=null,this.elementsCache=new Map,this._resizeBatch=null,this.now=()=>{var i,n,r;return((r=(n=(i=this.targetWindow)==null?void 0:i.performance)==null?void 0:n.now)==null?void 0:r.call(n))??Date.now()},this.observer=(()=>{let i=null,n=null,r=!1,s=!1,a=new Set,o=()=>{if(i)return i;let c=this.targetWindow;if(!c||!c.ResizeObserver)return null;let u=n=NN(c);return i=new c.ResizeObserver(h=>{let d=()=>{let f={sync:!1};this._resizeBatch=f;try{h.forEach(l)}finally{this._resizeBatch=null,f.notify&&(this.notify(f.sync),this._noteClampMax(),this._flushHoldIfReady(!0),this._retryClampedAdjustment(),this.measureElement(null))}};if(this.options.useAnimationFrameWithResizeObserver)u.schedule(d);else{r=!0;try{d()}finally{r=!1}}})},l=c=>{let u=c.target,h=this.indexFromElement(u);if(!u.isConnected){this.observer.unobserve(u);for(let[d,f]of this.elementsCache)if(f===u){this.elementsCache.delete(d);break}return}this.isIndexInRange(h)&&this.shouldMeasureDuringScroll(h)&&this.resizeItem(h,this.options.measureElement(u,c,this))};return{disconnect:()=>{var c;(c=o())==null||c.disconnect(),n?.cancel(),a.clear(),s=!1,i=null,n=null},observe:c=>{let u=o();if(u){if(!r){u.observe(c,{box:"border-box"});return}a.add(c),s||(s=!0,n?.schedule(()=>{s=!1,a.forEach(h=>{h.isConnected&&i?.observe(h,{box:"border-box"})}),a.clear()}))}},unobserve:c=>{var u;a.delete(c),(u=o())==null||u.unobserve(c)}}})(),this.range=null,this.setOptions=i=>{var n;let r={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:b5,rangeExtractor:y5,onChange:()=>{},measureElement:x5,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(let u in i){let h=i[u];h!==void 0&&(r[u]=h)}let s=this.options,a=null,o=null,l=!1;if(s!==void 0&&s.enabled&&r.enabled&&r.anchorTo==="end"&&this.scrollElement!==null){let u=s.count,h=r.count,d=this.getMeasurements(),f=((n=this._singleLaneMeasurements)==null?void 0:n.items)??d,p=b=>pN(f[b]),_=u>0?p(0):null,S=u>0?p(u-1):null;if(h!==u||u>0&&h>0&&(r.getItemKey(0)!==_||r.getItemKey(h-1)!==S)){l=!0;let b=u>0?this.getVirtualItemForOffset(this.getScrollOffset())??d[0]:null;b&&(a=[b.key,this.getScrollOffset()-b.start]);let w=r.followOnAppend===!0?"auto":r.followOnAppend||null;w&&h>0&&this.isAtEnd(s.scrollEndThreshold)&&(u===0||r.getItemKey(h-1)!==S)&&(h>u||C5(u,h,p,r.getItemKey))&&(o=w)}}this.options=r,l&&(this.pendingMin=0,this.itemSizeCacheVersion++);let c=null;if(a&&this.scrollOffset!==null&&!this._awaitingCommandReadBack()){let[u,h]=a,d=this.getMeasurements(),{count:f,getItemKey:p}=this.options,_=0;for(;_{var n,r;(r=(n=this.options).onChange)==null||r.call(n,this,i)},this.maybeNotify=oo(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),i=>{this.notify(i)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{var i;this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,(i=this._momentumStop)==null||i.restore(),this._momentumStop=null,this.isScrolling=!1,this.scrollDirection=null,this._holdOffset=0,this._reportedOverscroll=!1,this._clampedAdjustment=null,this.pendingWrite=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var i;let n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((i=this.scrollElement)==null?void 0:i.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,a)=>{var o,l,c,u;let h=a?this._elementMaxScrollOffset():null,d=this._reportedOverscroll;this._reportedOverscroll=s<0||h!==null&&s>h+1;let f=s;this._lastElementOffset=f,s=this._toLayoutOffset(s);let p=this._classifyScrollEvent(s,a,h);if(p==="spurious")return;p==="readBack"?s=this.pendingWrite.target:p==="clampedReadBack"&&((o=this.scrollState)==null?void 0:o.index)!=null&&sthis.getScrollStateTarget(this.scrollState)})&&(this.scrollState=null),this.pendingWrite=null,this._clampedAdjustment!==null&&Math.abs(s-this._clampedAdjustment.maxAtWrite)>=1.5&&(this._clampedAdjustment=null);let _=this.getScrollOffset(),S=this.scrollDirection;this.scrollDirection=a?_===s?this.scrollDirection:_g-b.t<=200),{t:g,offset:f}],(S!==null&&this.scrollDirection!==S||yN(m.samples))&&(this.scrollState=null)}this._iosGesture.onScroll({isScrolling:a,ownReadBack:p==="readBack",moved:s!==_,external:p==="external"&&((l=this.scrollState)==null?void 0:l.phase)!=="smooth"&&((c=this.scrollState)==null?void 0:c.phase)!=="smoothFinishing"})&&((u=this.scrollState)==null?void 0:u.phase)==="queued"&&(this.scrollState=null),this._flushHoldIfReady(!0),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement&&this.unsubs.push(this._iosGesture.listen(this.scrollElement)),this._scrollToOffset(this.getScrollOffset())}this._noteClampMax();let r=this.pendingScrollAnchor;this.pendingScrollAnchor=null,r&&this.scrollElement&&this.options.enabled&&(r.kind==="anchor"?this._canWriteScroll()?xu(this.scrollState)&&!ps(this.getScrollOffset()-r.delta,this.scrollState.lastTargetOffset)||(this._followOffsetTarget(r.delta),this._scrollToOffset(this.getScrollOffset())):(this._holdOffset+=r.delta,this._followOffsetTarget(r.delta),this.notify(!1)):this.scrollToEnd({behavior:r.behavior})),this._flushHoldIfReady(!1),this._retryClampedAdjustment()},this._classifyScrollEvent=(i,n,r)=>{var s;return vN({offset:i,isScrolling:n,elementMax:r,holdOffset:this._holdOffset,scrollOffset:this.scrollOffset,pendingWrite:this.pendingWrite,clampedMaxAtWrite:((s=this._clampedAdjustment)==null?void 0:s.maxAtWrite)??null})},this._retryClampedAdjustment=()=>{if(this._clampedAdjustment===null||!this.scrollElement||!this.options.enabled||!this._canWriteScroll())return;let{target:i,maxAtWrite:n}=this._clampedAdjustment,r=this.getMaxScrollOffset();r>n+.5&&(this._clampedAdjustment=i>r+.5?{target:i,maxAtWrite:r}:null,this._scrollToOffset(i))},this._writeAwaitingCommand=()=>{let i=this.scrollState;if(i===null||i.phase!=="queued")return;let{behavior:n}=i;this.getMeasurements();let r=this.getScrollStateTarget(i);i.lastTargetOffset=r,this._clampedAdjustment=null,i.phase=TN(n,i.index!=null&&ps(r,this.getScrollOffset())),this._scrollToOffset(r,{behavior:n}),this.scheduleScrollReconcile()},this._readElementOffset=()=>{let i=this.scrollElement;if(i==null)return null;let{horizontal:n,isRtl:r}=this.options;return typeof i.scrollTop=="number"?n?i.scrollLeft*(r&&-1||1):i.scrollTop:typeof i.scrollY=="number"?n?i.scrollX:i.scrollY:null},this._canWriteScroll=()=>!(wu()&&this._iosGesture.inMotion())&&!this._reportedOverscroll,this._flushHoldIfReady=i=>{var n;if(this._holdOffset===0||!this.scrollElement||!this.options.enabled||!this._canWriteScroll()||((n=this.scrollState)==null?void 0:n.phase)==="smooth")return;this._holdOffset=0,this.scrollOffset!==null&&this.scrollOffset<0&&(this.scrollOffset=0),this.notify(i);let r=this.getCommandWrittenOffset()??this.getScrollOffset();this._clampedAdjustment=this._clampedBy(r),this._scrollToOffset(r)},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=oo(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(i,n,r,s,a,o,l,c)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMin=null,{count:i,paddingStart:n,scrollMargin:r,getItemKey:s,enabled:a,lanes:o,laneAssignmentMode:l,gap:c}),{key:!1}),this.isIndexInRange=i=>i>=0&&i[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:i,paddingStart:n,scrollMargin:r,getItemKey:s,enabled:a,lanes:o,laneAssignmentMode:l,gap:c},u)=>{var h;let d=this.itemSizeCache;if(!a)return this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>i)for(let g of this.laneAssignments.keys())g>=i&&this.laneAssignments.delete(g);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(g=>{this.itemSizeCache.set(g.key,g.size)}));let f=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===i&&(this.lanesSettling=!1),o===1){let g=i*2,b=(h=this._singleLaneMeasurements)==null?void 0:h.flat;if(!b||b.length0&&O.set(b.subarray(0,f*2)),b=O}let w=f===0?new Array(i):this._singleLaneMeasurements.items.slice(),E;if(f===0)E=n+r;else{let O=f-1;E=b[O*2]+b[O*2+1]+c}for(let O=f;O1){E=w;let P=_[E],I=P!==void 0?p[P]:void 0;A=I?I.end+c:n+r}else if(m===o){let P=0,I=S[0],B=_[0];for(let x=1;xthis.options.debug}),this.calculateRange=oo(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(i,n,r,s)=>i.length===0||n===0?(this.range=null,null):(this.range=T5(i,n,r,s,s===1&&this._singleLaneMeasurements!==null?this._singleLaneMeasurements.flat:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=oo(()=>{let i=null,n=null,r=this.calculateRange();return r&&(i=r.startIndex,n=r.endIndex),this.maybeNotify.updateDeps([this.isScrolling,i,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,i,n,this.options.lanes]},(i,n,r,s,a,o)=>s===null||a===null?[]:i({startIndex:s,endIndex:a,overscan:n,count:r,lanes:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=i=>{let n=this.options.indexAttribute,r=i.getAttribute(n);return r?parseInt(r,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=i=>{var n;if(!xu(this.scrollState))return!0;let r=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(r!==void 0&&this.range){let s=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,r-s),o=Math.min(this.options.count-1,r+s);return i>=a&&i<=o}return!0},this.measureElement=i=>{if(!i){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}let n=this.indexFromElement(i);if(!this.isIndexInRange(n))return;let r=this.options.getItemKey(n),s=this.elementsCache.get(r);s!==i&&(s&&this.observer.unobserve(s),this.observer.observe(i),this.elementsCache.set(r,i)),i.isConnected&&(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(i,void 0,this))},this.resizeItem=(i,n)=>{var r,s,a;if(!this.isIndexInRange(i))return;(r=this._resizeBatch)!=null&&r.sync&&this.getMeasurements();let o,l,c,u=(s=this._singleLaneMeasurements)==null?void 0:s.flat;if(this.options.lanes===1&&u!=null)c=this.options.getItemKey(i),l=u[i*2],o=u[i*2+1];else{let f=this.measurementsCache[i];if(!f)return;c=f.key,l=f.start,o=f.size}let h=this.itemSizeCache.get(c)??o,d=n-h;if(d!==0){let f=this.options.anchorTo==="end"&&!xu(this.scrollState)&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,p=f?this._getLayoutTotalSize():0,_=this.getScrollOffset(),m=!this.itemSizeCache.has(c)?l<_:l+h<=_&&this.scrollDirection!=="backward",g=!xu(this.scrollState)&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[i]??{index:i,key:c,start:l,size:o,end:l+o,lane:0},d,this):m);(this.pendingMin===null||i[this.getVirtualIndexes(),this.getMeasurements(),this._holdOffset],(i,n,r)=>{let s=[];for(let a=0,o=i.length;athis.options.debug}),this.getVirtualItemForOffset=i=>{var n;let r=this.getMeasurements();if(r.length===0)return;let s=(n=this._singleLaneMeasurements)==null?void 0:n.flat,a=this.options.lanes===1&&s!=null,o=ON(0,r.length-1,a?l=>s[l*2]:l=>Gv(r[l]).start,i);return Gv(r[o])},this._noteClampMax=()=>{if(!this._awaitingCommandReadBack())return;let i=this._elementMaxScrollOffset();if(i===null)return;let n=this.pendingWrite,r=Math.max(i,0)+this._holdOffset;if(r>=n.target)return;let s=n.lowMaxes??(n.lowMaxes=[]);s[s.length-1]!==r&&s.push(r)},this.getMaxScrollOffset=()=>(this._elementMaxScrollOffset()??0)+this._holdOffset,this._toLayoutOffset=i=>{var n;let r=i+this._holdOffset;return((n=this.pendingScrollAnchor)==null?void 0:n.kind)==="anchor"&&(r+=this.pendingScrollAnchor.delta),r},this._elementMaxScrollOffset=()=>{let i=this.scrollElement;if(i===null)return null;if("scrollHeight"in i)return this.options.horizontal?i.scrollWidth-i.clientWidth:i.scrollHeight-i.clientHeight;if("document"in i){let n=i.document.documentElement;return this.options.horizontal?n.scrollWidth-i.innerWidth:n.scrollHeight-i.innerHeight}return null},this._momentumStop=null,this._stopMomentum=i=>{let n=this.scrollElement,r=this.targetWindow;if(n===null||r===null)return;let s="document"in n?n.document.scrollingElement:n;if(!s?.style)return;if(this._momentumStop){this._momentumStop.done=i;return}let{style:a}=s,o=this.options.horizontal?"overflow-x":"overflow-y",l=a.getPropertyValue(o),c=a.getPropertyPriority(o),u=()=>this.options.horizontal?s.clientHeight:s.clientWidth,h=u();if(a.setProperty(o,"hidden","important"),u()!==h){a.setProperty(o,l,c);return}let d={restore:()=>a.getPropertyValue(o)!=="hidden"||a.getPropertyPriority(o)!=="important"?!1:(a.setProperty(o,l,c),!0),done:i};this._momentumStop=d,r.requestAnimationFrame(()=>r.requestAnimationFrame(()=>{this._momentumStop===d&&(this._momentumStop=null,d.restore()&&d.done())}))},this._clampedBy=i=>{let n=this._elementMaxScrollOffset();if(n===null)return null;let r=n+this._holdOffset;return i>r+.5?{target:i,maxAtWrite:r}:null},this.getVirtualDistanceFromEnd=()=>Math.max(this._getLayoutTotalSize()+this.options.scrollMargin-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(i=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=i,this.getOffsetForAlignment=(i,n,r=0)=>{if(!this.scrollElement)return 0;let s=this.getSize(),a=this.getScrollOffset();n==="auto"&&(n=i>=a+s?"end":"start"),n==="center"?i+=(r-s)/2:n==="end"&&(i-=s);let o=this.getMaxScrollOffset();return Math.max(Math.min(o,i),0)},this.getOffsetForIndex=(i,n="auto")=>{i=Math.max(0,Math.min(i,this.options.count-1));let r=this.getSize(),s=this.getScrollOffset(),a=this.measurementsCache[i];if(!a)return;if(n==="auto")if(a.end>=s+r-this.options.scrollPaddingEnd)n="end";else if(a.start<=s+this.options.scrollPaddingStart)n="start";else return[s,n];if(n==="end"&&i===this.options.count-1){let l=this.getMaxScrollOffset(),c=l-this.options.paddingEnd+this.options.scrollPaddingEnd;return[Math.max(Math.min(c,l),0),n]}let o=n==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,n,a.size),n]},this.scrollToOffset=(i,{align:n="start",behavior:r="auto"}={})=>{this._startScroll({index:null,align:n},this.getOffsetForAlignment(i,n),r,"absolute")},this.scrollToIndex=(i,{align:n="auto",behavior:r="auto"}={})=>{i=Math.max(0,Math.min(i,this.options.count-1));let s=this.getOffsetForIndex(i,n);if(!s)return;let[a,o]=s;this._startScroll({index:i,align:o},a,r,"absolute")},this.scrollBy=(i,{behavior:n="auto"}={})=>{let r=this.getOffsetForAlignment((this.getCommandWrittenOffset()??this.getScrollOffset())+i,"start");this._startScroll({index:null,align:"start"},r,n,"relative")},this.scrollToEnd=({behavior:i="auto"}={})=>{if(this.options.count>0){this._startScroll({index:this.options.count-1,align:"end",toEnd:!0},Math.max(this.getMaxScrollOffset(),0),i,"absolute");return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:i})},this.cancelScroll=()=>{this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null},this.getTotalSize=()=>Math.max(this._getLayoutTotalSize()-this._holdOffset,0),this._getLayoutTotalSize=()=>{var i,n;let r=this.getMeasurements(),s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){let a=r.length-1,o=(i=this._singleLaneMeasurements)==null?void 0:i.flat;o!=null?s=o[a*2]+o[a*2+1]:s=((n=r[a])==null?void 0:n.end)??0}else{let a=Array(this.options.lanes).fill(null),o=r.length-1;for(;o>=0&&a.some(l=>l===null);){let l=r[o];a[l.lane]===null&&(a[l.lane]=l.end),o--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{let i=[];if(this.itemSizeCache.size===0)return i;let n=this.getMeasurements();for(let r of n)r&&this.itemSizeCache.has(r.key)&&i.push({index:r.index,key:r.key,start:r.start,size:r.size,end:r.end,lane:r.lane});return i},this._scrollToOffset=(i,{adjustments:n,behavior:r}={})=>{let s={target:i+(n??0),smooth:r==="smooth"};return this.pendingWrite=s,this.options.scrollToFn(i-this._holdOffset,{behavior:r,adjustments:n},this),s},this.getCommandWrittenOffset=()=>this.scrollState!==null&&this.pendingWrite!==null&&!this.pendingWrite.smooth?this.pendingWrite.target:null,this._awaitingCommandReadBack=()=>{let i=this.getCommandWrittenOffset();return!(wu()&&this._iosGesture.dragging())&&i!==null&&!ps(i,this.getScrollOffset())},this._followOffsetTarget=i=>{this.scrollState!==null&&this.scrollState.index==null&&(this.scrollState.lastTargetOffset+=i)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}get scrollAdjustments(){return 0}applyScrollAdjustment(t,i){if(t===0)return!1;if(this._followOffsetTarget(t),this._canWriteScroll()){let n=this.getScrollOffset();this._clampedAdjustment=this._clampedBy(n+t);let r=this._scrollToOffset(n,{adjustments:t,behavior:i});return this.scrollOffset!==null&&(this.pendingWrite===r&&(this.scrollOffset+=t),this.scrollOffset<0&&(this.scrollOffset=0)),!0}else return this._holdOffset+=t,this.scrollOffset!==null&&(this.scrollOffset+=t),!0}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}getScrollStateTarget(t){let i=t.toEnd?[Math.max(this.getMaxScrollOffset(),0)]:t.index!=null?this.getOffsetForIndex(t.index,t.align):void 0;return i?i[0]:t.lastTargetOffset}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}if(this.scrollState.phase==="queued"){this.scheduleScrollReconcile();return}this.getMeasurements();let n=this.getScrollStateTarget(this.scrollState),r=this.scrollState.index==null?1:this.options.useAnimationFrameWithResizeObserver?3:2,s=n!==this.scrollState.lastTargetOffset;if(!s&&ps(n,this.getScrollOffset())){if(this.scrollState.phase==="smooth"?this.scrollState.phase="smoothLanded":this.scrollState.phase==="smoothFinishing"&&(this.scrollState.phase="instant"),this.scrollState.stableFrames++,this.scrollState.stableFrames>=r){this.getScrollOffset()!==n&&this._scrollToOffset(n,{behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,s){let a=this.getSize()||600,o=Math.abs(n-this.getScrollOffset()),l=xu(this.scrollState)&&o>a;this.scrollState.lastTargetOffset=n,l?this.scrollState.phase="smooth":this.scrollState.phase==="smooth"?this.scrollState.phase="smoothFinishing":this.scrollState.phase==="smoothLanded"&&(this.scrollState.phase="instant"),this._scrollToOffset(n,{behavior:l?"smooth":"auto"})}this.scheduleScrollReconcile()}_startScroll(t,i,n,r){this.pendingScrollAnchor=null,this._clampedAdjustment=null;let s=this._iosGesture.tail();if(r==="absolute"&&s!==null){if(s==="fling"&&xN()){this._stopMomentum(()=>{let a=this.scrollState;a?.phase!=="queued"||this._iosGesture.tail()!=="fling"||this._reportedOverscroll||(this._iosGesture.end(),this._flushHoldIfReady(!0),this._writeAwaitingCommand())}),this.scrollState={...t,startedAt:this.now(),lastTargetOffset:i,stableFrames:0,phase:"queued",behavior:n,samples:[]},this.scheduleScrollReconcile();return}this._iosGesture.end()}this.scrollState={...t,startedAt:this.now(),lastTargetOffset:i,stableFrames:0,behavior:n,phase:TN(n,t.index!=null&&ps(i,this.getScrollOffset()))},this._scrollToOffset(i,{behavior:n}),this.scheduleScrollReconcile()}},ON=(e,t,i,n)=>{for(;e<=t;){let r=(e+t)/2|0,s=i(r);if(sn)t=r-1;else return r}return e>0?e-1:0}});function N5({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:i="transform",...n}){let r=lr.useReducer(d=>d+1,0)[1],s=lr.useRef({enabled:t,mode:i,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});s.current.enabled=t,s.current.mode=i;let a=lr.useRef(!1),o=d=>{let f=s.current;if(!f.enabled||!f.container)return;let p=d.getTotalSize();if(p!==f.lastSize){f.lastSize=p;let _=d.options.horizontal?"width":"height";f.container.style[_]=`${p}px`}},l=(d,f,p)=>{let _=s.current,S=!!d.options.horizontal,m=f.start-d.options.scrollMargin;_.lastPositions.get(p)!==m&&(_.lastPositions.set(p,m),_.mode==="transform"?p.style.transform=S?`translate3d(${m}px, 0, 0)`:`translate3d(0, ${m}px, 0)`:p.style[S?"left":"top"]=`${m}px`)},c=d=>{let f=s.current;if(!(!f.enabled||!f.container)){o(d);for(let p of d.getVirtualItems()){let _=d.elementsCache.get(p.key);_&&l(d,p,_)}}},u={...n,onChange:(d,f)=>{var p;let _=s.current,S=!0;if(_.enabled){c(d);let m=d.range,g=_.prevRange;S=!g||g.isScrolling!==d.isScrolling||g.startIndex!==m?.startIndex||g.endIndex!==m?.endIndex,S&&(_.prevRange=m?{startIndex:m.startIndex,endIndex:m.endIndex,isScrolling:d.isScrolling}:null)}S&&(e&&f&&!a.current?(0,DN.flushSync)(r):r()),(p=n.onChange)==null||p.call(n,d,f)}},[h]=lr.useState(()=>{let d=new zf(u),f=d.measureElement;return d.measureElement=p=>{a.current=!0;try{f(p)}finally{a.current=!1}let _=s.current;if(p!==null&&_.enabled&&_.container){let S=d.measurementsCache[d.indexFromElement(p)];S&&l(d,S,p)}},Object.assign(d,{containerRef:p=>{let _=s.current;_.container=p,_.lastSize=null,p!==null&&c(d)}})});return h.setOptions(u),Zv(()=>h._didMount(),[]),Zv(()=>(o(h),h._willUpdate())),Zv(()=>{c(h)}),h}function LN(e){return N5({observeElementRect:AN,observeElementOffset:MN,scrollToFn:RN,...e})}var lr,DN,Zv,IN=se(()=>{lr=ae(kt(),1),DN=ae(xa(),1);Xv();Xv();Zv=typeof document<"u"?lr.useLayoutEffect:lr.useEffect});function Fl(){return{items:[],seenSeq:new Set,byItemId:new Map,toolLoc:new Map,openGroup:null,reqLoc:new Map,turnUsage:new Map,lastUserIdx:new Map,turnStart:new Map}}function ms(e){e.openGroup=null}function BN(e,t,i,n){let r=e.byItemId.get(t);if(r){let o=e.items[r.idx];o.text+=n,o.streaming=!0;return}ms(e);let s=`${i}:${t}`,a=i==="assistant"?{kind:"assistant",key:s,itemId:t,text:n,streaming:!0}:{kind:"reasoning",key:s,itemId:t,text:n,streaming:!0};e.byItemId.set(t,{idx:e.items.length,field:i}),e.items.push(a)}function A5(e,t,i){let n=/^(.*):[ktx]\d+$/.exec(t);if(!n)return;let r=n[1]+":";for(let[s,a]of[...e.byItemId])a.field===i&&s.startsWith(r)&&s!==t&&(e.items[a.idx]={kind:"gone",key:`gone:${s}`},e.byItemId.delete(s))}function zN(e,t,i,n){A5(e,t,i);let r=e.byItemId.get(t);if(r){let o=e.items[r.idx];o.text=n,o.streaming=!1;return}ms(e);let s=`${i}:${t}`,a=i==="assistant"?{kind:"assistant",key:s,itemId:t,text:n,streaming:!1}:{kind:"reasoning",key:s,itemId:t,text:n,streaming:!1};e.byItemId.set(t,{idx:e.items.length,field:i}),e.items.push(a)}function M5(e,t){let i=e.toolLoc.get(t.itemId);if(i){let a=e.items[i.group];if(a?.kind==="toolgroup"){let o=a.steps[i.step];a.steps[i.step]={...o,kind:t.kind==="other"&&o.kind!=="other"?o.kind:t.kind,title:t.title||o.title,status:t.status,input:t.input??o.input,detail:t.detail??o.detail,output:t.output??o.output,exitCode:t.exitCode??o.exitCode,durationMs:t.durationMs??o.durationMs}}return}let n={itemId:t.itemId,kind:t.kind,title:t.title,status:t.status,input:t.input,detail:t.detail,output:t.output,exitCode:t.exitCode,durationMs:t.durationMs},r=e.openGroup;(r==null||e.items[r]?.kind!=="toolgroup")&&(r=e.items.length,e.items.push({kind:"toolgroup",key:`tg:${t.itemId}`,steps:[]}),e.openGroup=r);let s=e.items[r];e.toolLoc.set(t.itemId,{group:r,step:s.steps.length}),s.steps.push(n)}function Pf(e,t){if(t.seq!=null&&t.seq>0){if(e.seenSeq.has(t.seq))return;e.seenSeq.add(t.seq)}switch(t.type){case"user_message":ms(e),e.lastUserIdx.set(t.turnId??"",e.items.length),e.items.push({kind:"user",key:`u:${t.seq}`,text:t.text,attachments:t.attachments,...t.mentions?.length?{mentions:t.mentions}:{},steered:t.steered,ts:t.ts});return;case"assistant_delta":BN(e,t.itemId,"assistant",t.text);return;case"reasoning_delta":BN(e,t.itemId,"reasoning",t.text);return;case"assistant_message":zN(e,t.itemId,"assistant",t.text);return;case"reasoning":zN(e,t.itemId,"reasoning",t.text);return;case"tool_output_delta":{let i=e.toolLoc.get(t.itemId);if(i){let n=e.items[i.group];if(n?.kind==="toolgroup"){let r=n.steps[i.step];r.output=(r.output??"")+t.text}}return}case"tool_call":M5(e,t);return;case"plan":ms(e),e.items.push({kind:"plan",key:`plan:${t.itemId}`,itemId:t.itemId,markdown:t.markdown});return;case"todo":ms(e),e.items.push({kind:"todo",key:`todo:${t.seq}`,items:t.items});return;case"permission_request":ms(e),e.reqLoc.set(t.requestId,e.items.length),e.items.push({kind:"permission",key:`perm:${t.requestId}`,requestId:t.requestId,title:t.title,kindStr:t.kind,detail:t.detail,options:t.options,status:"pending"});return;case"permission_resolved":{let i=e.reqLoc.get(t.requestId),n=i!=null?e.items[i]:null;n?.kind==="permission"&&(n.status=t.cancelled?"cancelled":"resolved",n.choice=t.optionId);return}case"question":ms(e),e.reqLoc.set(t.requestId,e.items.length),e.items.push({kind:"question",key:`q:${t.requestId}`,requestId:t.requestId,questions:t.questions,status:"pending"});return;case"question_answered":{let i=e.reqLoc.get(t.requestId),n=i!=null?e.items[i]:null;n?.kind==="question"&&(n.status="answered",n.answers=t.answers);return}case"usage":{let i=t.turnId??"",n=e.turnUsage.get(i)??{inputTokens:0,outputTokens:0,cacheReadTokens:0,costUsd:0};n.inputTokens+=t.inputTokens,n.outputTokens+=t.outputTokens,n.cacheReadTokens+=t.cacheReadTokens,n.costUsd+=t.costUsd,e.turnUsage.set(i,n);return}case"notice":ms(e),e.items.push({kind:"notice",key:`n:${t.seq}`,level:t.level,message:t.message});return;case"turn_ended":ms(e),e.items.push({kind:"turnend",key:`te:${t.seq}`,status:t.status,durationMs:t.durationMs??(e.turnStart.has(t.turnId)?Math.max(0,t.ts-e.turnStart.get(t.turnId)):void 0),error:t.error,filesChanged:t.filesChanged,usage:e.turnUsage.get(t.turnId)});return;case"turn_started":e.turnStart.set(t.turnId,t.ts);return;case"status":return;default:return}}function PN(e,t={}){let i=Fl();for(let s of e)Pf(i,s);let n=t.runtimeStatus!=="running"&&t.runtimeStatus!=="initializing",r=null;for(let s of i.items){if(s.kind==="user"&&(r=s.text),n&&s.kind==="permission"&&s.status==="pending"&&(s.status="cancelled"),n&&s.kind==="question"&&s.status==="pending"&&(s.status="cancelled"),n&&s.kind==="toolgroup")for(let a of s.steps)a.status==="running"&&(a.status="failed");(s.kind==="assistant"||s.kind==="reasoning")&&n&&s.streaming&&(s.streaming=!1)}return{items:i.items,lastUserText:r}}var UN=se(()=>{});var FN={};pO(FN,{useTimeline:()=>Gn});function HN(){let e=ca!=="running"&&ca!=="initializing";for(let t of Ir.items)if(e&&t.kind==="permission"&&t.status==="pending"&&(t.status="cancelled"),e&&t.kind==="question"&&t.status==="pending"&&(t.status="cancelled"),e&&(t.kind==="assistant"||t.kind==="reasoning")&&t.streaming&&(t.streaming=!1),e&&t.kind==="toolgroup")for(let i of t.steps)i.status==="running"&&(i.status="failed")}var Ir,lo,ca,Uf,Gn,ql=se(()=>{Sa();UN();an();Ir=Fl(),lo=0,ca="idle",Uf=null;Gn=Mn((e,t)=>{let i=n=>{Uf?.(),Uf=V.subscribe(`thread:${n}`,(r,s)=>{let a=s;if(t().threadId===n){if(a.type==="event"&&a.event){let o=a.event;if(o.seq!=null&&o.seq>0){if(o.seq<=lo)return;lo=Math.max(lo,o.seq)}o.type==="user_message"&&e({lastUserText:o.text}),Pf(Ir,o);let l=Ir.items.filter(c=>(c.kind==="permission"||c.kind==="question")&&c.status==="pending").map(c=>({requestId:c.requestId,kind:c.kind}));e({items:Ir.items.slice(),pending:l});return}if(a.type==="status"&&a.status){ca=a.status,HN(),e({status:ca,items:Ir.items.slice()});return}if(a.type==="queue"&&a.queue){e({queue:a.queue});return}if(a.type==="pending"&&a.pending){e({pending:a.pending});return}if(a.type==="commands"&&a.commands){e({slashCommands:a.commands});return}}},()=>lo)};return{threadId:null,status:"idle",items:[],queue:[],pending:[],lastUserText:null,error:null,slashCommands:[],open:n=>{t().threadId!==n&&(t().close(),e({threadId:n,status:"initializing",items:[],queue:[],pending:[],lastUserText:null,error:null,slashCommands:[]}),Ir=Fl(),lo=0,ca="initializing",(async()=>{try{let r=await V.call("threads.get",{id:n});if(t().threadId!==n)return;ca=r.runtimeStatus??r.meta.status;let s=PN(r.events,{runtimeStatus:ca});Ir=Fl();for(let a of r.events)Pf(Ir,a);lo=Math.max(0,...r.events.map(a=>a.seq??0)),HN(),e({items:Ir.items.slice(),status:ca,queue:r.queue??[],pending:r.pending??[],lastUserText:s.lastUserText}),t().threadId===n&&i(n)}catch(r){t().threadId===n&&e({error:String(r?.message??r),status:"error"})}})())},close:()=>{Uf?.(),Uf=null,Ir=Fl(),lo=0,e({threadId:null,items:[],queue:[],pending:[],lastUserText:null,error:null,status:"idle",slashCommands:[]})}}})});var Hf,qN=se(()=>{Hf=class{constructor(t,i=2,n=8){fe(this,"render",t);fe(this,"minStep",i);fe(this,"frac",n);fe(this,"target","");fe(this,"shown","");fe(this,"raf",0);fe(this,"running",!1);fe(this,"tick",()=>{if(this.shown===this.target){this.running=!1;return}let t=this.target.length-this.shown.length,i=Math.max(this.minStep,Math.ceil(t/this.frac));this.shown=this.target.slice(0,this.shown.length+i),this.render(this.shown),this.raf=requestAnimationFrame(this.tick)})}push(t){this.target=t,this.shown.length>t.length&&(this.shown=t),this.running||(this.running=!0,this.tick())}flush(){this.shown=this.target,this.render(this.shown),this.running=!1,this.raf&&cancelAnimationFrame(this.raf)}stop(){this.running=!1,this.raf&&cancelAnimationFrame(this.raf)}}});function Kl(){let e=location.hash.startsWith("#")?location.hash.slice(1):location.hash;return new URLSearchParams(e).get("t")??""}var Ff=se(()=>{});function R5(e){return e==="+"||e==="-"?e:" "}function KN(e){if(!Array.isArray(e))return[];let t=[];for(let i of e){if(!i||typeof i!="object")continue;let n=i,r=[];for(let a of Array.isArray(n.lines)?n.lines:[]){if(!a||typeof a!="object")continue;let o=typeof a.text=="string"?a.text:typeof a.s=="string"?a.s:"";r.push({t:R5(a.t),text:o})}let s=typeof n.head=="string"?n.head:void 0;s===void 0&&Number.isInteger(n.oldStart)&&Number.isInteger(n.newStart)&&(s=`@@ -${n.oldStart} +${n.newStart} @@`),t.push({head:s,lines:r})}return t}var WN=se(()=>{});function GN(e){return`/attachments/${e}?t=${$N()}`}function O5({text:e}){let t=(0,Kt.useMemo)(()=>cN(e),[e]);return t.length===1&&typeof t[0]=="string"?(0,$.jsx)($.Fragment,{children:e}):(0,$.jsx)($.Fragment,{children:t.map((i,n)=>typeof i=="string"?i:(0,$.jsx)("a",{href:i.url,"data-ac-local":i.url,className:"ac-local",title:v("links.openPreviewTitle"),children:i.text},n))})}function eb({path:e,isDir:t,onRemove:i}){return(0,$.jsxs)("span",{className:"mention",title:e,children:[(0,$.jsx)(pe,{name:t?"files":"file",size:12}),(0,$.jsxs)("span",{className:"mention-name",children:[D5(e),t?"/":""]}),i&&(0,$.jsx)("button",{type:"button",className:"att-x","aria-label":v("mention.remove"),onClick:i,children:"\xD7"})]})}function L5({it:e,onRetry:t}){return(0,$.jsxs)("div",{className:"um-row",children:[(0,$.jsxs)("div",{className:"um",children:[e.attachments?.filter(i=>Qv(i.mime)).map(i=>(0,$.jsx)("img",{className:"um-img",src:`/attachments/${i.id}?t=${$N()}`,alt:i.name},i.id)),e.attachments?.some(i=>!Qv(i.mime))&&(0,$.jsx)("span",{className:"um-mentions",children:e.attachments.filter(i=>!Qv(i.mime)).map(i=>(0,$.jsxs)("span",{className:"mention",title:i.name,children:[(0,$.jsx)(pe,{name:"file",size:12}),(0,$.jsx)("span",{className:"mention-name",children:i.name})]},i.id))}),e.mentions&&e.mentions.length>0&&(0,$.jsx)("span",{className:"um-mentions",children:e.mentions.map(i=>(0,$.jsx)(eb,{path:i.path,isDir:i.isDir},i.path))}),(0,$.jsx)("span",{className:"um-text",children:e.text}),(0,$.jsxs)("div",{className:"um-act",children:[(0,$.jsx)("button",{className:"ibtn",title:v("common.copy"),onClick:()=>{$n(e.text)},children:(0,$.jsx)(pe,{name:"copy",size:13})}),t&&(0,$.jsx)("button",{className:"ibtn",title:v("timeline.editResend"),onClick:()=>t(e.text,e.mentions),children:(0,$.jsx)(pe,{name:"send",size:13})})]})]}),e.steered&&(0,$.jsx)("div",{className:"um-tag",children:v("timeline.steer")})]})}function I5({it:e}){let[t,i]=(0,Kt.useState)(e.streaming?"":e.text),n=(0,Kt.useRef)(null);return(0,Kt.useEffect)(()=>{n.current||(n.current=new Hf(i)),n.current.push(e.text),e.streaming||n.current.flush()},[e.text,e.streaming]),(0,Kt.useEffect)(()=>()=>n.current?.stop(),[]),(0,$.jsx)($v,{text:t,streaming:e.streaming})}function B5({it:e}){let[t,i]=(0,Kt.useState)(!1),n=Math.max(1,Math.round(e.text.length/40));return(0,$.jsxs)("div",{className:"rs-item",children:[(0,$.jsxs)("button",{className:"rs-head",onClick:()=>i(!t),children:[(0,$.jsx)("span",{className:`caret${t?" open":""}`,children:"\u203A"})," ",Me("timeline.thinking",{s:n})]}),t&&(0,$.jsx)("div",{className:"rs-body",children:e.text})]})}function Jv(e){let t=`timeline.tool.${e}`,i=v(t);return i.startsWith("timeline.tool.")?v("timeline.tool.other"):i}function z5({it:e}){let t=e.steps.some(l=>l.status==="failed"),i=e.steps.some(l=>{let c=l.detail,u=c?.hunks??c?.diff?.hunks;return Array.isArray(u)&&u.length>0}),[n,r]=(0,Kt.useState)(t||i),s=(0,Kt.useRef)(!1);(0,Kt.useEffect)(()=>{!s.current&&(t||i)&&r(!0)},[t,i]);let a=(()=>{let l=new Map;for(let u of e.steps)l.set(u.kind,(l.get(u.kind)??0)+1);let c=[...l.entries()].map(([u,h])=>`${Jv(u)} ${h}`);return Me(e.steps.length===1?"timeline.toolSummaryOne":"timeline.toolSummary",{n:e.steps.length,parts:c.join(" \xB7 ")})})(),o=e.steps.find(l=>l.status==="running");return(0,$.jsxs)("div",{className:"tg",children:[(0,$.jsxs)("button",{className:"tg-head",onClick:()=>{s.current=!0,r(!n)},children:[(0,$.jsx)("span",{className:`caret${n?" open":""}`,children:"\u203A"}),(0,$.jsx)("span",{children:a}),o&&(0,$.jsx)("span",{className:"tg-live",children:Me("timeline.toolRunning",{kind:Jv(o.kind),title:o.title})})]}),n&&(0,$.jsx)("div",{className:"tg-list",children:e.steps.map(l=>(0,$.jsx)(P5,{s:l},l.itemId))})]})}function P5({s:e}){let t=e.detail,[i,n]=(0,Kt.useState)(e.status==="failed"||Array.isArray(t?.hunks)&&t.hunks.length>0),r=e.status==="running"?"\u2026":e.status==="ok"?"\u2713":"\u2717",s=e.status==="running"?"run":e.status==="ok"?"ok":"fail",a=e.output||e.detail;return(0,$.jsxs)("div",{className:"ts",children:[(0,$.jsxs)("button",{className:"ts-head",onClick:()=>a&&n(!i),children:[(0,$.jsx)("span",{className:`ts-ic ${s}`,children:r}),(0,$.jsx)("span",{className:"ts-title",children:e.title||Jv(e.kind)}),e.durationMs!=null&&(0,$.jsx)("span",{className:"ts-meta",children:av(e.durationMs)}),e.exitCode!=null&&e.exitCode!==0&&(0,$.jsxs)("span",{className:"ts-meta err",children:["exit ",e.exitCode]})]}),i&&(0,$.jsx)(U5,{s:e})]})}function U5({s:e}){let[t,i]=(0,Kt.useState)(!1),n=e.detail,r=n?.hunks??n?.diff?.hunks;if(r)return(0,$.jsx)(qf,{hunks:KN(r),path:n?.diff?.path??n?.path});if(e.output!=null){let s=e.output.split(` +`),a=s.length>50&&!t,o=a?s.slice(-50).join(` +`):e.output;return(0,$.jsxs)("div",{className:"ts-out",children:[a&&(0,$.jsx)("button",{className:"ts-more",onClick:()=>i(!0),children:Me("timeline.showAllLines",{n:s.length})}),(0,$.jsx)("pre",{onClick:Lf,children:(0,$.jsx)(O5,{text:o})})]})}return e.input!=null?(0,$.jsx)("pre",{className:"ts-out",children:JSON.stringify(e.input,null,2).slice(0,4e3)}):null}function qf({hunks:e,path:t,max:i=3e3}){let n=0,r=!1;return(0,$.jsxs)("div",{className:"diff",children:[t&&(0,$.jsx)("div",{className:"diff-path",children:t}),(0,$.jsx)("pre",{className:"diff-pre",children:e.map((s,a)=>(0,$.jsxs)("span",{className:"dh",children:[(0,$.jsx)("span",{className:"dh-head",children:s.head??"@@"}),s.lines.map((o,l)=>(n++,n>i?(r=!0,null):(0,$.jsxs)("span",{className:`dl ${o.t==="+"?"add":o.t==="-"?"del":""}`,children:[o.t," ",o.text,` +`]},l)))]},a))}),r&&(0,$.jsx)("div",{className:"dlg-hint",children:Me("timeline.diffClip",{n:i})})]})}function H5({it:e}){return(0,$.jsx)("div",{className:"card plan",children:(0,$.jsx)($v,{text:e.markdown})})}function F5({it:e}){let[t,i]=(0,Kt.useState)(!1),n=e.items.filter(r=>r.status==="done"||r.status==="completed").length;return(0,$.jsxs)("div",{className:"rs-item",children:[(0,$.jsxs)("button",{className:"rs-head",onClick:()=>i(!t),children:[(0,$.jsx)("span",{className:`caret${t?" open":""}`,children:"\u203A"})," ",Me("timeline.todo",{done:n,total:e.items.length})]}),t&&(0,$.jsx)("ul",{className:"todo-list",children:e.items.map((r,s)=>(0,$.jsxs)("li",{className:`todo ${r.status}`,children:[r.status==="done"||r.status==="completed"?"\u2611":r.status==="in_progress"?"\u25D0":"\u2610"," ",r.text]},s))})]})}function q5({it:e,threadId:t}){let[i,n]=(0,Kt.useState)(!1),r=l=>{n(!0),V.call("thread.respond",{id:t,requestId:e.requestId,optionId:l}).catch(()=>n(!1))},s=e.detail,a=s?.hunks??s?.diff?.hunks,o=e.status==="resolved"?e.choice==="allow_always"||e.choice==="acceptForSession"?v("timeline.permAllowSession"):e.choice==="deny"||e.choice==="reject"||e.choice==="decline"?v("timeline.permDenied"):e.choice==="implement"?v("timeline.permAllowed"):v("timeline.permAllowed"):v("timeline.permCancelled");return(0,$.jsxs)("div",{className:`card perm${e.status!=="pending"?" done":""}`,children:[(0,$.jsx)("div",{className:"perm-title",children:e.title}),s?.command&&(0,$.jsx)("pre",{className:"perm-cmd",children:s.command}),s?.path&&(0,$.jsx)("div",{className:"perm-path",children:s.path}),a&&(0,$.jsx)(qf,{hunks:a,path:s?.diff?.path??s?.path,max:200}),e.status==="pending"?(0,$.jsx)("div",{className:"perm-btns",children:e.options.map(l=>(0,$.jsx)("button",{className:`btn ${l.kind==="allow_once"?"primary":l.kind==="reject_once"?"danger":""}`,disabled:i,onClick:()=>r(l.id),children:l.label},l.id))}):(0,$.jsx)("div",{className:"perm-done",children:o})]})}function K5({it:e,threadId:t}){let[i,n]=(0,Kt.useState)({}),[r,s]=(0,Kt.useState)({}),a=e.questions,o=(c,u)=>c.id??c.question??c.header??`q${u}`,l=()=>{let c={};a.forEach((u,h)=>{c[o(u,h)]=i[h]?.trim()||r[h]||""}),V.call("thread.respond",{id:t,requestId:e.requestId,answers:c})};return(0,$.jsxs)("div",{className:`card ask${e.status!=="pending"?" done":""}`,children:[a.map((c,u)=>(0,$.jsxs)("div",{className:"ask-q",children:[(0,$.jsx)("div",{className:"ask-t",children:c.header??c.question}),e.status==="pending"?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)("div",{className:"ask-opts",children:c.options?.map(h=>(0,$.jsx)("button",{className:`btn${r[u]===h.label?" primary":""}`,onClick:()=>s(d=>({...d,[u]:h.label})),children:h.label},h.label))}),(0,$.jsx)("input",{className:"tinput ask-free",placeholder:v("common.other"),value:i[u]??"",onChange:h=>n(d=>({...d,[u]:h.target.value}))})]}):(0,$.jsx)("div",{className:"perm-done",children:e.answers?Me("timeline.submitted",{ans:Object.values(e.answers).join("\u3001")}):v("timeline.permCancelled")})]},u)),e.status==="pending"&&(0,$.jsx)("button",{className:"btn primary",onClick:l,children:v("common.submit")})]})}function W5({it:e,onRetry:t,replyText:i}){let n=le(),[r,s]=(0,Kt.useState)(!1);if(e.status==="failed")return(0,$.jsxs)("div",{className:"card err-card",children:[(0,$.jsx)("div",{className:"err-line",children:Me("timeline.turnError",{err:$r(e.error??v("timeline.unknownError"))})}),(0,$.jsxs)("div",{className:"perm-btns",children:[t&&(0,$.jsx)("button",{className:"btn",onClick:t,children:v("common.retry")}),e.error&&e.error.length>60&&(0,$.jsx)("button",{className:"btn ghost",onClick:()=>s(!r),children:v("common.details")})]}),r&&(0,$.jsx)("pre",{className:"perm-cmd",children:$r(e.error??"")})]});let a=[];if(e.durationMs!=null&&a.push(av(e.durationMs)),e.usage){let o=e.usage.inputTokens+e.usage.outputTokens;o&&a.push(`${Tl(o)} tokens`),e.usage.costUsd&&a.push(cf(e.usage.costUsd))}return e.status==="interrupted"&&a.push(v("timeline.interrupted")),(0,$.jsxs)("div",{className:"te",children:[a.length>0&&(0,$.jsx)("span",{className:"te-meta",children:a.join(" \xB7 ")}),i&&(0,$.jsxs)("button",{className:"te-act",title:v("common.copy"),onClick:()=>{$n(i).then(()=>we(v("common.copied")))},children:[(0,$.jsx)(pe,{name:"copy",size:13}),(0,$.jsx)("span",{children:v("common.copy")})]}),t&&(0,$.jsxs)("button",{className:"te-act",title:v("common.retry"),onClick:t,children:[(0,$.jsx)(pe,{name:"refresh",size:13}),(0,$.jsx)("span",{children:v("common.retry")})]}),e.filesChanged!=null&&e.filesChanged>0&&(0,$.jsx)("button",{className:"te-files",onClick:()=>n.openPanel("changes"),children:Me("timeline.filesChanged",{n:e.filesChanged})})]})}function jN({it:e,threadId:t,onEditResend:i,onRetryLast:n,replyText:r}){switch(e.kind){case"user":return(0,$.jsx)(L5,{it:e,onRetry:i});case"assistant":return(0,$.jsx)("div",{className:"as",children:(0,$.jsx)(I5,{it:e})});case"reasoning":return(0,$.jsx)(B5,{it:e});case"toolgroup":return(0,$.jsx)(z5,{it:e});case"plan":return(0,$.jsx)(H5,{it:e});case"todo":return(0,$.jsx)(F5,{it:e});case"permission":return(0,$.jsx)(q5,{it:e,threadId:t});case"question":return(0,$.jsx)(K5,{it:e,threadId:t});case"notice":return(0,$.jsx)("div",{className:`nt ${e.level}`,children:$r(e.message)});case"turnend":return(0,$.jsx)(W5,{it:e,onRetry:n,replyText:r});case"gone":return null;default:return null}}var Kt,$,$N,D5,Qv,Kf=se(()=>{Kt=ae(kt(),1);yu();qN();hs();an();Ff();WN();uf();$i();Pt();Kn();Df();If();$=ae(ke(),1),$N=()=>Kl();D5=e=>e.replace(/[\\/]+$/,"").split(/[\\/]/).pop()||e,Qv=e=>!e||e.startsWith("image/")});function Eu(e,t){let i=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"),n=i?"\\":"/",r=t==="."?"":i?t.replace(/\//g,"\\"):t;return r?e.replace(/[\\/]+$/,"")+n+r:e}function YN(e){if(!e||e.length>1e4)return null;try{let t=JSON.parse(e);return typeof t.projectId!="string"||typeof t.rel!="string"||!t.rel||t.rel.length>4096?null:{projectId:t.projectId,rel:t.rel,isDir:t.isDir===!0}}catch{return null}}function VN(e,t){return e.some(i=>i.projectId===t.projectId&&i.rel===t.rel)||e.length>=50?e:[...e,t]}function XN(e){return e.map(t=>({rel:t.rel,isDir:t.isDir}))}function ZN(e,t){let i=o=>o.replace(/\\/g,"/").replace(/\/+$/,""),n=i(e),r=i(t),s=/^[a-zA-Z]:\//.test(n),a=(o,l)=>s?o.toLowerCase()===l.toLowerCase():o===l;return a(r,n)?".":r.length>n.length&&a(r.slice(0,n.length),n)&&r[n.length]==="/"?r.slice(n.length+1):null}var Wl,Wf=se(()=>{Wl="application/x-agent-console-path"});function ln({value:e,options:t,onChange:i,ariaLabel:n,title:r,className:s,children:a,prefer:o="down",matchWidth:l=!1,menuClassName:c,upAnchor:u}){let[h,d]=(0,Ni.useState)(!1),[f,p]=(0,Ni.useState)(-1),[_,S]=(0,Ni.useState)(null),m=(0,Ni.useRef)(null),g=(0,Ni.useRef)(null),b=(0,Ni.useId)(),w=t.find(I=>I.value===e),E=I=>I>=0&&I{for(let x=1;x<=t.length;x++){let z=(I+B*x+t.length*2)%t.length;if(!t[z].disabled)return z}return I},[t]),O=I=>{let B=t.findIndex(z=>z.value===e),x=I==="first"?A(-1,1):I==="last"?A(0,-1):B;E(x)||(x=A(-1,1)),p(x),S(null),d(!0)},k=I=>{d(!1),I&&m.current?.focus()},D=I=>{E(I)&&(k(!0),t[I].value!==e&&i(t[I].value))};(0,Ni.useLayoutEffect)(()=>{if(!h)return;let I=m.current?.getBoundingClientRect(),B=g.current;if(!I||!B)return;let x=window.innerWidth,z=window.innerHeight,C=l?I.width:0;B.style.minWidth=`${C}px`;let N=B.offsetWidth,R=B.scrollHeight,W=z-I.bottom-$f-Cu,X=u&&m.current?.closest(u)?.getBoundingClientRect().top||I.top,U=X-$f-Cu,Q=o==="up"?!(UU):WW,Ee=Q?U:W,he=Math.min(R,Ee),Ke=Q?X-$f-he:I.bottom+$f,J=Math.max(Cu,Math.min(I.left,x-N-Cu));S({left:J,top:Math.max(Cu,Ke),minWidth:C,maxHeight:Math.max(80,Ee)})},[h,o,l,t.length,u]),(0,Ni.useEffect)(()=>{h&&_&&g.current?.focus({preventScroll:!0})},[h,_]),(0,Ni.useEffect)(()=>{!h||f<0||g.current?.querySelector(`[data-i="${f}"]`)?.scrollIntoView({block:"nearest"})},[h,f]),(0,Ni.useEffect)(()=>{if(!h)return;let I=x=>{let z=x.target;g.current?.contains(z)||m.current?.contains(z)||k(!1)},B=()=>k(!1);return window.addEventListener("pointerdown",I,!0),window.addEventListener("resize",B),window.addEventListener("blur",B),()=>{window.removeEventListener("pointerdown",I,!0),window.removeEventListener("resize",B),window.removeEventListener("blur",B)}},[h]);let L=I=>{(I.key==="ArrowDown"||I.key==="ArrowUp"||I.key==="Enter"||I.key===" ")&&(I.preventDefault(),h?k(!1):O(I.key==="ArrowUp"?"last":void 0))},P=I=>{let B=I.key;if(B==="ArrowDown")p(x=>A(x<0?-1:x,1));else if(B==="ArrowUp")p(x=>A(x<0?0:x,-1));else if(B==="Home")p(A(-1,1));else if(B==="End")p(A(0,-1));else if(B==="Enter"||B===" ")D(f);else if(B==="Escape")k(!0);else if(B==="Tab"){k(!0);return}else if(B.length===1&&/\S/.test(B)){let x=B.toLowerCase();for(let z=1;z<=t.length;z++){let C=(Math.max(f,0)+z)%t.length;if(!t[C].disabled&&t[C].label.toLowerCase().startsWith(x)){p(C);break}}}else return;I.preventDefault(),I.stopPropagation()};return(0,Gi.jsxs)(Gi.Fragment,{children:[(0,Gi.jsx)("button",{ref:m,type:"button",className:s,title:r,"aria-label":n,"aria-haspopup":"listbox","aria-expanded":h,"aria-controls":h?`${b}-lb`:void 0,onClick:()=>h?k(!1):O(),onKeyDown:L,children:a??(0,Gi.jsx)("span",{className:"sm-val",children:w?.label??""})}),h&&(0,QN.createPortal)((0,Gi.jsx)("div",{ref:g,id:`${b}-lb`,className:`menu select-menu${c?` ${c}`:""}`,role:"listbox","aria-label":n,"aria-activedescendant":f>=0?`${b}-o${f}`:void 0,tabIndex:-1,"data-select-menu":"",style:_?{left:_.left,top:_.top,minWidth:_.minWidth,maxHeight:_.maxHeight}:{left:-9999,top:0,visibility:"hidden"},onKeyDown:P,children:t.map((I,B)=>(0,Gi.jsxs)("div",{id:`${b}-o${B}`,"data-i":B,role:"option","aria-selected":I.value===e,"aria-disabled":I.disabled||void 0,className:`mi sm-opt${B===f?" on":""}${I.disabled?" off":""}${I.danger?" danger":""}${I.hint?" has-hint":""}`,onPointerMove:()=>{!I.disabled&&f!==B&&p(B)},onClick:()=>D(B),children:[(0,Gi.jsxs)("span",{className:"sm-text",children:[(0,Gi.jsx)("span",{className:"sm-label",children:I.label}),I.hint&&(0,Gi.jsx)("span",{className:"sm-hint",children:I.hint})]}),(0,Gi.jsx)("span",{className:"sm-check","aria-hidden":"true",children:I.value===e?(0,Gi.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",children:(0,Gi.jsx)("path",{d:"M2.5 6.2 5 8.6l4.5-5",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}):null})]},I.value))}),document.body)]})}var Ni,QN,Gi,$f,Cu,Gf=se(()=>{Ni=ae(kt(),1),QN=ae(xa(),1),Gi=ae(ke(),1),$f=4,Cu=8});function tb(){return[{id:"plan",label:v("composer.mode.plan.label"),desc:v("composer.mode.plan.desc")},{id:"default",label:v("composer.mode.default.label"),desc:v("composer.mode.default.desc")},{id:"acceptEdits",label:v("composer.mode.acceptEdits.label"),desc:v("composer.mode.acceptEdits.desc")},{id:"bypassPermissions",label:v("composer.mode.bypass.label"),desc:v("composer.mode.bypass.desc"),danger:!0}]}function $5(){return[{id:"default",label:v("composer.mode.cursorAgent.label"),desc:v("composer.mode.cursorAgent.desc")},{id:"plan",label:v("composer.mode.cursorPlan.label"),desc:v("composer.mode.cursorPlan.desc")},{id:"ask",label:v("composer.mode.cursorAsk.label"),desc:v("composer.mode.cursorAsk.desc")}]}function JN(e,t,i){return(e==="cursor"?$5():tb()).filter(r=>t.includes(r.id)).map(r=>i?.[r.id]?{...r,label:G5(i[r.id])}:r)}function G5(e){let t=v(`composer.agentMode.${e}`);return t.startsWith("composer.agentMode.")?e:t}function jf(e,t){let i=v(`composer.effort.${e}`);return i.startsWith("composer.effort.")?t??e:i}var ib=se(()=>{Pt()});function nb(e){let t=e.trim();if(t){try{let i=JSON.parse(t);if(Array.isArray(i)&&i.every(n=>typeof n=="string"))return i}catch{}return null}}function rb(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let i=Number(t);return i>=5&&i<=240?i:null}var eA=se(()=>{});function tA(e){return!(e.enabled===!1||!e.available||e.status==="planned")}function V5(e){return e.status==="verified"?v("settings.providerVerified"):e.status==="experimental"?v("settings.providerExperimental"):e.status==="planned"?v("settings.providerPlanned"):v("settings.providerPending")}function iA(){V.call("providers.list").then(e=>{rt.setState({providers:e})}).catch(()=>{})}function rA({onClose:e,providers:t}){let[i,n]=(0,En.useState)(null),[r,s]=(0,En.useState)({}),[a,o]=(0,En.useState)(null),[l,c]=(0,En.useState)({}),[u,h]=(0,En.useState)({}),[d,f]=(0,En.useState)({}),[p,_]=(0,En.useState)({}),[S,m]=(0,En.useState)(null),g=tb();(0,En.useEffect)(()=>{V.call("settings.get").then(x=>n(x)),V.call("app.info").then(x=>s(x)).catch(()=>{})},[]);let b=async x=>{let z=i,C={...i,...x};n(C),x.theme&&Mr(x.theme);let N=x.contentWidth!==void 0||x.chatFontSize!==void 0;N&&nu(C);try{return await V.call("settings.set",{patch:x}),window.dispatchEvent(new CustomEvent("settings-changed",{detail:C})),!0}catch(R){return n(z),x.theme&&Mr(z?.theme),N&&nu(z??{}),we(v("settings.failSave")+ht(R),!0),!1}},w=async(x,z)=>{c(W=>({...W,[x]:z}));let C=i?.providerEnabled??{},N=i,R={...i,providerEnabled:{...C,[x]:z}};n(R);try{await V.call("settings.set",{patch:{providerEnabled:R.providerEnabled}}),window.dispatchEvent(new CustomEvent("settings-changed",{detail:R})),z||rt.setState(W=>({providers:W.providers.map(X=>X.id===x?{...X,enabled:!1}:X)})),iA()}catch(W){n(N),we(v("settings.providerToggleFailed")+ht(W),!0)}finally{c(W=>{let X={...W};return delete X[x],X})}},E=()=>{V.call("providers.list",{refresh:!0}).then(x=>{rt.setState({providers:x}),we(v("settings.providerRedetect")+" \u2713")}).catch(x=>we(ht(x),!0))},A=async(x,z)=>{let C={...i?.providerCommand??{}},N={...C[x],...z};N.executable||delete N.executable,(!N.args||N.args.length===0)&&delete N.args,JSON.stringify(C[x]??{})!==JSON.stringify(N)&&(C[x]=N,await b({providerCommand:C})&&iA())},O=x=>{let z=u[x];z!==void 0&&(A(x,{executable:z.trim()||void 0}),h(C=>{let N={...C};return delete N[x],N}))},k=x=>{let z=d[x];if(z===void 0)return;let C=nb(z);if(C===null){_(N=>({...N,[x]:!0}));return}_(N=>({...N,[x]:!1})),A(x,{args:C}),f(N=>{let R={...N};return delete R[x],R})},D=()=>{if(S===null)return;let x=rb(S);x!==null&&(m(null),x!==i?.idleCloseMinutes&&b({idleCloseMinutes:x}))},L=(x,z)=>{if(!z)return{dot:"off",text:v("settings.providerOff")};if(x.enabled===!1)return{dot:"pending",text:v("settings.providerPending")};if(!x.available)return{dot:"off",text:x.reason??v("common.notDetected")};let C=x.models?.length??0,N=V5(x),R=C>0?` \xB7 ${Me("settings.providerModels",{n:String(C)})}`:"";return{dot:x.status==="verified"?"on":"pending",text:N+R}};if(!i)return(0,ye.jsx)(Or,{title:v("settings.title"),onClose:e,children:(0,ye.jsx)("div",{className:"dlg-hint",children:v("common.loading")})});let P=(x,z,C)=>(0,ye.jsxs)("div",{className:"dlg-row",children:[(0,ye.jsx)("label",{children:x}),z,C&&(0,ye.jsx)("div",{className:"dlg-hint",style:{marginTop:4},children:C})]}),I=S!==null&&rb(S)===null,B=x=>z=>{z.key==="Enter"&&(z.preventDefault(),x())};return(0,ye.jsxs)(Or,{title:v("settings.title"),onClose:e,wide:!0,footer:(0,ye.jsx)("button",{className:"btn primary",onClick:e,children:v("common.done")}),children:[P(v("settings.defaultAgent"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.defaultAgent"),value:i.defaultProvider??"claude",onChange:x=>{b({defaultProvider:x})},options:t.map(x=>({value:x.id,label:x.name+(tA(x)?"":v("common.notInstalled")),disabled:!tA(x)}))})),(0,ye.jsxs)("div",{className:"dlg-row dlg-row-top",children:[(0,ye.jsx)("label",{children:v("settings.providers")}),(0,ye.jsxs)("div",{className:"provider-list",children:[(0,ye.jsx)("button",{type:"button",className:"btn sm provider-redetect",onClick:E,children:v("settings.providerRedetect")}),t.map(x=>{let z=l[x.id]??i.providerEnabled?.[x.id]??x.enabled!==!1,C=L(x,z),N=a===x.id,R=i.providerCommand?.[x.id],W=d[x.id]??(R?.args?.length?JSON.stringify(R.args):"");return(0,ye.jsxs)("div",{className:`provider-row${N?" open":""}`,children:[(0,ye.jsxs)("button",{type:"button",className:"provider-head",onClick:()=>o(N?null:x.id),children:[(0,ye.jsx)("span",{className:`provider-dot provider-dot-${C.dot}`,"aria-hidden":!0}),(0,ye.jsxs)("div",{className:"provider-meta",children:[(0,ye.jsx)("span",{className:"provider-name",children:x.name}),(0,ye.jsx)("span",{className:"dlg-hint",children:C.text})]}),(0,ye.jsx)("span",{className:"mi-caret",children:N?"\u25BE":"\u25B8"})]}),(0,ye.jsx)("label",{className:"provider-switch",title:x.name,children:(0,ye.jsx)("input",{type:"checkbox",checked:z,disabled:l[x.id]!==void 0,onChange:X=>{w(x.id,X.target.checked)}})}),N&&(0,ye.jsxs)("div",{className:"provider-detail",children:[x.bin&&(0,ye.jsxs)("div",{className:"dlg-hint",children:[x.bin,x.version?` \xB7 ${x.version}`:""]}),x.installHint&&(0,ye.jsxs)("div",{className:"provider-hint-row",children:[(0,ye.jsx)("code",{className:"dlg-hint",children:x.installHint}),(0,ye.jsx)("button",{type:"button",className:"te-files",onClick:()=>{navigator.clipboard?.writeText(x.installHint??"").then(()=>we(v("common.copied")))},children:v("settings.providerCopyHint")})]}),(0,ye.jsx)("div",{className:"dlg-hint",children:v("settings.providerLaunchCmd")}),(0,ye.jsx)("input",{className:"tinput",placeholder:v("settings.providerLaunchExe"),"aria-label":v("settings.providerLaunchExe"),value:u[x.id]??R?.executable??"",onChange:X=>{let U=X.target.value;h(Q=>({...Q,[x.id]:U}))},onBlur:()=>O(x.id),onKeyDown:B(()=>O(x.id))}),(0,ye.jsx)("input",{className:`tinput${p[x.id]?" err":""}`,placeholder:'["--foo"]',"aria-label":v("settings.providerLaunchArgs"),value:W,onChange:X=>{let U=X.target.value;f(Q=>({...Q,[x.id]:U})),p[x.id]&&_(Q=>({...Q,[x.id]:nb(U)===null}))},onBlur:()=>k(x.id),onKeyDown:B(()=>k(x.id))}),(0,ye.jsx)("div",{className:`dlg-hint${p[x.id]?" err":""}`,children:p[x.id]?v("settings.providerArgsInvalid"):v("settings.providerLaunchArgsHint")})]})]},x.id)})]})]}),P(v("settings.defaultMode"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.defaultMode"),value:i.defaultMode??"default",onChange:x=>{b({defaultMode:x})},options:g.map(x=>({value:x.id,label:x.label,hint:x.desc})),children:(0,ye.jsx)("span",{className:"sm-val",children:(()=>{let x=g.find(z=>z.id===(i.defaultMode??"default"));return x?`${x.label} \u2014 ${x.desc}`:""})()})}),v("settings.defaultModeHint")),P(v("settings.theme"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.theme"),value:Z_(i.theme),onChange:x=>{b({theme:x})},options:[{value:"auto",label:OE()?v("settings.themeMagpie"):v("settings.themeAuto")},{value:"light",label:v("settings.themeLight")},{value:"dark",label:v("settings.themeDark")}]})),P(v("settings.contentWidth"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.contentWidth"),value:tf(i.contentWidth),onChange:x=>{b({contentWidth:x})},options:[{value:"narrow",label:v("settings.widthNarrow")},{value:"default",label:v("settings.widthDefault")},{value:"wide",label:v("settings.widthWide")},{value:"full",label:v("settings.widthFull")}]})),P(v("settings.chatFont"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.chatFont"),value:String(ev(i.chatFontSize)),onChange:x=>{b({chatFontSize:Number(x)})},options:Array.from({length:Q_-ef+1},(x,z)=>ef+z).map(x=>({value:String(x),label:`${x} px${x===J_?v("settings.chatFontDefault"):""}`}))}),v("settings.chatFontHint")),P(v("settings.sendKey"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.sendKey"),value:i.sendKey??"enter",onChange:x=>{b({sendKey:x})},options:[{value:"enter",label:v("settings.sendEnter")},{value:"ctrlEnter",label:v("settings.sendCtrl")}]})),P(v("settings.runningSend"),(0,ye.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:v("settings.runningSend"),value:i.runningSend??"queue",onChange:x=>{b({runningSend:x})},options:[{value:"queue",label:v("settings.queue")},{value:"steer",label:v("settings.steer")}]}),v("settings.steerHint")),P(v("settings.thinking"),(0,ye.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"center",fontSize:"var(--fs-m)",color:"var(--fg)"},children:[(0,ye.jsx)("input",{type:"checkbox",checked:i.showThinking!==!1,onChange:x=>{b({showThinking:x.target.checked})}}),v("settings.showThinking")]})),P(v("settings.idleClose"),(0,ye.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[(0,ye.jsx)("input",{className:`tinput${I?" err":""}`,type:"number",min:5,max:240,step:1,style:{width:90,flex:"none"},"aria-label":v("settings.idleClose"),value:S??String(i.idleCloseMinutes??30),onChange:x=>m(x.target.value),onBlur:D,onKeyDown:B(D)}),(0,ye.jsx)("span",{className:"dlg-hint",children:v("settings.idleMinutes")})]}),I?v("settings.idleInvalid"):void 0),(0,ye.jsx)("div",{className:"msep"}),(0,ye.jsxs)("div",{className:"dlg-hint",children:[Me("settings.versionLine",{ver:r.version??"?",pid:r.pid??"?"}),(0,ye.jsx)("br",{}),v("settings.dataDir"),r.dataDir??"?"," ",(0,ye.jsx)("button",{className:"te-files",onClick:()=>{navigator.clipboard?.writeText(r.dataDir??"").catch(()=>{})},children:v("common.copy")})]})]})}function nA(e){return{sendKey:e?.sendKey==="ctrlEnter"?"ctrlEnter":"enter",runningSend:e?.runningSend==="steer"?"steer":"queue",showThinking:e?.showThinking!==!1}}function ku(){let[e,t]=(0,En.useState)(X5);return(0,En.useEffect)(()=>{V.call("settings.get").then(n=>t(nA(n))).catch(()=>{});let i=n=>t(nA(n.detail));return window.addEventListener("settings-changed",i),()=>window.removeEventListener("settings-changed",i)},[]),e}var En,ye,X5,Yf=se(()=>{En=ae(kt(),1);Al();Gf();an();Kn();ib();Pt();Fn();eA();iu();tv();ye=ae(ke(),1);X5={sendKey:"enter",runningSend:"queue",showThinking:!0}});function sA({size:e=18,className:t}){return(0,ua.jsxs)("svg",{className:t,width:e,height:e,viewBox:"0 0 64 64","aria-hidden":"true",children:[(0,ua.jsx)("rect",{width:"64",height:"64",rx:"15",fill:"#26292b"}),(0,ua.jsxs)("g",{fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"5.2",children:[(0,ua.jsx)("path",{d:"M14 20.5 25 31 14 41.5",stroke:"#fff"}),(0,ua.jsx)("path",{d:"M29.14 23.61A12 12 0 1 1 46.63 39.92L48.6 47.6 39.85 42.93A12 12 0 0 1 29.14 38.39",stroke:"#fff"}),(0,ua.jsx)("path",{d:"M35.6 35.4h6",stroke:"#2dd4bf"})]})]})}var ua,aA=se(()=>{ua=ae(ke(),1)});function oA(e,t=!1){if(t||!e.startsWith("/"))return{open:!1,query:""};let i=e.slice(1);return i.includes(` +`)||i.includes(" ")?{open:!1,query:""}:{open:!0,query:i}}function lA(e,t){let i=t.trim().toLowerCase();return i?e.filter(n=>n.name.toLowerCase().includes(i)||n.description.toLowerCase().includes(i)||(n.argumentHint??"").toLowerCase().includes(i)):e}function cA(e){let t=e.filter(r=>r.kind==="command"),i=e.filter(r=>r.kind==="skill"),n=[];if(t.length){n.push({type:"heading",id:"h-cmd",labelKey:"slashGroupCommand"});for(let r of t)n.push({type:"item",id:`c:${r.name}`,command:r})}if(i.length){n.push({type:"heading",id:"h-skill",labelKey:"slashGroupSkill"});for(let r of i)n.push({type:"item",id:`s:${r.name}`,command:r})}return n}function uA(e){return e.filter(t=>t.type==="item").map(t=>t.command)}function sb(e){return`/${e} `}function hA(e,t){return!!t&&e.trim()===`/${t}`}function ab(e,t){return t<=0?0:e<0?t-1:e>=t?0:e}var dA=se(()=>{});function fA(){let e=le(),{threads:t,providers:i,projects:n}=rt(),r=Gn(),[s,a]=(0,Ue.useState)(""),[o,l]=(0,Ue.useState)([]),[c,u]=(0,Ue.useState)([]),[h,d]=(0,Ue.useState)(!1),[f,p]=(0,Ue.useState)(!1),[_,S]=(0,Ue.useState)(null),[m,g]=(0,Ue.useState)(""),b=(0,Ue.useRef)(null),w=(0,Ue.useRef)(null),E=(0,Ue.useRef)(null),[A,O]=(0,Ue.useState)([]),[k,D]=(0,Ue.useState)(0),[L,P]=(0,Ue.useState)(0),I=(0,Ue.useRef)(!1),B=(0,Ue.useRef)(new Set),[x,z]=(0,Ue.useState)(!1),C=ku(),N=t.find(T=>T.id===e.currentThreadId),R=i.find(T=>T.id===N?.provider),W=r.status==="running"||r.status==="initializing",X=r.pending.length>0,U=R?.capabilities.steer??!1,Q=!!R&&!R.capabilities.images&&R.capabilities.imagesKnown!==!1,Ee=N?.mode??"default",he=JN(N?.provider,R?.capabilities.modes??[],R?.capabilities.modeLabels),Ke=he.find(T=>T.id===Ee),J=r.items.some(T=>T.kind==="user"),je=(0,Ue.useMemo)(()=>oA(s,I.current),[s]),Ai=(0,Ue.useMemo)(()=>lA(r.slashCommands,je.query),[r.slashCommands,je.query]),$t=(0,Ue.useMemo)(()=>cA(Ai),[Ai]),mi=(0,Ue.useMemo)(()=>uA($t),[$t]),gi=je.open&&!X;(0,Ue.useEffect)(()=>{P(0)},[je.query,gi]),(0,Ue.useEffect)(()=>{let T=N?.id;!gi||!T||B.current.has(T)||(B.current.add(T),z(!0),V.call("thread.commands",{id:T,load:!0},3e4).then(ee=>{let ue=ee.commands??[];(ue.length||!Gn.getState().slashCommands.length)&&Gn.setState({slashCommands:ue})}).catch(()=>{}).finally(()=>z(!1)))},[gi,N?.id]);let Bt=(0,Ue.useMemo)(()=>i.filter(T=>T.enabled!==!1||T.id===N?.provider),[i,N?.provider]),me=Bt.find(T=>T.id===(_??N?.provider)),un=T=>T.enabled!==!1&&T.available&&T.status!=="planned",zt=T=>{p(T),T&&(S(null),g(""))};(0,Ue.useEffect)(()=>{if(!f)return;let T=ue=>{b.current&&!b.current.contains(ue.target)&&zt(!1)},ee=ue=>{ue.key==="Escape"&&(ue.stopPropagation(),zt(!1))};return document.addEventListener("pointerdown",T,!0),window.addEventListener("keydown",ee,!0),()=>{document.removeEventListener("pointerdown",T,!0),window.removeEventListener("keydown",ee,!0)}},[f]);let ce=async(T,ee)=>{if(N){zt(!1);try{!J&&T!==N.provider&&await V.call("thread.setProvider",{id:N.id,provider:T}),await V.call("thread.setModel",{id:N.id,model:ee})}catch(ue){we(v("composer.failSwitchAgent")+ht(ue),!0)}}},zi=(0,Ue.useMemo)(()=>{let T=m.trim().toLowerCase();if(!T)return[];let ee=[];for(let ue of Bt)if(un(ue))for(let Ce of ue.models??[])(Ce.name.toLowerCase().includes(T)||Ce.id.toLowerCase().includes(T))&&ee.push({providerId:ue.id,providerName:ue.name,model:Ce});return ee.slice(0,100)},[m,Bt]),ie=!!(_&&!m.trim());(0,Ue.useEffect)(()=>{if(!W)return;let T=Date.now(),ee=setInterval(()=>D(Math.floor((Date.now()-T)/1e3)),1e3);return()=>clearInterval(ee)},[W]),(0,Ue.useEffect)(()=>{let T=w.current;if(!T)return;T.style.height="auto";let ee=parseFloat(getComputedStyle(T).lineHeight)||22;T.style.height=Math.min(T.scrollHeight,Math.round(12*ee))+"px"},[s]);let Pi=(0,Ue.useCallback)(async(T="queue")=>{let ee=e.currentThreadId,ue=s.trim();if(!(!ee||!ue&&o.length===0&&c.length===0)){W&&T==="queue"&&O(Ce=>[...Ce,ue]),a("");try{let Ce=await V.call("thread.send",{id:ee,text:ue,attachments:o.map(it=>({path:it.path,mime:it.mime,name:it.name})),...c.length?{mentions:XN(c)}:{},behavior:W&&T==="steer"&&U?"steer":"queue"});l([]),u([]),Ce?.delivered==="queued"&&W?we(v("composer.queuedToast")):Ce?.delivered==="steered"&&we(v("composer.steeredToast")),W||O(it=>[...it.slice(-9),ue])}catch(Ce){a(ue),we(v("composer.failSend")+ht(Ce),!0)}}},[s,o,c,e.currentThreadId,W,U]),Ye=T=>{if(qn(T.nativeEvent))return;if(gi&&mi.length>0){if(T.key==="ArrowDown"){T.preventDefault(),P(hr=>ab(hr+1,mi.length));return}if(T.key==="ArrowUp"){T.preventDefault(),P(hr=>ab(hr-1,mi.length));return}if(T.key==="Escape"){T.preventDefault(),I.current=!0,P(0);return}let Ce=mi[L]??mi[0],it=T.key==="Enter"&&hA(s,Ce?.name);if((T.key==="Enter"&&!T.shiftKey||T.key==="Tab")&&!it){T.preventDefault(),Ce&&(I.current=!1,a(sb(Ce.name)));return}}let ee=T.ctrlKey||T.metaKey;if(C.sendKey==="ctrlEnter"?T.key==="Enter"&&ee:T.key==="Enter"&&!T.shiftKey&&!ee){T.preventDefault(),W&&C.runningSend==="steer"&&U?Pi("steer"):Pi("queue");return}if(C.sendKey==="enter"&&T.key==="Enter"&&ee&&W){T.preventDefault(),Pi(U?"steer":"queue");return}T.key==="ArrowUp"&&s===""&&A.length>0&&(T.preventDefault(),a(A[A.length-1]))},Fe=async T=>{let ee=T.clipboardData?.items;if(!ee)return;for(let Ce of ee)if(Ce.type.startsWith("image/")){T.preventDefault();let it=Ce.getAsFile();it&&await An(it);return}let ue=T.clipboardData.getData("text/plain");if(ue&&ue.length>32*1024){T.preventDefault();let Ce=new File([ue],"paste.txt",{type:"text/plain"});await An(Ce)}},An=async T=>{let ee=Kl(),ue={path:"",name:T.name,mime:T.type||"application/octet-stream",uploading:!0};l(Ce=>[...Ce,ue]);try{let it=await(await fetch(`/api/upload?name=${encodeURIComponent(T.name)}`,{method:"POST",headers:{"x-agent-console":ee},body:T})).json();if(!it.ok)throw new Error(it.e?.message??v("composer.uploadFailed"));l(hr=>hr.map(vo=>vo===ue?{...vo,path:it.id,name:it.name??T.name,uploading:!1}:vo))}catch(Ce){l(it=>it.filter(hr=>hr!==ue)),we(v("composer.failUpload")+ht(Ce),!0)}},Gt=n.find(T=>T.id===N?.projectId)??null,qr=T=>{if(T){if(!N||T.projectId!==N.projectId){we(v("mention.otherProject"),!0);return}u(ee=>VN(ee,T)),w.current?.focus()}};(0,Ue.useEffect)(()=>{let T=ee=>qr(ee.detail);return window.addEventListener("ac-insert-mention",T),()=>window.removeEventListener("ac-insert-mention",T)}),(0,Ue.useEffect)(()=>{u([])},[e.currentThreadId]);let Kr=async T=>{if(T.preventDefault(),d(!1),T.dataTransfer.types.includes(Wl)){qr(YN(T.dataTransfer.getData(Wl)));return}for(let ee of T.dataTransfer.files)(ee.type.startsWith("image/")||ee.type.startsWith("text/"))&&await An(ee)},te=T=>{N&&V.call("thread.setMode",{id:N.id,mode:T})},oe=T=>{N&&V.call("thread.setEffort",{id:N.id,effort:T})},ge=T=>{N&&V.call("thread.setCursorOpts",{id:N.id,...T}).catch(ee=>we(ht(ee),!0))},Ae=N?.model?R?.models?.find(T=>T.id===N.model):R?.models?.find(T=>T.isDefault)??R?.models?.[0],tt=(Ae?.thinkingOptions??[]).map(T=>{let ee=T,ue=typeof ee.id=="string"?ee.id:typeof ee.reasoningEffort=="string"?ee.reasoningEffort:null,Ce=ee.id,it=ue??(Ce&&typeof Ce.reasoningEffort=="string"?Ce.reasoningEffort:null);return it?{id:it,label:typeof ee.label=="string"?ee.label:it}:null}).filter(T=>T!==null),_i=typeof Ae?.defaultThinking=="string"?Ae.defaultThinking:null,ws=tt.length>0,xs=(()=>{if(!N?.model){let ue=R?.models?.find(Ce=>Ce.isDefault);return ue?ue.name:v("composer.defaultModel")}let ee=R?.models?.find(ue=>ue.id===N.model)?.name??N.model;return N.cursorFast&&(ee+=" \xB7 Fast"),ee})();return e.currentThreadId?(0,j.jsxs)("div",{className:`composer${X?" waiting":""}`,onDrop:Kr,onDragOver:T=>{T.preventDefault();let ee=T.dataTransfer.types.includes(Wl);ee&&(T.dataTransfer.dropEffect="copy"),ee!==h&&d(ee)},onDragLeave:T=>{T.currentTarget.contains(T.relatedTarget)||d(!1)},children:[r.queue.length>0&&(0,j.jsx)("div",{className:"q-list",children:r.queue.map(T=>(0,j.jsxs)("div",{className:"q-item",children:[(0,j.jsx)("span",{className:"q-text",children:T.text}),(0,j.jsx)("button",{className:"ibtn",title:v("common.remove"),onClick:()=>{V.call("thread.queueRemove",{id:N?.id,queueId:T.id}).catch(()=>{})},children:(0,j.jsx)(pe,{name:"x",size:12})})]},T.id))}),Ee==="bypassPermissions"&&(0,j.jsx)("div",{className:"cp-danger",children:v("composer.bypassWarn")}),(0,j.jsxs)("div",{className:`cp-card${X?" waiting":""}${Ee==="bypassPermissions"?" danger":""}${h?" drop-on":""}`,children:[h&&(0,j.jsx)("div",{className:"cp-drop-hint",children:v("mention.drop")}),Q&&o.some(T=>T.mime.startsWith("image/"))&&(0,j.jsx)("div",{className:"att-note",children:Me("composer.imagesByPath",{agent:R?.name??""})}),(o.length>0||c.length>0)&&(0,j.jsxs)("div",{className:"att-bar",children:[c.map(T=>(0,j.jsx)(eb,{path:Gt?Eu(Gt.path,T.rel):T.rel,isDir:T.isDir,onRemove:()=>u(ee=>ee.filter(ue=>ue!==T))},T.rel)),o.map((T,ee)=>(0,j.jsxs)("span",{className:`att${T.uploading?" up":""}`,children:[T.mime.startsWith("image/")&&T.path?(0,j.jsx)("img",{src:GN(T.path),alt:T.name}):(0,j.jsx)(pe,{name:"attach",size:12}),(0,j.jsx)("span",{className:"att-name",children:T.name}),T.uploading&&(0,j.jsx)("span",{className:"att-prog",children:"\u2026"}),(0,j.jsx)("button",{className:"att-x",onClick:()=>l(ue=>ue.filter((Ce,it)=>it!==ee)),children:"\xD7"})]},ee))]}),(0,j.jsxs)("div",{className:"cp-ta-wrap",children:[gi&&(0,j.jsx)("div",{className:"pop agent-picker slash-pop",role:"listbox",children:(0,j.jsx)("div",{className:"ap-scroll",children:$t.length===0?(0,j.jsx)("div",{className:"ap-empty",children:v(x?"composer.slashLoading":"composer.slashNoCommands")}):$t.map(T=>{if(T.type==="heading")return(0,j.jsx)("div",{className:"slash-h",children:T.labelKey==="slashGroupCommand"?v("composer.slashGroupCommand"):v("composer.slashGroupSkill")},T.id);let ue=mi.indexOf(T.command)===L;return(0,j.jsxs)("button",{type:"button",role:"option","aria-selected":ue,className:`mi slash-item${ue?" sel":""}`,onMouseDown:Ce=>Ce.preventDefault(),onClick:()=>{I.current=!1,a(sb(T.command.name))},children:[(0,j.jsxs)("span",{className:"slash-name",children:["/",T.command.name]}),(0,j.jsx)("span",{className:"slash-desc",children:T.command.description}),T.command.argumentHint?(0,j.jsx)("span",{className:"slash-hint",children:T.command.argumentHint}):null]},T.id)})})}),(0,j.jsx)("textarea",{ref:w,className:"cp-ta",rows:1,placeholder:X?v("composer.waitPerm"):W?v(U?"composer.queuePlaceholder":"composer.queuePlaceholderNoSteer"):v("composer.inputPlaceholder"),value:s,disabled:X,onChange:T=>{I.current=!1,a(T.target.value)},onKeyDown:Ye,onPaste:Fe})]}),(0,j.jsxs)("div",{className:"cp-bar",children:[(0,j.jsxs)("div",{className:"pill-wrap",ref:b,children:[(0,j.jsxs)("button",{className:"pill chip",onClick:()=>zt(!f),title:v("composer.agentModel"),children:[(0,j.jsx)(sA,{size:18,className:"chip-logo"}),(0,j.jsx)("span",{className:"p-a",children:R?.name??N?.provider??v("composer.agent")}),(0,j.jsx)("span",{className:"p-t",children:xs}),(0,j.jsx)("svg",{className:"chip-caret",width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:(0,j.jsx)("path",{d:"M2.5 4l2.5 2.5L7.5 4",fill:"none",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"})})]}),f&&(0,j.jsxs)("div",{className:"pop agent-pop agent-picker",children:[(0,j.jsxs)("div",{className:"ap-search",children:[(0,j.jsx)(pe,{name:"search",size:14}),(0,j.jsx)("input",{className:"ap-search-in",autoFocus:!0,placeholder:v("composer.searchAllModels"),value:m,onChange:T=>g(T.target.value)})]}),m.trim()?(0,j.jsxs)("div",{className:"ap-scroll",children:[zi.length===0&&(0,j.jsx)("div",{className:"ap-empty",children:v("composer.noModelMatch")}),zi.map(({providerId:T,providerName:ee,model:ue})=>{let Ce=J&&T!==N?.provider;return(0,j.jsxs)("button",{className:"mi mi-row",disabled:Ce,onClick:()=>{ce(T,ue.id)},children:[(0,j.jsx)("span",{className:"mi-sub",children:ee}),(0,j.jsx)("span",{className:"mi-name",children:ue.name}),N?.provider===T&&N?.model===ue.id&&(0,j.jsx)("span",{className:"mi-check",children:"\u2713"})]},`${T}:${ue.id}`)})]}):ie&&me?(0,j.jsxs)("div",{className:"ap-scroll",children:[(0,j.jsxs)("button",{type:"button",className:"ap-back mi",onClick:()=>S(null),children:[(0,j.jsx)("span",{className:"ap-back-icon",children:(0,j.jsx)(pe,{name:"caret",size:14})}),me.name]}),(0,j.jsxs)("button",{className:"mi model-pick-row",title:me.models?.find(T=>T.isDefault)?.name??v("composer.defaultModel"),onClick:()=>{ce(me.id,null)},children:[(0,j.jsx)("span",{className:"model-pick-name",children:v("composer.defaultModel")}),(()=>{let T=me.models?.find(ee=>ee.isDefault);return T?(0,j.jsxs)("span",{className:"mi-sub model-pick-default",children:[" (",T.name,")"]}):null})(),N?.provider===me.id&&!N?.model?(0,j.jsx)("span",{className:"mi-check",children:"\u2713"}):""]}),(me.models??[]).filter(T=>!T.isDefault).slice(0,ob).map(T=>(0,j.jsxs)("button",{className:"mi model-pick-row",title:T.name,onClick:()=>{ce(me.id,T.id)},children:[(0,j.jsx)("span",{className:"model-pick-name",children:T.name}),N?.provider===me.id&&N?.model===T.id?(0,j.jsx)("span",{className:"mi-check",children:"\u2713"}):""]},T.id)),(me.models?.length??0)>ob&&(0,j.jsx)("div",{className:"ap-empty",children:Me("composer.moreModels",{n:String((me.models?.length??0)-ob)})})]}):(0,j.jsxs)("div",{className:"ap-scroll",children:[(0,j.jsx)("div",{className:"mlabel",children:J?v("composer.agentLocked"):v("composer.providers")}),J&&(0,j.jsx)("div",{className:"ap-empty",children:v("composer.agentLockedHint")}),Bt.length===0&&(0,j.jsx)("div",{className:"ap-empty",children:v("composer.providersLoading")}),Bt.map(T=>{let ue=un(T)&&(!J||T.id===N?.provider),Ce=T.models?.length??0,it=T.name?.trim()||T.id;return(0,j.jsxs)("button",{className:"mi mi-row provider-pick-row",disabled:!ue,onClick:()=>{ue&&S(T.id)},children:[(0,j.jsx)("span",{className:"provider-pick-name",children:it}),(0,j.jsxs)("span",{className:"provider-pick-meta",children:[T.id===N?.provider&&(0,j.jsx)("span",{className:"mi-tag",children:"Current"}),(0,j.jsx)("span",{className:"mi-meta",children:Ce===1?"1 model":`${Ce} models`}),ue&&(0,j.jsx)("span",{className:"mi-caret",children:(0,j.jsx)(pe,{name:"caret",size:14})}),T.enabled===!1&&(0,j.jsx)("span",{className:"dlg-hint",children:"Disabled"}),T.enabled!==!1&&T.status==="planned"&&(0,j.jsx)("span",{className:"dlg-hint",children:"Not available"}),T.enabled!==!1&&T.status!=="planned"&&!T.available&&(0,j.jsx)("span",{className:"dlg-hint",children:"Not detected"})]})]},T.id)})]})]})]}),ws&&(0,j.jsxs)(ln,{className:"pill ipill",title:v("composer.effortTitle"),ariaLabel:v("composer.effortTitle"),prefer:"up",upAnchor:".cp-card",value:N?.effort??"",onChange:T=>oe(T||null),options:[{value:"",label:_i?Me("composer.defaultEffortNamed",{level:jf(_i)}):v("composer.defaultEffort")},...tt.filter(T=>T.id!=="default").map(T=>({value:T.id,label:jf(T.id,T.label)}))],children:[(0,j.jsx)(pe,{name:"gauge",size:14}),(0,j.jsx)("span",{className:"ip-l",children:(()=>{let T=N?.effort??_i;return T?jf(T,tt.find(ee=>ee.id===T)?.label):v("composer.defaultEffort")})()})]}),he.length>1&&(()=>{let T=he.find(ee=>ee.id===Ee)??he[0];return(0,j.jsxs)(ln,{className:`pill ipill${T.danger?" danger":""}`,title:T.desc,ariaLabel:v("composer.modeTitle"),prefer:"up",upAnchor:".cp-card",menuClassName:"mode-menu",value:T.id,onChange:ee=>te(ee),options:he.map(ee=>({value:ee.id,label:ee.label,hint:ee.desc,danger:ee.danger})),children:[(0,j.jsx)(pe,{name:"shield",size:14}),(0,j.jsx)("span",{className:"ip-l",children:T.label})]})})(),N?.provider==="cursor"&&(0,j.jsx)(ln,{className:"pill ipill cursor-fast",title:"Fast",ariaLabel:"Fast",prefer:"up",upAnchor:".cp-card",value:N.cursorFast?"fast":"off",onChange:T=>ge({cursorFast:T==="fast"}),options:[{value:"off",label:"Fast: Off"},{value:"fast",label:"Fast: On"}],children:(0,j.jsx)("span",{className:"ip-l",children:N.cursorFast?"Fast: On":"Fast: Off"})}),(0,j.jsx)("span",{className:"cp-div","aria-hidden":"true"}),(0,j.jsx)("button",{className:"ibtn cp-attach",title:v("composer.attachTitle"),onClick:()=>E.current?.click(),children:(0,j.jsx)(pe,{name:"attach"})}),(0,j.jsx)("input",{ref:E,type:"file",hidden:!0,multiple:!0,accept:"image/*,.txt,.md,.log,.json,.csv",onChange:T=>{for(let ee of T.target.files??[])An(ee);T.target.value=""}}),(0,j.jsx)("div",{className:"cp-right",children:W?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)("span",{className:"cp-clock",children:[k,"s"]}),(s.trim()||o.length>0||c.length>0)&&(0,j.jsx)("button",{className:"cp-send",title:v(U&&C.runningSend==="steer"?"settings.steer":"settings.queue"),disabled:X||o.some(T=>T.uploading),onClick:()=>{Pi(C.runningSend==="steer"&&U?"steer":"queue")},children:(0,j.jsx)(pe,{name:"arrowUp"})}),(0,j.jsx)("button",{className:"cp-stop",title:v("common.stop"),onClick:()=>{V.call("thread.interrupt",{id:N?.id})},children:(0,j.jsx)(pe,{name:"stopFill"})})]}):(0,j.jsx)("button",{className:"cp-send",title:v("common.send"),disabled:X||!s.trim()&&o.length===0&&c.length===0||o.some(T=>T.uploading),onClick:()=>{Pi("queue")},children:(0,j.jsx)(pe,{name:"arrowUp"})})})]})]}),W&&!U&&C.runningSend==="steer"&&(0,j.jsx)("div",{className:"cp-hint",children:Me("composer.steerUnsupported",{agent:R?.name??N?.provider??""})})]}):null}var Ue,j,ob,pA=se(()=>{Ue=ae(kt(),1);kl();$i();Fn();ql();an();Ff();hs();Kf();Wf();Kn();Yf();ib();aA();Gf();Pt();dA();j=ae(ke(),1),ob=150});function gA(){let e=le(),{projects:t,threads:i}=rt(),n=Gn(),s=ku().showThinking?n.items:n.items.filter(k=>k.kind!=="reasoning"),a=(0,jn.useRef)(null),[o,l]=(0,jn.useState)(!0),[c,u]=(0,jn.useState)(!1),h=t.find(k=>k.id===e.currentProjectId)??null,d=e.currentThreadId,f=d?i.find(k=>k.id===d)??null:null,p=h&&f&&f.projectId===h.id?f.id:null;(0,jn.useEffect)(()=>{p?n.open(p):n.close(),l(!0),u(!1)},[p]);let _=(0,jn.useCallback)(k=>{let D=s[k];if(!D)return 80;switch(D.kind){case"user":return 60;case"assistant":case"reasoning":return 120;case"toolgroup":return 30+D.steps.length*26;case"plan":return 200;case"permission":case"question":return 120;case"todo":return 30;case"turnend":case"notice":return 30;default:return 60}},[s]),S=LN({count:s.length,getScrollElement:()=>a.current,estimateSize:_,getItemKey:k=>s[k]?.key??k,overscan:8,measureElement:k=>k.getBoundingClientRect().height}),m=s.length;(0,jn.useEffect)(()=>{let k=a.current;k&&(o?k.scrollTop=k.scrollHeight:u(!0))},[m,o]);let g=()=>{let k=a.current;if(!k)return;let D=k.scrollHeight-k.scrollTop-k.clientHeight<60;l(D),D&&u(!1)},b=()=>{a.current?.scrollTo({top:a.current.scrollHeight,behavior:"smooth"}),l(!0),u(!1)},w=(k,D)=>{if(!p)return;let L=h?.path,P=L&&D?.length?D.map(I=>({rel:ZN(L,I.path),isDir:I.isDir})).filter(I=>!!I.rel):[];V.call("thread.send",{id:p,text:k,...P.length?{mentions:P}:{}})},E=()=>{n.lastUserText&&w(n.lastUserText)};if(t.length===0)return(0,He.jsx)("div",{className:"scroll",ref:a,children:(0,He.jsx)(mA,{kind:"no-projects"})});if(!p)return(0,He.jsx)("div",{className:"scroll",ref:a,children:h?(0,He.jsxs)("div",{className:"empty-wrap",children:[(0,He.jsx)("div",{className:"cp-hero-t",children:Me("chat.newInProject",{name:h.name})}),(0,He.jsx)(Z5,{projectId:h.id})]}):(0,He.jsx)(mA,{kind:"pick-project"})});let A=-1;for(let k=s.length-1;k>=0;k--)if(s[k].kind==="turnend"){A=k;break}let O=k=>{let D=[];for(let L=k-1;L>=0;L--){let P=s[L];if(P.kind==="user"||P.kind==="turnend")break;P.kind==="assistant"&&D.unshift(P.text)}return D.join(` -`)};return(0,Pe.jsxs)(Pe.Fragment,{children:[(0,Pe.jsx)("div",{className:"scroll",ref:a,onScroll:m,children:(0,Pe.jsxs)("div",{className:"tl-wrap",children:[(0,Pe.jsx)("div",{style:{height:w.getTotalSize(),position:"relative"},children:w.getVirtualItems().map(T=>{let D=r[T.index];return D?(0,Pe.jsx)("div",{"data-index":T.index,ref:w.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${T.start}px)`},children:(0,Pe.jsx)(eN,{it:D,threadId:p,onEditResend:S,onRetryLast:T.index===A?k:void 0,replyText:D.kind==="turnend"?O(T.index):void 0})},T.key):null})}),n.items.length===0&&!n.error&&(0,Pe.jsx)("div",{className:"sb-empty",children:y("chat.emptyHint")}),n.error&&(0,Pe.jsx)("div",{className:"nt error",children:La(n.error)})]})}),!o&&(0,Pe.jsxs)("button",{className:"jump",onClick:v,title:y("chat.jumpBottom"),children:[(0,Pe.jsx)(ye,{name:"caret"}),c&&(0,Pe.jsx)("span",{className:"jd"})]}),(0,Pe.jsx)(gN,{})]})}function vN({kind:e}){let t=e==="pick-project";return(0,Pe.jsxs)("div",{className:"empty-wrap workspace-empty",children:[(0,Pe.jsx)("div",{className:"cp-hero-t",children:y(t?"chat.pickProjectTitle":"sidebar.noProjectsTitle")}),(0,Pe.jsx)("div",{className:"cp-hero-s",children:y(t?"chat.pickProjectSub":"sidebar.noProjectsSub")}),(0,Pe.jsx)("div",{className:"empty-actions",children:(0,Pe.jsx)("button",{type:"button",className:"btn primary",onClick:()=>window.dispatchEvent(new CustomEvent("open-new-project")),children:y("sidebar.newProject")})})]})}function Oz({projectId:e}){let t=fe(),i=ou(),[n,s]=(0,Bn.useState)(""),[r,a]=(0,Bn.useState)(!1),o=async()=>{if(!(!n.trim()||r)){a(!0);try{let l=await fl(),c=await te.call("settings.get"),u=await te.call("threads.create",{projectId:e,provider:l,model:null,mode:c.defaultMode??"default"});t.select(e,u.id),await te.call("thread.send",{id:u.id,text:n.trim()})}catch(l){Te(y("chat.failSend")+ct(l),!0),a(!1)}}};return(0,Pe.jsxs)("div",{className:"cp-card",style:{marginTop:18},children:[(0,Pe.jsx)("textarea",{className:"cp-ta",rows:3,placeholder:y("chat.emptyPlaceholder"),value:n,onChange:l=>s(l.target.value),onKeyDown:l=>{if(Mn(l.nativeEvent))return;let c=l.ctrlKey||l.metaKey;(i.sendKey==="ctrlEnter"?l.key==="Enter"&&c:l.key==="Enter"&&!l.shiftKey&&!c)&&(l.preventDefault(),o())}}),(0,Pe.jsxs)("div",{className:"cp-bar",children:[(0,Pe.jsx)("span",{className:"dlg-hint",children:y("chat.autoNewThread")}),(0,Pe.jsx)("div",{className:"cp-right",children:(0,Pe.jsx)("button",{className:"cp-send",disabled:!n.trim()||r,onClick:()=>{o()},title:y("common.send"),children:(0,Pe.jsx)(ye,{name:"send"})})})]})]})}var Bn,Pe,yN=le(()=>{Bn=ae(Nt(),1);pl();qT();dn();jn();Ml();gf();_N();Wr();Rn();Vn();yf();Ci();Pe=ae(ke(),1)});function wN({onClose:e}){let{projects:t,threads:i,providers:n}=ut(),s=fe(),[r,a]=(0,Ns.useState)(""),[o,l]=(0,Ns.useState)(0),c=(0,Ns.useRef)(null);(0,Ns.useEffect)(()=>{c.current?.focus()},[]);let u=(0,Ns.useMemo)(()=>{let f=[],p=r.trim().toLowerCase(),_=g=>!p||g.toLowerCase().includes(p),w=[[y("palette.actNewThread"),()=>{let g=s.currentProjectId??t[0]?.id;g&&d(g)}],[y("palette.actSettings"),()=>window.dispatchEvent(new CustomEvent("open-settings"))],[y("palette.actTheme"),()=>{Dz()}],[y("palette.actChanges"),()=>s.openPanel("changes")],[y("palette.actFiles"),()=>s.openPanel("files")],[y("palette.actTerminal"),()=>s.openPanel("terminal")],[y("palette.actImport"),()=>{let g=s.currentProjectId??t[0]?.id;g&&window.dispatchEvent(new CustomEvent("open-import",{detail:{projectId:g}}))}]];for(let[g,m]of w)_(g)&&f.push({id:`act:${g}`,label:g,hint:y("palette.hintAction"),run:m});for(let g of t)_(g.name)&&f.push({id:`p:${g.id}`,label:g.name,hint:y("palette.hintProject"),run:()=>s.select(g.id,null)});for(let g of i){let m=t.find(S=>S.id===g.projectId),v=`${g.title} ${m?.name??""}`;_(v)&&f.push({id:`t:${g.id}`,label:g.title,hint:m?.name??y("palette.hintThread"),run:()=>s.select(g.projectId,g.id)})}return f.slice(0,30)},[r,t,i]);(0,Ns.useEffect)(()=>{l(0)},[r]);let h=f=>{if(f.key==="ArrowDown")f.preventDefault(),l(p=>Math.min(u.length-1,p+1));else if(f.key==="ArrowUp")f.preventDefault(),l(p=>Math.max(0,p-1));else if(f.key==="Enter"&&!Mn(f.nativeEvent)){f.preventDefault();let p=u[o];p&&(e(),p.run())}else f.key==="Escape"&&(f.preventDefault(),e())};async function d(f){try{let p=await te.call("settings.get"),_=await fl(),w=await te.call("threads.create",{projectId:f,provider:_,mode:p.defaultMode??"default"});fe.getState().select(f,w.id)}catch(p){Te(y("palette.failNew")+ct(p),!0)}}return(0,SN.createPortal)((0,Ts.jsx)("div",{className:"dlg-scrim",style:{alignItems:"flex-start",paddingTop:"14vh"},onPointerDown:f=>{f.target===f.currentTarget&&e()},children:(0,Ts.jsxs)("div",{className:"dlg cpal",role:"dialog","aria-label":y("palette.aria"),children:[(0,Ts.jsx)("input",{ref:c,className:"cpal-in",placeholder:y("palette.placeholder"),value:r,onChange:f=>a(f.target.value),onKeyDown:h}),(0,Ts.jsxs)("div",{className:"cpal-list",children:[u.map((f,p)=>(0,Ts.jsxs)("button",{className:`cpal-item${p===o?" on":""}`,onMouseEnter:()=>l(p),onClick:()=>{e(),f.run()},children:[(0,Ts.jsx)("span",{className:"cpal-label",children:f.label}),f.hint&&(0,Ts.jsx)("span",{className:"cpal-hint",children:f.hint})]},f.id)),u.length===0&&(0,Ts.jsx)("div",{className:"sb-empty",children:y("palette.noMatch")})]})]})}),document.body)}async function Dz(){let e=qE()==="dark"?"light":"dark";Xs(e);try{await te.call("settings.set",{patch:{theme:e}})}catch{}}var Ns,SN,Ts,EN=le(()=>{Nd();Ns=ae(Nt(),1);pl();SN=ae(oa(),1);jn();dn();Rn();Vn();Ci();Ts=ae(ke(),1)});function Iz(e){return e.replace(/\r?\n/g,"\r")}function zz(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function Pz(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function Uz(e,t,i,n){if(e.stopPropagation(),e.clipboardData){let s=e.clipboardData.getData("text/plain");RA(s,t,i,n)}}function RA(e,t,i,n){e=Iz(e),e=zz(e,i.decPrivateModes.bracketedPasteMode&&n.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function OA(e,t,i){let n=i.getBoundingClientRect(),s=e.clientX-n.left-10,r=e.clientY-n.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${s}px`,t.style.top=`${r}px`,t.style.zIndex="1000",t.focus()}function kN(e,t,i,n,s){OA(e,t,i),s&&n.rightClickSelect(e),t.value=n.selectionText,t.select()}function ta(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Kf(e,t=0,i=e.length){let n="";for(let s=t;s65535?(r-=65536,n+=String.fromCharCode((r>>10)+55296)+String.fromCharCode(r%1024+56320)):n+=String.fromCharCode(r)}return n}function qz(e){return e[qv]||[]}function si(e){if(xv.has(e))return xv.get(e);let t=function(i,n,s){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");Kz(t,i,s)};return t._id=e,xv.set(e,t),t}function Kz(e,t,i){t[TN]===t?t[qv].push({id:e,index:i}):(t[qv]=[{id:e,index:i}],t[TN]=t)}function Gz(e,t){if(confirm(`Do you want to navigate to ${t}? +`)};return(0,He.jsxs)(He.Fragment,{children:[(0,He.jsx)("div",{className:"scroll",ref:a,onScroll:g,children:(0,He.jsxs)("div",{className:"tl-wrap",children:[(0,He.jsx)("div",{style:{height:S.getTotalSize(),position:"relative"},children:S.getVirtualItems().map(k=>{let D=s[k.index];return D?(0,He.jsx)("div",{"data-index":k.index,ref:S.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${k.start}px)`},children:(0,He.jsx)(jN,{it:D,threadId:p,onEditResend:w,onRetryLast:k.index===A?E:void 0,replyText:D.kind==="turnend"?O(k.index):void 0})},k.key):null})}),n.items.length===0&&!n.error&&(0,He.jsx)("div",{className:"sb-empty",children:v("chat.emptyHint")}),n.error&&(0,He.jsx)("div",{className:"nt error",children:$r(n.error)})]})}),!o&&(0,He.jsxs)("button",{className:"jump",onClick:b,title:v("chat.jumpBottom"),children:[(0,He.jsx)(pe,{name:"caret"}),c&&(0,He.jsx)("span",{className:"jd"})]}),(0,He.jsx)(fA,{})]})}function mA({kind:e}){let t=e==="pick-project";return(0,He.jsxs)("div",{className:"empty-wrap workspace-empty",children:[(0,He.jsx)("div",{className:"cp-hero-t",children:v(t?"chat.pickProjectTitle":"sidebar.noProjectsTitle")}),(0,He.jsx)("div",{className:"cp-hero-s",children:v(t?"chat.pickProjectSub":"sidebar.noProjectsSub")}),(0,He.jsx)("div",{className:"empty-actions",children:(0,He.jsx)("button",{type:"button",className:"btn primary",onClick:()=>window.dispatchEvent(new CustomEvent("open-new-project")),children:v("sidebar.newProject")})})]})}function Z5({projectId:e}){let t=le(),i=ku(),[n,r]=(0,jn.useState)(""),[s,a]=(0,jn.useState)(!1),o=async()=>{if(!(!n.trim()||s)){a(!0);try{let l=await Cl(),c=await V.call("settings.get"),u=await V.call("threads.create",{projectId:e,provider:l,model:null,mode:c.defaultMode??"default"});t.select(e,u.id),await V.call("thread.send",{id:u.id,text:n.trim()})}catch(l){we(v("chat.failSend")+ht(l),!0),a(!1)}}};return(0,He.jsxs)("div",{className:"cp-card",style:{marginTop:18},children:[(0,He.jsx)("textarea",{className:"cp-ta",rows:3,placeholder:v("chat.emptyPlaceholder"),value:n,onChange:l=>r(l.target.value),onKeyDown:l=>{if(qn(l.nativeEvent))return;let c=l.ctrlKey||l.metaKey;(i.sendKey==="ctrlEnter"?l.key==="Enter"&&c:l.key==="Enter"&&!l.shiftKey&&!c)&&(l.preventDefault(),o())}}),(0,He.jsxs)("div",{className:"cp-bar",children:[(0,He.jsx)("span",{className:"dlg-hint",children:v("chat.autoNewThread")}),(0,He.jsx)("div",{className:"cp-right",children:(0,He.jsx)("button",{className:"cp-send",disabled:!n.trim()||s,onClick:()=>{o()},title:v("common.send"),children:(0,He.jsx)(pe,{name:"send"})})})]})]})}var jn,He,_A=se(()=>{jn=ae(kt(),1);kl();IN();$i();Fn();ql();Kf();pA();hs();an();Kn();Wf();Yf();Pt();He=ae(ke(),1)});function bA({onClose:e}){let{projects:t,threads:i,providers:n}=rt(),r=le(),[s,a]=(0,zr.useState)(""),[o,l]=(0,zr.useState)(0),c=(0,zr.useRef)(null);(0,zr.useEffect)(()=>{c.current?.focus()},[]);let u=(0,zr.useMemo)(()=>{let f=[],p=s.trim().toLowerCase(),_=m=>!p||m.toLowerCase().includes(p),S=[[v("palette.actNewThread"),()=>{let m=r.currentProjectId??t[0]?.id;m&&d(m)}],[v("palette.actSettings"),()=>window.dispatchEvent(new CustomEvent("open-settings"))],[v("palette.actTheme"),()=>{Q5()}],[v("palette.actChanges"),()=>r.openPanel("changes")],[v("palette.actFiles"),()=>r.openPanel("files")],[v("palette.actTerminal"),()=>r.openPanel("terminal")],[v("palette.actImport"),()=>{let m=r.currentProjectId??t[0]?.id;m&&window.dispatchEvent(new CustomEvent("open-import",{detail:{projectId:m}}))}]];for(let[m,g]of S)_(m)&&f.push({id:`act:${m}`,label:m,hint:v("palette.hintAction"),run:g});for(let m of t)_(m.name)&&f.push({id:`p:${m.id}`,label:m.name,hint:v("palette.hintProject"),run:()=>r.select(m.id,null)});for(let m of i){let g=t.find(w=>w.id===m.projectId),b=`${m.title} ${g?.name??""}`;_(b)&&f.push({id:`t:${m.id}`,label:m.title,hint:g?.name??v("palette.hintThread"),run:()=>r.select(m.projectId,m.id)})}return f.slice(0,30)},[s,t,i]);(0,zr.useEffect)(()=>{l(0)},[s]);let h=f=>{if(f.key==="ArrowDown")f.preventDefault(),l(p=>Math.min(u.length-1,p+1));else if(f.key==="ArrowUp")f.preventDefault(),l(p=>Math.max(0,p-1));else if(f.key==="Enter"&&!qn(f.nativeEvent)){f.preventDefault();let p=u[o];p&&(e(),p.run())}else f.key==="Escape"&&(f.preventDefault(),e())};async function d(f){try{let p=await V.call("settings.get"),_=await Cl(),S=await V.call("threads.create",{projectId:f,provider:_,mode:p.defaultMode??"default"});le.getState().select(f,S.id)}catch(p){we(v("palette.failNew")+ht(p),!0)}}return(0,vA.createPortal)((0,Br.jsx)("div",{className:"dlg-scrim",style:{alignItems:"flex-start",paddingTop:"14vh"},onPointerDown:f=>{f.target===f.currentTarget&&e()},children:(0,Br.jsxs)("div",{className:"dlg cpal",role:"dialog","aria-label":v("palette.aria"),children:[(0,Br.jsx)("input",{ref:c,className:"cpal-in",placeholder:v("palette.placeholder"),value:s,onChange:f=>a(f.target.value),onKeyDown:h}),(0,Br.jsxs)("div",{className:"cpal-list",children:[u.map((f,p)=>(0,Br.jsxs)("button",{className:`cpal-item${p===o?" on":""}`,onMouseEnter:()=>l(p),onClick:()=>{e(),f.run()},children:[(0,Br.jsx)("span",{className:"cpal-label",children:f.label}),f.hint&&(0,Br.jsx)("span",{className:"cpal-hint",children:f.hint})]},f.id)),u.length===0&&(0,Br.jsx)("div",{className:"sb-empty",children:v("palette.noMatch")})]})]})}),document.body)}async function Q5(){let e=LE()==="dark"?"light":"dark";Mr(e);try{await V.call("settings.set",{patch:{theme:e}})}catch{}}var zr,vA,Br,yA=se(()=>{iu();zr=ae(kt(),1);kl();vA=ae(xa(),1);Fn();$i();an();Kn();Pt();Br=ae(ke(),1)});function t4(e){return e.replace(/\r?\n/g,"\r")}function i4(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function n4(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function r4(e,t,i,n){if(e.stopPropagation(),e.clipboardData){let r=e.clipboardData.getData("text/plain");NM(r,t,i,n)}}function NM(e,t,i,n){e=t4(e),e=i4(e,i.decPrivateModes.bracketedPasteMode&&n.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function AM(e,t,i){let n=i.getBoundingClientRect(),r=e.clientX-n.left-10,s=e.clientY-n.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${s}px`,t.style.zIndex="1000",t.focus()}function xA(e,t,i,n,r){AM(e,t,i),r&&n.rightClickSelect(e),t.value=n.selectionText,t.select()}function ma(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function _p(e,t=0,i=e.length){let n="";for(let r=t;r65535?(s-=65536,n+=String.fromCharCode((s>>10)+55296)+String.fromCharCode(s%1024+56320)):n+=String.fromCharCode(s)}return n}function o4(e){return e[kb]||[]}function di(e){if(lb.has(e))return lb.get(e);let t=function(i,n,r){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");l4(t,i,r)};return t._id=e,lb.set(e,t),t}function l4(e,t,i){t[EA]===t?t[kb].push({id:e,index:i}):(t[kb]=[{id:e,index:i}],t[EA]=t)}function h4(e,t){if(confirm(`Do you want to navigate to ${t}? -WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}function kf(e){Xz(e)||Vz.onUnexpectedError(e)}function Xz(e){return e instanceof Zz?!0:e instanceof Error&&e.name===Wv&&e.message===Wv}function Qz(e){return e?new Error(`Illegal argument: ${e}`):new Error("Illegal argument")}function Jz(e,t,i=0,n=e.length){let s=i,r=n;for(;st(e(i),e(n))}function n5(e,t){let i=Object.create(null);for(let n of e){let s=t(n),r=i[s];r||(r=i[s]=[]),r.push(n)}return i}function r5(e,t){let i=this,n=!1,s;return function(){if(n)return s;if(n=!0,t)try{s=e.apply(i,arguments)}finally{t()}else s=e.apply(i,arguments);return s}}function l5(e){eo=e}function $f(e){return eo?.trackDisposable(e),e}function Gf(e){eo?.markAsDisposed(e)}function Cu(e,t){eo?.setParent(e,t)}function c5(e,t){if(eo)for(let i of e)eo.setParent(i,t)}function ON(e){return eo?.markAsSingleton(e),e}function to(e){if(Vv.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(n){t.push(n)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function u5(...e){let t=ft(()=>to(e));return c5(e,t),t}function ft(e){let t=$f({dispose:r5(()=>{Gf(t),e()})});return t}function E5(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}function x5(e){return Mb.INSTANCE.getZoomFactor(e)}function C5(){return Mf}function F5(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return nb.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(ib)switch(t){case 59:return 85;case 60:if(D5)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Rs)return 57;break}else if(Af&&(Rs&&t===93||!Rs&&t===92))return 57;return P5[t]||0}function G5(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}function Z5(e){return 55296<=e&&e<=56319}function $N(e){return 56320<=e&&e<=57343}function Q5(e,t){return(e-55296<<10)+(t-56320)+65536}function J5(e){return Lb(e,0)}function Lb(e,t){switch(typeof e){case"object":return e===null?rr(349,t):Array.isArray(e)?t4(e,t):i4(e,t);case"string":return sM(e,t);case"boolean":return e4(e,t);case"number":return rr(e,t);case"undefined":return rr(937,t);default:return rr(617,t)}}function rr(e,t){return(t<<5)-t+e|0}function e4(e,t){return rr(e?433:863,t)}function sM(e,t){t=rr(149417,t);for(let i=0,n=e.length;iLb(n,i),t)}function i4(e,t){return t=rr(181387,t),Object.keys(e).sort().reduce((i,n)=>(i=sM(n,i),Lb(e[n],i)),t)}function Av(e,t,i=32){let n=i-t,s=~((1<>>n)>>>0}function GN(e,t=0,i=e.byteLength,n=0){for(let s=0;si.toString(16).padStart(2,"0")).join(""):n4((e>>>0).toString(16),t/4)}function _e(e,t,i,n){return new a4(e,t,i,n)}function o4(e,t){return function(i){return t(new mu(e,i))}}function l4(e){return function(t){return e(new sb(t))}}function h4(e){let t=e.getBoundingClientRect(),i=es(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}function aM(e,t,i,...n){let s=d4.exec(t);if(!s)throw new Error("Bad use of emmet");let r=s[1]||"div",a;return e!=="http://www.w3.org/1999/xhtml"?a=document.createElementNS(e,r):a=document.createElement(r),s[3]&&(a.id=s[3]),s[4]&&(a.className=s[4].replace(/\./g," ").trim()),i&&Object.entries(i).forEach(([o,l])=>{typeof l>"u"||(/^on\w+$/.test(o)?a[o]=l:o==="selected"?l&&a.setAttribute(o,"true"):a.setAttribute(o,l))}),a.append(...n),a}function f4(e,t,...i){return aM("http://www.w3.org/1999/xhtml",e,t,...i)}function Ji(e){return typeof e=="number"?`${e}px`:e}function wu(e){return new p4(e)}function m4(e,t,i){let n=null,s=null;if(typeof i.value=="function"?(n="value",s=i.value,s.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(n="get",s=i.get),!s)throw new Error("not supported");let r=`$memoize$${t}`;i[n]=function(...a){return this.hasOwnProperty(r)||Object.defineProperty(this,r,{configurable:!1,enumerable:!1,writable:!1,value:s.apply(this,a)}),this[r]}}function Rv(e,t){let i=t-e;return function(n){return e+i*w4(n)}}function y4(e,t,i){return function(n){return ne?"D":"C",Tu(Math.abs(s-e),ku(a,n));a=r>t?"D":"C";let o=Math.abs(r-t),l=a6(r>t?e:s,i)+(o-1)*i.cols+1+r6(r>t?s:e,i);return Tu(l,ku(a,n))}function r6(e,t){return e-1}function a6(e,t){return t.cols-e}function o6(e,t,i,n,s,r){return jf(t,n,s,r).length===0?"":Tu(vM(e,t,e,t-io(t,s),!1,s).length,ku("D",r))}function jf(e,t,i,n){let s=e-io(e,i),r=t-io(t,i),a=Math.abs(s-r)-c6(e,t,i);return Tu(a,ku(_M(e,t),n))}function l6(e,t,i,n,s,r){let a;jf(t,n,s,r).length>0?a=n-io(n,s):a=t;let o=n,l=u6(e,t,i,n,s,r);return Tu(vM(e,a,i,o,l==="C",s).length,ku(l,r))}function c6(e,t,i){let n=0,s=e-io(e,i),r=t-io(t,i);for(let a=0;a=0&&e0?a=n-io(n,s):a=t,e=i&&at?"A":"B"}function vM(e,t,i,n,s,r){let a=e,o=t,l="";for(;(a!==i||o!==n)&&o>=0&&or.cols-1?(l+=r.buffer.translateBufferLineToString(o,!1,e,a),a=0,e=0,o++):!s&&a<0&&(l+=r.buffer.translateBufferLineToString(o,!1,0,e+1),a=r.cols-1,e=a,o--);return l+r.buffer.translateBufferLineToString(o,!1,e,a)}function ku(e,t){let i=t?"O":"[";return H.ESC+i+e}function Tu(e,t){e=Math.floor(e);let i="";for(let n=0;ne.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}function tt(e,t){if(e!==void 0)try{return vt.toColor(e)}catch{}return t}function E6(e,t,i,n,s,r){let a=[];for(let o=0;o=o&&n0&&(w>h||u[w].getTrimmedLength()===0);w--)_++;_>0&&(a.push(o+u.length-_),a.push(_)),o+=u.length-1}return a}function x6(e,t){let i=[],n=0,s=t[n],r=0;for(let a=0;aNu(e,c,t)).reduce((l,c)=>l+c),r=0,a=0,o=0;for(;ol&&(r-=l,a++);let c=e[a].getWidth(r-1)===2;c&&r--;let u=c?i-1:i;n.push(u),o+=u}return n}function Nu(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let n=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,s=e[t+1].getWidth(0)===2;return n&&s?i-1:i}function R6(e){return e==="block"||e==="underline"||e==="bar"}function bu(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let n in e)i[n]=t<=1?e[n]:e[n]&&bu(e[n],t-1);return i}function Bv(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}function D6(e,t){let i=0,n=t.length-1,s;if(et[n][1])return!1;for(;n>=i;)if(s=i+n>>1,e>t[s][1])i=s+1;else if(e>4:r>>8}return n}}function Pv(e,t){let i=e.toString(16),n=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}function W6(e,t=16){let[i,n,s]=e;return`rgb:${Pv(i,t)}/${Pv(n,t)}/${Pv(s,t)}`}function yA(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}function EA(e){return 0<=e&&e<256}function Q6(e,t,i,n){let s={type:0,cancel:!1,key:void 0},r=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?s.key=H.ESC+"OA":s.key=H.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?s.key=H.ESC+"OD":s.key=H.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?s.key=H.ESC+"OC":s.key=H.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?s.key=H.ESC+"OB":s.key=H.ESC+"[B");break;case 8:s.key=e.ctrlKey?"\b":H.DEL,e.altKey&&(s.key=H.ESC+s.key);break;case 9:if(e.shiftKey){s.key=H.ESC+"[Z";break}s.key=H.HT,s.cancel=!0;break;case 13:s.key=e.altKey?H.ESC+H.CR:H.CR,s.cancel=!0;break;case 27:s.key=H.ESC,e.altKey&&(s.key=H.ESC+H.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;r?s.key=H.ESC+"[1;"+(r+1)+"D":t?s.key=H.ESC+"OD":s.key=H.ESC+"[D";break;case 39:if(e.metaKey)break;r?s.key=H.ESC+"[1;"+(r+1)+"C":t?s.key=H.ESC+"OC":s.key=H.ESC+"[C";break;case 38:if(e.metaKey)break;r?s.key=H.ESC+"[1;"+(r+1)+"A":t?s.key=H.ESC+"OA":s.key=H.ESC+"[A";break;case 40:if(e.metaKey)break;r?s.key=H.ESC+"[1;"+(r+1)+"B":t?s.key=H.ESC+"OB":s.key=H.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(s.key=H.ESC+"[2~");break;case 46:r?s.key=H.ESC+"[3;"+(r+1)+"~":s.key=H.ESC+"[3~";break;case 36:r?s.key=H.ESC+"[1;"+(r+1)+"H":t?s.key=H.ESC+"OH":s.key=H.ESC+"[H";break;case 35:r?s.key=H.ESC+"[1;"+(r+1)+"F":t?s.key=H.ESC+"OF":s.key=H.ESC+"[F";break;case 33:e.shiftKey?s.type=2:e.ctrlKey?s.key=H.ESC+"[5;"+(r+1)+"~":s.key=H.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:e.ctrlKey?s.key=H.ESC+"[6;"+(r+1)+"~":s.key=H.ESC+"[6~";break;case 112:r?s.key=H.ESC+"[1;"+(r+1)+"P":s.key=H.ESC+"OP";break;case 113:r?s.key=H.ESC+"[1;"+(r+1)+"Q":s.key=H.ESC+"OQ";break;case 114:r?s.key=H.ESC+"[1;"+(r+1)+"R":s.key=H.ESC+"OR";break;case 115:r?s.key=H.ESC+"[1;"+(r+1)+"S":s.key=H.ESC+"OS";break;case 116:r?s.key=H.ESC+"[15;"+(r+1)+"~":s.key=H.ESC+"[15~";break;case 117:r?s.key=H.ESC+"[17;"+(r+1)+"~":s.key=H.ESC+"[17~";break;case 118:r?s.key=H.ESC+"[18;"+(r+1)+"~":s.key=H.ESC+"[18~";break;case 119:r?s.key=H.ESC+"[19;"+(r+1)+"~":s.key=H.ESC+"[19~";break;case 120:r?s.key=H.ESC+"[20;"+(r+1)+"~":s.key=H.ESC+"[20~";break;case 121:r?s.key=H.ESC+"[21;"+(r+1)+"~":s.key=H.ESC+"[21~";break;case 122:r?s.key=H.ESC+"[23;"+(r+1)+"~":s.key=H.ESC+"[23~";break;case 123:r?s.key=H.ESC+"[24;"+(r+1)+"~":s.key=H.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?s.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?s.key=H.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?s.key=H.DEL:e.keyCode===219?s.key=H.ESC:e.keyCode===220?s.key=H.FS:e.keyCode===221&&(s.key=H.GS);else if((!i||n)&&e.altKey&&!e.metaKey){let a=Z6[e.keyCode]?.[e.shiftKey?1:0];if(a)s.key=H.ESC+a;else if(e.keyCode>=65&&e.keyCode<=90){let o=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(o);e.shiftKey&&(l=l.toUpperCase()),s.key=H.ESC+l}else if(e.keyCode===32)s.key=H.ESC+(e.ctrlKey?H.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let o=e.code.slice(3,4);e.shiftKey||(o=o.toLowerCase()),s.key=H.ESC+o,s.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(s.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?s.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(s.key=H.US),e.key==="@"&&(s.key=H.NUL));break}return s}function sP(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}function aP(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var MA,Lz,Bz,kt,se,xN,Hv,CN,Fv,Hz,Fz,DA,ia,Au,Lf,Un,TN,qv,xv,Ui,zA,no,Wz,Nb,PA,Hi,UA,$z,Mu,Kv,Wf,or,Ab,lr,Yz,HA,Bl,FA,jz,Vz,Wv,Zz,NN,Gv,e5,Yv,i5,AN,MN,RN,B9,s5,Vv,a5,eo,o5,$A,na,Ae,Ll,bn,Xv,St,DN,h5,d5,f5,LN,p5,ni,Qv,m5,BN,jA,g5,eb,_5,v5,b5,Tf,y5,S5,Nf,Q,w5,tb,Mb,z9,P9,Il,ib,Af,Rb,ZA,U9,H9,Mf,Dl,Bf,If,Su,k5,QA,JA,T5,N5,A5,M5,Sf,Rf,IN,R5,sr,ar,vn,eM,O5,Cv,tM,Rs,D5,kv,L5,F9,Os,Zr,zN,B5,I5,z5,q9,K9,W9,$9,Qr,G9,Ob,Tv,PN,UN,P5,nb,U5,H5,q5,K5,W5,$5,sb,HN,Y5,mu,FN,nM,qN,j5,Db,V5,X5,Nv,KN,WN,s4,Y9,es,j9,V9,X9,YN,Z9,Q9,r4,J9,e7,a4,jN,c4,zf,u4,Mv,VN,t7,Jt,d4,p4,oM,Jn,gu,g4,Bb,XN,_4,v4,b4,ZN,QN,E4,x4,lM,cM,C4,k4,T4,JN,eA,N4,lb,A4,M4,R4,cb,ub,D4,As,Jr,cu,Pf,H,Eu,hb,db,ei,ti,ii,Ct,tA,Rt,ht,vt,Ni,xu,L4,Uf,fb,U4,H4,Ov,In,Ef,nA,uu,xf,q4,pb,mb,uM,K4,W4,$4,G4,Y4,gb,V4,hM,Yf,Ru,Ou,dM,X4,fM,Hf,Q4,J4,pM,zb,mM,gM,e6,t6,Ff,i6,_b,n6,h6,Dv,d6,f6,p6,m6,g6,vb,rA,aA,Kt,Za,_u,oA,lA,hu,_6,bb,v6,b6,y6,S6,yb,w6,cA,Oe,Pt,Cf,Lv,vu,yM,T6,$t,Qa,uA,hA,N6,wM,EM,Sb,Ol,A6,M6,dA,fA,wb,pA,Iv,mA,Eb,zv,O6,Wt,L6,Ja,B6,du,I6,xM,fu,z6,_n,pu,P6,yu,_A,U6,Pn,H6,F6,q6,K6,$6,ea,bA,SA,wA,G6,Cb,Y6,xA,j6,V6,kb,CA,X6,Z6,Mt,J6,Uv,kA,eP,tP,iP,nP,TA,NA,qf,Tb,rP,oP,lP,AA,cP,uP,hP,dP,Ms,CM,kM=le(()=>{MA=Object.defineProperty,Lz=Object.getOwnPropertyDescriptor,Bz=(e,t)=>{for(var i in t)MA(e,i,{get:t[i],enumerable:!0})},kt=(e,t,i,n)=>{for(var s=n>1?void 0:n?Lz(t,i):t,r=e.length-1,a;r>=0;r--)(a=e[r])&&(s=(n?a(t,i,s):a(s))||s);return n&&s&&MA(t,i,s),s},se=(e,t)=>(i,n)=>t(i,n,e),xN="Terminal input",Hv={get:()=>xN,set:e=>xN=e},CN="Too much output to announce, navigate to rows manually to read",Fv={get:()=>CN,set:e=>CN=e};Hz=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let n=0,s=0;if(this._interim){let r=e.charCodeAt(s++);56320<=r&&r<=57343?t[n++]=(this._interim-55296)*1024+r-56320+65536:(t[n++]=this._interim,t[n++]=r),this._interim=0}for(let r=s;r=i)return this._interim=a,n;let o=e.charCodeAt(r);56320<=o&&o<=57343?t[n++]=(a-55296)*1024+o-56320+65536:(t[n++]=a,t[n++]=o);continue}a!==65279&&(t[n++]=a)}return n}},Fz=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let n=0,s,r,a,o,l=0,c=0;if(this.interim[0]){let d=!1,f=this.interim[0];f&=(f&224)===192?31:(f&240)===224?15:7;let p=0,_;for(;(_=this.interim[++p]&63)&&p<4;)f<<=6,f|=_;let w=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,g=w-p;for(;c=i)return 0;if(_=e[c++],(_&192)!==128){c--,d=!0;break}else this.interim[p++]=_,f<<=6,f|=_&63}d||(w===2?f<128?c--:t[n++]=f:w===3?f<2048||f>=55296&&f<=57343||f===65279||(t[n++]=f):f<65536||f>1114111||(t[n++]=f)),this.interim.fill(0)}let u=i-4,h=c;for(;h=i)return this.interim[0]=s,n;if(r=e[h++],(r&192)!==128){h--;continue}if(l=(s&31)<<6|r&63,l<128){h--;continue}t[n++]=l}else if((s&240)===224){if(h>=i)return this.interim[0]=s,n;if(r=e[h++],(r&192)!==128){h--;continue}if(h>=i)return this.interim[0]=s,this.interim[1]=r,n;if(a=e[h++],(a&192)!==128){h--;continue}if(l=(s&15)<<12|(r&63)<<6|a&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[n++]=l}else if((s&248)===240){if(h>=i)return this.interim[0]=s,n;if(r=e[h++],(r&192)!==128){h--;continue}if(h>=i)return this.interim[0]=s,this.interim[1]=r,n;if(a=e[h++],(a&192)!==128){h--;continue}if(h>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=a,n;if(o=e[h++],(o&192)!==128){h--;continue}if(l=(s&7)<<18|(r&63)<<12|(a&63)<<6|o&63,l<65536||l>1114111)continue;t[n++]=l}}return n}},DA="",ia=" ",Au=class LA{constructor(){this.fg=0,this.bg=0,this.extended=new Lf}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new LA;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Lf=class BA{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new BA(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Un=class IA extends Au{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Lf,this.combinedData=""}static fromCharData(t){let i=new IA;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?ta(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let n=t[1].charCodeAt(0);if(55296<=n&&n<=56319){let s=t[1].charCodeAt(1);56320<=s&&s<=57343?this.content=(n-55296)*1024+s-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},TN="di$target",qv="di$dependencies",xv=new Map;Ui=si("BufferService"),zA=si("CoreMouseService"),no=si("CoreService"),Wz=si("CharsetService"),Nb=si("InstantiationService"),PA=si("LogService"),Hi=si("OptionsService"),UA=si("OscLinkService"),$z=si("UnicodeService"),Mu=si("DecorationService"),Kv=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let n=[],s=this._optionsService.rawOptions.linkHandler,r=new Un,a=i.getTrimmedLength(),o=-1,l=-1,c=!1;for(let u=0;us?s.activate(p,_,d):Gz(p,_),hover:(p,_)=>s?.hover?.(p,_,d),leave:(p,_)=>s?.leave?.(p,_,d)})}c=!1,r.hasExtendedAttrs()&&r.extended.urlId?(l=u,o=r.extended.urlId):(l=-1,o=-1)}}t(n)}};Kv=kt([se(0,Ui),se(1,Hi),se(2,UA)],Kv);Wf=si("CharSizeService"),or=si("CoreBrowserService"),Ab=si("MouseService"),lr=si("RenderService"),Yz=si("SelectionService"),HA=si("CharacterJoinerService"),Bl=si("ThemeService"),FA=si("LinkProviderService"),jz=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?NN.isErrorNoTelemetry(e)?new NN(e.message+` +WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){try{i.opener=null}catch{}i.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}function ep(e){m4(e)||p4.onUnexpectedError(e)}function m4(e){return e instanceof g4?!0:e instanceof Error&&e.name===Nb&&e.message===Nb}function _4(e){return e?new Error(`Illegal argument: ${e}`):new Error("Illegal argument")}function v4(e,t,i=0,n=e.length){let r=i,s=n;for(;rt(e(i),e(n))}function w4(e,t){let i=Object.create(null);for(let n of e){let r=t(n),s=i[r];s||(s=i[r]=[]),s.push(n)}return i}function E4(e,t){let i=this,n=!1,r;return function(){if(n)return r;if(n=!0,t)try{r=e.apply(i,arguments)}finally{t()}else r=e.apply(i,arguments);return r}}function T4(e){po=e}function bp(e){return po?.trackDisposable(e),e}function yp(e){po?.markAsDisposed(e)}function Wu(e,t){po?.setParent(e,t)}function N4(e,t){if(po)for(let i of e)po.setParent(i,t)}function AA(e){return po?.markAsSingleton(e),e}function mo(e){if(Db.is(e)){let t=[];for(let i of e)if(i)try{i.dispose()}catch(n){t.push(n)}if(t.length===1)throw t[0];if(t.length>1)throw new AggregateError(t,"Encountered errors while disposing of store");return Array.isArray(e)?[]:e}else if(e)return e.dispose(),e}function A4(...e){let t=_t(()=>mo(e));return N4(e,t),t}function _t(e){let t=bp({dispose:E4(()=>{yp(t),e()})});return t}function q4(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}function K4(e){return p0.INSTANCE.getZoomFactor(e)}function W4(){return rp}function a6(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return Fb.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Hb)switch(t){case 59:return 85;case 60:if(Q4)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(Hr)return 57;break}else if(np&&(Hr&&t===93||!Hr&&t===92))return 57;return n6[t]||0}function h6(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,i=e.parent.location;if(t.origin!=="null"&&i.origin!=="null"&&t.origin!==i.origin)return null}catch{return null}return e.parent}function g6(e){return 55296<=e&&e<=56319}function qA(e){return 56320<=e&&e<=57343}function _6(e,t){return(e-55296<<10)+(t-56320)+65536}function v6(e){return v0(e,0)}function v0(e,t){switch(typeof e){case"object":return e===null?vs(349,t):Array.isArray(e)?y6(e,t):S6(e,t);case"string":return tR(e,t);case"boolean":return b6(e,t);case"number":return vs(e,t);case"undefined":return vs(937,t);default:return vs(617,t)}}function vs(e,t){return(t<<5)-t+e|0}function b6(e,t){return vs(e?433:863,t)}function tR(e,t){t=vs(149417,t);for(let i=0,n=e.length;iv0(n,i),t)}function S6(e,t){return t=vs(181387,t),Object.keys(e).sort().reduce((i,n)=>(i=tR(n,i),v0(e[n],i)),t)}function fb(e,t,i=32){let n=i-t,r=~((1<>>n)>>>0}function KA(e,t=0,i=e.byteLength,n=0){for(let r=0;ri.toString(16).padStart(2,"0")).join(""):w6((e>>>0).toString(16),t/4)}function Se(e,t,i,n){return new C6(e,t,i,n)}function k6(e,t){return function(i){return t(new Lu(e,i))}}function T6(e){return function(t){return e(new qb(t))}}function M6(e){let t=e.getBoundingClientRect(),i=ur(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}function nR(e,t,i,...n){let r=R6.exec(t);if(!r)throw new Error("Bad use of emmet");let s=r[1]||"div",a;return e!=="http://www.w3.org/1999/xhtml"?a=document.createElementNS(e,s):a=document.createElement(s),r[3]&&(a.id=r[3]),r[4]&&(a.className=r[4].replace(/\./g," ").trim()),i&&Object.entries(i).forEach(([o,l])=>{typeof l>"u"||(/^on\w+$/.test(o)?a[o]=l:o==="selected"?l&&a.setAttribute(o,"true"):a.setAttribute(o,l))}),a.append(...n),a}function O6(e,t,...i){return nR("http://www.w3.org/1999/xhtml",e,t,...i)}function cn(e){return typeof e=="number"?`${e}px`:e}function Fu(e){return new D6(e)}function L6(e,t,i){let n=null,r=null;if(typeof i.value=="function"?(n="value",r=i.value,r.length!==0&&console.warn("Memoize should only be used in functions with zero parameters")):typeof i.get=="function"&&(n="get",r=i.get),!r)throw new Error("not supported");let s=`$memoize$${t}`;i[n]=function(...a){return this.hasOwnProperty(s)||Object.defineProperty(this,s,{configurable:!1,enumerable:!1,writable:!1,value:r.apply(this,a)}),this[s]}}function mb(e,t){let i=t-e;return function(n){return e+i*F6(n)}}function U6(e,t,i){return function(n){return ne?"D":"C",Gu(Math.abs(r-e),$u(a,n));a=s>t?"D":"C";let o=Math.abs(s-t),l=CP(s>t?e:r,i)+(o-1)*i.cols+1+EP(s>t?r:e,i);return Gu(l,$u(a,n))}function EP(e,t){return e-1}function CP(e,t){return t.cols-e}function kP(e,t,i,n,r,s){return wp(t,n,r,s).length===0?"":Gu(mR(e,t,e,t-go(t,r),!1,r).length,$u("D",s))}function wp(e,t,i,n){let r=e-go(e,i),s=t-go(t,i),a=Math.abs(r-s)-NP(e,t,i);return Gu(a,$u(pR(e,t),n))}function TP(e,t,i,n,r,s){let a;wp(t,n,r,s).length>0?a=n-go(n,r):a=t;let o=n,l=AP(e,t,i,n,r,s);return Gu(mR(e,a,i,o,l==="C",r).length,$u(l,s))}function NP(e,t,i){let n=0,r=e-go(e,i),s=t-go(t,i);for(let a=0;a=0&&e0?a=n-go(n,r):a=t,e=i&&at?"A":"B"}function mR(e,t,i,n,r,s){let a=e,o=t,l="";for(;(a!==i||o!==n)&&o>=0&&os.cols-1?(l+=s.buffer.translateBufferLineToString(o,!1,e,a),a=0,e=0,o++):!r&&a<0&&(l+=s.buffer.translateBufferLineToString(o,!1,0,e+1),a=s.cols-1,e=a,o--);return l+s.buffer.translateBufferLineToString(o,!1,e,a)}function $u(e,t){let i=t?"O":"[";return F.ESC+i+e}function Gu(e,t){e=Math.floor(e);let i="";for(let n=0;ne.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}function at(e,t){if(e!==void 0)try{return xt.toColor(e)}catch{}return t}function qP(e,t,i,n,r,s){let a=[];for(let o=0;o=o&&n0&&(S>h||u[S].getTrimmedLength()===0);S--)_++;_>0&&(a.push(o+u.length-_),a.push(_)),o+=u.length-1}return a}function KP(e,t){let i=[],n=0,r=t[n],s=0;for(let a=0;aju(e,c,t)).reduce((l,c)=>l+c),s=0,a=0,o=0;for(;ol&&(s-=l,a++);let c=e[a].getWidth(s-1)===2;c&&s--;let u=c?i-1:i;n.push(u),o+=u}return n}function ju(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();let n=!e[t].hasContent(i-1)&&e[t].getWidth(i-1)===1,r=e[t+1].getWidth(0)===2;return n&&r?i-1:i}function XP(e){return e==="block"||e==="underline"||e==="bar"}function Pu(e,t=5){if(typeof e!="object")return e;let i=Array.isArray(e)?[]:{};for(let n in e)i[n]=t<=1?e[n]:e[n]&&Pu(e[n],t-1);return i}function bb(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(i|=64,i|=e.action):(i|=e.button&3,e.button&4&&(i|=64),e.button&8&&(i|=128),e.action===32?i|=32:e.action===0&&!t&&(i|=3)),i}function QP(e,t){let i=0,n=t.length-1,r;if(et[n][1])return!1;for(;n>=i;)if(r=i+n>>1,e>t[r][1])i=r+1;else if(e>4:s>>8}return n}}function wb(e,t){let i=e.toString(16),n=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return n;case 12:return(n+n).slice(0,3);default:return n+n}}function cU(e,t=16){let[i,n,r]=e;return`rgb:${wb(i,t)}/${wb(n,t)}/${wb(r,t)}`}function _M(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}function yM(e){return 0<=e&&e<256}function _U(e,t,i,n){let r={type:0,cancel:!1,key:void 0},s=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key==="UIKeyInputUpArrow"?t?r.key=F.ESC+"OA":r.key=F.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?r.key=F.ESC+"OD":r.key=F.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?r.key=F.ESC+"OC":r.key=F.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?r.key=F.ESC+"OB":r.key=F.ESC+"[B");break;case 8:r.key=e.ctrlKey?"\b":F.DEL,e.altKey&&(r.key=F.ESC+r.key);break;case 9:if(e.shiftKey){r.key=F.ESC+"[Z";break}r.key=F.HT,r.cancel=!0;break;case 13:r.key=e.altKey?F.ESC+F.CR:F.CR,r.cancel=!0;break;case 27:r.key=F.ESC,e.altKey&&(r.key=F.ESC+F.ESC),r.cancel=!0;break;case 37:if(e.metaKey)break;s?r.key=F.ESC+"[1;"+(s+1)+"D":t?r.key=F.ESC+"OD":r.key=F.ESC+"[D";break;case 39:if(e.metaKey)break;s?r.key=F.ESC+"[1;"+(s+1)+"C":t?r.key=F.ESC+"OC":r.key=F.ESC+"[C";break;case 38:if(e.metaKey)break;s?r.key=F.ESC+"[1;"+(s+1)+"A":t?r.key=F.ESC+"OA":r.key=F.ESC+"[A";break;case 40:if(e.metaKey)break;s?r.key=F.ESC+"[1;"+(s+1)+"B":t?r.key=F.ESC+"OB":r.key=F.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(r.key=F.ESC+"[2~");break;case 46:s?r.key=F.ESC+"[3;"+(s+1)+"~":r.key=F.ESC+"[3~";break;case 36:s?r.key=F.ESC+"[1;"+(s+1)+"H":t?r.key=F.ESC+"OH":r.key=F.ESC+"[H";break;case 35:s?r.key=F.ESC+"[1;"+(s+1)+"F":t?r.key=F.ESC+"OF":r.key=F.ESC+"[F";break;case 33:e.shiftKey?r.type=2:e.ctrlKey?r.key=F.ESC+"[5;"+(s+1)+"~":r.key=F.ESC+"[5~";break;case 34:e.shiftKey?r.type=3:e.ctrlKey?r.key=F.ESC+"[6;"+(s+1)+"~":r.key=F.ESC+"[6~";break;case 112:s?r.key=F.ESC+"[1;"+(s+1)+"P":r.key=F.ESC+"OP";break;case 113:s?r.key=F.ESC+"[1;"+(s+1)+"Q":r.key=F.ESC+"OQ";break;case 114:s?r.key=F.ESC+"[1;"+(s+1)+"R":r.key=F.ESC+"OR";break;case 115:s?r.key=F.ESC+"[1;"+(s+1)+"S":r.key=F.ESC+"OS";break;case 116:s?r.key=F.ESC+"[15;"+(s+1)+"~":r.key=F.ESC+"[15~";break;case 117:s?r.key=F.ESC+"[17;"+(s+1)+"~":r.key=F.ESC+"[17~";break;case 118:s?r.key=F.ESC+"[18;"+(s+1)+"~":r.key=F.ESC+"[18~";break;case 119:s?r.key=F.ESC+"[19;"+(s+1)+"~":r.key=F.ESC+"[19~";break;case 120:s?r.key=F.ESC+"[20;"+(s+1)+"~":r.key=F.ESC+"[20~";break;case 121:s?r.key=F.ESC+"[21;"+(s+1)+"~":r.key=F.ESC+"[21~";break;case 122:s?r.key=F.ESC+"[23;"+(s+1)+"~":r.key=F.ESC+"[23~";break;case 123:s?r.key=F.ESC+"[24;"+(s+1)+"~":r.key=F.ESC+"[24~";break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?r.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?r.key=F.NUL:e.keyCode>=51&&e.keyCode<=55?r.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?r.key=F.DEL:e.keyCode===219?r.key=F.ESC:e.keyCode===220?r.key=F.FS:e.keyCode===221&&(r.key=F.GS);else if((!i||n)&&e.altKey&&!e.metaKey){let a=gU[e.keyCode]?.[e.shiftKey?1:0];if(a)r.key=F.ESC+a;else if(e.keyCode>=65&&e.keyCode<=90){let o=e.ctrlKey?e.keyCode-64:e.keyCode+32,l=String.fromCharCode(o);e.shiftKey&&(l=l.toUpperCase()),r.key=F.ESC+l}else if(e.keyCode===32)r.key=F.ESC+(e.ctrlKey?F.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let o=e.code.slice(3,4);e.shiftKey||(o=o.toLowerCase()),r.key=F.ESC+o,r.cancel=!0}}else i&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(r.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?r.key=e.key:e.key&&e.ctrlKey&&(e.key==="_"&&(r.key=F.US),e.key==="@"&&(r.key=F.NUL));break}return r}function xU(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}function CU(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var TM,J5,e4,Rt,re,SA,Eb,wA,Cb,s4,a4,MM,ga,Yu,lp,Zn,EA,kb,lb,ji,LM,_o,c4,d0,IM,Yi,BM,u4,Vu,Tb,vp,ys,f0,Ss,d4,zM,Yl,PM,f4,p4,Nb,g4,CA,Mb,b4,Rb,S4,kA,TA,NA,RF,x4,Db,C4,po,k4,qM,_a,Oe,jl,Nn,Lb,Ct,MA,M4,R4,O4,RA,D4,hi,Bb,L4,OA,$M,I4,Pb,B4,z4,P4,tp,U4,H4,ip,Z,F4,Ub,p0,DF,LF,Vl,Hb,np,m0,YM,IF,BF,rp,Gl,cp,up,Hu,$4,VM,XM,G4,j4,Y4,V4,Vf,sp,DA,X4,_s,bs,Tn,ZM,Z4,cb,QM,Hr,Q4,ub,J4,zF,Fr,ha,LA,e6,t6,i6,PF,UF,HF,FF,da,qF,g0,hb,IA,BA,n6,Fb,r6,s6,o6,l6,c6,u6,qb,zA,d6,Lu,PA,eR,UA,f6,_0,p6,m6,db,HA,FA,x6,KF,ur,WF,$F,GF,WA,jF,YF,E6,VF,XF,C6,$A,N6,hp,A6,pb,GA,ZF,oi,R6,D6,rR,cr,Iu,I6,b0,jA,B6,z6,P6,YA,VA,q6,K6,sR,aR,W6,$6,G6,XA,ZA,j6,Gb,Y6,V6,X6,jb,Yb,Q6,Pr,fa,Nu,dp,F,qu,Vb,Xb,li,ci,ui,Mt,QA,It,gt,xt,Ii,Ku,J6,fp,Zb,rP,sP,gb,Yn,Zf,eM,Au,Qf,oP,Qb,Jb,oR,lP,cP,uP,hP,dP,e0,pP,lR,Sp,Xu,Zu,cR,mP,uR,pp,_P,vP,hR,S0,dR,fR,bP,yP,mp,SP,t0,wP,MP,_b,RP,OP,DP,LP,IP,i0,iM,nM,Zt,uo,Bu,rM,sM,Mu,BP,n0,zP,PP,UP,HP,r0,FP,aM,Le,Wt,Jf,vb,zu,_R,GP,Jt,ho,oM,lM,jP,bR,yR,s0,$l,YP,VP,cM,uM,a0,hM,yb,dM,o0,Sb,ZP,Qt,JP,fo,eU,Ru,tU,SR,Ou,iU,kn,Du,nU,Uu,pM,rU,Xn,sU,aU,oU,lU,uU,pa,gM,vM,bM,hU,c0,dU,SM,fU,pU,u0,wM,mU,gU,Lt,vU,xb,xM,bU,yU,SU,wU,EM,CM,gp,h0,EU,kU,TU,kM,NU,AU,MU,RU,Ur,wR,xR=se(()=>{TM=Object.defineProperty,J5=Object.getOwnPropertyDescriptor,e4=(e,t)=>{for(var i in t)TM(e,i,{get:t[i],enumerable:!0})},Rt=(e,t,i,n)=>{for(var r=n>1?void 0:n?J5(t,i):t,s=e.length-1,a;s>=0;s--)(a=e[s])&&(r=(n?a(t,i,r):a(r))||r);return n&&r&&TM(t,i,r),r},re=(e,t)=>(i,n)=>t(i,n,e),SA="Terminal input",Eb={get:()=>SA,set:e=>SA=e},wA="Too much output to announce, navigate to rows manually to read",Cb={get:()=>wA,set:e=>wA=e};s4=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let i=e.length;if(!i)return 0;let n=0,r=0;if(this._interim){let s=e.charCodeAt(r++);56320<=s&&s<=57343?t[n++]=(this._interim-55296)*1024+s-56320+65536:(t[n++]=this._interim,t[n++]=s),this._interim=0}for(let s=r;s=i)return this._interim=a,n;let o=e.charCodeAt(s);56320<=o&&o<=57343?t[n++]=(a-55296)*1024+o-56320+65536:(t[n++]=a,t[n++]=o);continue}a!==65279&&(t[n++]=a)}return n}},a4=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let i=e.length;if(!i)return 0;let n=0,r,s,a,o,l=0,c=0;if(this.interim[0]){let d=!1,f=this.interim[0];f&=(f&224)===192?31:(f&240)===224?15:7;let p=0,_;for(;(_=this.interim[++p]&63)&&p<4;)f<<=6,f|=_;let S=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,m=S-p;for(;c=i)return 0;if(_=e[c++],(_&192)!==128){c--,d=!0;break}else this.interim[p++]=_,f<<=6,f|=_&63}d||(S===2?f<128?c--:t[n++]=f:S===3?f<2048||f>=55296&&f<=57343||f===65279||(t[n++]=f):f<65536||f>1114111||(t[n++]=f)),this.interim.fill(0)}let u=i-4,h=c;for(;h=i)return this.interim[0]=r,n;if(s=e[h++],(s&192)!==128){h--;continue}if(l=(r&31)<<6|s&63,l<128){h--;continue}t[n++]=l}else if((r&240)===224){if(h>=i)return this.interim[0]=r,n;if(s=e[h++],(s&192)!==128){h--;continue}if(h>=i)return this.interim[0]=r,this.interim[1]=s,n;if(a=e[h++],(a&192)!==128){h--;continue}if(l=(r&15)<<12|(s&63)<<6|a&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[n++]=l}else if((r&248)===240){if(h>=i)return this.interim[0]=r,n;if(s=e[h++],(s&192)!==128){h--;continue}if(h>=i)return this.interim[0]=r,this.interim[1]=s,n;if(a=e[h++],(a&192)!==128){h--;continue}if(h>=i)return this.interim[0]=r,this.interim[1]=s,this.interim[2]=a,n;if(o=e[h++],(o&192)!==128){h--;continue}if(l=(r&7)<<18|(s&63)<<12|(a&63)<<6|o&63,l<65536||l>1114111)continue;t[n++]=l}}return n}},MM="",ga=" ",Yu=class RM{constructor(){this.fg=0,this.bg=0,this.extended=new lp}static toColorRGB(t){return[t>>>16&255,t>>>8&255,t&255]}static fromColorRGB(t){return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255}clone(){let t=new RM;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===16777216||(this.extended.underlineColor&50331648)===33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)===0:this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},lp=class OM{constructor(t=0,i=0){this._ext=0,this._urlId=0,this._ext=t,this._urlId=i}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(t){this._ext=t}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(t){this._ext&=-469762049,this._ext|=t<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(t){this._ext&=-67108864,this._ext|=t&67108863}get urlId(){return this._urlId}set urlId(t){this._urlId=t}get underlineVariantOffset(){let t=(this._ext&3758096384)>>29;return t<0?t^4294967288:t}set underlineVariantOffset(t){this._ext&=536870911,this._ext|=t<<29&3758096384}clone(){return new OM(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Zn=class DM extends Yu{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new lp,this.combinedData=""}static fromCharData(t){let i=new DM;return i.setFromCharData(t),i}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?ma(this.content&2097151):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(t){this.fg=t[0],this.bg=0;let i=!1;if(t[1].length>2)i=!0;else if(t[1].length===2){let n=t[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=t[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|t[2]<<22:i=!0}else i=!0}else this.content=t[1].charCodeAt(0)|t[2]<<22;i&&(this.combinedData=t[1],this.content=2097152|t[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},EA="di$target",kb="di$dependencies",lb=new Map;ji=di("BufferService"),LM=di("CoreMouseService"),_o=di("CoreService"),c4=di("CharsetService"),d0=di("InstantiationService"),IM=di("LogService"),Yi=di("OptionsService"),BM=di("OscLinkService"),u4=di("UnicodeService"),Vu=di("DecorationService"),Tb=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){let i=this._bufferService.buffer.lines.get(e-1);if(!i){t(void 0);return}let n=[],r=this._optionsService.rawOptions.linkHandler,s=new Zn,a=i.getTrimmedLength(),o=-1,l=-1,c=!1;for(let u=0;ur?r.activate(p,_,d):h4(p,_),hover:(p,_)=>r?.hover?.(p,_,d),leave:(p,_)=>r?.leave?.(p,_,d)})}c=!1,s.hasExtendedAttrs()&&s.extended.urlId?(l=u,o=s.extended.urlId):(l=-1,o=-1)}}t(n)}};Tb=Rt([re(0,ji),re(1,Yi),re(2,BM)],Tb);vp=di("CharSizeService"),ys=di("CoreBrowserService"),f0=di("MouseService"),Ss=di("RenderService"),d4=di("SelectionService"),zM=di("CharacterJoinerService"),Yl=di("ThemeService"),PM=di("LinkProviderService"),f4=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?CA.isErrorNoTelemetry(e)?new CA(e.message+` `+e.stack):new Error(e.message+` -`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},Vz=new jz;Wv="Canceled";Zz=class extends Error{constructor(){super(Wv),this.name=this.message}};NN=class $v extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof $v)return t;let i=new $v;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Gv=class qA extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,qA.prototype)}};e5=class KA{constructor(t){this._array=t,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(KA.assertInvariants){if(this._prevFindLastPredicate){for(let n of this._array)if(this._prevFindLastPredicate(n)&&!t(n))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=t}let i=Jz(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=i+1,i===-1?void 0:this._array[i]}};e5.assertInvariants=!1;(e=>{function t(r){return r<0}e.isLessThan=t;function i(r){return r<=0}e.isLessThanOrEqual=i;function n(r){return r>0}e.isGreaterThan=n;function s(r){return r===0}e.isNeitherLessOrGreaterThan=s,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Yv||(Yv={}));i5=(e,t)=>e-t,AN=class jv{constructor(t){this.iterate=t}forEach(t){this.iterate(i=>(t(i),!0))}toArray(){let t=[];return this.iterate(i=>(t.push(i),!0)),t}filter(t){return new jv(i=>this.iterate(n=>t(n)?i(n):!0))}map(t){return new jv(i=>this.iterate(n=>i(t(n))))}some(t){let i=!1;return this.iterate(n=>(i=t(n),!i)),i}findFirst(t){let i;return this.iterate(n=>t(n)?(i=n,!1):!0),i}findLast(t){let i;return this.iterate(n=>(t(n)&&(i=n),!0)),i}findLastMaxBy(t){let i,n=!0;return this.iterate(s=>((n||Yv.isGreaterThan(t(s,i)))&&(n=!1,i=s),!0)),i}};AN.empty=new AN(e=>{});B9=class{constructor(e,t){this.toKey=t,this._map=new Map,this[MN]="SetWithKey";for(let i of e)this.add(i)}get size(){return this._map.size}add(e){let t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(let e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(let e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach(i=>e.call(t,i,i,this))}[(RN=Symbol.iterator,MN=Symbol.toStringTag,RN)](){return this.values()}},s5=class{constructor(){this.map=new Map}add(e,t){let i=this.map.get(e);i||(i=new Set,this.map.set(e,i)),i.add(t)}delete(e,t){let i=this.map.get(e);i&&(i.delete(t),i.size===0&&this.map.delete(e))}forEach(e,t){let i=this.map.get(e);i&&i.forEach(t)}get(e){return this.map.get(e)||new Set}};(e=>{function t(S){return S&&typeof S=="object"&&typeof S[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function n(){return i}e.empty=n;function*s(S){yield S}e.single=s;function r(S){return t(S)?S:s(S)}e.wrap=r;function a(S){return S||i}e.from=a;function*o(S){for(let k=S.length-1;k>=0;k--)yield S[k]}e.reverse=o;function l(S){return!S||S[Symbol.iterator]().next().done===!0}e.isEmpty=l;function c(S){return S[Symbol.iterator]().next().value}e.first=c;function u(S,k){let A=0;for(let O of S)if(k(O,A++))return!0;return!1}e.some=u;function h(S,k){for(let A of S)if(k(A))return A}e.find=h;function*d(S,k){for(let A of S)k(A)&&(yield A)}e.filter=d;function*f(S,k){let A=0;for(let O of S)yield k(O,A++)}e.map=f;function*p(S,k){let A=0;for(let O of S)yield*k(O,A++)}e.flatMap=p;function*_(...S){for(let k of S)yield*k}e.concat=_;function w(S,k,A){let O=A;for(let T of S)O=k(O,T);return O}e.reduce=w;function*g(S,k,A=S.length){for(k<0&&(k+=S.length),A<0?A+=S.length:A>S.length&&(A=S.length);ki.source!==null&&!this.getRootParent(i,t).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(t=10,i){let n;if(i)n=i;else{let l=new Map,c=[...this.livingDisposables.values()].filter(h=>h.source!==null&&!this.getRootParent(h,l).isSingleton);if(c.length===0)return;let u=new Set(c.map(h=>h.value));if(n=c.filter(h=>!(h.parent&&u.has(h.parent))),n.length===0)throw new Error("There are cyclic diposable chains!")}if(!n)return;function s(l){function c(h,d){for(;h.length>0&&d.some(f=>typeof f=="string"?f===h[0]:h[0].match(f));)h.shift()}let u=l.source.split(` -`).map(h=>h.trim().replace("at ","")).filter(h=>h!=="");return c(u,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),u.reverse()}let r=new s5;for(let l of n){let c=s(l);for(let u=0;u<=c.length;u++)r.add(c.slice(0,u).join(` -`),l)}n.sort(t5(l=>l.idx,i5));let a="",o=0;for(let l of n.slice(0,t)){o++;let c=s(l),u=[];for(let h=0;hs(_)[h]),_=>_);delete p[c[h]];for(let[_,w]of Object.entries(p))u.unshift(` - stacktraces of ${w.length} other leaks continue with ${_}`);u.unshift(d)}a+=` +`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}},p4=new f4;Nb="Canceled";g4=class extends Error{constructor(){super(Nb),this.name=this.message}};CA=class Ab extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Ab)return t;let i=new Ab;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Mb=class UM extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,UM.prototype)}};b4=class HM{constructor(t){this._array=t,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(HM.assertInvariants){if(this._prevFindLastPredicate){for(let n of this._array)if(this._prevFindLastPredicate(n)&&!t(n))throw new Error("MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.")}this._prevFindLastPredicate=t}let i=v4(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=i+1,i===-1?void 0:this._array[i]}};b4.assertInvariants=!1;(e=>{function t(s){return s<0}e.isLessThan=t;function i(s){return s<=0}e.isLessThanOrEqual=i;function n(s){return s>0}e.isGreaterThan=n;function r(s){return s===0}e.isNeitherLessOrGreaterThan=r,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(Rb||(Rb={}));S4=(e,t)=>e-t,kA=class Ob{constructor(t){this.iterate=t}forEach(t){this.iterate(i=>(t(i),!0))}toArray(){let t=[];return this.iterate(i=>(t.push(i),!0)),t}filter(t){return new Ob(i=>this.iterate(n=>t(n)?i(n):!0))}map(t){return new Ob(i=>this.iterate(n=>i(t(n))))}some(t){let i=!1;return this.iterate(n=>(i=t(n),!i)),i}findFirst(t){let i;return this.iterate(n=>t(n)?(i=n,!1):!0),i}findLast(t){let i;return this.iterate(n=>(t(n)&&(i=n),!0)),i}findLastMaxBy(t){let i,n=!0;return this.iterate(r=>((n||Rb.isGreaterThan(t(r,i)))&&(n=!1,i=r),!0)),i}};kA.empty=new kA(e=>{});RF=class{constructor(e,t){this.toKey=t,this._map=new Map,this[TA]="SetWithKey";for(let i of e)this.add(i)}get size(){return this._map.size}add(e){let t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(let e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(let e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach(i=>e.call(t,i,i,this))}[(NA=Symbol.iterator,TA=Symbol.toStringTag,NA)](){return this.values()}},x4=class{constructor(){this.map=new Map}add(e,t){let i=this.map.get(e);i||(i=new Set,this.map.set(e,i)),i.add(t)}delete(e,t){let i=this.map.get(e);i&&(i.delete(t),i.size===0&&this.map.delete(e))}forEach(e,t){let i=this.map.get(e);i&&i.forEach(t)}get(e){return this.map.get(e)||new Set}};(e=>{function t(w){return w&&typeof w=="object"&&typeof w[Symbol.iterator]=="function"}e.is=t;let i=Object.freeze([]);function n(){return i}e.empty=n;function*r(w){yield w}e.single=r;function s(w){return t(w)?w:r(w)}e.wrap=s;function a(w){return w||i}e.from=a;function*o(w){for(let E=w.length-1;E>=0;E--)yield w[E]}e.reverse=o;function l(w){return!w||w[Symbol.iterator]().next().done===!0}e.isEmpty=l;function c(w){return w[Symbol.iterator]().next().value}e.first=c;function u(w,E){let A=0;for(let O of w)if(E(O,A++))return!0;return!1}e.some=u;function h(w,E){for(let A of w)if(E(A))return A}e.find=h;function*d(w,E){for(let A of w)E(A)&&(yield A)}e.filter=d;function*f(w,E){let A=0;for(let O of w)yield E(O,A++)}e.map=f;function*p(w,E){let A=0;for(let O of w)yield*E(O,A++)}e.flatMap=p;function*_(...w){for(let E of w)yield*E}e.concat=_;function S(w,E,A){let O=A;for(let k of w)O=E(O,k);return O}e.reduce=S;function*m(w,E,A=w.length){for(E<0&&(E+=w.length),A<0?A+=w.length:A>w.length&&(A=w.length);Ei.source!==null&&!this.getRootParent(i,t).isSingleton).flatMap(([i])=>i)}computeLeakingDisposables(t=10,i){let n;if(i)n=i;else{let l=new Map,c=[...this.livingDisposables.values()].filter(h=>h.source!==null&&!this.getRootParent(h,l).isSingleton);if(c.length===0)return;let u=new Set(c.map(h=>h.value));if(n=c.filter(h=>!(h.parent&&u.has(h.parent))),n.length===0)throw new Error("There are cyclic diposable chains!")}if(!n)return;function r(l){function c(h,d){for(;h.length>0&&d.some(f=>typeof f=="string"?f===h[0]:h[0].match(f));)h.shift()}let u=l.source.split(` +`).map(h=>h.trim().replace("at ","")).filter(h=>h!=="");return c(u,["Error",/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),u.reverse()}let s=new x4;for(let l of n){let c=r(l);for(let u=0;u<=c.length;u++)s.add(c.slice(0,u).join(` +`),l)}n.sort(y4(l=>l.idx,S4));let a="",o=0;for(let l of n.slice(0,t)){o++;let c=r(l),u=[];for(let h=0;hr(_)[h]),_=>_);delete p[c[h]];for(let[_,S]of Object.entries(p))u.unshift(` - stacktraces of ${S.length} other leaks continue with ${_}`);u.unshift(d)}a+=` ==================== Leaking disposable ${o}/${n.length}: ${l.value.constructor.name} ==================== @@ -111,27 +112,27 @@ ${u.join(` ... and ${n.length-t} more leaking disposables -`),{leaks:n,details:a}}};o5.idx=0;if(a5){let e="__is_disposable_tracked__";l5(new class{trackDisposable(t){let i=new Error("Potentially leaked disposable").stack;setTimeout(()=>{t[e]||console.log(i)},3e3)}setParent(t,i){if(t&&t!==Ae.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==Ae.None)try{t[e]=!0}catch{}}markAsSingleton(t){}})}$A=class GA{constructor(){this._toDispose=new Set,this._isDisposed=!1,$f(this)}dispose(){this._isDisposed||(Gf(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{to(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return Cu(t,this),this._isDisposed?GA.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),Cu(t,null))}};$A.DISABLE_DISPOSED_WARNING=!1;na=$A,Ae=class{constructor(){this._store=new na,$f(this),Cu(this._store,this)}dispose(){Gf(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Ae.None=Object.freeze({dispose(){}});Ll=class{constructor(){this._isDisposed=!1,$f(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Cu(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Gf(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Cu(e,null),e}},bn=typeof window=="object"?window:globalThis,Xv=class Zv{constructor(t){this.element=t,this.next=Zv.Undefined,this.prev=Zv.Undefined}};Xv.Undefined=new Xv(void 0);St=Xv,DN=class{constructor(){this._first=St.Undefined,this._last=St.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===St.Undefined}clear(){let e=this._first;for(;e!==St.Undefined;){let t=e.next;e.prev=St.Undefined,e.next=St.Undefined,e=t}this._first=St.Undefined,this._last=St.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new St(e);if(this._first===St.Undefined)this._first=i,this._last=i;else if(t){let s=this._last;this._last=i,i.prev=s,s.next=i}else{let s=this._first;this._first=i,i.next=s,s.prev=i}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(i))}}shift(){if(this._first!==St.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==St.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==St.Undefined&&e.next!==St.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===St.Undefined&&e.next===St.Undefined?(this._first=St.Undefined,this._last=St.Undefined):e.next===St.Undefined?(this._last=this._last.prev,this._last.next=St.Undefined):e.prev===St.Undefined&&(this._first=this._first.next,this._first.prev=St.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==St.Undefined;)yield e.element,e=e.next}},h5=globalThis.performance&&typeof globalThis.performance.now=="function",d5=class YA{static create(t){return new YA(t)}constructor(t){this._now=h5&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},f5=!1,LN=!1,p5=!1;(e=>{e.None=()=>Ae.None;function t(B){if(p5){let{onDidAddListener:E}=B,I=eb.create(),C=0;B.onDidAddListener=()=>{++C===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),I.print()),E?.()}}}function i(B,E){return d(B,()=>{},0,void 0,!0,void 0,E)}e.defer=i;function n(B){return(E,I=null,C)=>{let L=!1,R;return R=B($=>{if(!L)return R?R.dispose():L=!0,E.call(I,$)},null,C),L&&R.dispose(),R}}e.once=n;function s(B,E,I){return u((C,L=null,R)=>B($=>C.call(L,E($)),null,R),I)}e.map=s;function r(B,E,I){return u((C,L=null,R)=>B($=>{E($),C.call(L,$)},null,R),I)}e.forEach=r;function a(B,E,I){return u((C,L=null,R)=>B($=>E($)&&C.call(L,$),null,R),I)}e.filter=a;function o(B){return B}e.signal=o;function l(...B){return(E,I=null,C)=>{let L=u5(...B.map(R=>R($=>E.call(I,$))));return h(L,C)}}e.any=l;function c(B,E,I,C){let L=I;return s(B,R=>(L=E(L,R),L),C)}e.reduce=c;function u(B,E){let I,C={onWillAddFirstListener(){I=B(L.fire,L)},onDidRemoveLastListener(){I?.dispose()}};E||t(C);let L=new Q(C);return E?.add(L),L.event}function h(B,E){return E instanceof Array?E.push(B):E&&E.add(B),B}function d(B,E,I=100,C=!1,L=!1,R,$){let ee,z,X,Ee=0,ue,De={leakWarningThreshold:R,onWillAddFirstListener(){ee=B(qe=>{Ee++,z=E(z,qe),C&&!X&&(J.fire(z),z=void 0),ue=()=>{let dt=z;z=void 0,X=void 0,(!C||Ee>1)&&J.fire(dt),Ee=0},typeof I=="number"?(clearTimeout(X),X=setTimeout(ue,I)):X===void 0&&(X=0,queueMicrotask(ue))})},onWillRemoveListener(){L&&Ee>0&&ue?.()},onDidRemoveLastListener(){ue=void 0,ee.dispose()}};$||t(De);let J=new Q(De);return $?.add(J),J.event}e.debounce=d;function f(B,E=0,I){return e.debounce(B,(C,L)=>C?(C.push(L),C):[L],E,void 0,!0,void 0,I)}e.accumulate=f;function p(B,E=(C,L)=>C===L,I){let C=!0,L;return a(B,R=>{let $=C||!E(R,L);return C=!1,L=R,$},I)}e.latch=p;function _(B,E,I){return[e.filter(B,E,I),e.filter(B,C=>!E(C),I)]}e.split=_;function w(B,E=!1,I=[],C){let L=I.slice(),R=B(z=>{L?L.push(z):ee.fire(z)});C&&C.add(R);let $=()=>{L?.forEach(z=>ee.fire(z)),L=null},ee=new Q({onWillAddFirstListener(){R||(R=B(z=>ee.fire(z)),C&&C.add(R))},onDidAddFirstListener(){L&&(E?setTimeout($):$())},onDidRemoveLastListener(){R&&R.dispose(),R=null}});return C&&C.add(ee),ee.event}e.buffer=w;function g(B,E){return(I,C,L)=>{let R=E(new v);return B(function($){let ee=R.evaluate($);ee!==m&&I.call(C,ee)},void 0,L)}}e.chain=g;let m=Symbol("HaltChainable");class v{constructor(){this.steps=[]}map(E){return this.steps.push(E),this}forEach(E){return this.steps.push(I=>(E(I),I)),this}filter(E){return this.steps.push(I=>E(I)?I:m),this}reduce(E,I){let C=I;return this.steps.push(L=>(C=E(C,L),C)),this}latch(E=(I,C)=>I===C){let I=!0,C;return this.steps.push(L=>{let R=I||!E(L,C);return I=!1,C=L,R?L:m}),this}evaluate(E){for(let I of this.steps)if(E=I(E),E===m)break;return E}}function S(B,E,I=C=>C){let C=(...ee)=>$.fire(I(...ee)),L=()=>B.on(E,C),R=()=>B.removeListener(E,C),$=new Q({onWillAddFirstListener:L,onDidRemoveLastListener:R});return $.event}e.fromNodeEventEmitter=S;function k(B,E,I=C=>C){let C=(...ee)=>$.fire(I(...ee)),L=()=>B.addEventListener(E,C),R=()=>B.removeEventListener(E,C),$=new Q({onWillAddFirstListener:L,onDidRemoveLastListener:R});return $.event}e.fromDOMEventEmitter=k;function A(B){return new Promise(E=>n(B)(E))}e.toPromise=A;function O(B){let E=new Q;return B.then(I=>{E.fire(I)},()=>{E.fire(void 0)}).finally(()=>{E.dispose()}),E.event}e.fromPromise=O;function T(B,E){return B(I=>E.fire(I))}e.forward=T;function D(B,E,I){return E(I),B(C=>E(C))}e.runAndSubscribe=D;class F{constructor(E,I){this._observable=E,this._counter=0,this._hasChanged=!1;let C={onWillAddFirstListener:()=>{E.addObserver(this)},onDidRemoveLastListener:()=>{E.removeObserver(this)}};I||t(C),this.emitter=new Q(C),I&&I.add(this.emitter)}beginUpdate(E){this._counter++}handlePossibleChange(E){}handleChange(E,I){this._hasChanged=!0}endUpdate(E){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function P(B,E){return new F(B,E).emitter.event}e.fromObservable=P;function M(B){return(E,I,C)=>{let L=0,R=!1,$={beginUpdate(){L++},endUpdate(){L--,L===0&&(B.reportChanges(),R&&(R=!1,E.call(I)))},handlePossibleChange(){},handleChange(){R=!0}};B.addObserver($),B.reportChanges();let ee={dispose(){B.removeObserver($)}};return C instanceof na?C.add(ee):Array.isArray(C)&&C.push(ee),ee}}e.fromObservableLight=M})(ni||(ni={}));Qv=class Jv{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Jv._idPool++}`,Jv.all.add(this)}start(t){this._stopWatch=new d5,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Qv.all=new Set,Qv._idPool=0;m5=Qv,BN=-1,jA=class VA{constructor(t,i,n=(VA._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=n,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,i){let n=this.threshold;if(n<=0||i{let r=this._stacks.get(t.value)||0;this._stacks.set(t.value,r-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[n,s]of this._stacks)(!t||i{t[e]||console.log(i)},3e3)}setParent(t,i){if(t&&t!==Oe.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==Oe.None)try{t[e]=!0}catch{}}markAsSingleton(t){}})}qM=class KM{constructor(){this._toDispose=new Set,this._isDisposed=!1,bp(this)}dispose(){this._isDisposed||(yp(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{mo(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw new Error("Cannot register a disposable on itself!");return Wu(t,this),this._isDisposed?KM.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(t),t}delete(t){if(t){if(t===this)throw new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(t),t.dispose()}}deleteAndLeak(t){t&&this._toDispose.has(t)&&(this._toDispose.delete(t),Wu(t,null))}};qM.DISABLE_DISPOSED_WARNING=!1;_a=qM,Oe=class{constructor(){this._store=new _a,bp(this),Wu(this._store,this)}dispose(){yp(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Oe.None=Object.freeze({dispose(){}});jl=class{constructor(){this._isDisposed=!1,bp(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&Wu(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,yp(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&Wu(e,null),e}},Nn=typeof window=="object"?window:globalThis,Lb=class Ib{constructor(t){this.element=t,this.next=Ib.Undefined,this.prev=Ib.Undefined}};Lb.Undefined=new Lb(void 0);Ct=Lb,MA=class{constructor(){this._first=Ct.Undefined,this._last=Ct.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ct.Undefined}clear(){let e=this._first;for(;e!==Ct.Undefined;){let t=e.next;e.prev=Ct.Undefined,e.next=Ct.Undefined,e=t}this._first=Ct.Undefined,this._last=Ct.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let i=new Ct(e);if(this._first===Ct.Undefined)this._first=i,this._last=i;else if(t){let r=this._last;this._last=i,i.prev=r,r.next=i}else{let r=this._first;this._first=i,i.next=r,r.prev=i}this._size+=1;let n=!1;return()=>{n||(n=!0,this._remove(i))}}shift(){if(this._first!==Ct.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ct.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ct.Undefined&&e.next!==Ct.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ct.Undefined&&e.next===Ct.Undefined?(this._first=Ct.Undefined,this._last=Ct.Undefined):e.next===Ct.Undefined?(this._last=this._last.prev,this._last.next=Ct.Undefined):e.prev===Ct.Undefined&&(this._first=this._first.next,this._first.prev=Ct.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==Ct.Undefined;)yield e.element,e=e.next}},M4=globalThis.performance&&typeof globalThis.performance.now=="function",R4=class WM{static create(t){return new WM(t)}constructor(t){this._now=M4&&t===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime!==-1?this._stopTime-this._startTime:this._now()-this._startTime}},O4=!1,RA=!1,D4=!1;(e=>{e.None=()=>Oe.None;function t(B){if(D4){let{onDidAddListener:x}=B,z=Pb.create(),C=0;B.onDidAddListener=()=>{++C===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),z.print()),x?.()}}}function i(B,x){return d(B,()=>{},0,void 0,!0,void 0,x)}e.defer=i;function n(B){return(x,z=null,C)=>{let N=!1,R;return R=B(W=>{if(!N)return R?R.dispose():N=!0,x.call(z,W)},null,C),N&&R.dispose(),R}}e.once=n;function r(B,x,z){return u((C,N=null,R)=>B(W=>C.call(N,x(W)),null,R),z)}e.map=r;function s(B,x,z){return u((C,N=null,R)=>B(W=>{x(W),C.call(N,W)},null,R),z)}e.forEach=s;function a(B,x,z){return u((C,N=null,R)=>B(W=>x(W)&&C.call(N,W),null,R),z)}e.filter=a;function o(B){return B}e.signal=o;function l(...B){return(x,z=null,C)=>{let N=A4(...B.map(R=>R(W=>x.call(z,W))));return h(N,C)}}e.any=l;function c(B,x,z,C){let N=z;return r(B,R=>(N=x(N,R),N),C)}e.reduce=c;function u(B,x){let z,C={onWillAddFirstListener(){z=B(N.fire,N)},onDidRemoveLastListener(){z?.dispose()}};x||t(C);let N=new Z(C);return x?.add(N),N.event}function h(B,x){return x instanceof Array?x.push(B):x&&x.add(B),B}function d(B,x,z=100,C=!1,N=!1,R,W){let X,U,Q,Ee=0,he,Ke={leakWarningThreshold:R,onWillAddFirstListener(){X=B(je=>{Ee++,U=x(U,je),C&&!Q&&(J.fire(U),U=void 0),he=()=>{let Ai=U;U=void 0,Q=void 0,(!C||Ee>1)&&J.fire(Ai),Ee=0},typeof z=="number"?(clearTimeout(Q),Q=setTimeout(he,z)):Q===void 0&&(Q=0,queueMicrotask(he))})},onWillRemoveListener(){N&&Ee>0&&he?.()},onDidRemoveLastListener(){he=void 0,X.dispose()}};W||t(Ke);let J=new Z(Ke);return W?.add(J),J.event}e.debounce=d;function f(B,x=0,z){return e.debounce(B,(C,N)=>C?(C.push(N),C):[N],x,void 0,!0,void 0,z)}e.accumulate=f;function p(B,x=(C,N)=>C===N,z){let C=!0,N;return a(B,R=>{let W=C||!x(R,N);return C=!1,N=R,W},z)}e.latch=p;function _(B,x,z){return[e.filter(B,x,z),e.filter(B,C=>!x(C),z)]}e.split=_;function S(B,x=!1,z=[],C){let N=z.slice(),R=B(U=>{N?N.push(U):X.fire(U)});C&&C.add(R);let W=()=>{N?.forEach(U=>X.fire(U)),N=null},X=new Z({onWillAddFirstListener(){R||(R=B(U=>X.fire(U)),C&&C.add(R))},onDidAddFirstListener(){N&&(x?setTimeout(W):W())},onDidRemoveLastListener(){R&&R.dispose(),R=null}});return C&&C.add(X),X.event}e.buffer=S;function m(B,x){return(z,C,N)=>{let R=x(new b);return B(function(W){let X=R.evaluate(W);X!==g&&z.call(C,X)},void 0,N)}}e.chain=m;let g=Symbol("HaltChainable");class b{constructor(){this.steps=[]}map(x){return this.steps.push(x),this}forEach(x){return this.steps.push(z=>(x(z),z)),this}filter(x){return this.steps.push(z=>x(z)?z:g),this}reduce(x,z){let C=z;return this.steps.push(N=>(C=x(C,N),C)),this}latch(x=(z,C)=>z===C){let z=!0,C;return this.steps.push(N=>{let R=z||!x(N,C);return z=!1,C=N,R?N:g}),this}evaluate(x){for(let z of this.steps)if(x=z(x),x===g)break;return x}}function w(B,x,z=C=>C){let C=(...X)=>W.fire(z(...X)),N=()=>B.on(x,C),R=()=>B.removeListener(x,C),W=new Z({onWillAddFirstListener:N,onDidRemoveLastListener:R});return W.event}e.fromNodeEventEmitter=w;function E(B,x,z=C=>C){let C=(...X)=>W.fire(z(...X)),N=()=>B.addEventListener(x,C),R=()=>B.removeEventListener(x,C),W=new Z({onWillAddFirstListener:N,onDidRemoveLastListener:R});return W.event}e.fromDOMEventEmitter=E;function A(B){return new Promise(x=>n(B)(x))}e.toPromise=A;function O(B){let x=new Z;return B.then(z=>{x.fire(z)},()=>{x.fire(void 0)}).finally(()=>{x.dispose()}),x.event}e.fromPromise=O;function k(B,x){return B(z=>x.fire(z))}e.forward=k;function D(B,x,z){return x(z),B(C=>x(C))}e.runAndSubscribe=D;class L{constructor(x,z){this._observable=x,this._counter=0,this._hasChanged=!1;let C={onWillAddFirstListener:()=>{x.addObserver(this)},onDidRemoveLastListener:()=>{x.removeObserver(this)}};z||t(C),this.emitter=new Z(C),z&&z.add(this.emitter)}beginUpdate(x){this._counter++}handlePossibleChange(x){}handleChange(x,z){this._hasChanged=!0}endUpdate(x){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function P(B,x){return new L(B,x).emitter.event}e.fromObservable=P;function I(B){return(x,z,C)=>{let N=0,R=!1,W={beginUpdate(){N++},endUpdate(){N--,N===0&&(B.reportChanges(),R&&(R=!1,x.call(z)))},handlePossibleChange(){},handleChange(){R=!0}};B.addObserver(W),B.reportChanges();let X={dispose(){B.removeObserver(W)}};return C instanceof _a?C.add(X):Array.isArray(C)&&C.push(X),X}}e.fromObservableLight=I})(hi||(hi={}));Bb=class zb{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${zb._idPool++}`,zb.all.add(this)}start(t){this._stopWatch=new R4,this.listenerCount=t}stop(){if(this._stopWatch){let t=this._stopWatch.elapsed();this.durations.push(t),this.elapsedOverall+=t,this.invocationCount+=1,this._stopWatch=void 0}}};Bb.all=new Set,Bb._idPool=0;L4=Bb,OA=-1,$M=class GM{constructor(t,i,n=(GM._idPool++).toString(16).padStart(3,"0")){this._errorHandler=t,this.threshold=i,this.name=n,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(t,i){let n=this.threshold;if(n<=0||i{let s=this._stacks.get(t.value)||0;this._stacks.set(t.value,s-1)}}getMostFrequentStack(){if(!this._stacks)return;let t,i=0;for(let[n,r]of this._stacks)(!t||i{if(e instanceof Tf)t(e);else for(let i=0;i{e.length!==0&&(console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"),console.warn(e.join(` -`)),e.length=0)},3e3),Nf=new FinalizationRegistry(t=>{typeof t=="string"&&e.push(t)})}Q=class{constructor(e){this._size=0,this._options=e,this._leakageMon=BN>0||this._options?.leakWarningThreshold?new g5(e?.onListenerError??kf,this._options?.leakWarningThreshold??BN):void 0,this._perfMon=this._options?._profName?new m5(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(LN){let e=this._listeners;queueMicrotask(()=>{S5(e,t=>t.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??(this._event=(e,t,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let o=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(o);let l=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new v5(`${o}. HINT: Stack shows most frequent listener (${l[1]}-times)`,l[0]);return(this._options?.onListenerError||kf)(c),Ae.None}if(this._disposed)return Ae.None;t&&(e=e.bind(t));let n=new Tf(e),s,r;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=eb.create(),s=this._leakageMon.check(n.stack,this._size+1)),LN&&(n.stack=r??eb.create()),this._listeners?this._listeners instanceof Tf?(this._deliveryQueue??(this._deliveryQueue=new w5),this._listeners=[this._listeners,n]):this._listeners.push(n):(this._options?.onWillAddFirstListener?.(this),this._listeners=n,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=ft(()=>{Nf?.unregister(a),s?.(),this._removeListener(n)});if(i instanceof na?i.add(a):Array.isArray(i)&&i.push(a),Nf){let o=new Error().stack.split(` +`))}},B4=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},z4=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},P4=0,tp=class{constructor(e){this.value=e,this.id=P4++}},U4=2,H4=(e,t)=>{if(e instanceof tp)t(e);else for(let i=0;i{e.length!==0&&(console.warn("[LEAKING LISTENERS] GC'ed these listeners that were NOT yet disposed:"),console.warn(e.join(` +`)),e.length=0)},3e3),ip=new FinalizationRegistry(t=>{typeof t=="string"&&e.push(t)})}Z=class{constructor(e){this._size=0,this._options=e,this._leakageMon=OA>0||this._options?.leakWarningThreshold?new I4(e?.onListenerError??ep,this._options?.leakWarningThreshold??OA):void 0,this._perfMon=this._options?._profName?new L4(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){if(!this._disposed){if(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners){if(RA){let e=this._listeners;queueMicrotask(()=>{H4(e,t=>t.stack?.print())})}this._listeners=void 0,this._size=0}this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose()}}get event(){return this._event??(this._event=(e,t,i)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let o=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(o);let l=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],c=new z4(`${o}. HINT: Stack shows most frequent listener (${l[1]}-times)`,l[0]);return(this._options?.onListenerError||ep)(c),Oe.None}if(this._disposed)return Oe.None;t&&(e=e.bind(t));let n=new tp(e),r,s;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=Pb.create(),r=this._leakageMon.check(n.stack,this._size+1)),RA&&(n.stack=s??Pb.create()),this._listeners?this._listeners instanceof tp?(this._deliveryQueue??(this._deliveryQueue=new F4),this._listeners=[this._listeners,n]):this._listeners.push(n):(this._options?.onWillAddFirstListener?.(this),this._listeners=n,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=_t(()=>{ip?.unregister(a),r?.(),this._removeListener(n)});if(i instanceof _a?i.add(a):Array.isArray(i)&&i.push(a),ip){let o=new Error().stack.split(` `).slice(2,3).join(` -`).trim(),l=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(o);Nf.register(a,l?.[2]??o,a)}return a}),this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[i]=void 0;let n=this._deliveryQueue.current===this;if(this._size*y5<=t.length){let s=0;for(let r=0;r0}},w5=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},tb=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Q,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Q,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(n,t),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToFullScreen.set(n,t),this._onDidChangeFullscreen.fire(n)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};tb.INSTANCE=new tb;Mb=tb;z9=Mb.INSTANCE.onDidChangeZoomLevel;P9=Mb.INSTANCE.onDidChangeFullscreen,Il=typeof navigator=="object"?navigator.userAgent:"",ib=Il.indexOf("Firefox")>=0,Af=Il.indexOf("AppleWebKit")>=0,Rb=Il.indexOf("Chrome")>=0,ZA=!Rb&&Il.indexOf("Safari")>=0,U9=Il.indexOf("Electron/")>=0,H9=Il.indexOf("Android")>=0,Mf=!1;if(typeof bn.matchMedia=="function"){let e=bn.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=bn.matchMedia("(display-mode: fullscreen)");Mf=e.matches,E5(bn,e,({matches:i})=>{Mf&&t.matches||(Mf=i)})}Dl="en",Bf=!1,If=!1,Su=!1,k5=!1,QA=!1,JA=!1,T5=!1,N5=!1,A5=!1,M5=!1,Rf=Dl,IN=Dl,ar=globalThis;typeof ar.vscode<"u"&&typeof ar.vscode.process<"u"?vn=ar.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(vn=process);eM=typeof vn?.versions?.electron=="string",O5=eM&&vn?.type==="renderer";if(typeof vn=="object"){Bf=vn.platform==="win32",If=vn.platform==="darwin",Su=vn.platform==="linux",k5=Su&&!!vn.env.SNAP&&!!vn.env.SNAP_REVISION,T5=eM,A5=!!vn.env.CI||!!vn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Sf=Dl,Rf=Dl;let e=vn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Sf=t.userLocale,IN=t.osLocale,Rf=t.resolvedLanguage||Dl,R5=t.languagePack?.translationsConfigFile}catch{}QA=!0}else typeof navigator=="object"&&!O5?(sr=navigator.userAgent,Bf=sr.indexOf("Windows")>=0,If=sr.indexOf("Macintosh")>=0,N5=(sr.indexOf("Macintosh")>=0||sr.indexOf("iPad")>=0||sr.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Su=sr.indexOf("Linux")>=0,M5=sr?.indexOf("Mobi")>=0,JA=!0,Rf=globalThis._VSCODE_NLS_LANGUAGE||Dl,Sf=navigator.language.toLowerCase(),IN=Sf):console.error("Unable to resolve platform.");Cv=0;If?Cv=1:Bf?Cv=3:Su&&(Cv=2);tM=Bf,Rs=If,D5=Su,kv=QA,L5=JA&&typeof ar.importScripts=="function",F9=L5?ar.origin:void 0,Os=sr,Zr=Rf;(e=>{function t(){return Zr}e.value=t;function i(){return Zr.length===2?Zr==="en":Zr.length>=3?Zr[0]==="e"&&Zr[1]==="n"&&Zr[2]==="-":!1}e.isDefaultVariant=i;function n(){return Zr==="en"}e.isDefault=n})(zN||(zN={}));B5=typeof ar.postMessage=="function"&&!ar.importScripts,I5=(()=>{if(B5){let e=[];ar.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let n=0,s=e.length;n{let n=++t;e.push({id:n,callback:i}),ar.postMessage({vscodeScheduleAsyncWork:n},"*")}}return e=>setTimeout(e)})(),z5=!!(Os&&Os.indexOf("Chrome")>=0),q9=!!(Os&&Os.indexOf("Firefox")>=0),K9=!!(!z5&&Os&&Os.indexOf("Safari")>=0),W9=!!(Os&&Os.indexOf("Edg/")>=0),$9=!!(Os&&Os.indexOf("Android")>=0),Qr=typeof navigator=="object"?navigator:{},G9={clipboard:{writeText:kv||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(Qr&&Qr.clipboard&&Qr.clipboard.writeText),readText:kv||!!(Qr&&Qr.clipboard&&Qr.clipboard.readText)},keyboard:kv||C5()?0:Qr.keyboard||ZA?1:2,touch:"ontouchstart"in bn||Qr.maxTouchPoints>0,pointerEvents:bn.PointerEvent&&("ontouchstart"in bn||navigator.maxTouchPoints>0)},Ob=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Tv=new Ob,PN=new Ob,UN=new Ob,P5=new Array(230);(e=>{function t(o){return Tv.keyCodeToStr(o)}e.toString=t;function i(o){return Tv.strToKeyCode(o)}e.fromString=i;function n(o){return PN.keyCodeToStr(o)}e.toUserSettingsUS=n;function s(o){return UN.keyCodeToStr(o)}e.toUserSettingsGeneral=s;function r(o){return PN.strToKeyCode(o)||UN.strToKeyCode(o)}e.fromUserSettings=r;function a(o){if(o>=98&&o<=113)return null;switch(o){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return Tv.keyCodeToStr(o)}e.toElectronAccelerator=a})(nb||(nb={}));U5=class iM{constructor(t,i,n,s,r){this.ctrlKey=t,this.shiftKey=i,this.altKey=n,this.metaKey=s,this.keyCode=r}equals(t){return t instanceof iM&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",n=this.altKey?"1":"0",s=this.metaKey?"1":"0";return`K${t}${i}${n}${s}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new H5([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},H5=class{constructor(e){if(e.length===0)throw Qz("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof j5?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ni.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:nM})})(qN||(qN={}));j5=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?nM:(this._emitter||(this._emitter=new Q),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},Db=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Gv("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Gv("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},V5=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Gv("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let n=i.setInterval(()=>{e()},t);this.disposable=ft(()=>{i.clearInterval(n),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?Nv=(e,t)=>{I5(()=>{if(i)return;let n=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,n-Date.now())}}))});let i=!1;return{dispose(){i||(i=!0)}}}:Nv=(e,t,i)=>{let n=e.requestIdleCallback(t,typeof i=="number"?{timeout:i}:void 0),s=!1;return{dispose(){s||(s=!0,e.cancelIdleCallback(n))}}},X5=e=>Nv(globalThis,e)})();(e=>{async function t(n){let s,r=await Promise.all(n.map(a=>a.then(o=>o,o=>{s||(s=o)})));if(typeof s<"u")throw s;return r}e.settled=t;function i(n){return new Promise(async(s,r)=>{try{await n(s,r)}catch(a){r(a)}})}e.withAsyncBody=i})(KN||(KN={}));WN=class zn{static fromArray(t){return new zn(i=>{i.emitMany(t)})}static fromPromise(t){return new zn(async i=>{i.emitMany(await t)})}static fromPromises(t){return new zn(async i=>{await Promise.all(t.map(async n=>i.emitOne(await n)))})}static merge(t){return new zn(async i=>{await Promise.all(t.map(async n=>{for await(let s of n)i.emitOne(s)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new Q,queueMicrotask(async()=>{let n={emitOne:s=>this.emitOne(s),emitMany:s=>this.emitMany(s),reject:s=>this.reject(s)};try{await Promise.resolve(t(n)),this.resolve()}catch(s){this.reject(s)}finally{n.emitOne=void 0,n.emitMany=void 0,n.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,i){return new zn(async n=>{for await(let s of t)n.emitOne(i(s))})}map(t){return zn.map(this,t)}static filter(t,i){return new zn(async n=>{for await(let s of t)i(s)&&n.emitOne(s)})}filter(t){return zn.filter(this,t)}static coalesce(t){return zn.filter(t,i=>!!i)}coalesce(){return zn.coalesce(this)}static async toPromise(t){let i=[];for await(let n of t)i.push(n);return i}toPromise(){return zn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};WN.EMPTY=WN.fromArray([]);s4=class rM{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let i=t.length;if(i===0)return;let n=this._buff,s=this._buffLen,r=this._leftoverHighSurrogate,a,o;for(r!==0?(a=r,o=-1,r=0):(a=t.charCodeAt(0),o=0);;){let l=a;if(Z5(a))if(o+1>>6,t[i++]=128|(n&63)>>>0):n<65536?(t[i++]=224|(n&61440)>>>12,t[i++]=128|(n&4032)>>>6,t[i++]=128|(n&63)>>>0):(t[i++]=240|(n&1835008)>>>18,t[i++]=128|(n&258048)>>>12,t[i++]=128|(n&4032)>>>6,t[i++]=128|(n&63)>>>0),i>=64&&(this._step(),i-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),i}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),lu(this._h0)+lu(this._h1)+lu(this._h2)+lu(this._h3)+lu(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,GN(this._buff,this._buffLen),this._buffLen>56&&(this._step(),GN(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=rM._bigBlock32,i=this._buffDV;for(let h=0;h<64;h+=4)t.setUint32(h,i.getUint32(h,!1),!1);for(let h=64;h<320;h+=4)t.setUint32(h,Av(t.getUint32(h-12,!1)^t.getUint32(h-32,!1)^t.getUint32(h-56,!1)^t.getUint32(h-64,!1),1),!1);let n=this._h0,s=this._h1,r=this._h2,a=this._h3,o=this._h4,l,c,u;for(let h=0;h<80;h++)h<20?(l=s&r|~s&a,c=1518500249):h<40?(l=s^r^a,c=1859775393):h<60?(l=s&r|s&a|r&a,c=2400959708):(l=s^r^a,c=3395469782),u=Av(n,5)+l+o+c+t.getUint32(h*4,!1)&4294967295,o=a,a=r,r=Av(s,30),s=n,n=u;this._h0=this._h0+n&4294967295,this._h1=this._h1+s&4294967295,this._h2=this._h2+r&4294967295,this._h3=this._h3+a&4294967295,this._h4=this._h4+o&4294967295}};s4._bigBlock32=new DataView(new ArrayBuffer(320));({registerWindow:Y9,getWindow:es,getDocument:j9,getWindows:V9,getWindowsCount:X9,getWindowId:YN,getWindowById:Z9,hasWindow:Q9,onDidRegisterWindow:r4,onWillUnregisterWindow:J9,onDidUnregisterWindow:e7}=(function(){let e=new Map,t={window:bn,disposables:new na};e.set(bn.vscodeWindowId,t);let i=new Q,n=new Q,s=new Q;function r(a,o){return(typeof a=="number"?e.get(a):void 0)??(o?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:s.event,onDidUnregisterWindow:n.event,registerWindow(a){if(e.has(a.vscodeWindowId))return Ae.None;let o=new na,l={window:a,disposables:o.add(new na)};return e.set(a.vscodeWindowId,l),o.add(ft(()=>{e.delete(a.vscodeWindowId),n.fire(a)})),o.add(_e(a,Jt.BEFORE_UNLOAD,()=>{s.fire(a)})),i.fire(l),o},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(a){return a.vscodeWindowId},hasWindow(a){return e.has(a)},getWindowById:r,getWindow(a){let o=a;if(o?.ownerDocument?.defaultView)return o.ownerDocument.defaultView.window;let l=a;return l?.view?l.view.window:bn},getDocument(a){return es(a).document}}})()),a4=class{constructor(e,t,i,n){this._node=e,this._type=t,this._handler=i,this._options=n||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};jN=function(e,t,i,n){let s=i;return t==="click"||t==="mousedown"||t==="contextmenu"?s=o4(es(e),i):(t==="keydown"||t==="keypress"||t==="keyup")&&(s=l4(i)),_e(e,t,s,n)},u4=class extends V5{constructor(e){super(),this.defaultTarget=e&&es(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},Mv=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){kf(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,n=new Map,s=r=>{i.set(r,!1);let a=e.get(r)??[];for(t.set(r,a),e.set(r,[]),n.set(r,!0);a.length>0;)a.sort(Mv.sort),a.shift().execute();n.set(r,!1)};zf=(r,a,o=0)=>{let l=YN(r),c=new Mv(a,o),u=e.get(l);return u||(u=[],e.set(l,u)),u.push(c),i.get(l)||(i.set(l,!0),r.requestAnimationFrame(()=>s(l))),c},c4=(r,a,o)=>{let l=YN(r);if(n.get(l)){let c=new Mv(a,o),u=t.get(l);return u||(u=[],t.set(l,u)),u.push(c),c}else return zf(r,a,o)}})();VN=class Of{constructor(t,i){this.width=t,this.height=i}with(t=this.width,i=this.height){return t!==this.width||i!==this.height?new Of(t,i):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof Of?t:new Of(t.width,t.height)}static equals(t,i){return t===i?!0:!t||!i?!1:t.width===i.width&&t.height===i.height}};VN.None=new VN(0,0);t7=new class{constructor(){this.mutationObservers=new Map}observe(e,t,i){let n=this.mutationObservers.get(e);n||(n=new Map,this.mutationObservers.set(e,n));let s=J5(i),r=n.get(s);if(r)r.users+=1;else{let a=new Q,o=new MutationObserver(c=>a.fire(c));o.observe(e,i);let l=r={users:1,observer:o,onDidMutate:a.event};t.add(ft(()=>{l.users-=1,l.users===0&&(a.dispose(),o.disconnect(),n?.delete(s),n?.size===0&&this.mutationObservers.delete(e))})),n.set(s,r)}return r.onDidMutate}},Jt={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:Af?"webkitAnimationStart":"animationstart",ANIMATION_END:Af?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:Af?"webkitAnimationIteration":"animationiteration"},d4=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;f4.SVG=function(e,t,...i){return aM("http://www.w3.org/2000/svg",e,t,...i)};p4=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=Ji(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Ji(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Ji(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Ji(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Ji(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Ji(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Ji(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Ji(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Ji(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Ji(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Ji(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Ji(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Ji(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Ji(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};oM=class{constructor(){this._hooks=new na,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,n,s){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=n,this._onStopCallback=s;let r=e;try{e.setPointerCapture(t),this._hooks.add(ft(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{r=es(e)}this._hooks.add(_e(r,Jt.POINTER_MOVE,a=>{if(a.buttons!==i){this.stopMonitoring(!0);return}a.preventDefault(),this._pointerMoveCallback(a)})),this._hooks.add(_e(r,Jt.POINTER_UP,a=>this.stopMonitoring(!0)))}};(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(Jn||(Jn={}));gu=class Ti extends Ae{constructor(){super(),this.dispatched=!1,this.targets=new DN,this.ignoreTargets=new DN,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(ni.runAndSubscribe(r4,({window:t,disposables:i})=>{i.add(_e(t.document,"touchstart",n=>this.onTouchStart(n),{passive:!1})),i.add(_e(t.document,"touchend",n=>this.onTouchEnd(t,n))),i.add(_e(t.document,"touchmove",n=>this.onTouchMove(n),{passive:!1}))},{window:bn,disposables:this._store}))}static addTarget(t){if(!Ti.isTouchDevice())return Ae.None;Ti.INSTANCE||(Ti.INSTANCE=ON(new Ti));let i=Ti.INSTANCE.targets.push(t);return ft(i)}static ignoreTarget(t){if(!Ti.isTouchDevice())return Ae.None;Ti.INSTANCE||(Ti.INSTANCE=ON(new Ti));let i=Ti.INSTANCE.ignoreTargets.push(t);return ft(i)}static isTouchDevice(){return"ontouchstart"in bn||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let n=0,s=t.targetTouches.length;n=Ti.HOLD_DELAY&&Math.abs(l.initialPageX-gn(l.rollingPageX))<30&&Math.abs(l.initialPageY-gn(l.rollingPageY))<30){let u=this.newGestureEvent(Jn.Contextmenu,l.initialTarget);u.pageX=gn(l.rollingPageX),u.pageY=gn(l.rollingPageY),this.dispatchEvent(u)}else if(s===1){let u=gn(l.rollingPageX),h=gn(l.rollingPageY),d=gn(l.rollingTimestamps)-l.rollingTimestamps[0],f=u-l.rollingPageX[0],p=h-l.rollingPageY[0],_=[...this.targets].filter(w=>l.initialTarget instanceof Node&&w.contains(l.initialTarget));this.inertia(t,_,n,Math.abs(f)/d,f>0?1:-1,u,Math.abs(p)/d,p>0?1:-1,h)}this.dispatchEvent(this.newGestureEvent(Jn.End,l.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let n=document.createEvent("CustomEvent");return n.initEvent(t,!1,!0),n.initialTarget=i,n.tapCount=0,n}dispatchEvent(t){if(t.type===Jn.Tap){let i=new Date().getTime(),n=0;i-this._lastSetTapCountTime>Ti.CLEAR_TAP_COUNT_TIME?n=1:n=2,this._lastSetTapCountTime=i,t.tapCount=n}else(t.type===Jn.Change||t.type===Jn.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let n of this.ignoreTargets)if(n.contains(t.initialTarget))return;let i=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let s=0,r=t.initialTarget;for(;r&&r!==n;)s++,r=r.parentElement;i.push([s,n])}i.sort((n,s)=>n[0]-s[0]);for(let[n,s]of i)s.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,n,s,r,a,o,l,c){this.handle=zf(t,()=>{let u=Date.now(),h=u-n,d=0,f=0,p=!0;s+=Ti.SCROLL_FRICTION*h,o+=Ti.SCROLL_FRICTION*h,s>0&&(p=!1,d=r*s*h),o>0&&(p=!1,f=l*o*h);let _=this.newGestureEvent(Jn.Change);_.translationX=d,_.translationY=f,i.forEach(w=>w.dispatchEvent(_)),p||this.inertia(t,i,u,s,r,a+d,o,l,c+f)})}onTouchMove(t){let i=Date.now();for(let n=0,s=t.changedTouches.length;n3&&(a.rollingPageX.shift(),a.rollingPageY.shift(),a.rollingTimestamps.shift()),a.rollingPageX.push(r.pageX),a.rollingPageY.push(r.pageY),a.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};gu.SCROLL_FRICTION=-.005,gu.HOLD_DELAY=700,gu.CLEAR_TAP_COUNT_TIME=400,kt([m4],gu,"isTouchDevice",1);g4=gu,Bb=class extends Ae{onclick(e,t){this._register(_e(e,Jt.CLICK,i=>t(new mu(es(e),i))))}onmousedown(e,t){this._register(_e(e,Jt.MOUSE_DOWN,i=>t(new mu(es(e),i))))}onmouseover(e,t){this._register(_e(e,Jt.MOUSE_OVER,i=>t(new mu(es(e),i))))}onmouseleave(e,t){this._register(_e(e,Jt.MOUSE_LEAVE,i=>t(new mu(es(e),i))))}onkeydown(e,t){this._register(_e(e,Jt.KEY_DOWN,i=>t(new sb(i))))}onkeyup(e,t){this._register(_e(e,Jt.KEY_UP,i=>t(new sb(i))))}oninput(e,t){this._register(_e(e,Jt.INPUT,t))}onblur(e,t){this._register(_e(e,Jt.BLUR,t))}onfocus(e,t){this._register(_e(e,Jt.FOCUS,t))}onchange(e,t){this._register(_e(e,Jt.CHANGE,t))}ignoreGesture(e){return g4.ignoreTarget(e)}},XN=11,_4=class extends Bb{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=XN+"px",this.domNode.style.height=XN+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new oM),this._register(jN(this.bgDomNode,Jt.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(jN(this.domNode,Jt.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new u4),this._pointerdownScheduleRepeatTimer=this._register(new Db)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,es(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},v4=class rb{constructor(t,i,n,s,r,a,o){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,n=n|0,s=s|0,r=r|0,a=a|0,o=o|0),this.rawScrollLeft=s,this.rawScrollTop=o,i<0&&(i=0),s+i>n&&(s=n-i),s<0&&(s=0),r<0&&(r=0),o+r>a&&(o=a-r),o<0&&(o=0),this.width=i,this.scrollWidth=n,this.scrollLeft=s,this.height=r,this.scrollHeight=a,this.scrollTop=o}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new rb(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new rb(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let n=this.width!==t.width,s=this.scrollWidth!==t.scrollWidth,r=this.scrollLeft!==t.scrollLeft,a=this.height!==t.height,o=this.scrollHeight!==t.scrollHeight,l=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:s,scrollLeftChanged:r,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:l}}},b4=class extends Ae{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new v4(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let n;t?n=new QN(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):n=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=n}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=QN.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},ZN=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};QN=class ab{constructor(t,i,n,s){this.from=t,this.to=i,this.duration=s,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,i,n){if(Math.abs(t-i)>2.5*n){let s,r;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},x4=140,lM=class extends Bb{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new E4(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new oM),this._shouldRender=!0,this.domNode=wu(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(_e(this.domNode.domNode,Jt.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new _4(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,n){this.slider=wu(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof n=="number"&&this.slider.setHeight(n),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(_e(this.slider.domNode,Jt.POINTER_DOWN,s=>{s.button===0&&(s.preventDefault(),this._sliderPointerDown(s))})),this.onclick(this.slider.domNode,s=>{s.leftButton&&s.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),n=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),s=this._sliderPointerPosition(e);i<=s&&s<=n?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let s=h4(this.domNode.domNode);t=e.pageX-s.left,i=e.pageY-s.top}let n=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(n):this._scrollbarState.getDesiredScrollPositionFromOffset(n)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),n=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,s=>{let r=this._sliderOrthogonalPointerPosition(s),a=Math.abs(r-i);if(tM&&a>x4){this._setDesiredScrollPositionNow(n.getScrollPosition());return}let o=this._sliderPointerPosition(s)-t;this._setDesiredScrollPositionNow(n.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},cM=class ob{constructor(t,i,n,s,r,a){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(t),this._visibleSize=s,this._scrollSize=r,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new ob(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,n,s,r){let a=Math.max(0,n-t),o=Math.max(0,a-2*i),l=s>0&&s>n;if(!l)return{computedAvailableSize:Math.round(a),computedIsNeeded:l,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/s))),u=(o-c)/(s-n),h=r*u;return{computedAvailableSize:Math.round(a),computedIsNeeded:l,computedSliderSize:Math.round(c),computedSliderRatio:u,computedSliderPosition:Math.round(h)}}_refreshComputedValues(){let t=ob._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,n=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(n+=.25),i){let s=Math.abs(t.deltaX),r=Math.abs(t.deltaY),a=Math.abs(i.deltaX),o=Math.abs(i.deltaY),l=Math.max(Math.min(s,a),1),c=Math.max(Math.min(r,o),1),u=Math.max(s,a),h=Math.max(r,o);u%l===0&&h%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};lb.INSTANCE=new lb;A4=lb,M4=class extends Bb{constructor(e,t,i){super(),this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Q),this.onWillScroll=this._onWillScroll.event,this._options=O4(t),this._scrollable=i,this._register(this._scrollable.onScroll(s=>{this._onWillScroll.fire(s),this._onDidScroll(s),this._onScroll.fire(s)}));let n={onMouseWheel:s=>this._onMouseWheel(s),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new k4(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new C4(this._scrollable,this._options,n)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=wu(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=wu(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=wu(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,s=>this._onMouseOver(s)),this.onmouseleave(this._listenOnDomNode,s=>this._onMouseLeave(s)),this._hideTimeout=this._register(new Db),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=to(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Rs&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new FN(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=to(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new FN(i))};this._mouseWheelToDispose.push(_e(this._listenOnDomNode,Jt.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=A4.INSTANCE;eA&&t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let s=e.deltaY*this._options.mouseWheelScrollSensitivity,r=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&r+s===0?r=s=0:Math.abs(s)>=Math.abs(r)?r=0:s=0),this._options.flipAxes&&([s,r]=[r,s]);let a=!Rs&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!r&&(r=s,s=0),e.browserEvent&&e.browserEvent.altKey&&(r=r*this._options.fastScrollSensitivity,s=s*this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),l={};if(s){let c=JN*s,u=o.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(l,u)}if(r){let c=JN*r,u=o.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(l,u)}l=this._scrollable.validateScrollPosition(l),(o.scrollLeft!==l.scrollLeft||o.scrollTop!==l.scrollTop)&&(eA&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(l):this._scrollable.setScrollPositionNow(l),i=!0)}let n=i;!n&&this._options.alwaysConsumeMouseWheel&&(n=!0),!n&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(n=!0),n&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,n=i?" left":"",s=t?" top":"",r=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${n}`),this._topShadowDomNode.setClassName(`shadow${s}`),this._topLeftShadowDomNode.setClassName(`shadow${r}${s}${n}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),T4)}},R4=class extends M4{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};cb=class extends Ae{constructor(e,t,i,n,s,r,a,o){super(),this._bufferService=i,this._optionsService=a,this._renderService=o,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let l=this._register(new b4({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:c=>zf(n.window,c)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{l.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new R4(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},l)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(s.onProtocolChange(c=>{this._scrollableElement.updateOptions({handleMouseWheel:!(c&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(ni.runAndSubscribe(r.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=r.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(ft(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(ft(()=>this._styleElement.remove())),this._register(ni.runAndSubscribe(r.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${r.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${r.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${r.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` -`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(c=>this._handleScroll(c)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};cb=kt([se(2,Ui),se(3,or),se(4,zA),se(5,Bl),se(6,Hi),se(7,lr)],cb);ub=class extends Ae{constructor(e,t,i,n,s){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=n,this._renderService=s,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(r=>this._removeDecoration(r))),this._register(ft(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};ub=kt([se(1,Ui),se(2,or),se(3,Mu),se(4,lr)],ub);D4=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},As={full:0,left:0,center:0,right:0},Jr={full:0,left:0,center:0,right:0},cu={full:0,left:0,center:0,right:0},Pf=class extends Ae{constructor(e,t,i,n,s,r,a,o){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=n,this._renderService=s,this._optionsService=r,this._themeService=a,this._coreBrowserService=o,this._colorZoneStore=new D4,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(ft(()=>this._canvas?.remove()));let l=this._canvas.getContext("2d");if(l)this._ctx=l;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);Jr.full=this._canvas.width,Jr.left=e,Jr.center=t,Jr.right=e,this._refreshDrawHeightConstants(),cu.full=1,cu.left=1,cu.center=1+Jr.left,cu.right=1+Jr.left+Jr.center}_refreshDrawHeightConstants(){As.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);As.left=t,As.center=t,As.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*As.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*As.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*As.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*As.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(cu[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-As[e.position||"full"]/2),Jr[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+As[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};Pf=kt([se(2,Ui),se(3,Mu),se(4,lr),se(5,Hi),se(6,Bl),se(7,or)],Pf);(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` -`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL="\x7F"))(H||(H={}));(e=>(e.PAD="\x80",e.HOP="\x81",e.BPH="\x82",e.NBH="\x83",e.IND="\x84",e.NEL="\x85",e.SSA="\x86",e.ESA="\x87",e.HTS="\x88",e.HTJ="\x89",e.VTS="\x8A",e.PLD="\x8B",e.PLU="\x8C",e.RI="\x8D",e.SS2="\x8E",e.SS3="\x8F",e.DCS="\x90",e.PU1="\x91",e.PU2="\x92",e.STS="\x93",e.CCH="\x94",e.MW="\x95",e.SPA="\x96",e.EPA="\x97",e.SOS="\x98",e.SGCI="\x99",e.SCI="\x9A",e.CSI="\x9B",e.ST="\x9C",e.OSC="\x9D",e.PM="\x9E",e.APC="\x9F"))(Eu||(Eu={}));(e=>e.ST=`${H.ESC}\\`)(hb||(hb={}));db=class{constructor(e,t,i,n,s,r){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=n,this._coreService=s,this._renderService=r,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};db=kt([se(2,Ui),se(3,Hi),se(4,no),se(5,lr)],db);ei=0,ti=0,ii=0,Ct=0,tA={css:"#00000000",rgba:0};(e=>{function t(s,r,a,o){return o!==void 0?`#${Xa(s)}${Xa(r)}${Xa(a)}${Xa(o)}`:`#${Xa(s)}${Xa(r)}${Xa(a)}`}e.toCss=t;function i(s,r,a,o=255){return(s<<24|r<<16|a<<8|o)>>>0}e.toRgba=i;function n(s,r,a,o){return{css:e.toCss(s,r,a,o),rgba:e.toRgba(s,r,a,o)}}e.toColor=n})(Rt||(Rt={}));(e=>{function t(l,c){if(Ct=(c.rgba&255)/255,Ct===1)return{css:c.css,rgba:c.rgba};let u=c.rgba>>24&255,h=c.rgba>>16&255,d=c.rgba>>8&255,f=l.rgba>>24&255,p=l.rgba>>16&255,_=l.rgba>>8&255;ei=f+Math.round((u-f)*Ct),ti=p+Math.round((h-p)*Ct),ii=_+Math.round((d-_)*Ct);let w=Rt.toCss(ei,ti,ii),g=Rt.toRgba(ei,ti,ii);return{css:w,rgba:g}}e.blend=t;function i(l){return(l.rgba&255)===255}e.isOpaque=i;function n(l,c,u){let h=xu.ensureContrastRatio(l.rgba,c.rgba,u);if(h)return Rt.toColor(h>>24&255,h>>16&255,h>>8&255)}e.ensureContrastRatio=n;function s(l){let c=(l.rgba|255)>>>0;return[ei,ti,ii]=xu.toChannels(c),{css:Rt.toCss(ei,ti,ii),rgba:c}}e.opaque=s;function r(l,c){return Ct=Math.round(c*255),[ei,ti,ii]=xu.toChannels(l.rgba),{css:Rt.toCss(ei,ti,ii,Ct),rgba:Rt.toRgba(ei,ti,ii,Ct)}}e.opacity=r;function a(l,c){return Ct=l.rgba&255,r(l,Ct*c/255)}e.multiplyOpacity=a;function o(l){return[l.rgba>>24&255,l.rgba>>16&255,l.rgba>>8&255]}e.toColorRGB=o})(ht||(ht={}));(e=>{let t,i;try{let s=document.createElement("canvas");s.width=1,s.height=1;let r=s.getContext("2d",{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function n(s){if(s.match(/#[\da-f]{3,8}/i))switch(s.length){case 4:return ei=parseInt(s.slice(1,2).repeat(2),16),ti=parseInt(s.slice(2,3).repeat(2),16),ii=parseInt(s.slice(3,4).repeat(2),16),Rt.toColor(ei,ti,ii);case 5:return ei=parseInt(s.slice(1,2).repeat(2),16),ti=parseInt(s.slice(2,3).repeat(2),16),ii=parseInt(s.slice(3,4).repeat(2),16),Ct=parseInt(s.slice(4,5).repeat(2),16),Rt.toColor(ei,ti,ii,Ct);case 7:return{css:s,rgba:(parseInt(s.slice(1),16)<<8|255)>>>0};case 9:return{css:s,rgba:parseInt(s.slice(1),16)>>>0}}let r=s.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return ei=parseInt(r[1]),ti=parseInt(r[2]),ii=parseInt(r[3]),Ct=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),Rt.toColor(ei,ti,ii,Ct);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=s,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[ei,ti,ii,Ct]=t.getImageData(0,0,1,1).data,Ct!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:Rt.toRgba(ei,ti,ii,Ct),css:s}}e.toColor=n})(vt||(vt={}));(e=>{function t(n){return i(n>>16&255,n>>8&255,n&255)}e.relativeLuminance=t;function i(n,s,r){let a=n/255,o=s/255,l=r/255,c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),u=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4);return c*.2126+u*.7152+h*.0722}e.relativeLuminance2=i})(Ni||(Ni={}));(e=>{function t(a,o){if(Ct=(o&255)/255,Ct===1)return o;let l=o>>24&255,c=o>>16&255,u=o>>8&255,h=a>>24&255,d=a>>16&255,f=a>>8&255;return ei=h+Math.round((l-h)*Ct),ti=d+Math.round((c-d)*Ct),ii=f+Math.round((u-f)*Ct),Rt.toRgba(ei,ti,ii)}e.blend=t;function i(a,o,l){let c=Ni.relativeLuminance(a>>8),u=Ni.relativeLuminance(o>>8);if(nr(c,u)>8));if(p>8));return p>w?f:_}return f}let h=s(a,o,l),d=nr(c,Ni.relativeLuminance(h>>8));if(d>8));return d>p?h:f}return h}}e.ensureContrastRatio=i;function n(a,o,l){let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=o>>24&255,f=o>>16&255,p=o>>8&255,_=nr(Ni.relativeLuminance2(d,f,p),Ni.relativeLuminance2(c,u,h));for(;_0||f>0||p>0);)d-=Math.max(0,Math.ceil(d*.1)),f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),_=nr(Ni.relativeLuminance2(d,f,p),Ni.relativeLuminance2(c,u,h));return(d<<24|f<<16|p<<8|255)>>>0}e.reduceLuminance=n;function s(a,o,l){let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=o>>24&255,f=o>>16&255,p=o>>8&255,_=nr(Ni.relativeLuminance2(d,f,p),Ni.relativeLuminance2(c,u,h));for(;_>>0}e.increaseLuminance=s;function r(a){return[a>>24&255,a>>16&255,a>>8&255,a&255]}e.toChannels=r})(xu||(xu={}));L4=class extends Au{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Uf=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Un}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t1){let u=this._getJoinedRanges(n,a,r,t,s);for(let h=0;h1){let c=this._getJoinedRanges(n,a,r,t,s);for(let u=0;u=F,L=B,R=this._workCell;if(d.length>0&&B===d[0][0]&&C){let xe=d.shift(),ci=this._isCellInSelection(xe[0],t);for(m=xe[0]+1;m=xe[1]),C?(I=!0,R=new L4(this._workCell,e.translateToString(!0,xe[0],xe[1]),xe[1]-xe[0]),L=xe[1]-1,E=R.getWidth()):F=xe[1]}let $=this._isCellInSelection(B,t),ee=i&&B===r,z=M&&B>=c&&B<=u,X=!1;this._decorationService.forEachDecorationAtCell(B,t,void 0,xe=>{X=!0});let Ee=R.getChars()||ia;if(Ee===" "&&(R.isUnderline()||R.isOverline())&&(Ee="\xA0"),D=E*o-l.get(Ee,R.isBold(),R.isItalic()),!_)_=this._document.createElement("span");else if(w&&($&&T||!$&&!T&&R.bg===v)&&($&&T&&f.selectionForeground||R.fg===S)&&R.extended.ext===k&&z===A&&D===O&&!ee&&!I&&!X&&C){R.isInvisible()?g+=ia:g+=Ee,w++;continue}else w&&(_.textContent=g),_=this._document.createElement("span"),w=0,g="";if(v=R.bg,S=R.fg,k=R.extended.ext,A=z,O=D,T=$,I&&r>=B&&r<=L&&(r=B),!this._coreService.isCursorHidden&&ee&&this._coreService.isCursorInitialized){if(P.push("xterm-cursor"),this._coreBrowserService.isFocused)a&&P.push("xterm-cursor-blink"),P.push(n==="bar"?"xterm-cursor-bar":n==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(s)switch(s){case"outline":P.push("xterm-cursor-outline");break;case"block":P.push("xterm-cursor-block");break;case"bar":P.push("xterm-cursor-bar");break;case"underline":P.push("xterm-cursor-underline");break;default:break}}if(R.isBold()&&P.push("xterm-bold"),R.isItalic()&&P.push("xterm-italic"),R.isDim()&&P.push("xterm-dim"),R.isInvisible()?g=ia:g=R.getChars()||ia,R.isUnderline()&&(P.push(`xterm-underline-${R.extended.underlineStyle}`),g===" "&&(g="\xA0"),!R.isUnderlineColorDefault()))if(R.isUnderlineColorRGB())_.style.textDecorationColor=`rgb(${Au.toColorRGB(R.getUnderlineColor()).join(",")})`;else{let xe=R.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&R.isBold()&&xe<8&&(xe+=8),_.style.textDecorationColor=f.ansi[xe].css}R.isOverline()&&(P.push("xterm-overline"),g===" "&&(g="\xA0")),R.isStrikethrough()&&P.push("xterm-strikethrough"),z&&(_.style.textDecoration="underline");let ue=R.getFgColor(),De=R.getFgColorMode(),J=R.getBgColor(),qe=R.getBgColorMode(),dt=!!R.isInverse();if(dt){let xe=ue;ue=J,J=xe;let ci=De;De=qe,qe=ci}let oi,Mi,Ri=!1;this._decorationService.forEachDecorationAtCell(B,t,void 0,xe=>{xe.options.layer!=="top"&&Ri||(xe.backgroundColorRGB&&(qe=50331648,J=xe.backgroundColorRGB.rgba>>8&16777215,oi=xe.backgroundColorRGB),xe.foregroundColorRGB&&(De=50331648,ue=xe.foregroundColorRGB.rgba>>8&16777215,Mi=xe.foregroundColorRGB),Ri=xe.options.layer==="top")}),!Ri&&$&&(oi=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,J=oi.rgba>>8&16777215,qe=50331648,Ri=!0,f.selectionForeground&&(De=50331648,ue=f.selectionForeground.rgba>>8&16777215,Mi=f.selectionForeground)),Ri&&P.push("xterm-decoration-top");let li;switch(qe){case 16777216:case 33554432:li=f.ansi[J],P.push(`xterm-bg-${J}`);break;case 50331648:li=Rt.toColor(J>>16,J>>8&255,J&255),this._addStyle(_,`background-color:#${iA((J>>>0).toString(16),"0",6)}`);break;default:dt?(li=f.foreground,P.push("xterm-bg-257")):li=f.background}switch(oi||R.isDim()&&(oi=ht.multiplyOpacity(li,.5)),De){case 16777216:case 33554432:R.isBold()&&ue<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ue+=8),this._applyMinimumContrast(_,li,f.ansi[ue],R,oi,void 0)||P.push(`xterm-fg-${ue}`);break;case 50331648:let xe=Rt.toColor(ue>>16&255,ue>>8&255,ue&255);this._applyMinimumContrast(_,li,xe,R,oi,Mi)||this._addStyle(_,`color:#${iA(ue.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(_,li,f.foreground,R,oi,Mi)||dt&&P.push("xterm-fg-257")}P.length&&(_.className=P.join(" "),P.length=0),!ee&&!I&&!X&&C?w++:_.textContent=g,D!==this.defaultSpacing&&(_.style.letterSpacing=`${D}px`),h.push(_),B=L}return _&&w&&(_.textContent=g),h}_applyMinimumContrast(e,t,i,n,s,r){if(this._optionsService.rawOptions.minimumContrastRatio===1||z4(n.getCode()))return!1;let a=this._getContrastCache(n),o;if(!s&&!r&&(o=a.getColor(t.rgba,i.rgba)),o===void 0){let l=this._optionsService.rawOptions.minimumContrastRatio/(n.isDim()?2:1);o=ht.ensureContrastRatio(s||t,r||i,l),a.setColor((s||t).rgba,(r||i).rgba,o??null)}return o?(this._addStyle(e,`color:${o.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,n=this._selectionEnd;return!i||!n?!1:this._columnSelectMode?i[0]<=n[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=n[0]&&t<=n[1]:t>i[1]&&t=i[0]&&e=i[0]}};fb=kt([se(1,HA),se(2,Hi),se(3,or),se(4,no),se(5,Mu),se(6,Bl)],fb);U4=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let i=e.createElement("span");i.classList.add("xterm-char-measure-element");let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold";let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontStyle="italic";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontWeight="bold",r.style.fontStyle="italic",this._measureElements=[i,n,s,r],this._container.appendChild(i),this._container.appendChild(n),this._container.appendChild(s),this._container.appendChild(r),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,n){e===this._font&&t===this._fontSize&&i===this._weight&&n===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=n,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${n}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${n}`,this.clear())}get(e,t,i){let n=0;if(!t&&!i&&e.length===1&&(n=e.charCodeAt(0))<256){if(this._flat[n]!==-9999)return this._flat[n];let a=this._measure(e,0);return a>0&&(this._flat[n]=a),a}let s=e;t&&(s+="B"),i&&(s+="I");let r=this._holey.get(s);if(r===void 0){let a=0;t&&(a|=1),i&&(a|=2),r=this._measure(e,a),r>0&&this._holey.set(s,r)}return r}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},H4=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,n=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let s=e.buffers.active.ydisp,r=t[1]-s,a=i[1]-s,o=Math.max(r,0),l=Math.min(a,e.rows-1);if(o>=e.rows||l<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=n,this.viewportStartRow=r,this.viewportEndRow=a,this.viewportCappedStartRow=o,this.viewportCappedEndRow=l,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};Ov="xterm-dom-renderer-owner-",In="xterm-rows",Ef="xterm-fg-",nA="xterm-bg-",uu="xterm-focus",xf="xterm-selection",q4=1,pb=class extends Ae{constructor(e,t,i,n,s,r,a,o,l,c,u,h,d,f){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=n,this._viewportElement=s,this._helperContainer=r,this._linkifier2=a,this._charSizeService=l,this._optionsService=c,this._bufferService=u,this._coreService=h,this._coreBrowserService=d,this._themeService=f,this._terminalClass=q4++,this._rowElements=[],this._selectionRenderModel=F4(),this.onRequestRedraw=this._register(new Q).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(In),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(xf),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=P4(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(p=>this._injectCss(p))),this._injectCss(this._themeService.colors),this._rowFactory=o.createInstance(fb,document),this._element.classList.add(Ov+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(p=>this._handleLinkHover(p))),this._register(this._linkifier2.onHideLinkUnderline(p=>this._handleLinkLeave(p))),this._register(ft(()=>{this._element.classList.remove(Ov+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new U4(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${In} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${In} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${In} .xterm-dim { color: ${ht.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,n=`blink_bar_${this._terminalClass}`,s=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${n} { 50% { box-shadow: none; }}`,t+=`@keyframes ${s} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${In}.${uu} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${In}.${uu} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${In}.${uu} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${In} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${In} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${In} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${In} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${In} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${xf} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${xf} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${xf} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[r,a]of e.ansi.entries())t+=`${this._terminalSelector} .${Ef}${r} { color: ${a.css}; }${this._terminalSelector} .${Ef}${r}.xterm-dim { color: ${ht.multiplyOpacity(a,.5).css}; }${this._terminalSelector} .${nA}${r} { background-color: ${a.css}; }`;t+=`${this._terminalSelector} .${Ef}257 { color: ${ht.opaque(e.background).css}; }${this._terminalSelector} .${Ef}257.xterm-dim { color: ${ht.multiplyOpacity(ht.opaque(e.background),.5).css}; }${this._terminalSelector} .${nA}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let n=this._document.createElement("div");this._rowContainer.appendChild(n),this._rowElements.push(n)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(uu),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(uu),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let n=this._selectionRenderModel.viewportStartRow,s=this._selectionRenderModel.viewportEndRow,r=this._selectionRenderModel.viewportCappedStartRow,a=this._selectionRenderModel.viewportCappedEndRow,o=this._document.createDocumentFragment();if(i){let l=e[0]>t[0];o.appendChild(this._createSelectionElement(r,l?t[0]:e[0],l?e[0]:t[0],a-r+1))}else{let l=n===r?e[0]:0,c=r===s?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(r,l,c));let u=a-r-1;if(o.appendChild(this._createSelectionElement(r+1,0,this._bufferService.cols,u)),r!==a){let h=s===a?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(a,0,h))}}this._selectionContainer.appendChild(o)}_createSelectionElement(e,t,i,n=1){let s=this._document.createElement("div"),r=t*this.dimensions.css.cell.width,a=this.dimensions.css.cell.width*(i-t);return r+a>this.dimensions.css.canvas.width&&(a=this.dimensions.css.canvas.width-r),s.style.height=`${n*this.dimensions.css.cell.height}px`,s.style.top=`${e*this.dimensions.css.cell.height}px`,s.style.left=`${r}px`,s.style.width=`${a}px`,s}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,n=i.ybase+i.y,s=Math.min(i.x,this._bufferService.cols-1),r=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,a=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,o=this._optionsService.rawOptions.cursorInactiveStyle;for(let l=e;l<=t;l++){let c=l+i.ydisp,u=this._rowElements[l],h=i.lines.get(c);if(!u||!h)break;u.replaceChildren(...this._rowFactory.createRow(h,c,c===n,a,o,s,r,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${Ov}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,n,s,r){i<0&&(e=0),n<0&&(t=0);let a=this._bufferService.rows-1;i=Math.max(Math.min(i,a),0),n=Math.max(Math.min(n,a),0),s=Math.min(s,this._bufferService.cols);let o=this._bufferService.buffer,l=o.ybase+o.y,c=Math.min(o.x,s-1),u=this._optionsService.rawOptions.cursorBlink,h=this._optionsService.rawOptions.cursorStyle,d=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=i;f<=n;++f){let p=f+o.ydisp,_=this._rowElements[f],w=o.lines.get(p);if(!_||!w)break;_.replaceChildren(...this._rowFactory.createRow(w,p,p===l,h,d,c,u,this.dimensions.css.cell.width,this._widthCache,r?f===i?e:0:-1,r?(f===n?t:s)-1:-1))}}};pb=kt([se(7,Nb),se(8,Wf),se(9,Hi),se(10,Ui),se(11,no),se(12,or),se(13,Bl)],pb);mb=class extends Ae{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Q),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new W4(this._optionsService))}catch{this._measureStrategy=this._register(new K4(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};mb=kt([se(2,Hi)],mb);uM=class extends Ae{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},K4=class extends uM{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},W4=class extends uM{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},$4=class extends Ae{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new G4(this._window)),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Q),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(n=>this._screenDprMonitor.setWindow(n))),this._register(ni.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(_e(this._textarea,"focus",()=>this._isFocused=!0)),this._register(_e(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},G4=class extends Ae{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Ll),this._onDprChange=this._register(new Q),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(ft(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=_e(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},Y4=class extends Ae{constructor(){super(),this.linkProviders=[],this._register(ft(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};gb=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,n,s){return j4(window,e,t,i,n,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,s)}getMouseReportCoords(e,t){let i=Ib(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};gb=kt([se(0,lr),se(1,Wf)],gb);V4=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},hM={};Bz(hM,{getSafariVersion:()=>Z4,isChromeOS:()=>mM,isFirefox:()=>dM,isIpad:()=>Q4,isIphone:()=>J4,isLegacyEdge:()=>X4,isLinux:()=>zb,isMac:()=>Hf,isNode:()=>Yf,isSafari:()=>fM,isWindows:()=>pM});Yf=typeof process<"u"&&"title"in process,Ru=Yf?"node":navigator.userAgent,Ou=Yf?"node":navigator.platform,dM=Ru.includes("Firefox"),X4=Ru.includes("Edge"),fM=/^((?!chrome|android).)*safari/i.test(Ru);Hf=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Ou),Q4=Ou==="iPad",J4=Ou==="iPhone",pM=["Windows","Win16","Win32","WinCE"].includes(Ou),zb=Ou.indexOf("Linux")>=0,mM=/\bCrOS\b/.test(Ru),gM=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._is){n-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(n-t))}ms`),this._start();return}n=s}this.clear()}},e6=class extends gM{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},t6=class extends gM{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Ff=!Yf&&"requestIdleCallback"in window?t6:e6,i6=class{constructor(){this._queue=new Ff}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},_b=class extends Ae{constructor(e,t,i,n,s,r,a,o,l){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=n,this._coreService=s,this._coreBrowserService=o,this._renderer=this._register(new Ll),this._pausedResizeTask=new i6,this._observerDisposable=this._register(new Ll),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Q),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Q),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Q),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new V4((c,u)=>this._renderRows(c,u),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new n6(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(ft(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(a.onResize(()=>this._fullRefresh())),this._register(a.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(r.onDecorationRegistered(()=>this._fullRefresh())),this._register(r.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(a.cols,a.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(a.buffer.y,a.buffer.y,!0))),this._register(l.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(c=>this._registerIntersectionObserver(c,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(n=>this._handleIntersectionChange(n[n.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=ft(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let n=this._syncOutputHandler.flush();n&&(e=Math.min(e,n.start),t=Math.max(t,n.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};_b=kt([se(2,Hi),se(3,Wf),se(4,no),se(5,Mu),se(6,Ui),se(7,or),se(8,Bl)],_b);n6=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};h6=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};Dv=50,d6=15,f6=50,p6=500,m6="\xA0",g6=new RegExp(m6,"g"),vb=class extends Ae{constructor(e,t,i,n,s,r,a,o,l){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=n,this._coreService=s,this._mouseService=r,this._optionsService=a,this._renderService=o,this._coreBrowserService=l,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Un,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Q),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Q),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Q),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=c=>this._handleMouseMove(c),this._mouseUpListener=c=>this._handleMouseUp(c),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(c=>this._handleTrim(c)),this._register(this._bufferService.buffers.onBufferActivate(c=>this._handleBufferActivate(c))),this.enable(),this._model=new h6(this._bufferService),this._activeSelectionMode=0,this._register(ft(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(c=>{c.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,n=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let s=e[0]s.replace(g6," ")).join(pM?`\r +`).trim(),l=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(o);ip.register(a,l?.[2]??o,a)}return a}),this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,i=t.indexOf(e);if(i===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[i]=void 0;let n=this._deliveryQueue.current===this;if(this._size*U4<=t.length){let r=0;for(let s=0;s0}},F4=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,i){this.i=0,this.end=i,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Ub=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Z,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Z,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(t){return this.mapWindowIdToZoomLevel.get(this.getWindowId(t))??0}setZoomLevel(t,i){if(this.getZoomLevel(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToZoomLevel.set(n,t),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(t){return this.mapWindowIdToZoomFactor.get(this.getWindowId(t))??1}setZoomFactor(t,i){this.mapWindowIdToZoomFactor.set(this.getWindowId(i),t)}setFullscreen(t,i){if(this.isFullscreen(i)===t)return;let n=this.getWindowId(i);this.mapWindowIdToFullScreen.set(n,t),this._onDidChangeFullscreen.fire(n)}isFullscreen(t){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(t))}getWindowId(t){return t.vscodeWindowId}};Ub.INSTANCE=new Ub;p0=Ub;DF=p0.INSTANCE.onDidChangeZoomLevel;LF=p0.INSTANCE.onDidChangeFullscreen,Vl=typeof navigator=="object"?navigator.userAgent:"",Hb=Vl.indexOf("Firefox")>=0,np=Vl.indexOf("AppleWebKit")>=0,m0=Vl.indexOf("Chrome")>=0,YM=!m0&&Vl.indexOf("Safari")>=0,IF=Vl.indexOf("Electron/")>=0,BF=Vl.indexOf("Android")>=0,rp=!1;if(typeof Nn.matchMedia=="function"){let e=Nn.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=Nn.matchMedia("(display-mode: fullscreen)");rp=e.matches,q4(Nn,e,({matches:i})=>{rp&&t.matches||(rp=i)})}Gl="en",cp=!1,up=!1,Hu=!1,$4=!1,VM=!1,XM=!1,G4=!1,j4=!1,Y4=!1,V4=!1,sp=Gl,DA=Gl,bs=globalThis;typeof bs.vscode<"u"&&typeof bs.vscode.process<"u"?Tn=bs.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(Tn=process);ZM=typeof Tn?.versions?.electron=="string",Z4=ZM&&Tn?.type==="renderer";if(typeof Tn=="object"){cp=Tn.platform==="win32",up=Tn.platform==="darwin",Hu=Tn.platform==="linux",$4=Hu&&!!Tn.env.SNAP&&!!Tn.env.SNAP_REVISION,G4=ZM,Y4=!!Tn.env.CI||!!Tn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,Vf=Gl,sp=Gl;let e=Tn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);Vf=t.userLocale,DA=t.osLocale,sp=t.resolvedLanguage||Gl,X4=t.languagePack?.translationsConfigFile}catch{}VM=!0}else typeof navigator=="object"&&!Z4?(_s=navigator.userAgent,cp=_s.indexOf("Windows")>=0,up=_s.indexOf("Macintosh")>=0,j4=(_s.indexOf("Macintosh")>=0||_s.indexOf("iPad")>=0||_s.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,Hu=_s.indexOf("Linux")>=0,V4=_s?.indexOf("Mobi")>=0,XM=!0,sp=globalThis._VSCODE_NLS_LANGUAGE||Gl,Vf=navigator.language.toLowerCase(),DA=Vf):console.error("Unable to resolve platform.");cb=0;up?cb=1:cp?cb=3:Hu&&(cb=2);QM=cp,Hr=up,Q4=Hu,ub=VM,J4=XM&&typeof bs.importScripts=="function",zF=J4?bs.origin:void 0,Fr=_s,ha=sp;(e=>{function t(){return ha}e.value=t;function i(){return ha.length===2?ha==="en":ha.length>=3?ha[0]==="e"&&ha[1]==="n"&&ha[2]==="-":!1}e.isDefaultVariant=i;function n(){return ha==="en"}e.isDefault=n})(LA||(LA={}));e6=typeof bs.postMessage=="function"&&!bs.importScripts,t6=(()=>{if(e6){let e=[];bs.addEventListener("message",i=>{if(i.data&&i.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n{let n=++t;e.push({id:n,callback:i}),bs.postMessage({vscodeScheduleAsyncWork:n},"*")}}return e=>setTimeout(e)})(),i6=!!(Fr&&Fr.indexOf("Chrome")>=0),PF=!!(Fr&&Fr.indexOf("Firefox")>=0),UF=!!(!i6&&Fr&&Fr.indexOf("Safari")>=0),HF=!!(Fr&&Fr.indexOf("Edg/")>=0),FF=!!(Fr&&Fr.indexOf("Android")>=0),da=typeof navigator=="object"?navigator:{},qF={clipboard:{writeText:ub||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!(da&&da.clipboard&&da.clipboard.writeText),readText:ub||!!(da&&da.clipboard&&da.clipboard.readText)},keyboard:ub||W4()?0:da.keyboard||YM?1:2,touch:"ontouchstart"in Nn||da.maxTouchPoints>0,pointerEvents:Nn.PointerEvent&&("ontouchstart"in Nn||navigator.maxTouchPoints>0)},g0=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},hb=new g0,IA=new g0,BA=new g0,n6=new Array(230);(e=>{function t(o){return hb.keyCodeToStr(o)}e.toString=t;function i(o){return hb.strToKeyCode(o)}e.fromString=i;function n(o){return IA.keyCodeToStr(o)}e.toUserSettingsUS=n;function r(o){return BA.keyCodeToStr(o)}e.toUserSettingsGeneral=r;function s(o){return IA.strToKeyCode(o)||BA.strToKeyCode(o)}e.fromUserSettings=s;function a(o){if(o>=98&&o<=113)return null;switch(o){case 16:return"Up";case 18:return"Down";case 15:return"Left";case 17:return"Right"}return hb.keyCodeToStr(o)}e.toElectronAccelerator=a})(Fb||(Fb={}));r6=class JM{constructor(t,i,n,r,s){this.ctrlKey=t,this.shiftKey=i,this.altKey=n,this.metaKey=r,this.keyCode=s}equals(t){return t instanceof JM&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){let t=this.ctrlKey?"1":"0",i=this.shiftKey?"1":"0",n=this.altKey?"1":"0",r=this.metaKey?"1":"0";return`K${t}${i}${n}${r}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new s6([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},s6=class{constructor(e){if(e.length===0)throw _4("chords");this.chords=e}getHashCode(){let e="";for(let t=0,i=this.chords.length;t{function t(i){return i===e.None||i===e.Cancelled||i instanceof f6?!0:!i||typeof i!="object"?!1:typeof i.isCancellationRequested=="boolean"&&typeof i.onCancellationRequested=="function"}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:hi.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:eR})})(UA||(UA={}));f6=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?eR:(this._emitter||(this._emitter=new Z),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},_0=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e=="function"&&typeof t=="number"&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new Mb("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Mb("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},p6=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,i=globalThis){if(this.isDisposed)throw new Mb("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let n=i.setInterval(()=>{e()},t);this.disposable=_t(()=>{i.clearInterval(n),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?db=(e,t)=>{t6(()=>{if(i)return;let n=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining(){return Math.max(0,n-Date.now())}}))});let i=!1;return{dispose(){i||(i=!0)}}}:db=(e,t,i)=>{let n=e.requestIdleCallback(t,typeof i=="number"?{timeout:i}:void 0),r=!1;return{dispose(){r||(r=!0,e.cancelIdleCallback(n))}}},m6=e=>db(globalThis,e)})();(e=>{async function t(n){let r,s=await Promise.all(n.map(a=>a.then(o=>o,o=>{r||(r=o)})));if(typeof r<"u")throw r;return s}e.settled=t;function i(n){return new Promise(async(r,s)=>{try{await n(r,s)}catch(a){s(a)}})}e.withAsyncBody=i})(HA||(HA={}));FA=class Vn{static fromArray(t){return new Vn(i=>{i.emitMany(t)})}static fromPromise(t){return new Vn(async i=>{i.emitMany(await t)})}static fromPromises(t){return new Vn(async i=>{await Promise.all(t.map(async n=>i.emitOne(await n)))})}static merge(t){return new Vn(async i=>{await Promise.all(t.map(async n=>{for await(let r of n)i.emitOne(r)}))})}constructor(t,i){this._state=0,this._results=[],this._error=null,this._onReturn=i,this._onStateChanged=new Z,queueMicrotask(async()=>{let n={emitOne:r=>this.emitOne(r),emitMany:r=>this.emitMany(r),reject:r=>this.reject(r)};try{await Promise.resolve(t(n)),this.resolve()}catch(r){this.reject(r)}finally{n.emitOne=void 0,n.emitMany=void 0,n.reject=void 0}})}[Symbol.asyncIterator](){let t=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(t(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,i){return new Vn(async n=>{for await(let r of t)n.emitOne(i(r))})}map(t){return Vn.map(this,t)}static filter(t,i){return new Vn(async n=>{for await(let r of t)i(r)&&n.emitOne(r)})}filter(t){return Vn.filter(this,t)}static coalesce(t){return Vn.filter(t,i=>!!i)}coalesce(){return Vn.coalesce(this)}static async toPromise(t){let i=[];for await(let n of t)i.push(n);return i}toPromise(){return Vn.toPromise(this)}emitOne(t){this._state===0&&(this._results.push(t),this._onStateChanged.fire())}emitMany(t){this._state===0&&(this._results=this._results.concat(t),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(t){this._state===0&&(this._state=2,this._error=t,this._onStateChanged.fire())}};FA.EMPTY=FA.fromArray([]);x6=class iR{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(t){let i=t.length;if(i===0)return;let n=this._buff,r=this._buffLen,s=this._leftoverHighSurrogate,a,o;for(s!==0?(a=s,o=-1,s=0):(a=t.charCodeAt(0),o=0);;){let l=a;if(g6(a))if(o+1>>6,t[i++]=128|(n&63)>>>0):n<65536?(t[i++]=224|(n&61440)>>>12,t[i++]=128|(n&4032)>>>6,t[i++]=128|(n&63)>>>0):(t[i++]=240|(n&1835008)>>>18,t[i++]=128|(n&258048)>>>12,t[i++]=128|(n&4032)>>>6,t[i++]=128|(n&63)>>>0),i>=64&&(this._step(),i-=64,this._totalLen+=64,t[0]=t[64],t[1]=t[65],t[2]=t[66]),i}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),Tu(this._h0)+Tu(this._h1)+Tu(this._h2)+Tu(this._h3)+Tu(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,KA(this._buff,this._buffLen),this._buffLen>56&&(this._step(),KA(this._buff));let t=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(t/4294967296),!1),this._buffDV.setUint32(60,t%4294967296,!1),this._step()}_step(){let t=iR._bigBlock32,i=this._buffDV;for(let h=0;h<64;h+=4)t.setUint32(h,i.getUint32(h,!1),!1);for(let h=64;h<320;h+=4)t.setUint32(h,fb(t.getUint32(h-12,!1)^t.getUint32(h-32,!1)^t.getUint32(h-56,!1)^t.getUint32(h-64,!1),1),!1);let n=this._h0,r=this._h1,s=this._h2,a=this._h3,o=this._h4,l,c,u;for(let h=0;h<80;h++)h<20?(l=r&s|~r&a,c=1518500249):h<40?(l=r^s^a,c=1859775393):h<60?(l=r&s|r&a|s&a,c=2400959708):(l=r^s^a,c=3395469782),u=fb(n,5)+l+o+c+t.getUint32(h*4,!1)&4294967295,o=a,a=s,s=fb(r,30),r=n,n=u;this._h0=this._h0+n&4294967295,this._h1=this._h1+r&4294967295,this._h2=this._h2+s&4294967295,this._h3=this._h3+a&4294967295,this._h4=this._h4+o&4294967295}};x6._bigBlock32=new DataView(new ArrayBuffer(320));({registerWindow:KF,getWindow:ur,getDocument:WF,getWindows:$F,getWindowsCount:GF,getWindowId:WA,getWindowById:jF,hasWindow:YF,onDidRegisterWindow:E6,onWillUnregisterWindow:VF,onDidUnregisterWindow:XF}=(function(){let e=new Map,t={window:Nn,disposables:new _a};e.set(Nn.vscodeWindowId,t);let i=new Z,n=new Z,r=new Z;function s(a,o){return(typeof a=="number"?e.get(a):void 0)??(o?t:void 0)}return{onDidRegisterWindow:i.event,onWillUnregisterWindow:r.event,onDidUnregisterWindow:n.event,registerWindow(a){if(e.has(a.vscodeWindowId))return Oe.None;let o=new _a,l={window:a,disposables:o.add(new _a)};return e.set(a.vscodeWindowId,l),o.add(_t(()=>{e.delete(a.vscodeWindowId),n.fire(a)})),o.add(Se(a,oi.BEFORE_UNLOAD,()=>{r.fire(a)})),i.fire(l),o},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(a){return a.vscodeWindowId},hasWindow(a){return e.has(a)},getWindowById:s,getWindow(a){let o=a;if(o?.ownerDocument?.defaultView)return o.ownerDocument.defaultView.window;let l=a;return l?.view?l.view.window:Nn},getDocument(a){return ur(a).document}}})()),C6=class{constructor(e,t,i,n){this._node=e,this._type=t,this._handler=i,this._options=n||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,this._handler=null)}};$A=function(e,t,i,n){let r=i;return t==="click"||t==="mousedown"||t==="contextmenu"?r=k6(ur(e),i):(t==="keydown"||t==="keypress"||t==="keyup")&&(r=T6(i)),Se(e,t,r,n)},A6=class extends p6{constructor(e){super(),this.defaultTarget=e&&ur(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},pb=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){ep(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,i=new Map,n=new Map,r=s=>{i.set(s,!1);let a=e.get(s)??[];for(t.set(s,a),e.set(s,[]),n.set(s,!0);a.length>0;)a.sort(pb.sort),a.shift().execute();n.set(s,!1)};hp=(s,a,o=0)=>{let l=WA(s),c=new pb(a,o),u=e.get(l);return u||(u=[],e.set(l,u)),u.push(c),i.get(l)||(i.set(l,!0),s.requestAnimationFrame(()=>r(l))),c},N6=(s,a,o)=>{let l=WA(s);if(n.get(l)){let c=new pb(a,o),u=t.get(l);return u||(u=[],t.set(l,u)),u.push(c),c}else return hp(s,a,o)}})();GA=class ap{constructor(t,i){this.width=t,this.height=i}with(t=this.width,i=this.height){return t!==this.width||i!==this.height?new ap(t,i):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof ap?t:new ap(t.width,t.height)}static equals(t,i){return t===i?!0:!t||!i?!1:t.width===i.width&&t.height===i.height}};GA.None=new GA(0,0);ZF=new class{constructor(){this.mutationObservers=new Map}observe(e,t,i){let n=this.mutationObservers.get(e);n||(n=new Map,this.mutationObservers.set(e,n));let r=v6(i),s=n.get(r);if(s)s.users+=1;else{let a=new Z,o=new MutationObserver(c=>a.fire(c));o.observe(e,i);let l=s={users:1,observer:o,onDidMutate:a.event};t.add(_t(()=>{l.users-=1,l.users===0&&(a.dispose(),o.disconnect(),n?.delete(r),n?.size===0&&this.mutationObservers.delete(e))})),n.set(r,s)}return s.onDidMutate}},oi={CLICK:"click",AUXCLICK:"auxclick",DBLCLICK:"dblclick",MOUSE_UP:"mouseup",MOUSE_DOWN:"mousedown",MOUSE_OVER:"mouseover",MOUSE_MOVE:"mousemove",MOUSE_OUT:"mouseout",MOUSE_ENTER:"mouseenter",MOUSE_LEAVE:"mouseleave",MOUSE_WHEEL:"wheel",POINTER_UP:"pointerup",POINTER_DOWN:"pointerdown",POINTER_MOVE:"pointermove",POINTER_LEAVE:"pointerleave",CONTEXT_MENU:"contextmenu",WHEEL:"wheel",KEY_DOWN:"keydown",KEY_PRESS:"keypress",KEY_UP:"keyup",LOAD:"load",BEFORE_UNLOAD:"beforeunload",UNLOAD:"unload",PAGE_SHOW:"pageshow",PAGE_HIDE:"pagehide",PASTE:"paste",ABORT:"abort",ERROR:"error",RESIZE:"resize",SCROLL:"scroll",FULLSCREEN_CHANGE:"fullscreenchange",WK_FULLSCREEN_CHANGE:"webkitfullscreenchange",SELECT:"select",CHANGE:"change",SUBMIT:"submit",RESET:"reset",FOCUS:"focus",FOCUS_IN:"focusin",FOCUS_OUT:"focusout",BLUR:"blur",INPUT:"input",STORAGE:"storage",DRAG_START:"dragstart",DRAG:"drag",DRAG_ENTER:"dragenter",DRAG_LEAVE:"dragleave",DRAG_OVER:"dragover",DROP:"drop",DRAG_END:"dragend",ANIMATION_START:np?"webkitAnimationStart":"animationstart",ANIMATION_END:np?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:np?"webkitAnimationIteration":"animationiteration"},R6=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;O6.SVG=function(e,t,...i){return nR("http://www.w3.org/2000/svg",e,t,...i)};D6=class{constructor(e){this.domNode=e,this._maxWidth="",this._width="",this._height="",this._top="",this._left="",this._bottom="",this._right="",this._paddingTop="",this._paddingLeft="",this._paddingBottom="",this._paddingRight="",this._fontFamily="",this._fontWeight="",this._fontSize="",this._fontStyle="",this._fontFeatureSettings="",this._fontVariationSettings="",this._textDecoration="",this._lineHeight="",this._letterSpacing="",this._className="",this._display="",this._position="",this._visibility="",this._color="",this._backgroundColor="",this._layerHint=!1,this._contain="none",this._boxShadow=""}setMaxWidth(e){let t=cn(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=cn(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=cn(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=cn(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=cn(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=cn(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=cn(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=cn(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=cn(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=cn(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=cn(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=cn(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=cn(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=cn(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?"translate3d(0px, 0px, 0px)":"")}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};rR=class{constructor(){this._hooks=new _a,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let i=this._onStopCallback;this._onStopCallback=null,e&&i&&i(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,i,n,r){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=n,this._onStopCallback=r;let s=e;try{e.setPointerCapture(t),this._hooks.add(_t(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{s=ur(e)}this._hooks.add(Se(s,oi.POINTER_MOVE,a=>{if(a.buttons!==i){this.stopMonitoring(!0);return}a.preventDefault(),this._pointerMoveCallback(a)})),this._hooks.add(Se(s,oi.POINTER_UP,a=>this.stopMonitoring(!0)))}};(e=>(e.Tap="-xterm-gesturetap",e.Change="-xterm-gesturechange",e.Start="-xterm-gesturestart",e.End="-xterm-gesturesend",e.Contextmenu="-xterm-gesturecontextmenu"))(cr||(cr={}));Iu=class Li extends Oe{constructor(){super(),this.dispatched=!1,this.targets=new MA,this.ignoreTargets=new MA,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(hi.runAndSubscribe(E6,({window:t,disposables:i})=>{i.add(Se(t.document,"touchstart",n=>this.onTouchStart(n),{passive:!1})),i.add(Se(t.document,"touchend",n=>this.onTouchEnd(t,n))),i.add(Se(t.document,"touchmove",n=>this.onTouchMove(n),{passive:!1}))},{window:Nn,disposables:this._store}))}static addTarget(t){if(!Li.isTouchDevice())return Oe.None;Li.INSTANCE||(Li.INSTANCE=AA(new Li));let i=Li.INSTANCE.targets.push(t);return _t(i)}static ignoreTarget(t){if(!Li.isTouchDevice())return Oe.None;Li.INSTANCE||(Li.INSTANCE=AA(new Li));let i=Li.INSTANCE.ignoreTargets.push(t);return _t(i)}static isTouchDevice(){return"ontouchstart"in Nn||navigator.maxTouchPoints>0}dispose(){this.handle&&(this.handle.dispose(),this.handle=null),super.dispose()}onTouchStart(t){let i=Date.now();this.handle&&(this.handle.dispose(),this.handle=null);for(let n=0,r=t.targetTouches.length;n=Li.HOLD_DELAY&&Math.abs(l.initialPageX-Cn(l.rollingPageX))<30&&Math.abs(l.initialPageY-Cn(l.rollingPageY))<30){let u=this.newGestureEvent(cr.Contextmenu,l.initialTarget);u.pageX=Cn(l.rollingPageX),u.pageY=Cn(l.rollingPageY),this.dispatchEvent(u)}else if(r===1){let u=Cn(l.rollingPageX),h=Cn(l.rollingPageY),d=Cn(l.rollingTimestamps)-l.rollingTimestamps[0],f=u-l.rollingPageX[0],p=h-l.rollingPageY[0],_=[...this.targets].filter(S=>l.initialTarget instanceof Node&&S.contains(l.initialTarget));this.inertia(t,_,n,Math.abs(f)/d,f>0?1:-1,u,Math.abs(p)/d,p>0?1:-1,h)}this.dispatchEvent(this.newGestureEvent(cr.End,l.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&(i.preventDefault(),i.stopPropagation(),this.dispatched=!1)}newGestureEvent(t,i){let n=document.createEvent("CustomEvent");return n.initEvent(t,!1,!0),n.initialTarget=i,n.tapCount=0,n}dispatchEvent(t){if(t.type===cr.Tap){let i=new Date().getTime(),n=0;i-this._lastSetTapCountTime>Li.CLEAR_TAP_COUNT_TIME?n=1:n=2,this._lastSetTapCountTime=i,t.tapCount=n}else(t.type===cr.Change||t.type===cr.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let n of this.ignoreTargets)if(n.contains(t.initialTarget))return;let i=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,s=t.initialTarget;for(;s&&s!==n;)r++,s=s.parentElement;i.push([r,n])}i.sort((n,r)=>n[0]-r[0]);for(let[n,r]of i)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,i,n,r,s,a,o,l,c){this.handle=hp(t,()=>{let u=Date.now(),h=u-n,d=0,f=0,p=!0;r+=Li.SCROLL_FRICTION*h,o+=Li.SCROLL_FRICTION*h,r>0&&(p=!1,d=s*r*h),o>0&&(p=!1,f=l*o*h);let _=this.newGestureEvent(cr.Change);_.translationX=d,_.translationY=f,i.forEach(S=>S.dispatchEvent(_)),p||this.inertia(t,i,u,r,s,a+d,o,l,c+f)})}onTouchMove(t){let i=Date.now();for(let n=0,r=t.changedTouches.length;n3&&(a.rollingPageX.shift(),a.rollingPageY.shift(),a.rollingTimestamps.shift()),a.rollingPageX.push(s.pageX),a.rollingPageY.push(s.pageY),a.rollingTimestamps.push(i)}this.dispatched&&(t.preventDefault(),t.stopPropagation(),this.dispatched=!1)}};Iu.SCROLL_FRICTION=-.005,Iu.HOLD_DELAY=700,Iu.CLEAR_TAP_COUNT_TIME=400,Rt([L6],Iu,"isTouchDevice",1);I6=Iu,b0=class extends Oe{onclick(e,t){this._register(Se(e,oi.CLICK,i=>t(new Lu(ur(e),i))))}onmousedown(e,t){this._register(Se(e,oi.MOUSE_DOWN,i=>t(new Lu(ur(e),i))))}onmouseover(e,t){this._register(Se(e,oi.MOUSE_OVER,i=>t(new Lu(ur(e),i))))}onmouseleave(e,t){this._register(Se(e,oi.MOUSE_LEAVE,i=>t(new Lu(ur(e),i))))}onkeydown(e,t){this._register(Se(e,oi.KEY_DOWN,i=>t(new qb(i))))}onkeyup(e,t){this._register(Se(e,oi.KEY_UP,i=>t(new qb(i))))}oninput(e,t){this._register(Se(e,oi.INPUT,t))}onblur(e,t){this._register(Se(e,oi.BLUR,t))}onfocus(e,t){this._register(Se(e,oi.FOCUS,t))}onchange(e,t){this._register(Se(e,oi.CHANGE,t))}ignoreGesture(e){return I6.ignoreTarget(e)}},jA=11,B6=class extends b0{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement("div"),this.bgDomNode.className="arrow-background",this.bgDomNode.style.position="absolute",this.bgDomNode.style.width=e.bgWidth+"px",this.bgDomNode.style.height=e.bgHeight+"px",typeof e.top<"u"&&(this.bgDomNode.style.top="0px"),typeof e.left<"u"&&(this.bgDomNode.style.left="0px"),typeof e.bottom<"u"&&(this.bgDomNode.style.bottom="0px"),typeof e.right<"u"&&(this.bgDomNode.style.right="0px"),this.domNode=document.createElement("div"),this.domNode.className=e.className,this.domNode.style.position="absolute",this.domNode.style.width=jA+"px",this.domNode.style.height=jA+"px",typeof e.top<"u"&&(this.domNode.style.top=e.top+"px"),typeof e.left<"u"&&(this.domNode.style.left=e.left+"px"),typeof e.bottom<"u"&&(this.domNode.style.bottom=e.bottom+"px"),typeof e.right<"u"&&(this.domNode.style.right=e.right+"px"),this._pointerMoveMonitor=this._register(new rR),this._register($A(this.bgDomNode,oi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register($A(this.domNode,oi.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new A6),this._pointerdownScheduleRepeatTimer=this._register(new _0)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ur(e))};this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(t,200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,i=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault()}},z6=class Kb{constructor(t,i,n,r,s,a,o){this._forceIntegerValues=t,this._scrollStateBrand=void 0,this._forceIntegerValues&&(i=i|0,n=n|0,r=r|0,s=s|0,a=a|0,o=o|0),this.rawScrollLeft=r,this.rawScrollTop=o,i<0&&(i=0),r+i>n&&(r=n-i),r<0&&(r=0),s<0&&(s=0),o+s>a&&(o=a-s),o<0&&(o=0),this.width=i,this.scrollWidth=n,this.scrollLeft=r,this.height=s,this.scrollHeight=a,this.scrollTop=o}equals(t){return this.rawScrollLeft===t.rawScrollLeft&&this.rawScrollTop===t.rawScrollTop&&this.width===t.width&&this.scrollWidth===t.scrollWidth&&this.scrollLeft===t.scrollLeft&&this.height===t.height&&this.scrollHeight===t.scrollHeight&&this.scrollTop===t.scrollTop}withScrollDimensions(t,i){return new Kb(this._forceIntegerValues,typeof t.width<"u"?t.width:this.width,typeof t.scrollWidth<"u"?t.scrollWidth:this.scrollWidth,i?this.rawScrollLeft:this.scrollLeft,typeof t.height<"u"?t.height:this.height,typeof t.scrollHeight<"u"?t.scrollHeight:this.scrollHeight,i?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new Kb(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<"u"?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<"u"?t.scrollTop:this.rawScrollTop)}createScrollEvent(t,i){let n=this.width!==t.width,r=this.scrollWidth!==t.scrollWidth,s=this.scrollLeft!==t.scrollLeft,a=this.height!==t.height,o=this.scrollHeight!==t.scrollHeight,l=this.scrollTop!==t.scrollTop;return{inSmoothScrolling:i,oldWidth:t.width,oldScrollWidth:t.scrollWidth,oldScrollLeft:t.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:t.height,oldScrollHeight:t.scrollHeight,oldScrollTop:t.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:s,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:l}}},P6=class extends Oe{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new z6(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let i=this._state.withScrollDimensions(e,t);this._setState(i,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&(this._smoothScrolling.dispose(),this._smoothScrolling=null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>"u"?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>"u"?this._smoothScrolling.to.scrollTop:e.scrollTop};let i=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===i.scrollLeft&&this._smoothScrolling.to.scrollTop===i.scrollTop)return;let n;t?n=new VA(this._smoothScrolling.from,i,this._smoothScrolling.startTime,this._smoothScrolling.duration):n=this._smoothScrolling.combine(this._state,i,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=n}else{let i=this._state.withScrollPosition(e);this._smoothScrolling=VA.start(this._state,i,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),!!this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let i=this._state;i.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(i,t)))}},YA=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};VA=class Wb{constructor(t,i,n,r){this.from=t,this.to=i,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(t,i,n){if(Math.abs(t-i)>2.5*n){let r,s;return t{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?" fade":"")))}},K6=140,sR=class extends b0{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new q6(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new rR),this._shouldRender=!0,this.domNode=Fu(document.createElement("div")),this.domNode.setAttribute("role","presentation"),this.domNode.setAttribute("aria-hidden","true"),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition("absolute"),this._register(Se(this.domNode.domNode,oi.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new B6(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,n){this.slider=Fu(document.createElement("div")),this.slider.setClassName("slider"),this.slider.setPosition("absolute"),this.slider.setTop(e),this.slider.setLeft(t),typeof i=="number"&&this.slider.setWidth(i),typeof n=="number"&&this.slider.setHeight(n),this.slider.setLayerHinting(!0),this.slider.setContain("strict"),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Se(this.slider.domNode,oi.POINTER_DOWN,r=>{r.button===0&&(r.preventDefault(),this._sliderPointerDown(r))})),this.onclick(this.slider.domNode,r=>{r.leftButton&&r.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,i=t+this._scrollbarState.getSliderPosition(),n=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),r=this._sliderPointerPosition(e);i<=r&&r<=n?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,i;if(e.target===this.domNode.domNode&&typeof e.offsetX=="number"&&typeof e.offsetY=="number")t=e.offsetX,i=e.offsetY;else{let r=M6(this.domNode.domNode);t=e.pageX-r.left,i=e.pageY-r.top}let n=this._pointerDownRelativePosition(t,i);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(n):this._scrollbarState.getDesiredScrollPositionFromOffset(n)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),i=this._sliderOrthogonalPointerPosition(e),n=this._scrollbarState.clone();this.slider.toggleClassName("active",!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,r=>{let s=this._sliderOrthogonalPointerPosition(r),a=Math.abs(s-i);if(QM&&a>K6){this._setDesiredScrollPositionNow(n.getScrollPosition());return}let o=this._sliderPointerPosition(r)-t;this._setDesiredScrollPositionNow(n.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName("active",!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},aR=class $b{constructor(t,i,n,r,s,a){this._scrollbarSize=Math.round(i),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(t),this._visibleSize=r,this._scrollSize=s,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new $b(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(t){let i=Math.round(t);return this._visibleSize!==i?(this._visibleSize=i,this._refreshComputedValues(),!0):!1}setScrollSize(t){let i=Math.round(t);return this._scrollSize!==i?(this._scrollSize=i,this._refreshComputedValues(),!0):!1}setScrollPosition(t){let i=Math.round(t);return this._scrollPosition!==i?(this._scrollPosition=i,this._refreshComputedValues(),!0):!1}setScrollbarSize(t){this._scrollbarSize=Math.round(t)}setOppositeScrollbarSize(t){this._oppositeScrollbarSize=Math.round(t)}static _computeValues(t,i,n,r,s){let a=Math.max(0,n-t),o=Math.max(0,a-2*i),l=r>0&&r>n;if(!l)return{computedAvailableSize:Math.round(a),computedIsNeeded:l,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),u=(o-c)/(r-n),h=s*u;return{computedAvailableSize:Math.round(a),computedIsNeeded:l,computedSliderSize:Math.round(c),computedSliderRatio:u,computedSliderPosition:Math.round(h)}}_refreshComputedValues(){let t=$b._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize-this._computedSliderSize/2;return Math.round(i/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(t){if(!this._computedIsNeeded)return 0;let i=t-this._arrowSize,n=this._scrollPosition;return i0&&Math.abs(t.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(t.deltaX)||!this._isAlmostInt(t.deltaY))&&(n+=.25),i){let r=Math.abs(t.deltaX),s=Math.abs(t.deltaY),a=Math.abs(i.deltaX),o=Math.abs(i.deltaY),l=Math.max(Math.min(r,a),1),c=Math.max(Math.min(s,o),1),u=Math.max(r,a),h=Math.max(s,o);u%l===0&&h%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(t){return Math.abs(Math.round(t)-t)<.01}};Gb.INSTANCE=new Gb;Y6=Gb,V6=class extends b0{constructor(e,t,i){super(),this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Z),this.onWillScroll=this._onWillScroll.event,this._options=Z6(t),this._scrollable=i,this._register(this._scrollable.onScroll(r=>{this._onWillScroll.fire(r),this._onDidScroll(r),this._onScroll.fire(r)}));let n={onMouseWheel:r=>this._onMouseWheel(r),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new $6(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new W6(this._scrollable,this._options,n)),this._domNode=document.createElement("div"),this._domNode.className="xterm-scrollable-element "+this._options.className,this._domNode.setAttribute("role","presentation"),this._domNode.style.position="relative",this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Fu(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Fu(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Fu(document.createElement("div")),this._topLeftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,r=>this._onMouseOver(r)),this.onmouseleave(this._listenOnDomNode,r=>this._onMouseLeave(r)),this._hideTimeout=this._register(new _0),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=mo(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,Hr&&(this._options.className+=" mac"),this._domNode.className="xterm-scrollable-element "+this._options.className}updateOptions(e){typeof e.handleMouseWheel<"u"&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<"u"&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<"u"&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<"u"&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<"u"&&(this._options.horizontal=e.horizontal),typeof e.vertical<"u"&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<"u"&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<"u"&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<"u"&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new PA(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=mo(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new PA(i))};this._mouseWheelToDispose.push(Se(this._listenOnDomNode,oi.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Y6.INSTANCE;ZA&&t.acceptStandardWheelEvent(e);let i=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,s=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&s+r===0?s=r=0:Math.abs(r)>=Math.abs(s)?s=0:r=0),this._options.flipAxes&&([r,s]=[s,r]);let a=!Hr&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!s&&(s=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(s=s*this._options.fastScrollSensitivity,r=r*this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),l={};if(r){let c=XA*r,u=o.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(l,u)}if(s){let c=XA*s,u=o.scrollLeft-(c<0?Math.floor(c):Math.ceil(c));this._horizontalScrollbar.writeScrollPosition(l,u)}l=this._scrollable.validateScrollPosition(l),(o.scrollLeft!==l.scrollLeft||o.scrollTop!==l.scrollTop)&&(ZA&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(l):this._scrollable.setScrollPositionNow(l),i=!0)}let n=i;!n&&this._options.alwaysConsumeMouseWheel&&(n=!0),!n&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(n=!0),n&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw new Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,i=e.scrollLeft>0,n=i?" left":"",r=t?" top":"",s=i||t?" top-left-corner":"";this._leftShadowDomNode.setClassName(`shadow${n}`),this._topShadowDomNode.setClassName(`shadow${r}`),this._topLeftShadowDomNode.setClassName(`shadow${s}${r}${n}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),G6)}},X6=class extends V6{constructor(e,t,i){super(e,t,i)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};jb=class extends Oe{constructor(e,t,i,n,r,s,a,o){super(),this._bufferService=i,this._optionsService=a,this._renderService=o,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let l=this._register(new P6({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:c=>hp(n.window,c)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{l.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new X6(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},l)),this._register(this._optionsService.onMultipleOptionChange(["scrollSensitivity","fastScrollSensitivity","overviewRuler"],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(r.onProtocolChange(c=>{this._scrollableElement.updateOptions({handleMouseWheel:!(c&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(hi.runAndSubscribe(s.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=s.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(_t(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(_t(()=>this._styleElement.remove())),this._register(hi.runAndSubscribe(s.onChangeColors,()=>{this._styleElement.textContent=[".xterm .xterm-scrollable-element > .scrollbar > .slider {",` background: ${s.colors.scrollbarSliderBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider:hover {",` background: ${s.colors.scrollbarSliderHoverBackground.css};`,"}",".xterm .xterm-scrollable-element > .scrollbar > .slider.active {",` background: ${s.colors.scrollbarSliderActiveBackground.css};`,"}"].join(` +`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(c=>this._handleScroll(c)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),i=t-this._bufferService.buffer.ydisp;i!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(i)),this._isHandlingScroll=!1}};jb=Rt([re(2,ji),re(3,ys),re(4,LM),re(5,Yl),re(6,Yi),re(7,Ss)],jb);Yb=class extends Oe{constructor(e,t,i,n,r){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=i,this._decorationService=n,this._renderService=r,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(s=>this._removeDecoration(s))),this._register(_t(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",e?.options?.layer==="top"),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let i=e.options.x??0;return i&&i>this._bufferService.cols&&(t.style.display="none"),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose(()=>{this._decorationElements.delete(e),i.remove()})),i.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(i.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,i.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,i.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,i.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){if(!t)return;let i=e.options.x??0;(e.options.anchor||"left")==="right"?t.style.right=i?`${i*this._renderService.dimensions.css.cell.width}px`:"":t.style.left=i?`${i*this._renderService.dimensions.css.cell.width}px`:""}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};Yb=Rt([re(1,ji),re(2,ys),re(3,Vu),re(4,Ss)],Yb);Q6=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},Pr={full:0,left:0,center:0,right:0},fa={full:0,left:0,center:0,right:0},Nu={full:0,left:0,center:0,right:0},dp=class extends Oe{constructor(e,t,i,n,r,s,a,o){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=n,this._renderService=r,this._optionsService=s,this._themeService=a,this._coreBrowserService=o,this._colorZoneStore=new Q6,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(_t(()=>this._canvas?.remove()));let l=this._canvas.getContext("2d");if(l)this._ctx=l;else throw new Error("Ctx cannot be null");this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange("overviewRuler",()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);fa.full=this._canvas.width,fa.left=e,fa.center=t,fa.right=e,this._refreshDrawHeightConstants(),Nu.full=1,Nu.left=1,Nu.center=1+fa.left,Nu.right=1+fa.left+fa.center}_refreshDrawHeightConstants(){Pr.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);Pr.left=t,Pr.center=t,Pr.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Pr.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Pr.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Pr.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*Pr.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let t of this._decorationService.decorations)this._colorZoneStore.addDecoration(t);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!=="full"&&this._renderColorZone(t);for(let t of e)t.position==="full"&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(Nu[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-Pr[e.position||"full"]/2),fa[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+Pr[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};dp=Rt([re(2,ji),re(3,Vu),re(4,Ss),re(5,Yi),re(6,Yl),re(7,ys)],dp);(e=>(e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="\x07",e.BS="\b",e.HT=" ",e.LF=` +`,e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="\x1B",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL="\x7F"))(F||(F={}));(e=>(e.PAD="\x80",e.HOP="\x81",e.BPH="\x82",e.NBH="\x83",e.IND="\x84",e.NEL="\x85",e.SSA="\x86",e.ESA="\x87",e.HTS="\x88",e.HTJ="\x89",e.VTS="\x8A",e.PLD="\x8B",e.PLU="\x8C",e.RI="\x8D",e.SS2="\x8E",e.SS3="\x8F",e.DCS="\x90",e.PU1="\x91",e.PU2="\x92",e.STS="\x93",e.CCH="\x94",e.MW="\x95",e.SPA="\x96",e.EPA="\x97",e.SOS="\x98",e.SGCI="\x99",e.SCI="\x9A",e.CSI="\x9B",e.ST="\x9C",e.OSC="\x9D",e.PM="\x9E",e.APC="\x9F"))(qu||(qu={}));(e=>e.ST=`${F.ESC}\\`)(Vb||(Vb={}));Xb=class{constructor(e,t,i,n,r,s){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=n,this._coreService=r,this._renderService=s,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode===229?(this._handleAnyTextareaChanges(),!1):!0}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let i;t.start+=this._dataAlreadySent.length,this._isComposing?i=this._textarea.value.substring(t.start,this._compositionPosition.start):i=this._textarea.value.substring(t.start),i.length>0&&this._coreService.triggerDataEvent(i,!0)}},0)}else{this._isSendingComposition=!1;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0),0)}}};Xb=Rt([re(2,ji),re(3,Yi),re(4,_o),re(5,Ss)],Xb);li=0,ci=0,ui=0,Mt=0,QA={css:"#00000000",rgba:0};(e=>{function t(r,s,a,o){return o!==void 0?`#${co(r)}${co(s)}${co(a)}${co(o)}`:`#${co(r)}${co(s)}${co(a)}`}e.toCss=t;function i(r,s,a,o=255){return(r<<24|s<<16|a<<8|o)>>>0}e.toRgba=i;function n(r,s,a,o){return{css:e.toCss(r,s,a,o),rgba:e.toRgba(r,s,a,o)}}e.toColor=n})(It||(It={}));(e=>{function t(l,c){if(Mt=(c.rgba&255)/255,Mt===1)return{css:c.css,rgba:c.rgba};let u=c.rgba>>24&255,h=c.rgba>>16&255,d=c.rgba>>8&255,f=l.rgba>>24&255,p=l.rgba>>16&255,_=l.rgba>>8&255;li=f+Math.round((u-f)*Mt),ci=p+Math.round((h-p)*Mt),ui=_+Math.round((d-_)*Mt);let S=It.toCss(li,ci,ui),m=It.toRgba(li,ci,ui);return{css:S,rgba:m}}e.blend=t;function i(l){return(l.rgba&255)===255}e.isOpaque=i;function n(l,c,u){let h=Ku.ensureContrastRatio(l.rgba,c.rgba,u);if(h)return It.toColor(h>>24&255,h>>16&255,h>>8&255)}e.ensureContrastRatio=n;function r(l){let c=(l.rgba|255)>>>0;return[li,ci,ui]=Ku.toChannels(c),{css:It.toCss(li,ci,ui),rgba:c}}e.opaque=r;function s(l,c){return Mt=Math.round(c*255),[li,ci,ui]=Ku.toChannels(l.rgba),{css:It.toCss(li,ci,ui,Mt),rgba:It.toRgba(li,ci,ui,Mt)}}e.opacity=s;function a(l,c){return Mt=l.rgba&255,s(l,Mt*c/255)}e.multiplyOpacity=a;function o(l){return[l.rgba>>24&255,l.rgba>>16&255,l.rgba>>8&255]}e.toColorRGB=o})(gt||(gt={}));(e=>{let t,i;try{let r=document.createElement("canvas");r.width=1,r.height=1;let s=r.getContext("2d",{willReadFrequently:!0});s&&(t=s,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}catch{}function n(r){if(r.match(/#[\da-f]{3,8}/i))switch(r.length){case 4:return li=parseInt(r.slice(1,2).repeat(2),16),ci=parseInt(r.slice(2,3).repeat(2),16),ui=parseInt(r.slice(3,4).repeat(2),16),It.toColor(li,ci,ui);case 5:return li=parseInt(r.slice(1,2).repeat(2),16),ci=parseInt(r.slice(2,3).repeat(2),16),ui=parseInt(r.slice(3,4).repeat(2),16),Mt=parseInt(r.slice(4,5).repeat(2),16),It.toColor(li,ci,ui,Mt);case 7:return{css:r,rgba:(parseInt(r.slice(1),16)<<8|255)>>>0};case 9:return{css:r,rgba:parseInt(r.slice(1),16)>>>0}}let s=r.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(s)return li=parseInt(s[1]),ci=parseInt(s[2]),ui=parseInt(s[3]),Mt=Math.round((s[5]===void 0?1:parseFloat(s[5]))*255),It.toColor(li,ci,ui,Mt);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=r,typeof t.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[li,ci,ui,Mt]=t.getImageData(0,0,1,1).data,Mt!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:It.toRgba(li,ci,ui,Mt),css:r}}e.toColor=n})(xt||(xt={}));(e=>{function t(n){return i(n>>16&255,n>>8&255,n&255)}e.relativeLuminance=t;function i(n,r,s){let a=n/255,o=r/255,l=s/255,c=a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4),u=o<=.03928?o/12.92:Math.pow((o+.055)/1.055,2.4),h=l<=.03928?l/12.92:Math.pow((l+.055)/1.055,2.4);return c*.2126+u*.7152+h*.0722}e.relativeLuminance2=i})(Ii||(Ii={}));(e=>{function t(a,o){if(Mt=(o&255)/255,Mt===1)return o;let l=o>>24&255,c=o>>16&255,u=o>>8&255,h=a>>24&255,d=a>>16&255,f=a>>8&255;return li=h+Math.round((l-h)*Mt),ci=d+Math.round((c-d)*Mt),ui=f+Math.round((u-f)*Mt),It.toRgba(li,ci,ui)}e.blend=t;function i(a,o,l){let c=Ii.relativeLuminance(a>>8),u=Ii.relativeLuminance(o>>8);if(gs(c,u)>8));if(p>8));return p>S?f:_}return f}let h=r(a,o,l),d=gs(c,Ii.relativeLuminance(h>>8));if(d>8));return d>p?h:f}return h}}e.ensureContrastRatio=i;function n(a,o,l){let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=o>>24&255,f=o>>16&255,p=o>>8&255,_=gs(Ii.relativeLuminance2(d,f,p),Ii.relativeLuminance2(c,u,h));for(;_0||f>0||p>0);)d-=Math.max(0,Math.ceil(d*.1)),f-=Math.max(0,Math.ceil(f*.1)),p-=Math.max(0,Math.ceil(p*.1)),_=gs(Ii.relativeLuminance2(d,f,p),Ii.relativeLuminance2(c,u,h));return(d<<24|f<<16|p<<8|255)>>>0}e.reduceLuminance=n;function r(a,o,l){let c=a>>24&255,u=a>>16&255,h=a>>8&255,d=o>>24&255,f=o>>16&255,p=o>>8&255,_=gs(Ii.relativeLuminance2(d,f,p),Ii.relativeLuminance2(c,u,h));for(;_>>0}e.increaseLuminance=r;function s(a){return[a>>24&255,a>>16&255,a>>8&255,a&255]}e.toChannels=s})(Ku||(Ku={}));J6=class extends Yu{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},fp=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Zn}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t1){let u=this._getJoinedRanges(n,a,s,t,r);for(let h=0;h1){let c=this._getJoinedRanges(n,a,s,t,r);for(let u=0;u=L,N=B,R=this._workCell;if(d.length>0&&B===d[0][0]&&C){let me=d.shift(),un=this._isCellInSelection(me[0],t);for(g=me[0]+1;g=me[1]),C?(z=!0,R=new J6(this._workCell,e.translateToString(!0,me[0],me[1]),me[1]-me[0]),N=me[1]-1,x=R.getWidth()):L=me[1]}let W=this._isCellInSelection(B,t),X=i&&B===s,U=I&&B>=c&&B<=u,Q=!1;this._decorationService.forEachDecorationAtCell(B,t,void 0,me=>{Q=!0});let Ee=R.getChars()||ga;if(Ee===" "&&(R.isUnderline()||R.isOverline())&&(Ee="\xA0"),D=x*o-l.get(Ee,R.isBold(),R.isItalic()),!_)_=this._document.createElement("span");else if(S&&(W&&k||!W&&!k&&R.bg===b)&&(W&&k&&f.selectionForeground||R.fg===w)&&R.extended.ext===E&&U===A&&D===O&&!X&&!z&&!Q&&C){R.isInvisible()?m+=ga:m+=Ee,S++;continue}else S&&(_.textContent=m),_=this._document.createElement("span"),S=0,m="";if(b=R.bg,w=R.fg,E=R.extended.ext,A=U,O=D,k=W,z&&s>=B&&s<=N&&(s=B),!this._coreService.isCursorHidden&&X&&this._coreService.isCursorInitialized){if(P.push("xterm-cursor"),this._coreBrowserService.isFocused)a&&P.push("xterm-cursor-blink"),P.push(n==="bar"?"xterm-cursor-bar":n==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":P.push("xterm-cursor-outline");break;case"block":P.push("xterm-cursor-block");break;case"bar":P.push("xterm-cursor-bar");break;case"underline":P.push("xterm-cursor-underline");break;default:break}}if(R.isBold()&&P.push("xterm-bold"),R.isItalic()&&P.push("xterm-italic"),R.isDim()&&P.push("xterm-dim"),R.isInvisible()?m=ga:m=R.getChars()||ga,R.isUnderline()&&(P.push(`xterm-underline-${R.extended.underlineStyle}`),m===" "&&(m="\xA0"),!R.isUnderlineColorDefault()))if(R.isUnderlineColorRGB())_.style.textDecorationColor=`rgb(${Yu.toColorRGB(R.getUnderlineColor()).join(",")})`;else{let me=R.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&R.isBold()&&me<8&&(me+=8),_.style.textDecorationColor=f.ansi[me].css}R.isOverline()&&(P.push("xterm-overline"),m===" "&&(m="\xA0")),R.isStrikethrough()&&P.push("xterm-strikethrough"),U&&(_.style.textDecoration="underline");let he=R.getFgColor(),Ke=R.getFgColorMode(),J=R.getBgColor(),je=R.getBgColorMode(),Ai=!!R.isInverse();if(Ai){let me=he;he=J,J=me;let un=Ke;Ke=je,je=un}let $t,mi,gi=!1;this._decorationService.forEachDecorationAtCell(B,t,void 0,me=>{me.options.layer!=="top"&&gi||(me.backgroundColorRGB&&(je=50331648,J=me.backgroundColorRGB.rgba>>8&16777215,$t=me.backgroundColorRGB),me.foregroundColorRGB&&(Ke=50331648,he=me.foregroundColorRGB.rgba>>8&16777215,mi=me.foregroundColorRGB),gi=me.options.layer==="top")}),!gi&&W&&($t=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,J=$t.rgba>>8&16777215,je=50331648,gi=!0,f.selectionForeground&&(Ke=50331648,he=f.selectionForeground.rgba>>8&16777215,mi=f.selectionForeground)),gi&&P.push("xterm-decoration-top");let Bt;switch(je){case 16777216:case 33554432:Bt=f.ansi[J],P.push(`xterm-bg-${J}`);break;case 50331648:Bt=It.toColor(J>>16,J>>8&255,J&255),this._addStyle(_,`background-color:#${JA((J>>>0).toString(16),"0",6)}`);break;default:Ai?(Bt=f.foreground,P.push("xterm-bg-257")):Bt=f.background}switch($t||R.isDim()&&($t=gt.multiplyOpacity(Bt,.5)),Ke){case 16777216:case 33554432:R.isBold()&&he<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(he+=8),this._applyMinimumContrast(_,Bt,f.ansi[he],R,$t,void 0)||P.push(`xterm-fg-${he}`);break;case 50331648:let me=It.toColor(he>>16&255,he>>8&255,he&255);this._applyMinimumContrast(_,Bt,me,R,$t,mi)||this._addStyle(_,`color:#${JA(he.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(_,Bt,f.foreground,R,$t,mi)||Ai&&P.push("xterm-fg-257")}P.length&&(_.className=P.join(" "),P.length=0),!X&&!z&&!Q&&C?S++:_.textContent=m,D!==this.defaultSpacing&&(_.style.letterSpacing=`${D}px`),h.push(_),B=N}return _&&S&&(_.textContent=m),h}_applyMinimumContrast(e,t,i,n,r,s){if(this._optionsService.rawOptions.minimumContrastRatio===1||iP(n.getCode()))return!1;let a=this._getContrastCache(n),o;if(!r&&!s&&(o=a.getColor(t.rgba,i.rgba)),o===void 0){let l=this._optionsService.rawOptions.minimumContrastRatio/(n.isDim()?2:1);o=gt.ensureContrastRatio(r||t,s||i,l),a.setColor((r||t).rgba,(s||i).rgba,o??null)}return o?(this._addStyle(e,`color:${o.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){let i=this._selectionStart,n=this._selectionEnd;return!i||!n?!1:this._columnSelectMode?i[0]<=n[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=n[0]&&t<=n[1]:t>i[1]&&t=i[0]&&e=i[0]}};Zb=Rt([re(1,zM),re(2,Yi),re(3,ys),re(4,_o),re(5,Vu),re(6,Yl)],Zb);rP=class{constructor(e,t){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";let i=e.createElement("span");i.classList.add("xterm-char-measure-element");let n=e.createElement("span");n.classList.add("xterm-char-measure-element"),n.style.fontWeight="bold";let r=e.createElement("span");r.classList.add("xterm-char-measure-element"),r.style.fontStyle="italic";let s=e.createElement("span");s.classList.add("xterm-char-measure-element"),s.style.fontWeight="bold",s.style.fontStyle="italic",this._measureElements=[i,n,r,s],this._container.appendChild(i),this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(s),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,n){e===this._font&&t===this._fontSize&&i===this._weight&&n===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=n,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${n}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${n}`,this.clear())}get(e,t,i){let n=0;if(!t&&!i&&e.length===1&&(n=e.charCodeAt(0))<256){if(this._flat[n]!==-9999)return this._flat[n];let a=this._measure(e,0);return a>0&&(this._flat[n]=a),a}let r=e;t&&(r+="B"),i&&(r+="I");let s=this._holey.get(r);if(s===void 0){let a=0;t&&(a|=1),i&&(a|=2),s=this._measure(e,a),s>0&&this._holey.set(r,s)}return s}_measure(e,t){let i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}},sP=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,i,n=!1){if(this.selectionStart=t,this.selectionEnd=i,!t||!i||t[0]===i[0]&&t[1]===i[1]){this.clear();return}let r=e.buffers.active.ydisp,s=t[1]-r,a=i[1]-r,o=Math.max(s,0),l=Math.min(a,e.rows-1);if(o>=e.rows||l<0){this.clear();return}this.hasSelection=!0,this.columnSelectMode=n,this.viewportStartRow=s,this.viewportEndRow=a,this.viewportCappedStartRow=o,this.viewportCappedEndRow=l,this.startCol=t[0],this.endCol=i[0]}isCellSelected(e,t,i){return this.hasSelection?(i-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&i>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&i<=this.viewportCappedEndRow:i>this.viewportStartRow&&i=this.startCol&&t=this.startCol):!1}};gb="xterm-dom-renderer-owner-",Yn="xterm-rows",Zf="xterm-fg-",eM="xterm-bg-",Au="xterm-focus",Qf="xterm-selection",oP=1,Qb=class extends Oe{constructor(e,t,i,n,r,s,a,o,l,c,u,h,d,f){super(),this._terminal=e,this._document=t,this._element=i,this._screenElement=n,this._viewportElement=r,this._helperContainer=s,this._linkifier2=a,this._charSizeService=l,this._optionsService=c,this._bufferService=u,this._coreService=h,this._coreBrowserService=d,this._themeService=f,this._terminalClass=oP++,this._rowElements=[],this._selectionRenderModel=aP(),this.onRequestRedraw=this._register(new Z).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Yn),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(Qf),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=nP(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(p=>this._injectCss(p))),this._injectCss(this._themeService.colors),this._rowFactory=o.createInstance(Zb,document),this._element.classList.add(gb+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(p=>this._handleLinkHover(p))),this._register(this._linkifier2.onHideLinkUnderline(p=>this._handleLinkLeave(p))),this._register(_t(()=>{this._element.classList.remove(gb+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new rP(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let i of this._rowElements)i.style.width=`${this.dimensions.css.canvas.width}px`,i.style.height=`${this.dimensions.css.cell.height}px`,i.style.lineHeight=`${this.dimensions.css.cell.height}px`,i.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${Yn} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${Yn} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${Yn} .xterm-dim { color: ${gt.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let i=`blink_underline_${this._terminalClass}`,n=`blink_bar_${this._terminalClass}`,r=`blink_block_${this._terminalClass}`;t+=`@keyframes ${i} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${n} { 50% { box-shadow: none; }}`,t+=`@keyframes ${r} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${Yn}.${Au} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Yn}.${Au} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Yn}.${Au} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${Yn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Yn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Yn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Yn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Yn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${Qf} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${Qf} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${Qf} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[s,a]of e.ansi.entries())t+=`${this._terminalSelector} .${Zf}${s} { color: ${a.css}; }${this._terminalSelector} .${Zf}${s}.xterm-dim { color: ${gt.multiplyOpacity(a,.5).css}; }${this._terminalSelector} .${eM}${s} { background-color: ${a.css}; }`;t+=`${this._terminalSelector} .${Zf}257 { color: ${gt.opaque(e.background).css}; }${this._terminalSelector} .${Zf}257.xterm-dim { color: ${gt.multiplyOpacity(gt.opaque(e.background),.5).css}; }${this._terminalSelector} .${eM}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let i=this._rowElements.length;i<=t;i++){let n=this._document.createElement("div");this._rowContainer.appendChild(n),this._rowElements.push(n)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(Au),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(Au),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,i),!this._selectionRenderModel.hasSelection))return;let n=this._selectionRenderModel.viewportStartRow,r=this._selectionRenderModel.viewportEndRow,s=this._selectionRenderModel.viewportCappedStartRow,a=this._selectionRenderModel.viewportCappedEndRow,o=this._document.createDocumentFragment();if(i){let l=e[0]>t[0];o.appendChild(this._createSelectionElement(s,l?t[0]:e[0],l?e[0]:t[0],a-s+1))}else{let l=n===s?e[0]:0,c=s===r?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(s,l,c));let u=a-s-1;if(o.appendChild(this._createSelectionElement(s+1,0,this._bufferService.cols,u)),s!==a){let h=r===a?t[0]:this._bufferService.cols;o.appendChild(this._createSelectionElement(a,0,h))}}this._selectionContainer.appendChild(o)}_createSelectionElement(e,t,i,n=1){let r=this._document.createElement("div"),s=t*this.dimensions.css.cell.width,a=this.dimensions.css.cell.width*(i-t);return s+a>this.dimensions.css.canvas.width&&(a=this.dimensions.css.canvas.width-s),r.style.height=`${n*this.dimensions.css.cell.height}px`,r.style.top=`${e*this.dimensions.css.cell.height}px`,r.style.left=`${s}px`,r.style.width=`${a}px`,r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let i=this._bufferService.buffer,n=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),s=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,a=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,o=this._optionsService.rawOptions.cursorInactiveStyle;for(let l=e;l<=t;l++){let c=l+i.ydisp,u=this._rowElements[l],h=i.lines.get(c);if(!u||!h)break;u.replaceChildren(...this._rowFactory.createRow(h,c,c===n,a,o,r,s,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${gb}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,n,r,s){i<0&&(e=0),n<0&&(t=0);let a=this._bufferService.rows-1;i=Math.max(Math.min(i,a),0),n=Math.max(Math.min(n,a),0),r=Math.min(r,this._bufferService.cols);let o=this._bufferService.buffer,l=o.ybase+o.y,c=Math.min(o.x,r-1),u=this._optionsService.rawOptions.cursorBlink,h=this._optionsService.rawOptions.cursorStyle,d=this._optionsService.rawOptions.cursorInactiveStyle;for(let f=i;f<=n;++f){let p=f+o.ydisp,_=this._rowElements[f],S=o.lines.get(p);if(!_||!S)break;_.replaceChildren(...this._rowFactory.createRow(S,p,p===l,h,d,c,u,this.dimensions.css.cell.width,this._widthCache,s?f===i?e:0:-1,s?(f===n?t:r)-1:-1))}}};Qb=Rt([re(7,d0),re(8,vp),re(9,Yi),re(10,ji),re(11,_o),re(12,ys),re(13,Yl)],Qb);Jb=class extends Oe{constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Z),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new cP(this._optionsService))}catch{this._measureStrategy=this._register(new lP(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};Jb=Rt([re(2,Yi)],Jb);oR=class extends Oe{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},lP=class extends oR{constructor(e,t,i){super(),this._document=e,this._parentElement=t,this._optionsService=i,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},cP=class extends oR{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");let t=this._ctx.measureText("W");if(!("width"in t&&"fontBoundingBoxAscent"in t&&"fontBoundingBoxDescent"in t))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText("W");return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},uP=class extends Oe{constructor(e,t,i){super(),this._textarea=e,this._window=t,this.mainDocument=i,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new hP(this._window)),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Z),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(n=>this._screenDprMonitor.setWindow(n))),this._register(hi.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Se(this._textarea,"focus",()=>this._isFocused=!0)),this._register(Se(this._textarea,"blur",()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},hP=class extends Oe{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new jl),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(_t(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Se(this._parentWindow,"resize",()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},dP=class extends Oe{constructor(){super(),this.linkProviders=[],this._register(_t(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};e0=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,n,r){return fP(window,e,t,i,n,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){let i=y0(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};e0=Rt([re(0,Ss),re(1,vp)],e0);pP=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh())),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=e!==void 0?e:0,t=t!==void 0?t:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,e):e,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,t):t,!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},lR={};e4(lR,{getSafariVersion:()=>gP,isChromeOS:()=>dR,isFirefox:()=>cR,isIpad:()=>_P,isIphone:()=>vP,isLegacyEdge:()=>mP,isLinux:()=>S0,isMac:()=>pp,isNode:()=>Sp,isSafari:()=>uR,isWindows:()=>hR});Sp=typeof process<"u"&&"title"in process,Xu=Sp?"node":navigator.userAgent,Zu=Sp?"node":navigator.platform,cR=Xu.includes("Firefox"),mP=Xu.includes("Edge"),uR=/^((?!chrome|android).)*safari/i.test(Xu);pp=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Zu),_P=Zu==="iPad",vP=Zu==="iPhone",hR=["Windows","Win16","Win32","WinCE"].includes(Zu),S0=Zu.indexOf("Linux")>=0,dR=/\bCrOS\b/.test(Xu),fR=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ir){n-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(n-t))}ms`),this._start();return}n=r}this.clear()}},bP=class extends fR{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},yP=class extends fR{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},mp=!Sp&&"requestIdleCallback"in window?yP:bP,SP=class{constructor(){this._queue=new mp}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},t0=class extends Oe{constructor(e,t,i,n,r,s,a,o,l){super(),this._rowCount=e,this._optionsService=i,this._charSizeService=n,this._coreService=r,this._coreBrowserService=o,this._renderer=this._register(new jl),this._pausedResizeTask=new SP,this._observerDisposable=this._register(new jl),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Z),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Z),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Z),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new pP((c,u)=>this._renderRows(c,u),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new wP(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(_t(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(a.onResize(()=>this._fullRefresh())),this._register(a.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(s.onDecorationRegistered(()=>this._fullRefresh())),this._register(s.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],()=>{this.clear(),this.handleResize(a.cols,a.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(a.buffer.y,a.buffer.y,!0))),this._register(l.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(c=>this._registerIntersectionObserver(c,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if("IntersectionObserver"in e){let i=new e.IntersectionObserver(n=>this._handleIntersectionChange(n[n.length-1]),{threshold:0});i.observe(t),this._observerDisposable.value=_t(()=>i.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let n=this._syncOutputHandler.flush();n&&(e=Math.min(e,n.start),t=Math.max(t,n.end)),i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(t=>this.refreshRows(t.start,t.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,i){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,this._renderer.value?.handleSelectionChanged(e,t,i)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};t0=Rt([re(2,Yi),re(3,vp),re(4,_o),re(5,Vu),re(6,ji),re(7,ys),re(8,Yl)],t0);wP=class{constructor(e,t,i){this._coreBrowserService=e,this._coreService=t,this._onTimeout=i,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};MP=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};_b=50,RP=15,OP=50,DP=500,LP="\xA0",IP=new RegExp(LP,"g"),i0=class extends Oe{constructor(e,t,i,n,r,s,a,o,l){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=n,this._coreService=r,this._mouseService=s,this._optionsService=a,this._renderService=o,this._coreBrowserService=l,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Zn,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Z),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Z),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=c=>this._handleMouseMove(c),this._mouseUpListener=c=>this._handleMouseUp(c),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(c=>this._handleTrim(c)),this._register(this._bufferService.buffers.onBufferActivate(c=>this._handleBufferActivate(c))),this.enable(),this._model=new MP(this._bufferService),this._activeSelectionMode=0,this._register(_t(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(c=>{c.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";let i=this._bufferService.buffer,n=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return"";let r=e[0]r.replace(IP," ")).join(hR?`\r `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),zb&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n||!t?!1:this._areCoordsInSelection(t,i,n)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n?!1:this._areCoordsInSelection([e,t],i,n)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=sA(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=Ib(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-Dv),Dv),t/=Dv,t/Math.abs(t)+Math.round(t*(d6-1)))}shouldForceSelection(e){return Hf?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),f6)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Hf&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let n=0;t>=n;n++){let s=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:s>1&&t!==n&&(i+=s-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let s=this._bufferService.buffer,r=s.lines.get(e[1]);if(!r)return;let a=s.translateBufferLineToString(e[1],!1),o=this._convertViewportColToCharacterIndex(r,e[0]),l=o,c=e[0]-o,u=0,h=0,d=0,f=0;if(a.charAt(o)===" "){for(;o>0&&a.charAt(o-1)===" ";)o--;for(;l1&&(f+=m-1,l+=m-1);w>0&&o>0&&!this._isCharWordSeparator(r.loadCell(w-1,this._workCell));){r.loadCell(w-1,this._workCell);let v=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,w--):v>1&&(d+=v-1,o-=v-1),o--,w--}for(;g1&&(f+=v-1,l+=v-1),l++,g++}}l++;let p=o+c-u+d,_=Math.min(this._bufferService.cols,l-o+u+h-d-f);if(!(!t&&a.slice(o,l).trim()==="")){if(i&&p===0&&r.getCodePoint(0)!==32){let w=s.lines.get(e[1]-1);if(w&&r.isWrapped&&w.getCodePoint(this._bufferService.cols-1)!==32){let g=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(g){let m=this._bufferService.cols-g.start;p-=m,_+=m}}}if(n&&p+_===this._bufferService.cols&&r.getCodePoint(this._bufferService.cols-1)!==32){let w=s.lines.get(e[1]+1);if(w?.isWrapped&&w.getCodePoint(0)!==32){let g=this._getWordAt([0,e[1]+1],!1,!1,!0);g&&(_+=g.length)}}return{start:p,length:_}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=sA(i,this._bufferService.cols)}};vb=kt([se(3,Ui),se(4,no),se(5,Ab),se(6,Hi),se(7,lr),se(8,or)],vb);rA=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},aA=class{constructor(){this._color=new rA,this._css=new rA}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Kt=Object.freeze((()=>{let e=[vt.toColor("#2e3436"),vt.toColor("#cc0000"),vt.toColor("#4e9a06"),vt.toColor("#c4a000"),vt.toColor("#3465a4"),vt.toColor("#75507b"),vt.toColor("#06989a"),vt.toColor("#d3d7cf"),vt.toColor("#555753"),vt.toColor("#ef2929"),vt.toColor("#8ae234"),vt.toColor("#fce94f"),vt.toColor("#729fcf"),vt.toColor("#ad7fa8"),vt.toColor("#34e2e2"),vt.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let n=t[i/36%6|0],s=t[i/6%6|0],r=t[i%6];e.push({css:Rt.toCss(n,s,r),rgba:Rt.toRgba(n,s,r)})}for(let i=0;i<24;i++){let n=8+i*10;e.push({css:Rt.toCss(n,n,n),rgba:Rt.toRgba(n,n,n)})}return e})()),Za=vt.toColor("#ffffff"),_u=vt.toColor("#000000"),oA=vt.toColor("#ffffff"),lA=_u,hu={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},_6=Za,bb=class extends Ae{constructor(e){super(),this._optionsService=e,this._contrastCache=new aA,this._halfContrastCache=new aA,this._onChangeColors=this._register(new Q),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Za,background:_u,cursor:oA,cursorAccent:lA,selectionForeground:void 0,selectionBackgroundTransparent:hu,selectionBackgroundOpaque:ht.blend(_u,hu),selectionInactiveBackgroundTransparent:hu,selectionInactiveBackgroundOpaque:ht.blend(_u,hu),scrollbarSliderBackground:ht.opacity(Za,.2),scrollbarSliderHoverBackground:ht.opacity(Za,.4),scrollbarSliderActiveBackground:ht.opacity(Za,.5),overviewRulerBorder:Za,ansi:Kt.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=tt(e.foreground,Za),t.background=tt(e.background,_u),t.cursor=ht.blend(t.background,tt(e.cursor,oA)),t.cursorAccent=ht.blend(t.background,tt(e.cursorAccent,lA)),t.selectionBackgroundTransparent=tt(e.selectionBackground,hu),t.selectionBackgroundOpaque=ht.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=tt(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=ht.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?tt(e.selectionForeground,tA):void 0,t.selectionForeground===tA&&(t.selectionForeground=void 0),ht.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=ht.opacity(t.selectionBackgroundTransparent,.3)),ht.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=ht.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=tt(e.scrollbarSliderBackground,ht.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=tt(e.scrollbarSliderHoverBackground,ht.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=tt(e.scrollbarSliderActiveBackground,ht.opacity(t.foreground,.5)),t.overviewRulerBorder=tt(e.overviewRulerBorder,_6),t.ansi=Kt.slice(),t.ansi[0]=tt(e.black,Kt[0]),t.ansi[1]=tt(e.red,Kt[1]),t.ansi[2]=tt(e.green,Kt[2]),t.ansi[3]=tt(e.yellow,Kt[3]),t.ansi[4]=tt(e.blue,Kt[4]),t.ansi[5]=tt(e.magenta,Kt[5]),t.ansi[6]=tt(e.cyan,Kt[6]),t.ansi[7]=tt(e.white,Kt[7]),t.ansi[8]=tt(e.brightBlack,Kt[8]),t.ansi[9]=tt(e.brightRed,Kt[9]),t.ansi[10]=tt(e.brightGreen,Kt[10]),t.ansi[11]=tt(e.brightYellow,Kt[11]),t.ansi[12]=tt(e.brightBlue,Kt[12]),t.ansi[13]=tt(e.brightMagenta,Kt[13]),t.ansi[14]=tt(e.brightCyan,Kt[14]),t.ansi[15]=tt(e.brightWhite,Kt[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let n=0;nr.index-a.index),n=[];for(let r of i){let a=this._services.get(r.id);if(!a)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${r.id._id}.`);n.push(a)}let s=i.length>0?i[0].index:t.length;if(t.length!==s)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${s+1} conflicts with ${t.length} static arguments`);return new e(...t,...n)}},y6={trace:0,debug:1,info:2,warn:3,error:4,off:5},S6="xterm.js: ",yb=class extends Ae{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),w6=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=y6[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;nthis._maxLength){let n=this._length+i.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let s=t-1;s>=0;s--)this.set(e+s+i,this.get(e+s));let n=e+t+i-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n]}set(t,i){this._data[t*Oe+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*Oe+0]=t|2097152|i[2]<<22):this._data[t*Oe+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*Oe+0]>>22}hasWidth(t){return this._data[t*Oe+0]&12582912}getFg(t){return this._data[t*Oe+1]}getBg(t){return this._data[t*Oe+2]}hasContent(t){return this._data[t*Oe+0]&4194303}getCodePoint(t){let i=this._data[t*Oe+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*Oe+0]&2097152}getString(t){let i=this._data[t*Oe+0];return i&2097152?this._combined[t]:i&2097151?ta(i&2097151):""}isProtected(t){return this._data[t*Oe+2]&536870912}loadCell(t,i){return Cf=t*Oe,i.content=this._data[Cf+0],i.fg=this._data[Cf+1],i.bg=this._data[Cf+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*Oe+0]=i.content,this._data[t*Oe+1]=i.fg,this._data[t*Oe+2]=i.bg}setCellFromCodepoint(t,i,n,s){s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*Oe+0]=i|n<<22,this._data[t*Oe+1]=s.fg,this._data[t*Oe+2]=s.bg}addCodepointToCell(t,i,n){let s=this._data[t*Oe+0];s&2097152?this._combined[t]+=ta(i):s&2097151?(this._combined[t]=ta(s&2097151)+ta(i),s&=-2097152,s|=2097152):s=i|1<<22,n&&(s&=-12582913,s|=n<<22),this._data[t*Oe+0]=s}insertCells(t,i,n){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),i=0;--r)this.setCell(t+i+r,this.loadCell(t+r,s));for(let r=0;rthis.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let s=new Uint32Array(n);s.set(this._data),this._data=s}for(let s=this.length;s=t&&delete this._combined[o]}let r=Object.keys(this._extendedAttrs);for(let a=0;a=t&&delete this._extendedAttrs[o]}}return this.length=t,n*4*Lv=0;--t)if(this._data[t*Oe+0]&4194303)return t+(this._data[t*Oe+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Oe+0]&4194303||this._data[t*Oe+2]&50331648)return t+(this._data[t*Oe+0]>>22);return 0}copyCellsFrom(t,i,n,s,r){let a=t._data;if(r)for(let l=s-1;l>=0;l--){for(let c=0;c=i&&(this._combined[c-i+n]=t._combined[c])}}translateToString(t,i,n,s){i=i??0,n=n??this.length,t&&(n=Math.min(n,this.getTrimmedLength())),s&&(s.length=0);let r="";for(;i>22||1}return s&&s.push(i),r}};yM=class SM{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=SM._nextId++,this._onDispose=this.register(new Q),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),to(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};yM._nextId=1;T6=yM,$t={},Qa=$t.B;$t[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"};$t.A={"#":"\xA3"};$t.B=void 0;$t[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};$t.C=$t[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};$t.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};$t.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};$t.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};$t.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};$t.E=$t[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};$t.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};$t.H=$t[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};$t["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};uA=4294967295,hA=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Pt.clone(),this.savedCharset=Qa,this.markers=[],this._nullCell=Un.fromCharData([0,DA,1,0]),this._whitespaceCell=Un.fromCharData([0,ia,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Ff,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new cA(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Lf),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Lf),this._whitespaceCell}getBlankLine(e,t){return new vu(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&euA?uA:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Pt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new cA(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Pt),n=0,s=this._getCorrectBufferLength(t);if(s>this.lines.maxLength&&(this.lines.maxLength=s),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+r+1?(this.ybase--,r++,this.ydisp>0&&this.ydisp--):this.lines.push(new vu(e,i)));else for(let a=this._rows;a>t;a--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(s0&&(this.lines.trimStart(a),this.ybase=Math.max(this.ybase-a,0),this.ydisp=Math.max(this.ydisp-a,0),this.savedY=Math.max(this.savedY-a,0)),this.lines.maxLength=s}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),r&&(this.y+=r),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let r=0;r.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,n=E6(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Pt),i);if(n.length>0){let s=x6(this.lines,n);C6(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let n=this.getNullCell(Pt),s=i;for(;s-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;a--){let o=this.lines.get(a);if(!o||!o.isWrapped&&o.getTrimmedLength()<=e)continue;let l=[o];for(;o.isWrapped&&a>0;)o=this.lines.get(--a),l.unshift(o);if(!i){let v=this.ybase+this.y;if(v>=a&&v0&&(s.push({start:a+l.length+r,newLines:f}),r+=f.length),l.push(...f);let p=u.length-1,_=u[p];_===0&&(p--,_=u[p]);let w=l.length-h-1,g=c;for(;w>=0;){let v=Math.min(g,_);if(l[p]===void 0)break;if(l[p].copyCellsFrom(l[w],g-v,_-v,v,!0),_-=v,_===0&&(p--,_=u[p]),g-=v,g===0){w--;let S=Math.max(w,0);g=Nu(l,S,this._cols)}}for(let v=0;v0;)this.ybase===0?this.y0){let a=[],o=[];for(let _=0;_=0;_--)if(h&&h.start>c+d){for(let w=h.newLines.length-1;w>=0;w--)this.lines.set(_--,h.newLines[w]);_++,a.push({index:c+1,amount:h.newLines.length}),d+=h.newLines.length,h=s[++u]}else this.lines.set(_,o[c--]);let f=0;for(let _=a.length-1;_>=0;_--)a[_].index+=f,this.lines.onInsertEmitter.fire(a[_]),f+=a[_].amount;let p=Math.max(0,l+r-this.lines.maxLength);p>0&&this.lines.onTrimEmitter.fire(p)}}translateBufferLineToString(e,t,i=0,n){let s=this.lines.get(e);return s?s.translateToString(t,i,n):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},N6=class extends Ae{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Q),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new hA(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new hA(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},wM=2,EM=1,Sb=class extends Ae{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onScroll=this._register(new Q),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,wM),this.rows=Math.max(e.rawOptions.rows||0,EM),this.buffers=this._register(new N6(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,n=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=i.getBlankLine(e,t),this._cachedBlankLine=n),n.isWrapped=t;let s=i.ybase+i.scrollTop,r=i.ybase+i.scrollBottom;if(i.scrollTop===0){let a=i.lines.isFull;r===i.lines.length-1?a?i.lines.recycle().copyFrom(n):i.lines.push(n.clone()):i.lines.splice(r+1,0,n.clone()),a?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let a=r-s+1;i.lines.shiftElements(s+1,a-1,-1),i.lines.set(r,n.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let n=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),n!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};Sb=kt([se(0,Hi)],Sb);Ol={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:Hf,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},A6=["normal","bold","100","200","300","400","500","600","700","800","900"],M6=class extends Ae{constructor(e){super(),this._onOptionChange=this._register(new Q),this.onOptionChange=this._onOptionChange.event;let t={...Ol};for(let i in e)if(i in t)try{let n=e[i];t[i]=this._sanitizeAndValidateOption(i,n)}catch(n){console.error(n)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ft(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in Ol))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,n)=>{if(!(i in Ol))throw new Error(`No option with key "${i}"`);n=this._sanitizeAndValidateOption(i,n),this.rawOptions[i]!==n&&(this.rawOptions[i]=n,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let n={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,n)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=Ol[e]),!R6(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Ol[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=A6.includes(t)?t:Ol[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};dA=Object.freeze({insertMode:!1}),fA=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),wb=class extends Ae{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Q),this.onData=this._onData.event,this._onUserInput=this._register(new Q),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Q),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=bu(dA),this.decPrivateModes=bu(fA)}reset(){this.modes=bu(dA),this.decPrivateModes=bu(fA)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(n=>n.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};wb=kt([se(0,Ui),se(1,PA),se(2,Hi)],wb);pA={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};Iv=String.fromCharCode,mA={DEFAULT:e=>{let t=[Bv(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${Iv(t[0])}${Iv(t[1])}${Iv(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Bv(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${Bv(e,!0)};${e.x};${e.y}${t}`}},Eb=class extends Ae{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Q),this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(pA))this.addProtocol(n,pA[n]);for(let n of Object.keys(mA))this.addEncoding(n,mA[n]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let n=t/i,s=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(s/=n+0,Math.abs(e.deltaY)<50&&(s*=.3),this._wheelPartialScroll+=s,s=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(s*=this._bufferService.rows),s}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};Eb=kt([se(0,Ui),se(1,no),se(2,Hi)],Eb);zv=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],O6=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];L6=class{constructor(){if(this.version="6",!Wt){Wt=new Uint8Array(65536),Wt.fill(1),Wt[0]=0,Wt.fill(0,1,32),Wt.fill(0,127,160),Wt.fill(2,4352,4448),Wt[9001]=2,Wt[9002]=2,Wt.fill(2,11904,42192),Wt[12351]=1,Wt.fill(2,44032,55204),Wt.fill(2,63744,64256),Wt.fill(2,65040,65050),Wt.fill(2,65072,65136),Wt.fill(2,65280,65377),Wt.fill(2,65504,65511);for(let e=0;e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),n=i===0&&t!==0;if(n){let s=Ja.extractWidth(t);s===0?n=!1:s>i&&(i=s)}return Ja.createPropertyValue(0,i,n)}},Ja=class Df{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Q,this.onChange=this._onChange.event;let t=new L6;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,n=!1){return(t&16777215)<<3|(i&3)<<1|(n?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,n=0,s=t.length;for(let r=0;r=s)return i+this.wcwidth(a);let c=t.charCodeAt(r);56320<=c&&c<=57343?a=(a-55296)*1024+c-56320+65536:i+=this.wcwidth(c)}let o=this.charProperties(a,n),l=Df.extractWidth(o);Df.extractShouldJoin(o)&&(l-=Df.extractWidth(n)),i+=l,n=o}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},B6=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};du=2147483647,I6=256,xM=class xb{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>I6)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new xb;if(!t.length)return i;for(let n=Array.isArray(t[0])?1:0;n>8,s=this._subParamsIdx[i]&255;s-n>0&&t.push(Array.prototype.slice.call(this._subParams,n,s))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>du?du:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>du?du:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,n=this._subParamsIdx[t]&255;return n-i>0?this._subParams.subarray(i,n):null}getSubParamsAll(){let t={};for(let i=0;i>8,s=this._subParamsIdx[i]&255;s-n>0&&(t[i]=this._subParams.slice(n,s))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,s=n[i-1];n[i-1]=~s?Math.min(s*10+t,du):t}},fu=[],z6=class{constructor(){this._state=0,this._active=fu,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=fu}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=fu,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||fu,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",Kf(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,n=this._active.length-1,s=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&i===!1){for(;n>=0&&(i=this._active[n].end(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=fu,this._id=-1,this._state=0}}},_n=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Kf(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},pu=[],P6=class{constructor(){this._handlers=Object.create(null),this._active=pu,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=pu}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=pu,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||pu,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",Kf(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,n=this._active.length-1,s=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,s=this._stack.fallThrough,this._stack.paused=!1),!s&&i===!1){for(;n>=0&&(i=this._active[n].unhook(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=pu,this._ident=0}},yu=new xM;yu.addParam(0);_A=class{constructor(e){this._handler=e,this._data="",this._params=yu,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():yu,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Kf(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=yu,this._data="",this._hitLimit=!1,i));return this._params=yu,this._data="",this._hitLimit=!1,t}},U6=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,n){this.table[t<<8|e]=i<<4|n}addMany(e,t,i,n){for(let s=0;sl),i=(o,l)=>t.slice(o,l),n=i(32,127),s=i(0,24);s.push(25),s.push.apply(s,i(28,32));let r=i(0,14),a;e.setDefault(1,0),e.addMany(n,0,2,0);for(a in r)e.addMany([24,26,153,154],a,3,0),e.addMany(i(128,144),a,3,0),e.addMany(i(144,152),a,3,0),e.add(156,a,0,0),e.add(27,a,11,1),e.add(157,a,4,8),e.addMany([152,158,159],a,0,7),e.add(155,a,11,3),e.add(144,a,11,9);return e.addMany(s,0,3,0),e.addMany(s,1,3,1),e.add(127,1,0,1),e.addMany(s,8,0,8),e.addMany(s,3,3,3),e.add(127,3,0,3),e.addMany(s,4,3,4),e.add(127,4,0,4),e.addMany(s,6,3,6),e.addMany(s,5,3,5),e.add(127,5,0,5),e.addMany(s,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(n,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(n,7,0,7),e.addMany(s,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(s,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(s,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(s,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(s,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(s,13,13,13),e.addMany(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Pn,0,2,0),e.add(Pn,8,5,8),e.add(Pn,6,0,6),e.add(Pn,11,0,11),e.add(Pn,13,13,13),e})(),F6=class extends Ae{constructor(e=H6){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new xM,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,n)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ft(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new z6),this._dcsParser=this._register(new P6),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let s=0;sr||r>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=r}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(t[0]>n||n>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=n,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let n=this._escHandlers[i];return n.push(t),{dispose:()=>{let s=n.indexOf(t);s!==-1&&n.splice(s,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let n=this._csiHandlers[i];return n.push(t),{dispose:()=>{let s=n.indexOf(t);s!==-1&&n.splice(s,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,n,s){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=n,this._parseStack.chunkPos=s}parse(e,t,i){let n=0,s=0,r=0,a;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,r=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let o=this._parseStack.handlers,l=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&l>-1){for(;l>=0&&(a=o[l](this._params),a!==!0);l--)if(a instanceof Promise)return this._parseStack.handlerPos=l,a}this._parseStack.handlers=[];break;case 4:if(i===!1&&l>-1){for(;l>=0&&(a=o[l](),a!==!0);l--)if(a instanceof Promise)return this._parseStack.handlerPos=l,a}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],a=this._dcsParser.unhook(n!==24&&n!==26,i),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],a=this._oscParser.end(n!==24&&n!==26,i),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,r=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let o=r;o>4){case 2:for(let d=o+1;;++d){if(d>=t||(n=e[d])<32||n>126&&n=t||(n=e[d])<32||n>126&&n=t||(n=e[d])<32||n>126&&n=t||(n=e[d])<32||n>126&&n=0&&(a=l[c](this._params),a!==!0);c--)if(a instanceof Promise)return this._preserveStack(3,l,c,s,o),a;c<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++o47&&n<60);o--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let u=this._escHandlers[this._collect<<8|n],h=u?u.length-1:-1;for(;h>=0&&(a=u[h](),a!==!0);h--)if(a instanceof Promise)return this._preserveStack(4,u,h,s,o),a;h<0&&this._escHandlerFb(this._collect<<8|n),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|n,this._params);break;case 13:for(let d=o+1;;++d)if(d>=t||(n=e[d])===24||n===26||n===27||n>127&&n=t||(n=e[d])<32||n>127&&nthis._activeBuffer=c.activeBuffer)),this._parser.setCsiHandlerFallback((c,u)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(c),params:u.toArray()})}),this._parser.setEscHandlerFallback(c=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(c)})}),this._parser.setExecuteHandlerFallback(c=>{this._logService.debug("Unknown EXECUTE code: ",{code:c})}),this._parser.setOscHandlerFallback((c,u,h)=>{this._logService.debug("Unknown OSC code: ",{identifier:c,action:u,data:h})}),this._parser.setDcsHandlerFallback((c,u,h)=>{u==="HOOK"&&(h=h.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(c),action:u,payload:h})}),this._parser.setPrintHandler((c,u,h)=>this.print(c,u,h)),this._parser.registerCsiHandler({final:"@"},c=>this.insertChars(c)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},c=>this.scrollLeft(c)),this._parser.registerCsiHandler({final:"A"},c=>this.cursorUp(c)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},c=>this.scrollRight(c)),this._parser.registerCsiHandler({final:"B"},c=>this.cursorDown(c)),this._parser.registerCsiHandler({final:"C"},c=>this.cursorForward(c)),this._parser.registerCsiHandler({final:"D"},c=>this.cursorBackward(c)),this._parser.registerCsiHandler({final:"E"},c=>this.cursorNextLine(c)),this._parser.registerCsiHandler({final:"F"},c=>this.cursorPrecedingLine(c)),this._parser.registerCsiHandler({final:"G"},c=>this.cursorCharAbsolute(c)),this._parser.registerCsiHandler({final:"H"},c=>this.cursorPosition(c)),this._parser.registerCsiHandler({final:"I"},c=>this.cursorForwardTab(c)),this._parser.registerCsiHandler({final:"J"},c=>this.eraseInDisplay(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},c=>this.eraseInDisplay(c,!0)),this._parser.registerCsiHandler({final:"K"},c=>this.eraseInLine(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},c=>this.eraseInLine(c,!0)),this._parser.registerCsiHandler({final:"L"},c=>this.insertLines(c)),this._parser.registerCsiHandler({final:"M"},c=>this.deleteLines(c)),this._parser.registerCsiHandler({final:"P"},c=>this.deleteChars(c)),this._parser.registerCsiHandler({final:"S"},c=>this.scrollUp(c)),this._parser.registerCsiHandler({final:"T"},c=>this.scrollDown(c)),this._parser.registerCsiHandler({final:"X"},c=>this.eraseChars(c)),this._parser.registerCsiHandler({final:"Z"},c=>this.cursorBackwardTab(c)),this._parser.registerCsiHandler({final:"`"},c=>this.charPosAbsolute(c)),this._parser.registerCsiHandler({final:"a"},c=>this.hPositionRelative(c)),this._parser.registerCsiHandler({final:"b"},c=>this.repeatPrecedingCharacter(c)),this._parser.registerCsiHandler({final:"c"},c=>this.sendDeviceAttributesPrimary(c)),this._parser.registerCsiHandler({prefix:">",final:"c"},c=>this.sendDeviceAttributesSecondary(c)),this._parser.registerCsiHandler({final:"d"},c=>this.linePosAbsolute(c)),this._parser.registerCsiHandler({final:"e"},c=>this.vPositionRelative(c)),this._parser.registerCsiHandler({final:"f"},c=>this.hVPosition(c)),this._parser.registerCsiHandler({final:"g"},c=>this.tabClear(c)),this._parser.registerCsiHandler({final:"h"},c=>this.setMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"h"},c=>this.setModePrivate(c)),this._parser.registerCsiHandler({final:"l"},c=>this.resetMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"l"},c=>this.resetModePrivate(c)),this._parser.registerCsiHandler({final:"m"},c=>this.charAttributes(c)),this._parser.registerCsiHandler({final:"n"},c=>this.deviceStatus(c)),this._parser.registerCsiHandler({prefix:"?",final:"n"},c=>this.deviceStatusPrivate(c)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},c=>this.softReset(c)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},c=>this.setCursorStyle(c)),this._parser.registerCsiHandler({final:"r"},c=>this.setScrollRegion(c)),this._parser.registerCsiHandler({final:"s"},c=>this.saveCursor(c)),this._parser.registerCsiHandler({final:"t"},c=>this.windowOptions(c)),this._parser.registerCsiHandler({final:"u"},c=>this.restoreCursor(c)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},c=>this.insertColumns(c)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},c=>this.deleteColumns(c)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},c=>this.selectProtected(c)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},c=>this.requestMode(c,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},c=>this.requestMode(c,!1)),this._parser.setExecuteHandler(H.BEL,()=>this.bell()),this._parser.setExecuteHandler(H.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(H.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(H.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(H.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(H.BS,()=>this.backspace()),this._parser.setExecuteHandler(H.HT,()=>this.tab()),this._parser.setExecuteHandler(H.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(H.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Eu.IND,()=>this.index()),this._parser.setExecuteHandler(Eu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Eu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new _n(c=>(this.setTitle(c),this.setIconName(c),!0))),this._parser.registerOscHandler(1,new _n(c=>this.setIconName(c))),this._parser.registerOscHandler(2,new _n(c=>this.setTitle(c))),this._parser.registerOscHandler(4,new _n(c=>this.setOrReportIndexedColor(c))),this._parser.registerOscHandler(8,new _n(c=>this.setHyperlink(c))),this._parser.registerOscHandler(10,new _n(c=>this.setOrReportFgColor(c))),this._parser.registerOscHandler(11,new _n(c=>this.setOrReportBgColor(c))),this._parser.registerOscHandler(12,new _n(c=>this.setOrReportCursorColor(c))),this._parser.registerOscHandler(104,new _n(c=>this.restoreIndexedColor(c))),this._parser.registerOscHandler(110,new _n(c=>this.restoreFgColor(c))),this._parser.registerOscHandler(111,new _n(c=>this.restoreBgColor(c))),this._parser.registerOscHandler(112,new _n(c=>this.restoreCursorColor(c))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let c in $t)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(c=>(this._logService.error("Parsing error: ",c),c)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new _A((c,u)=>this.requestStatusString(c,u)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),SA))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${SA} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,n=this._activeBuffer.x,s=this._activeBuffer.y,r=0,a=this._parseStack.paused;if(a){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;n=this._parseStack.cursorStartX,s=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>ea&&(r=this._parseStack.position+ea)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,c=>String.fromCharCode(c)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(c=>c.charCodeAt(0)):e),this._parseBuffer.lengthea)for(let c=r;c0&&h.getWidth(this._activeBuffer.x-1)===2&&h.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let d=this._parser.precedingJoinState;for(let f=t;fo){if(l){let g=h,m=this._activeBuffer.x-w;for(this._activeBuffer.x=w,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),w>0&&h instanceof vu&&h.copyCellsFrom(g,m,0,w,!1);m=0;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(c&&(h.insertCells(this._activeBuffer.x,s-w,this._activeBuffer.getNullCell(u)),h.getWidth(o-1)===2&&h.setCellFromCodepoint(o-1,0,1,u)),h.setCellFromCodepoint(this._activeBuffer.x++,n,s,u),s>0)for(;--s;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=d,this._activeBuffer.x0&&h.getWidth(this._activeBuffer.x)===0&&!h.hasContent(this._activeBuffer.x)&&h.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>yA(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new _A(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _n(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,n=!1,s=!1){let r=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);r.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),s),n&&(r.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+i)?.getTrimmedLength(););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let l=o;for(let c=1;c0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(H.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(H.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(H.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(H.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(H.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(_[_.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",_[_.SET=1]="SET",_[_.RESET=2]="RESET",_[_.PERMANENTLY_SET=3]="PERMANENTLY_SET",_[_.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(i||(i={}));let n=this._coreService.decPrivateModes,{activeProtocol:s,activeEncoding:r}=this._coreMouseService,a=this._coreService,{buffers:o,cols:l}=this._bufferService,{active:c,alt:u}=o,h=this._optionsService.rawOptions,d=(_,w)=>(a.triggerDataEvent(`${H.ESC}[${t?"":"?"}${_};${w}$y`),!0),f=_=>_?1:2,p=e.params[0];return t?p===2?d(p,4):p===4?d(p,f(a.modes.insertMode)):p===12?d(p,3):p===20?d(p,f(h.convertEol)):d(p,0):p===1?d(p,f(n.applicationCursorKeys)):p===3?d(p,h.windowOptions.setWinLines?l===80?2:l===132?1:0:0):p===6?d(p,f(n.origin)):p===7?d(p,f(n.wraparound)):p===8?d(p,3):p===9?d(p,f(s==="X10")):p===12?d(p,f(h.cursorBlink)):p===25?d(p,f(!a.isCursorHidden)):p===45?d(p,f(n.reverseWraparound)):p===66?d(p,f(n.applicationKeypad)):p===67?d(p,4):p===1e3?d(p,f(s==="VT200")):p===1002?d(p,f(s==="DRAG")):p===1003?d(p,f(s==="ANY")):p===1004?d(p,f(n.sendFocus)):p===1005?d(p,4):p===1006?d(p,f(r==="SGR")):p===1015?d(p,4):p===1016?d(p,f(r==="SGR_PIXELS")):p===1048?d(p,1):p===47||p===1047||p===1049?d(p,f(c===u)):p===2004?d(p,f(n.bracketedPasteMode)):p===2026?d(p,f(n.synchronizedOutput)):d(p,0)}_updateAttrColor(e,t,i,n,s){return t===2?(e|=50331648,e&=-16777216,e|=Au.fromColorRGB([i,n,s])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let n=[0,0,-1,0,0,0],s=0,r=0;do{if(n[r+s]=e.params[t+r],e.hasSubParams(t+r)){let a=e.getSubParams(t+r),o=0;do n[1]===5&&(s=1),n[r+o+1+s]=a[o];while(++o=2||n[1]===2&&r+s>=5)break;n[1]&&(s=1)}while(++r+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Pt.fg,e.bg=Pt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,n=this._curAttrData;for(let s=0;s=30&&i<=37?(n.fg&=-50331904,n.fg|=16777216|i-30):i>=40&&i<=47?(n.bg&=-50331904,n.bg|=16777216|i-40):i>=90&&i<=97?(n.fg&=-50331904,n.fg|=16777216|i-90|8):i>=100&&i<=107?(n.bg&=-50331904,n.bg|=16777216|i-100|8):i===0?this._processSGR0(n):i===1?n.fg|=134217728:i===3?n.bg|=67108864:i===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(s)?e.getSubParams(s)[0]:1,n)):i===5?n.fg|=536870912:i===7?n.fg|=67108864:i===8?n.fg|=1073741824:i===9?n.fg|=2147483648:i===2?n.bg|=134217728:i===21?this._processUnderline(2,n):i===22?(n.fg&=-134217729,n.bg&=-134217729):i===23?n.bg&=-67108865:i===24?(n.fg&=-268435457,this._processUnderline(0,n)):i===25?n.fg&=-536870913:i===27?n.fg&=-67108865:i===28?n.fg&=-1073741825:i===29?n.fg&=2147483647:i===39?(n.fg&=-67108864,n.fg|=Pt.fg&16777215):i===49?(n.bg&=-67108864,n.bg|=Pt.bg&16777215):i===38||i===48||i===58?s+=this._extractColor(e,s,n):i===53?n.bg|=1073741824:i===55?n.bg&=-1073741825:i===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):i===100?(n.fg&=-67108864,n.fg|=Pt.fg&16777215,n.bg&=-67108864,n.bg|=Pt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${H.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${H.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${H.ESC}[?${t};${i}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Pt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!yA(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${H.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>bA&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>bA&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let n=i.shift(),s=i.shift();if(/^\d+$/.exec(n)){let r=parseInt(n);if(EA(r))if(s==="?")t.push({type:0,index:r});else{let a=vA(s);a&&t.push({type:1,index:r,color:a})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),n=e.slice(t+1);return n?this._createHyperlink(i,n):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),n,s=i.findIndex(r=>r.startsWith("id="));return s!==-1&&(n=i[s].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let n=0;n=this._specialColors.length);++n,++t)if(i[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let s=vA(i[n]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let n=0;n=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Pt.clone(),this._eraseAttrDataInternal=Pt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Un;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${H.ESC}${a}${H.ESC}\\`),!0),n=this._bufferService.buffer,s=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},Cb=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(wA=e,e=t,t=wA),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};Cb=kt([se(0,Ui)],Cb);Y6=5e7,xA=12,j6=50,V6=class extends Ae{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>Y6)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let n=this._writeBuffer[this._bufferOffset],s=this._action(n,t);if(s){let a=o=>performance.now()-i>=xA?setTimeout(()=>this._innerWrite(0,o)):this._innerWrite(i,o);s.catch(o=>(queueMicrotask(()=>{throw o}),Promise.resolve(!1))).then(a);return}let r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-i>=xA)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>j6&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},kb=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let o=t.addMarker(t.ybase+t.y),l={data:e,id:this._nextId++,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(l,o)),this._dataByLinkId.set(l.id,l),l.id}let i=e,n=this._getEntryIdKey(i),s=this._entriesWithId.get(n);if(s)return this.addLineToLink(s.id,t.ybase+t.y),s.id;let r=t.addMarker(t.ybase+t.y),a={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[r]};return r.onDispose(()=>this._removeMarkerFromLink(a,r)),this._entriesWithId.set(a.key,a),this._dataByLinkId.set(a.id,a),a.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(n=>n.line!==t)){let n=this._bufferService.buffer.addMarker(t);i.lines.push(n),n.onDispose(()=>this._removeMarkerFromLink(i,n))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};kb=kt([se(0,Ui)],kb);CA=!1,X6=class extends Ae{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Ll),this._onBinary=this._register(new Q),this.onBinary=this._onBinary.event,this._onData=this._register(new Q),this.onData=this._onData.event,this._onLineFeed=this._register(new Q),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Q),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Q),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Q),this._instantiationService=new b6,this.optionsService=this._register(new M6(e)),this._instantiationService.setService(Hi,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Sb)),this._instantiationService.setService(Ui,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(yb)),this._instantiationService.setService(PA,this._logService),this.coreService=this._register(this._instantiationService.createInstance(wb)),this._instantiationService.setService(no,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Eb)),this._instantiationService.setService(zA,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Ja)),this._instantiationService.setService($z,this.unicodeService),this._charsetService=this._instantiationService.createInstance(B6),this._instantiationService.setService(Wz,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(kb),this._instantiationService.setService(UA,this._oscLinkService),this._inputHandler=this._register(new G6(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(ni.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(ni.forward(this._bufferService.onResize,this._onResize)),this._register(ni.forward(this.coreService.onData,this._onData)),this._register(ni.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new V6((t,i)=>this._inputHandler.parse(t,i))),this._register(ni.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Q),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!CA&&(this._logService.warn("writeSync is unreliable and will be removed soon."),CA=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,wM),t=Math.max(t,EM),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(gA.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(gA(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ft(()=>{for(let t of e)t.dispose()})}}},Z6={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};Mt=0,J6=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Ff,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Ff,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((s,r)=>this._getKey(s)-this._getKey(r)),t=0,i=0,n=new Array(this._array.length+this._insertedValues.length);for(let s=0;s=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(n[s]=e[t],t++):n[s]=this._array[i++];this._array=n,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Mt=this._search(t),Mt===-1)||this._getKey(this._array[Mt])!==t)return!1;do if(this._array[Mt]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Mt),!0;while(++Mts-r),t=0,i=new Array(this._array.length-e.length),n=0;for(let s=0;s0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Mt=this._search(e),!(Mt<0||Mt>=this._array.length)&&this._getKey(this._array[Mt])===e))do yield this._array[Mt];while(++Mt=this._array.length)&&this._getKey(this._array[Mt])===e))do t(this._array[Mt]);while(++Mt=t;){let n=t+i>>1,s=this._getKey(this._array[n]);if(s>e)i=n-1;else if(s0&&this._getKey(this._array[n-1])===e;)n--;return n}}return t}},Uv=0,kA=0,eP=class extends Ae{constructor(){super(),this._decorations=new J6(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Q),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Q),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ft(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new tP(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let n=0,s=0;for(let r of this._decorations.getKeyIterator(t))n=r.options.x??0,s=n+(r.options.width??1),e>=n&&e{Uv=s.options.x??0,kA=Uv+(s.options.width??1),e>=Uv&&e=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let s=n-this._lastRefreshMs,r=this._debounceThresholdMS-s;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},r)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},TA=20,NA=!1,qf=class extends Ae{constructor(e,t,i,n){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=n,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let s=this._coreBrowserService.mainDocument;this._accessibilityContainer=s.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=s.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let r=0;rthis._handleBoundaryFocus(r,0),this._bottomBoundaryFocusListener=r=>this._handleBoundaryFocus(r,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=s.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new nP(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");NA?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=s.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(s.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(s.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(r=>this._handleResize(r.rows))),this._register(this._terminal.onRender(r=>this._refreshRows(r.start,r.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(r=>this._handleChar(r))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` -`))),this._register(this._terminal.onA11yTab(r=>this._handleTab(r))),this._register(this._terminal.onKey(r=>this._handleKey(r.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(_e(s,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ft(()=>{NA?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` -`&&(this._liveRegionLineCount++,this._liveRegionLineCount===TA+1&&(this._liveRegion.textContent+=Fv.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,n=i.lines.length.toString();for(let s=e;s<=t;s++){let r=i.lines.get(i.ydisp+s),a=[],o=r?.translateToString(!0,void 0,void 0,a)||"",l=(i.ydisp+s+1).toString(),c=this._rowElements[s];c&&(o.length===0?(c.textContent="\xA0",this._rowColumns.set(c,[0,1])):(c.textContent=o,this._rowColumns.set(c,a)),c.setAttribute("aria-posinset",l),c.setAttribute("aria-setsize",n),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,n=this._rowElements[t===0?1:this._rowElements.length-2],s=i.getAttribute("aria-posinset"),r=t===0?"1":`${this._terminal.buffer.lines.length}`;if(s===r||e.relatedTarget!==n)return;let a,o;if(t===0?(a=i,o=this._rowElements.pop(),this._rowContainer.removeChild(o)):(a=this._rowElements.shift(),o=i,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),o.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let l=this._createAccessibilityTreeNode();this._rowElements.unshift(l),this._rowContainer.insertAdjacentElement("afterbegin",l)}else{let l=this._createAccessibilityTreeNode();this._rowElements.push(l),this._rowContainer.appendChild(l)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let n=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(i.node))return;let s=({node:o,offset:l})=>{let c=o instanceof Text?o.parentNode:o,u=parseInt(c?.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let h=this._rowColumns.get(c);if(!h)return console.warn("columns is null. Race condition?"),null;let d=l=this._terminal.cols&&(++u,d=0),{row:u,column:d}},r=s(t),a=s(i);if(!(!r||!a)){if(r.row>a.row||r.row===a.row&&r.column>=a.column)throw new Error("invalid range");this._terminal.select(r.column,r.row,(a.row-r.row)*this._terminal.cols-r.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{to(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(_e(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(_e(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(_e(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(_e(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let n=0;n{n?.forEach(s=>{s.link.dispose&&s.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[n,s]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(n)&&(i=this._checkLinkProviderResult(n,e,i)):s.provideLinks(e.y,r=>{if(this._isMouseOut)return;let a=r?.map(o=>({link:o}));this._activeProviderReplies?.set(n,a),i=this._checkLinkProviderResult(n,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let n=0;ne?this._bufferService.cols:a.link.range.end.x;for(let c=o;c<=l;c++){if(i.has(c)){s.splice(r--,1);break}i.add(c)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;let n=this._activeProviderReplies.get(e),s=!1;for(let r=0;rthis._linkAtPosition(a.link,t));r&&(i=!0,this._handleNewLink(r))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let r=0;rthis._linkAtPosition(o.link,t));if(a){i=!0,this._handleNewLink(a);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&sP(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,to(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:i=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:i=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let n=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,s=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=n&&this._currentLink.link.range.end.y<=s&&(this._clearCurrentLink(n,s),this._lastMouseEvent)){let r=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);r&&this._askForLink(r,!1)}})))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,n=this._bufferService.buffer.ydisp,s=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-n-1,i.end.x,i.end.y-n-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(s)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,s=t.y*this._bufferService.cols+t.x;return i<=s&&s<=n}_positionFromMouseEvent(e,t,i){let n=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,n,s){return{x1:e,y1:t,x2:i,y2:n,cols:this._bufferService.cols,fg:s}}};Tb=kt([se(1,Ab),se(2,lr),se(3,Ui),se(4,FA)],Tb);rP=class extends X6{constructor(e={}){super(e),this._linkifier=this._register(new Ll),this.browser=hM,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Ll),this._onCursorMove=this._register(new Q),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Q),this.onKey=this._onKey.event,this._onRender=this._register(new Q),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Q),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Q),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Q),this.onBell=this._onBell.event,this._onFocus=this._register(new Q),this._onBlur=this._register(new Q),this._onA11yCharEmitter=this._register(new Q),this._onA11yTabEmitter=this._register(new Q),this._onWillOpen=this._register(new Q),this._setup(),this._decorationService=this._instantiationService.createInstance(eP),this._instantiationService.setService(Mu,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(Y4),this._instantiationService.setService(FA,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Kv)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(ni.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(ni.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(ni.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(ni.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(ft(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,n="";switch(t.index){case 256:i="foreground",n="10";break;case 257:i="background",n="11";break;case 258:i="cursor",n="12";break;default:i="ansi",n="4;"+t.index}switch(t.type){case 0:let s=ht.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${H.ESC}]${n};${W6(s)}${hb.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(r=>r.ansi[t.index]=Rt.toColor(...t.color));else{let r=i;this._themeService.modifyColors(a=>a[r]=Rt.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(qf,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(H.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(H.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,s=t.getWidth(i),r=this._renderService.dimensions.css.cell.width*s,a=this.buffer.y*this._renderService.dimensions.css.cell.height,o=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=o+"px",this.textarea.style.top=a+"px",this.textarea.style.width=r+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(_e(this.element,"copy",t=>{this.hasSelection()&&Pz(t,this._selectionService)}));let e=t=>Uz(t,this.textarea,this.coreService,this.optionsService);this._register(_e(this.textarea,"paste",e)),this._register(_e(this.element,"paste",e)),dM?this._register(_e(this.element,"mousedown",t=>{t.button===2&&kN(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(_e(this.element,"contextmenu",t=>{kN(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),zb&&this._register(_e(this.element,"auxclick",t=>{t.button===1&&OA(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(_e(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(_e(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(_e(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(_e(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(_e(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(_e(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(_e(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(_e(this.screenElement,"mousemove",s=>this.updateCursorStyle(s))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Hv.get()),mM||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance($4,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(or,this._coreBrowserService),this._register(_e(this.textarea,"focus",s=>this._handleTextAreaFocus(s))),this._register(_e(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(mb,this._document,this._helperContainer),this._instantiationService.setService(Wf,this._charSizeService),this._themeService=this._instantiationService.createInstance(bb),this._instantiationService.setService(Bl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Uf),this._instantiationService.setService(HA,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(_b,this.rows,this.screenElement)),this._instantiationService.setService(lr,this._renderService),this._register(this._renderService.onRenderedViewportChange(s=>this._onRender.fire(s))),this.onResize(s=>this._renderService.resize(s.cols,s.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(db,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(gb),this._instantiationService.setService(Ab,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(Tb,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(cb,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(s=>{super.scrollLines(s,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(vb,this.element,this.screenElement,n)),this._instantiationService.setService(Yz,this._selectionService),this._register(this._selectionService.onRequestScrollLines(s=>this.scrollLines(s.amount,s.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(s=>this._renderService.handleSelectionChanged(s.start,s.end,s.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(s=>{this.textarea.value=s,this.textarea.focus(),this.textarea.select()})),this._register(ni.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(ub,this.screenElement)),this._register(_e(this.element,"mousedown",s=>this._selectionService.handleMouseDown(s))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(qf,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",s=>this._handleScreenReaderModeOptionChange(s))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Pf,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",s=>{!this._overviewRulerRenderer&&s&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Pf,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(pb,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(r){let a=e._mouseService.getMouseReportCoords(r,e.screenElement);if(!a)return!1;let o,l;switch(r.overrideType||r.type){case"mousemove":l=32,r.buttons===void 0?(o=3,r.button!==void 0&&(o=r.button<3?r.button:3)):o=r.buttons&1?0:r.buttons&4?1:r.buttons&2?2:3;break;case"mouseup":l=0,o=r.button<3?r.button:3;break;case"mousedown":l=1,o=r.button<3?r.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(r)===!1)return!1;let c=r.deltaY;if(c===0||e.coreMouseService.consumeWheelEvent(r,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;l=c<0?0:1,o=4;break;default:return!1}return l===void 0||o===void 0||o>4?!1:e.coreMouseService.triggerMouseEvent({col:a.col,row:a.row,x:a.x,y:a.y,button:o,action:l,ctrl:r.ctrlKey,alt:r.altKey,shift:r.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},s={mouseup:r=>(i(r),r.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(r)),wheel:r=>(i(r),this.cancel(r,!0)),mousedrag:r=>{r.buttons&&i(r)},mousemove:r=>{r.buttons||i(r)}};this._register(this.coreMouseService.onProtocolChange(r=>{r?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(r)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),r&8?n.mousemove||(t.addEventListener("mousemove",s.mousemove),n.mousemove=s.mousemove):(t.removeEventListener("mousemove",n.mousemove),n.mousemove=null),r&16?n.wheel||(t.addEventListener("wheel",s.wheel,{passive:!1}),n.wheel=s.wheel):(t.removeEventListener("wheel",n.wheel),n.wheel=null),r&2?n.mouseup||(n.mouseup=s.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),r&4?n.mousedrag||(n.mousedrag=s.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(_e(t,"mousedown",r=>{if(r.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(r)))return i(r),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(r)})),this._register(_e(t,"wheel",r=>{if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(r)===!1)return!1;if(!this.buffer.hasScrollback){if(r.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(r,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(r,!0);let a=H.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(r.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(a,!0),this.cancel(r,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){RA(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=Q6(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let n=this.rows-1;return this.scrollLines(i.type===2?-n:n),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===H.ETX||i.key===H.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(aP(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Un)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},AA=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new lP(t)}getNullCell(){return new Un}},cP=class extends Ae{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Q),this.onBufferChange=this._onBufferChange.event,this._normal=new AA(this._core.buffers.normal,"normal"),this._alternate=new AA(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},uP=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,n)=>t(i,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},hP=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},dP=["cols","rows"],Ms=0,CM=class extends Ae{constructor(e){super(),this._core=this._register(new rP(e)),this._addonManager=this._register(new oP),this._publicOptions={...this._core.options};let t=n=>this._core.options[n],i=(n,s)=>{this._checkReadonlyOptions(n),this._core.options[n]=s};for(let n in this._core.options){let s={get:t.bind(this,n),set:i.bind(this,n)};Object.defineProperty(this._publicOptions,n,s)}}_checkReadonlyOptions(e){if(dP.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new uP(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new hP(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new cP(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r -`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Hv.get()},set promptLabel(e){Hv.set(e)},get tooMuchOutput(){return Fv.get()},set tooMuchOutput(e){Fv.set(e)}}}_verifyIntegers(...e){for(Ms of e)if(Ms===1/0||isNaN(Ms)||Ms%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Ms of e)if(Ms&&(Ms===1/0||isNaN(Ms)||Ms%1!==0||Ms<0))throw new Error("This API only accepts positive integers")}}});var fP,pP,TM,NM=le(()=>{fP=2,pP=1,TM=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,i=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(i.getPropertyValue("height")),s=Math.max(0,parseInt(i.getPropertyValue("width"))),r=window.getComputedStyle(this._terminal.element),a={top:parseInt(r.getPropertyValue("padding-top")),bottom:parseInt(r.getPropertyValue("padding-bottom")),right:parseInt(r.getPropertyValue("padding-right")),left:parseInt(r.getPropertyValue("padding-left"))},o=a.top+a.bottom,l=a.right+a.left,c=n-o,u=s-l-t;return{cols:Math.max(fP,Math.floor(u/e.css.cell.width)),rows:Math.max(pP,Math.floor(c/e.css.cell.height))}}}});var AM=le(()=>{});function mP(){let e=document.documentElement.dataset.theme;return e==="dark"?!0:e==="light"?!1:window.matchMedia("(prefers-color-scheme: dark)").matches}function Pb(){return mP()?{background:"#0c0c0c",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#0c0c0c",selectionBackground:"#264f78",selectionForeground:"#ffffff",black:"#0c0c0c",red:"#f14c4c",green:"#23d18b",yellow:"#f5f543",blue:"#3b8eea",magenta:"#d670d6",cyan:"#29b8db",white:"#cccccc",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#ffffff"}:{background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff",selectionForeground:"#1e1e1e",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"}}var MM=le(()=>{});function RM(){let{projects:e,threads:t}=ut(),i=fe(),n=t.find(w=>w.id===i.currentThreadId)??null,s=n?e.find(w=>w.id===n.projectId):e.find(w=>w.id===i.currentProjectId),r=s?.id??null,[a,o]=(0,ri.useState)([]),[l,c]=(0,ri.useState)(null),[u,h]=(0,ri.useState)(null),d=(0,ri.useCallback)(async()=>{if(!r){o([]);return}try{let w=await te.call("terminal.list",{projectId:r});o(w),c(g=>g&&w.some(m=>m.id===g)?g:w[0]?.id??null)}catch{}},[r]);(0,ri.useEffect)(()=>{d()},[d]),(0,ri.useEffect)(()=>te.subscribe("terminals",(g,m)=>{let v=m;v?.type==="terminal.exit"&&(o(S=>S.filter(k=>k.id!==v.id)),c(S=>S===v.id?null:S))}),[]);let f=async()=>{if(r)try{let w=await te.call("terminal.create",{projectId:r,cols:100,rows:28});await d(),c(w.id)}catch(w){Te(y("terminal.failNew")+ct(w),!0)}},p=async w=>{try{await te.call("terminal.kill",{id:w.id}),o(g=>g.filter(m=>m.id!==w.id)),c(g=>g===w.id?null:g)}catch(g){Te(y("terminal.failKill")+ct(g),!0)}};if(!s)return(0,Gt.jsx)("div",{className:"pn-empty",children:y("panel.pickProject")});let _=a.find(w=>w.id===l)??null;return(0,Gt.jsxs)(Gt.Fragment,{children:[(0,Gt.jsxs)("div",{className:"tm-tabs",children:[a.map(w=>(0,Gt.jsxs)("button",{className:`tm-tab${w.id===l?" on":""}`,onClick:()=>c(w.id),title:w.title,children:[w.title,(0,Gt.jsx)("span",{className:"tm-x",onClick:g=>{g.stopPropagation(),h(w)},children:"\xD7"})]},w.id)),(0,Gt.jsx)("button",{className:"ibtn",title:y("terminal.new"),onClick:()=>{f()},children:(0,Gt.jsx)(ye,{name:"plus",size:14})})]}),_?.simple&&(0,Gt.jsx)("div",{className:"tm-note",children:y("terminal.simpleNote")}),(0,Gt.jsxs)("div",{className:"tm-body",children:[a.length===0&&(0,Gt.jsxs)("div",{className:"pn-empty",children:[y("terminal.noTerm"),(0,Gt.jsx)("div",{style:{marginTop:8},children:(0,Gt.jsx)("button",{className:"btn primary",onClick:()=>{f()},children:y("terminal.new")})})]}),a.map(w=>(0,Gt.jsx)(gP,{term:w,visible:w.id===l},w.id))]}),u&&(0,Gt.jsx)(gl,{title:y("terminal.closeTitle"),body:Ce("terminal.closeBody",{title:u.title}),okLabel:y("terminal.closeOk"),danger:!0,onOk:()=>{p(u)},onClose:()=>h(null)})]})}function gP({term:e,visible:t}){let i=(0,ri.useRef)(null),n=(0,ri.useRef)(null),s=(0,ri.useRef)(null),[r,a]=(0,ri.useState)(!1);return(0,ri.useEffect)(()=>{let o=i.current;if(!o)return;let l=new CM({fontFamily:'"Cascadia Mono", "Cascadia Code", Consolas, "SF Mono", Menlo, Monaco, "DejaVu Sans Mono", "Ubuntu Mono", "Microsoft YaHei UI", "PingFang SC", "Noto Sans Mono CJK SC", monospace',fontSize:13,lineHeight:1.25,cursorBlink:!0,scrollback:5e3,allowTransparency:!1,theme:Pb()}),c=new TM;l.loadAddon(c),l.open(o),n.current=l,s.current=c;try{c.fit()}catch{}let u=new TextDecoder,h=new TextEncoder,d=te.onBinaryFrame((f,p,_)=>{p!==e.index||f!==1||l.write(u.decode(_))});return l.onData(f=>te.sendBinary(2,e.index,h.encode(f))),(async()=>{try{let f=await te.call("terminal.attach",{id:e.id});f.windowsPty&&(l.options.windowsPty=f.windowsPty),f.snapshot&&l.write(f.snapshot),a(!0)}catch{l.writeln(y("terminal.ended"))}})(),()=>{d(),l.dispose(),n.current=null,s.current=null}},[e.id,e.index]),(0,ri.useEffect)(()=>{let o=document.documentElement,l=()=>{let h=n.current;h&&(h.options.theme=Pb())},c=new MutationObserver(l);c.observe(o,{attributes:!0,attributeFilter:["data-theme"]});let u=window.matchMedia("(prefers-color-scheme: dark)");return u.addEventListener("change",l),()=>{c.disconnect(),u.removeEventListener("change",l)}},[]),(0,ri.useEffect)(()=>{if(!t)return;let o=s.current,l=n.current;if(!o||!l||!r)return;let c=setTimeout(()=>{try{o.fit();let u=new TextEncoder;te.sendBinary(3,e.index,u.encode(JSON.stringify({cols:l.cols,rows:l.rows})))}catch{}},50);return()=>clearTimeout(c)},[t,r,e.index]),(0,ri.useEffect)(()=>{let o=i.current;if(!o)return;let l=new ResizeObserver(()=>{let c=s.current,u=n.current;if(!(!c||!u||!t))try{c.fit();let h=new TextEncoder;te.sendBinary(3,e.index,h.encode(JSON.stringify({cols:u.cols,rows:u.rows})))}catch{}});return l.observe(o),()=>l.disconnect()},[t,e.index]),(0,Gt.jsx)("div",{className:"tm-view",ref:i,style:{display:t?"block":"none"}})}var ri,Gt,OM=le(()=>{ri=ae(Nt(),1);kM();NM();dn();jn();Rn();Wr();_l();Vn();Ci();AM();MM();Gt=ae(ke(),1)});function DM(){let e=fe(),t=[{tab:"changes",label:y("panel.changes")},{tab:"files",label:y("panel.files")},{tab:"terminal",label:y("panel.terminal")}];return(0,re.jsxs)(re.Fragment,{children:[(0,re.jsxs)("div",{className:"pn-head",children:[(0,re.jsx)("div",{className:"pn-tabs",children:t.map(i=>(0,re.jsx)("button",{className:`pn-tab${e.panelTab===i.tab?" on":""}`,onClick:()=>e.setPanelTab(i.tab),children:i.label},i.tab))}),(0,re.jsx)("button",{className:"ibtn pn-close",title:y("panel.closeTitle"),onClick:()=>e.closePanel(),children:(0,re.jsx)(ye,{name:"x"})})]}),(0,re.jsxs)("div",{className:"pn-body",children:[e.panelTab==="changes"&&(0,re.jsx)(yP,{}),e.panelTab==="files"&&(0,re.jsx)(SP,{}),e.panelTab==="terminal"&&(0,re.jsx)(RM,{})]})]})}function vP(e){let t=[],i=null;for(let n of e.split(` -`))if(!(n.startsWith("diff ")||n.startsWith("index ")||n.startsWith("--- ")||n.startsWith("+++ "))){if(n.startsWith("@@")){i={head:n,lines:[]},t.push(i);continue}i&&(n.startsWith("+")?i.lines.push({t:"+",text:n.slice(1)}):n.startsWith("-")?i.lines.push({t:"-",text:n.slice(1)}):n.startsWith("\\")?i.lines.push({t:" ",text:n}):i.lines.push({t:" ",text:n.startsWith(" ")?n.slice(1):n}))}return t}function bP(e){let t=0,i=0;for(let n of e.split(` -`))n.startsWith("+")&&!n.startsWith("+++")?t++:n.startsWith("-")&&!n.startsWith("---")&&i++;return{add:t,del:i}}function yP(){let{projects:e,threads:t}=ut(),i=fe(),n=Dn(T=>T.status),[s,r]=(0,bt.useState)(null),[a,o]=(0,bt.useState)(!1),[l,c]=(0,bt.useState)(null),[u,h]=(0,bt.useState)(null),[d,f]=(0,bt.useState)(null),[p,_]=(0,bt.useState)({}),w=(0,bt.useRef)(n),g=(0,bt.useRef)(null);g.current=l;let m=t.find(T=>T.id===i.currentThreadId)??null,v=m?e.find(T=>T.id===m.projectId):e.find(T=>T.id===i.currentProjectId),S=v?.id??null,k=(0,bt.useCallback)(async()=>{if(!S){r(null);return}try{let T=await te.call("git.status",{projectId:S});r(T);let D=g.current;D&&!T.files?.some(F=>F.path===D)&&(c(null),h(null))}catch(T){r({isRepo:!1,error:String(T?.message??T)})}},[S]);(0,bt.useEffect)(()=>{k();let T=setInterval(()=>{k()},3e3);return()=>clearInterval(T)},[k]),(0,bt.useEffect)(()=>{let T=w.current;w.current=n,(T==="running"||T==="initializing")&&n!=="running"&&n!=="initializing"&&k()},[n,k]);let A=(0,bt.useCallback)(async T=>{if(S){c(T.path),h({loading:!0});try{let D=await te.call("git.diff",{projectId:S,path:T.path});if(D.tooLarge)h({tooLarge:!0});else if(D.error)h({error:D.error});else{let F=vP(D.diff??"");h({hunks:F}),_(P=>({...P,[T.path]:bP(D.diff??"")}))}}catch(D){h({error:String(D?.message??D)})}}},[S]),O=(0,bt.useCallback)(async T=>{if(S){o(!0);try{await te.call("git.discard",{projectId:S,path:T.path}),l===T.path&&(c(null),h(null)),await k()}catch(D){Te(y("panel.failDiscard")+ct(D),!0)}finally{o(!1)}}},[S,l,k]);return v?s&&!s.isRepo?(0,re.jsxs)("div",{className:"pn-empty",children:[y("panel.notGit"),s.error&&(0,re.jsx)("div",{className:"pn-empty-sub",children:s.error})]}):(0,re.jsxs)(re.Fragment,{children:[(0,re.jsxs)("div",{className:"chg-head",children:[(0,re.jsxs)("span",{className:"chg-branch",title:y("panel.branch"),children:[(0,re.jsx)(ye,{name:"changes",size:13})," ",s?.branch??"\u2026"]}),(0,re.jsx)("button",{className:"ibtn",title:y("common.refresh"),onClick:()=>{k()},children:(0,re.jsx)(ye,{name:"refresh",size:14})})]}),(0,re.jsxs)("div",{className:"chg-list",children:[(s?.files??[]).length===0&&(0,re.jsx)("div",{className:"pn-empty",children:y("panel.clean")}),s?.files?.map(T=>{let D=p[T.path];return(0,re.jsxs)("div",{className:`chg-row${l===T.path?" on":""}`,onClick:()=>{A(T)},children:[(0,re.jsx)("span",{className:`chg-kind k-${T.kind}`,title:T.kind,children:_P(T.kind)}),(0,re.jsx)("span",{className:"chg-path",title:T.path,children:T.path}),D&&(0,re.jsxs)("span",{className:"chg-stat",children:[(0,re.jsxs)("em",{className:"add",children:["+",D.add]})," ",(0,re.jsxs)("em",{className:"del",children:["\u2212",D.del]})]}),(0,re.jsx)("button",{className:"ibtn chg-discard",title:y("panel.discardBtn"),disabled:a,onClick:F=>{F.stopPropagation(),f(T)},children:(0,re.jsx)(ye,{name:"x",size:13})})]},T.path)})]}),(0,re.jsxs)("div",{className:"chg-diff",children:[u?.loading&&(0,re.jsx)("div",{className:"pn-empty",children:y("panel.loadingDiff")}),u?.tooLarge&&(0,re.jsx)("div",{className:"pn-empty",children:y("panel.diffTooLarge")}),u?.error&&(0,re.jsx)("div",{className:"pn-empty",children:u.error}),u?.hunks&&(0,re.jsx)(mf,{hunks:u.hunks,path:l??void 0})]}),d&&(0,re.jsx)(gl,{title:y("panel.discardTitle"),body:d.kind==="untracked"?Ce("panel.discardUntracked",{path:d.path}):Ce("panel.discardTracked",{path:d.path}),okLabel:y("common.discard"),danger:!0,onOk:()=>{O(d)},onClose:()=>f(null)})]}):(0,re.jsx)("div",{className:"pn-empty",children:y("panel.pickProject")})}function SP(){let{projects:e,threads:t}=ut(),i=fe(),n=t.find(m=>m.id===i.currentThreadId)??null,s=n?e.find(m=>m.id===n.projectId):e.find(m=>m.id===i.currentProjectId),r=s?.id??null,[a,o]=(0,bt.useState)({}),[l,c]=(0,bt.useState)(null),[u,h]=(0,bt.useState)(null),d=(0,bt.useCallback)(async m=>{if(r){o(v=>({...v,[m]:"loading"}));try{let v=await te.call("files.tree",{projectId:r,dir:m});o(S=>({...S,[m]:v.error?`err:${v.error}`:v.entries??[]}))}catch(v){o(S=>({...S,[m]:`err:${String(v?.message??v)}`}))}}},[r]);(0,bt.useEffect)(()=>{o({}),c(null),h(null),r&&d(".")},[r,d]);let f=m=>{if(!m.isDir){p(m.path);return}let v=a[m.path];v&&v!=="loading"?o(S=>{let k={...S};return delete k[m.path],k}):v||d(m.path)},p=async m=>{if(r){c(m),h({loading:!0});try{let v=await te.call("files.read",{projectId:r,path:m});h(v)}catch(v){h({error:String(v?.message??v)})}}},_=(0,bt.useRef)(null);if((0,bt.useEffect)(()=>{let m=_.current;if(!(!m||!u?.text))try{of.highlightElement(m)}catch{}},[u?.text,u?.language]),!s)return(0,re.jsx)("div",{className:"pn-empty",children:y("panel.pickProject")});let w=l?l.split("/"):[],g=(m,v)=>{let S=a[m];return!S||S==="loading"?null:typeof S=="string"?(0,re.jsx)("div",{className:"ft-err",style:{paddingLeft:8+v*14},children:S.slice(4)}):S.map(k=>(0,re.jsxs)("div",{children:[(0,re.jsxs)("div",{className:`ft-row${l===k.path?" on":""}`,style:{paddingLeft:8+v*14},onClick:()=>f(k),title:k.path,children:[k.isDir?(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)("span",{className:`caret${a[k.path]&&a[k.path]!=="loading"?" open":""}`,children:"\u203A"}),(0,re.jsx)(ye,{name:"files",size:13})]}):(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)("span",{className:"caret",style:{visibility:"hidden"},children:"\u203A"}),(0,re.jsx)("span",{className:"ft-dot"})]}),(0,re.jsx)("span",{className:"ft-name",children:k.name})]}),k.isDir&&g(k.path,v+1)]},k.path))};return(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)("div",{className:"ft-crumbs",children:l?(0,re.jsxs)(re.Fragment,{children:[(0,re.jsx)("button",{className:"ft-crumb",onClick:()=>c(null),title:y("panel.closePreview"),children:"\xD7"}),w.map((m,v)=>(0,re.jsxs)("span",{className:"ft-crumb-t",children:[v>0?"/":"",m]},v)),(0,re.jsx)("button",{className:"ibtn",title:y("common.copyPath"),onClick:()=>{jr(l),Te(y("common.copiedPath"))},children:(0,re.jsx)(ye,{name:"copy",size:13})})]}):(0,re.jsx)("span",{className:"ft-crumb-t muted",children:s.name})}),(0,re.jsx)("div",{className:"ft-tree",children:g(".",0)}),l&&(0,re.jsxs)("div",{className:"ft-view",children:[u?.loading&&(0,re.jsx)("div",{className:"pn-empty",children:y("panel.reading")}),u?.binary&&(0,re.jsx)("div",{className:"pn-empty",children:y("panel.binary")}),u?.tooLarge&&(0,re.jsx)("div",{className:"pn-empty",children:y("panel.tooLarge")}),u?.error&&(0,re.jsx)("div",{className:"pn-empty",children:u.error}),u?.text!=null&&(0,re.jsx)("pre",{className:"ft-pre",children:(0,re.jsx)("code",{ref:_,className:`language-${u.language??"plaintext"}`,children:u.text})})]})]})}var bt,re,_P,LM=le(()=>{bt=ae(Nt(),1);dn();jn();Ml();Rn();Wr();gf();_l();Vn();Ci();OM();lf();lv();re=ae(ke(),1);_P=e=>y(`panel.gitKind.${e}`)});function BM(){let{state:e,version:t}=ws(),i=Dn(l=>l.pending),n=ut(l=>l.providers),[s,r]=(0,Du.useState)(!1),[a,o]=(0,Du.useState)(!1);return(0,Du.useEffect)(()=>{let l=u=>{(u.ctrlKey||u.metaKey)&&u.key.toLowerCase()==="k"&&(u.preventDefault(),r(h=>!h))},c=()=>o(!0);return window.addEventListener("keydown",l),window.addEventListener("open-settings",c),()=>{window.removeEventListener("keydown",l),window.removeEventListener("open-settings",c)}},[]),e==="down"?(0,ai.jsx)("div",{className:"boot-screen",children:(0,ai.jsxs)("div",{className:"boot-wrap",children:[(0,ai.jsx)("span",{children:y("boot.serviceDown")}),(0,ai.jsx)("button",{className:"btn primary",onClick:()=>{Md()||location.reload()},children:y("boot.retry")})]})}):e==="connecting"&&!t?(0,ai.jsxs)("div",{className:"boot-screen",children:[(0,ai.jsx)("div",{className:"boot-dot","data-state":e}),(0,ai.jsx)("span",{className:"boot-label",children:y("boot.connecting")})]}):(0,ai.jsxs)(lx,{sidebar:(0,ai.jsx)(gx,{pendingByThread:new Set(i.map(l=>Dn.getState().threadId).filter(Boolean))}),topbar:(0,ai.jsx)(bT,{pendingCount:i.length}),panel:(0,ai.jsx)(DM,{}),children:[e==="reconnecting"&&(0,ai.jsx)("div",{className:"connbar",children:y("boot.reconnecting")}),(0,ai.jsx)(bN,{}),s&&(0,ai.jsx)(wN,{onClose:()=>r(!1)}),a&&(0,ai.jsx)(oN,{onClose:()=>o(!1),providers:n}),(0,ai.jsx)(px,{})]})}var Du,ai,IM=le(()=>{qc();cx();_x();yT();yN();Ml();jn();Du=ae(Nt(),1);EN();LM();yf();Vn();Ci();b_();ai=ae(ke(),1)});function zM(){let{state:e,version:t}=ws(),[i,n]=(0,Ai.useState)([]),[s,r]=(0,Ai.useState)([]),[a,o]=(0,Ai.useState)(""),[l,c]=(0,Ai.useState)(""),[u,h]=(0,Ai.useState)([]),[d,f]=(0,Ai.useState)([]),[p,_]=(0,Ai.useState)([]),[w,g]=(0,Ai.useState)(""),[m,v]=(0,Ai.useState)(""),S=(0,Ai.useRef)(null);(0,Ai.useEffect)(()=>{e==="open"&&(sa("projects.list").then(D=>n(D??[])),sa("threads.list").then(D=>r(D??[])))},[e]),(0,Ai.useEffect)(()=>{if(S.current?.(),S.current=null,h([]),f([]),_([]),!(!l||e!=="open"))return sa("threads.get",{id:l}).then(D=>{let F=D;h(F.events??[]),f(F.pending??[]),_(F.queue??[])}),S.current=te.subscribe(`thread:${l}`,(D,F)=>{let P=F;if(P.type==="event"&&P.event&&(h(M=>[...M,P.event]),P.event.type==="permission_resolved"||P.event.type==="question_answered")){let M=P.event.requestId;f(B=>B.filter(E=>E.requestId!==M))}P.type==="queue"&&P.queue&&_(P.queue)}),()=>S.current?.()},[l,e]),(0,Ai.useEffect)(()=>{let D=u.filter(M=>M.type==="permission_request"||M.type==="question"),F=new Set(u.filter(M=>M.type==="permission_resolved"||M.type==="question_answered").map(M=>M.requestId)),P=D.filter(M=>!F.has(M.requestId)).map(M=>({requestId:M.requestId??"",kind:M.type==="question"?"question":"permission",options:M.options}));f(M=>{let B=new Map(M.map(E=>[E.requestId,E]));for(let E of P)B.set(E.requestId,E);return[...B.values()]})},[u]);let k=async()=>{if(!l)return;let D=await sa("threads.get",{id:l}).catch(()=>null);D&&(h(D.events??[]),f(F=>{let P=new Map(F.map(M=>[M.requestId,M]));for(let M of D.pending??[])P.set(M.requestId,M);return[...P.values()]}),_(D.queue??[]))},A=async D=>{if(v(""),!l||!w.trim())return;let F=w;g("");try{await sa("thread.send",{id:l,text:F,behavior:D})}catch(P){v(String(P?.message??P))}await k()},O=async(D,F,P)=>{await sa("thread.respond",{id:l,requestId:D,optionId:F,answers:P}).catch(M=>v(String(M?.message??M))),setTimeout(()=>{k()},1500)},T=async()=>{if(!a)return;let D=await sa("threads.create",{projectId:a,provider:"mock"}).catch(F=>(v(String(F?.message??F)),null));D&&(r(F=>[D,...F]),c(D.id))};return(0,pt.jsxs)("div",{style:{display:"flex",height:"100vh",font:"13px/1.5 system-ui",color:"var(--fg)"},children:[(0,pt.jsxs)("div",{style:{width:260,borderRight:"1px solid var(--border)",padding:12,overflowY:"auto"},children:[(0,pt.jsx)("div",{style:{marginBottom:8},children:e==="open"?`\u5DF2\u8FDE\u63A5 \xB7 ${t??""}`:"\u8FDE\u63A5\u4E2D\u2026"}),(0,pt.jsx)(Ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:"\u9009\u62E9\u9879\u76EE",value:a,onChange:o,options:[{value:"",label:"\u9009\u62E9\u9879\u76EE"},...i.map(D=>({value:D.id,label:D.name}))]}),(0,pt.jsx)("button",{onClick:()=>{T()},disabled:!a,style:{width:"100%",marginTop:8},children:"\u65B0\u5EFA\u5BF9\u8BDD\uFF08mock\uFF09"}),(0,pt.jsx)("div",{style:{marginTop:12},children:s.filter(D=>!a||D.projectId===a).map(D=>(0,pt.jsxs)("div",{onClick:()=>c(D.id),style:{padding:"6px 8px",cursor:"pointer",borderRadius:4,background:D.id===l?"var(--bg-active, #333)":"transparent"},children:[D.title," ",(0,pt.jsxs)("span",{style:{opacity:.6},children:["(",D.status,")"]})]},D.id))})]}),(0,pt.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[(0,pt.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:12},children:[u.map((D,F)=>(0,pt.jsx)("pre",{style:{margin:"4px 0",fontSize:11,whiteSpace:"pre-wrap",borderBottom:"1px solid var(--border)",paddingBottom:4},children:(D.seq??"")+" "+(D.type??"?")+" "+JSON.stringify(D).slice(0,400)},F)),d.map(D=>(0,pt.jsxs)("div",{style:{border:"1px solid var(--warn, orange)",borderRadius:6,padding:8,margin:"8px 0"},children:[(0,pt.jsxs)("div",{children:["\u6388\u6743/\u63D0\u95EE ",D.requestId]}),D.options?.map(F=>(0,pt.jsx)("button",{onClick:()=>{O(D.requestId,F.id)},style:{marginRight:8},children:F.label},F.id)),D.kind==="question"&&(0,pt.jsx)("button",{onClick:()=>{O(D.requestId,void 0,{q1:"staging",q2:""})},children:"\u586B\u8868\u63D0\u4EA4"}),(0,pt.jsx)("button",{onClick:()=>{O(D.requestId,void 0,void 0)},children:"\u53D6\u6D88"})]},D.requestId))]}),p.length>0&&(0,pt.jsxs)("div",{style:{padding:"4px 12px",opacity:.7},children:["\u6392\u961F\u4E2D\uFF1A",p.length," \u6761"]}),m&&(0,pt.jsx)("div",{style:{padding:"4px 12px",color:"var(--danger, red)"},children:m}),(0,pt.jsxs)("div",{style:{display:"flex",gap:8,padding:12,borderTop:"1px solid var(--border)"},children:[(0,pt.jsx)("input",{value:w,onChange:D=>g(D.target.value),onKeyDown:D=>{D.key==="Enter"&&A()},placeholder:"/perm /plan /slow /exit \u2026",style:{flex:1}}),(0,pt.jsx)("button",{onClick:()=>{A()},children:"\u53D1\u9001"}),(0,pt.jsx)("button",{onClick:()=>{A("steer")},children:"\u63D2\u8BDD"}),(0,pt.jsx)("button",{onClick:()=>{sa("thread.interrupt",{id:l})},children:"\u6253\u65AD"})]})]})]})}var Ai,pt,sa,PM=le(()=>{Ai=ae(Nt(),1);qc();Rn();vf();pt=ae(ke(),1),sa=(e,t)=>te.call(e,t)});var UM,Ub,wP,HM,te,EP,Rn=le(()=>{d0();f0();p0();m0();g0();UM=ae(IE(),1);PE();Nd();b_();Ci();jE();qc();dn();jn();IM();PM();pf();Ub=ae(ke(),1),wP=Rl(),HM=new URLSearchParams(location.search);YE(location.search);zE(location.search);HE(location.search);te=new Ld(wP,Rd());window.__ws=te;window.__stores={useData:ut,useUi:fe,useConnection:ws};Promise.resolve().then(()=>(Ml(),jT)).then(e=>{window.__tl=e.useTimeline});te.onState(e=>ws.getState().set({state:e}));KE(te,()=>{Md()});te.connect();te.waitHello().then(async e=>{ws.getState().set({version:e.version??null}),fe.getState().bind(te);try{let t=await te.call("settings.get");fe.getState().hydrate(t),Xs(t.theme)}catch{}await ut.getState().bind(te)});setInterval(()=>te.ping(),1e4);EP=HM.get("debug")==="1";(0,UM.createRoot)(document.getElementById("root")).render(EP?(0,Ub.jsx)(zM,{}):(0,Ub.jsx)(BM,{}));HM.get("audit")==="1"&&setTimeout(()=>{try{let e=window.innerWidth,t=document.documentElement.scrollWidth,i=new Set,n=[],s=0,r=getComputedStyle(document.documentElement).getPropertyValue("--accent").trim(),a=c=>c.top0&&c.width>0;document.querySelectorAll("*").forEach(c=>{let u=c,h=getComputedStyle(u),d=u.getBoundingClientRect();if(!a(d)||h.display==="none"||h.visibility==="hidden"||d.width<3||d.height<3)return;i.add(h.fontSize),h.borderTopWidth!=="0px"&&h.borderTopStyle!=="none"&&s++,h.borderBottomWidth!=="0px"&&h.borderBottomStyle!=="none"&&s++;let f=h.backgroundColor,p=h.color;if(r&&(f===r||p===r)){let _=(u.getAttribute("class")??"").split(" ")[0];n.includes(_)||n.push(_)}});let o={vw:e,docW:t,noHScroll:t<=e+1,fontSizes:[...i].sort(),bordersFirstScreen:s,accentEls:n},l=document.createElement("pre");l.id="audit",l.style.display="none",l.textContent=JSON.stringify(o),document.body.appendChild(l)}catch(e){let t=document.createElement("pre");t.id="audit",t.textContent=JSON.stringify({error:String(e)}),document.body.appendChild(t)}},1500)});Rn();})(); +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),S0&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n||!t?!1:this._areCoordsInSelection(t,i,n)}isCellInSelection(e,t){let i=this._model.finalSelectionStart,n=this._model.finalSelectionEnd;return!i||!n?!1:this._areCoordsInSelection([e,t],i,n)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let i=this._linkifier.currentLink?.link?.range;if(i)return this._model.selectionStart=[i.start.x-1,i.start.y-1],this._model.selectionStartLength=tM(i,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let n=this._getMouseBufferCoords(e);return n?(this._selectWordAt(n,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=y0(this._coreBrowserService.window,e,this._screenElement)[1],i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-_b),_b),t/=_b,t/Math.abs(t)+Math.round(t*(RP-1)))}shouldForceSelection(e){return pp?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),OP)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(pp&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&tthis._handleTrim(t))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let n=0;t>=n;n++){let r=e.loadCell(n,this._workCell).getChars().length;this._workCell.getWidth()===0?i--:r>1&&t!==n&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,n=!0){if(e[0]>=this._bufferService.cols)return;let r=this._bufferService.buffer,s=r.lines.get(e[1]);if(!s)return;let a=r.translateBufferLineToString(e[1],!1),o=this._convertViewportColToCharacterIndex(s,e[0]),l=o,c=e[0]-o,u=0,h=0,d=0,f=0;if(a.charAt(o)===" "){for(;o>0&&a.charAt(o-1)===" ";)o--;for(;l1&&(f+=g-1,l+=g-1);S>0&&o>0&&!this._isCharWordSeparator(s.loadCell(S-1,this._workCell));){s.loadCell(S-1,this._workCell);let b=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,S--):b>1&&(d+=b-1,o-=b-1),o--,S--}for(;m1&&(f+=b-1,l+=b-1),l++,m++}}l++;let p=o+c-u+d,_=Math.min(this._bufferService.cols,l-o+u+h-d-f);if(!(!t&&a.slice(o,l).trim()==="")){if(i&&p===0&&s.getCodePoint(0)!==32){let S=r.lines.get(e[1]-1);if(S&&s.isWrapped&&S.getCodePoint(this._bufferService.cols-1)!==32){let m=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(m){let g=this._bufferService.cols-m.start;p-=g,_+=g}}}if(n&&p+_===this._bufferService.cols&&s.getCodePoint(this._bufferService.cols-1)!==32){let S=r.lines.get(e[1]+1);if(S?.isWrapped&&S.getCodePoint(0)!==32){let m=this._getWordAt([0,e[1]+1],!1,!1,!0);m&&(_+=m.length)}}return{start:p,length:_}}}_selectWordAt(e,t){let i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return e.getWidth()===0?!1:this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=tM(i,this._bufferService.cols)}};i0=Rt([re(3,ji),re(4,_o),re(5,f0),re(6,Yi),re(7,Ss),re(8,ys)],i0);iM=class{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},nM=class{constructor(){this._color=new iM,this._css=new iM}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},Zt=Object.freeze((()=>{let e=[xt.toColor("#2e3436"),xt.toColor("#cc0000"),xt.toColor("#4e9a06"),xt.toColor("#c4a000"),xt.toColor("#3465a4"),xt.toColor("#75507b"),xt.toColor("#06989a"),xt.toColor("#d3d7cf"),xt.toColor("#555753"),xt.toColor("#ef2929"),xt.toColor("#8ae234"),xt.toColor("#fce94f"),xt.toColor("#729fcf"),xt.toColor("#ad7fa8"),xt.toColor("#34e2e2"),xt.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){let n=t[i/36%6|0],r=t[i/6%6|0],s=t[i%6];e.push({css:It.toCss(n,r,s),rgba:It.toRgba(n,r,s)})}for(let i=0;i<24;i++){let n=8+i*10;e.push({css:It.toCss(n,n,n),rgba:It.toRgba(n,n,n)})}return e})()),uo=xt.toColor("#ffffff"),Bu=xt.toColor("#000000"),rM=xt.toColor("#ffffff"),sM=Bu,Mu={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},BP=uo,n0=class extends Oe{constructor(e){super(),this._optionsService=e,this._contrastCache=new nM,this._halfContrastCache=new nM,this._onChangeColors=this._register(new Z),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:uo,background:Bu,cursor:rM,cursorAccent:sM,selectionForeground:void 0,selectionBackgroundTransparent:Mu,selectionBackgroundOpaque:gt.blend(Bu,Mu),selectionInactiveBackgroundTransparent:Mu,selectionInactiveBackgroundOpaque:gt.blend(Bu,Mu),scrollbarSliderBackground:gt.opacity(uo,.2),scrollbarSliderHoverBackground:gt.opacity(uo,.4),scrollbarSliderActiveBackground:gt.opacity(uo,.5),overviewRulerBorder:uo,ansi:Zt.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange("theme",()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=at(e.foreground,uo),t.background=at(e.background,Bu),t.cursor=gt.blend(t.background,at(e.cursor,rM)),t.cursorAccent=gt.blend(t.background,at(e.cursorAccent,sM)),t.selectionBackgroundTransparent=at(e.selectionBackground,Mu),t.selectionBackgroundOpaque=gt.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=at(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=gt.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?at(e.selectionForeground,QA):void 0,t.selectionForeground===QA&&(t.selectionForeground=void 0),gt.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=gt.opacity(t.selectionBackgroundTransparent,.3)),gt.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=gt.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=at(e.scrollbarSliderBackground,gt.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=at(e.scrollbarSliderHoverBackground,gt.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=at(e.scrollbarSliderActiveBackground,gt.opacity(t.foreground,.5)),t.overviewRulerBorder=at(e.overviewRulerBorder,BP),t.ansi=Zt.slice(),t.ansi[0]=at(e.black,Zt[0]),t.ansi[1]=at(e.red,Zt[1]),t.ansi[2]=at(e.green,Zt[2]),t.ansi[3]=at(e.yellow,Zt[3]),t.ansi[4]=at(e.blue,Zt[4]),t.ansi[5]=at(e.magenta,Zt[5]),t.ansi[6]=at(e.cyan,Zt[6]),t.ansi[7]=at(e.white,Zt[7]),t.ansi[8]=at(e.brightBlack,Zt[8]),t.ansi[9]=at(e.brightRed,Zt[9]),t.ansi[10]=at(e.brightGreen,Zt[10]),t.ansi[11]=at(e.brightYellow,Zt[11]),t.ansi[12]=at(e.brightBlue,Zt[12]),t.ansi[13]=at(e.brightMagenta,Zt[13]),t.ansi[14]=at(e.brightCyan,Zt[14]),t.ansi[15]=at(e.brightWhite,Zt[15]),e.extendedAnsi){let i=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let n=0;ns.index-a.index),n=[];for(let s of i){let a=this._services.get(s.id);if(!a)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${s.id._id}.`);n.push(a)}let r=i.length>0?i[0].index:t.length;if(t.length!==r)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${r+1} conflicts with ${t.length} static arguments`);return new e(...t,...n)}},UP={trace:0,debug:1,info:2,warn:3,error:4,off:5},HP="xterm.js: ",r0=class extends Oe{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),FP=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=UP[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tthis._length)for(let t=this._length;t=e;n--)this._array[this._getCyclicIndex(n+i.length)]=this._array[this._getCyclicIndex(n)];for(let n=0;nthis._maxLength){let n=this._length+i.length-this._maxLength;this._startIndex+=n,this._length=this._maxLength,this.onTrimEmitter.fire(n)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let r=t-1;r>=0;r--)this.set(e+r+i,this.get(e+r));let n=e+t+i-this._length;if(n>0)for(this._length+=n;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let n=0;n>22,i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):n]}set(t,i){this._data[t*Le+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*Le+0]=t|2097152|i[2]<<22):this._data[t*Le+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*Le+0]>>22}hasWidth(t){return this._data[t*Le+0]&12582912}getFg(t){return this._data[t*Le+1]}getBg(t){return this._data[t*Le+2]}hasContent(t){return this._data[t*Le+0]&4194303}getCodePoint(t){let i=this._data[t*Le+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*Le+0]&2097152}getString(t){let i=this._data[t*Le+0];return i&2097152?this._combined[t]:i&2097151?ma(i&2097151):""}isProtected(t){return this._data[t*Le+2]&536870912}loadCell(t,i){return Jf=t*Le,i.content=this._data[Jf+0],i.fg=this._data[Jf+1],i.bg=this._data[Jf+2],i.content&2097152&&(i.combinedData=this._combined[t]),i.bg&268435456&&(i.extended=this._extendedAttrs[t]),i}setCell(t,i){i.content&2097152&&(this._combined[t]=i.combinedData),i.bg&268435456&&(this._extendedAttrs[t]=i.extended),this._data[t*Le+0]=i.content,this._data[t*Le+1]=i.fg,this._data[t*Le+2]=i.bg}setCellFromCodepoint(t,i,n,r){r.bg&268435456&&(this._extendedAttrs[t]=r.extended),this._data[t*Le+0]=i|n<<22,this._data[t*Le+1]=r.fg,this._data[t*Le+2]=r.bg}addCodepointToCell(t,i,n){let r=this._data[t*Le+0];r&2097152?this._combined[t]+=ma(i):r&2097151?(this._combined[t]=ma(r&2097151)+ma(i),r&=-2097152,r|=2097152):r=i|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[t*Le+0]=r}insertCells(t,i,n){if(t%=this.length,t&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t-1,0,1,n),i=0;--s)this.setCell(t+i+s,this.loadCell(t+s,r));for(let s=0;sthis.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let r=new Uint32Array(n);r.set(this._data),this._data=r}for(let r=this.length;r=t&&delete this._combined[o]}let s=Object.keys(this._extendedAttrs);for(let a=0;a=t&&delete this._extendedAttrs[o]}}return this.length=t,n*4*vb=0;--t)if(this._data[t*Le+0]&4194303)return t+(this._data[t*Le+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Le+0]&4194303||this._data[t*Le+2]&50331648)return t+(this._data[t*Le+0]>>22);return 0}copyCellsFrom(t,i,n,r,s){let a=t._data;if(s)for(let l=r-1;l>=0;l--){for(let c=0;c=i&&(this._combined[c-i+n]=t._combined[c])}}translateToString(t,i,n,r){i=i??0,n=n??this.length,t&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let s="";for(;i>22||1}return r&&r.push(i),s}};_R=class vR{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=vR._nextId++,this._onDispose=this.register(new Z),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),mo(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};_R._nextId=1;GP=_R,Jt={},ho=Jt.B;Jt[0]={"`":"\u25C6",a:"\u2592",b:"\u2409",c:"\u240C",d:"\u240D",e:"\u240A",f:"\xB0",g:"\xB1",h:"\u2424",i:"\u240B",j:"\u2518",k:"\u2510",l:"\u250C",m:"\u2514",n:"\u253C",o:"\u23BA",p:"\u23BB",q:"\u2500",r:"\u23BC",s:"\u23BD",t:"\u251C",u:"\u2524",v:"\u2534",w:"\u252C",x:"\u2502",y:"\u2264",z:"\u2265","{":"\u03C0","|":"\u2260","}":"\xA3","~":"\xB7"};Jt.A={"#":"\xA3"};Jt.B=void 0;Jt[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};Jt.C=Jt[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};Jt.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};Jt.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};Jt.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};Jt.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};Jt.E=Jt[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};Jt.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};Jt.H=Jt[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};Jt["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};oM=4294967295,lM=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=Wt.clone(),this.savedCharset=ho,this.markers=[],this._nullCell=Zn.fromCharData([0,MM,1,0]),this._whitespaceCell=Zn.fromCharData([0,ga,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new mp,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new aM(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new lp),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new lp),this._whitespaceCell}getBlankLine(e,t){return new zu(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&eoM?oM:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=Wt);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new aM(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(Wt),n=0,r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+s+1?(this.ybase--,s++,this.ydisp>0&&this.ydisp--):this.lines.push(new zu(e,i)));else for(let a=this._rows;a>t;a--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r0&&(this.lines.trimStart(a),this.ybase=Math.max(this.ybase-a,0),this.ydisp=Math.max(this.ydisp-a,0),this.savedY=Math.max(this.savedY-a,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),s&&(this.y+=s),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let s=0;s.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend==="conpty"&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let i=this._optionsService.rawOptions.reflowCursorLine,n=qP(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(Wt),i);if(n.length>0){let r=KP(this.lines,n);WP(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let n=this.getNullCell(Wt),r=i;for(;r-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;a--){let o=this.lines.get(a);if(!o||!o.isWrapped&&o.getTrimmedLength()<=e)continue;let l=[o];for(;o.isWrapped&&a>0;)o=this.lines.get(--a),l.unshift(o);if(!i){let b=this.ybase+this.y;if(b>=a&&b0&&(r.push({start:a+l.length+s,newLines:f}),s+=f.length),l.push(...f);let p=u.length-1,_=u[p];_===0&&(p--,_=u[p]);let S=l.length-h-1,m=c;for(;S>=0;){let b=Math.min(m,_);if(l[p]===void 0)break;if(l[p].copyCellsFrom(l[S],m-b,_-b,b,!0),_-=b,_===0&&(p--,_=u[p]),m-=b,m===0){S--;let w=Math.max(S,0);m=ju(l,w,this._cols)}}for(let b=0;b0;)this.ybase===0?this.y0){let a=[],o=[];for(let _=0;_=0;_--)if(h&&h.start>c+d){for(let S=h.newLines.length-1;S>=0;S--)this.lines.set(_--,h.newLines[S]);_++,a.push({index:c+1,amount:h.newLines.length}),d+=h.newLines.length,h=r[++u]}else this.lines.set(_,o[c--]);let f=0;for(let _=a.length-1;_>=0;_--)a[_].index+=f,this.lines.onInsertEmitter.fire(a[_]),f+=a[_].amount;let p=Math.max(0,l+s-this.lines.maxLength);p>0&&this.lines.onTrimEmitter.fire(p)}}translateBufferLineToString(e,t,i=0,n){let r=this.lines.get(e);return r?r.translateToString(t,i,n):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e==null&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=i,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(i=>{t.line>=i.index&&(t.line+=i.amount)})),t.register(this.lines.onDelete(i=>{t.line>=i.index&&t.linei.index&&(t.line-=i.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},jP=class extends Oe{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Z),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange("scrollback",()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange("tabStopWidth",()=>this.setupTabStops()))}reset(){this._normal=new lM(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new lM(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},bR=2,yR=1,s0=class extends Oe{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,bR),this.rows=Math.max(e.rawOptions.rows||0,yR),this.buffers=this._register(new jP(e,this)),this._register(this.buffers.onBufferActivate(t=>{this._onScroll.fire(t.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let i=this.cols!==e,n=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:i,rowsChanged:n})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let i=this.buffer,n;n=this._cachedBlankLine,(!n||n.length!==this.cols||n.getFg(0)!==e.fg||n.getBg(0)!==e.bg)&&(n=i.getBlankLine(e,t),this._cachedBlankLine=n),n.isWrapped=t;let r=i.ybase+i.scrollTop,s=i.ybase+i.scrollBottom;if(i.scrollTop===0){let a=i.lines.isFull;s===i.lines.length-1?a?i.lines.recycle().copyFrom(n):i.lines.push(n.clone()):i.lines.splice(s+1,0,n.clone()),a?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{let a=s-r+1;i.lines.shiftElements(r+1,a-1,-1),i.lines.set(s,n.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t){let i=this.buffer;if(e<0){if(i.ydisp===0)return;this.isUserScrolling=!0}else e+i.ydisp>=i.ybase&&(this.isUserScrolling=!1);let n=i.ydisp;i.ydisp=Math.max(Math.min(i.ydisp+e,i.ybase),0),n!==i.ydisp&&(t||this._onScroll.fire(i.ydisp))}};s0=Rt([re(0,Yi)],s0);$l={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:pp,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},YP=["normal","bold","100","200","300","400","500","600","700","800","900"],VP=class extends Oe{constructor(e){super(),this._onOptionChange=this._register(new Z),this.onOptionChange=this._onOptionChange.event;let t={...$l};for(let i in e)if(i in t)try{let n=e[i];t[i]=this._sanitizeAndValidateOption(i,n)}catch(n){console.error(n)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(_t(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(i=>{i===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(i=>{e.indexOf(i)!==-1&&t()})}_setupOptions(){let e=i=>{if(!(i in $l))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,n)=>{if(!(i in $l))throw new Error(`No option with key "${i}"`);n=this._sanitizeAndValidateOption(i,n),this.rawOptions[i]!==n&&(this.rawOptions[i]=n,this._onOptionChange.fire(i))};for(let i in this.rawOptions){let n={get:e.bind(this,i),set:t.bind(this,i)};Object.defineProperty(this.options,i,n)}}_sanitizeAndValidateOption(e,t){switch(e){case"cursorStyle":if(t||(t=$l[e]),!XP(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=$l[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=YP.includes(t)?t:$l[e];break;case"cursorWidth":t=Math.floor(t);case"lineHeight":case"tabStopWidth":if(t<1)throw new Error(`${e} cannot be less than 1, value: ${t}`);break;case"minimumContrastRatio":t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case"scrollback":if(t=Math.min(t,4294967295),t<0)throw new Error(`${e} cannot be less than 0, value: ${t}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(t<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case"rows":case"cols":if(!t&&t!==0)throw new Error(`${e} must be numeric, value: ${t}`);break;case"windowsPty":t=t??{};break}return t}};cM=Object.freeze({insertMode:!1}),uM=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),a0=class extends Oe{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Z),this.onData=this._onData.event,this._onUserInput=this._register(new Z),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Z),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Pu(cM),this.decPrivateModes=Pu(uM)}reset(){this.modes=Pu(cM),this.decPrivateModes=Pu(uM)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace("sending data (codes)",()=>e.split("").map(n=>n.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace("sending binary (codes)",()=>e.split("").map(t=>t.charCodeAt(0))),this._onBinary.fire(e))}};a0=Rt([re(0,ji),re(1,IM),re(2,Yi)],a0);hM={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>!(e.action===32&&e.button===3)},ANY:{events:31,restrict:e=>!0}};yb=String.fromCharCode,dM={DEFAULT:e=>{let t=[bb(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${yb(t[0])}${yb(t[1])}${yb(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${bb(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${bb(e,!0)};${e.x};${e.y}${t}`}},o0=class extends Oe{constructor(e,t,i){super(),this._bufferService=e,this._coreService=t,this._optionsService=i,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Z),this.onProtocolChange=this._onProtocolChange.event;for(let n of Object.keys(hM))this.addProtocol(n,hM[n]);for(let n of Object.keys(dM))this.addEncoding(n,dM[n]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,i){if(e.deltaY===0||e.shiftKey||t===void 0||i===void 0)return 0;let n=t/i,r=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(r/=n+0,Math.abs(e.deltaY)<50&&(r*=.3),this._wheelPartialScroll+=r,r=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(r*=this._bufferService.rows),r}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return!(e.button!==t.button||e.action!==t.action||e.ctrl!==t.ctrl||e.alt!==t.alt||e.shift!==t.shift)}};o0=Rt([re(0,ji),re(1,_o),re(2,Yi)],o0);Sb=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],ZP=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];JP=class{constructor(){if(this.version="6",!Qt){Qt=new Uint8Array(65536),Qt.fill(1),Qt[0]=0,Qt.fill(0,1,32),Qt.fill(0,127,160),Qt.fill(2,4352,4448),Qt[9001]=2,Qt[9002]=2,Qt.fill(2,11904,42192),Qt[12351]=1,Qt.fill(2,44032,55204),Qt.fill(2,63744,64256),Qt.fill(2,65040,65050),Qt.fill(2,65072,65136),Qt.fill(2,65280,65377),Qt.fill(2,65504,65511);for(let e=0;e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let i=this.wcwidth(e),n=i===0&&t!==0;if(n){let r=fo.extractWidth(t);r===0?n=!1:r>i&&(i=r)}return fo.createPropertyValue(0,i,n)}},fo=class op{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Z,this.onChange=this._onChange.event;let t=new JP;this.register(t),this._active=t.version,this._activeProvider=t}static extractShouldJoin(t){return(t&1)!==0}static extractWidth(t){return t>>1&3}static extractCharKind(t){return t>>3}static createPropertyValue(t,i,n=!1){return(t&16777215)<<3|(i&3)<<1|(n?1:0)}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(t){if(!this._providers[t])throw new Error(`unknown Unicode version "${t}"`);this._active=t,this._activeProvider=this._providers[t],this._onChange.fire(t)}register(t){this._providers[t.version]=t}wcwidth(t){return this._activeProvider.wcwidth(t)}getStringCellWidth(t){let i=0,n=0,r=t.length;for(let s=0;s=r)return i+this.wcwidth(a);let c=t.charCodeAt(s);56320<=c&&c<=57343?a=(a-55296)*1024+c-56320+65536:i+=this.wcwidth(c)}let o=this.charProperties(a,n),l=op.extractWidth(o);op.extractShouldJoin(o)&&(l-=op.extractWidth(n)),i+=l,n=o}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},eU=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};Ru=2147483647,tU=256,SR=class l0{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>tU)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(t),this.length=0,this._subParams=new Int32Array(i),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(t),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let i=new l0;if(!t.length)return i;for(let n=Array.isArray(t[0])?1:0;n>8,r=this._subParamsIdx[i]&255;r-n>0&&t.push(Array.prototype.slice.call(this._subParams,n,r))}return t}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(t){if(this._digitIsSub=!1,this.length>=this.maxLength){this._rejectDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=t>Ru?Ru:t}addSubParam(t){if(this._digitIsSub=!0,!!this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(t<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=t>Ru?Ru:t,this._subParamsIdx[this.length-1]++}}hasSubParams(t){return(this._subParamsIdx[t]&255)-(this._subParamsIdx[t]>>8)>0}getSubParams(t){let i=this._subParamsIdx[t]>>8,n=this._subParamsIdx[t]&255;return n-i>0?this._subParams.subarray(i,n):null}getSubParamsAll(){let t={};for(let i=0;i>8,r=this._subParamsIdx[i]&255;r-n>0&&(t[i]=this._subParams.slice(n,r))}return t}addDigit(t){let i;if(this._rejectDigits||!(i=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[i-1];n[i-1]=~r?Math.min(r*10+t,Ru):t}},Ou=[],iU=class{constructor(){this._state=0,this._active=Ou,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Ou}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Ou,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Ou,!this._active.length)this._handlerFb(this._id,"START");else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,i){if(!this._active.length)this._handlerFb(this._id,"PUT",_p(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}start(){this.reset(),this._state=1}put(e,t,i){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,"END",e);else{let i=!1,n=this._active.length-1,r=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;n>=0&&(i=this._active[n].end(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=Ou,this._id=-1,this._state=0}}},kn=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=_p(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(i=>(this._data="",this._hitLimit=!1,i));return this._data="",this._hitLimit=!1,t}},Du=[],nU=class{constructor(){this._handlers=Object.create(null),this._active=Du,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Du}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let i=this._handlers[e];return i.push(t),{dispose:()=>{let n=i.indexOf(t);n!==-1&&i.splice(n,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Du,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Du,!this._active.length)this._handlerFb(this._ident,"HOOK",t);else for(let i=this._active.length-1;i>=0;i--)this._active[i].hook(t)}put(e,t,i){if(!this._active.length)this._handlerFb(this._ident,"PUT",_p(e,t,i));else for(let n=this._active.length-1;n>=0;n--)this._active[n].put(e,t,i)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,"UNHOOK",e);else{let i=!1,n=this._active.length-1,r=!1;if(this._stack.paused&&(n=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&i===!1){for(;n>=0&&(i=this._active[n].unhook(e),i!==!0);n--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!1,i;n--}for(;n>=0;n--)if(i=this._active[n].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=n,this._stack.fallThrough=!0,i}this._active=Du,this._ident=0}},Uu=new SR;Uu.addParam(0);pM=class{constructor(e){this._handler=e,this._data="",this._params=Uu,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Uu,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=_p(e,t,i),this._data.length>1e7&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(i=>(this._params=Uu,this._data="",this._hitLimit=!1,i));return this._params=Uu,this._data="",this._hitLimit=!1,t}},rU=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,n){this.table[t<<8|e]=i<<4|n}addMany(e,t,i,n){for(let r=0;rl),i=(o,l)=>t.slice(o,l),n=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));let s=i(0,14),a;e.setDefault(1,0),e.addMany(n,0,2,0);for(a in s)e.addMany([24,26,153,154],a,3,0),e.addMany(i(128,144),a,3,0),e.addMany(i(144,152),a,3,0),e.add(156,a,0,0),e.add(27,a,11,1),e.add(157,a,4,8),e.addMany([152,158,159],a,0,7),e.add(155,a,11,3),e.add(144,a,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(n,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(n,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(n,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Xn,0,2,0),e.add(Xn,8,5,8),e.add(Xn,6,0,6),e.add(Xn,11,0,11),e.add(Xn,13,13,13),e})(),aU=class extends Oe{constructor(e=sU){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new SR,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(t,i,n)=>{},this._executeHandlerFb=t=>{},this._csiHandlerFb=(t,i)=>{},this._escHandlerFb=t=>{},this._errorHandlerFb=t=>t,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(_t(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new iU),this._dcsParser=this._register(new nU),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let r=0;rs||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(e.final.length!==1)throw new Error("final must be a single byte");let n=e.final.charCodeAt(0);if(t[0]>n||n>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=n,i}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let i=this._identifier(e,[48,126]);this._escHandlers[i]===void 0&&(this._escHandlers[i]=[]);let n=this._escHandlers[i];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let i=this._identifier(e);this._csiHandlers[i]===void 0&&(this._csiHandlers[i]=[]);let n=this._csiHandlers[i];return n.push(t),{dispose:()=>{let r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,n,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=n,this._parseStack.chunkPos=r}parse(e,t,i){let n=0,r=0,s=0,a;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,s=this._parseStack.chunkPos+1;else{if(i===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");let o=this._parseStack.handlers,l=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(i===!1&&l>-1){for(;l>=0&&(a=o[l](this._params),a!==!0);l--)if(a instanceof Promise)return this._parseStack.handlerPos=l,a}this._parseStack.handlers=[];break;case 4:if(i===!1&&l>-1){for(;l>=0&&(a=o[l](),a!==!0);l--)if(a instanceof Promise)return this._parseStack.handlerPos=l,a}this._parseStack.handlers=[];break;case 6:if(n=e[this._parseStack.chunkPos],a=this._dcsParser.unhook(n!==24&&n!==26,i),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(n=e[this._parseStack.chunkPos],a=this._oscParser.end(n!==24&&n!==26,i),a)return a;n===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break}this._parseStack.state=0,s=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}for(let o=s;o>4){case 2:for(let d=o+1;;++d){if(d>=t||(n=e[d])<32||n>126&&n=t||(n=e[d])<32||n>126&&n=t||(n=e[d])<32||n>126&&n=t||(n=e[d])<32||n>126&&n=0&&(a=l[c](this._params),a!==!0);c--)if(a instanceof Promise)return this._preserveStack(3,l,c,r,o),a;c<0&&this._csiHandlerFb(this._collect<<8|n,this._params),this.precedingJoinState=0;break;case 8:do switch(n){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(n-48)}while(++o47&&n<60);o--;break;case 9:this._collect<<=8,this._collect|=n;break;case 10:let u=this._escHandlers[this._collect<<8|n],h=u?u.length-1:-1;for(;h>=0&&(a=u[h](),a!==!0);h--)if(a instanceof Promise)return this._preserveStack(4,u,h,r,o),a;h<0&&this._escHandlerFb(this._collect<<8|n),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|n,this._params);break;case 13:for(let d=o+1;;++d)if(d>=t||(n=e[d])===24||n===26||n===27||n>127&&n=t||(n=e[d])<32||n>127&&nthis._activeBuffer=c.activeBuffer)),this._parser.setCsiHandlerFallback((c,u)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(c),params:u.toArray()})}),this._parser.setEscHandlerFallback(c=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(c)})}),this._parser.setExecuteHandlerFallback(c=>{this._logService.debug("Unknown EXECUTE code: ",{code:c})}),this._parser.setOscHandlerFallback((c,u,h)=>{this._logService.debug("Unknown OSC code: ",{identifier:c,action:u,data:h})}),this._parser.setDcsHandlerFallback((c,u,h)=>{u==="HOOK"&&(h=h.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(c),action:u,payload:h})}),this._parser.setPrintHandler((c,u,h)=>this.print(c,u,h)),this._parser.registerCsiHandler({final:"@"},c=>this.insertChars(c)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},c=>this.scrollLeft(c)),this._parser.registerCsiHandler({final:"A"},c=>this.cursorUp(c)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},c=>this.scrollRight(c)),this._parser.registerCsiHandler({final:"B"},c=>this.cursorDown(c)),this._parser.registerCsiHandler({final:"C"},c=>this.cursorForward(c)),this._parser.registerCsiHandler({final:"D"},c=>this.cursorBackward(c)),this._parser.registerCsiHandler({final:"E"},c=>this.cursorNextLine(c)),this._parser.registerCsiHandler({final:"F"},c=>this.cursorPrecedingLine(c)),this._parser.registerCsiHandler({final:"G"},c=>this.cursorCharAbsolute(c)),this._parser.registerCsiHandler({final:"H"},c=>this.cursorPosition(c)),this._parser.registerCsiHandler({final:"I"},c=>this.cursorForwardTab(c)),this._parser.registerCsiHandler({final:"J"},c=>this.eraseInDisplay(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},c=>this.eraseInDisplay(c,!0)),this._parser.registerCsiHandler({final:"K"},c=>this.eraseInLine(c,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},c=>this.eraseInLine(c,!0)),this._parser.registerCsiHandler({final:"L"},c=>this.insertLines(c)),this._parser.registerCsiHandler({final:"M"},c=>this.deleteLines(c)),this._parser.registerCsiHandler({final:"P"},c=>this.deleteChars(c)),this._parser.registerCsiHandler({final:"S"},c=>this.scrollUp(c)),this._parser.registerCsiHandler({final:"T"},c=>this.scrollDown(c)),this._parser.registerCsiHandler({final:"X"},c=>this.eraseChars(c)),this._parser.registerCsiHandler({final:"Z"},c=>this.cursorBackwardTab(c)),this._parser.registerCsiHandler({final:"`"},c=>this.charPosAbsolute(c)),this._parser.registerCsiHandler({final:"a"},c=>this.hPositionRelative(c)),this._parser.registerCsiHandler({final:"b"},c=>this.repeatPrecedingCharacter(c)),this._parser.registerCsiHandler({final:"c"},c=>this.sendDeviceAttributesPrimary(c)),this._parser.registerCsiHandler({prefix:">",final:"c"},c=>this.sendDeviceAttributesSecondary(c)),this._parser.registerCsiHandler({final:"d"},c=>this.linePosAbsolute(c)),this._parser.registerCsiHandler({final:"e"},c=>this.vPositionRelative(c)),this._parser.registerCsiHandler({final:"f"},c=>this.hVPosition(c)),this._parser.registerCsiHandler({final:"g"},c=>this.tabClear(c)),this._parser.registerCsiHandler({final:"h"},c=>this.setMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"h"},c=>this.setModePrivate(c)),this._parser.registerCsiHandler({final:"l"},c=>this.resetMode(c)),this._parser.registerCsiHandler({prefix:"?",final:"l"},c=>this.resetModePrivate(c)),this._parser.registerCsiHandler({final:"m"},c=>this.charAttributes(c)),this._parser.registerCsiHandler({final:"n"},c=>this.deviceStatus(c)),this._parser.registerCsiHandler({prefix:"?",final:"n"},c=>this.deviceStatusPrivate(c)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},c=>this.softReset(c)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},c=>this.setCursorStyle(c)),this._parser.registerCsiHandler({final:"r"},c=>this.setScrollRegion(c)),this._parser.registerCsiHandler({final:"s"},c=>this.saveCursor(c)),this._parser.registerCsiHandler({final:"t"},c=>this.windowOptions(c)),this._parser.registerCsiHandler({final:"u"},c=>this.restoreCursor(c)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},c=>this.insertColumns(c)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},c=>this.deleteColumns(c)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},c=>this.selectProtected(c)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},c=>this.requestMode(c,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},c=>this.requestMode(c,!1)),this._parser.setExecuteHandler(F.BEL,()=>this.bell()),this._parser.setExecuteHandler(F.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(F.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(F.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(F.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(F.BS,()=>this.backspace()),this._parser.setExecuteHandler(F.HT,()=>this.tab()),this._parser.setExecuteHandler(F.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(F.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(qu.IND,()=>this.index()),this._parser.setExecuteHandler(qu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(qu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new kn(c=>(this.setTitle(c),this.setIconName(c),!0))),this._parser.registerOscHandler(1,new kn(c=>this.setIconName(c))),this._parser.registerOscHandler(2,new kn(c=>this.setTitle(c))),this._parser.registerOscHandler(4,new kn(c=>this.setOrReportIndexedColor(c))),this._parser.registerOscHandler(8,new kn(c=>this.setHyperlink(c))),this._parser.registerOscHandler(10,new kn(c=>this.setOrReportFgColor(c))),this._parser.registerOscHandler(11,new kn(c=>this.setOrReportBgColor(c))),this._parser.registerOscHandler(12,new kn(c=>this.setOrReportCursorColor(c))),this._parser.registerOscHandler(104,new kn(c=>this.restoreIndexedColor(c))),this._parser.registerOscHandler(110,new kn(c=>this.restoreFgColor(c))),this._parser.registerOscHandler(111,new kn(c=>this.restoreBgColor(c))),this._parser.registerOscHandler(112,new kn(c=>this.restoreCursorColor(c))),this._parser.registerEscHandler({final:"7"},()=>this.saveCursor()),this._parser.registerEscHandler({final:"8"},()=>this.restoreCursor()),this._parser.registerEscHandler({final:"D"},()=>this.index()),this._parser.registerEscHandler({final:"E"},()=>this.nextLine()),this._parser.registerEscHandler({final:"H"},()=>this.tabSet()),this._parser.registerEscHandler({final:"M"},()=>this.reverseIndex()),this._parser.registerEscHandler({final:"="},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:">"},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:"c"},()=>this.fullReset()),this._parser.registerEscHandler({final:"n"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"o"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"|"},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:"}"},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:"~"},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:"%",final:"@"},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:"%",final:"G"},()=>this.selectDefaultCharset());for(let c in Jt)this._parser.registerEscHandler({intermediates:"(",final:c},()=>this.selectCharset("("+c)),this._parser.registerEscHandler({intermediates:")",final:c},()=>this.selectCharset(")"+c)),this._parser.registerEscHandler({intermediates:"*",final:c},()=>this.selectCharset("*"+c)),this._parser.registerEscHandler({intermediates:"+",final:c},()=>this.selectCharset("+"+c)),this._parser.registerEscHandler({intermediates:"-",final:c},()=>this.selectCharset("-"+c)),this._parser.registerEscHandler({intermediates:".",final:c},()=>this.selectCharset("."+c)),this._parser.registerEscHandler({intermediates:"/",final:c},()=>this.selectCharset("/"+c));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(c=>(this._logService.error("Parsing error: ",c),c)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new pM((c,u)=>this.requestStatusString(c,u)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,i,n){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=n}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((t,i)=>setTimeout(()=>i("#SLOW_TIMEOUT"),vM))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${vM} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,n=this._activeBuffer.x,r=this._activeBuffer.y,s=0,a=this._parseStack.paused;if(a){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;n=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>pa&&(s=this._parseStack.position+pa)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e=="string"?` "${e}"`:` "${Array.prototype.map.call(e,c=>String.fromCharCode(c)).join("")}"`}`),this._logService.logLevel===0&&this._logService.trace("parsing data (codes)",typeof e=="string"?e.split("").map(c=>c.charCodeAt(0)):e),this._parseBuffer.lengthpa)for(let c=s;c0&&h.getWidth(this._activeBuffer.x-1)===2&&h.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let d=this._parser.precedingJoinState;for(let f=t;fo){if(l){let m=h,g=this._activeBuffer.x-S;for(this._activeBuffer.x=S,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),h=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),S>0&&h instanceof zu&&h.copyCellsFrom(m,g,0,S,!1);g=0;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(c&&(h.insertCells(this._activeBuffer.x,r-S,this._activeBuffer.getNullCell(u)),h.getWidth(o-1)===2&&h.setCellFromCodepoint(o-1,0,1,u)),h.setCellFromCodepoint(this._activeBuffer.x++,n,r,u),r>0)for(;--r;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=d,this._activeBuffer.x0&&h.getWidth(this._activeBuffer.x)===0&&!h.hasContent(this._activeBuffer.x)&&h.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final==="t"&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,i=>_M(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new pM(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new kn(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,n=!1,r=!1){let s=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);s.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),r),n&&(s.isWrapped=!1)}_resetBufferLine(e,t=!1){let i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let i;switch(e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(i=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,i-1);i--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+i)?.getTrimmedLength(););for(;i>=0;i--)this._bufferService.scroll(this._eraseAttrData())}else{for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let n=this._activeBuffer.lines.length-this._bufferService.rows;n>0&&(this._activeBuffer.lines.trimStart(n),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-n,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-n,0),this._onScroll.fire(0));break}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t);break}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let l=o;for(let c=1;c0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(F.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(F.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(F.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(F.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(F.ESC+"[>83;40003;0c")),!0}_is(e){return(this._optionsService.rawOptions.termName+"").indexOf(e)===0}setMode(e){for(let t=0;t(_[_.NOT_RECOGNIZED=0]="NOT_RECOGNIZED",_[_.SET=1]="SET",_[_.RESET=2]="RESET",_[_.PERMANENTLY_SET=3]="PERMANENTLY_SET",_[_.PERMANENTLY_RESET=4]="PERMANENTLY_RESET"))(i||(i={}));let n=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:s}=this._coreMouseService,a=this._coreService,{buffers:o,cols:l}=this._bufferService,{active:c,alt:u}=o,h=this._optionsService.rawOptions,d=(_,S)=>(a.triggerDataEvent(`${F.ESC}[${t?"":"?"}${_};${S}$y`),!0),f=_=>_?1:2,p=e.params[0];return t?p===2?d(p,4):p===4?d(p,f(a.modes.insertMode)):p===12?d(p,3):p===20?d(p,f(h.convertEol)):d(p,0):p===1?d(p,f(n.applicationCursorKeys)):p===3?d(p,h.windowOptions.setWinLines?l===80?2:l===132?1:0:0):p===6?d(p,f(n.origin)):p===7?d(p,f(n.wraparound)):p===8?d(p,3):p===9?d(p,f(r==="X10")):p===12?d(p,f(h.cursorBlink)):p===25?d(p,f(!a.isCursorHidden)):p===45?d(p,f(n.reverseWraparound)):p===66?d(p,f(n.applicationKeypad)):p===67?d(p,4):p===1e3?d(p,f(r==="VT200")):p===1002?d(p,f(r==="DRAG")):p===1003?d(p,f(r==="ANY")):p===1004?d(p,f(n.sendFocus)):p===1005?d(p,4):p===1006?d(p,f(s==="SGR")):p===1015?d(p,4):p===1016?d(p,f(s==="SGR_PIXELS")):p===1048?d(p,1):p===47||p===1047||p===1049?d(p,f(c===u)):p===2004?d(p,f(n.bracketedPasteMode)):p===2026?d(p,f(n.synchronizedOutput)):d(p,0)}_updateAttrColor(e,t,i,n,r){return t===2?(e|=50331648,e&=-16777216,e|=Yu.fromColorRGB([i,n,r])):t===5&&(e&=-50331904,e|=33554432|i&255),e}_extractColor(e,t,i){let n=[0,0,-1,0,0,0],r=0,s=0;do{if(n[s+r]=e.params[t+s],e.hasSubParams(t+s)){let a=e.getSubParams(t+s),o=0;do n[1]===5&&(r=1),n[s+o+1+r]=a[o];while(++o=2||n[1]===2&&s+r>=5)break;n[1]&&(r=1)}while(++s+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=Wt.fg,e.bg=Wt.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,i,n=this._curAttrData;for(let r=0;r=30&&i<=37?(n.fg&=-50331904,n.fg|=16777216|i-30):i>=40&&i<=47?(n.bg&=-50331904,n.bg|=16777216|i-40):i>=90&&i<=97?(n.fg&=-50331904,n.fg|=16777216|i-90|8):i>=100&&i<=107?(n.bg&=-50331904,n.bg|=16777216|i-100|8):i===0?this._processSGR0(n):i===1?n.fg|=134217728:i===3?n.bg|=67108864:i===4?(n.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,n)):i===5?n.fg|=536870912:i===7?n.fg|=67108864:i===8?n.fg|=1073741824:i===9?n.fg|=2147483648:i===2?n.bg|=134217728:i===21?this._processUnderline(2,n):i===22?(n.fg&=-134217729,n.bg&=-134217729):i===23?n.bg&=-67108865:i===24?(n.fg&=-268435457,this._processUnderline(0,n)):i===25?n.fg&=-536870913:i===27?n.fg&=-67108865:i===28?n.fg&=-1073741825:i===29?n.fg&=2147483647:i===39?(n.fg&=-67108864,n.fg|=Wt.fg&16777215):i===49?(n.bg&=-67108864,n.bg|=Wt.bg&16777215):i===38||i===48||i===58?r+=this._extractColor(e,r,n):i===53?n.bg|=1073741824:i===55?n.bg&=-1073741825:i===59?(n.extended=n.extended.clone(),n.extended.underlineColor=-1,n.updateExtended()):i===100?(n.fg&=-67108864,n.fg|=Wt.fg&16777215,n.bg&=-67108864,n.bg|=Wt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${F.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${F.ESC}[${t};${i}R`);break}return!0}deviceStatusPrivate(e){switch(e.params[0]){case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${F.ESC}[?${t};${i}R`);break;case 15:break;case 25:break;case 26:break;case 53:break}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=Wt.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle="block";break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle="underline";break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle="bar";break}let i=t%2===1;this._coreService.decPrivateModes.cursorBlink=i}return!0}setScrollRegion(e){let t=e.params[0]||1,i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||i===0)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!_M(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${F.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>gM&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>gM&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop());break}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],i=e.split(";");for(;i.length>1;){let n=i.shift(),r=i.shift();if(/^\d+$/.exec(n)){let s=parseInt(n);if(yM(s))if(r==="?")t.push({type:0,index:s});else{let a=mM(r);a&&t.push({type:1,index:s,color:a})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(";");if(t===-1)return!0;let i=e.slice(0,t).trim(),n=e.slice(t+1);return n?this._createHyperlink(i,n):i.trim()?!1:this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let i=e.split(":"),n,r=i.findIndex(s=>s.startsWith("id="));return r!==-1&&(n=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:n,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let i=e.split(";");for(let n=0;n=this._specialColors.length);++n,++t)if(i[n]==="?")this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=mM(i[n]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],i=e.split(";");for(let n=0;n=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=Wt.clone(),this._eraseAttrDataInternal=Wt.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Zn;e.content=1<<22|69,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${F.ESC}${a}${F.ESC}\\`),!0),n=this._bufferService.buffer,r=this._optionsService.rawOptions;return i(e==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e==='"p'?'P1$r61;1"p':e==="r"?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e==="m"?"P1$r0m":e===" q"?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},c0=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(bM=e,e=t,t=bM),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};c0=Rt([re(0,ji)],c0);dU=5e7,SM=12,fU=50,pU=class extends Oe{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let i;for(;i=this._writeBuffer.shift();){this._action(i);let n=this._callbacks.shift();n&&n()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>dU)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let i=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let n=this._writeBuffer[this._bufferOffset],r=this._action(n,t);if(r){let a=o=>performance.now()-i>=SM?setTimeout(()=>this._innerWrite(0,o)):this._innerWrite(i,o);r.catch(o=>(queueMicrotask(()=>{throw o}),Promise.resolve(!1))).then(a);return}let s=this._callbacks[this._bufferOffset];if(s&&s(),this._bufferOffset++,this._pendingData-=n.length,performance.now()-i>=SM)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>fU&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},u0=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let o=t.addMarker(t.ybase+t.y),l={data:e,id:this._nextId++,lines:[o]};return o.onDispose(()=>this._removeMarkerFromLink(l,o)),this._dataByLinkId.set(l.id,l),l.id}let i=e,n=this._getEntryIdKey(i),r=this._entriesWithId.get(n);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;let s=t.addMarker(t.ybase+t.y),a={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[s]};return s.onDispose(()=>this._removeMarkerFromLink(a,s)),this._entriesWithId.set(a.key,a),this._dataByLinkId.set(a.id,a),a.id}addLineToLink(e,t){let i=this._dataByLinkId.get(e);if(i&&i.lines.every(n=>n.line!==t)){let n=this._bufferService.buffer.addMarker(t);i.lines.push(n),n.onDispose(()=>this._removeMarkerFromLink(i,n))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let i=e.lines.indexOf(t);i!==-1&&(e.lines.splice(i,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};u0=Rt([re(0,ji)],u0);wM=!1,mU=class extends Oe{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new jl),this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onData=this._register(new Z),this.onData=this._onData.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Z),this._instantiationService=new PP,this.optionsService=this._register(new VP(e)),this._instantiationService.setService(Yi,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(s0)),this._instantiationService.setService(ji,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(r0)),this._instantiationService.setService(IM,this._logService),this.coreService=this._register(this._instantiationService.createInstance(a0)),this._instantiationService.setService(_o,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(o0)),this._instantiationService.setService(LM,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(fo)),this._instantiationService.setService(u4,this.unicodeService),this._charsetService=this._instantiationService.createInstance(eU),this._instantiationService.setService(c4,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(u0),this._instantiationService.setService(BM,this._oscLinkService),this._inputHandler=this._register(new hU(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(hi.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(hi.forward(this._bufferService.onResize,this._onResize)),this._register(hi.forward(this.coreService.onData,this._onData)),this._register(hi.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new pU((t,i)=>this._inputHandler.parse(t,i))),this._register(hi.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Z),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!wM&&(this._logService.warn("writeSync is unreliable and will be removed soon."),wM=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,bR),t=Math.max(t,yR),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend==="conpty"&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(fM.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(fM(this._bufferService),!1))),this._windowsWrappingHeuristics.value=_t(()=>{for(let t of e)t.dispose()})}}},gU={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};Lt=0,vU=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new mp,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new mp,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((r,s)=>this._getKey(r)-this._getKey(s)),t=0,i=0,n=new Array(this._array.length+this._insertedValues.length);for(let r=0;r=this._array.length||this._getKey(e[t])<=this._getKey(this._array[i])?(n[r]=e[t],t++):n[r]=this._array[i++];this._array=n,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(Lt=this._search(t),Lt===-1)||this._getKey(this._array[Lt])!==t)return!1;do if(this._array[Lt]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(Lt),!0;while(++Ltr-s),t=0,i=new Array(this._array.length-e.length),n=0;for(let r=0;r0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(Lt=this._search(e),!(Lt<0||Lt>=this._array.length)&&this._getKey(this._array[Lt])===e))do yield this._array[Lt];while(++Lt=this._array.length)&&this._getKey(this._array[Lt])===e))do t(this._array[Lt]);while(++Lt=t;){let n=t+i>>1,r=this._getKey(this._array[n]);if(r>e)i=n-1;else if(r0&&this._getKey(this._array[n-1])===e;)n--;return n}}return t}},xb=0,xM=0,bU=class extends Oe{constructor(){super(),this._decorations=new vU(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Z),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Z),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(_t(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new yU(e);if(t){let i=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),i.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){let n=0,r=0;for(let s of this._decorations.getKeyIterator(t))n=s.options.x??0,r=n+(s.options.width??1),e>=n&&e{xb=r.options.x??0,xM=xb+(r.options.width??1),e>=xb&&e=this._debounceThresholdMS)this._lastRefreshMs=n,this._innerRefresh();else if(!this._additionalRefreshRequested){let r=n-this._lastRefreshMs,s=this._debounceThresholdMS-r;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},s)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},EM=20,CM=!1,gp=class extends Oe{constructor(e,t,i,n){super(),this._terminal=e,this._coreBrowserService=i,this._renderService=n,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="";let r=this._coreBrowserService.mainDocument;this._accessibilityContainer=r.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=r.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let s=0;sthis._handleBoundaryFocus(s,0),this._bottomBoundaryFocusListener=s=>this._handleBoundaryFocus(s,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=r.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new wU(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");CM?(this._accessibilityContainer.classList.add("debug"),this._rowContainer.classList.add("debug"),this._debugRootContainer=r.createElement("div"),this._debugRootContainer.classList.add("xterm"),this._debugRootContainer.appendChild(r.createTextNode("------start a11y------")),this._debugRootContainer.appendChild(this._accessibilityContainer),this._debugRootContainer.appendChild(r.createTextNode("------end a11y------")),this._terminal.element.insertAdjacentElement("afterend",this._debugRootContainer)):this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this._register(this._terminal.onResize(s=>this._handleResize(s.rows))),this._register(this._terminal.onRender(s=>this._refreshRows(s.start,s.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(s=>this._handleChar(s))),this._register(this._terminal.onLineFeed(()=>this._handleChar(` +`))),this._register(this._terminal.onA11yTab(s=>this._handleTab(s))),this._register(this._terminal.onKey(s=>this._handleKey(s.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Se(r,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(_t(()=>{CM?this._debugRootContainer.remove():this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===EM+1&&(this._liveRegion.textContent+=Cb.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let i=this._terminal.buffer,n=i.lines.length.toString();for(let r=e;r<=t;r++){let s=i.lines.get(i.ydisp+r),a=[],o=s?.translateToString(!0,void 0,void 0,a)||"",l=(i.ydisp+r+1).toString(),c=this._rowElements[r];c&&(o.length===0?(c.textContent="\xA0",this._rowColumns.set(c,[0,1])):(c.textContent=o,this._rowColumns.set(c,a)),c.setAttribute("aria-posinset",l),c.setAttribute("aria-setsize",n),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let i=e.target,n=this._rowElements[t===0?1:this._rowElements.length-2],r=i.getAttribute("aria-posinset"),s=t===0?"1":`${this._terminal.buffer.lines.length}`;if(r===s||e.relatedTarget!==n)return;let a,o;if(t===0?(a=i,o=this._rowElements.pop(),this._rowContainer.removeChild(o)):(a=this._rowElements.shift(),o=i,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),o.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let l=this._createAccessibilityTreeNode();this._rowElements.unshift(l),this._rowContainer.insertAdjacentElement("afterbegin",l)}else{let l=this._createAccessibilityTreeNode();this._rowElements.push(l),this._rowContainer.appendChild(l)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},i={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===i.node&&t.offset>i.offset)&&([t,i]=[i,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let n=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(n)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:n,offset:n.textContent?.length??0}),!this._rowContainer.contains(i.node))return;let r=({node:o,offset:l})=>{let c=o instanceof Text?o.parentNode:o,u=parseInt(c?.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let h=this._rowColumns.get(c);if(!h)return console.warn("columns is null. Race condition?"),null;let d=l=this._terminal.cols&&(++u,d=0),{row:u,column:d}},s=r(t),a=r(i);if(!(!s||!a)){if(s.row>a.row||s.row===a.row&&s.column>=a.column)throw new Error("invalid range");this._terminal.select(s.column,s.row,(a.row-s.row)*this._terminal.cols-s.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;te;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{mo(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Se(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Se(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(Se(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(Se(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let i=e.composedPath();for(let n=0;n{n?.forEach(r=>{r.link.dispose&&r.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let i=!1;for(let[n,r]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(n)&&(i=this._checkLinkProviderResult(n,e,i)):r.provideLinks(e.y,s=>{if(this._isMouseOut)return;let a=s?.map(o=>({link:o}));this._activeProviderReplies?.set(n,a),i=this._checkLinkProviderResult(n,e,i),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let i=new Set;for(let n=0;ne?this._bufferService.cols:a.link.range.end.x;for(let c=o;c<=l;c++){if(i.has(c)){r.splice(s--,1);break}i.add(c)}}}}_checkLinkProviderResult(e,t,i){if(!this._activeProviderReplies)return i;let n=this._activeProviderReplies.get(e),r=!1;for(let s=0;sthis._linkAtPosition(a.link,t));s&&(i=!0,this._handleNewLink(s))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let s=0;sthis._linkAtPosition(o.link,t));if(a){i=!0,this._handleNewLink(a);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&xU(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,mo(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0?!0:e.link.decorations.underline,pointerCursor:e.link.decorations===void 0?!0:e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:i=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:i=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let n=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=n&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(n,r),this._lastMouseEvent)){let s=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);s&&this._askForLink(s,!1)}})))}_linkHover(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){let i=e.range,n=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-n-1,i.end.x,i.end.y-n-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){let i=e.range.start.y*this._bufferService.cols+e.range.start.x,n=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=n}_positionFromMouseEvent(e,t,i){let n=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(n)return{x:n[0],y:n[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,n,r){return{x1:e,y1:t,x2:i,y2:n,cols:this._bufferService.cols,fg:r}}};h0=Rt([re(1,f0),re(2,Ss),re(3,ji),re(4,PM)],h0);EU=class extends mU{constructor(e={}){super(e),this._linkifier=this._register(new jl),this.browser=lR,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new jl),this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Z),this.onKey=this._onKey.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Z),this.onBell=this._onBell.event,this._onFocus=this._register(new Z),this._onBlur=this._register(new Z),this._onA11yCharEmitter=this._register(new Z),this._onA11yTabEmitter=this._register(new Z),this._onWillOpen=this._register(new Z),this._setup(),this._decorationService=this._instantiationService.createInstance(bU),this._instantiationService.setService(Vu,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(dP),this._instantiationService.setService(PM,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Tb)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(t=>this.refresh(t?.start??0,t?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(t=>this._reportWindowsOptions(t))),this._register(this._inputHandler.onColor(t=>this._handleColorEvent(t))),this._register(hi.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(hi.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(hi.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(hi.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(t=>this._afterResize(t.cols,t.rows))),this._register(_t(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let i,n="";switch(t.index){case 256:i="foreground",n="10";break;case 257:i="background",n="11";break;case 258:i="cursor",n="12";break;default:i="ansi",n="4;"+t.index}switch(t.type){case 0:let r=gt.toColorRGB(i==="ansi"?this._themeService.colors.ansi[t.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${F.ESC}]${n};${cU(r)}${Vb.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(s=>s.ansi[t.index]=It.toColor(...t.color));else{let s=i;this._themeService.modifyColors(a=>a[s]=It.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(gp,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(F.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(F.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let i=Math.min(this.buffer.x,this.cols-1),n=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),s=this._renderService.dimensions.css.cell.width*r,a=this.buffer.y*this._renderService.dimensions.css.cell.height,o=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=o+"px",this.textarea.style.top=a+"px",this.textarea.style.width=s+"px",this.textarea.style.height=n+"px",this.textarea.style.lineHeight=n+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(Se(this.element,"copy",t=>{this.hasSelection()&&n4(t,this._selectionService)}));let e=t=>r4(t,this.textarea,this.coreService,this.optionsService);this._register(Se(this.textarea,"paste",e)),this._register(Se(this.element,"paste",e)),cR?this._register(Se(this.element,"mousedown",t=>{t.button===2&&xA(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Se(this.element,"contextmenu",t=>{xA(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),S0&&this._register(Se(this.element,"auxclick",t=>{t.button===1&&AM(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Se(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(Se(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(Se(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(Se(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(Se(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(Se(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(Se(this.textarea,"input",e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw new Error("Terminal requires a parent element.");if(e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(Se(this.screenElement,"mousemove",r=>this.updateCursorStyle(r))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Eb.get()),dR||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(uP,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ys,this._coreBrowserService),this._register(Se(this.textarea,"focus",r=>this._handleTextAreaFocus(r))),this._register(Se(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Jb,this._document,this._helperContainer),this._instantiationService.setService(vp,this._charSizeService),this._themeService=this._instantiationService.createInstance(n0),this._instantiationService.setService(Yl,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(fp),this._instantiationService.setService(zM,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(t0,this.rows,this.screenElement)),this._instantiationService.setService(Ss,this._renderService),this._register(this._renderService.onRenderedViewportChange(r=>this._onRender.fire(r))),this.onResize(r=>this._renderService.resize(r.cols,r.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(Xb,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(e0),this._instantiationService.setService(f0,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(h0,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(jb,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(r=>{super.scrollLines(r,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(i0,this.element,this.screenElement,n)),this._instantiationService.setService(d4,this._selectionService),this._register(this._selectionService.onRequestScrollLines(r=>this.scrollLines(r.amount,r.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(r=>this._renderService.handleSelectionChanged(r.start,r.end,r.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(r=>{this.textarea.value=r,this.textarea.focus(),this.textarea.select()})),this._register(hi.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(Yb,this.screenElement)),this._register(Se(this.element,"mousedown",r=>this._selectionService.handleMouseDown(r))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(gp,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",r=>this._handleScreenReaderModeOptionChange(r))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(dp,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",r=>{!this._overviewRulerRenderer&&r&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(dp,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Qb,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function i(s){let a=e._mouseService.getMouseReportCoords(s,e.screenElement);if(!a)return!1;let o,l;switch(s.overrideType||s.type){case"mousemove":l=32,s.buttons===void 0?(o=3,s.button!==void 0&&(o=s.button<3?s.button:3)):o=s.buttons&1?0:s.buttons&4?1:s.buttons&2?2:3;break;case"mouseup":l=0,o=s.button<3?s.button:3;break;case"mousedown":l=1,o=s.button<3?s.button:3;break;case"wheel":if(e._customWheelEventHandler&&e._customWheelEventHandler(s)===!1)return!1;let c=s.deltaY;if(c===0||e.coreMouseService.consumeWheelEvent(s,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;l=c<0?0:1,o=4;break;default:return!1}return l===void 0||o===void 0||o>4?!1:e.coreMouseService.triggerMouseEvent({col:a.col,row:a.row,x:a.x,y:a.y,button:o,action:l,ctrl:s.ctrlKey,alt:s.altKey,shift:s.shiftKey})}let n={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:s=>(i(s),s.buttons||(this._document.removeEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.removeEventListener("mousemove",n.mousedrag)),this.cancel(s)),wheel:s=>(i(s),this.cancel(s,!0)),mousedrag:s=>{s.buttons&&i(s)},mousemove:s=>{s.buttons||i(s)}};this._register(this.coreMouseService.onProtocolChange(s=>{s?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(s)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),s&8?n.mousemove||(t.addEventListener("mousemove",r.mousemove),n.mousemove=r.mousemove):(t.removeEventListener("mousemove",n.mousemove),n.mousemove=null),s&16?n.wheel||(t.addEventListener("wheel",r.wheel,{passive:!1}),n.wheel=r.wheel):(t.removeEventListener("wheel",n.wheel),n.wheel=null),s&2?n.mouseup||(n.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",n.mouseup),n.mouseup=null),s&4?n.mousedrag||(n.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",n.mousedrag),n.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Se(t,"mousedown",s=>{if(s.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(s)))return i(s),n.mouseup&&this._document.addEventListener("mouseup",n.mouseup),n.mousedrag&&this._document.addEventListener("mousemove",n.mousedrag),this.cancel(s)})),this._register(Se(t,"wheel",s=>{if(!n.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(s)===!1)return!1;if(!this.buffer.hasScrollback){if(s.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(s,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(s,!0);let a=F.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(s.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(a,!0),this.cancel(s,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){NM(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key==="Dead"||e.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=_U(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),i.type===3||i.type===2){let n=this.rows-1;return this.scrollLines(i.type===2?-n:n),this.cancel(e,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===F.ETX||i.key===F.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return t.type==="keypress"?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(CU(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType==="insertText"&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){if(e===this.cols&&t===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Zn)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}},kM=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new TU(t)}getNullCell(){return new Zn}},NU=class extends Oe{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Z),this.onBufferChange=this._onBufferChange.event,this._normal=new kM(this._core.buffers.normal,"normal"),this._alternate=new kM(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},AU=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,i=>t(i.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(i,n)=>t(i,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},MU=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},RU=["cols","rows"],Ur=0,wR=class extends Oe{constructor(e){super(),this._core=this._register(new EU(e)),this._addonManager=this._register(new kU),this._publicOptions={...this._core.options};let t=n=>this._core.options[n],i=(n,r)=>{this._checkReadonlyOptions(n),this._core.options[n]=r};for(let n in this._core.options){let r={get:t.bind(this,n),set:i.bind(this,n)};Object.defineProperty(this._publicOptions,n,r)}}_checkReadonlyOptions(e){if(RU.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new AU(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new MU(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new NU(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any";break}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return Eb.get()},set promptLabel(e){Eb.set(e)},get tooMuchOutput(){return Cb.get()},set tooMuchOutput(e){Cb.set(e)}}}_verifyIntegers(...e){for(Ur of e)if(Ur===1/0||isNaN(Ur)||Ur%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Ur of e)if(Ur&&(Ur===1/0||isNaN(Ur)||Ur%1!==0||Ur<0))throw new Error("This API only accepts positive integers")}}});var OU,DU,ER,CR=se(()=>{OU=2,DU=1,ER=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,i=window.getComputedStyle(this._terminal.element.parentElement),n=parseInt(i.getPropertyValue("height")),r=Math.max(0,parseInt(i.getPropertyValue("width"))),s=window.getComputedStyle(this._terminal.element),a={top:parseInt(s.getPropertyValue("padding-top")),bottom:parseInt(s.getPropertyValue("padding-bottom")),right:parseInt(s.getPropertyValue("padding-right")),left:parseInt(s.getPropertyValue("padding-left"))},o=a.top+a.bottom,l=a.right+a.left,c=n-o,u=r-l-t;return{cols:Math.max(OU,Math.floor(u/e.css.cell.width)),rows:Math.max(DU,Math.floor(c/e.css.cell.height))}}}});var kR=se(()=>{});function LU(){let e=document.documentElement.dataset.theme;return e==="dark"?!0:e==="light"?!1:window.matchMedia("(prefers-color-scheme: dark)").matches}function w0(){return LU()?{background:"#0c0c0c",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#0c0c0c",selectionBackground:"#264f78",selectionForeground:"#ffffff",black:"#0c0c0c",red:"#f14c4c",green:"#23d18b",yellow:"#f5f543",blue:"#3b8eea",magenta:"#d670d6",cyan:"#29b8db",white:"#cccccc",brightBlack:"#666666",brightRed:"#f14c4c",brightGreen:"#23d18b",brightYellow:"#f5f543",brightBlue:"#3b8eea",brightMagenta:"#d670d6",brightCyan:"#29b8db",brightWhite:"#ffffff"}:{background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff",selectionForeground:"#1e1e1e",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"}}var TR=se(()=>{});function NR(){let{projects:e,threads:t}=rt(),i=le(),n=t.find(S=>S.id===i.currentThreadId)??null,r=n?e.find(S=>S.id===n.projectId):e.find(S=>S.id===i.currentProjectId),s=r?.id??null,[a,o]=(0,fi.useState)([]),[l,c]=(0,fi.useState)(null),[u,h]=(0,fi.useState)(null),d=(0,fi.useCallback)(async()=>{if(!s){o([]);return}try{let S=await V.call("terminal.list",{projectId:s});o(S),c(m=>m&&S.some(g=>g.id===m)?m:S[0]?.id??null)}catch{}},[s]);(0,fi.useEffect)(()=>{d()},[d]),(0,fi.useEffect)(()=>V.subscribe("terminals",(m,g)=>{let b=g;b?.type==="terminal.exit"&&(o(w=>w.filter(E=>E.id!==b.id)),c(w=>w===b.id?null:w))}),[]);let f=async()=>{if(s)try{let S=await V.call("terminal.create",{projectId:s,cols:100,rows:28});await d(),c(S.id)}catch(S){we(v("terminal.failNew")+ht(S),!0)}},p=async S=>{try{await V.call("terminal.kill",{id:S.id}),o(m=>m.filter(g=>g.id!==S.id)),c(m=>m===S.id?null:m)}catch(m){we(v("terminal.failKill")+ht(m),!0)}};if(!r)return(0,ei.jsx)("div",{className:"pn-empty",children:v("panel.pickProject")});let _=a.find(S=>S.id===l)??null;return(0,ei.jsxs)(ei.Fragment,{children:[(0,ei.jsxs)("div",{className:"tm-tabs",children:[a.map(S=>(0,ei.jsxs)("button",{className:`tm-tab${S.id===l?" on":""}`,onClick:()=>c(S.id),title:S.title,children:[S.title,(0,ei.jsx)("span",{className:"tm-x",onClick:m=>{m.stopPropagation(),h(S)},children:"\xD7"})]},S.id)),(0,ei.jsx)("button",{className:"ibtn",title:v("terminal.new"),onClick:()=>{f()},children:(0,ei.jsx)(pe,{name:"plus",size:14})})]}),_?.simple&&(0,ei.jsx)("div",{className:"tm-note",children:v("terminal.simpleNote")}),(0,ei.jsxs)("div",{className:"tm-body",children:[a.length===0&&(0,ei.jsxs)("div",{className:"pn-empty",children:[v("terminal.noTerm"),(0,ei.jsx)("div",{style:{marginTop:8},children:(0,ei.jsx)("button",{className:"btn primary",onClick:()=>{f()},children:v("terminal.new")})})]}),a.map(S=>(0,ei.jsx)(IU,{term:S,visible:S.id===l},S.id))]}),u&&(0,ei.jsx)(Nl,{title:v("terminal.closeTitle"),body:Me("terminal.closeBody",{title:u.title}),okLabel:v("terminal.closeOk"),danger:!0,onOk:()=>{p(u)},onClose:()=>h(null)})]})}function IU({term:e,visible:t}){let i=(0,fi.useRef)(null),n=(0,fi.useRef)(null),r=(0,fi.useRef)(null),[s,a]=(0,fi.useState)(!1);return(0,fi.useEffect)(()=>{let o=i.current;if(!o)return;let l=new wR({fontFamily:'"Cascadia Mono", "Cascadia Code", Consolas, "SF Mono", Menlo, Monaco, "DejaVu Sans Mono", "Ubuntu Mono", "Microsoft YaHei UI", "PingFang SC", "Noto Sans Mono CJK SC", monospace',fontSize:13,lineHeight:1.25,cursorBlink:!0,scrollback:5e3,allowTransparency:!1,theme:w0()}),c=new ER;l.loadAddon(c),l.open(o),n.current=l,r.current=c;try{c.fit()}catch{}let u=new TextDecoder,h=new TextEncoder,d=V.onBinaryFrame((f,p,_)=>{p!==e.index||f!==1||l.write(u.decode(_))});return l.onData(f=>V.sendBinary(2,e.index,h.encode(f))),(async()=>{try{let f=await V.call("terminal.attach",{id:e.id});f.windowsPty&&(l.options.windowsPty=f.windowsPty),f.snapshot&&l.write(f.snapshot),a(!0)}catch{l.writeln(v("terminal.ended"))}})(),()=>{d(),l.dispose(),n.current=null,r.current=null}},[e.id,e.index]),(0,fi.useEffect)(()=>{let o=document.documentElement,l=()=>{let h=n.current;h&&(h.options.theme=w0())},c=new MutationObserver(l);c.observe(o,{attributes:!0,attributeFilter:["data-theme"]});let u=window.matchMedia("(prefers-color-scheme: dark)");return u.addEventListener("change",l),()=>{c.disconnect(),u.removeEventListener("change",l)}},[]),(0,fi.useEffect)(()=>{if(!t)return;let o=r.current,l=n.current;if(!o||!l||!s)return;let c=setTimeout(()=>{try{o.fit();let u=new TextEncoder;V.sendBinary(3,e.index,u.encode(JSON.stringify({cols:l.cols,rows:l.rows})))}catch{}},50);return()=>clearTimeout(c)},[t,s,e.index]),(0,fi.useEffect)(()=>{let o=i.current;if(!o)return;let l=new ResizeObserver(()=>{let c=r.current,u=n.current;if(!(!c||!u||!t))try{c.fit();let h=new TextEncoder;V.sendBinary(3,e.index,h.encode(JSON.stringify({cols:u.cols,rows:u.rows})))}catch{}});return l.observe(o),()=>l.disconnect()},[t,e.index]),(0,ei.jsx)("div",{className:"tm-view",ref:i,style:{display:t?"block":"none"}})}var fi,ei,AR=se(()=>{fi=ae(kt(),1);xR();CR();$i();Fn();an();hs();Al();Kn();Pt();kR();TR();ei=ae(ke(),1)});function MR(){let e=le(),t=rt(L=>L.threads),i=e.currentThreadId,n=Jl(i),r=vi(L=>L.byThread[n]),s=t.find(L=>L.id===i)??null,a=(0,Qn.useRef)(null),[o,l]=(0,Qn.useState)(""),[c,u]=(0,Qn.useState)(!1),[h,d]=(0,Qn.useState)(null),f=(0,Qn.useRef)(null);(0,Qn.useEffect)(()=>{let L=vi.getState(),P=L.byThread[n];if(P&&P.proxyHref)return;let I=P?.url??s?.previewUrl??null;I&&L.navigate(Qu,n,i,I,{push:!1})},[n,i,s?.previewUrl]);let p=r?.origin,_=!!r?.proxyOrigin;(0,Qn.useEffect)(()=>{if(!(!p||!_))return()=>{let L=vi.getState(),P=Jl(le.getState().currentThreadId),I=le.getState().panelOpen&&le.getState().panelTab==="preview"&&L.byThread[P]?.origin===p&&P!==n;L.detach(n),I||V.call("preview.release",{url:p}).catch(()=>{})}},[p,_,n]),(0,Qn.useEffect)(()=>{c||l(r?hh(r.url):"")},[r?.url,c]),(0,Qn.useEffect)(()=>{let L=P=>{let I=a.current?.contentWindow;if(!I||P.source!==I)return;let B=P.data;if(!B||typeof B!="object"||B.ac_preview!==1||typeof B.href!="string")return;let x=vi.getState().byThread[n];if(!x?.proxyOrigin)return;let z=hy(B.href.slice(0,2048),x.proxyOrigin,x.origin),C=Wr(z);if(!C.ok||C.target.origin!==x.origin)return;let N=typeof B.title=="string"?B.title.slice(0,200):"";vi.getState().reported(n,C.target.href,N),i&&C.target.href!==x.url&&(f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{V.call("threads.update",{id:i,previewUrl:C.target.href}).catch(()=>{})},800))};return window.addEventListener("message",L),()=>window.removeEventListener("message",L)},[n,i]);let S=L=>{let P=L.trim();if(!P)return;let I=Wr(P);if(!I.ok){d(P);return}d(null),u(!1),vi.getState().navigate(Qu,n,i,I.target.href,{push:!0})},m=L=>{try{a.current?.contentWindow?.postMessage({ac_preview_cmd:L},"*")}catch{}},g=()=>{if(r?.bridged)return m("back");let L=vi.getState().step(n,-1);L&&vi.getState().navigate(Qu,n,i,L,{push:!1})},b=()=>{if(r?.bridged)return m("forward");let L=vi.getState().step(n,1);L&&vi.getState().navigate(Qu,n,i,L,{push:!1})},w=()=>{if(r){if(r.error||!r.proxyHref){vi.getState().navigate(Qu,n,i,r.url,{push:!1});return}r.bridged?m("reload"):vi.getState().reload(n)}},E=!!r&&(r.bridged||r.idx>0),A=!!r&&(r.bridged||r.idxe.setPanelWidth(Math.min(su,ls({...le.getState(),panelOpen:!0})));return(0,ot.jsxs)("div",{className:"pv",children:[(0,ot.jsxs)("div",{className:"pv-bar",children:[(0,ot.jsx)("button",{type:"button",className:"ibtn",title:v("preview.back"),"aria-label":v("preview.back"),disabled:!E,onClick:g,children:(0,ot.jsx)(pe,{name:"arrowLeft",size:15})}),(0,ot.jsx)("button",{type:"button",className:"ibtn",title:v("preview.forward"),"aria-label":v("preview.forward"),disabled:!A,onClick:b,children:(0,ot.jsx)(pe,{name:"arrowRight",size:15})}),(0,ot.jsx)("button",{type:"button",className:"ibtn",title:v("preview.reload"),"aria-label":v("preview.reload"),disabled:!r,onClick:w,children:(0,ot.jsx)(pe,{name:"refresh",size:14})}),(0,ot.jsx)("input",{className:`pv-addr${h?" err":""}`,value:o,spellCheck:!1,placeholder:v("preview.placeholder"),"aria-label":v("preview.address"),onFocus:L=>{u(!0),L.currentTarget.select()},onBlur:()=>{u(!1)},onChange:L=>{l(L.target.value),h&&d(null)},onKeyDown:L=>{L.nativeEvent.isComposing||(L.key==="Enter"?(L.preventDefault(),S(o)):L.key==="Escape"&&(u(!1),d(null),l(r?hh(r.url):""),L.target.blur()))}}),(0,ot.jsx)("button",{type:"button",className:"ibtn",title:v("preview.openExternal"),"aria-label":v("preview.openExternal"),disabled:!O,onClick:()=>O&&void bu(O),children:(0,ot.jsx)(pe,{name:"external",size:14})}),(0,ot.jsx)("button",{type:"button",className:"ibtn",title:v("preview.widen"),"aria-label":v("preview.widen"),onClick:D,children:(0,ot.jsx)(pe,{name:"widen",size:15})})]}),h&&(0,ot.jsxs)("div",{className:"pv-note err",children:[(0,ot.jsx)("span",{children:v("preview.onlyLocal")}),k&&(0,ot.jsx)("button",{type:"button",className:"btn",onClick:()=>{bu(k),d(null)},children:v("preview.openExternal")})]}),r?.error&&(0,ot.jsxs)("div",{className:"pv-note err",children:[(0,ot.jsxs)("span",{children:[v("preview.failed"),$r(r.error)]}),O&&(0,ot.jsx)("button",{type:"button",className:"btn",onClick:()=>{bu(O)},children:v("preview.openExternal")}),(0,ot.jsx)("button",{type:"button",className:"btn",onClick:w,children:v("common.retry")})]}),r?(0,ot.jsxs)("div",{className:"pv-frame-wrap",children:[r.loading&&(0,ot.jsx)("div",{className:"pv-loading"}),r.proxyHref&&(0,ot.jsx)("iframe",{ref:a,className:"pv-frame",title:r.title||hh(r.url),src:r.proxyHref,referrerPolicy:"no-referrer"},`${r.proxyOrigin}|${r.nonce}`)]}):(0,ot.jsxs)("div",{className:"pv-empty",children:[(0,ot.jsx)("div",{children:v("preview.empty")}),(0,ot.jsx)("div",{className:"pv-hint",children:v("preview.limits")})]})]})}var Qn,ot,Qu,RR=se(()=>{Qn=ae(kt(),1);an();$i();Fn();dh();lh();If();Pt();hs();of();ot=ae(ke(),1),Qu=(e,t)=>V.call(e,t)});function OR(){let e=le(),t=[{tab:"changes",label:v("panel.changes")},{tab:"files",label:v("panel.files")},{tab:"terminal",label:v("panel.terminal")},{tab:"preview",label:v("preview.tab")}];return(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsxs)("div",{className:"pn-head",children:[(0,ne.jsx)("div",{className:"pn-tabs",children:t.map(i=>(0,ne.jsx)("button",{className:`pn-tab${e.panelTab===i.tab?" on":""}`,onClick:()=>e.setPanelTab(i.tab),children:i.label},i.tab))}),(0,ne.jsx)("button",{className:"ibtn pn-close",title:v("panel.closeTitle"),onClick:()=>e.closePanel(),children:(0,ne.jsx)(pe,{name:"x"})})]}),(0,ne.jsxs)("div",{className:"pn-body",children:[e.panelTab==="changes"&&(0,ne.jsx)(UU,{}),e.panelTab==="files"&&(0,ne.jsx)(FU,{}),e.panelTab==="terminal"&&(0,ne.jsx)(NR,{}),e.panelTab==="preview"&&e.panelOpen&&(0,ne.jsx)(MR,{})]})]})}function zU(e){let t=[],i=null;for(let n of e.split(` +`))if(!(n.startsWith("diff ")||n.startsWith("index ")||n.startsWith("--- ")||n.startsWith("+++ "))){if(n.startsWith("@@")){i={head:n,lines:[]},t.push(i);continue}i&&(n.startsWith("+")?i.lines.push({t:"+",text:n.slice(1)}):n.startsWith("-")?i.lines.push({t:"-",text:n.slice(1)}):n.startsWith("\\")?i.lines.push({t:" ",text:n}):i.lines.push({t:" ",text:n.startsWith(" ")?n.slice(1):n}))}return t}function PU(e){let t=0,i=0;for(let n of e.split(` +`))n.startsWith("+")&&!n.startsWith("+++")?t++:n.startsWith("-")&&!n.startsWith("---")&&i++;return{add:t,del:i}}function UU(){let{projects:e,threads:t}=rt(),i=le(),n=Gn(k=>k.status),[r,s]=(0,vt.useState)(null),[a,o]=(0,vt.useState)(!1),[l,c]=(0,vt.useState)(null),[u,h]=(0,vt.useState)(null),[d,f]=(0,vt.useState)(null),[p,_]=(0,vt.useState)({}),S=(0,vt.useRef)(n),m=(0,vt.useRef)(null);m.current=l;let g=t.find(k=>k.id===i.currentThreadId)??null,b=g?e.find(k=>k.id===g.projectId):e.find(k=>k.id===i.currentProjectId),w=b?.id??null,E=(0,vt.useCallback)(async()=>{if(!w){s(null);return}try{let k=await V.call("git.status",{projectId:w});s(k);let D=m.current;D&&!k.files?.some(L=>L.path===D)&&(c(null),h(null))}catch(k){s({isRepo:!1,error:String(k?.message??k)})}},[w]);(0,vt.useEffect)(()=>{E();let k=setInterval(()=>{E()},3e3);return()=>clearInterval(k)},[E]),(0,vt.useEffect)(()=>{let k=S.current;S.current=n,(k==="running"||k==="initializing")&&n!=="running"&&n!=="initializing"&&E()},[n,E]);let A=(0,vt.useCallback)(async k=>{if(w){c(k.path),h({loading:!0});try{let D=await V.call("git.diff",{projectId:w,path:k.path});if(D.tooLarge)h({tooLarge:!0});else if(D.error)h({error:D.error});else{let L=zU(D.diff??"");h({hunks:L}),_(P=>({...P,[k.path]:PU(D.diff??"")}))}}catch(D){h({error:String(D?.message??D)})}}},[w]),O=(0,vt.useCallback)(async k=>{if(w){o(!0);try{await V.call("git.discard",{projectId:w,path:k.path}),l===k.path&&(c(null),h(null)),await E()}catch(D){we(v("panel.failDiscard")+ht(D),!0)}finally{o(!1)}}},[w,l,E]);return b?r&&!r.isRepo?(0,ne.jsxs)("div",{className:"pn-empty",children:[v("panel.notGit"),r.error&&(0,ne.jsx)("div",{className:"pn-empty-sub",children:r.error})]}):(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsxs)("div",{className:"chg-head",children:[(0,ne.jsxs)("span",{className:"chg-branch",title:v("panel.branch"),children:[(0,ne.jsx)(pe,{name:"changes",size:13})," ",r?.branch??"\u2026"]}),(0,ne.jsx)("button",{className:"ibtn",title:v("common.refresh"),onClick:()=>{E()},children:(0,ne.jsx)(pe,{name:"refresh",size:14})})]}),(0,ne.jsxs)("div",{className:"chg-list",children:[(r?.files??[]).length===0&&(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.clean")}),r?.files?.map(k=>{let D=p[k.path];return(0,ne.jsxs)("div",{className:`chg-row${l===k.path?" on":""}`,onClick:()=>{A(k)},children:[(0,ne.jsx)("span",{className:`chg-kind k-${k.kind}`,title:k.kind,children:BU(k.kind)}),(0,ne.jsx)("span",{className:"chg-path",title:k.path,children:k.path}),D&&(0,ne.jsxs)("span",{className:"chg-stat",children:[(0,ne.jsxs)("em",{className:"add",children:["+",D.add]})," ",(0,ne.jsxs)("em",{className:"del",children:["\u2212",D.del]})]}),(0,ne.jsx)("button",{className:"ibtn chg-discard",title:v("panel.discardBtn"),disabled:a,onClick:L=>{L.stopPropagation(),f(k)},children:(0,ne.jsx)(pe,{name:"x",size:13})})]},k.path)})]}),(0,ne.jsxs)("div",{className:"chg-diff",children:[u?.loading&&(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.loadingDiff")}),u?.tooLarge&&(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.diffTooLarge")}),u?.error&&(0,ne.jsx)("div",{className:"pn-empty",children:u.error}),u?.hunks&&(0,ne.jsx)(qf,{hunks:u.hunks,path:l??void 0})]}),d&&(0,ne.jsx)(Nl,{title:v("panel.discardTitle"),body:d.kind==="untracked"?Me("panel.discardUntracked",{path:d.path}):Me("panel.discardTracked",{path:d.path}),okLabel:v("common.discard"),danger:!0,onOk:()=>{O(d)},onClose:()=>f(null)})]}):(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.pickProject")})}function HU(e){window.dispatchEvent(new CustomEvent("ac-insert-mention",{detail:e}))}function FU(){let{projects:e,threads:t}=rt(),i=le(),n=t.find(E=>E.id===i.currentThreadId)??null,r=n?e.find(E=>E.id===n.projectId):e.find(E=>E.id===i.currentProjectId),s=r?.id??null,[a,o]=(0,vt.useState)({}),[l,c]=(0,vt.useState)(null),[u,h]=(0,vt.useState)(null),[d,f]=(0,vt.useState)(null),p=(0,vt.useCallback)(async E=>{if(s){o(A=>({...A,[E]:"loading"}));try{let A=await V.call("files.tree",{projectId:s,dir:E});o(O=>({...O,[E]:A.error?`err:${A.error}`:A.entries??[]}))}catch(A){o(O=>({...O,[E]:`err:${String(A?.message??A)}`}))}}},[s]);(0,vt.useEffect)(()=>{o({}),c(null),h(null),s&&p(".")},[s,p]);let _=E=>{if(!E.isDir){S(E.path);return}let A=a[E.path];A&&A!=="loading"?o(O=>{let k={...O};return delete k[E.path],k}):A||p(E.path)},S=async E=>{if(s){c(E),h({loading:!0});try{let A=await V.call("files.read",{projectId:s,path:E});h(A)}catch(A){h({error:String(A?.message??A)})}}},m=(0,vt.useRef)(null);if((0,vt.useEffect)(()=>{let E=m.current;if(!(!E||!u?.text))try{Of.highlightElement(E)}catch{}},[u?.text,u?.language]),!r)return(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.pickProject")});let g=l?l.split("/"):[],b=(E,A)=>{let O=a[E];return!O||O==="loading"?null:typeof O=="string"?(0,ne.jsx)("div",{className:"ft-err",style:{paddingLeft:8+A*14},children:O.slice(4)}):O.map(k=>(0,ne.jsxs)("div",{children:[(0,ne.jsxs)("div",{className:`ft-row${l===k.path?" on":""}`,style:{paddingLeft:8+A*14},onClick:()=>_(k),title:k.path,draggable:!0,onDragStart:D=>{D.dataTransfer.effectAllowed="copy",D.dataTransfer.setData(Wl,JSON.stringify({projectId:r.id,rel:k.path,isDir:k.isDir})),D.dataTransfer.setData("text/plain",Eu(r.path,k.path))},onContextMenu:D=>{D.preventDefault(),f({x:D.clientX,y:D.clientY,entry:k})},children:[k.isDir?(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsx)("span",{className:`caret${a[k.path]&&a[k.path]!=="loading"?" open":""}`,children:"\u203A"}),(0,ne.jsx)(pe,{name:"files",size:13})]}):(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsx)("span",{className:"caret",style:{visibility:"hidden"},children:"\u203A"}),(0,ne.jsx)("span",{className:"ft-dot"})]}),(0,ne.jsx)("span",{className:"ft-name",children:k.name})]}),k.isDir&&b(k.path,A+1)]},k.path))},w=d?[{kind:"item",label:v("mention.add"),onClick:()=>HU({projectId:r.id,rel:d.entry.path,isDir:d.entry.isDir})},{kind:"sep"},{kind:"item",label:v("common.copyPath"),onClick:()=>{$n(Eu(r.path,d.entry.path)),we(v("common.copiedPath"))}},{kind:"item",label:v("mention.copyRel"),onClick:()=>{$n(d.entry.path),we(v("common.copiedPath"))}}]:[];return(0,ne.jsxs)(ne.Fragment,{children:[d&&(0,ne.jsx)(Xa,{x:d.x,y:d.y,items:w,onClose:()=>f(null)}),(0,ne.jsx)("div",{className:"ft-crumbs",children:l?(0,ne.jsxs)(ne.Fragment,{children:[(0,ne.jsx)("button",{className:"ft-crumb",onClick:()=>c(null),title:v("panel.closePreview"),children:"\xD7"}),g.map((E,A)=>(0,ne.jsxs)("span",{className:"ft-crumb-t",children:[A>0?"/":"",E]},A)),(0,ne.jsx)("button",{className:"ibtn",title:v("common.copyPath"),onClick:()=>{$n(l),we(v("common.copiedPath"))},children:(0,ne.jsx)(pe,{name:"copy",size:13})})]}):(0,ne.jsx)("span",{className:"ft-crumb-t muted",children:r.name})}),(0,ne.jsx)("div",{className:"ft-tree",children:b(".",0)}),l&&(0,ne.jsxs)("div",{className:"ft-view",children:[u?.loading&&(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.reading")}),u?.binary&&(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.binary")}),u?.tooLarge&&(0,ne.jsx)("div",{className:"pn-empty",children:v("panel.tooLarge")}),u?.error&&(0,ne.jsx)("div",{className:"pn-empty",children:u.error}),u?.text!=null&&(0,ne.jsx)("pre",{className:"ft-pre",children:(0,ne.jsx)("code",{ref:m,className:`language-${u.language??"plaintext"}`,children:u.text})})]})]})}var vt,ne,BU,DR=se(()=>{vt=ae(kt(),1);$i();Fn();ql();an();hs();Kf();Al();Kn();Pt();AR();RR();hf();Wf();yu();qv();ne=ae(ke(),1);BU=e=>v(`panel.gitKind.${e}`)});function LR(){let{state:e,version:t}=Rr(),i=Gn(l=>l.pending),n=rt(l=>l.providers),[r,s]=(0,Ju.useState)(!1),[a,o]=(0,Ju.useState)(!1);return(0,Ju.useEffect)(()=>{let l=u=>{(u.ctrlKey||u.metaKey)&&u.key.toLowerCase()==="k"&&(u.preventDefault(),s(h=>!h))},c=()=>o(!0);return window.addEventListener("keydown",l),window.addEventListener("open-settings",c),()=>{window.removeEventListener("keydown",l),window.removeEventListener("open-settings",c)}},[]),e==="down"?(0,pi.jsx)("div",{className:"boot-screen",children:(0,pi.jsxs)("div",{className:"boot-wrap",children:[(0,pi.jsx)("span",{children:v("boot.serviceDown")}),(0,pi.jsx)("button",{className:"btn primary",onClick:()=>{rf()||location.reload()},children:v("boot.retry")})]})}):e==="connecting"&&!t?(0,pi.jsxs)("div",{className:"boot-screen",children:[(0,pi.jsx)("div",{className:"boot-dot","data-state":e}),(0,pi.jsx)("span",{className:"boot-label",children:v("boot.connecting")})]}):(0,pi.jsxs)(XE,{sidebar:(0,pi.jsx)(rC,{pendingByThread:new Set(i.map(l=>Gn.getState().threadId).filter(Boolean))}),topbar:(0,pi.jsx)(dN,{pendingCount:i.length}),panel:(0,pi.jsx)(OR,{}),children:[e==="reconnecting"&&(0,pi.jsx)("div",{className:"connbar",children:v("boot.reconnecting")}),(0,pi.jsx)(gA,{}),r&&(0,pi.jsx)(bA,{onClose:()=>s(!1)}),a&&(0,pi.jsx)(rA,{onClose:()=>o(!1),providers:n}),(0,pi.jsx)(iC,{})]})}var Ju,pi,IR=se(()=>{ru();ZE();uv();fN();_A();ql();Fn();Ju=ae(kt(),1);yA();DR();Yf();Kn();Pt();iv();pi=ae(ke(),1)});function BR(){let{state:e,version:t}=Rr(),[i,n]=(0,Bi.useState)([]),[r,s]=(0,Bi.useState)([]),[a,o]=(0,Bi.useState)(""),[l,c]=(0,Bi.useState)(""),[u,h]=(0,Bi.useState)([]),[d,f]=(0,Bi.useState)([]),[p,_]=(0,Bi.useState)([]),[S,m]=(0,Bi.useState)(""),[g,b]=(0,Bi.useState)(""),w=(0,Bi.useRef)(null);(0,Bi.useEffect)(()=>{e==="open"&&(va("projects.list").then(D=>n(D??[])),va("threads.list").then(D=>s(D??[])))},[e]),(0,Bi.useEffect)(()=>{if(w.current?.(),w.current=null,h([]),f([]),_([]),!(!l||e!=="open"))return va("threads.get",{id:l}).then(D=>{let L=D;h(L.events??[]),f(L.pending??[]),_(L.queue??[])}),w.current=V.subscribe(`thread:${l}`,(D,L)=>{let P=L;if(P.type==="event"&&P.event&&(h(I=>[...I,P.event]),P.event.type==="permission_resolved"||P.event.type==="question_answered")){let I=P.event.requestId;f(B=>B.filter(x=>x.requestId!==I))}P.type==="queue"&&P.queue&&_(P.queue)}),()=>w.current?.()},[l,e]),(0,Bi.useEffect)(()=>{let D=u.filter(I=>I.type==="permission_request"||I.type==="question"),L=new Set(u.filter(I=>I.type==="permission_resolved"||I.type==="question_answered").map(I=>I.requestId)),P=D.filter(I=>!L.has(I.requestId)).map(I=>({requestId:I.requestId??"",kind:I.type==="question"?"question":"permission",options:I.options}));f(I=>{let B=new Map(I.map(x=>[x.requestId,x]));for(let x of P)B.set(x.requestId,x);return[...B.values()]})},[u]);let E=async()=>{if(!l)return;let D=await va("threads.get",{id:l}).catch(()=>null);D&&(h(D.events??[]),f(L=>{let P=new Map(L.map(I=>[I.requestId,I]));for(let I of D.pending??[])P.set(I.requestId,I);return[...P.values()]}),_(D.queue??[]))},A=async D=>{if(b(""),!l||!S.trim())return;let L=S;m("");try{await va("thread.send",{id:l,text:L,behavior:D})}catch(P){b(String(P?.message??P))}await E()},O=async(D,L,P)=>{await va("thread.respond",{id:l,requestId:D,optionId:L,answers:P}).catch(I=>b(String(I?.message??I))),setTimeout(()=>{E()},1500)},k=async()=>{if(!a)return;let D=await va("threads.create",{projectId:a,provider:"mock"}).catch(L=>(b(String(L?.message??L)),null));D&&(s(L=>[D,...L]),c(D.id))};return(0,bt.jsxs)("div",{style:{display:"flex",height:"100vh",font:"13px/1.5 system-ui",color:"var(--fg)"},children:[(0,bt.jsxs)("div",{style:{width:260,borderRight:"1px solid var(--border)",padding:12,overflowY:"auto"},children:[(0,bt.jsx)("div",{style:{marginBottom:8},children:e==="open"?`\u5DF2\u8FDE\u63A5 \xB7 ${t??""}`:"\u8FDE\u63A5\u4E2D\u2026"}),(0,bt.jsx)(ln,{className:"tinput sm-field",matchWidth:!0,ariaLabel:"\u9009\u62E9\u9879\u76EE",value:a,onChange:o,options:[{value:"",label:"\u9009\u62E9\u9879\u76EE"},...i.map(D=>({value:D.id,label:D.name}))]}),(0,bt.jsx)("button",{onClick:()=>{k()},disabled:!a,style:{width:"100%",marginTop:8},children:"\u65B0\u5EFA\u5BF9\u8BDD\uFF08mock\uFF09"}),(0,bt.jsx)("div",{style:{marginTop:12},children:r.filter(D=>!a||D.projectId===a).map(D=>(0,bt.jsxs)("div",{onClick:()=>c(D.id),style:{padding:"6px 8px",cursor:"pointer",borderRadius:4,background:D.id===l?"var(--bg-active, #333)":"transparent"},children:[D.title," ",(0,bt.jsxs)("span",{style:{opacity:.6},children:["(",D.status,")"]})]},D.id))})]}),(0,bt.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[(0,bt.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:12},children:[u.map((D,L)=>(0,bt.jsx)("pre",{style:{margin:"4px 0",fontSize:11,whiteSpace:"pre-wrap",borderBottom:"1px solid var(--border)",paddingBottom:4},children:(D.seq??"")+" "+(D.type??"?")+" "+JSON.stringify(D).slice(0,400)},L)),d.map(D=>(0,bt.jsxs)("div",{style:{border:"1px solid var(--warn, orange)",borderRadius:6,padding:8,margin:"8px 0"},children:[(0,bt.jsxs)("div",{children:["\u6388\u6743/\u63D0\u95EE ",D.requestId]}),D.options?.map(L=>(0,bt.jsx)("button",{onClick:()=>{O(D.requestId,L.id)},style:{marginRight:8},children:L.label},L.id)),D.kind==="question"&&(0,bt.jsx)("button",{onClick:()=>{O(D.requestId,void 0,{q1:"staging",q2:""})},children:"\u586B\u8868\u63D0\u4EA4"}),(0,bt.jsx)("button",{onClick:()=>{O(D.requestId,void 0,void 0)},children:"\u53D6\u6D88"})]},D.requestId))]}),p.length>0&&(0,bt.jsxs)("div",{style:{padding:"4px 12px",opacity:.7},children:["\u6392\u961F\u4E2D\uFF1A",p.length," \u6761"]}),g&&(0,bt.jsx)("div",{style:{padding:"4px 12px",color:"var(--danger, red)"},children:g}),(0,bt.jsxs)("div",{style:{display:"flex",gap:8,padding:12,borderTop:"1px solid var(--border)"},children:[(0,bt.jsx)("input",{value:S,onChange:D=>m(D.target.value),onKeyDown:D=>{D.key==="Enter"&&A()},placeholder:"/perm /plan /slow /exit \u2026",style:{flex:1}}),(0,bt.jsx)("button",{onClick:()=>{A()},children:"\u53D1\u9001"}),(0,bt.jsx)("button",{onClick:()=>{A("steer")},children:"\u63D2\u8BDD"}),(0,bt.jsx)("button",{onClick:()=>{va("thread.interrupt",{id:l})},children:"\u6253\u65AD"})]})]})]})}var Bi,bt,va,zR=se(()=>{Bi=ae(kt(),1);ru();an();Gf();bt=ae(ke(),1),va=(e,t)=>V.call(e,t)});function FR(){PR++,WU.render(KU?(0,x0.jsx)(BR,{}):(0,x0.jsx)(LR,{},`${wa()}-${PR}`))}var UR,x0,qU,HR,V,KU,WU,PR,an=se(()=>{dh();vy();by();yy();Sy();wy();UR=ae(NE(),1);X_();iu();PE();tv();iv();Pt();HE();ru();$i();Fn();IR();zR();Ff();x0=ae(ke(),1),qU=Kl(),HR=new URLSearchParams(location.search);py(location.search);AE(location.search);RE(location.search);V=new sf(qU,wa());zE(e=>{!e.lang||!my(e.lang)||(V.setLang(wa()),V.call("app.setLocale",{lang:wa()}).catch(()=>{}),FR())});window.__ws=V;window.__stores={useData:rt,useUi:le,useConnection:Rr,usePreview:vi};Promise.resolve().then(()=>(ql(),FN)).then(e=>{window.__tl=e.useTimeline});V.onState(e=>Rr.getState().set({state:e}));UE(V,()=>{rf()});V.connect();V.waitHello().then(async e=>{Rr.getState().set({version:e.version??null}),le.getState().bind(V);try{let t=await V.call("settings.get");le.getState().hydrate(t),Mr(t.theme),nu(t)}catch{}await rt.getState().bind(V)});setInterval(()=>V.ping(),1e4);KU=HR.get("debug")==="1",WU=(0,UR.createRoot)(document.getElementById("root")),PR=0;FR();HR.get("audit")==="1"&&setTimeout(()=>{try{let e=window.innerWidth,t=document.documentElement.scrollWidth,i=new Set,n=[],r=0,s=getComputedStyle(document.documentElement).getPropertyValue("--accent").trim(),a=c=>c.top0&&c.width>0;document.querySelectorAll("*").forEach(c=>{let u=c,h=getComputedStyle(u),d=u.getBoundingClientRect();if(!a(d)||h.display==="none"||h.visibility==="hidden"||d.width<3||d.height<3)return;i.add(h.fontSize),h.borderTopWidth!=="0px"&&h.borderTopStyle!=="none"&&r++,h.borderBottomWidth!=="0px"&&h.borderBottomStyle!=="none"&&r++;let f=h.backgroundColor,p=h.color;if(s&&(f===s||p===s)){let _=(u.getAttribute("class")??"").split(" ")[0];n.includes(_)||n.push(_)}});let o={vw:e,docW:t,noHScroll:t<=e+1,fontSizes:[...i].sort(),bordersFirstScreen:r,accentEls:n},l=document.createElement("pre");l.id="audit",l.style.display="none",l.textContent=JSON.stringify(o),document.body.appendChild(l)}catch(e){let t=document.createElement("pre");t.id="audit",t.textContent=JSON.stringify({error:String(e)}),document.body.appendChild(t)}},1500)});an();})(); /*! Bundled license information: -scheduler/cjs/scheduler.production.js: +react/cjs/react.production.js: (** * @license React - * scheduler.production.js + * react.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * @@ -139,10 +140,10 @@ scheduler/cjs/scheduler.production.js: * LICENSE file in the root directory of this source tree. *) -react/cjs/react.production.js: +scheduler/cjs/scheduler.production.js: (** * @license React - * react.production.js + * scheduler.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * diff --git a/packages/agent-console/daemon/dist/main.js b/packages/agent-console/daemon/dist/main.js index 346a82c..ea4d98e 100644 --- a/packages/agent-console/daemon/dist/main.js +++ b/packages/agent-console/daemon/dist/main.js @@ -91,6 +91,31 @@ var init_log = __esm({ } }); +// daemon/src/security.ts +import { timingSafeEqual, createHash } from "node:crypto"; +function checkHost(host, port) { + if (!host) return { ok: false, code: 421, message: "Host \u4E0D\u5BF9" }; + const h = host.toLowerCase(); + if (h === `127.0.0.1:${port}` || h === `localhost:${port}`) return { ok: true }; + return { ok: false, code: 421, message: "Host \u4E0D\u5BF9" }; +} +function classifyOrigin(origin, port) { + if (origin === void 0 || origin === "") return "none"; + if (origin === "null") return "opaque"; + const o = origin.toLowerCase(); + if (o === `http://127.0.0.1:${port}` || o === `http://localhost:${port}`) return "self"; + return "foreign"; +} +function tokenEqual(a, b) { + const ha = createHash("sha256").update(a).digest(); + const hb = createHash("sha256").update(b).digest(); + return timingSafeEqual(ha, hb); +} +var init_security = __esm({ + "daemon/src/security.ts"() { + } +}); + // daemon/src/util/i18n.ts function normalizeLang(raw) { const s = String(raw ?? "").trim().toLowerCase(); @@ -129,6 +154,7 @@ var init_i18n = __esm({ "notice.acpImageByPathSwitched": "{agent} \u662F\u5728\u53E6\u4E00\u4E2A\u6A21\u578B\u4E0A\u542F\u52A8\u7684\uFF0C\u53EA\u5BF9\u90A3\u4E2A\u6A21\u578B\u63A5\u6536\u56FE\u7247\uFF0C\u8FD9\u6B21\u6539\u4E3A\u53D1\u9001\u56FE\u7247\u7684\u6587\u4EF6\u8DEF\u5F84\uFF08\u5F53\u524D\u6A21\u578B\u80FD\u770B\u56FE\u65F6\u5B83\u4F1A\u7528 read_image \u6253\u5F00\uFF09\uFF1A{paths}", "notice.acpSessionNotRestored": "{agent} \u4E0D\u80FD\u6062\u590D\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\uFF08\u5B83\u7684 ACP \u65E2\u4E0D\u652F\u6301 session/load \u4E5F\u4E0D\u652F\u6301 session/resume\uFF09\uFF0C\u5DF2\u65B0\u5F00\u4E00\u8F6E\uFF1B\u5148\u524D\u7684\u4E0A\u4E0B\u6587\u4E0D\u4F1A\u5E26\u56DE\u3002", "notice.attachmentIssue": "\u9644\u4EF6\u95EE\u9898\uFF1A{detail}", + "notice.mentionSkipped": "\u8FD9\u4E9B\u8DEF\u5F84\u4E0D\u5728\u9879\u76EE\u91CC\u6216\u5DF2\u4E0D\u5B58\u5728\uFF0C\u6CA1\u6709\u53D1\u7ED9 Agent\uFF1A{paths}", "claude.notFound": "\u627E\u4E0D\u5230 claude\uFF08{detail}\uFF09\u3002\u672C\u63D2\u4EF6\u4E0D\u9644\u5E26 Claude Code\uFF0C\u8BF7\u5148\u5B89\u88C5\uFF1A{hint}", "claude.startFailed": "\u65E0\u6CD5\u542F\u52A8 claude\uFF1A{detail}", "claude.exited": "claude \u8FDB\u7A0B\u610F\u5916\u9000\u51FA\uFF08{code}\uFF09", @@ -146,6 +172,9 @@ var init_i18n = __esm({ "provider.unavailable": "{name} \u672A\u5B89\u88C5\u6216\u4E0D\u53EF\u7528", "provider.unknown": "\u672A\u77E5 Agent\uFF1A{id}", "provider.timeout": "\u68C0\u6D4B\u8D85\u65F6", + "err.previewUrl": "\u9884\u89C8\u53EA\u652F\u6301\u672C\u673A\u5730\u5740\uFF08localhost\u3001127.0.0.1 \u7B49\uFF09", + "err.previewDenied": "\u8FD9\u4E2A\u7AEF\u53E3\u4E0D\u80FD\u9884\u89C8\uFF08\u662F Agent \u63A7\u5236\u53F0\u6216 Magpie \u81EA\u5DF1\u7684\u7AEF\u53E3\uFF09", + "err.previewUnavailable": "\u9884\u89C8\u4E0D\u53EF\u7528", "err.projectMissing": "\u9879\u76EE\u4E0D\u5B58\u5728", "err.threadMissing": "\u5BF9\u8BDD\u4E0D\u5B58\u5728", "err.dirMissing": "\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6587\u4EF6\u5939", @@ -235,6 +264,7 @@ var init_i18n = __esm({ "notice.acpImageByPathSwitched": "{agent} was started on another model and takes image blocks only for that one, so the image went as its file path (it opens it with read_image when this model sees images): {paths}", "notice.acpSessionNotRestored": "{agent} can't restore the previous conversation (its ACP advertises neither session/load nor session/resume); started a new one \u2014 prior context won't come back.", "notice.attachmentIssue": "Attachment issue: {detail}", + "notice.mentionSkipped": "Not sent to the Agent (outside the project or gone): {paths}", "claude.notFound": "claude was not found ({detail}). Claude Code is not bundled with this plugin; install it first: {hint}", "claude.startFailed": "Could not start claude: {detail}", "claude.exited": "claude exited unexpectedly ({code})", @@ -252,6 +282,9 @@ var init_i18n = __esm({ "provider.unavailable": "{name} is not installed or not available", "provider.unknown": "Unknown agent: {id}", "provider.timeout": "Detection timed out", + "err.previewUrl": "Preview only supports local addresses (localhost, 127.0.0.1, \u2026)", + "err.previewDenied": "This port can't be previewed (it belongs to Agent Console or Magpie)", + "err.previewUnavailable": "Preview is unavailable", "err.projectMissing": "Project not found", "err.threadMissing": "Conversation not found", "err.dirMissing": "The folder does not exist or is not a folder", @@ -774,6 +807,7 @@ function pickScript(text) { if (t.startsWith("/error")) return scriptError; if (t.startsWith("/long")) return scriptLong; if (t.startsWith("/exit")) return scriptExit; + if (t.startsWith("/serve")) return scriptServe; return scriptDefault; } async function sleepAbortable(ms, ctx) { @@ -789,6 +823,25 @@ function chunkText(s, n) { for (let i = 0; i < s.length; i += n) out.push(s.slice(i, i + n)); return out; } +async function scriptServe(ctx) { + const emit = (e) => ctx.emit(e); + const reply = [ + "\u5F00\u53D1\u670D\u52A1\u5668\u5DF2\u7ECF\u542F\u52A8\uFF1Ahttp://localhost:5173/ \uFF0C\u63A5\u53E3\u5728 127.0.0.1:5173/api.json\u3002", + "", + "- \u5728\u9884\u89C8\u91CC\u6253\u5F00 [\u9996\u9875](http://localhost:5173/) \u6216 [about](http://localhost:5173/about.html)", + "- \u6587\u6863\uFF1A[Vite](https://vite.dev/guide/)", + "", + "```", + " VITE v5.4.21 ready in 139 ms", + " \u279C Local: http://localhost:5173/", + "```" + ].join("\n"); + for (const ch of chunkText(reply, 40)) { + if (await sleepAbortable(20, ctx)) return; + emit({ type: "assistant_delta", itemId: "sv", text: ch }); + } + emit({ type: "assistant_message", itemId: "sv", text: reply }); +} function mockReply(ctx) { const base = [ "\u597D\u7684\uFF0C\u6211\u5DF2\u7ECF\u6309\u4F60\u7684\u8981\u6C42\u6539\u597D\u4E86\u3002", @@ -931,21 +984,21 @@ var init_mock = __esm({ } } respond(requestId, answer) { - const resolve2 = this.pendingReq.get(requestId); - if (resolve2) { + const resolve4 = this.pendingReq.get(requestId); + if (resolve4) { this.pendingReq.delete(requestId); - resolve2(answer); + resolve4(answer); } } waitFor(requestId) { - return new Promise((resolve2) => { - this.pendingReq.set(requestId, resolve2); + return new Promise((resolve4) => { + this.pendingReq.set(requestId, resolve4); }); } async interrupt() { this.interruptFlag = true; - for (const [id2, resolve2] of this.pendingReq) { - resolve2({ cancelled: true }); + for (const [id2, resolve4] of this.pendingReq) { + resolve4({ cancelled: true }); this.pendingReq.delete(id2); } await sleep(120); @@ -973,7 +1026,7 @@ var init_mock = __esm({ } async close() { this.closed = true; - for (const [, resolve2] of this.pendingReq) resolve2({ cancelled: true }); + for (const [, resolve4] of this.pendingReq) resolve4({ cancelled: true }); this.pendingReq.clear(); this.q.close(); } @@ -1037,8 +1090,8 @@ function extraBinDirs({ platform = process.platform, env = process.env, home = h return dirs; } function searchDirs({ platform = process.platform, env = process.env, home = homedir2(), extra = true } = {}) { - const sep4 = platform === "win32" ? ";" : ":"; - const raw = String(envGet(env, "PATH") ?? "").split(sep4).map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean); + const sep5 = platform === "win32" ? ";" : ":"; + const raw = String(envGet(env, "PATH") ?? "").split(sep5).map((d) => d.trim().replace(/^"(.*)"$/, "$1")).filter(Boolean); const all = extra ? [...raw, ...extraBinDirs({ platform, env, home })] : raw; const seen = /* @__PURE__ */ new Set(); const out = []; @@ -1306,6 +1359,8 @@ var init_bin = __esm({ }); // daemon/src/agents/kinds.ts +import { existsSync as existsSync5 } from "node:fs"; +import { isAbsolute, resolve as resolve2 } from "node:path"; function relPath(p, cwd) { if (!p) return ""; const s = String(p); @@ -1317,6 +1372,15 @@ function relPath(p, cwd) { if (a.toLowerCase() === b.toLowerCase()) return "."; return s; } +function targetExists(input, cwd = "") { + const p = String(input.file_path ?? input.path ?? ""); + if (!p) return false; + try { + return existsSync5(isAbsolute(p) || !cwd ? p : resolve2(cwd, p)); + } catch { + return false; + } +} function callInfo(name, input = {}, cwd = "") { const t = String(name || ""); const f = (kind, title, detail) => ({ kind, title, detail }); @@ -1521,7 +1585,7 @@ function mapToolUse(blk, cwd) { const input = rec(blk.input); const name = str(blk.name) ?? "tool"; const id2 = str(blk.id) ?? ""; - const info = callInfo(name, { ...input, _exists: true }, cwd); + const info = callInfo(name, { ...input, _exists: name === "Write" ? targetExists(input, cwd) : true }, cwd); let detail = info.detail; if (info.kind === "edit" && (input.old_string !== void 0 || Array.isArray(input.edits))) { detail = editDetail({ path: info.detail.path, old: input.old_string, new: input.new_string, edits: input.edits }); @@ -1573,7 +1637,7 @@ __export(attachmentRefs_exports, { resolveAttachmentRefs: () => resolveAttachmentRefs, resolveImagePath: () => resolveImagePath }); -import { existsSync as existsSync5 } from "node:fs"; +import { existsSync as existsSync6 } from "node:fs"; function bindAttachmentStore(store) { globalAttachmentStore = store; } @@ -1596,7 +1660,7 @@ async function resolveAttachmentRefs(store, refs) { out.push({ path: viaGlobal, mime: a.mime }); continue; } - if (existsSync5(a.path)) { + if (existsSync6(a.path)) { out.push(a); continue; } @@ -1605,7 +1669,7 @@ async function resolveAttachmentRefs(store, refs) { return out; } async function resolveImagePath(ref) { - if (existsSync5(ref)) return ref; + if (existsSync6(ref)) return ref; const p = await lookupAttachmentPath(ref); if (p) return p; throw new Error(tr("attachment.missing", { ref })); @@ -1768,15 +1832,15 @@ var init_cli = __esm({ }); this.child.stdin?.on("error", () => { }); - this.exited = new Promise((resolve2) => { + this.exited = new Promise((resolve4) => { this.child.on("error", (e) => { this.spawnError = e; this.finish(); - resolve2({ code: null, signal: null }); + resolve4({ code: null, signal: null }); }); this.child.on("close", (code, signal) => { this.finish(); - resolve2({ code, signal }); + resolve4({ code, signal }); }); }); this.initialized = this.request({ subtype: "initialize" }, 6e4).catch(() => null); @@ -1893,8 +1957,8 @@ var init_cli = __esm({ request(request, timeoutMs = 1e4) { if (this.dead) return Promise.reject(new Error("claude is not running")); const id2 = `ac_${++this.seq}_${Math.random().toString(36).slice(2, 8)}`; - return new Promise((resolve2, reject) => { - const p = { resolve: resolve2, reject }; + return new Promise((resolve4, reject) => { + const p = { resolve: resolve4, reject }; p.timer = setTimeout(() => { if (this.pending.delete(id2)) reject(new Error(`claude did not answer ${String(request.subtype)} in ${Math.round(timeoutMs / 1e3)} s`)); }, timeoutMs); @@ -2066,7 +2130,7 @@ var init_session = __esm({ if (toolName === "AskUserQuestion" && Array.isArray(input.questions)) { return this.handleQuestion(requestId, input, signal); } - const info = callInfo(toolName, { ...input, _exists: true }, this.o.cwd); + const info = callInfo(toolName, { ...input, _exists: toolName === "Write" ? targetExists(input, this.o.cwd) : true }, this.o.cwd); let detail = { ...info.detail, toolName }; if (info.kind === "edit" && (input.old_string !== void 0 || Array.isArray(input.edits))) { detail = { ...editDetail({ path: info.detail.path, old: input.old_string, new: input.new_string, edits: input.edits }), toolName }; @@ -2083,12 +2147,12 @@ var init_session = __esm({ { id: "deny", label: tr("perm.deny"), kind: "reject_once" } ] }); - return new Promise((resolve2) => { - this.pending.set(requestId, { kind: "permission", resolve: (a) => resolve2(this.toPermissionDecision(a, input)) }); + return new Promise((resolve4) => { + this.pending.set(requestId, { kind: "permission", resolve: (a) => resolve4(this.toPermissionDecision(a, input)) }); signal.addEventListener("abort", () => { if (this.pending.delete(requestId)) { this.emit({ type: "permission_resolved", requestId, cancelled: true }); - resolve2({ behavior: "deny", message: "Cancelled by the user", interrupt: true }); + resolve4({ behavior: "deny", message: "Cancelled by the user", interrupt: true }); } }, { once: true }); }); @@ -2115,12 +2179,12 @@ var init_session = __esm({ { id: "reject", label: tr("perm.deny"), kind: "reject_once" } ] }); - const answer = await new Promise((resolve2) => { - this.pending.set(requestId, { kind: "permission", resolve: (a) => resolve2(a) }); + const answer = await new Promise((resolve4) => { + this.pending.set(requestId, { kind: "permission", resolve: (a) => resolve4(a) }); signal.addEventListener("abort", () => { if (this.pending.delete(requestId)) { this.emit({ type: "permission_resolved", requestId, cancelled: true }); - resolve2({ cancelled: true }); + resolve4({ cancelled: true }); } }, { once: true }); }); @@ -2138,12 +2202,12 @@ var init_session = __esm({ } async handleQuestion(requestId, input, signal) { this.emit({ type: "question", requestId, questions: input.questions }); - const answer = await new Promise((resolve2) => { - this.pending.set(requestId, { kind: "question", resolve: (a) => resolve2(a) }); + const answer = await new Promise((resolve4) => { + this.pending.set(requestId, { kind: "question", resolve: (a) => resolve4(a) }); signal.addEventListener("abort", () => { if (this.pending.delete(requestId)) { this.emit({ type: "permission_resolved", requestId, cancelled: true }); - resolve2({ cancelled: true }); + resolve4({ cancelled: true }); } }, { once: true }); }); @@ -2265,7 +2329,7 @@ var init_models = __esm({ // daemon/src/history/import.ts import { readdir, readFile as readFile5, stat as stat4 } from "node:fs/promises"; -import { existsSync as existsSync6 } from "node:fs"; +import { existsSync as existsSync7 } from "node:fs"; import { join as join6 } from "node:path"; import { homedir as homedir3 } from "node:os"; function parseLine(line) { @@ -2332,7 +2396,7 @@ async function readClaudeHistory(sessionId, cwd) { const dirs = await readdir(CLAUDE_ROOT).catch(() => []); for (const d of dirs) { const path3 = join6(CLAUDE_ROOT, d, `${sessionId}.jsonl`); - if (!existsSync6(path3)) continue; + if (!existsSync7(path3)) continue; const msgs = []; let matched = false; for await (const line of linesOf(path3)) { @@ -2387,14 +2451,14 @@ function runVersion(r, args, timeoutMs = 5e3) { }); } function createClaudeProvider(opts = {}) { - const resolve2 = opts.resolve ?? resolveBin; + const resolve4 = opts.resolve ?? resolveBin; const resolveCustom = opts.resolve ? (l) => opts.resolve(l.cmd) : resolveLaunch; return { id: "claude", name: "Claude Code", capabilities: claudeCapabilities, async detect(launch) { - const bin = launch ? await resolveCustom(launch) : await resolve2("claude"); + const bin = launch ? await resolveCustom(launch) : await resolve4("claude"); if (!bin.ok) return { available: false, reason: bin.reason, installHint: INSTALL_HINT }; try { const version = await runVersion(bin, [...launch?.prefixArgs ?? [], "--version"]); @@ -2407,7 +2471,7 @@ function createClaudeProvider(opts = {}) { return listClaudeModels(); }, async createSession(o) { - const bin = o.launch ? await resolveCustom(o.launch) : await resolve2("claude"); + const bin = o.launch ? await resolveCustom(o.launch) : await resolve4("claude"); if (!bin.ok) throw new Error(tr("claude.notFound", { detail: bin.reason, hint: INSTALL_HINT })); return new ClaudeSession({ threadId: o.threadId, @@ -3423,8 +3487,8 @@ var init_session2 = __esm({ } } waitFor(requestId) { - return new Promise((resolve2) => { - this.pending.set(requestId, { kind: "permission", resolve: resolve2 }); + return new Promise((resolve4) => { + this.pending.set(requestId, { kind: "permission", resolve: resolve4 }); }); } respond(requestId, answer) { @@ -3943,7 +4007,7 @@ var init_sessionCaps = __esm({ import { readFile as readFile10, stat as stat7 } from "node:fs/promises"; import { basename as basename4 } from "node:path"; import { pathToFileURL } from "node:url"; -async function buildAcpPrompt(text, attachments, caps) { +async function buildAcpPrompt(text, attachments, caps, mentions = []) { const media = []; const links = []; const pathLines = []; @@ -4006,6 +4070,9 @@ async function buildAcpPrompt(text, attachments, caps) { const blocks = []; if (fullText) blocks.push({ type: "text", text: fullText }); blocks.push(...media, ...links); + for (const m of mentions) { + blocks.push({ type: "resource_link", uri: pathToFileURL(m.path).href, name: basename4(m.path) || m.path }); + } return { blocks, imagesByPath, warnings }; } var MAX_INLINE_MEDIA_BYTES, MAX_INLINE_TOTAL_BYTES, MAX_EMBED_TEXT_BYTES, isText; @@ -4309,8 +4376,8 @@ var init_session3 = __esm({ await this.applyCursorAutoReviewConfig(false); } waitPerm(requestId) { - return new Promise((resolve2) => { - this.permPending.set(requestId, resolve2); + return new Promise((resolve4) => { + this.permPending.set(requestId, resolve4); }); } respond(requestId, answer) { @@ -4347,7 +4414,7 @@ var init_session3 = __esm({ this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" }); return; } - const built = await buildAcpPrompt(text, attachments, this.promptCaps); + const built = await buildAcpPrompt(text, attachments, this.promptCaps, input.mentions ?? []); const agent = this.o.providerName ?? this.o.binName; if (built.imagesByPath.length && !this.promptCaps.image) { const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel; @@ -4966,13 +5033,13 @@ var init_pickFolderWin = __esm({ // daemon/src/util/pickFolder.ts import { execFile as execFile2 } from "node:child_process"; -import { existsSync as existsSync7, statSync as statSync3 } from "node:fs"; +import { existsSync as existsSync8, statSync as statSync3 } from "node:fs"; function appleScriptString(s) { return '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"'; } function isDir(p) { try { - return !!p && existsSync7(p) && statSync3(p).isDirectory(); + return !!p && existsSync8(p) && statSync3(p).isDirectory(); } catch { return false; } @@ -5222,13 +5289,869 @@ var init_modes = __esm({ } }); +// daemon/src/util/mentions.ts +import { realpath, stat as stat8 } from "node:fs/promises"; +import { isAbsolute as isAbsolute2, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path"; +function insideRoot(root, child, platform = process.platform) { + const p = platform === "win32" ? win322 : posix2; + const norm = (s) => platform === "win32" ? p.resolve(s).toLowerCase() : p.resolve(s); + const r = p.relative(norm(root), norm(child)); + return r === "" || !r.startsWith("..") && !p.isAbsolute(r); +} +async function resolveMentions(projectPath, refs) { + const mentions = []; + const warnings = []; + const seen = /* @__PURE__ */ new Set(); + const shown = resolve3(projectPath); + let realRoot; + try { + realRoot = await realpath(shown); + } catch { + return { mentions, warnings: refs.map((r) => r.rel) }; + } + for (const ref of refs.slice(0, MAX_MENTIONS)) { + const rel = String(ref.rel ?? "").replace(/\\/g, "/"); + if (!rel || rel.includes("\0") || isAbsolute2(rel) || /^[a-zA-Z]:/.test(rel)) { + warnings.push(rel || "(empty)"); + continue; + } + const abs = resolve3(shown, rel === "." ? "" : rel); + if (!insideRoot(shown, abs)) { + warnings.push(rel); + continue; + } + let real; + let isDir2; + try { + real = await realpath(abs); + isDir2 = (await stat8(real)).isDirectory(); + } catch { + warnings.push(rel); + continue; + } + if (!insideRoot(realRoot, real)) { + warnings.push(rel); + continue; + } + if (seen.has(abs)) continue; + seen.add(abs); + mentions.push({ path: abs, isDir: isDir2 }); + } + return { mentions, warnings }; +} +function mentionSection(mentions) { + if (!mentions.length) return ""; + const lines = mentions.map((m) => { + const shown = m.isDir && !m.path.endsWith(sep2) && !m.path.endsWith("/") ? m.path + (m.path.includes("\\") && !m.path.includes("/") ? "\\" : "/") : m.path; + const quoted = /\s|`/.test(shown) ? "`" + shown.replace(/`/g, "'") + "`" : shown; + return `- ${quoted}${m.isDir ? " (folder)" : ""}`; + }); + return `Referenced files (read them as needed): +${lines.join("\n")}`; +} +function withMentions(text, mentions) { + const sec = mentionSection(mentions); + if (!sec) return text; + return text.trim() ? `${text} + +${sec}` : sec; +} +var MAX_MENTIONS; +var init_mentions = __esm({ + "daemon/src/util/mentions.ts"() { + MAX_MENTIONS = 50; + } +}); + +// daemon/src/preview/url.ts +function isLoopbackHost(host) { + const h = host.toLowerCase().replace(/^\[|\]$/g, ""); + if (h === "localhost" || h.endsWith(".localhost")) return /^[a-z0-9.-]+$/.test(h) && !h.includes(".."); + if (h === "0.0.0.0" || h === "::1" || h === "::") return true; + const m = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h); + return !!m && m.slice(1).every((x) => Number(x) <= 255); +} +function connectHosts(h) { + if (h === "localhost" || h.endsWith(".localhost")) return ["127.0.0.1", "::1"]; + if (h === "0.0.0.0") return ["127.0.0.1"]; + if (h === "::1") return ["::1"]; + if (h === "::") return ["::1", "127.0.0.1"]; + return [h]; +} +function withScheme(raw) { + const s = raw.trim(); + if (/^\d{1,5}$/.test(s)) return `http://localhost:${s}/`; + if (/^:\d{1,5}(?:[/?#].*)?$/.test(s)) return `http://localhost${s}`; + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) return s; + if (/^[a-z][a-z0-9+.-]*:(?!\d)/i.test(s)) return s; + return `http://${s}`; +} +function checkPreviewUrl(raw) { + if (typeof raw !== "string" || !raw.trim()) return { ok: false, reason: "empty" }; + if (raw.length > MAX_PREVIEW_URL) return { ok: false, reason: "too_long" }; + let u; + try { + u = new URL(withScheme(raw)); + } catch { + return { ok: false, reason: "bad_url" }; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return { ok: false, reason: "scheme" }; + if (u.username || u.password) return { ok: false, reason: "userinfo" }; + const hostname = u.hostname.toLowerCase().replace(/^\[|\]$/g, ""); + if (!isLoopbackHost(hostname)) return { ok: false, reason: "not_local" }; + const secure = u.protocol === "https:"; + const port = u.port ? Number(u.port) : secure ? 443 : 80; + if (!Number.isInteger(port) || port < 1 || port > 65535) return { ok: false, reason: "port" }; + const href = u.href; + if (href.length > MAX_PREVIEW_URL) return { ok: false, reason: "too_long" }; + const hostForUrl = hostname.includes(":") ? `[${hostname}]` : hostname; + return { + ok: true, + target: { + href, + origin: `${u.protocol}//${hostForUrl}:${port}`, + path: `${u.pathname}${u.search}${u.hash}`, + secure, + hostname, + port, + connect: connectHosts(hostname), + hostHeader: `${hostForUrl}:${port}` + } + }; +} +function deniedPort(port, denied) { + for (const d of denied) if (d === port) return true; + return false; +} +function displayOrigin(origin) { + return origin.replace(/^http:\/\/(.+):80$/, "http://$1").replace(/^https:\/\/(.+):443$/, "https://$1"); +} +function externalHref(raw) { + if (typeof raw !== "string" || !raw || raw.length > MAX_PREVIEW_URL) return null; + let u; + try { + u = new URL(raw); + } catch { + return null; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return null; + if (!u.hostname) return null; + const href = u.href; + if (/[\s"'<>`\\^{|}]/.test(href) || href.length > MAX_PREVIEW_URL) return null; + return href; +} +var MAX_PREVIEW_URL; +var init_url = __esm({ + "daemon/src/preview/url.ts"() { + MAX_PREVIEW_URL = 2048; + } +}); + +// daemon/src/util/openExternal.ts +import { execFile as execFile3 } from "node:child_process"; +function openerFor(platform, href) { + if (platform === "win32") return { cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", href] }; + if (platform === "darwin") return { cmd: "open", args: [href] }; + return { cmd: "xdg-open", args: [href] }; +} +async function openExternal(raw, opts = {}) { + const href = externalHref(raw); + if (!href) return { ok: false, reason: "bad_url" }; + const { cmd, args } = openerFor(opts.platform ?? process.platform, href); + const run = opts.exec ?? execFile3; + return await new Promise((resolve4) => { + let settled = false; + const done = (v) => { + if (!settled) { + settled = true; + resolve4(v); + } + }; + try { + const child = run(cmd, args, { windowsHide: true, timeout: 15e3 }, (err) => { + done(err ? { ok: false, href, reason: "opener_failed" } : { ok: true, href }); + }); + child.on("error", () => done({ ok: false, href, reason: "no_opener" })); + } catch { + done({ ok: false, href, reason: "no_opener" }); + } + setTimeout(() => done({ ok: true, href }), opts.waitMs ?? 4e3).unref?.(); + }); +} +var init_openExternal = __esm({ + "daemon/src/util/openExternal.ts"() { + init_url(); + } +}); + +// daemon/src/preview/inject.ts +function injectScriptTag(html) { + const tag = ``; + const head = /]*)?>/i.exec(html); + if (head) return html.slice(0, head.index + head[0].length) + tag + html.slice(head.index + head[0].length); + const root = /]*)?>/i.exec(html); + if (root) return html.slice(0, root.index + root[0].length) + tag + html.slice(root.index + root[0].length); + const doctype = /^\s*]*>/i.exec(html); + if (doctype) return html.slice(0, doctype[0].length) + tag + html.slice(doctype[0].length); + return tag + html; +} +var PREVIEW_SCRIPT_PATH, PREVIEW_SCRIPT; +var init_inject = __esm({ + "daemon/src/preview/inject.ts"() { + PREVIEW_SCRIPT_PATH = "/__agent_console__/preview.js"; + PREVIEW_SCRIPT = `(function(){ + "use strict"; + if (window.__acPreview) return; window.__acPreview = 1; + function mem(){ var m = new Map(); var s = { + getItem: function(k){ k = String(k); return m.has(k) ? m.get(k) : null; }, + setItem: function(k, v){ m.set(String(k), String(v)); }, + removeItem: function(k){ m.delete(String(k)); }, + clear: function(){ m.clear(); }, + key: function(i){ var a = Array.from(m.keys()); return i >= 0 && i < a.length ? a[i] : null; } + }; Object.defineProperty(s, "length", { get: function(){ return m.size; } }); return s; } + ["localStorage", "sessionStorage"].forEach(function(n){ + var ok = true; try { var st = window[n]; st.getItem("__ac"); } catch (e) { ok = false; } + if (!ok) { try { Object.defineProperty(window, n, { value: mem(), configurable: true }); } catch (e) {} } + }); + try { void document.cookie; } catch (e) { + var jar = {}; + try { Object.defineProperty(document, "cookie", { configurable: true, + get: function(){ return Object.keys(jar).map(function(k){ return k + "=" + jar[k]; }).join("; "); }, + set: function(v){ var p = String(v).split(";")[0]; var i = p.indexOf("="); if (i > 0) jar[p.slice(0, i).trim()] = p.slice(i + 1).trim(); } + }); } catch (e2) {} + } + var parentWin = window.parent; + if (!parentWin || parentWin === window) return; + var last = ""; + function report(){ try { + var msg = { ac_preview: 1, href: String(location.href), title: String(document.title || "") }; + var key = msg.href + "\\n" + msg.title; if (key === last) return; last = key; + parentWin.postMessage(msg, "*"); + } catch (e) {} } + ["pushState", "replaceState"].forEach(function(k){ + var orig = history[k]; if (typeof orig !== "function") return; + history[k] = function(){ var r = orig.apply(this, arguments); setTimeout(report, 0); return r; }; + }); + window.addEventListener("popstate", report); + window.addEventListener("hashchange", report); + window.addEventListener("load", report); + document.addEventListener("DOMContentLoaded", report); + setInterval(report, 1000); + window.addEventListener("message", function(e){ + if (e.source !== parentWin) return; + var d = e.data; if (!d || typeof d !== "object") return; + var c = d.ac_preview_cmd; + if (c === "back") history.back(); + else if (c === "forward") history.forward(); + else if (c === "reload") location.reload(); + else if (c === "ping") { last = ""; report(); } + }); + report(); +})(); +`; + } +}); + +// daemon/src/preview/proxy.ts +import { createServer as createServer2, request as httpRequest } from "node:http"; +import { request as httpsRequest } from "node:https"; +import { connect as netConnect, isIP } from "node:net"; +import { connect as tlsConnect } from "node:tls"; +import { randomBytes as randomBytes3 } from "node:crypto"; +function esc(s) { + return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); +} +function rewriteRequestHeaders(inH, t, proxyOrigin, upgrade) { + const out = {}; + const targetOrigin = displayOrigin(t.origin); + for (const [k, v] of Object.entries(inH)) { + if (v === void 0) continue; + const key = k.toLowerCase(); + if (!upgrade && HOP.has(key)) continue; + if (upgrade && (key === "proxy-connection" || key === "proxy-authorization" || key === "keep-alive" || key === "te" || key === "trailer" || key === "transfer-encoding")) continue; + if (key === "cookie" || key === "host" || key === "origin" || key === "referer" || key === "forwarded" || key.startsWith("x-forwarded-")) continue; + out[key] = v; + } + out.host = t.hostHeader.replace(/:(80|443)$/, (m) => m === ":80" && !t.secure || m === ":443" && t.secure ? "" : m); + if (inH.origin !== void 0) out.origin = targetOrigin; + const ref = inH.referer; + if (typeof ref === "string" && (ref === proxyOrigin || ref.startsWith(proxyOrigin + "/"))) out.referer = targetOrigin + ref.slice(proxyOrigin.length); + if (inH["sec-fetch-site"] !== void 0) out["sec-fetch-site"] = "same-origin"; + if (!upgrade) out["accept-encoding"] = "identity"; + return out; +} +function rewriteResponseHeaders(inH, t, proxyOrigin) { + const out = {}; + for (const [k, v] of Object.entries(inH)) { + if (v === void 0) continue; + const key = k.toLowerCase(); + if (HOP.has(key)) continue; + if (key === "x-frame-options" || key === "set-cookie" || key === "referrer-policy" || key.startsWith("access-control-allow-")) continue; + if (key === "content-security-policy" || key === "content-security-policy-report-only") { + const kept = (Array.isArray(v) ? v : [v]).map(stripFrameAncestors).filter(Boolean); + if (kept.length) out[key] = kept.join(", "); + continue; + } + if (key === "location" && typeof v === "string") { + out[key] = rewriteLocation(v, t, proxyOrigin); + continue; + } + out[key] = v; + } + out["access-control-allow-origin"] = "null"; + out["referrer-policy"] = "no-referrer"; + const vary = typeof out.vary === "string" ? out.vary : ""; + out.vary = vary ? /\borigin\b/i.test(vary) ? vary : `${vary}, Origin` : "Origin"; + return out; +} +function stripFrameAncestors(csp) { + return csp.split(";").map((d) => d.trim()).filter((d) => d && !/^frame-ancestors(\s|$)/i.test(d)).join("; "); +} +function rewriteLocation(loc, t, proxyOrigin) { + let u; + try { + u = new URL(loc, t.href); + } catch { + return loc; + } + if (!/^[a-z][a-z0-9+.-]*:/i.test(loc) && !loc.startsWith("//")) return loc; + const port = u.port ? Number(u.port) : u.protocol === "https:" ? 443 : 80; + const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, ""); + if (u.protocol === (t.secure ? "https:" : "http:") && host === t.hostname && port === t.port) { + return proxyOrigin + u.pathname + u.search + u.hash; + } + return loc; +} +function looksLikeMagpie(h) { + return Object.keys(h).some((k) => k.toLowerCase().startsWith("x-magpie-")); +} +function magpieIndex(body) { + try { + const j = JSON.parse(body); + return !!j && typeof j === "object" && j.name === "magpie" && (Array.isArray(j.apis) || typeof j.version === "string"); + } catch { + return false; + } +} +async function identify(t, addrs, timeoutMs) { + for (const addr of addrs) { + const r = await new Promise((resolve4) => { + let settled = false; + const done = (v) => { + if (!settled) { + settled = true; + clearTimeout(timer); + resolve4(v); + } + }; + const reqFn = t.secure ? httpsRequest : httpRequest; + const q = reqFn({ + host: addr, + port: t.port, + method: "GET", + path: "/", + headers: { host: t.hostHeader, accept: "application/json", "accept-encoding": "identity", "user-agent": "agent-console-preview-check" }, + agent: false, + ...t.secure ? { rejectUnauthorized: false, servername: isIP(t.hostname) ? void 0 : t.hostname } : {} + }); + const timer = setTimeout(() => { + q.destroy(); + done("none"); + }, timeoutMs); + q.on("error", () => done("none")); + q.on("response", (res) => { + if (looksLikeMagpie(res.headers)) { + res.destroy(); + return done("magpie"); + } + const ct = String(res.headers["content-type"] ?? "").toLowerCase(); + if (!ct.includes("json")) { + res.destroy(); + return done("other"); + } + const chunks = []; + let size = 0; + res.on("data", (c) => { + size += c.length; + if (size > 256 * 1024) { + res.destroy(); + done("other"); + return; + } + chunks.push(c); + }); + res.on("end", () => done(magpieIndex(Buffer.concat(chunks).toString("utf8")) ? "magpie" : "other")); + res.on("error", () => done("none")); + }); + q.end(); + }); + if (r !== "none") return r; + } + return "none"; +} +var PreviewError, HOP, RETRY_CODES, IDENTITY_TTL, PREVIEW_PING_PATH, PreviewProxy; +var init_proxy = __esm({ + "daemon/src/preview/proxy.ts"() { + init_security(); + init_url(); + init_inject(); + PreviewError = class extends Error { + code; + constructor(code, message) { + super(message); + this.code = code; + } + }; + HOP = /* @__PURE__ */ new Set(["connection", "keep-alive", "proxy-connection", "proxy-authorization", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade"]); + RETRY_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "EADDRNOTAVAIL", "EAFNOSUPPORT", "ENETUNREACH", "EHOSTUNREACH", "ECONNRESET", "ETIMEDOUT"]); + IDENTITY_TTL = 60 * 1e3; + PREVIEW_PING_PATH = "/__agent_console__/ping"; + PreviewProxy = class { + constructor(opts) { + this.opts = opts; + this.idleMs = opts.idleMs ?? 10 * 60 * 1e3; + this.maxTargets = opts.maxTargets ?? 8; + this.maxHtml = opts.maxHtmlBytes ?? 8 * 1024 * 1024; + this.now = opts.now ?? Date.now; + this.identityTimeout = opts.identityTimeoutMs ?? 30 * 1e3; + } + opts; + byOrigin = /* @__PURE__ */ new Map(); + opening = /* @__PURE__ */ new Map(); + sweepTimer = null; + idleMs; + maxTargets; + maxHtml; + now; + identityTimeout; + /** Ports of the listeners themselves (a preview of a preview is refused) */ + ports() { + return [...this.byOrigin.values()].map((l) => l.port); + } + get size() { + return this.byOrigin.size; + } + async open(raw) { + const c = checkPreviewUrl(raw); + if (!c.ok) throw new PreviewError(c.reason, `preview url refused: ${c.reason}`); + const t = c.target; + if (deniedPort(t.port, [...this.opts.deniedPorts(), ...this.ports()])) { + throw new PreviewError("denied_port", `port ${t.port} can't be previewed`); + } + let l = this.byOrigin.get(t.origin); + if (!l) { + const who = await identify(t, t.connect, Math.min(3e3, this.identityTimeout)); + if (who === "magpie") { + this.opts.log?.("warn", `preview refused: ${t.origin} answers like Magpie's gateway`); + throw new PreviewError("denied_port", `${t.origin} is Magpie's gateway`); + } + let p = this.opening.get(t.origin); + if (!p) { + p = this.listen(t).finally(() => this.opening.delete(t.origin)); + this.opening.set(t.origin, p); + } + l = await p; + } + l.lastUsed = this.now(); + l.nonce = randomBytes3(16).toString("hex"); + l.canaryAuthority = `acprobe${randomBytes3(16).toString("hex")}.localhost:${l.port}`; + l.canaryNonce = randomBytes3(16).toString("hex"); + this.ensureSweep(); + return { + proxyOrigin: l.proxyOrigin, + target: t.origin, + url: t.href, + path: t.path, + proxyHref: l.proxyOrigin + t.path, + nonce: l.nonce, + canaryOrigin: `http://${l.canaryAuthority}`, + canaryNonce: l.canaryNonce + }; + } + /** Close the listener for this target (any URL on it, or its origin) */ + release(raw) { + const c = checkPreviewUrl(raw); + if (!c.ok) return false; + const l = this.byOrigin.get(c.target.origin); + if (!l) return false; + this.close(l); + return true; + } + closeAll() { + for (const l of [...this.byOrigin.values()]) this.close(l); + if (this.sweepTimer) clearInterval(this.sweepTimer); + this.sweepTimer = null; + } + /** Close listeners idle for idleMs (no request and no open WebSocket); exposed for tests with a fake clock */ + sweep() { + const now = this.now(); + for (const l of [...this.byOrigin.values()]) { + if (l.tunnels === 0 && now - l.lastUsed > this.idleMs) { + this.opts.log?.("info", `preview proxy for ${l.target.origin} idle, closing`); + this.close(l); + } + } + if (this.byOrigin.size === 0 && this.sweepTimer) { + clearInterval(this.sweepTimer); + this.sweepTimer = null; + } + } + ensureSweep() { + if (this.sweepTimer) return; + this.sweepTimer = setInterval(() => this.sweep(), 60 * 1e3); + this.sweepTimer.unref(); + } + close(l) { + if (this.byOrigin.get(l.target.origin) === l) this.byOrigin.delete(l.target.origin); + try { + l.server.close(); + } catch { + } + for (const s of l.sockets) s.destroy(); + l.sockets.clear(); + } + async listen(t) { + while (this.byOrigin.size >= this.maxTargets) { + const oldest = [...this.byOrigin.values()].sort((a2, b) => a2.lastUsed - b.lastUsed)[0]; + if (!oldest) break; + this.close(oldest); + } + const server = createServer2(); + const l = { + target: t, + server, + port: 0, + authority: "", + proxyOrigin: "", + nonce: "", + canaryAuthority: "", + canaryNonce: "", + magpie: false, + checkedAt: 0, + resolving: null, + lastUsed: this.now(), + sockets: /* @__PURE__ */ new Set(), + tunnels: 0, + addr: null + }; + server.on("connection", (s) => { + l.sockets.add(s); + s.on("close", () => l.sockets.delete(s)); + }); + server.on("request", (req, res) => this.onRequest(l, req, res)); + server.on("upgrade", (req, socket, head) => this.onUpgrade(l, req, socket, head)); + server.on("clientError", (_e, socket) => { + try { + socket.destroy(); + } catch { + } + }); + await new Promise((resolve4, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => resolve4()); + }); + const a = server.address(); + l.port = a && typeof a === "object" ? a.port : 0; + l.authority = `ac${randomBytes3(16).toString("hex")}.localhost:${l.port}`; + l.proxyOrigin = `http://${l.authority}`; + this.byOrigin.set(t.origin, l); + this.opts.log?.("info", `preview proxy 127.0.0.1:${l.port} \u2192 ${t.origin}`); + return l; + } + // ---- request gate shared by HTTP and WS ---- + /** null = refuse; otherwise which name matched (canary is ping-only) */ + gate(l, req) { + const host = String(req.headers.host ?? "").toLowerCase(); + let role = null; + if (l.authority && tokenEqual(host, l.authority)) role = "key"; + else if (l.canaryAuthority && tokenEqual(host, l.canaryAuthority)) role = "canary"; + else { + return checkHost(req.headers.host, l.port).ok ? { code: 403, why: "preview_key" } : { code: 421, why: "bad_host" }; + } + const o = req.headers.origin; + if (o !== void 0 && o !== "" && o !== "null") { + if (role === "key" && o.toLowerCase() !== l.proxyOrigin) return { code: 403, why: "bad_origin" }; + if (role === "canary") return { code: 403, why: "bad_origin" }; + } + return { role }; + } + /** A refusal: plain text, no CORS headers (the page that sent it can't read it), nothing forwarded */ + refuse(res, req, code, why) { + res.writeHead(code, { + "content-type": "text/plain; charset=utf-8", + "cache-control": "no-store", + "x-content-type-options": "nosniff", + "content-security-policy": "sandbox; default-src 'none'", + "referrer-policy": "no-referrer" + }); + res.end(req.method === "HEAD" ? void 0 : why); + req.resume(); + } + onRequest(l, req, res) { + const g = this.gate(l, req); + if ("code" in g) { + this.refuse(res, req, g.code, g.why); + return; + } + l.lastUsed = this.now(); + const path3 = (req.url ?? "/").split("?")[0]; + if (path3 === PREVIEW_PING_PATH) { + const body = g.role === "canary" ? l.canaryNonce : l.nonce; + res.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null", "referrer-policy": "no-referrer" }); + res.end(req.method === "HEAD" ? void 0 : body); + req.resume(); + return; + } + if (g.role === "canary") { + this.refuse(res, req, 403, "preview_canary"); + return; + } + if (l.magpie) { + this.refuse(res, req, 403, "magpie"); + return; + } + if (path3 === PREVIEW_SCRIPT_PATH) { + res.writeHead(200, { + "content-type": "text/javascript; charset=utf-8", + "cache-control": "no-store", + "access-control-allow-origin": "null", + "x-content-type-options": "nosniff", + "referrer-policy": "no-referrer" + }); + res.end(req.method === "HEAD" ? void 0 : PREVIEW_SCRIPT); + return; + } + if (req.method === "OPTIONS" && req.headers["access-control-request-method"]) { + const h = { + "access-control-allow-origin": "null", + "access-control-allow-methods": String(req.headers["access-control-request-method"]).slice(0, 200) + ", GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD", + "access-control-max-age": "600", + vary: "origin" + }; + const rh = req.headers["access-control-request-headers"]; + if (typeof rh === "string") h["access-control-allow-headers"] = rh.slice(0, 2e3); + res.writeHead(204, h); + res.end(); + req.resume(); + return; + } + void this.forward(l, req, res); + } + /** + * The address to forward to, once the target is known not to be Magpie's gateway (asked again after IDENTITY_TTL). + * Fails closed: no answer to the identity check → null (error page), Magpie → l.magpie (refused from then on). + */ + resolveAddr(l) { + if (l.magpie) return Promise.resolve(null); + if (l.addr && this.now() - l.checkedAt < IDENTITY_TTL) return Promise.resolve(l.addr); + if (!l.resolving) { + l.resolving = (async () => { + const addr = l.addr ?? await this.probeAddr(l); + if (!addr) return null; + const who = await identify(l.target, [addr], this.identityTimeout); + if (who === "magpie") { + l.magpie = true; + l.addr = null; + this.opts.log?.("warn", `preview proxy for ${l.target.origin}: the target answers like Magpie's gateway, refusing`); + return null; + } + if (who === "none") { + l.addr = null; + return null; + } + l.addr = addr; + l.checkedAt = this.now(); + return addr; + })().finally(() => { + l.resolving = null; + }); + } + return l.resolving; + } + async probeAddr(l) { + for (const host of l.target.connect) { + const ok = await new Promise((resolve4) => { + const s = netConnect({ host, port: l.target.port }); + const done = (v) => { + s.removeAllListeners(); + s.destroy(); + resolve4(v); + }; + s.setTimeout(3e3, () => done(false)); + s.once("connect", () => done(true)); + s.once("error", () => done(false)); + }); + if (ok) return host; + } + return null; + } + servername(l) { + return isIP(l.target.hostname) ? void 0 : l.target.hostname; + } + async forward(l, req, res) { + const addr = await this.resolveAddr(l); + if (l.magpie) { + this.refuse(res, req, 403, "magpie"); + return; + } + if (!addr) { + this.errorPage(l, req, res); + return; + } + const headers = rewriteRequestHeaders(req.headers, l.target, l.proxyOrigin, false); + const reqFn = l.target.secure ? httpsRequest : httpRequest; + const up = reqFn({ + host: addr, + port: l.target.port, + method: req.method, + path: req.url ?? "/", + headers, + ...l.target.secure ? { rejectUnauthorized: false, servername: this.servername(l) } : {} + }); + up.on("response", (ur) => this.respond(l, req, res, ur)); + up.on("error", (e) => { + if (RETRY_CODES.has(e.code ?? "")) l.addr = null; + if (!res.headersSent) this.errorPage(l, req, res); + else res.destroy(); + }); + req.on("aborted", () => up.destroy()); + res.on("close", () => { + if (!res.writableFinished) up.destroy(); + }); + req.pipe(up); + } + respond(l, req, res, ur) { + l.lastUsed = this.now(); + if (looksLikeMagpie(ur.headers)) { + l.magpie = true; + l.addr = null; + ur.resume(); + this.refuse(res, req, 403, "magpie"); + return; + } + const h = rewriteResponseHeaders(ur.headers, l.target, l.proxyOrigin); + const status = ur.statusCode ?? 502; + const ctype = String(ur.headers["content-type"] ?? "").toLowerCase(); + const encoded = !!ur.headers["content-encoding"] && ur.headers["content-encoding"] !== "identity"; + const html = ctype.includes("text/html") && !encoded && req.method !== "HEAD" && status !== 204 && status !== 304; + if (!html) { + res.writeHead(status, h); + ur.pipe(res); + return; + } + const chunks = []; + let size = 0; + let passthrough = false; + ur.on("data", (c) => { + if (passthrough) return; + size += c.length; + chunks.push(c); + if (size > this.maxHtml) { + passthrough = true; + res.writeHead(status, h); + for (const x of chunks) res.write(x); + ur.removeAllListeners("data"); + ur.removeAllListeners("end"); + ur.pipe(res); + } + }); + ur.on("end", () => { + if (passthrough) return; + const out = Buffer.from(injectScriptTag(Buffer.concat(chunks).toString("latin1")), "latin1"); + h["content-length"] = String(out.length); + res.writeHead(status, h); + res.end(out); + }); + ur.on("error", () => res.destroy()); + } + errorPage(l, req, res) { + const where = displayOrigin(l.target.origin).replace(/^https?:\/\//, ""); + const body = `${esc(where)} + +
    ${esc(where)} \u6CA1\u6709\u54CD\u5E94\uFF0Cdev server \u542F\u52A8\u4E86\u5417\uFF1F
    ${esc(where)} is not responding. Is the dev server running?
    +
    `; + res.writeHead(502, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null" }); + res.end(req.method === "HEAD" ? void 0 : body); + req.resume(); + } + // ---- WebSocket (HMR) ---- + onUpgrade(l, req, socket, head) { + const g = this.gate(l, req); + if ("code" in g || g.role === "canary" || l.magpie) { + const code = "code" in g ? g.code : 403; + socket.end(`HTTP/1.1 ${code} ${code === 421 ? "Misdirected Request" : "Forbidden"}\r +connection: close\r +\r +`); + return; + } + l.lastUsed = this.now(); + socket.on("error", () => { + }); + void this.resolveAddr(l).then((addr) => { + if (!addr || socket.destroyed) { + socket.end("HTTP/1.1 502 Bad Gateway\r\nconnection: close\r\n\r\n"); + return; + } + const up = l.target.secure ? tlsConnect({ host: addr, port: l.target.port, rejectUnauthorized: false, servername: this.servername(l) }) : netConnect({ host: addr, port: l.target.port }); + const ready = l.target.secure ? "secureConnect" : "connect"; + l.tunnels++; + let counted = true; + const done = () => { + if (counted) { + counted = false; + l.tunnels--; + l.lastUsed = this.now(); + } + up.destroy(); + socket.destroy(); + }; + up.once(ready, () => { + const lines = [`${req.method ?? "GET"} ${req.url ?? "/"} HTTP/1.1`]; + const hs = rewriteRequestHeaders(req.headers, l.target, l.proxyOrigin, true); + for (const [k, v] of Object.entries(hs)) { + if (v === void 0) continue; + for (const one of Array.isArray(v) ? v : [v]) lines.push(`${k}: ${String(one).replace(/[\r\n]/g, "")}`); + } + up.write(lines.join("\r\n") + "\r\n\r\n"); + if (head?.length) up.write(head); + up.pipe(socket); + socket.pipe(up); + }); + up.on("data", () => { + l.lastUsed = this.now(); + }); + up.on("error", done); + up.on("close", done); + socket.on("close", done); + }); + } + }; + } +}); + +// daemon/src/preview/host.ts +import os from "node:os"; +function previewHost(platform = os.platform(), release2 = os.release()) { + if (platform !== "darwin") return { platform, darwinMajor: null }; + const m = /^(\d+)\./.exec(String(release2 ?? "").trim()) ?? /^(\d+)$/.exec(String(release2 ?? "").trim()); + const major = m ? Number(m[1]) : NaN; + return { platform, darwinMajor: Number.isInteger(major) && major > 0 ? major : null }; +} +var init_host = __esm({ + "daemon/src/preview/host.ts"() { + } +}); + // daemon/src/ws/methods.ts import { z } from "zod"; -import { existsSync as existsSync8, statSync as statSync4 } from "node:fs"; +import { existsSync as existsSync9, statSync as statSync4 } from "node:fs"; import { mkdir as mkdir3, writeFile as writeFile4 } from "node:fs/promises"; import { homedir as homedir8 } from "node:os"; import { dirname as dirname3, join as join12, win32 as win32Path } from "node:path"; -import { execFile as execFile3 } from "node:child_process"; +import { execFile as execFile4 } from "node:child_process"; function wrap(schema, fn) { return (params, ctx) => { const r = schema.safeParse(params ?? {}); @@ -5240,6 +6163,10 @@ function wrap(schema, fn) { } function registerMethods(gw, svc) { const zEmpty = z.object({}).passthrough().optional(); + gw.method("app.setLocale", wrap(z.object({ lang: z.string().max(32) }), (p) => { + setAppLocale(p.lang); + return true; + })); gw.method("app.info", wrap(zEmpty, () => ({ version: svc.cfg.version, dataDir: svc.cfg.dataDir, @@ -5250,6 +6177,33 @@ function registerMethods(gw, svc) { setTimeout(() => process.exit(0), 100); return { ok: true }; })); + gw.method("app.openExternal", wrap(z.object({ url: z.string().min(1).max(MAX_PREVIEW_URL) }), async (p) => openExternal(p.url))); + gw.method("preview.open", wrap( + z.object({ url: z.string().min(1).max(MAX_PREVIEW_URL), threadId: z.string().max(200).optional() }), + async (p) => { + if (!svc.preview) throw new ApiError("unavailable", tr("err.previewUnavailable")); + let r; + try { + r = await svc.preview.open(p.url); + } catch (e) { + if (e instanceof PreviewError) { + throw new ApiError(e.code === "denied_port" ? "preview_denied" : "preview_url", tr(e.code === "denied_port" ? "err.previewDenied" : "err.previewUrl")); + } + throw e; + } + if (p.threadId) { + const meta = await svc.threads.get(p.threadId); + if (meta && meta.previewUrl !== r.url) { + const next = await svc.threads.patch(p.threadId, { previewUrl: r.url }); + gw.publish("sidebar", { type: "thread.upsert", thread: next }); + } + } + return { ...r, host: previewHost() }; + } + )); + gw.method("preview.release", wrap(z.object({ url: z.string().min(1).max(MAX_PREVIEW_URL) }), (p) => ({ + ok: svc.preview?.release(p.url) ?? false + }))); gw.method("settings.get", wrap(zEmpty, () => svc.settings.get())); gw.method("settings.set", wrap(z.object({ patch: z.record(z.string(), z.unknown()) }), async (p) => { const checked = parseSettingsPatch(p.patch); @@ -5352,10 +6306,10 @@ function registerMethods(gw, svc) { gw.method("projects.open", wrap(z.object({ id: z.string() }), async (p) => { const proj = await svc.projects.get(p.id); if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); - if (!existsSync8(proj.path)) throw new ApiError("bad_path", tr("err.dirMissing")); + if (!existsSync9(proj.path)) throw new ApiError("bad_path", tr("err.dirMissing")); const cmd = process.platform === "win32" ? "explorer.exe" : process.platform === "darwin" ? "open" : "xdg-open"; const target = process.platform === "win32" ? win32Path.normalize(proj.path) : proj.path; - execFile3(cmd, [target], { windowsHide: true }, () => { + execFile4(cmd, [target], { windowsHide: true }, () => { }).on("error", () => { }); return { ok: true }; @@ -5364,7 +6318,7 @@ function registerMethods(gw, svc) { let exists = false; let isDir2 = false; try { - exists = existsSync8(p.path); + exists = existsSync9(p.path); isDir2 = exists && statSync4(p.path).isDirectory(); } catch { } @@ -5393,7 +6347,7 @@ function registerMethods(gw, svc) { async (p) => { const proj = await svc.projects.get(p.projectId); if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); - if (!existsSync8(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone")); + if (!existsSync9(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone")); if (!p.providerSessionId && !isProviderEnabled(await svc.settings.get(), p.provider)) { throw new ApiError("bad_params", tr("provider.disabledNamed", { name: catalogById(p.provider)?.name ?? p.provider })); } @@ -5429,7 +6383,8 @@ function registerMethods(gw, svc) { id: z.string(), title: z.string().optional(), pinned: z.boolean().optional(), - archived: z.boolean().optional() + archived: z.boolean().optional(), + previewUrl: z.string().max(MAX_PREVIEW_URL).nullable().optional() }), async (p) => { const meta = await svc.threads.get(p.id); @@ -5441,6 +6396,14 @@ function registerMethods(gw, svc) { } if (p.pinned !== void 0) patch.pinned = p.pinned; if (p.archived !== void 0) patch.archived = p.archived; + if (p.previewUrl !== void 0) { + if (p.previewUrl === null) patch.previewUrl = null; + else { + const c = checkPreviewUrl(p.previewUrl); + if (!c.ok) throw new ApiError("bad_params", tr("err.previewUrl")); + patch.previewUrl = c.target.href; + } + } const next = await svc.threads.patch(p.id, patch); gw.publish("sidebar", { type: "thread.upsert", thread: next }); return next; @@ -5457,7 +6420,7 @@ function registerMethods(gw, svc) { const projectPath = async (projectId) => { const proj = await svc.projects.get(projectId); if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); - if (!existsSync8(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone")); + if (!existsSync9(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone")); return proj.path; }; gw.method("git.status", wrap( @@ -5564,10 +6527,12 @@ function registerMethods(gw, svc) { id: z.string(), text: z.string(), attachments: z.array(z.object({ path: z.string(), mime: z.string(), name: z.string().optional() })).optional(), + // 1.2: paths dragged from the Files panel, relative to the project (the daemon resolves and checks them) + mentions: z.array(z.object({ rel: z.string().min(1).max(4096), isDir: z.boolean().optional() })).max(MAX_MENTIONS).optional(), behavior: z.enum(["queue", "steer"]).optional() }), async (p) => { - const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? "queue"); + const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments, mentions: p.mentions }, p.behavior ?? "queue"); return { ok: true, delivered: delivered ?? "started" }; } )); @@ -5638,11 +6603,13 @@ function registerMethods(gw, svc) { L.push(`> ${meta.provider} \xB7 ${meta.model ?? tr("export.defaultModel")} \xB7 ${meta.mode} \xB7 ${new Date(meta.createdAt).toLocaleString(intlLocale())}`, ""); for (const e of events) { switch (e.type) { - case "user_message": + case "user_message": { + const refs = e.mentions?.length ? "\n\n" + e.mentions.map((m) => `- \`${m.path}${m.isDir ? "/" : ""}\``).join("\n") : ""; L.push(`**${tr("export.me")}**${e.steered ? tr("export.steered") : ""}: -${e.text}`, ""); +${e.text}${refs}`, ""); break; + } case "assistant_message": L.push(e.text, ""); break; @@ -5691,7 +6658,7 @@ ${e.text} await mkdir3(dir, { recursive: true }); } let dest = join12(dir, filename); - if (existsSync8(dest)) { + if (existsSync9(dest)) { const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19); dest = join12(dir, `${safe}-${stamp2}.md`); } @@ -5702,18 +6669,18 @@ ${e.text} } function revealInFileManager(filePath) { if (process.platform === "win32") { - execFile3("explorer.exe", ["/select," + win32Path.normalize(filePath)], { windowsHide: true }, () => { + execFile4("explorer.exe", ["/select," + win32Path.normalize(filePath)], { windowsHide: true }, () => { }).on("error", () => { }); return; } if (process.platform === "darwin") { - execFile3("open", ["-R", filePath], () => { + execFile4("open", ["-R", filePath], () => { }).on("error", () => { }); return; } - execFile3("xdg-open", [dirname3(filePath)], () => { + execFile4("xdg-open", [dirname3(filePath)], () => { }).on("error", () => { }); } @@ -5730,6 +6697,11 @@ var init_methods = __esm({ init_launch(); init_modes(); init_i18n(); + init_mentions(); + init_openExternal(); + init_proxy(); + init_url(); + init_host(); threadModeSchema = z.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]); ApiError = class extends Error { code; @@ -5790,10 +6762,14 @@ function sanitizeStored(raw) { } return out; } -var DEFAULT_SETTINGS, IDLE_CLOSE_MIN, IDLE_CLOSE_MAX, mode, id, settingsPatchSchema, SettingsStore; +var CONTENT_WIDTHS, CHAT_FONT_MIN, CHAT_FONT_MAX, CHAT_FONT_DEFAULT, DEFAULT_SETTINGS, IDLE_CLOSE_MIN, IDLE_CLOSE_MAX, mode, id, settingsPatchSchema, SettingsStore; var init_settings = __esm({ "daemon/src/store/settings.ts"() { init_atomic(); + CONTENT_WIDTHS = ["narrow", "default", "wide", "full"]; + CHAT_FONT_MIN = 12; + CHAT_FONT_MAX = 18; + CHAT_FONT_DEFAULT = 13; DEFAULT_SETTINGS = { defaultProvider: "claude", defaultMode: "default", @@ -5801,6 +6777,8 @@ var init_settings = __esm({ runningSend: "queue", showThinking: true, theme: "auto", + contentWidth: "default", + chatFontSize: CHAT_FONT_DEFAULT, idleCloseMinutes: 30, collapsedProjects: [], panel: { open: false, tab: "changes", width: 440 }, @@ -5821,10 +6799,13 @@ var init_settings = __esm({ showThinking: z2.boolean(), // auto = follow the host: Magpie's light/dark inside Magpie, the OS outside it theme: z2.enum(["auto", "light", "dark"]), + contentWidth: z2.enum(CONTENT_WIDTHS), + chatFontSize: z2.number().int().min(CHAT_FONT_MIN).max(CHAT_FONT_MAX), idleCloseMinutes: z2.number().int().min(IDLE_CLOSE_MIN).max(IDLE_CLOSE_MAX), collapsedProjects: z2.array(id).max(1e3), panel: z2.object({ open: z2.boolean(), tab: z2.string().max(40), width: z2.number().min(0).max(5e3) }).partial(), sidebarWidth: z2.number().min(0).max(5e3), + sidebarHidden: z2.boolean(), lastProjectId: id.nullable(), lastThreadId: id.nullable(), recentDirs: z2.array(z2.string().max(4096)).max(50), @@ -5919,8 +6900,8 @@ __export(legacy_exports, { migrateLegacy: () => migrateLegacy }); import { cp as cp2, mkdir as mkdir8, readdir as readdir6, readFile as readFile18 } from "node:fs/promises"; -import { existsSync as existsSync12 } from "node:fs"; -import { join as join19 } from "node:path"; +import { existsSync as existsSync13 } from "node:fs"; +import { join as join20 } from "node:path"; function stamp() { const d = /* @__PURE__ */ new Date(); const p = (n) => String(n).padStart(2, "0"); @@ -5929,19 +6910,19 @@ function stamp() { async function migrateLegacy(dataDir, stores) { const settings = await stores.settings.get(); if (settings.v1Migrated) return { migrated: 0, skipped: true }; - const oldDir = join19(dataDir, "sessions"); - const oldSettingsPath = join19(dataDir, "settings.json"); - if (!existsSync12(oldDir) && !existsSync12(oldSettingsPath)) { + const oldDir = join20(dataDir, "sessions"); + const oldSettingsPath = join20(dataDir, "settings.json"); + if (!existsSync13(oldDir) && !existsSync13(oldSettingsPath)) { await stores.settings.set({ v1Migrated: true }); return { migrated: 0, skipped: true }; } - const backup = join19(dataDir, "trash", `legacy-${stamp()}`); + const backup = join20(dataDir, "trash", `legacy-${stamp()}`); await mkdir8(backup, { recursive: true }); - if (existsSync12(oldDir)) await cp2(oldDir, join19(backup, "sessions"), { recursive: true }).catch(() => { + if (existsSync13(oldDir)) await cp2(oldDir, join20(backup, "sessions"), { recursive: true }).catch(() => { }); - if (existsSync12(oldSettingsPath)) await cp2(oldSettingsPath, join19(backup, "settings.json")).catch(() => { + if (existsSync13(oldSettingsPath)) await cp2(oldSettingsPath, join20(backup, "settings.json")).catch(() => { }); - const oldSettings = existsSync12(oldSettingsPath) ? JSON.parse(await readFile18(oldSettingsPath, "utf8").catch(() => "{}")) : {}; + const oldSettings = existsSync13(oldSettingsPath) ? JSON.parse(await readFile18(oldSettingsPath, "utf8").catch(() => "{}")) : {}; const projectIdByPath = /* @__PURE__ */ new Map(); const lc = (p) => p.replace(/\\/g, "/").toLowerCase().replace(/\/+$/, ""); for (const p of oldSettings.projects ?? []) { @@ -5955,13 +6936,13 @@ async function migrateLegacy(dataDir, stores) { } let sessionIds = []; try { - sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync12(join19(oldDir, d, "meta.json"))); + sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync13(join20(oldDir, d, "meta.json"))); } catch { } const metas = []; for (const id2 of sessionIds) { try { - const m = JSON.parse(await readFile18(join19(oldDir, id2, "meta.json"), "utf8")); + const m = JSON.parse(await readFile18(join20(oldDir, id2, "meta.json"), "utf8")); if (m?.cwd) metas.push(m); } catch { } @@ -5975,7 +6956,7 @@ async function migrateLegacy(dataDir, stores) { extraDirs.push(m.cwd); } for (const d of extraDirs) { - if (!existsSync12(d)) continue; + if (!existsSync13(d)) continue; try { const name = d.replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? d; const proj = await stores.projects.create(d, name); @@ -5994,7 +6975,7 @@ async function migrateLegacy(dataDir, stores) { return best ? projectIdByPath.get(best) : null; }; let migrated = 0; - const threadsDir = join19(dataDir, "threads"); + const threadsDir = join20(dataDir, "threads"); for (const m of metas) { try { const projectId = projectOf(m.cwd); @@ -6031,10 +7012,10 @@ async function migrateLegacy(dataDir, stores) { importedFrom: m.cliSessionId ? { provider, sessionId: m.cliSessionId } : void 0, seq: 0 }; - const tdir = join19(threadsDir, meta.id); - if (existsSync12(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80); - await mkdir8(join19(threadsDir, meta.id), { recursive: true }); - const oldEvts = (await readFile18(join19(oldDir, m.id, "events.jsonl"), "utf8").catch(() => "")).split("\n").filter((l) => l.trim()).map((l) => { + const tdir = join20(threadsDir, meta.id); + if (existsSync13(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80); + await mkdir8(join20(threadsDir, meta.id), { recursive: true }); + const oldEvts = (await readFile18(join20(oldDir, m.id, "events.jsonl"), "utf8").catch(() => "")).split("\n").filter((l) => l.trim()).map((l) => { try { return JSON.parse(l); } catch { @@ -6113,9 +7094,9 @@ async function migrateLegacy(dataDir, stores) { seq++; lines.push({ type: "tool_call", itemId: key, kind: "other", title: o.title, status: "failed", seq, ts: Date.now(), threadId: meta.id }); } - for (const ev of lines) await appendJsonl(join19(threadsDir, meta.id, "timeline.jsonl"), ev); + for (const ev of lines) await appendJsonl(join20(threadsDir, meta.id, "timeline.jsonl"), ev); meta.seq = seq; - await writeJsonAtomic(join19(threadsDir, meta.id, "meta.json"), meta); + await writeJsonAtomic(join20(threadsDir, meta.id, "meta.json"), meta); migrated++; } catch (e) { log("warn", "\u8FC1\u79FB\uFF1A\u4F1A\u8BDD\u5931\u8D25", { id: m.id, err: String(e) }); @@ -6180,8 +7161,8 @@ var init_warm = __esm({ // daemon/src/main.ts import { mkdirSync as mkdirSync2, rmSync as rmSync2, chmodSync as chmodSync2 } from "node:fs"; -import { join as join20, dirname as dirname7 } from "node:path"; -import { fileURLToPath as fileURLToPath3 } from "node:url"; +import { join as join21, dirname as dirname8 } from "node:path"; +import { fileURLToPath as fileURLToPath4 } from "node:url"; // daemon/src/config.ts import { randomBytes } from "node:crypto"; @@ -6236,6 +7217,7 @@ function parseConfig(argv) { let data = null; let token = null; let parentPid; + let gatePort; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "--port" && argv[i + 1]) port = Number(argv[++i]); @@ -6246,6 +7228,8 @@ function parseConfig(argv) { else if (a.startsWith("--token=")) token = a.slice(8); else if (a === "--parent-pid" && argv[i + 1]) parentPid = Number(argv[++i]); else if (a.startsWith("--parent-pid=")) parentPid = Number(a.slice(13)); + else if (a === "--gate-port" && argv[i + 1]) gatePort = Number(argv[++i]); + else if (a.startsWith("--gate-port=")) gatePort = Number(a.slice(12)); } if (port == null || !Number.isInteger(port) || port < 0 || port > 65535) { const envPort = Number(process.env.AGENT_CONSOLE_PORT || ""); @@ -6261,7 +7245,8 @@ function parseConfig(argv) { version: pkgVersion(), idleExitMinutes: Number.isFinite(idleEnv) && idleEnv > 0 ? idleEnv : 60, buildStamp: daemonBuildStamp(), - parentPid: Number.isInteger(parentPid) ? parentPid : void 0 + parentPid: Number.isInteger(parentPid) ? parentPid : void 0, + gatePort: Number.isInteger(gatePort) && gatePort > 0 && gatePort <= 65535 ? gatePort : void 0 }; } @@ -6269,35 +7254,13 @@ function parseConfig(argv) { init_log(); // daemon/src/http.ts +init_security(); +init_log(); +init_i18n(); import { createServer } from "node:http"; import { readFile, stat } from "node:fs/promises"; import { existsSync as existsSync2 } from "node:fs"; import { join as join4, normalize, extname } from "node:path"; - -// daemon/src/security.ts -import { timingSafeEqual, createHash } from "node:crypto"; -function checkHost(host, port) { - if (!host) return { ok: false, code: 421, message: "Host \u4E0D\u5BF9" }; - const h = host.toLowerCase(); - if (h === `127.0.0.1:${port}` || h === `localhost:${port}`) return { ok: true }; - return { ok: false, code: 421, message: "Host \u4E0D\u5BF9" }; -} -function classifyOrigin(origin, port) { - if (origin === void 0 || origin === "") return "none"; - if (origin === "null") return "opaque"; - const o = origin.toLowerCase(); - if (o === `http://127.0.0.1:${port}` || o === `http://localhost:${port}`) return "self"; - return "foreign"; -} -function tokenEqual(a, b) { - const ha = createHash("sha256").update(a).digest(); - const hb = createHash("sha256").update(b).digest(); - return timingSafeEqual(ha, hb); -} - -// daemon/src/http.ts -init_log(); -init_i18n(); var MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", @@ -6559,11 +7522,11 @@ init_atomic(); init_paths(); init_methods(); import { readFile as readFile13 } from "node:fs/promises"; -import { existsSync as existsSync9, statSync as statSync5 } from "node:fs"; +import { existsSync as existsSync10, statSync as statSync5 } from "node:fs"; import { join as join14 } from "node:path"; -import { randomBytes as randomBytes3 } from "node:crypto"; +import { randomBytes as randomBytes4 } from "node:crypto"; function newId() { - return "p_" + Date.now().toString(36) + randomBytes3(3).toString("hex"); + return "p_" + Date.now().toString(36) + randomBytes4(3).toString("hex"); } var ProjectsStore = class { file; @@ -6594,7 +7557,7 @@ var ProjectsStore = class { } async create(path3, name) { if (!path3 || typeof path3 !== "string") throw new ApiError("bad_params", "\u8DEF\u5F84\u4E0D\u80FD\u4E3A\u7A7A"); - if (!existsSync9(path3) || !statSync5(path3).isDirectory()) { + if (!existsSync10(path3) || !statSync5(path3).isDirectory()) { throw new ApiError("bad_path", "\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6587\u4EF6\u5939"); } const np = normPath(path3); @@ -6636,9 +7599,9 @@ init_methods(); init_i18n(); import { mkdir as mkdir6, rename as rename3, readdir as readdir4, readFile as readFile15 } from "node:fs/promises"; import { join as join15 } from "node:path"; -import { randomBytes as randomBytes4 } from "node:crypto"; +import { randomBytes as randomBytes5 } from "node:crypto"; function newId2() { - return "t_" + Date.now().toString(36) + randomBytes4(3).toString("hex"); + return "t_" + Date.now().toString(36) + randomBytes5(3).toString("hex"); } var ThreadsStore = class { dir; @@ -6784,10 +7747,11 @@ var ThreadsStore = class { }; // daemon/src/ws/gateway.ts -import { WebSocketServer, WebSocket } from "ws"; -import { randomBytes as randomBytes5 } from "node:crypto"; +init_security(); init_log(); init_i18n(); +import { WebSocketServer, WebSocket } from "ws"; +import { randomBytes as randomBytes6 } from "node:crypto"; var Conn = class { id; ws; @@ -6796,7 +7760,7 @@ var Conn = class { alive = true; lastMsg = Date.now(); constructor(ws) { - this.id = "c_" + randomBytes5(4).toString("hex"); + this.id = "c_" + randomBytes6(4).toString("hex"); this.ws = ws; } send(obj) { @@ -6840,6 +7804,8 @@ var Gateway = class { methods = /* @__PURE__ */ new Map(); helloTimers = /* @__PURE__ */ new Map(); onTerminalInput; + /** Called after a connection closes, with how many are left (the preview proxy closes when none are) */ + onConnectionClosed; method(name, fn) { this.methods.set(name, fn); } @@ -6890,6 +7856,10 @@ var Gateway = class { }); ws.on("close", () => { this.conns.delete(conn.id); + try { + this.onConnectionClosed?.(this.conns.size); + } catch { + } const t = this.helloTimers.get(conn.id); if (t) clearTimeout(t); this.helloTimers.delete(conn.id); @@ -7037,6 +8007,7 @@ var Coalescer = class { init_methods(); init_log(); init_i18n(); +init_mentions(); init_commands(); var SLASH_CACHE_TTL_MS = 10 * 60 * 1e3; var MAX_WARM_IDLE = 3; @@ -7062,6 +8033,17 @@ var AgentManager = class { resolveAttachments(refs) { return resolveAttachmentRefs(this.attachments, refs); } + /** Mentions from the Files panel → absolute paths inside the project; a path that can't be used gets a notice */ + async resolveMentionRefs(threadId, projectId, refs) { + if (!refs?.length) return []; + const proj = await this.projects.get(projectId); + if (!proj) return []; + const { mentions, warnings } = await resolveMentions(proj.path, refs); + if (warnings.length) { + await this.appendRaw(threadId, { type: "notice", level: "warn", message: tr("notice.mentionSkipped", { paths: warnings.join(", ") }) }); + } + return mentions; + } attachmentLabels(refs) { return refs.map((a) => ({ id: a.path, name: (a.name ?? "").trim() || a.path, mime: a.mime })); } @@ -7179,6 +8161,7 @@ var AgentManager = class { // ---- send ---- async send(threadId, input, behavior = "queue") { const meta = await this.mustThread(threadId); + const mentions = await this.resolveMentionRefs(threadId, meta.projectId, input.mentions); if (meta.archived) { await this.threads.patch(threadId, { archived: false }); this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) }); @@ -7202,36 +8185,37 @@ var AgentManager = class { if (behavior === "steer" && provider?.capabilities.steer && rt.session?.steer && !rt.starting) { try { const images = await this.resolveAttachments(attachmentRefs); - await rt.session.steer({ text: input.text, images }); + await rt.session.steer({ text: withMentions(input.text, mentions), images, mentions }); await this.appendRaw(threadId, { type: "user_message", text: input.text, steered: true, - attachments: this.attachmentLabels(attachmentRefs) + attachments: this.attachmentLabels(attachmentRefs), + ...mentions.length ? { mentions } : {} }); return "steered"; } catch (e) { log("info", `thread ${threadId} \u63D2\u8BDD\u5931\u8D25\uFF0C\u6539\u4E3A\u6392\u961F\uFF1A${String(e)}`); } } - const q = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs }; + const q = { id: "q" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), text: input.text, attachments: attachmentRefs, ...mentions.length ? { mentions } : {} }; rt.queue.push(q); this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue }); return "queued"; } - await this.startTurn(threadId, input.text, attachmentRefs); + await this.startTurn(threadId, input.text, attachmentRefs, mentions); return "started"; } - async startTurn(threadId, text, attachmentRefs) { + async startTurn(threadId, text, attachmentRefs, mentions = []) { const rt = this.rt(threadId); rt.starting = true; try { - await this.startTurnInner(threadId, text, attachmentRefs); + await this.startTurnInner(threadId, text, attachmentRefs, mentions); } finally { rt.starting = false; } } - async startTurnInner(threadId, text, attachmentRefs) { + async startTurnInner(threadId, text, attachmentRefs, mentions) { const meta = await this.mustThread(threadId); const rt = this.rt(threadId); const provider = await this.assertProviderUsable(meta.provider, { allowDisabled: !!meta.providerSessionId }); @@ -7254,12 +8238,13 @@ var AgentManager = class { await this.appendRaw(threadId, { type: "user_message", text, - attachments: this.attachmentLabels(attachmentRefs) + attachments: this.attachmentLabels(attachmentRefs), + ...mentions.length ? { mentions } : {} }); await this.setStatus(threadId, "running"); try { const images = await this.resolveAttachments(attachmentRefs); - await rt.session.send({ text, images }); + await rt.session.send({ text: withMentions(text, mentions), images, mentions }); } catch (e) { const msg = String(e?.message ?? e); await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sendFailed", { detail: msg }) }); @@ -7390,7 +8375,7 @@ var AgentManager = class { }); if (next) { this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue }); - await this.startTurn(threadId, next.text, next.attachments).catch((e) => { + await this.startTurn(threadId, next.text, next.attachments, next.mentions ?? []).catch((e) => { log("warn", `thread ${threadId} \u6392\u961F\u6D88\u606F\u542F\u52A8\u5931\u8D25\uFF1A${String(e)}`); }); } @@ -7755,15 +8740,15 @@ var AgentManager = class { // daemon/src/git/service.ts init_i18n(); -import { execFile as execFile4 } from "node:child_process"; -import { existsSync as existsSync10 } from "node:fs"; -import { cp, mkdir as mkdir7, readFile as readFile16, rename as rename4, rm, stat as stat9 } from "node:fs/promises"; -import { join as join16, normalize as normalize2, sep as sep2 } from "node:path"; +import { execFile as execFile5 } from "node:child_process"; +import { existsSync as existsSync11 } from "node:fs"; +import { cp, mkdir as mkdir7, readFile as readFile16, rename as rename4, rm, stat as stat10 } from "node:fs/promises"; +import { join as join16, normalize as normalize2, sep as sep3 } from "node:path"; var TIMEOUT2 = 15e3; var DIFF_LIMIT = 1024 * 1024; function runGit(cwd, args) { return new Promise((res) => { - execFile4("git", ["-c", "core.quotepath=false", ...args], { cwd, timeout: TIMEOUT2, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (e, stdout, stderr) => { + execFile5("git", ["-c", "core.quotepath=false", ...args], { cwd, timeout: TIMEOUT2, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (e, stdout, stderr) => { const code = e && typeof e.code === "number" ? e.code : e ? 1 : 0; const missing = e?.code === "ENOENT"; res({ code, out: String(stdout ?? ""), err: missing ? tr("git.missing") : String(stderr || (e?.message ?? "")) }); @@ -7774,7 +8759,7 @@ function insidePath(projectPath, p) { const rel = normalize2(p).replace(/\\/g, "/"); const abs = normalize2(join16(projectPath, rel)); const proj = normalize2(projectPath); - if (abs !== proj && !abs.startsWith(proj + sep2)) return null; + if (abs !== proj && !abs.startsWith(proj + sep3)) return null; return rel.replace(/\\/g, "/"); } async function moveAcrossDevices(from, to, ops = {}) { @@ -7822,8 +8807,8 @@ var GitService = class { const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]); if (ls.code !== 0) { const full = join16(projectPath, rel); - if (!existsSync10(full)) return { error: tr("fs.fileMissing") }; - const s = await stat9(full); + if (!existsSync11(full)) return { error: tr("fs.fileMissing") }; + const s = await stat10(full); if (!s.isFile()) return { error: tr("fs.notFile") }; if (s.size > DIFF_LIMIT) return { tooLarge: true }; const text = await readFile16(full, "utf8").catch(() => null); @@ -7856,7 +8841,7 @@ ${lines}` }; return { ok: true }; } const full = join16(projectPath, rel); - if (!existsSync10(full)) return { ok: false, error: tr("fs.fileMissing") }; + if (!existsSync11(full)) return { ok: false, error: tr("fs.fileMissing") }; const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19); const dest = join16(dataDir, "trash", "discarded", stamp2, rel); await mkdir7(join16(dest, ".."), { recursive: true }); @@ -7871,8 +8856,8 @@ ${lines}` }; // daemon/src/files/service.ts init_i18n(); -import { readdir as readdir5, readFile as readFile17, stat as stat10 } from "node:fs/promises"; -import { join as join17, normalize as normalize3, sep as sep3, extname as extname3 } from "node:path"; +import { readdir as readdir5, readFile as readFile17, stat as stat11 } from "node:fs/promises"; +import { join as join17, normalize as normalize3, sep as sep4, extname as extname3 } from "node:path"; import ignore from "ignore"; function decodeText(buf) { try { @@ -7937,7 +8922,7 @@ function insidePath2(projectPath, p) { const rel = normalize3(p || ".").replace(/\\/g, "/"); const abs = normalize3(join17(projectPath, rel)); const proj = normalize3(projectPath); - if (abs !== proj && !abs.startsWith(proj + sep3)) return null; + if (abs !== proj && !abs.startsWith(proj + sep4)) return null; return rel; } var FileService = class { @@ -7946,7 +8931,7 @@ var FileService = class { igCache = /* @__PURE__ */ new Map(); async igFor(projectPath) { const gi = join17(projectPath, ".gitignore"); - const st = await stat10(gi).catch(() => null); + const st = await stat11(gi).catch(() => null); const mtime = st?.isFile() ? st.mtimeMs : -1; const hit = this.igCache.get(projectPath); if (hit && hit.mtime === mtime) return hit.ig; @@ -7965,7 +8950,7 @@ var FileService = class { const rel = insidePath2(projectPath, dir); if (rel === null) return { error: tr("fs.pathDenied") }; const abs = join17(projectPath, rel); - const s = await stat10(abs).catch(() => null); + const s = await stat11(abs).catch(() => null); if (!s?.isDirectory()) return { error: tr("fs.dirMissing") }; const ig = await this.igFor(projectPath); const dirents = await readdir5(abs, { withFileTypes: true }).catch(() => null); @@ -7978,7 +8963,7 @@ var FileService = class { const childRel = rel === "." ? name : `${rel}/${name}`; let isDir2 = d.isDirectory(); if (d.isSymbolicLink()) { - const st = await stat10(join17(projectPath, childRel)).catch(() => null); + const st = await stat11(join17(projectPath, childRel)).catch(() => null); if (!st) continue; isDir2 = st.isDirectory(); } else if (!d.isFile() && !isDir2) { @@ -7996,7 +8981,7 @@ var FileService = class { const rel = insidePath2(projectPath, p); if (rel === null) return { error: tr("fs.pathDenied") }; const abs = join17(projectPath, rel); - const s = await stat10(abs).catch(() => null); + const s = await stat11(abs).catch(() => null); if (!s) return { error: tr("fs.fileMissing") }; if (!s.isFile()) return { error: tr("fs.notFile") }; if (s.size > MAX_READ) return { tooLarge: true }; @@ -8014,7 +8999,7 @@ init_pathscan(); init_log(); init_i18n(); import { spawn as spawn3, execFileSync as execFileSync2 } from "node:child_process"; -import { accessSync as accessSync2, chmodSync, constants as fsc, existsSync as existsSync11, statSync as statSync6 } from "node:fs"; +import { accessSync as accessSync2, chmodSync, constants as fsc, existsSync as existsSync12, statSync as statSync6 } from "node:fs"; import { createRequire as moduleRequire } from "node:module"; import { release } from "node:os"; import { dirname as dirname6, join as join18 } from "node:path"; @@ -8064,7 +9049,7 @@ function fixSpawnHelper() { const root = dirname6(req.resolve("node-pty/package.json")); for (const sub of [`prebuilds/darwin-${process.arch}`, "build/Release"]) { const f = join18(root, sub, "spawn-helper"); - if (existsSync11(f) && !isExecFile(f)) { + if (existsSync12(f) && !isExecFile(f)) { chmodSync(f, 493); log("info", "\u5DF2\u4FEE\u590D node-pty spawn-helper \u7684\u53EF\u6267\u884C\u4F4D", { file: f }); } @@ -8296,9 +9281,9 @@ function pidAlive(pid, kill = (p, s) => process.kill(p, s)) { } function augmentPath(env, nodeDir, platform = process.platform, home) { const win = platform === "win32"; - const sep4 = win ? ";" : platform === process.platform ? delimiter : ":"; + const sep5 = win ? ";" : platform === process.platform ? delimiter : ":"; const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH"; - const cur = (env[key] ?? "").split(sep4).filter(Boolean); + const cur = (env[key] ?? "").split(sep5).filter(Boolean); const norm = (d) => win ? d.replace(/[\\/]+$/, "").toLowerCase() : d.replace(/\/+$/, ""); const seen = new Set(cur.map(norm)); const out = [...cur]; @@ -8307,7 +9292,87 @@ function augmentPath(env, nodeDir, platform = process.platform, home) { seen.add(norm(d)); out.push(d); } - return out.join(sep4); + return out.join(sep5); +} + +// daemon/src/main.ts +init_proxy(); + +// daemon/src/preview/ports.ts +import { readFileSync as readFileSync2 } from "node:fs"; +import { homedir as homedir9 } from "node:os"; +import { basename as basename5, dirname as dirname7, isAbsolute as isAbsolute3, join as join19 } from "node:path"; +import { fileURLToPath as fileURLToPath3 } from "node:url"; +var MAGPIE_DEFAULT_PORTS = [3425, 3430]; +var GATE_DEFAULT_PORT = 3488; +function portOf(addr) { + if (!addr) return null; + const m = /:(\d{1,5})\/?$/.exec(addr.trim()); + const n = m ? Number(m[1]) : NaN; + return Number.isInteger(n) && n > 0 && n <= 65535 ? n : null; +} +function magpieDirFromInstall(p) { + const norm = p.replace(/\\/g, "/"); + const i = norm.lastIndexOf("/plugins/node_modules/"); + if (i <= 0) return null; + return p.slice(0, i); +} +function magpieConfigDirs(env = process.env, where = {}) { + const out = []; + const add = (d) => { + if (d && isAbsolute3(d) && !out.includes(d)) out.push(d); + }; + let self = where.self; + if (self === void 0) { + try { + self = fileURLToPath3(import.meta.url); + } catch { + self = ""; + } + } + add(magpieDirFromInstall(self)); + const cwd = where.cwd ?? (env === process.env ? process.cwd() : ""); + if (cwd && basename5(cwd) === "plugin-work") add(dirname7(cwd)); + const x = env.XDG_CONFIG_HOME; + if (x && isAbsolute3(x)) add(join19(x, "magpie")); + const platform = where.platform ?? process.platform; + const home = where.home ?? (env === process.env ? homedir9() : platform === "win32" ? env.USERPROFILE : env.HOME); + if (home) add(join19(home, ".config", "magpie")); + return out; +} +function savedGatewayPort(file, read = (f) => readFileSync2(f, "utf8")) { + let raw; + try { + raw = read(file); + } catch { + return null; + } + try { + const s = JSON.parse(raw); + const p = typeof s?.port === "number" ? s.port : 0; + return Number.isInteger(p) && p >= 1024 && p <= 65535 ? p : MAGPIE_DEFAULT_PORTS[0]; + } catch { + return null; + } +} +function previewDeniedPorts(cfg2, env = process.env, opts = {}) { + const out = /* @__PURE__ */ new Set([cfg2.port, GATE_DEFAULT_PORT, ...MAGPIE_DEFAULT_PORTS]); + if (cfg2.gatePort) out.add(cfg2.gatePort); + for (const k of ["MAGPIE_ADDR", "MAGPIE_WEB_ADDR", "MAGPIE_URL"]) { + const p = portOf(env[k]); + if (p) out.add(p); + } + for (const d of opts.configDirs ?? magpieConfigDirs(env)) { + const p = savedGatewayPort(join19(d, "settings.json"), opts.read); + if (p) out.add(p); + } + const extra = env.AGENT_CONSOLE_PREVIEW_DENY; + if (extra) for (const s of extra.split(/[,\s]+/)) { + const n = Number(s); + if (Number.isInteger(n) && n > 0 && n <= 65535) out.add(n); + } + out.delete(0); + return [...out]; } // daemon/src/main.ts @@ -8316,7 +9381,7 @@ if (nodeMajor < 20) { console.error(`[agent-console] \u9700\u8981 Node.js 20 \u6216\u66F4\u9AD8\u7248\u672C\uFF0C\u5F53\u524D ${process.version}\uFF08${process.execPath}\uFF09`); process.exit(3); } -process.env.PATH = augmentPath(process.env, dirname7(process.execPath)); +process.env.PATH = augmentPath(process.env, dirname8(process.execPath)); var cfg = parseConfig(process.argv.slice(2)); process.on("uncaughtException", (e) => { if (e?.code === "EPIPE") return; @@ -8328,10 +9393,10 @@ process.on("unhandledRejection", (e) => { async function main() { initLog(cfg.dataDir); for (const d of ["threads", "attachments", "trash", "logs"]) { - mkdirSync2(join20(cfg.dataDir, d), { recursive: true }); + mkdirSync2(join21(cfg.dataDir, d), { recursive: true }); } - const appDir = join20(dirname7(fileURLToPath3(import.meta.url)), "..", "..", "app"); - const attachments = new AttachmentStore(join20(cfg.dataDir, "attachments")); + const appDir = join21(dirname8(fileURLToPath4(import.meta.url)), "..", "..", "app"); + const attachments = new AttachmentStore(join21(cfg.dataDir, "attachments")); const { bindAttachmentStore: bindAttachmentStore2 } = await Promise.resolve().then(() => (init_attachmentRefs(), attachmentRefs_exports)); bindAttachmentStore2(attachments); const settings = new SettingsStore(cfg.dataDir); @@ -8348,6 +9413,13 @@ async function main() { const manager = new AgentManager(gateway, threads, projects, settings, attachments); await manager.recoverOnStart(); const terminals = new TerminalService(gateway); + const preview = new PreviewProxy({ + deniedPorts: () => previewDeniedPorts(cfg), + log: (level, msg) => log(level, msg) + }); + gateway.onConnectionClosed = (left) => { + if (left === 0) preview.closeAll(); + }; registerMethods(gateway, { cfg, settings, @@ -8358,6 +9430,7 @@ async function main() { git: new GitService(), files: new FileService(), terminals, + preview, runtime: (id2) => manager.runtimeInfo(id2) }); const server = createHttpServer(cfg, appDir, attachments, { @@ -8390,7 +9463,7 @@ async function main() { const { warmProviderCache: warmProviderCache2 } = await Promise.resolve().then(() => (init_warm(), warm_exports)); await warmProviderCache2(await settings.get()); })().catch((e) => log("warn", "Provider \u9884\u70ED\u5931\u8D25", { err: String(e) })); - const daemonJsonPath = join20(cfg.dataDir, "daemon.json"); + const daemonJsonPath = join21(cfg.dataDir, "daemon.json"); await writeJsonAtomic(daemonJsonPath, { pid: process.pid, port: cfg.port, @@ -8419,6 +9492,7 @@ async function main() { shuttingDown = true; log("info", "daemon \u5173\u95ED\u4E2D"); terminals.killAll(); + preview.closeAll(); gateway.closeAll(); try { rmSync2(daemonJsonPath, { force: true }); diff --git a/packages/agent-console/daemon/dist/main.js.map b/packages/agent-console/daemon/dist/main.js.map index 845c420..dd83daf 100644 --- a/packages/agent-console/daemon/dist/main.js.map +++ b/packages/agent-console/daemon/dist/main.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/log.ts","../src/util/i18n.ts","../src/util/paths.ts","../src/util/queue.ts","../src/agents/diff.ts","../src/providers/slash.ts","../src/providers/mock.ts","../../lib/pathscan.mjs","../src/util/bin.ts","../src/agents/kinds.ts","../src/providers/claude/map.ts","../src/util/attachmentRefs.ts","../src/util/attachmentKinds.ts","../src/providers/claude/content.ts","../src/providers/launch.ts","../src/providers/claude/cli.ts","../src/providers/claude/session.ts","../src/providers/claude/models.ts","../src/history/import.ts","../src/providers/claude/provider.ts","../src/history/codex.ts","../src/providers/codex/rpc.ts","../src/providers/codex/input.ts","../src/providers/codex/map.ts","../src/providers/codex/commands.ts","../src/providers/codex/session.ts","../src/providers/types.ts","../src/providers/codex/provider.ts","../src/providers/catalog.ts","../src/providers/acp/spawn.ts","../src/providers/acp/clientHandlers.ts","../src/providers/acp/mapUpdate.ts","../src/providers/acp/promptCaps.ts","../src/providers/acp/sessionCaps.ts","../src/providers/acp/prompt.ts","../src/providers/acp/session.ts","../src/providers/acp/provider.ts","../src/providers/acp/dsh.ts","../src/providers/acp/probe.ts","../src/providers/acp/specs.ts","../src/providers/registry.ts","../src/providers/enabled.ts","../src/util/pickFolderWin.ts","../src/util/pickFolder.ts","../src/providers/magpieGateway.ts","../src/providers/infoCache.ts","../src/providers/modes.ts","../src/ws/methods.ts","../src/util/atomic.ts","../src/store/settings.ts","../src/util/jsonl.ts","../src/migrate/legacy.ts","../src/providers/warm.ts","../src/main.ts","../src/config.ts","../src/util/buildStamp.ts","../src/http.ts","../src/security.ts","../src/store/attachments.ts","../src/store/projects.ts","../src/store/threads.ts","../src/ws/gateway.ts","../src/agents/manager.ts","../src/timeline/coalescer.ts","../src/git/service.ts","../src/files/service.ts","../src/terminal/service.ts","../src/util/proc.ts"],"sourcesContent":["// Simple logging: writes dataDir/logs/daemon-YYYY-MM-DD.log (kept 7 days) and to the console.\nimport { appendFileSync, mkdirSync, readdirSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nlet logDir = \"\";\nlet today = \"\";\nlet logFile = \"\";\n\nfunction fileName(d: Date): string {\n const p = (n: number) => String(n).padStart(2, \"0\");\n return `daemon-${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}.log`;\n}\n\nexport function initLog(dataDir: string): void {\n logDir = join(dataDir, \"logs\");\n mkdirSync(logDir, { recursive: true });\n // Keep 7 days\n try {\n const keep = new Set();\n const now = new Date();\n for (let i = 0; i < 7; i++) {\n keep.add(fileName(new Date(now.getTime() - i * 86400000)));\n }\n for (const f of readdirSync(logDir)) {\n if (/^daemon-\\d{4}-\\d{2}-\\d{2}\\.log$/.test(f) && !keep.has(f)) {\n rmSync(join(logDir, f), { force: true });\n }\n }\n } catch {}\n}\n\n// The console is a pipe to the plugin host. When the host is killed hard, the reader is gone and a write fails with EPIPE\n// (asynchronously, as an 'error' event on the stream): without a listener that becomes an uncaughtException. Once that happens\n// the console is dropped and only the log file is written.\nlet consoleGone = false;\nlet guarded = false;\nfunction guardConsole(): void {\n if (guarded) return;\n guarded = true;\n for (const stream of [process.stdout, process.stderr]) {\n // EPIPE, EIO, ERR_STREAM_DESTROYED…: any write error means the reader is gone; logging must never take the daemon down\n stream?.on?.(\"error\", () => { consoleGone = true; });\n }\n}\nexport function consoleClosed(): boolean {\n return consoleGone;\n}\n\nexport function log(level: \"info\" | \"warn\" | \"error\", msg: string, extra?: unknown): void {\n const line = `[${new Date().toISOString()}] [${level}] ${msg}${extra !== undefined ? \" \" + safeJson(extra) : \"\"}`;\n try {\n const d = new Date();\n const name = fileName(d);\n if (name !== today && logDir) {\n today = name;\n logFile = join(logDir, name);\n }\n if (logFile) appendFileSync(logFile, line + \"\\n\", \"utf8\");\n } catch {}\n guardConsole();\n if (consoleGone) return;\n const stream = level === \"info\" ? process.stdout : process.stderr;\n if (stream?.destroyed || stream?.writableEnded) { consoleGone = true; return; }\n const fn = level === \"error\" ? console.error : level === \"warn\" ? console.warn : console.log;\n try {\n fn(`[agent-console] ${msg}`, extra !== undefined ? extra : \"\");\n } catch {\n consoleGone = true;\n }\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","/** Same as the frontend's normalizeLang */\nexport type AppLocale = \"zh\" | \"en\";\n\nlet locale: AppLocale = \"zh\";\n\nexport function normalizeLang(raw: string | null | undefined): AppLocale {\n const s = String(raw ?? \"\").trim().toLowerCase();\n if (!s) return \"zh\";\n if (s === \"zh\" || s.startsWith(\"zh-\")) return \"zh\";\n return \"en\";\n}\n\nexport function setAppLocale(lang: string | undefined): void {\n locale = normalizeLang(lang);\n}\n\nexport function getAppLocale(): AppLocale {\n return locale;\n}\n\nexport function intlLocale(): string {\n return locale === \"zh\" ? \"zh-CN\" : \"en-US\";\n}\n\nconst dict: Record> = {\n zh: {\n \"thread.defaultTitle\": \"新对话\",\n \"notice.daemonRestart\": \"后台已重启,本轮已中断\",\n \"notice.sessionStartFailed\": \"会话启动失败:{detail}\",\n \"notice.sendFailed\": \"发送失败:{detail}\",\n \"notice.effortNextTurn\": \"思考强度已保存,将在下一轮生效\",\n \"notice.effortResetOnModel\": \"当前模型不支持该思考强度,已恢复为 Default\",\n \"turn.agentExit\": \"Agent 进程意外退出\",\n \"attachment.missing\": \"附件不存在或已失效({ref}),请重新上传\",\n \"notice.acpImageByPath\": \"{agent} 不能直接看图片(它的 ACP 初始化未声明支持图片输入),已改为发送图片的文件路径:{paths}\",\n \"notice.acpImageByPathSwitched\": \"{agent} 是在另一个模型上启动的,只对那个模型接收图片,这次改为发送图片的文件路径(当前模型能看图时它会用 read_image 打开):{paths}\",\n \"notice.acpSessionNotRestored\": \"{agent} 不能恢复上一轮对话(它的 ACP 既不支持 session/load 也不支持 session/resume),已新开一轮;先前的上下文不会带回。\",\n \"notice.attachmentIssue\": \"附件问题:{detail}\",\n \"claude.notFound\": \"找不到 claude({detail})。本插件不附带 Claude Code,请先安装:{hint}\",\n \"claude.startFailed\": \"无法启动 claude:{detail}\",\n \"claude.exited\": \"claude 进程意外退出({code})\",\n \"claude.notRunning\": \"claude 没有在运行,消息未发出\",\n \"claude.closed\": \"会话已关闭\",\n \"export.defaultModel\": \"默认\",\n \"bin.notOnPath\": \"PATH 里找不到 {name}\",\n \"bin.or\": \" 或 \",\n \"launch.notFound\": \"找不到自定义的可执行文件:{cmd}(请填写绝对路径,或 PATH 里能找到的命令名)\",\n \"codex.notFound\": \"找不到 codex({detail})。请先安装:{hint}\",\n \"provider.disabled\": \"已在设置中禁用\",\n \"provider.planned\": \"尚未接入\",\n \"provider.disabledNamed\": \"{name} 已在设置中禁用\",\n \"provider.plannedNamed\": \"{name} 尚未接入,暂不能新建对话\",\n \"provider.unavailable\": \"{name} 未安装或不可用\",\n \"provider.unknown\": \"未知 Agent:{id}\",\n \"provider.timeout\": \"检测超时\",\n \"err.projectMissing\": \"项目不存在\",\n \"err.threadMissing\": \"对话不存在\",\n \"err.dirMissing\": \"目录不存在或不是文件夹\",\n \"err.projectDirGone\": \"项目目录已不存在\",\n \"err.terminalMissing\": \"终端不存在\",\n \"err.noManager\": \"会话管理器未启动\",\n \"err.badParams\": \"参数不对:{detail}\",\n \"export.me\": \"我\",\n \"export.steered\": \"(插话)\",\n \"export.reasoning\": \"思考\",\n \"export.plan\": \"计划\",\n \"export.todo\": \"待办\",\n \"err.requestGone\": \"授权/提问不存在或已回应\",\n \"err.badOption\": \"optionId 非法:{id}\",\n \"err.cursorOnly\": \"仅 Cursor 对话支持该选项\",\n \"err.busySwitch\": \"对话运行中,不能更换 Agent\",\n \"err.hasMessages\": \"已有消息,不能更换 Agent\",\n \"tool.read\": \"读取 {x}\",\n \"tool.edit\": \"编辑 {x}\",\n \"tool.multiEdit\": \"编辑 {x}({n} 处)\",\n \"tool.overwrite\": \"覆盖 {x}\",\n \"tool.create\": \"新建 {x}\",\n \"tool.notebook\": \"编辑笔记本 {x}\",\n \"tool.run\": \"运行 {x}\",\n \"tool.output\": \"查看输出 {x}\",\n \"tool.kill\": \"结束进程 {x}\",\n \"tool.grep\": \"搜索 \\\"{x}\\\"\",\n \"tool.glob\": \"查找 {x}\",\n \"tool.fetch\": \"打开 {x}\",\n \"tool.webSearch\": \"搜索网页 \\\"{x}\\\"\",\n \"tool.todo\": \"更新待办({done}/{n})\",\n \"tool.task\": \"子任务:{x}\",\n \"tool.generic\": \"工具\",\n \"tool.editFiles\": \"修改 {n} 个文件\",\n \"tool.needsApproval\": \"需要授权\",\n \"perm.editFiles\": \"修改文件\",\n \"perm.allow\": \"允许\",\n \"perm.allowSession\": \"本对话都允许\",\n \"perm.deny\": \"拒绝\",\n \"perm.plan\": \"Agent 提交了计划\",\n \"perm.implement\": \"实施\",\n \"http.internal\": \"服务内部错误\",\n \"http.badOrigin\": \"来源不允许\",\n \"http.badPreflight\": \"预检不允许\",\n \"http.badToken\": \"令牌无效\",\n \"http.noAttachment\": \"附件不存在\",\n \"http.method\": \"方法不允许\",\n \"http.noApp\": \"app 还没构建(缺 app/index.html)\",\n \"http.badPath\": \"路径不合法\",\n \"http.pathDenied\": \"路径不允许\",\n \"http.noFile\": \"文件不存在\",\n \"http.badType\": \"不支持的文件类型\",\n \"http.tooLarge\": \"文件太大(上限 50MB)\",\n \"http.noRoute\": \"接口不存在\",\n \"codex.error\": \"Codex 错误\",\n \"codex.closed\": \"会话已关闭\",\n \"codex.noTurnSteer\": \"当前轮次还没开始,无法插话\",\n \"acp.exited\": \"{name} 进程退出 ({code})\",\n \"notice.apiRetry\": \"API 重试中(第 {n} 次)\",\n \"notice.compacted\": \"上下文已压缩\",\n \"term.max\": \"每个项目最多 {n} 个终端\",\n \"term.title\": \"终端 {n}\",\n \"stub.planned\": \"该 Agent 尚未在 Agent Console 接入,敬请期待\",\n \"stub.unverified\": \"已检测到 CLI,会话驱动尚未完全验证\",\n \"stub.notFound\": \"未找到 {bin}\",\n \"history.untitled\": \"(无标题)\",\n \"history.toolCall\": \"(历史)调用 {name}\",\n \"fs.pathDenied\": \"路径不允许\",\n \"fs.dirMissing\": \"目录不存在\",\n \"fs.dirUnreadable\": \"无法读取目录\",\n \"fs.fileMissing\": \"文件不存在\",\n \"fs.notFile\": \"不是文件\",\n \"fs.unreadable\": \"无法读取\",\n \"git.missing\": \"找不到 git(请先安装 git 并加入 PATH)\",\n \"git.binary\": \"二进制或无法读取\",\n },\n en: {\n \"thread.defaultTitle\": \"New chat\",\n \"notice.daemonRestart\": \"Daemon restarted — this turn was interrupted\",\n \"notice.sessionStartFailed\": \"Session start failed: {detail}\",\n \"notice.sendFailed\": \"Send failed: {detail}\",\n \"notice.effortNextTurn\": \"Reasoning effort saved — takes effect on the next turn\",\n \"notice.effortResetOnModel\": \"This model does not support that effort level; reset to Default\",\n \"turn.agentExit\": \"Agent process exited unexpectedly\",\n \"attachment.missing\": \"Attachment missing or expired ({ref}) — upload again\",\n \"notice.acpImageByPath\": \"{agent} can't see images directly (its ACP initialize doesn't advertise image input); sent the image file path instead: {paths}\",\n \"notice.acpImageByPathSwitched\": \"{agent} was started on another model and takes image blocks only for that one, so the image went as its file path (it opens it with read_image when this model sees images): {paths}\",\n \"notice.acpSessionNotRestored\": \"{agent} can't restore the previous conversation (its ACP advertises neither session/load nor session/resume); started a new one — prior context won't come back.\",\n \"notice.attachmentIssue\": \"Attachment issue: {detail}\",\n \"claude.notFound\": \"claude was not found ({detail}). Claude Code is not bundled with this plugin; install it first: {hint}\",\n \"claude.startFailed\": \"Could not start claude: {detail}\",\n \"claude.exited\": \"claude exited unexpectedly ({code})\",\n \"claude.notRunning\": \"claude is not running; the message was not sent\",\n \"claude.closed\": \"The session is closed\",\n \"export.defaultModel\": \"Default\",\n \"bin.notOnPath\": \"{name} was not found on PATH\",\n \"bin.or\": \" or \",\n \"launch.notFound\": \"Custom executable not found: {cmd} (use an absolute path or a command name on PATH)\",\n \"codex.notFound\": \"codex was not found ({detail}). Install it first: {hint}\",\n \"provider.disabled\": \"Disabled in Settings\",\n \"provider.planned\": \"Not supported yet\",\n \"provider.disabledNamed\": \"{name} is disabled in Settings\",\n \"provider.plannedNamed\": \"{name} is not supported yet; it can't start new conversations\",\n \"provider.unavailable\": \"{name} is not installed or not available\",\n \"provider.unknown\": \"Unknown agent: {id}\",\n \"provider.timeout\": \"Detection timed out\",\n \"err.projectMissing\": \"Project not found\",\n \"err.threadMissing\": \"Conversation not found\",\n \"err.dirMissing\": \"The folder does not exist or is not a folder\",\n \"err.projectDirGone\": \"The project folder no longer exists\",\n \"err.terminalMissing\": \"Terminal not found\",\n \"err.noManager\": \"The session manager is not running\",\n \"err.badParams\": \"Invalid parameters: {detail}\",\n \"export.me\": \"Me\",\n \"export.steered\": \" (steer)\",\n \"export.reasoning\": \"Reasoning\",\n \"export.plan\": \"Plan\",\n \"export.todo\": \"Todos\",\n \"err.requestGone\": \"That approval or question no longer exists or was already answered\",\n \"err.badOption\": \"Invalid optionId: {id}\",\n \"err.cursorOnly\": \"Only Cursor conversations support this option\",\n \"err.busySwitch\": \"The conversation is running; the agent can't be changed\",\n \"err.hasMessages\": \"The conversation already has messages; the agent can't be changed\",\n \"tool.read\": \"Read {x}\",\n \"tool.edit\": \"Edit {x}\",\n \"tool.multiEdit\": \"Edit {x} ({n} edits)\",\n \"tool.overwrite\": \"Overwrite {x}\",\n \"tool.create\": \"Create {x}\",\n \"tool.notebook\": \"Edit notebook {x}\",\n \"tool.run\": \"Run {x}\",\n \"tool.output\": \"Read output {x}\",\n \"tool.kill\": \"Stop process {x}\",\n \"tool.grep\": \"Search \\\"{x}\\\"\",\n \"tool.glob\": \"Find {x}\",\n \"tool.fetch\": \"Open {x}\",\n \"tool.webSearch\": \"Web search \\\"{x}\\\"\",\n \"tool.todo\": \"Update todos ({done}/{n})\",\n \"tool.task\": \"Subtask: {x}\",\n \"tool.generic\": \"Tool\",\n \"tool.editFiles\": \"Edit {n} file(s)\",\n \"tool.needsApproval\": \"Needs approval\",\n \"perm.editFiles\": \"Edit files\",\n \"perm.allow\": \"Allow\",\n \"perm.allowSession\": \"Allow for this chat\",\n \"perm.deny\": \"Deny\",\n \"perm.plan\": \"The agent proposed a plan\",\n \"perm.implement\": \"Implement\",\n \"http.internal\": \"Internal error\",\n \"http.badOrigin\": \"Origin not allowed\",\n \"http.badPreflight\": \"Preflight not allowed\",\n \"http.badToken\": \"Invalid token\",\n \"http.noAttachment\": \"Attachment not found\",\n \"http.method\": \"Method not allowed\",\n \"http.noApp\": \"The app is not built (app/index.html is missing)\",\n \"http.badPath\": \"Invalid path\",\n \"http.pathDenied\": \"Path not allowed\",\n \"http.noFile\": \"File not found\",\n \"http.badType\": \"Unsupported file type\",\n \"http.tooLarge\": \"File too large (50 MB max)\",\n \"http.noRoute\": \"No such endpoint\",\n \"codex.error\": \"Codex error\",\n \"codex.closed\": \"The session is closed\",\n \"codex.noTurnSteer\": \"The turn hasn't started yet; can't steer\",\n \"acp.exited\": \"{name} exited ({code})\",\n \"notice.apiRetry\": \"Retrying the API (attempt {n})\",\n \"notice.compacted\": \"Context compacted\",\n \"term.max\": \"At most {n} terminals per project\",\n \"term.title\": \"Terminal {n}\",\n \"stub.planned\": \"This agent isn't supported in Agent Console yet\",\n \"stub.unverified\": \"CLI found; its session driver isn't fully verified yet\",\n \"stub.notFound\": \"{bin} was not found\",\n \"history.untitled\": \"(untitled)\",\n \"history.toolCall\": \"(history) called {name}\",\n \"fs.pathDenied\": \"Path not allowed\",\n \"fs.dirMissing\": \"Folder not found\",\n \"fs.dirUnreadable\": \"Can't read the folder\",\n \"fs.fileMissing\": \"File not found\",\n \"fs.notFile\": \"Not a file\",\n \"fs.unreadable\": \"Can't read the file\",\n \"git.missing\": \"git was not found (install git and add it to PATH)\",\n \"git.binary\": \"Binary or unreadable\",\n },\n};\n\nexport function tr(key: string, params?: Record): string {\n let s = dict[locale][key] ?? dict.en[key] ?? key;\n if (params) {\n for (const [k, v] of Object.entries(params)) s = s.replaceAll(`{${k}}`, String(v));\n }\n return s;\n}\n","// Path utilities: normalization, samePath, isInside (decided after resolving realpath).\nimport { realpathSync, existsSync } from \"node:fs\";\nimport { posix, sep, win32 } from \"node:path\";\n\n// Normalization: realpath (when it exists) + unified separators + case-insensitive on Windows/macOS (NTFS and APFS are case-insensitive by default).\n// Only for comparison/dedupe, never for display or storage.\nexport function normPath(p: string, platform: NodeJS.Platform = process.platform): string {\n // Resolve with the target platform's rules: normalizing a macOS/Linux path on Windows must not prepend the host drive (D:\\…)\n let r = (platform === \"win32\" ? win32 : posix).resolve(p);\n try {\n // native restores 8.3 short names (C:\\PROGRA~1), subst drives and letter case to what's on disk; fall back to the JS implementation on failure\n r = realpathSync.native(r);\n } catch {\n try {\n r = realpathSync(r);\n } catch {}\n }\n if (platform === \"win32\") {\n // Strip the \\\\?\\ long-path prefix; UNC stays \\\\server\\share\n r = r.replace(/\\//g, \"\\\\\").replace(/^\\\\\\\\\\?\\\\(?!UNC\\\\)/i, \"\").replace(/^\\\\\\\\\\?\\\\UNC\\\\/i, \"\\\\\\\\\").toLowerCase();\n } else {\n r = r.replace(/\\\\/g, \"/\");\n if (platform === \"darwin\") r = r.normalize(\"NFC\").toLowerCase();\n }\n // Strip trailing separators (except for the root)\n while (r.length > 3 && (r.endsWith(\"/\") || r.endsWith(\"\\\\\"))) r = r.slice(0, -1);\n return r;\n}\n\nexport function samePath(a: string, b: string): boolean {\n return normPath(a) === normPath(b);\n}\n\n// Whether child is inside the parent directory (including equal).\nexport function isInside(child: string, parent: string): boolean {\n const c = normPath(child);\n const p = normPath(parent);\n if (c === p) return true;\n return c.startsWith(p + sep) || c.startsWith(p + \"/\") || c.startsWith(p + \"\\\\\");\n}\n\n// id check: only safe characters, prevents path traversal.\nconst ID_RE = /^[\\w-]{1,80}$/;\nexport function validId(id: unknown): id is string {\n return typeof id === \"string\" && ID_RE.test(id);\n}\n\nexport function pathExists(p: string): boolean {\n return existsSync(p);\n}\n","// AsyncQueue: push/close/[Symbol.asyncIterator], the prompt input stream for the Claude SDK.\nexport class AsyncQueue implements AsyncIterable {\n private buf: T[] = [];\n private waiters: ((v: IteratorResult) => void)[] = [];\n private closed = false;\n private err: unknown = null;\n\n push(item: T): void {\n if (this.closed) return;\n const w = this.waiters.shift();\n if (w) w({ value: item, done: false });\n else this.buf.push(item);\n }\n\n close(): void {\n if (this.closed) return;\n this.closed = true;\n while (this.waiters.length) {\n const w = this.waiters.shift()!;\n w({ value: undefined as never, done: true });\n }\n }\n\n fail(err: unknown): void {\n if (this.closed) return;\n this.err = err;\n this.closed = true;\n while (this.waiters.length) {\n const w = this.waiters.shift()!;\n // Make waiters throw\n w({ value: undefined as never, done: true });\n }\n }\n\n get isClosed(): boolean {\n return this.closed;\n }\n\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: (): Promise> => {\n if (this.buf.length) return Promise.resolve({ value: this.buf.shift()!, done: false });\n if (this.closed) {\n if (this.err) return Promise.reject(this.err);\n return Promise.resolve({ value: undefined as never, done: true });\n }\n if (this.err) return Promise.reject(this.err);\n return new Promise>((res, rej) => {\n this.waiters.push((r) => {\n if (this.err) {\n rej(this.err);\n return;\n }\n res(r);\n });\n });\n },\n };\n }\n}\n","// Line-level diff (ported from lib/diff.mjs): oldStr/newStr → { hunks, added, removed }\n// hunk: { oldStart, newStart, lines: [{ t: \" \"|\"+\"|\"-\", s }] }\n// LCS minimal edit script; keep context lines between changes and merge nearby small blocks into one hunk.\n\nconst CONTEXT = 3;\nconst MERGE_GAP = 6;\nconst MAX_LINES = 400;\n\nexport type DiffLine = { t: \" \" | \"+\" | \"-\"; s: string };\nexport type Hunk = { oldStart: number; newStart: number; lines: DiffLine[] };\nexport type DiffResult = { hunks: Hunk[]; added: number; removed: number; truncated?: boolean };\n\nexport function diffLines(oldStr = \"\", newStr = \"\", { context = CONTEXT } = {}): DiffResult {\n const a = splitLines(oldStr);\n const b = splitLines(newStr);\n if (a.length > MAX_LINES || b.length > MAX_LINES) return coarseDiff(a, b);\n const ops = lcsOps(a, b);\n return buildHunks(ops, context);\n}\n\nfunction splitLines(s: string): string[] {\n s = String(s);\n if (!s) return [];\n return s.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").split(\"\\n\");\n}\n\ntype Op = { t: \" \" | \"+\" | \"-\"; s: string };\n\nfunction lcsOps(a: string[], b: string[]): Op[] {\n const n = a.length;\n const m = b.length;\n const dp = new Uint32Array((n + 1) * (m + 1));\n for (let i = n - 1; i >= 0; i--)\n for (let j = m - 1; j >= 0; j--)\n dp[i * (m + 1) + j] = a[i] === b[j]\n ? dp[(i + 1) * (m + 1) + j + 1] + 1\n : Math.max(dp[(i + 1) * (m + 1) + j], dp[i * (m + 1) + j + 1]);\n const ops: Op[] = [];\n let i = 0;\n let j = 0;\n while (i < n && j < m) {\n if (a[i] === b[j]) {\n ops.push({ t: \" \", s: a[i] });\n i++; j++;\n } else if (dp[(i + 1) * (m + 1) + j] >= dp[i * (m + 1) + j + 1]) {\n ops.push({ t: \"-\", s: a[i] });\n i++;\n } else {\n ops.push({ t: \"+\", s: b[j] });\n j++;\n }\n }\n while (i < n) ops.push({ t: \"-\", s: a[i++] });\n while (j < m) ops.push({ t: \"+\", s: b[j++] });\n return ops;\n}\n\nfunction buildHunks(ops: Op[], context: number): DiffResult {\n const changed: number[] = [];\n ops.forEach((op, i) => {\n if (op.t !== \" \") changed.push(i);\n });\n if (!changed.length) return { hunks: [], added: 0, removed: 0 };\n\n let added = 0;\n let removed = 0;\n for (const op of ops) {\n if (op.t === \"+\") added++;\n else if (op.t === \"-\") removed++;\n }\n\n const ranges: { s: number; e: number }[] = [];\n for (const idx of changed) {\n const s = Math.max(0, idx - context);\n const e = Math.min(ops.length, idx + context + 1);\n const last = ranges[ranges.length - 1];\n if (last && s <= last.e + MERGE_GAP) last.e = Math.max(last.e, e);\n else ranges.push({ s, e });\n }\n\n const hunks: Hunk[] = [];\n let oldLn = 1;\n let newLn = 1;\n const oldNos: number[] = [];\n const newNos: number[] = [];\n for (const op of ops) {\n oldNos.push(oldLn);\n newNos.push(newLn);\n if (op.t !== \"+\") oldLn++;\n if (op.t !== \"-\") newLn++;\n }\n for (const r of ranges) {\n hunks.push({\n oldStart: oldNos[r.s],\n newStart: newNos[r.s],\n lines: ops.slice(r.s, r.e).map((op) => ({ t: op.t, s: op.s })),\n });\n }\n return { hunks, added, removed };\n}\n\nfunction coarseDiff(a: string[], b: string[]): DiffResult {\n return {\n hunks: [\n {\n oldStart: 1,\n newStart: 1,\n lines: [...a.map((s) => ({ t: \"-\" as const, s })), ...b.map((s) => ({ t: \"+\" as const, s }))].slice(0, 2000),\n },\n ],\n added: b.length,\n removed: a.length,\n truncated: true,\n };\n}\n\n// Build the detail for Edit/MultiEdit: compute hunks from old/new or edits[]\nexport function editDetail(detail: Record = {}) {\n if (Array.isArray(detail.edits) && detail.edits.length) {\n const hunks: Hunk[] = [];\n let added = 0;\n let removed = 0;\n for (const e of detail.edits as { old_string?: string; old?: string; new_string?: string; new?: string }[]) {\n const d = diffLines(e.old_string ?? e.old ?? \"\", e.new_string ?? e.new ?? \"\");\n for (const h of d.hunks) hunks.push(h);\n added += d.added;\n removed += d.removed;\n }\n return { path: detail.path, hunks, added, removed };\n }\n if (detail.old !== undefined || detail.new !== undefined) {\n const d = diffLines(String(detail.old ?? \"\"), String(detail.new ?? \"\"));\n return { path: detail.path, hunks: d.hunks, added: d.added, removed: d.removed };\n }\n return detail;\n}\n","export type SlashCommandKind = \"command\" | \"skill\";\n\nexport type SlashCommand = {\n name: string;\n description: string;\n argumentHint?: string;\n kind: SlashCommandKind;\n};\n\nconst CLAUDE_BUILTIN_COMMANDS = new Set([\"clear\", \"compact\", \"context\", \"usage\", \"init\", \"debug\"]);\n\nexport function classifyClaudeSlashCommand(name: string): SlashCommandKind {\n return CLAUDE_BUILTIN_COMMANDS.has(name) ? \"command\" : \"skill\";\n}\n\n/** Parse \"/name args\" (must start with /) */\nexport function parseSlashInput(text: string): { name: string; args: string; raw: string } | null {\n const t = text.trim();\n if (!t.startsWith(\"/\")) return null;\n const body = t.slice(1).trim();\n if (!body) return null;\n const sp = body.indexOf(\" \");\n if (sp === -1) return { name: body, args: \"\", raw: t };\n return { name: body.slice(0, sp), args: body.slice(sp + 1).trim(), raw: t };\n}\n\nexport function mapAcpAvailableCommands(\n cmds: { name: string; description: string; input?: { hint?: string } | null }[],\n): SlashCommand[] {\n return cmds.map((c) => ({\n name: c.name,\n description: c.description,\n argumentHint: c.input?.hint,\n kind: \"skill\" as const,\n }));\n}\n\nexport function sortSlashCommands(list: SlashCommand[]): SlashCommand[] {\n return [...list].sort((a, b) => {\n if (a.kind !== b.kind) return a.kind === \"command\" ? -1 : 1;\n return a.name.localeCompare(b.name);\n });\n}\n","// MockProvider: registered only with AGENT_CONSOLE_MOCK=1. Persistent session, interruptible, with permissions and steering.\n// Scripts by message prefix: default /perm /plan /ask /slow /error /long /exit; supports steer/interrupt/resume.\nimport { tr } from \"../util/i18n.js\";\nimport type { Provider, ProviderSession, DetectResult, ModelInfo,\n Mode, SendInput, RespondAnswer, SlashCommand,\n} from \"./types.js\";\nimport type { ProviderEvent } from \"../timeline/types.js\";\nimport { AsyncQueue } from \"../util/queue.js\";\nimport { editDetail } from \"../agents/diff.js\";\nimport { sortSlashCommands } from \"./slash.js\";\n\nexport const mockCapabilities = {\n resume: true,\n interrupt: true,\n steer: true,\n images: true,\n plan: true,\n questions: true,\n cost: true,\n effort: [\"low\", \"medium\", \"high\"],\n modes: [\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\"] as Mode[],\n};\n\nconst rid = () => Math.random().toString(36).slice(2, 10);\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nclass MockCrash extends Error {\n constructor() {\n super(\"__mock_crash__\");\n }\n}\n\ntype Ctx = {\n emit: (ev: ProviderEvent) => void;\n waitFor: (requestId: string) => Promise;\n interrupted: () => boolean;\n steerText: () => string;\n replyPrefix: () => string;\n input: SendInput;\n};\n\nexport class MockSession implements ProviderSession {\n events: AsyncIterable;\n private q = new AsyncQueue();\n private sessionId: string;\n private turnId: string | null = null;\n private turnNum = 0;\n private interruptFlag = false;\n private closed = false;\n private pendingReq = new Map void>();\n private steered: string[] = [];\n private resumed = false;\n\n constructor(private o: {\n threadId: string;\n cwd: string;\n model: string | null;\n mode: Mode;\n effort: string | null;\n resumeId: string | null;\n }) {\n this.sessionId = o.resumeId ?? \"mock-\" + rid();\n this.resumed = o.resumeId !== null;\n this.events = this.q;\n this.q.push({ type: \"provider_session_id\", id: this.sessionId });\n }\n\n private emit(ev: ProviderEvent): void {\n (ev as { turnId?: string }).turnId ??= this.turnId ?? undefined;\n this.q.push(ev);\n }\n\n async send(input: SendInput): Promise {\n if (this.closed) throw new Error(\"mock session closed\");\n this.turnNum++;\n this.turnId = \"u_\" + Date.now().toString(36) + \"_\" + this.turnNum;\n this.interruptFlag = false;\n this.steered = [];\n this.emit({\n type: \"turn_started\",\n turnId: this.turnId,\n model: this.o.model ?? \"demo-fast\",\n mode: this.o.mode,\n effort: this.o.effort,\n });\n void this.runTurn(input);\n }\n\n private async runTurn(input: SendInput): Promise {\n // itemIds are globally unique (a real provider creates new itemIds each time); sessionId can't be used:\n // a resumed session keeps the same providerSessionId and would collide with the old session's itemIds.\n // Same ids would merge the new turn's events into old entries, and the new reply would \"fly\" into an old bubble mid-timeline.\n const p = \"i\" + rid() + \"_\";\n const ctx: Ctx = {\n emit: (ev) => {\n const e = ev as { itemId?: string };\n if (e.itemId) e.itemId = p + e.itemId;\n this.emit(ev);\n },\n waitFor: (id) => this.waitFor(id),\n interrupted: () => this.interruptFlag || this.closed,\n steerText: () => this.steered.join(\";\"),\n replyPrefix: () => this.resumePrefix(),\n input,\n };\n try {\n const script = pickScript(input.text);\n await script(ctx);\n if (this.interruptFlag || this.closed) {\n this.emit({ type: \"turn_ended\", turnId: this.turnId!, status: \"interrupted\", durationMs: 0 });\n } else {\n this.emit({ type: \"usage\", inputTokens: 1200, outputTokens: 340, cacheReadTokens: 800, costUsd: 0.0123 });\n this.emit({ type: \"turn_ended\", turnId: this.turnId!, status: \"completed\", durationMs: 6000, filesChanged: 1 });\n }\n } catch (e) {\n if (e instanceof MockCrash) {\n this.q.close(); // Crash: no turn_ended; the manager appends failed\n return;\n }\n if (this.interruptFlag || this.closed) {\n this.emit({ type: \"turn_ended\", turnId: this.turnId!, status: \"interrupted\", durationMs: 0 });\n } else {\n this.emit({ type: \"turn_ended\", turnId: this.turnId!, status: \"failed\", error: String((e as Error)?.message ?? e) });\n }\n }\n }\n\n respond(requestId: string, answer: RespondAnswer): void {\n const resolve = this.pendingReq.get(requestId);\n if (resolve) {\n this.pendingReq.delete(requestId);\n resolve(answer);\n }\n }\n\n private waitFor(requestId: string): Promise {\n return new Promise((resolve) => {\n this.pendingReq.set(requestId, resolve);\n });\n }\n\n async interrupt(): Promise {\n this.interruptFlag = true;\n // Pending permissions/questions are cancelled directly\n for (const [id, resolve] of this.pendingReq) {\n resolve({ cancelled: true });\n this.pendingReq.delete(id);\n }\n await sleep(120); // Guarantees interrupted within <1s\n }\n\n async steer(input: SendInput): Promise {\n this.steered.push(input.text);\n }\n\n async setModel(model: string | null): Promise {\n this.o.model = model;\n }\n async setMode(mode: Mode): Promise {\n this.o.mode = mode;\n }\n async setEffort(effort: string | null): Promise {\n this.o.effort = effort;\n }\n\n async listCommands(): Promise {\n return sortSlashCommands([\n { name: \"perm\", description: \"演示授权弹窗\", kind: \"command\" },\n { name: \"plan\", description: \"演示计划审批\", kind: \"command\" },\n { name: \"ask\", description: \"演示提问\", kind: \"command\" },\n { name: \"slow\", description: \"慢速多步工具\", kind: \"skill\" },\n { name: \"error\", description: \"模拟失败\", kind: \"skill\" },\n ]);\n }\n\n async close(): Promise {\n this.closed = true;\n for (const [, resolve] of this.pendingReq) resolve({ cancelled: true });\n this.pendingReq.clear();\n this.q.close();\n }\n\n // With resumeId the first reply gets a \"(已续接)\" prefix\n private resumePrefix(): string {\n if (this.resumed && this.turnNum === 1) return \"(已续接)\";\n return \"\";\n }\n}\n\n// ---------- scripts ----------\n\nasync function scriptDefault(ctx: Ctx): Promise {\n const { emit } = ctx;\n const sleepA = (ms: number) => sleepAbortable(ms, ctx);\n\n emit({ type: \"reasoning_delta\", itemId: \"r1\", text: \"让我看看项目结构…\" });\n await sleepA(500);\n emit({ type: \"reasoning\", itemId: \"r1\", text: \"让我看看项目结构…需要先读几个文件。\" });\n\n const tools = [\n { id: \"t1\", name: \"Read\", input: { file_path: ctx.input.text.includes(\"abs\") ? \"D:/x/a.ts\" : \"src/index.ts\" } },\n { id: \"t2\", name: \"Read\", input: { file_path: \"package.json\" } },\n ];\n for (const t of tools) {\n emit({ type: \"tool_call\", itemId: t.id, kind: \"read\", title: `读取 ${t.input.file_path}`, status: \"running\", input: t.input });\n if (await sleepA(300)) return;\n emit({ type: \"tool_call\", itemId: t.id, kind: \"read\", title: `读取 ${t.input.file_path}`, status: \"ok\", output: \"…文件内容…\", durationMs: 300 });\n }\n\n emit({ type: \"tool_call\", itemId: \"t3\", kind: \"search\", title: '搜索 \"TODO\"', status: \"running\", input: { pattern: \"TODO\" } });\n await sleepA(200);\n emit({ type: \"tool_call\", itemId: \"t3\", kind: \"search\", title: '搜索 \"TODO\"', status: \"ok\", output: \"3 处匹配\" });\n\n const oldStr = \"const x = 1;\\nconst y = 2;\\nreturn x + y;\";\n const newStr = \"const x = 1;\\nconst y = 2;\\nconst z = 3;\\nreturn x + y + z;\";\n emit({\n type: \"tool_call\", itemId: \"t4\", kind: \"edit\", title: \"编辑 src/index.ts\", status: \"running\",\n input: { file_path: \"src/index.ts\", old_string: oldStr, new_string: newStr },\n detail: editDetail({ path: \"src/index.ts\", old: oldStr, new: newStr }),\n });\n if (await sleepA(400)) return;\n emit({\n type: \"tool_call\", itemId: \"t4\", kind: \"edit\", title: \"编辑 src/index.ts\", status: \"ok\",\n detail: editDetail({ path: \"src/index.ts\", old: oldStr, new: newStr }), durationMs: 400,\n });\n\n emit({ type: \"tool_call\", itemId: \"t5\", kind: \"bash\", title: \"运行 npm test\", status: \"running\", input: { command: \"npm test\" } });\n for (let i = 1; i <= 20; i++) {\n if (await sleepA(60)) return;\n emit({ type: \"tool_output_delta\", itemId: \"t5\", text: `第 ${i} 行输出\\n` });\n }\n emit({ type: \"tool_call\", itemId: \"t5\", kind: \"bash\", title: \"运行 npm test\", status: \"ok\", output: \"✓ 全部通过\", exitCode: 0, durationMs: 1200 });\n\n emit({\n type: \"todo\",\n items: [\n { text: \"分析需求\", status: \"done\" },\n { text: \"修改代码\", status: \"done\" },\n { text: \"跑测试\", status: \"done\" },\n { text: \"写文档\", status: \"in_progress\" },\n ],\n });\n await sleepA(300);\n\n const reply = ctx.replyPrefix() + mockReply(ctx);\n for (const ch of chunkText(reply, 40)) {\n if (await sleepA(30)) return;\n emit({ type: \"assistant_delta\", itemId: \"m1\", text: ch });\n }\n emit({ type: \"assistant_message\", itemId: \"m1\", text: reply });\n}\n\nasync function scriptPerm(ctx: Ctx): Promise {\n const { emit } = ctx;\n const requestId = \"perm-\" + rid();\n emit({\n type: \"permission_request\",\n requestId,\n title: \"运行 npm test\",\n kind: \"tool\",\n detail: { command: \"npm test\", cwd: \".\", toolName: \"Bash\" },\n options: [\n { id: \"accept\", label: tr(\"perm.allow\"), kind: \"allow_once\" },\n { id: \"acceptForSession\", label: tr(\"perm.allowSession\"), kind: \"allow_always\" },\n { id: \"decline\", label: tr(\"perm.deny\"), kind: \"reject_once\" },\n ],\n });\n const ans = await ctx.waitFor(requestId);\n if (ans.cancelled || ans.optionId === \"decline\") {\n emit({ type: \"tool_call\", itemId: \"p1\", kind: \"bash\", title: \"运行 npm test\", status: \"failed\", output: \"已被用户拒绝\", exitCode: 1 });\n emit({ type: \"assistant_message\", itemId: \"pm\", text: \"已按你的要求跳过该操作。\" });\n return;\n }\n emit({ type: \"tool_call\", itemId: \"p1\", kind: \"bash\", title: \"运行 npm test\", status: \"running\", input: { command: \"npm test\" } });\n if (await sleepAbortable(500, ctx)) return;\n emit({ type: \"tool_call\", itemId: \"p1\", kind: \"bash\", title: \"运行 npm test\", status: \"ok\", output: \"✓ 12 个测试通过\", exitCode: 0, durationMs: 500 });\n emit({ type: \"assistant_message\", itemId: \"pm\", text: \"测试通过了。\" });\n}\n\nasync function scriptPlan(ctx: Ctx): Promise {\n const { emit } = ctx;\n emit({\n type: \"plan\",\n itemId: \"plan1\",\n markdown: \"## 实施计划\\n\\n1. 改 `src/index.ts` 入口\\n2. 更新测试\\n3. 跑一遍 e2e\",\n entries: [\n { step: \"改 src/index.ts 入口\", status: \"pending\" },\n { step: \"更新测试\", status: \"pending\" },\n { step: \"跑一遍 e2e\", status: \"pending\" },\n ],\n });\n const requestId = \"perm-\" + rid();\n emit({\n type: \"permission_request\",\n requestId,\n title: \"实施这个计划?\",\n kind: \"plan\",\n detail: { markdown: \"见上方计划\" },\n options: [\n { id: \"implement\", label: \"开始实施\", kind: \"allow_once\" },\n { id: \"reject\", label: tr(\"perm.deny\"), kind: \"reject_once\" },\n ],\n });\n const ans = await ctx.waitFor(requestId);\n if (ans.cancelled || ans.optionId === \"reject\") {\n emit({ type: \"assistant_message\", itemId: \"pm\", text: \"好的,请告诉我怎么改。\" });\n return;\n }\n emit({ type: \"tool_call\", itemId: \"pl1\", kind: \"edit\", title: \"编辑 src/index.ts\", status: \"ok\" });\n await sleepAbortable(400, ctx);\n emit({ type: \"assistant_message\", itemId: \"pm\", text: \"已按计划改完入口和测试。\" });\n}\n\nasync function scriptAsk(ctx: Ctx): Promise {\n const { emit } = ctx;\n const requestId = \"q-\" + rid();\n emit({\n type: \"question\",\n requestId,\n questions: [\n {\n id: \"q1\",\n header: \"部署目标\",\n question: \"要部署到哪个环境?\",\n options: [\n { id: \"staging\", label: \"Staging\" },\n { id: \"prod\", label: \"生产环境\" },\n ],\n },\n {\n id: \"q2\",\n header: \"备注\",\n question: \"还有什么要补充的?\",\n freeText: true,\n },\n ],\n });\n const ans = await ctx.waitFor(requestId);\n const env = ans.answers?.q1 ?? \"(未选)\";\n const note = ans.answers?.q2 ?? \"\";\n emit({ type: \"assistant_message\", itemId: \"am\", text: `收到:部署到 ${env}${note ? `,备注「${note}」` : \"\"}。` });\n}\n\nasync function scriptSlow(ctx: Ctx): Promise {\n const { emit } = ctx;\n for (let i = 1; i <= 6; i++) {\n const id = \"s\" + i;\n emit({ type: \"tool_call\", itemId: id, kind: \"bash\", title: `步骤 ${i}/6`, status: \"running\", input: { command: `step ${i}` } });\n if (await sleepAbortable(2000, ctx)) return;\n emit({ type: \"tool_call\", itemId: id, kind: \"bash\", title: `步骤 ${i}/6`, status: \"ok\", output: `步骤 ${i} 完成`, durationMs: 2000 });\n }\n emit({ type: \"assistant_message\", itemId: \"sm\", text: \"6 个步骤全部跑完。\" });\n}\n\nasync function scriptError(ctx: Ctx): Promise {\n const { emit } = ctx;\n emit({ type: \"tool_call\", itemId: \"e1\", kind: \"bash\", title: \"运行 ./build.sh\", status: \"running\", input: { command: \"./build.sh\" } });\n await sleepAbortable(800, ctx);\n throw new Error(\"构建失败:找不到模块 foo(模拟错误)\");\n}\n\nasync function scriptLong(ctx: Ctx): Promise {\n const { emit } = ctx;\n emit({ type: \"assistant_delta\", itemId: \"L1\", text: \"\" });\n for (let i = 0; i < 5000; i++) {\n if (i % 100 === 0 && ctx.interrupted()) return;\n emit({ type: \"assistant_delta\", itemId: \"L1\", text: `块${i} ` });\n if (i % 200 === 0) await sleep(0);\n }\n emit({ type: \"assistant_message\", itemId: \"L1\", text: \"(5000 个增量合并后的长文)\" });\n}\n\nasync function scriptExit(_ctx: Ctx): Promise {\n await sleep(300);\n throw new MockCrash();\n}\n\nfunction pickScript(text: string): (ctx: Ctx) => Promise {\n const t = text.trim();\n if (t.startsWith(\"/perm\")) return scriptPerm;\n if (t.startsWith(\"/plan\")) return scriptPlan;\n if (t.startsWith(\"/ask\")) return scriptAsk;\n if (t.startsWith(\"/slow\")) return scriptSlow;\n if (t.startsWith(\"/error\")) return scriptError;\n if (t.startsWith(\"/long\")) return scriptLong;\n if (t.startsWith(\"/exit\")) return scriptExit;\n return scriptDefault;\n}\n\nasync function sleepAbortable(ms: number, ctx: Ctx): Promise {\n const start = Date.now();\n while (Date.now() - start < ms) {\n if (ctx.interrupted()) return true;\n await sleep(Math.min(20, Math.max(1, ms - (Date.now() - start))));\n }\n return ctx.interrupted();\n}\n\nfunction chunkText(s: string, n: number): string[] {\n const out: string[] = [];\n for (let i = 0; i < s.length; i += n) out.push(s.slice(i, i + n));\n return out;\n}\n\nfunction mockReply(ctx: Ctx): string {\n const base = [\n \"好的,我已经按你的要求改好了。\",\n \"\",\n \"## 改动\",\n \"- `src/index.ts`:把返回逻辑补成三变量求和\",\n \"- 新增一行常量 `z`\",\n \"\",\n \"```ts\",\n \"const z = 3;\",\n \"return x + y + z;\",\n \"```\",\n \"\",\n \"| 文件 | 变更 |\",\n \"|---|---|\",\n \"| src/index.ts | +2/-1 |\",\n \"\",\n \"测试全部通过。\",\n ].join(\"\\n\");\n return ctx.steerText() ? base + `\\n\\n> 插话:${ctx.steerText()}` : base;\n}\n\n// ---------- Provider ----------\n\n/** For tests: counts createSession calls */\nexport const mockProviderMetrics = { createSessionCalls: 0 };\n\nexport function createMockProvider(): Provider {\n return {\n id: \"mock\",\n name: \"Mock(演示)\",\n capabilities: mockCapabilities,\n async detect(): Promise {\n return { available: true, bin: \"mock\", version: \"demo\" };\n },\n async listModels(): Promise {\n return [\n { id: \"demo-fast\", name: \"演示·快\", isDefault: true, efforts: [\"low\", \"medium\", \"high\"] },\n { id: \"demo-pro\", name: \"演示·强\", efforts: [\"low\", \"medium\", \"high\"] },\n ];\n },\n async createSession(o) {\n mockProviderMetrics.createSessionCalls++;\n return new MockSession(o);\n },\n };\n}\n","// Cross-platform executable lookup in PATH (shared by the plugin host index.mjs and the daemon; esbuild bundles it into dist for the daemon).\n//\n// which / where.exe are no longer used:\n// - some minimal Linux systems have no which;\n// - where.exe writes in the console code page (CP936 on Chinese Windows), so a Chinese user name or path is garbled when decoded as UTF-8,\n// existsSync fails and the CLI \"can't be found\".\n// Windows searches in PATHEXT order (.COM;.EXE;.BAT;.CMD), with .ps1 last; extensionless npm sh shims are never returned.\n// Besides PATH, add a set of common install directories: GUI apps launched from the macOS Dock/Finder only get launchd's minimal PATH\n// (Magpie adds the login shell's PATH itself; this is the fallback): Homebrew, npm global, Volta, Claude's native install, etc.\nimport { accessSync, constants, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport path from \"node:path\";\n\nfunction defaultExists(file, platform) {\n try {\n if (!statSync(file).isFile()) return false;\n if (platform !== \"win32\") accessSync(file, constants.X_OK);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction envGet(env, name) {\n if (env[name] !== undefined) return env[name];\n // Windows environment variable names are case-insensitive (Path / PATH)\n const lower = name.toLowerCase();\n for (const key of Object.keys(env)) if (key.toLowerCase() === lower) return env[key];\n return undefined;\n}\n\n/** Common install directories that aren't necessarily in a GUI process's PATH (candidates only; callers check whether they exist). */\nexport function extraBinDirs({ platform = process.platform, env = process.env, home = homedir() } = {}) {\n const p = platform === \"win32\" ? path.win32 : path.posix;\n const dirs = [];\n if (platform === \"win32\") {\n const appData = envGet(env, \"APPDATA\");\n const localAppData = envGet(env, \"LOCALAPPDATA\");\n const programFiles = envGet(env, \"ProgramFiles\") || \"C:\\\\Program Files\";\n const nvmSymlink = envGet(env, \"NVM_SYMLINK\");\n if (home) dirs.push(p.join(home, \".local\", \"bin\"));\n if (appData) dirs.push(p.join(appData, \"npm\"));\n if (nvmSymlink) dirs.push(nvmSymlink);\n dirs.push(p.join(programFiles, \"nodejs\"));\n if (localAppData) dirs.push(p.join(localAppData, \"Programs\", \"nodejs\"));\n if (home) {\n dirs.push(p.join(home, \".volta\", \"bin\"));\n dirs.push(p.join(home, \".bun\", \"bin\"));\n }\n return dirs;\n }\n if (home) {\n dirs.push(p.join(home, \".local\", \"bin\"));\n dirs.push(p.join(home, \".npm-global\", \"bin\"));\n dirs.push(p.join(home, \".volta\", \"bin\"));\n dirs.push(p.join(home, \".bun\", \"bin\"));\n dirs.push(p.join(home, \".claude\", \"local\"));\n }\n if (platform === \"darwin\") dirs.push(\"/opt/homebrew/bin\");\n dirs.push(\"/usr/local/bin\", \"/usr/bin\", \"/bin\");\n return dirs;\n}\n\n/** PATH's directories followed by extraBinDirs; deduped (case-insensitive on Windows). */\nexport function searchDirs({ platform = process.platform, env = process.env, home = homedir(), extra = true } = {}) {\n const sep = platform === \"win32\" ? \";\" : \":\";\n const raw = String(envGet(env, \"PATH\") ?? \"\")\n .split(sep)\n .map((d) => d.trim().replace(/^\"(.*)\"$/, \"$1\"))\n .filter(Boolean);\n const all = extra ? [...raw, ...extraBinDirs({ platform, env, home })] : raw;\n const seen = new Set();\n const out = [];\n for (const d of all) {\n const key = platform === \"win32\" ? d.toLowerCase().replace(/[\\\\/]+$/, \"\") : d.replace(/\\/+$/, \"\");\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(d);\n }\n return out;\n}\n\nfunction windowsExts(env) {\n const list = String(envGet(env, \"PATHEXT\") || \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((e) => e.trim().toLowerCase())\n .filter((e) => e.startsWith(\".\"));\n if (!list.includes(\".ps1\")) list.push(\".ps1\");\n return list;\n}\n\n/**\n * Return the full paths of every hit, in order (PATH first, then extraBinDirs).\n * @param {string} name command name (may include an extension on Windows)\n */\nexport function findOnPath(\n name,\n { platform = process.platform, env = process.env, home = homedir(), extra = true, exists } = {},\n) {\n if (!name) return [];\n const p = platform === \"win32\" ? path.win32 : path.posix;\n const check = exists ?? ((file) => defaultExists(file, platform));\n // Already a path: check it directly\n if (name.includes(\"/\") || (platform === \"win32\" && name.includes(\"\\\\\"))) {\n return check(name) ? [name] : [];\n }\n let names = [name];\n if (platform === \"win32\") {\n const exts = windowsExts(env);\n const ext = p.extname(name).toLowerCase();\n names = ext && exts.includes(ext) ? [name] : exts.map((e) => name + e);\n }\n const hits = [];\n for (const dir of searchDirs({ platform, env, home, extra })) {\n for (const n of names) {\n const file = p.join(dir, n);\n if (check(file) && !hits.includes(file)) hits.push(file);\n }\n }\n return hits;\n}\n\n/** The resolved node executable, or null if not found (the plugin host is Bun, so process.execPath can't serve as node). */\nexport function findNode(opts = {}) {\n return findOnPath(\"node\", opts).find((file) => isNodeExecutable(file)) ?? null;\n}\n\n/** Whether process.execPath itself is node (rather than Bun / Electron etc.). */\nexport function isNodeExecutable(file) {\n return /^node(\\.exe)?$/i.test(String(file || \"\").split(/[\\\\/]/).pop() ?? \"\");\n}\n\nexport const NODE_MISSING_MESSAGE =\n \"找不到 Node.js(需要 20 或更高版本)。请安装 Node.js(https://nodejs.org)后完全退出并重新打开 Magpie。\" +\n \" / Node.js 20+ was not found on PATH. Install it, then quit and reopen Magpie.\";\nexport const NODE_TOO_OLD_MESSAGE =\n \"Node.js 版本太旧,需要 20 或更高版本。升级后完全退出并重新打开 Magpie。\" +\n \" / Node.js 20+ is required. Upgrade it, then quit and reopen Magpie.\";\n\n/**\n * For the plugin host: return the real node path (the host itself is Bun). If none is found, throw an error with a userMessage,\n * which the gate's 503 page displays; the daemon is no longer silently run on Bun.\n */\nexport function requireNode({ execPath = process.execPath, find = findNode } = {}) {\n if (isNodeExecutable(execPath)) return execPath;\n const hit = find();\n if (hit) return hit;\n const error = new Error(\"node not found on PATH\");\n error.code = \"ENODE\";\n error.userMessage = NODE_MISSING_MESSAGE;\n throw error;\n}\n","// Cross-platform executable resolution + process tree termination (ported from lib/bin.mjs).\n// Goal: start .cmd-shim CLIs like claude/codex without shell:true.\n\nimport { execFileSync, spawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\nimport { findOnPath, findNode as findNodeOnPath, isNodeExecutable } from \"../../../lib/pathscan.mjs\";\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { tr } from \"./i18n.js\";\n\nconst IS_WIN = process.platform === \"win32\";\nconst cache = new Map();\nconst CACHE_MS = 60 * 1000;\n\nexport type ResolveResult =\n | {\n ok: true;\n cmd: string;\n prefixArgs: string[];\n display: string;\n via: string;\n /** via === \"cmd-shim\": a .cmd/.bat that must be started through cmd.exe (spawnBin / argvFor handle escaping) */\n shim?: string;\n }\n | { ok: false; reason: string };\n\n// PATH lookup lives in lib/pathscan.mjs: which / where.exe are no longer used (where's output uses the console code page, which garbles Chinese paths).\nfunction which(name: string): string[] {\n return findOnPath(name);\n}\n\n// ---- Windows: escaping when starting a .cmd/.bat through cmd.exe (same rules as cross-spawn) ----\nconst CMD_META = /([()\\][%!^\"`<>&|;, *?])/g;\n\nexport function escapeCmdCommand(cmd: string): string {\n return cmd.replace(CMD_META, \"^$1\");\n}\n\nexport function escapeCmdArgument(arg: string, doubleEscape: boolean): string {\n let a = String(arg);\n // First quote per CommandLineToArgvW rules (backslashes + quotes)\n a = a.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n a = a.replace(/(\\\\*)$/, \"$1$1\");\n a = `\"${a}\"`;\n // Then escape cmd metacharacters; batch files parse arguments again, so escape twice\n a = a.replace(CMD_META, \"^$1\");\n if (doubleEscape) a = a.replace(CMD_META, \"^$1\");\n return a;\n}\n\nexport type Argv = { cmd: string; args: string[]; windowsVerbatimArguments?: boolean };\n\n/** Resolution result + arguments → the command line actually given to spawn. */\nexport function argvFor(r: ResolveResult & { ok: true }, args: string[]): Argv {\n if (r.via === \"cmd-shim\" && r.shim) {\n const line = [escapeCmdCommand(r.shim), ...args.map((a) => escapeCmdArgument(a, true))].join(\" \");\n return { cmd: r.cmd, args: [\"/d\", \"/s\", \"/c\", `\"${line}\"`], windowsVerbatimArguments: true };\n }\n return { cmd: r.cmd, args: [...r.prefixArgs, ...args] };\n}\n\n// ---- Safety net: end Agent process trees still alive when the daemon exits ----\nconst liveTrees = new Set();\nlet exitHookInstalled = false;\n\nfunction reapOnExit(): void {\n for (const pid of liveTrees) {\n try {\n if (IS_WIN) execFileSync(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], { stdio: \"ignore\", windowsHide: true, timeout: 3000 });\n else process.kill(-pid, \"SIGKILL\");\n } catch {}\n }\n liveTrees.clear();\n}\n\n/** Register a process to clean up when the daemon exits (on non-Windows it must lead a detached process group). */\nexport function trackTree(child: ChildProcess): void {\n if (child.pid == null) return;\n const pid = child.pid;\n liveTrees.add(pid);\n child.once(\"exit\", () => liveTrees.delete(pid));\n if (!exitHookInstalled) {\n exitHookInstalled = true;\n process.once(\"exit\", reapOnExit);\n }\n}\n\n/** Start a CLI from a resolution result. On non-Windows it gets its own process group (detached) so killTree can also end grandchildren. */\nexport function spawnBin(\n r: ResolveResult & { ok: true },\n args: string[],\n opts: SpawnOptions & { group?: boolean } = {},\n): ChildProcess {\n const a = argvFor(r, args);\n const { group, ...rest } = opts;\n const child = spawn(a.cmd, a.args, {\n windowsHide: true,\n ...rest,\n ...(a.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),\n ...(group && !IS_WIN ? { detached: true } : {}),\n });\n if (group) trackTree(child);\n return child;\n}\n\n// Find the script/program path a .cmd calls from its text.\nexport function shimTarget(\n cmdText: string,\n cmdDir: string | null,\n deps: { exists?: (p: string) => boolean; win?: boolean } = {},\n): string | null {\n const exists = deps.exists ?? existsSync;\n const P = (deps.win ?? IS_WIN) ? path.win32 : path;\n const cands: string[] = [];\n const re = /\"([^\"]+?\\.(?:js|mjs|cjs|exe|cmd|bat))\"/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(cmdText))) cands.push(m[1]);\n const re2 = /(?:%~?dp0%?)?[A-Za-z]:?[\\\\/\\w.@-]*?\\.(?:js|mjs|cjs|exe)\\b/gi;\n while ((m = re2.exec(cmdText))) cands.push(m[0]);\n const found: string[] = [];\n for (const raw of cands) {\n let p = raw.replace(/%~?dp0%?/gi, \"\");\n p = p.replace(/%[A-Z_]+%/gi, \"\");\n p = p.trim().replace(/^[\\\\/]+/, \"\");\n if (!p || /%\\w+%/.test(p) || !/\\.(js|mjs|cjs|exe)$/i.test(p)) continue;\n if (!P.isAbsolute(p)) {\n if (!cmdDir) continue;\n p = P.join(cmdDir, p);\n }\n if (exists(p)) found.push(P.resolve(p));\n }\n // npm shims first write IF EXIST \"%dp0%\\node.exe\" (it really exists when the global dir is the node install dir, e.g. nvm-windows),\n // and only then the real cli.js: the script wins, node.exe itself is not the target\n return (\n found.find((f) => /\\.(js|mjs|cjs)$/i.test(f)) ??\n found.find((f) => /\\.exe$/i.test(f) && !isNodeExecutable(P.basename(f))) ??\n null\n );\n}\n\n// Which node to use when the shim points at a .js: the daemon itself runs on node, so prefer that one; otherwise node from PATH\nfunction findNode(): string {\n if (isNodeExecutable(process.execPath)) return process.execPath;\n return findNodeOnPath() ?? \"node\";\n}\n\nexport async function resolveBin(name: string): Promise {\n const hit = cache.get(name);\n if (hit && Date.now() - hit.at < CACHE_MS) return hit.out;\n const out = await resolveBinUncached(name);\n cache.set(name, { out, at: Date.now() });\n return out;\n}\n\nexport type ResolvedBin = ResolveResult & { ok: true; binName: string };\n\n/** Try several executable names from the catalog in order and return the first hit. */\nexport async function resolveFirstBin(names: string[]): Promise {\n const uniq = [...new Set(names.filter(Boolean))];\n for (const binName of uniq) {\n const r = await resolveBin(binName);\n if (r.ok) return { ...r, binName };\n }\n const label = uniq[0] ?? \"cli\";\n return { ok: false, reason: tr(\"bin.notOnPath\", { name: uniq.length > 1 ? uniq.join(tr(\"bin.or\")) : label }) };\n}\n\nexport function clearBinCache(name?: string): void {\n if (name) cache.delete(name);\n else cache.clear();\n}\n\nexport type ResolveDeps = {\n platform?: NodeJS.Platform;\n find?: (name: string) => string[];\n readText?: (file: string) => Promise;\n exists?: (file: string) => boolean;\n node?: () => string;\n comspec?: string;\n};\n\nfunction resolveBinUncached(name: string): Promise {\n return resolveBinWith(name);\n}\n\n/** Implementation of resolveBin with injectable dependencies (tests simulate a Windows PATH / shims). */\nexport async function resolveBinWith(name: string, deps: ResolveDeps = {}): Promise {\n const platform = deps.platform ?? process.platform;\n const win = platform === \"win32\";\n const P = win ? path.win32 : path.posix;\n const exists = deps.exists ?? existsSync;\n const hits = (deps.find ?? which)(name);\n if (!hits.length) return { ok: false, reason: tr(\"bin.notOnPath\", { name }) };\n // Take the first hit in PATH order (same as typing the command in a terminal; within one directory on Windows, PATHEXT order)\n const first = hits[0];\n if (!win) return { ok: true, cmd: first, prefixArgs: [], display: first, via: \"path\" };\n\n const ext = P.extname(first).toLowerCase();\n if (ext === \".exe\" || ext === \".com\") return { ok: true, cmd: first, prefixArgs: [], display: first, via: \"exe\" };\n if (ext === \".ps1\") {\n return {\n ok: true,\n cmd: \"powershell.exe\",\n prefixArgs: [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", first],\n display: first,\n via: \"ps1\",\n };\n }\n // .cmd / .bat\n const dir = P.dirname(first);\n if (name.toLowerCase() === \"npx\") {\n const node = P.join(dir, \"node.exe\");\n const cli = P.join(dir, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\");\n if (exists(node) && exists(cli))\n return { ok: true, cmd: node, prefixArgs: [cli], display: `${node} ${cli}`, via: \"npx-shim\" };\n }\n const text = await (deps.readText ?? ((f: string) => readFile(f, \"utf8\")))(first).catch(() => \"\");\n const target = shimTarget(text, dir, { exists, win: true });\n if (target && /\\.(js|mjs|cjs)$/i.test(target)) {\n const node = (deps.node ?? findNode)();\n return { ok: true, cmd: node, prefixArgs: [target], display: `${node} ${target}`, via: \"shim-js\" };\n }\n if (target && /\\.exe$/i.test(target)) {\n return { ok: true, cmd: target, prefixArgs: [], display: target, via: \"shim-exe\" };\n }\n // PowerShell / other .cmd wrappers: start through cmd.exe (e.g. cursor-agent); escaping happens in argvFor\n const comspec = deps.comspec ?? (process.env.ComSpec || \"cmd.exe\");\n return { ok: true, cmd: comspec, prefixArgs: [], display: first, via: \"cmd-shim\", shim: first };\n}\n\n// Windows: taskkill /T kills the whole tree; elsewhere: detached process group, kill(-pid).\nexport function killTree(child: ChildProcess | null | undefined, { graceMs = 3000 } = {}): Promise {\n if (!child || child.pid == null) return Promise.resolve();\n const pid = child.pid;\n if (IS_WIN) {\n return new Promise((resolvePromise) => {\n const tk = spawn(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], { windowsHide: true });\n tk.on(\"error\", () => {\n try {\n child.kill();\n } catch {}\n resolvePromise();\n });\n tk.on(\"close\", () => resolvePromise());\n setTimeout(resolvePromise, graceMs + 2000);\n });\n }\n return new Promise((resolvePromise) => {\n let done = false;\n const finish = () => {\n if (!done) {\n done = true;\n resolvePromise();\n }\n };\n try {\n process.kill(-pid, \"SIGTERM\");\n } catch {\n try {\n child.kill(\"SIGTERM\");\n } catch {}\n }\n // A child that has already exited won't emit close again: no need to wait out graceMs\n if (child.exitCode !== null || child.signalCode !== null) {\n finish();\n return;\n }\n const t = setTimeout(() => {\n try {\n process.kill(-pid, \"SIGKILL\");\n } catch {\n try {\n child.kill(\"SIGKILL\");\n } catch {}\n }\n finish();\n }, graceMs);\n t.unref?.();\n child.on(\"close\", () => {\n clearTimeout(t);\n finish();\n });\n });\n}\n","// Tool name → kind / title / detail mapping (ported from lib/agents/kinds.mjs).\n// Adapters call callInfo(name, input, cwd) to get {kind, title, detail}; the frontend renders by kind.\nimport type { ToolKind } from \"../timeline/types.js\";\nimport { tr } from \"../util/i18n.js\";\n\nconst MAX_CMD = 80;\nconst trunc = (s: string, n = MAX_CMD): string => (s.length > n ? s.slice(0, n - 1) + \"…\" : s);\n\nexport function relPath(p: string, cwd: string): string {\n if (!p) return \"\";\n const s = String(p);\n if (!cwd) return s;\n const norm = (x: string) => x.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const a = norm(s);\n const b = norm(cwd);\n if (a.toLowerCase().startsWith(b.toLowerCase() + \"/\")) return a.slice(b.length + 1);\n if (a.toLowerCase() === b.toLowerCase()) return \".\";\n return s;\n}\n\nexport type CallInfo = { kind: ToolKind; title: string; detail: Record };\n\ntype ToolInput = Record & { _exists?: boolean };\n\nexport function callInfo(name: string, input: ToolInput = {}, cwd = \"\"): CallInfo {\n const t = String(name || \"\");\n const f = (kind: ToolKind, title: string, detail: Record): CallInfo => ({ kind, title, detail });\n const file = String(input.file_path ?? input.path ?? input.notebook_path ?? \"\");\n\n switch (t) {\n case \"Read\":\n return f(\"read\", tr(\"tool.read\", { x: relPath(file, cwd) }), { path: file, offset: input.offset, limit: input.limit });\n case \"Edit\":\n return f(\"edit\", tr(\"tool.edit\", { x: relPath(file, cwd) }), { path: file, old: input.old_string, new: input.new_string });\n case \"MultiEdit\":\n return f(\"edit\", tr(\"tool.multiEdit\", { x: relPath(file, cwd), n: ((input.edits as unknown[]) || []).length }), { path: file, edits: input.edits ?? [] });\n case \"Write\":\n return f(\"write\", tr(input._exists ? \"tool.overwrite\" : \"tool.create\", { x: relPath(file, cwd) }), { path: file, content: input.content });\n case \"NotebookEdit\":\n return f(\"edit\", tr(\"tool.notebook\", { x: relPath(String(input.notebook_path || file), cwd) }), { path: input.notebook_path ?? file });\n case \"Bash\":\n return f(\"bash\", tr(\"tool.run\", { x: trunc(String(input.command ?? \"\")) }), { command: input.command, description: input.description });\n case \"BashOutput\":\n return f(\"bash\", tr(\"tool.output\", { x: String(input.bash_id ?? \"\") }), { bashId: input.bash_id });\n case \"KillShell\":\n return f(\"bash\", tr(\"tool.kill\", { x: String(input.shell_id ?? \"\") }), { shellId: input.shell_id });\n case \"Grep\":\n return f(\"search\", tr(\"tool.grep\", { x: trunc(String(input.pattern ?? \"\"), 40) }), { pattern: input.pattern, path: input.path, glob: input.glob });\n case \"Glob\":\n case \"LS\":\n return f(\"glob\", tr(\"tool.glob\", { x: trunc(String(input.pattern ?? input.path ?? \"\"), 40) }), { pattern: input.pattern, path: input.path });\n case \"WebFetch\":\n return f(\"web\", tr(\"tool.fetch\", { x: hostOf(String(input.url ?? \"\")) }), { url: input.url });\n case \"WebSearch\":\n return f(\"web\", tr(\"tool.webSearch\", { x: trunc(String(input.query ?? \"\"), 40) }), { query: input.query });\n case \"TodoWrite\": {\n const items = todoItems((input.todos as { content?: string; text?: string; status?: string }[]) ?? []);\n const done = items.filter((x) => x.status === \"done\").length;\n return f(\"todo\", tr(\"tool.todo\", { done, n: items.length }), { items });\n }\n case \"Task\":\n case \"Agent\":\n return f(\"task\", tr(\"tool.task\", { x: trunc(String(input.description ?? input.prompt ?? \"\"), 40) }), { description: input.description });\n default:\n break;\n }\n const m = /^mcp__([^_]+)__(.+)$/.exec(t);\n if (m) return f(\"mcp\", `${m[1]} · ${m[2]}`, { server: m[1], tool: m[2] });\n return f(\"other\", t || tr(\"tool.generic\"), {});\n}\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).host;\n } catch {\n return String(url || \"\").slice(0, 40);\n }\n}\n\nexport function todoItems(todos: { content?: string; text?: string; status?: string }[] = []): { text: string; status: string }[] {\n return todos.map((x) => ({\n text: x.content || x.text || \"\",\n status: x.status === \"completed\" ? \"done\" : x.status === \"in_progress\" ? \"in_progress\" : \"pending\",\n }));\n}\n","// claude stream-json messages (and ~/.claude/projects jsonl lines) → ProviderEvent (§7.2.3). Ported from normalize in lib/agents/claude.mjs.\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { callInfo, todoItems } from \"../../agents/kinds.js\";\nimport { editDetail } from \"../../agents/diff.js\";\nimport { tr } from \"../../util/i18n.js\";\n\nconst MAX_OUTPUT = 20 * 1024;\nconst ANSI_RE = /\\x1b\\[[0-9;]*[a-zA-Z]|\\x1b\\][^\\x07]*\\x07/g;\nconst clean = (s: string): string => String(s ?? \"\").replace(ANSI_RE, \"\");\n\nexport type MapState = {\n blocks: Map; // content_block_start index → block type\n msgId: string; // Current streaming message.id\n // Streaming block index → unified itemId (msgId:type:ordinal within type).\n // claude's content_block index interleaves thinking/text, while the content array of the assistant event\n // may be renumbered (when thinking is split into another message, text goes back to 0) — a bare index would make\n // the delta and complete event itemIds diverge and the frontend render two duplicate replies. Align both sides by type + ordinal within type.\n itemIdByBlock: Map;\n typeSeq: Map; // Count of each block type in the current message (delta side)\n sawInterrupt: boolean; // After interrupt() the next result counts as interrupted\n};\n\nexport function newMapState(): MapState {\n return { blocks: new Map(), msgId: \"\", itemIdByBlock: new Map(), typeSeq: new Map(), sawInterrupt: false };\n}\n\n// Block type → short code and channel for itemIds; thinking/reasoning are one kind, text another; tool_use uses the tool id and doesn't go through here\nconst blockKind = (t: string): string =>\n t === \"thinking\" || t === \"redacted_thinking\" ? \"k\" : t === \"text\" ? \"t\" : \"x\";\n\nfunction itemIdFor(st: MapState, blockIdx: number, blkType: string): string {\n const k = blockKind(blkType);\n const n = st.typeSeq.get(k) ?? 0;\n st.typeSeq.set(k, n + 1);\n const id = `${st.msgId}:${k}${n}`;\n st.itemIdByBlock.set(blockIdx, id);\n return id;\n}\n\ntype Rec = Record;\nconst rec = (v: unknown): Rec => (v && typeof v === \"object\" ? (v as Rec) : {});\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n\n// One stream-json message → 0..n unified events\n/** total_cost_usd is Claude Code's estimate at Anthropic's prices. For another vendor's model behind a gateway (DeepSeek through\n * magpie, say) it is meaningless, so it is only kept when every model the turn used is a Claude model (B14). */\nexport function costIsReal(modelUsage: unknown): boolean {\n if (!modelUsage || typeof modelUsage !== \"object\") return true;\n const names = Object.keys(modelUsage as Record);\n return names.every((n) => /claude|opus|sonnet|haiku/i.test(n));\n}\n\nexport function mapSdkMessage(m: unknown, st: MapState, cwd: string): ProviderEvent[] {\n const out: ProviderEvent[] = [];\n if (!m || typeof m !== \"object\") return out;\n const r = m as unknown as Rec;\n\n if (r.type === \"system\") {\n if (r.subtype === \"init\") {\n const sid = str(r.session_id) ?? \"\";\n if (sid) out.push({ type: \"provider_session_id\", id: sid });\n }\n // compact_boundary / status / api_retry etc. → lightweight notices\n if (r.subtype === \"api_retry\") {\n out.push({ type: \"notice\", level: \"warn\", message: tr(\"notice.apiRetry\", { n: String(r.attempt ?? \"?\") }) });\n }\n if (r.subtype === \"compact_boundary\") {\n out.push({ type: \"notice\", level: \"info\", message: tr(\"notice.compacted\") });\n }\n return out;\n }\n\n if (r.type === \"stream_event\") {\n const e = rec(r.event);\n if (e.type === \"message_start\") {\n const mid = str(rec(e.message).id);\n if (mid) st.msgId = mid;\n st.blocks.clear();\n st.itemIdByBlock.clear();\n st.typeSeq.clear();\n return out;\n }\n if (e.type === \"content_block_start\") {\n const idx = typeof e.index === \"number\" ? e.index : 0;\n const bt = str(rec(e.content_block).type) ?? \"\";\n st.blocks.set(idx, bt);\n itemIdFor(st, idx, bt); // Register index → unified itemId\n return out;\n }\n if (e.type === \"content_block_delta\") {\n const idx = typeof e.index === \"number\" ? e.index : 0;\n const d = rec(e.delta);\n // Fallback when a delta arrives before its start: infer and register from the delta type\n const itemId = st.itemIdByBlock.get(idx) ?? itemIdFor(st, idx, d.type === \"thinking_delta\" ? \"thinking\" : \"text\");\n if (d.type === \"text_delta\" && typeof d.text === \"string\" && d.text) {\n out.push({ type: \"assistant_delta\", itemId, text: d.text });\n } else if (d.type === \"thinking_delta\") {\n const t = str(d.thinking) ?? str(d.text);\n if (t) out.push({ type: \"reasoning_delta\", itemId, text: t });\n }\n // Ignore input_json_delta: wait for the complete tool_use in the assistant message\n }\n return out;\n }\n\n if (r.type === \"assistant\") {\n const mid = str(rec(r.message).id) ?? st.msgId ?? \"\";\n const content = rec(r.message).content;\n const parts = Array.isArray(content) ? content : [];\n // Same rule as the streaming side: build itemIds from type + ordinal within type so they overwrite the matching deltas\n const seqs = new Map();\n parts.forEach((p) => {\n const blk = rec(p);\n const t = str(blk.type) ?? \"\";\n const k = blockKind(t);\n const n = seqs.get(k) ?? 0;\n seqs.set(k, n + 1);\n const itemId = `${mid}:${k}${n}`;\n if (blk.type === \"text\" && typeof blk.text === \"string\" && blk.text) {\n out.push({ type: \"assistant_message\", itemId, text: blk.text });\n } else if (blk.type === \"thinking\" || blk.type === \"redacted_thinking\") {\n const t2 = str(blk.thinking) ?? str(blk.text);\n if (t2) out.push({ type: \"reasoning\", itemId, text: t2 });\n } else if (blk.type === \"tool_use\") {\n out.push(...mapToolUse(blk, cwd));\n }\n });\n return out;\n }\n\n if (r.type === \"user\") {\n const content = rec(r.message).content;\n const parts = Array.isArray(content) ? content : [];\n for (const p of parts) {\n const blk = rec(p);\n if (blk.type === \"tool_result\") {\n const output = clean(contentText(blk.content));\n out.push({\n type: \"tool_call\",\n itemId: str(blk.tool_use_id) ?? \"\",\n kind: \"other\",\n title: \"\",\n status: blk.is_error ? \"failed\" : \"ok\",\n output: output.length > MAX_OUTPUT ? output.slice(0, MAX_OUTPUT) : output,\n });\n }\n }\n return out;\n }\n\n if (r.type === \"result\") {\n const usage = rec(r.usage);\n const num = (k: string): number => (typeof usage[k] === \"number\" ? (usage[k] as number) : 0);\n out.push({\n type: \"usage\",\n inputTokens: num(\"input_tokens\"),\n outputTokens: num(\"output_tokens\"),\n cacheReadTokens: num(\"cache_read_input_tokens\"),\n costUsd: typeof r.total_cost_usd === \"number\" && costIsReal(r.modelUsage) ? r.total_cost_usd : 0,\n });\n const subtype = str(r.subtype) ?? \"\";\n const interrupted = st.sawInterrupt || /interrupt/i.test(subtype);\n const isError = r.is_error === true;\n out.push({\n type: \"turn_ended\",\n turnId: \"\", // The session fills in the current turnId\n status: interrupted ? \"interrupted\" : isError ? \"failed\" : \"completed\",\n durationMs: typeof r.duration_ms === \"number\" ? r.duration_ms : undefined,\n error: isError && !interrupted ? str(r.result) ?? subtype : undefined,\n filesChanged: typeof r.num_turns === \"number\" ? undefined : undefined,\n });\n st.sawInterrupt = false;\n return out;\n }\n return out;\n}\n\nfunction mapToolUse(blk: Rec, cwd: string): ProviderEvent[] {\n const input = rec(blk.input);\n const name = str(blk.name) ?? \"tool\";\n const id = str(blk.id) ?? \"\";\n const info = callInfo(name, { ...input, _exists: true }, cwd);\n let detail: unknown = info.detail;\n if (info.kind === \"edit\" && (input.old_string !== undefined || Array.isArray(input.edits))) {\n detail = editDetail({ path: (info.detail as Rec).path as string, old: input.old_string, new: input.new_string, edits: input.edits });\n }\n if (info.kind === \"write\" && typeof input.content === \"string\") {\n const lines = input.content.split(\"\\n\");\n detail = { path: (info.detail as Rec).path, lines: lines.slice(0, 200), totalLines: lines.length };\n }\n const out: ProviderEvent[] = [\n {\n type: \"tool_call\",\n itemId: id,\n kind: info.kind,\n title: info.title,\n status: \"running\",\n input,\n detail,\n },\n ];\n if (name === \"TodoWrite\") {\n out.push({ type: \"todo\", items: todoItems((input.todos as { content?: string; status?: string }[]) ?? []) });\n }\n return out;\n}\n\nfunction contentText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content)) return content.map((p) => str(rec(p).text) ?? \"\").join(\"\");\n return \"\";\n}\n","import { existsSync } from \"node:fs\";\nimport type { AttachmentStore } from \"../store/attachments.js\";\nimport { validId } from \"./paths.js\";\nimport { tr } from \"./i18n.js\";\n\nlet globalAttachmentStore: AttachmentStore | null = null;\n\n/** Registered at main startup so Providers can resolve upload ids when reading images */\nexport function bindAttachmentStore(store: AttachmentStore): void {\n globalAttachmentStore = store;\n}\n\nasync function lookupAttachmentPath(ref: string): Promise {\n const store = globalAttachmentStore;\n if (!store || !validId(ref)) return null;\n const att = await store.get(ref);\n return att?.path ?? null;\n}\n\nexport async function resolveAttachmentRefs(\n store: AttachmentStore,\n refs: { path: string; mime: string }[],\n): Promise<{ path: string; mime: string }[]> {\n const out: { path: string; mime: string }[] = [];\n for (const a of refs) {\n const att = validId(a.path) ? await store.get(a.path) : null;\n if (att) {\n out.push({ path: att.path, mime: att.mime || a.mime });\n continue;\n }\n const viaGlobal = await lookupAttachmentPath(a.path);\n if (viaGlobal) {\n out.push({ path: viaGlobal, mime: a.mime });\n continue;\n }\n if (existsSync(a.path)) {\n out.push(a);\n continue;\n }\n throw new Error(tr(\"attachment.missing\", { ref: a.path }));\n }\n return out;\n}\n\n/** One path: absolute path / upload id → the file under the attachments directory; throws on failure */\nexport async function resolveImagePath(ref: string): Promise {\n if (existsSync(ref)) return ref;\n const p = await lookupAttachmentPath(ref);\n if (p) return p;\n throw new Error(tr(\"attachment.missing\", { ref: ref }));\n}\n","// What an attachment is, for deciding how each Agent gets it.\n// Only PNG, JPEG, GIF and WebP are images to the model APIs behind Claude Code, Codex and the ACP Agents\n// (Anthropic's Base64ImageSource.media_type is exactly these four); anything else is a file the Agent opens by path.\nexport const MODEL_IMAGE_MIMES = new Set([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"]);\n\nexport type AttachmentKind = \"image\" | \"text\" | \"other\";\n\n/** \"text/plain; charset=utf-8\" → \"text/plain\" */\nexport function baseMime(mime: string | undefined | null): string {\n return String(mime ?? \"\").split(\";\")[0].trim().toLowerCase();\n}\n\nconst TEXT_APP = new Set([\"application/json\", \"application/xml\", \"application/yaml\", \"application/x-yaml\", \"application/toml\", \"application/javascript\"]);\n\nexport function attachmentKind(mime: string | undefined | null): AttachmentKind {\n const m = baseMime(mime);\n if (MODEL_IMAGE_MIMES.has(m)) return \"image\";\n if (m.startsWith(\"text/\") || TEXT_APP.has(m)) return \"text\";\n return \"other\";\n}\n\n/** The line an Agent gets for an attachment sent by path */\nexport function pathNote(kind: AttachmentKind, file: string): string {\n return `${kind === \"image\" ? \"Attached image\" : \"Attached file\"}: ${file}`;\n}\n","// One user message → the content blocks of a claude stream-json user message (Anthropic Messages content).\n// - PNG / JPEG / GIF / WebP (Base64ImageSource's media types), up to 5 MB each: an image block\n// - text files up to 1 MB: a document block with a plain-text source (DocumentBlockParam + PlainTextSource)\n// - anything else, or too large: the file's absolute path in the text, which Claude Code can Read; with a warning\n// for files that aren't images or text, so the user knows\nimport { readFile, stat } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { resolveImagePath } from \"../../util/attachmentRefs.js\";\nimport { attachmentKind, baseMime, pathNote } from \"../../util/attachmentKinds.js\";\n\n/** Anthropic's per-image limit */\nexport const CLAUDE_MAX_IMAGE_BYTES = 5 * 1024 * 1024;\nexport const CLAUDE_MAX_TEXT_BYTES = 1024 * 1024;\n\ntype ImageMedia = \"image/png\" | \"image/jpeg\" | \"image/gif\" | \"image/webp\";\nexport type ClaudeBlock =\n | { type: \"text\"; text: string }\n | { type: \"image\"; source: { type: \"base64\"; media_type: ImageMedia; data: string } }\n | { type: \"document\"; source: { type: \"text\"; media_type: \"text/plain\"; data: string }; title?: string; context?: string };\n\nexport async function buildClaudeContent(\n text: string,\n attachments: { path: string; mime: string }[],\n): Promise<{ blocks: ClaudeBlock[]; warnings: string[] }> {\n const media: ClaudeBlock[] = [];\n const notes: string[] = [];\n const warnings: string[] = [];\n for (const a of attachments) {\n let file: string;\n let size: number;\n try {\n file = await resolveImagePath(a.path);\n size = (await stat(file)).size;\n } catch (e) {\n warnings.push(`${a.path}: ${String((e as Error)?.message ?? e)}`);\n continue;\n }\n const kind = attachmentKind(a.mime);\n try {\n if (kind === \"image\" && size <= CLAUDE_MAX_IMAGE_BYTES) {\n const data = (await readFile(file)).toString(\"base64\");\n media.push({ type: \"image\", source: { type: \"base64\", media_type: baseMime(a.mime) as ImageMedia, data } });\n continue;\n }\n if (kind === \"text\" && size <= CLAUDE_MAX_TEXT_BYTES) {\n const data = await readFile(file, \"utf8\");\n media.push({ type: \"document\", source: { type: \"text\", media_type: \"text/plain\", data }, title: basename(file), context: file });\n continue;\n }\n } catch (e) {\n warnings.push(`${basename(file)}: ${String((e as Error)?.message ?? e)}`);\n }\n notes.push(pathNote(kind, file));\n if (kind === \"other\") warnings.push(`${basename(file)} (${baseMime(a.mime) || \"unknown type\"}) is not an image or a text file; sent its path`);\n else if (kind === \"image\" && size > CLAUDE_MAX_IMAGE_BYTES) warnings.push(`${basename(file)}: ${(size / 1024 / 1024).toFixed(1)} MB, over Claude's 5 MB image limit; sent its path`);\n else if (kind === \"text\" && size > CLAUDE_MAX_TEXT_BYTES) warnings.push(`${basename(file)}: ${(size / 1024 / 1024).toFixed(1)} MB, too large to attach inline; sent its path`);\n }\n const fullText = [text, ...(notes.length ? [notes.join(\"\\n\")] : [])].filter(Boolean).join(\"\\n\\n\");\n // Media first, as before; the text block always comes last (claude needs at least one block)\n return { blocks: [...media, { type: \"text\", text: fullText }], warnings };\n}\n","// Settings › Launch command: a custom executable for an Agent plus extra arguments.\n// The arguments the user types are APPENDED after the built-in ones (e.g. `opencode acp --foo`, `codex app-server --foo`,\n// `claude --foo`). prefixArgs is internal (tests run `node fixture.mjs`) and goes before the built-ins.\nimport type { LaunchCommand } from \"./types.js\";\nimport type { Settings } from \"../store/settings.js\";\nimport { resolveBin, type ResolveResult } from \"../util/bin.js\";\nimport { tr } from \"../util/i18n.js\";\n\nexport function launchFromSettings(settings: Settings, providerId: string): LaunchCommand | undefined {\n const c = settings.providerCommand?.[providerId];\n const cmd = typeof c?.executable === \"string\" ? c.executable.trim() : \"\";\n if (!cmd) return undefined;\n const args = Array.isArray(c?.args) ? c!.args.filter((a): a is string => typeof a === \"string\") : [];\n return { cmd, args };\n}\n\n/** Built-in arguments wrapped with the launch command's internal prefix and the user's extra arguments. */\nexport function launchArgv(builtin: string[], launch?: LaunchCommand): string[] {\n return [...(launch?.prefixArgs ?? []), ...builtin, ...(launch?.args ?? [])];\n}\n\n/** Resolve a custom executable (absolute path or a name on PATH; Windows .cmd/.ps1 shims are handled by resolveBin). */\nexport async function resolveLaunch(launch: LaunchCommand): Promise {\n const r = await resolveBin(launch.cmd);\n if (r.ok) return r;\n return { ok: false, reason: tr(\"launch.notFound\", { cmd: launch.cmd }) };\n}\n\nexport function launchKey(launch?: LaunchCommand): string {\n return launch ? `${launch.cmd}\\0${(launch.prefixArgs ?? []).join(\"\\0\")}\\0\\0${(launch.args ?? []).join(\"\\0\")}` : \"\";\n}\n","// The user's own `claude` CLI driven over its stream-json protocol (no SDK):\n// claude -p --input-format stream-json --output-format stream-json --verbose --include-partial-messages\n// --permission-prompt-tool stdio [--model m] [--permission-mode p] [--effort e] [--resume id]\n// stdin and stdout carry one JSON object per line. Besides the conversation messages (user / assistant / system /\n// stream_event / result), both sides send control messages:\n// → {type:\"control_request\", request_id, request:{subtype:\"initialize\" | \"interrupt\" | \"set_model\" | \"set_permission_mode\", ...}}\n// ← {type:\"control_response\", response:{subtype:\"success\" | \"error\", request_id, response? | error?}}\n// ← {type:\"control_request\", request_id, request:{subtype:\"can_use_tool\", tool_name, input, tool_use_id, ...}}\n// → {type:\"control_response\", response:{subtype:\"success\", request_id, response:{behavior:\"allow\", updatedInput} | {behavior:\"deny\", message, interrupt?}}}\n// ← {type:\"control_cancel_request\", request_id} (the CLI no longer waits for that answer)\nimport type { LaunchCommand } from \"../types.js\";\nimport { launchArgv } from \"../launch.js\";\nimport type { ChildProcess } from \"node:child_process\";\nimport { killTree, spawnBin, type ResolveResult } from \"../../util/bin.js\";\nimport { AsyncQueue } from \"../../util/queue.js\";\n\nexport type ClaudeBin = ResolveResult & { ok: true };\nexport type Json = Record;\n\nexport type ClaudeCliOpts = {\n bin: ClaudeBin;\n cwd: string;\n model: string | null;\n permissionMode: string;\n effort: string | null;\n resume: string | null;\n env?: NodeJS.ProcessEnv;\n /** Settings › Launch command: internal prefix before, user args after the built-in flags */\n launch?: LaunchCommand;\n};\n\nexport type PermissionDecision =\n | { behavior: \"allow\"; updatedInput: Json }\n | { behavior: \"deny\"; message: string; interrupt?: boolean };\n\nexport type ToolRequest = { toolName: string; input: Json; toolUseId?: string; signal: AbortSignal };\nexport type CanUseTool = (req: ToolRequest) => Promise;\n\n/** Session ids and model / mode / effort names become argv: plain tokens only, so nothing can turn into another flag. */\nconst SAFE_ARG = /^[A-Za-z0-9][A-Za-z0-9._:\\[\\]\\/@+-]{0,199}$/;\n\nexport function claudeArgs(o: Pick): string[] {\n const args = [\n \"-p\",\n \"--input-format\", \"stream-json\",\n \"--output-format\", \"stream-json\",\n \"--verbose\",\n \"--include-partial-messages\",\n \"--permission-prompt-tool\", \"stdio\",\n \"--setting-sources\", \"user,project,local\",\n ];\n const put = (flag: string, v: string | null | undefined) => {\n if (!v) return;\n if (!SAFE_ARG.test(v)) throw new Error(`Refusing to pass an unexpected value to claude ${flag}: ${JSON.stringify(v).slice(0, 80)}`);\n args.push(flag, v);\n };\n put(\"--permission-mode\", o.permissionMode);\n // claude only takes bypassPermissions when it is allowed at launch; it is not allowed otherwise (a later switch\n // into it restarts the CLI with --resume)\n if (o.permissionMode === \"bypassPermissions\") args.push(\"--allow-dangerously-skip-permissions\");\n put(\"--model\", o.model);\n put(\"--effort\", o.effort);\n put(\"--resume\", o.resume);\n return args;\n}\n\ntype Pending = { resolve: (v: Json) => void; reject: (e: Error) => void; timer?: NodeJS.Timeout };\n\nexport class ClaudeCli {\n /** Conversation messages (everything that is not a control message) */\n readonly messages = new AsyncQueue();\n readonly exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;\n /** The answer to initialize (commands, models, account …), null when it failed */\n readonly initialized: Promise;\n private child: ChildProcess;\n private buf = \"\";\n private seq = 0;\n private pending = new Map();\n private cancels = new Map();\n private stderrTail = \"\";\n private dead = false;\n private spawnError: Error | null = null;\n\n constructor(private o: ClaudeCliOpts, private canUseTool: CanUseTool) {\n const args = launchArgv(claudeArgs(o), o.launch);\n this.child = spawnBin(o.bin, args, {\n cwd: o.cwd,\n env: { ...(o.env ?? process.env), NO_COLOR: \"1\", FORCE_COLOR: \"0\" },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n group: true,\n });\n this.child.stdout?.setEncoding(\"utf8\");\n this.child.stdout?.on(\"data\", (d: string) => this.onData(d));\n this.child.stderr?.on(\"data\", (d: Buffer) => {\n this.stderrTail = (this.stderrTail + d.toString()).slice(-4096);\n });\n this.child.stdin?.on(\"error\", () => {}); // EPIPE after the CLI exits: reported through exited\n this.exited = new Promise((resolve) => {\n this.child.on(\"error\", (e) => {\n this.spawnError = e;\n this.finish();\n resolve({ code: null, signal: null });\n });\n this.child.on(\"close\", (code, signal) => {\n this.finish();\n resolve({ code, signal });\n });\n });\n this.initialized = this.request({ subtype: \"initialize\" }, 60000).catch(() => null);\n }\n\n get stderr(): string {\n return this.stderrTail;\n }\n\n get failure(): Error | null {\n return this.spawnError;\n }\n\n get alive(): boolean {\n return !this.dead;\n }\n\n private finish(): void {\n if (this.dead) return;\n this.dead = true;\n for (const [, p] of this.pending) {\n if (p.timer) clearTimeout(p.timer);\n p.reject(new Error(\"claude exited\"));\n }\n this.pending.clear();\n for (const [, c] of this.cancels) c.abort();\n this.cancels.clear();\n this.messages.close();\n }\n\n private onData(d: string): void {\n this.buf += d;\n let i: number;\n while ((i = this.buf.indexOf(\"\\n\")) >= 0) {\n const line = this.buf.slice(0, i).trim();\n this.buf = this.buf.slice(i + 1);\n if (!line) continue;\n let m: Json;\n try {\n m = JSON.parse(line);\n } catch {\n continue; // a stray non-JSON line (warnings some versions print) is not part of the protocol\n }\n if (m && typeof m === \"object\") this.onMessage(m);\n }\n }\n\n private onMessage(m: Json): void {\n if (m.type === \"control_response\") {\n const r = (m.response ?? {}) as Json;\n const id = String(r.request_id ?? \"\");\n const p = this.pending.get(id);\n if (!p) return;\n this.pending.delete(id);\n if (p.timer) clearTimeout(p.timer);\n if (r.subtype === \"success\") p.resolve((r.response ?? {}) as Json);\n else p.reject(new Error(String(r.error ?? \"control request failed\")));\n return;\n }\n if (m.type === \"control_request\") {\n void this.onControlRequest(String(m.request_id ?? \"\"), (m.request ?? {}) as Json);\n return;\n }\n if (m.type === \"control_cancel_request\") {\n const id = String(m.request_id ?? \"\");\n this.cancels.get(id)?.abort();\n this.cancels.delete(id);\n return;\n }\n if (m.type === \"keep_alive\") return;\n this.messages.push(m);\n }\n\n private async onControlRequest(id: string, req: Json): Promise {\n if (req.subtype !== \"can_use_tool\") {\n // hooks, in-process MCP servers, elicitation …: none are registered, so say so instead of leaving the CLI waiting\n this.write({ type: \"control_response\", response: { subtype: \"error\", request_id: id, error: `Unsupported control request: ${String(req.subtype)}` } });\n return;\n }\n const ac = new AbortController();\n this.cancels.set(id, ac);\n try {\n const decision = await this.canUseTool({\n toolName: String(req.tool_name ?? \"\"),\n input: (req.input && typeof req.input === \"object\" ? req.input : {}) as Json,\n toolUseId: typeof req.tool_use_id === \"string\" ? req.tool_use_id : undefined,\n signal: ac.signal,\n });\n if (ac.signal.aborted && !this.cancels.has(id)) return; // cancelled by the CLI: it no longer reads this answer\n this.write({ type: \"control_response\", response: { subtype: \"success\", request_id: id, response: decision } });\n } catch (e) {\n this.write({ type: \"control_response\", response: { subtype: \"error\", request_id: id, error: String((e as Error)?.message ?? e) } });\n } finally {\n this.cancels.delete(id);\n }\n }\n\n private write(o: Json): boolean {\n if (this.dead || !this.child.stdin || this.child.stdin.destroyed) return false;\n try {\n this.child.stdin.write(JSON.stringify(o) + \"\\n\");\n return true;\n } catch {\n return false;\n }\n }\n\n /** Send one control request and wait for its answer */\n request(request: Json, timeoutMs = 10000): Promise {\n if (this.dead) return Promise.reject(new Error(\"claude is not running\"));\n const id = `ac_${++this.seq}_${Math.random().toString(36).slice(2, 8)}`;\n return new Promise((resolve, reject) => {\n const p: Pending = { resolve, reject };\n p.timer = setTimeout(() => {\n if (this.pending.delete(id)) reject(new Error(`claude did not answer ${String(request.subtype)} in ${Math.round(timeoutMs / 1000)} s`));\n }, timeoutMs);\n this.pending.set(id, p);\n if (!this.write({ type: \"control_request\", request_id: id, request })) {\n this.pending.delete(id);\n clearTimeout(p.timer);\n reject(new Error(\"claude is not running\"));\n }\n });\n }\n\n /** One user message into the conversation */\n sendUser(content: unknown[], sessionId: string | null): boolean {\n return this.write({ type: \"user\", message: { role: \"user\", content }, parent_tool_use_id: null, session_id: sessionId ?? \"\" });\n }\n\n interrupt(): Promise {\n return this.request({ subtype: \"interrupt\" }, 5000);\n }\n\n setModel(model: string | null): Promise {\n return this.request(model ? { subtype: \"set_model\", model } : { subtype: \"set_model\" });\n }\n\n setPermissionMode(mode: string): Promise {\n return this.request({ subtype: \"set_permission_mode\", mode });\n }\n\n /** End stdin (the CLI finishes and exits), then end the process tree if it lingers */\n async close(graceMs = 2000): Promise {\n try {\n this.child.stdin?.end();\n } catch {}\n const done = await Promise.race([this.exited.then(() => true), new Promise((r) => setTimeout(() => r(false), graceMs))]);\n if (!done) await killTree(this.child, { graceMs: 500 });\n this.finish();\n }\n}\n","// Claude ProviderSession (§7.2.2/7.2.4/7.2.5/7.2.6): the user's own `claude` CLI over stream-json (./cli.ts),\n// one process per conversation, streaming, permissions, interrupt, hot switching. No SDK.\nimport type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from \"../types.js\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { AsyncQueue } from \"../../util/queue.js\";\nimport { callInfo } from \"../../agents/kinds.js\";\nimport { editDetail } from \"../../agents/diff.js\";\nimport { mapSdkMessage, newMapState, type MapState } from \"./map.js\";\nimport { log } from \"../../log.js\";\nimport { buildClaudeContent } from \"./content.js\";\nimport { tr } from \"../../util/i18n.js\";\nimport { classifyClaudeSlashCommand, sortSlashCommands } from \"../slash.js\";\nimport { ClaudeCli, type ClaudeBin, type PermissionDecision, type ToolRequest } from \"./cli.js\";\n\nconst EFFORTS = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\nconst MODES = [\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\"];\nconst rid = () => Math.random().toString(36).slice(2, 10);\n\ntype PendingReq = {\n kind: \"permission\" | \"question\";\n resolve: (r: RespondAnswer) => void;\n};\n\nexport type ClaudeSessionOpts = {\n threadId: string;\n cwd: string;\n model: string | null;\n mode: Mode;\n effort: string | null;\n resumeId: string | null;\n /** The user's claude, as resolveBin found it (a .cmd / .ps1 shim is started through cmd.exe / PowerShell by spawnBin) */\n bin: ClaudeBin;\n launch?: LaunchCommand;\n /** Environment for the CLI (tests point it at a stand-in); process.env when absent */\n env?: NodeJS.ProcessEnv;\n onModeChange?: (mode: Mode) => void; // Callback when a plan is approved → default (the manager updates meta)\n};\n\nexport class ClaudeSession implements ProviderSession {\n events: AsyncIterable;\n private q = new AsyncQueue();\n private cli: ClaudeCli | null = null;\n private sessionId: string | null;\n private turnId: string | null = null;\n private turnNum = 0;\n private st: MapState = newMapState();\n private pending = new Map();\n private needsRestart = false;\n private restarting: Promise | null = null;\n private closed = false;\n private stopping = new WeakSet();\n private pumpDone: Promise | null = null;\n /** Mode the running CLI was started with (bypassPermissions has to be allowed at launch) */\n private launchedMode: string | null = null;\n\n constructor(private o: ClaudeSessionOpts) {\n this.sessionId = o.resumeId;\n this.events = this.q;\n }\n\n // The CLI is only started before the first send (or a command list request)\n private ensureCli(): ClaudeCli {\n if (this.cli && !this.needsRestart) return this.cli;\n this.st = newMapState();\n const effort = this.o.effort && EFFORTS.includes(this.o.effort) ? this.o.effort : null;\n const cli = new ClaudeCli(\n {\n bin: this.o.bin,\n cwd: this.o.cwd,\n model: this.o.model,\n permissionMode: MODES.includes(this.o.mode) ? this.o.mode : \"default\",\n effort,\n resume: this.sessionId,\n env: this.o.env,\n launch: this.o.launch,\n },\n (req) => this.canUseTool(req),\n );\n this.cli = cli;\n this.launchedMode = this.o.mode;\n this.needsRestart = false;\n this.pumpDone = this.pump(cli);\n return cli;\n }\n\n private async pump(cli: ClaudeCli): Promise {\n for await (const m of cli.messages) {\n for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) this.emit(ev);\n }\n const exit = await cli.exited;\n // A CLI this session stopped on purpose (restart / close) is not a crash\n if (this.closed || this.stopping.has(cli)) return;\n const detail = cli.failure\n ? tr(\"claude.startFailed\", { detail: String(cli.failure.message) })\n : tr(\"claude.exited\", { code: String(exit.code ?? exit.signal ?? \"?\") });\n const tail = cli.stderr.trim().slice(-400);\n this.emit({ type: \"notice\", level: \"error\", message: tail ? `${detail} — stderr: ${tail}` : detail });\n if (this.turnId) this.emit({ type: \"turn_ended\", turnId: this.turnId, status: \"failed\", error: detail });\n this.turnId = null;\n // The event stream ended: an old CLI that restart() replaced must not close the event queue\n if (this.cli === cli) {\n this.needsRestart = true; // Rebuild with --resume on the next send\n this.q.close();\n }\n }\n\n private emit(ev: ProviderEvent): void {\n if (ev.type === \"turn_ended\" && !ev.turnId) ev.turnId = this.turnId ?? \"unknown\";\n if (ev.type === \"turn_ended\") this.turnId = null;\n if (ev.type === \"provider_session_id\" && ev.id) this.sessionId = ev.id;\n this.q.push(ev);\n }\n\n async send(input: SendInput): Promise {\n if (this.closed) throw new Error(tr(\"claude.closed\"));\n if (this.needsRestart) await this.restart();\n const cli = this.ensureCli();\n this.turnNum++;\n this.turnId = \"u_\" + Date.now().toString(36) + \"_\" + this.turnNum;\n this.st.sawInterrupt = false; // A new turn clears the old interrupt flag\n this.emit({\n type: \"turn_started\",\n turnId: this.turnId,\n model: this.o.model,\n mode: this.o.mode,\n effort: this.o.effort,\n });\n const built = await buildClaudeContent(input.text, input.images ?? []);\n for (const w of built.warnings) this.emit({ type: \"notice\", level: \"warn\", message: tr(\"notice.attachmentIssue\", { detail: w }) });\n if (!cli.sendUser(built.blocks, this.sessionId)) throw new Error(tr(\"claude.notRunning\"));\n }\n\n private async restart(): Promise {\n if (this.restarting) return this.restarting;\n this.restarting = (async () => {\n const old = this.cli;\n this.cli = null;\n if (old) {\n this.stopping.add(old);\n await old.close().catch(() => {});\n }\n if (this.pumpDone) await this.pumpDone.catch(() => {});\n try {\n this.ensureCli();\n } finally {\n this.restarting = null;\n }\n })();\n return this.restarting;\n }\n\n // ---- permissions (§7.2.4) ----\n private canUseTool(req: ToolRequest): Promise {\n const { toolName, input, signal } = req;\n const requestId = \"perm_\" + rid();\n const opts = { toolUseID: req.toolUseId };\n\n if (toolName === \"ExitPlanMode\") {\n return this.handlePlanMode(requestId, input, signal, opts.toolUseID);\n }\n if (toolName === \"AskUserQuestion\" && Array.isArray(input.questions)) {\n return this.handleQuestion(requestId, input, signal);\n }\n\n const info = callInfo(toolName, { ...input, _exists: true }, this.o.cwd);\n let detail: Record = { ...(info.detail as Record), toolName };\n if (info.kind === \"edit\" && (input.old_string !== undefined || Array.isArray(input.edits))) {\n detail = { ...editDetail({ path: info.detail.path as string, old: input.old_string, new: input.new_string, edits: input.edits }), toolName };\n }\n this.emit({\n type: \"permission_request\",\n requestId,\n title: info.title,\n kind: \"tool\",\n detail,\n options: [\n { id: \"allow\", label: tr(\"perm.allow\"), kind: \"allow_once\" },\n { id: \"allow_always\", label: tr(\"perm.allowSession\"), kind: \"allow_always\" },\n { id: \"deny\", label: tr(\"perm.deny\"), kind: \"reject_once\" },\n ],\n });\n return new Promise((resolve) => {\n this.pending.set(requestId, { kind: \"permission\", resolve: (a) => resolve(this.toPermissionDecision(a, input)) });\n signal.addEventListener(\"abort\", () => {\n if (this.pending.delete(requestId)) {\n this.emit({ type: \"permission_resolved\", requestId, cancelled: true });\n resolve({ behavior: \"deny\", message: \"Cancelled by the user\", interrupt: true });\n }\n }, { once: true });\n });\n }\n\n private toPermissionDecision(a: RespondAnswer, input: Record): PermissionDecision {\n if (a.cancelled || a.optionId === \"deny\") {\n return { behavior: \"deny\", message: \"The user denied this action\", ...(a.cancelled ? { interrupt: true } : {}) };\n }\n return { behavior: \"allow\", updatedInput: input };\n }\n\n private async handlePlanMode(requestId: string, input: Record, signal: AbortSignal, toolUseID?: string): Promise {\n const planText = typeof input.plan === \"string\" ? input.plan : \"\";\n if (planText) {\n this.emit({ type: \"plan\", itemId: toolUseID ?? requestId, markdown: planText });\n }\n this.emit({\n type: \"permission_request\",\n requestId,\n title: tr(\"perm.plan\"),\n kind: \"plan\",\n detail: { plan: planText },\n options: [\n { id: \"implement\", label: tr(\"perm.implement\"), kind: \"allow_once\" },\n { id: \"reject\", label: tr(\"perm.deny\"), kind: \"reject_once\" },\n ],\n });\n const answer = await new Promise((resolve) => {\n this.pending.set(requestId, { kind: \"permission\", resolve: (a) => resolve(a as RespondAnswer) });\n signal.addEventListener(\"abort\", () => {\n if (this.pending.delete(requestId)) {\n this.emit({ type: \"permission_resolved\", requestId, cancelled: true });\n resolve({ cancelled: true });\n }\n }, { once: true });\n });\n if (answer.cancelled || answer.optionId === \"reject\") {\n return { behavior: \"deny\", message: \"The user rejected the plan; revise it based on their feedback\", ...(answer.cancelled ? { interrupt: true } : {}) };\n }\n // implement: switch back to default mode\n try {\n await this.cli?.setPermissionMode(\"default\");\n this.o.mode = \"default\";\n this.o.onModeChange?.(\"default\");\n } catch (e) {\n log(\"warn\", \"setPermissionMode(default) 失败\", { err: String(e) });\n }\n return { behavior: \"allow\", updatedInput: input };\n }\n\n private async handleQuestion(requestId: string, input: Record, signal: AbortSignal): Promise {\n this.emit({ type: \"question\", requestId, questions: input.questions as unknown[] });\n const answer = await new Promise((resolve) => {\n this.pending.set(requestId, { kind: \"question\", resolve: (a) => resolve(a as RespondAnswer) });\n signal.addEventListener(\"abort\", () => {\n if (this.pending.delete(requestId)) {\n this.emit({ type: \"permission_resolved\", requestId, cancelled: true });\n resolve({ cancelled: true });\n }\n }, { once: true });\n });\n if (answer.cancelled) {\n return { behavior: \"deny\", message: \"The user cancelled the question\", interrupt: true };\n }\n // answers are keyed by the question text (Claude's AskUserQuestion schema keys answers by question text)\n const questions = (input.questions as { question?: string; header?: string }[]) ?? [];\n const normalized: Record = {};\n for (const ques of questions) {\n const text = ques.question;\n if (!text) continue;\n const v = answer.answers?.[text] ?? (ques.header ? answer.answers?.[ques.header] : undefined);\n if (v) normalized[text] = v;\n }\n return { behavior: \"allow\", updatedInput: { ...input, answers: normalized } };\n }\n\n respond(requestId: string, answer: RespondAnswer): void {\n const p = this.pending.get(requestId);\n if (p) {\n this.pending.delete(requestId);\n p.resolve(answer);\n }\n }\n\n async interrupt(): Promise {\n this.st.sawInterrupt = true;\n // Cancel every pending permission/question\n for (const [id, p] of this.pending) {\n this.emit({ type: \"permission_resolved\", requestId: id, cancelled: true });\n p.resolve({ cancelled: true });\n }\n this.pending.clear();\n const cli = this.cli;\n if (!cli || !cli.alive) return;\n try {\n await cli.interrupt();\n } catch (e) {\n // No answer: stop this CLI; the next send starts it again with --resume\n log(\"warn\", \"claude interrupt failed\", { err: String(e) });\n this.stopping.add(cli);\n this.needsRestart = true;\n void cli.close(500);\n if (this.turnId) this.emit({ type: \"turn_ended\", turnId: this.turnId, status: \"interrupted\" });\n }\n }\n\n async setModel(model: string | null): Promise {\n this.o.model = model;\n if (!this.cli?.alive) return;\n try {\n await this.cli.setModel(model);\n } catch (e) {\n log(\"warn\", \"claude set_model failed\", { err: String(e) });\n this.needsRestart = true;\n }\n }\n\n async setMode(mode: Mode): Promise {\n this.o.mode = mode;\n if (!this.cli?.alive) return;\n // bypassPermissions is only accepted by a CLI started with it allowed: restart into it (--resume keeps the context)\n if (mode === \"bypassPermissions\" && this.launchedMode !== \"bypassPermissions\") {\n this.needsRestart = true;\n return;\n }\n try {\n await this.cli.setPermissionMode(mode);\n } catch (e) {\n log(\"warn\", \"claude set_permission_mode failed\", { err: String(e) });\n this.needsRestart = true;\n }\n }\n\n async setEffort(effort: string | null): Promise {\n this.o.effort = effort;\n // --effort is a launch flag → restart (continued via --resume)\n this.needsRestart = true;\n }\n\n async listCommands(): Promise {\n try {\n const init = await this.ensureCli().initialized;\n const commands = Array.isArray(init?.commands) ? (init!.commands as { name?: string; description?: string; argumentHint?: string }[]) : [];\n const map = new Map();\n for (const cmd of commands) {\n if (cmd?.name && !map.has(cmd.name)) {\n map.set(cmd.name, {\n name: cmd.name,\n description: cmd.description ?? \"\",\n argumentHint: cmd.argumentHint,\n kind: classifyClaudeSlashCommand(cmd.name),\n });\n }\n }\n return sortSlashCommands([...map.values()]);\n } catch {\n return [];\n }\n }\n\n async close(): Promise {\n this.closed = true;\n for (const [, p] of this.pending) p.resolve({ cancelled: true });\n this.pending.clear();\n const cli = this.cli;\n if (cli) {\n this.stopping.add(cli);\n await cli.close().catch(() => {});\n }\n if (this.pumpDone) {\n await Promise.race([this.pumpDone.catch(() => {}), new Promise((r) => setTimeout(r, 3000))]);\n }\n this.q.close();\n }\n}\n","// Model list (§7.2.7): Claude Code has no model query API.\n// Behind the magpie gateway, gateway models, the default model and thinking levels are filled in by providers/magpieGateway.ts;\n// without magpie only \"Default\" is offered (the frontend always shows it; no empty-id placeholder is added here anymore).\nimport type { ModelInfo } from \"../types.js\";\n\nexport async function listClaudeModels(): Promise {\n return [];\n}\n","// History import (§7.6): Claude sessions live in ~/.claude/projects//.jsonl.\n// Don't guess the encoding rule: list every directory, read the first record with a cwd from each jsonl, match the project with samePath.\n// Read-only throughout.\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { samePath } from \"../util/paths.js\";\nimport { tr } from \"../util/i18n.js\";\n\nconst CLAUDE_ROOT = join(homedir(), \".claude\", \"projects\");\n\ntype Rec = Record;\nconst rec = (v: unknown): Rec => (v && typeof v === \"object\" ? (v as Rec) : {});\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n\n// One jsonl line → {cwd?, title?, isUserText}\nfunction parseLine(line: string): { cwd?: string; userText?: string } | null {\n let r: Rec;\n try {\n r = rec(JSON.parse(line));\n } catch {\n return null;\n }\n const cwd = str(r.cwd);\n let userText: string | undefined;\n if (r.type === \"user\") {\n const content = rec(r.message).content;\n if (typeof content === \"string\") userText = content;\n else if (Array.isArray(content)) {\n const t = content.map((p) => (rec(p).type === \"text\" ? str(rec(p).text) : undefined)).find(Boolean);\n userText = t;\n }\n }\n return { cwd, userText };\n}\n\nasync function* linesOf(path: string): AsyncGenerator {\n const text = await readFile(path, \"utf8\").catch(() => \"\");\n for (const line of text.split(\"\\n\")) {\n if (line.trim()) yield line;\n }\n}\n\n// Project cwd → that project's past sessions\nexport async function listClaudeHistory(cwd: string): Promise<{ sessionId: string; title: string; updatedAt: number; messageCount: number }[]> {\n const out: { sessionId: string; title: string; updatedAt: number; messageCount: number }[] = [];\n const dirs = await readdir(CLAUDE_ROOT).catch(() => [] as string[]);\n for (const d of dirs) {\n const dirPath = join(CLAUDE_ROOT, d);\n const files = (await readdir(dirPath).catch(() => [] as string[])).filter((f) => f.endsWith(\".jsonl\"));\n for (const f of files) {\n const path = join(dirPath, f);\n let match = false;\n let title = \"\";\n let count = 0;\n for await (const line of linesOf(path)) {\n const p = parseLine(line);\n if (!p) continue;\n if (!match) {\n if (!p.cwd) continue;\n match = samePath(p.cwd, cwd);\n if (!match) break;\n }\n if (p.userText && !title) title = p.userText.slice(0, 40);\n if (p.userText) count++;\n }\n if (!match) continue;\n const s = await stat(path).catch(() => null);\n out.push({\n sessionId: f.replace(/\\.jsonl$/, \"\"),\n title: title || tr(\"history.untitled\"),\n updatedAt: s ? Math.round(s.mtimeMs) : 0,\n messageCount: count,\n });\n }\n }\n out.sort((a, b) => b.updatedAt - a.updatedAt);\n return out;\n}\n\n// Read one session's jsonl → SDK message shape (so mapSdkMessage can be reused)\nexport async function readClaudeHistory(sessionId: string, cwd: string): Promise {\n const dirs = await readdir(CLAUDE_ROOT).catch(() => [] as string[]);\n for (const d of dirs) {\n const path = join(CLAUDE_ROOT, d, `${sessionId}.jsonl`);\n if (!existsSync(path)) continue;\n // Confirm it belongs to this project (the first cwd record matches)\n const msgs: Rec[] = [];\n let matched = false;\n for await (const line of linesOf(path)) {\n const p = parseLine(line);\n if (!matched) {\n if (p?.cwd && samePath(p.cwd, cwd)) matched = true;\n else continue;\n }\n let r: Rec;\n try {\n r = rec(JSON.parse(line));\n } catch {\n continue;\n }\n // Keep only user/assistant/result — same shape as the SDK's streamed messages, so mapSdkMessage can digest them\n if (r.type === \"user\" || r.type === \"assistant\") msgs.push(r);\n }\n return msgs;\n }\n return [];\n}\n","// Claude Provider (§7.2): detection + createSession(ClaudeSession).\nimport type { Provider, ProviderSession, DetectResult, ModelInfo, HistoryItem, LaunchCommand } from \"../types.js\";\nimport { resolveBin, killTree, spawnBin, type ResolveResult } from \"../../util/bin.js\";\nimport { ClaudeSession } from \"./session.js\";\nimport { listClaudeModels } from \"./models.js\";\nimport { listClaudeHistory, readClaudeHistory } from \"../../history/import.js\";\nimport { mapSdkMessage, newMapState } from \"./map.js\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { tr } from \"../../util/i18n.js\";\nimport { resolveLaunch } from \"../launch.js\";\n\nconst INSTALL_HINT = \"npm i -g @anthropic-ai/claude-code\";\n\nexport const claudeCapabilities = {\n resume: true,\n interrupt: true,\n steer: false, // Claude doesn't support real steering — the manager queues instead (§7.2.2)\n images: true,\n plan: true,\n questions: true,\n cost: true,\n effort: [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n modes: [\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\"] as (\"plan\" | \"default\" | \"acceptEdits\" | \"bypassPermissions\")[],\n};\n\nfunction runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 5000): Promise {\n return new Promise((resolvePromise, reject) => {\n let out = \"\";\n const p = spawnBin(r, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"], env: { ...process.env, NO_COLOR: \"1\", FORCE_COLOR: \"0\" } });\n const t = setTimeout(() => {\n try {\n void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes\n } catch {}\n reject(new Error(\"timeout\"));\n }, timeoutMs);\n p.stdout?.on(\"data\", (c: Buffer) => (out += c.toString()));\n p.stderr?.on(\"data\", (c: Buffer) => (out += c.toString()));\n p.on(\"error\", reject);\n p.on(\"close\", (code) => {\n clearTimeout(t);\n if (code === 0) resolvePromise(out);\n else reject(new Error(\"exit \" + code));\n });\n });\n}\n\nexport function createClaudeProvider(opts: { resolve?: (name: string) => Promise } = {}): Provider {\n const resolve = opts.resolve ?? resolveBin;\n const resolveCustom = opts.resolve ? (l: LaunchCommand) => opts.resolve!(l.cmd) : resolveLaunch;\n return {\n id: \"claude\",\n name: \"Claude Code\",\n capabilities: claudeCapabilities,\n async detect(launch?: LaunchCommand): Promise {\n const bin = launch ? await resolveCustom(launch) : await resolve(\"claude\");\n if (!bin.ok) return { available: false, reason: bin.reason, installHint: INSTALL_HINT };\n try {\n const version = await runVersion(bin, [...(launch?.prefixArgs ?? []), \"--version\"]);\n return { available: true, bin: bin.display, version: version.trim().split(\"\\n\")[0] || \"\" };\n } catch {\n return { available: true, bin: bin.display, version: \"\" };\n }\n },\n async listModels(): Promise {\n return listClaudeModels();\n },\n async createSession(o): Promise {\n const bin = o.launch ? await resolveCustom(o.launch) : await resolve(\"claude\");\n if (!bin.ok) throw new Error(tr(\"claude.notFound\", { detail: bin.reason, hint: INSTALL_HINT }));\n return new ClaudeSession({\n threadId: o.threadId,\n cwd: o.cwd,\n model: o.model,\n mode: o.mode,\n effort: o.effort,\n resumeId: o.resumeId,\n bin,\n launch: o.launch,\n });\n },\n // §7.6: jsonl sessions under ~/.claude/projects matched by cwd\n async listHistory(cwd: string): Promise {\n const items = await listClaudeHistory(cwd);\n return items.map((i) => ({ provider: \"claude\", ...i, imported: false }));\n },\n async readHistory(sessionId: string, cwd: string): Promise {\n const msgs = await readClaudeHistory(sessionId, cwd);\n const st = newMapState();\n const out: ProviderEvent[] = [];\n for (const m of msgs) {\n const r = m as { type?: string; message?: { content?: unknown } };\n // User text messages don't appear as events in claude's stream-json output (the manager writes user_message itself); emit them here\n if (r.type === \"user\") {\n const content = r.message?.content;\n const text = typeof content === \"string\"\n ? content\n : Array.isArray(content)\n ? (content as { type?: string; text?: string }[]).filter((b) => b.type === \"text\").map((b) => b.text ?? \"\").join(\"\")\n : \"\";\n if (text.trim()) out.push({ type: \"user_message\", text });\n else out.push(...mapSdkMessage(m as never, st, cwd)); // tool_result and the like still go through the mapping\n continue;\n }\n out.push(...mapSdkMessage(m as never, st, cwd));\n }\n // Finish: an imported session is closed\n out.push({ type: \"turn_ended\", turnId: \"\", status: \"completed\" });\n return out;\n },\n };\n}\n","// Codex history import (§7.6): ~/.codex/sessions/**/rollout-*.jsonl\n// Layout: session_meta (with cwd) → event_msg → response_item (message/function_call/...)\n// Import only user messages (minus environment_context and similar wrappers) + the assistant's final reply text; tool steps become notices. Read-only throughout.\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { samePath } from \"../util/paths.js\";\nimport { tr } from \"../util/i18n.js\";\n\nconst CODEX_ROOT = join(homedir(), \".codex\", \"sessions\");\n\ntype Rec = Record;\nconst rec = (v: unknown): Rec => (v && typeof v === \"object\" ? (v as Rec) : {});\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n\n// Environment wrappers in user messages: anything whose first line starts with or isn't user input\nconst WRAPPERS = /^\\s*<(environment_context|user_instructions|skills_instructions|permissions instructions)>/i;\n\nfunction textOf(content: unknown, kind: string): string {\n if (!Array.isArray(content)) return \"\";\n return (content as Rec[])\n .filter((p) => p.type === kind || p.type === \"input_text\" || p.type === \"output_text\")\n .map((p) => str(p.text) ?? \"\")\n .join(\"\\n\")\n .trim();\n}\n\n// Find rollout-*.jsonl recursively\nasync function* walk(dir: string, depth = 0): AsyncGenerator {\n if (depth > 6) return;\n for (const name of await readdir(dir).catch(() => [] as string[])) {\n const p = join(dir, name);\n const s = await stat(p).catch(() => null);\n if (!s) continue;\n if (s.isDirectory()) yield* walk(p, depth + 1);\n else if (/^rollout-.*\\.jsonl$/.test(name)) yield p;\n }\n}\n\nexport type CodexHistItem = { sessionId: string; title: string; updatedAt: number; messageCount: number };\n\nexport async function listCodexHistory(cwd: string): Promise {\n const out: CodexHistItem[] = [];\n for await (const path of walk(CODEX_ROOT)) {\n const m = /rollout-.*-([0-9a-f-]{36})\\.jsonl$/i.exec(path);\n const sessionId = m?.[1];\n if (!sessionId) continue;\n const text = await readFile(path, \"utf8\").catch(() => \"\");\n let match = false;\n let title = \"\";\n let count = 0;\n for (const line of text.split(\"\\n\")) {\n if (!line.trim()) continue;\n let r: Rec;\n try {\n r = rec(JSON.parse(line));\n } catch {\n continue;\n }\n // session_meta records payload.cwd\n if (r.type === \"session_meta\") {\n const cwdInFile = str(rec(r.payload).cwd);\n if (cwdInFile && samePath(cwdInFile, cwd)) match = true;\n else break; // Not this project: stop reading\n continue;\n }\n if (!match) continue;\n if (r.type === \"response_item\") {\n const p = rec(r.payload);\n if (p.type === \"message\" && p.role === \"user\") {\n const t = textOf(p.content, \"input_text\");\n if (t && !WRAPPERS.test(t)) {\n count++;\n if (!title) title = t.slice(0, 40);\n }\n }\n }\n }\n if (!match) continue;\n const s = await stat(path).catch(() => null);\n out.push({ sessionId, title: title || tr(\"history.untitled\"), updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count });\n }\n out.sort((a, b) => b.updatedAt - a.updatedAt);\n return out;\n}\n\n// Read one rollout → simplified events (user_message / assistant_message / notice for tool steps / turn_ended)\ntype CodexEv = {\n type: string; text?: string; message?: string; itemId?: string; level?: string;\n turnId?: string; status?: string;\n};\nexport async function readCodexHistory(sessionId: string, cwd: string): Promise {\n const out: CodexEv[] = [];\n let file: string | null = null;\n for await (const p of walk(CODEX_ROOT)) {\n if (p.endsWith(`${sessionId}.jsonl`)) { file = p; break; }\n }\n if (!file) return out;\n const text = await readFile(file, \"utf8\").catch(() => \"\");\n let matched = false;\n let aid = 0;\n // response_item.message and event_msg.item_completed duplicate each other → dedupe by text\n const seenText = new Set();\n const pushText = (type: \"user_message\" | \"assistant_message\", t: string) => {\n const key = type + \":\" + t;\n if (!t || seenText.has(key)) return;\n seenText.add(key);\n out.push(type === \"user_message\" ? { type, text: t } : { type, itemId: `imp_a${aid++}`, text: t });\n };\n for (const line of text.split(\"\\n\")) {\n if (!line.trim()) continue;\n let r: Rec;\n try {\n r = rec(JSON.parse(line));\n } catch {\n continue;\n }\n if (r.type === \"session_meta\") {\n const c = str(rec(r.payload).cwd);\n if (c && samePath(c, cwd)) matched = true;\n continue;\n }\n if (!matched) continue;\n // response_item message\n if (r.type === \"response_item\") {\n const p = rec(r.payload);\n if (p.type === \"message\") {\n const role = str(p.role);\n const phase = str(p.phase);\n if (role === \"user\") {\n const t = textOf(p.content, \"input_text\");\n if (t && !WRAPPERS.test(t)) pushText(\"user_message\", t);\n } else if (role === \"assistant\" && phase !== \"commentary\") {\n const t = textOf(p.content, \"output_text\");\n if (t) pushText(\"assistant_message\", t);\n }\n } else if (p.type === \"function_call\" || p.type === \"custom_tool_call\") {\n const name = str(p.name) ?? \"tool\";\n out.push({ type: \"notice\", level: \"info\", message: tr(\"history.toolCall\", { name }) });\n }\n continue;\n }\n // event_msg.item_completed: AgentMessage (Text content blocks) and task_complete.last_agent_message\n if (r.type === \"event_msg\") {\n const p = rec(r.payload);\n if (p.type === \"item_completed\") {\n const it = rec(p.item);\n if (it.type === \"AgentMessage\" && it.phase !== \"commentary\") {\n const t = textOf(it.content, \"Text\");\n if (t) pushText(\"assistant_message\", t);\n } else if (it.type === \"UserMessage\") {\n const t = textOf(it.content, \"text\");\n if (t && !WRAPPERS.test(t)) pushText(\"user_message\", t);\n }\n } else if (p.type === \"task_complete\") {\n const last = str(p.last_agent_message);\n if (last) pushText(\"assistant_message\", last);\n }\n continue;\n }\n const p2 = rec(r.payload);\n if (p2.type === \"function_call\" || p2.type === \"custom_tool_call\") {\n // Tool steps collapse into a one-line notice (§7.6, Codex part)\n const name = str(p2.name) ?? \"tool\";\n out.push({ type: \"notice\", level: \"info\", message: tr(\"history.toolCall\", { name }) });\n }\n }\n out.push({ type: \"turn_ended\", turnId: \"import\", status: \"completed\" });\n return out;\n}\n","// JSON-RPC over stdio client for `codex app-server` (§7.3.2).\n// stdout is parsed line by line: {id,result|error} → response; {id,method} → server request; {method} → notification.\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { log } from \"../../log.js\";\nimport { killTree, trackTree, type Argv } from \"../../util/bin.js\";\n\nexport class CodexRpcError extends Error {\n code?: number;\n constructor(message: string, code?: number) {\n super(message);\n this.code = code;\n }\n}\n\nexport class CodexProcessExitedError extends CodexRpcError {\n constructor() {\n super(\"Codex 进程已退出\");\n }\n}\n\ntype ServerRequestHandler = (method: string, params: Record) => Promise;\ntype NotificationHandler = (method: string, params: Record) => void;\n\nexport class CodexRpc {\n private proc: ChildProcess;\n private nextId = 1;\n private pending = new Map void; reject: (e: Error) => void }>();\n private buf = \"\";\n private exited = false;\n onServerRequest?: ServerRequestHandler;\n onNotification?: NotificationHandler;\n onExit?: (code: number | null) => void;\n\n constructor(\n argv: Argv,\n opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {},\n ) {\n this.proc = spawn(argv.cmd, argv.args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n ...(argv.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),\n // Non-Windows: its own process group, so after a close() timeout killTree also ends the commands codex started\n ...(process.platform !== \"win32\" ? { detached: true } : {}),\n });\n trackTree(this.proc);\n this.proc.stdout!.setEncoding(\"utf8\");\n this.proc.stdout!.on(\"data\", (chunk: string) => this.onData(chunk));\n this.proc.stderr!.setEncoding(\"utf8\");\n this.proc.stderr!.on(\"data\", (chunk: string) => {\n this.stderrTail = (this.stderrTail + chunk).slice(-4096);\n });\n this.proc.on(\"error\", () => this.failAll());\n this.proc.on(\"close\", (code) => {\n this.exited = true;\n this.failAll();\n this.onExit?.(code);\n });\n }\n\n private stderrTail = \"\";\n\n get stderr(): string {\n return this.stderrTail;\n }\n\n get isExited(): boolean {\n return this.exited;\n }\n\n private onData(chunk: string): void {\n this.buf += chunk;\n let i: number;\n while ((i = this.buf.indexOf(\"\\n\")) >= 0) {\n const line = this.buf.slice(0, i).trim();\n this.buf = this.buf.slice(i + 1);\n if (!line) continue;\n let msg: Record;\n try {\n msg = JSON.parse(line);\n } catch {\n log(\"warn\", \"codex rpc: 非 JSON 行\", { line: line.slice(0, 200) });\n continue;\n }\n void this.dispatch(msg);\n }\n }\n\n private async dispatch(msg: Record): Promise {\n const hasId = msg.id !== undefined && msg.id !== null;\n if (hasId && (\"result\" in msg || \"error\" in msg)) {\n const id = Number(msg.id);\n const p = this.pending.get(id);\n if (p) {\n this.pending.delete(id);\n if (msg.error) {\n const e = msg.error as { code?: number; message?: string };\n p.reject(new CodexRpcError(e.message ?? \"RPC error\", e.code));\n } else {\n p.resolve(msg.result);\n }\n }\n return;\n }\n if (hasId && msg.method) {\n // Server request → needs a response\n const id = Number(msg.id);\n try {\n const result = this.onServerRequest\n ? await this.onServerRequest(String(msg.method), (msg.params as Record) ?? {})\n : undefined;\n this.send({ id, result: result ?? null });\n } catch (e) {\n this.send({ id, error: { code: -32603, message: String((e as Error)?.message ?? e) } });\n }\n return;\n }\n if (!hasId && msg.method) {\n try {\n this.onNotification?.(String(msg.method), (msg.params as Record) ?? {});\n } catch (e) {\n log(\"warn\", \"codex rpc: 通知处理失败\", { method: msg.method, err: String(e) });\n }\n }\n }\n\n private send(obj: Record): void {\n if (this.exited) return;\n try {\n this.proc.stdin!.write(JSON.stringify(obj) + \"\\n\");\n } catch {}\n }\n\n request(method: string, params?: Record, timeoutMs = 60000): Promise {\n if (this.exited) return Promise.reject(new CodexProcessExitedError());\n const id = this.nextId++;\n return new Promise((resolvePromise, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(new CodexRpcError(`请求超时:${method}`));\n }, timeoutMs);\n this.pending.set(id, {\n resolve: (v) => {\n clearTimeout(timer);\n resolvePromise(v as T);\n },\n reject: (e) => {\n clearTimeout(timer);\n reject(e);\n },\n });\n this.send({ jsonrpc: \"2.0\", id, method, params: params ?? {} });\n });\n }\n\n notify(method: string, params?: Record): void {\n this.send({ jsonrpc: \"2.0\", method, params: params ?? {} });\n }\n\n private failAll(): void {\n const err = new CodexProcessExitedError();\n for (const [, p] of this.pending) p.reject(err);\n this.pending.clear();\n }\n\n async close(): Promise {\n try {\n this.proc.stdin?.end();\n } catch {}\n await new Promise((resolvePromise) => {\n const t = setTimeout(() => {\n void killTree(this.proc, { graceMs: 1500 });\n resolvePromise();\n }, 3000);\n this.proc.on(\"close\", () => {\n clearTimeout(t);\n resolvePromise();\n });\n if (this.exited) {\n clearTimeout(t);\n resolvePromise();\n }\n });\n }\n}\n","// One user message → Codex app-server UserInput items.\n// Only PNG / JPEG / GIF / WebP go as localImage; every other attachment (text files included) is named by its\n// absolute path in the text, which Codex opens with its own tools. Files that aren't images or text get a warning.\nimport { basename } from \"node:path\";\nimport { resolveImagePath } from \"../../util/attachmentRefs.js\";\nimport { attachmentKind, baseMime, pathNote } from \"../../util/attachmentKinds.js\";\n\nexport async function buildCodexInput(\n text: string,\n attachments: { path: string; mime: string }[],\n): Promise<{ items: Record[]; warnings: string[] }> {\n const images: Record[] = [];\n const notes: string[] = [];\n const warnings: string[] = [];\n for (const a of attachments) {\n let file: string;\n try {\n file = await resolveImagePath(a.path);\n } catch (e) {\n warnings.push(`${a.path}: ${String((e as Error)?.message ?? e)}`);\n continue;\n }\n const kind = attachmentKind(a.mime);\n if (kind === \"image\") {\n images.push({ type: \"localImage\", path: file });\n continue;\n }\n notes.push(pathNote(kind, file));\n if (kind === \"other\") warnings.push(`${basename(file)} (${baseMime(a.mime) || \"unknown type\"}) is not an image or a text file; sent its path`);\n }\n const fullText = [text, ...(notes.length ? [notes.join(\"\\n\")] : [])].filter(Boolean).join(\"\\n\\n\");\n return { items: [{ type: \"text\", text: fullText }, ...images], warnings };\n}\n","// Codex app-server notifications → ProviderEvent (§7.3.4). Method and field names follow the generated schema.\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { tr } from \"../../util/i18n.js\";\n\nconst MAX_OUTPUT = 20 * 1024;\nconst trunc = (s: string, n = 80): string => (s.length > n ? s.slice(0, n - 1) + \"…\" : s);\n\ntype Rec = Record;\nconst rec = (v: unknown): Rec => (v && typeof v === \"object\" ? (v as Rec) : {});\nconst str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n\nexport type CodexMapState = {\n currentTurnId: string | null;\n filesChanged: number;\n diffText: string;\n fileChangesByItemId: Map;\n /** Raw reasoning text streamed per item (DeepSeek and others send no summary): saved when the item completes (B15) */\n reasoningRaw: Map;\n};\n\nexport function newCodexMapState(): CodexMapState {\n return { currentTurnId: null, filesChanged: 0, diffText: \"\", fileChangesByItemId: new Map(), reasoningRaw: new Map() };\n}\n\n// One server notification → 0..n unified events. Server requests (approvals) don't go through here.\nexport function mapNotification(method: string, params: Rec, st: CodexMapState): ProviderEvent[] {\n const out: ProviderEvent[] = [];\n const turnId = str(params.turnId);\n\n switch (method) {\n case \"turn/started\": {\n const turn = rec(params.turn);\n const tid = str(turn.id);\n if (tid) st.currentTurnId = tid;\n st.filesChanged = 0;\n st.diffText = \"\";\n st.fileChangesByItemId.clear();\n st.reasoningRaw.clear();\n break;\n }\n case \"item/agentMessage/delta\": {\n const itemId = str(params.itemId) ?? \"\";\n const delta = str(params.delta) ?? \"\";\n if (itemId && delta) out.push({ type: \"assistant_delta\", itemId, text: delta });\n break;\n }\n case \"item/plan/delta\": {\n // Incremental plan stream: wait for the plan item in item/completed to send the full plan\n break;\n }\n case \"item/reasoning/summaryTextDelta\":\n case \"item/reasoning/textDelta\": {\n const itemId = str(params.itemId) ?? \"\";\n const delta = str(params.delta) ?? \"\";\n if (itemId && delta) {\n if (method === \"item/reasoning/textDelta\") st.reasoningRaw.set(itemId, (st.reasoningRaw.get(itemId) ?? \"\") + delta);\n out.push({ type: \"reasoning_delta\", itemId, text: delta });\n }\n break;\n }\n case \"item/commandExecution/outputDelta\":\n case \"item/fileChange/outputDelta\":\n case \"command/exec/outputDelta\": {\n const itemId = str(params.itemId) ?? \"\";\n const delta = str(params.delta) ?? \"\";\n if (itemId && delta) out.push({ type: \"tool_output_delta\", itemId, text: delta });\n break;\n }\n case \"item/started\": {\n const item = rec(params.item);\n const type = str(item.type) ?? \"\";\n const itemId = str(item.id) ?? \"\";\n if (type === \"commandExecution\") {\n const cmd = str(item.command) ?? \"\";\n out.push({\n type: \"tool_call\", itemId, kind: \"bash\",\n title: tr(\"tool.run\", { x: trunc(cmd) }), status: \"running\",\n detail: { command: cmd, cwd: str(item.cwd) },\n });\n } else if (type === \"fileChange\") {\n const changes = Array.isArray(item.changes) ? item.changes : [];\n if (itemId) st.fileChangesByItemId.set(itemId, changes);\n out.push({\n type: \"tool_call\", itemId, kind: \"edit\",\n title: tr(\"tool.editFiles\", { n: changes.length }), status: \"running\",\n detail: { changes },\n });\n } else if (type === \"mcpToolCall\" || type === \"dynamicToolCall\") {\n const tool = str(item.tool) ?? str(item.name) ?? \"\";\n const server = str(item.server) ?? \"\";\n out.push({\n type: \"tool_call\", itemId, kind: \"mcp\",\n title: `${server || \"mcp\"} · ${tool}`, status: \"running\",\n });\n } else if (type === \"webSearch\") {\n out.push({\n type: \"tool_call\", itemId, kind: \"web\",\n title: tr(\"tool.webSearch\", { x: trunc(str(item.query) ?? \"\", 40) }), status: \"running\",\n });\n }\n // agentMessage/reasoning/userMessage/plan etc.: wait for a delta or completed\n break;\n }\n case \"item/completed\": {\n const item = rec(params.item);\n const type = str(item.type) ?? \"\";\n const itemId = str(item.id) ?? \"\";\n if (type === \"agentMessage\") {\n const text = str(item.text) ?? \"\";\n if (text) out.push({ type: \"assistant_message\", itemId, text });\n } else if (type === \"reasoning\") {\n const summary = Array.isArray(item.summary) ? item.summary : [];\n const content = Array.isArray(item.content) ? item.content : [];\n const strings = (a: unknown[]) => a.filter((s): s is string => typeof s === \"string\").join(\"\\n\");\n // The summary when there is one, else the raw reasoning (on the item, or as streamed)\n const text = strings(summary) || strings(content) || st.reasoningRaw.get(itemId) || \"\";\n st.reasoningRaw.delete(itemId);\n if (text) out.push({ type: \"reasoning\", itemId, text });\n } else if (type === \"commandExecution\") {\n const cmd = str(item.command) ?? \"\";\n const exitCode = typeof item.exitCode === \"number\" ? item.exitCode : undefined;\n const output = str(item.aggregatedOutput) ?? \"\";\n out.push({\n type: \"tool_call\", itemId, kind: \"bash\",\n title: tr(\"tool.run\", { x: trunc(cmd) }),\n status: exitCode === 0 ? \"ok\" : \"failed\",\n output: output.length > MAX_OUTPUT ? output.slice(0, MAX_OUTPUT) : output,\n exitCode,\n durationMs: typeof item.durationMs === \"number\" ? item.durationMs : undefined,\n });\n } else if (type === \"fileChange\") {\n const changes = Array.isArray(item.changes) ? item.changes : [];\n if (itemId) st.fileChangesByItemId.set(itemId, changes);\n const istatus = str(item.status);\n st.filesChanged += changes.length;\n out.push({\n type: \"tool_call\", itemId, kind: \"edit\",\n title: tr(\"tool.editFiles\", { n: changes.length }),\n status: istatus === \"failed\" ? \"failed\" : \"ok\",\n detail: { changes },\n });\n } else if (type === \"mcpToolCall\" || type === \"dynamicToolCall\") {\n const tool = str(item.tool) ?? str(item.name) ?? \"\";\n const server = str(item.server) ?? \"\";\n const istatus = str(item.status);\n const err = str(item.error);\n out.push({\n type: \"tool_call\", itemId, kind: \"mcp\",\n title: `${server || \"mcp\"} · ${tool}`,\n status: istatus === \"failed\" || err ? \"failed\" : \"ok\",\n output: err ?? undefined,\n });\n } else if (type === \"webSearch\") {\n out.push({\n type: \"tool_call\", itemId, kind: \"web\",\n title: tr(\"tool.webSearch\", { x: trunc(str(item.query) ?? \"\", 40) }), status: \"ok\",\n });\n } else if (type === \"plan\") {\n const text = str(item.text) ?? \"\";\n if (text) out.push({ type: \"plan\", itemId, markdown: text });\n }\n break;\n }\n case \"turn/plan/updated\": {\n const steps = Array.isArray(params.plan) ? params.plan : [];\n const items = steps.map((s) => {\n const step = rec(s);\n const status = str(step.status) ?? \"pending\";\n return {\n text: str(step.step) ?? \"\",\n status: status === \"completed\" ? \"done\" : status === \"inProgress\" || status === \"in_progress\" ? \"in_progress\" : \"pending\",\n };\n });\n if (items.length) out.push({ type: \"todo\", items });\n break;\n }\n case \"turn/diff/updated\": {\n const diff = str(params.diff) ?? \"\";\n if (diff) st.diffText = diff;\n break;\n }\n case \"thread/tokenUsage/updated\": {\n const usage = rec(params.tokenUsage);\n const last = rec(usage.last) || usage;\n const input = typeof last.inputTokens === \"number\" ? last.inputTokens : 0;\n const output = typeof last.outputTokens === \"number\" ? last.outputTokens : 0;\n const cached = typeof last.cachedInputTokens === \"number\" ? last.cachedInputTokens : 0;\n out.push({\n type: \"usage\",\n inputTokens: input,\n outputTokens: output,\n cacheReadTokens: cached,\n costUsd: 0,\n });\n break;\n }\n case \"turn/completed\": {\n const turn = rec(params.turn);\n const status = str(turn.status) ?? \"completed\";\n const error = rec(turn.error);\n out.push({\n type: \"turn_ended\",\n turnId: str(turn.id) ?? turnId ?? st.currentTurnId ?? \"\",\n status: status === \"completed\" ? \"completed\" : status === \"interrupted\" ? \"interrupted\" : \"failed\",\n durationMs: typeof turn.durationMs === \"number\" ? turn.durationMs : undefined,\n error: str(error.message),\n filesChanged: st.filesChanged || undefined,\n });\n break;\n }\n case \"error\": {\n const msg = str(params.message) ?? tr(\"codex.error\");\n out.push({ type: \"notice\", level: \"error\", message: msg });\n break;\n }\n default:\n break;\n }\n return out;\n}\n","import { readdir, readFile, stat } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, join } from \"node:path\";\nimport type { SlashCommand } from \"../slash.js\";\nimport { parseSlashInput, sortSlashCommands } from \"../slash.js\";\n\nexport type CodexSlashEntry = SlashCommand & { body: string };\n\nfunction parseFrontMatter(raw: string): { meta: Record; body: string } {\n if (!raw.startsWith(\"---\\n\")) return { meta: {}, body: raw };\n const end = raw.indexOf(\"\\n---\\n\", 4);\n if (end === -1) return { meta: {}, body: raw };\n const fm = raw.slice(4, end);\n const meta: Record = {};\n for (const line of fm.split(/\\r?\\n/)) {\n const m = line.match(/^([a-zA-Z0-9_-]+):\\s*(.+)$/);\n if (m) meta[m[1]!] = m[2]!.trim().replace(/^[\"']|[\"']$/g, \"\");\n }\n return { meta, body: raw.slice(end + 5) };\n}\n\nfunction firstLine(body: string): string {\n for (const line of body.split(/\\r?\\n/)) {\n const t = line.trim();\n if (t && !t.startsWith(\"#\")) return t.replace(/^#+\\s*/, \"\").slice(0, 120);\n }\n return \"\";\n}\n\nasync function readPromptFiles(dir: string): Promise {\n const out: CodexSlashEntry[] = [];\n let names: string[] = [];\n try {\n names = await readdir(dir);\n } catch {\n return out;\n }\n for (const f of names) {\n if (!f.endsWith(\".md\")) continue;\n const path = join(dir, f);\n try {\n const st = await stat(path);\n if (!st.isFile()) continue;\n const raw = await readFile(path, \"utf8\");\n const { meta, body } = parseFrontMatter(raw);\n const name = basename(f, \".md\");\n out.push({\n name,\n description: meta.description || firstLine(body) || name,\n argumentHint: meta.argumentHint || meta[\"argument-hint\"],\n kind: \"command\",\n body,\n });\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\nasync function readSkillDirs(root: string): Promise {\n const out: CodexSlashEntry[] = [];\n let dirs: string[] = [];\n try {\n dirs = await readdir(root);\n } catch {\n return out;\n }\n for (const d of dirs) {\n const skillPath = join(root, d, \"SKILL.md\");\n try {\n const st = await stat(skillPath);\n if (!st.isFile()) continue;\n const raw = await readFile(skillPath, \"utf8\");\n const { meta, body } = parseFrontMatter(raw);\n const name = meta.name || d;\n out.push({\n name,\n description: meta.description || firstLine(body) || name,\n argumentHint: meta.argumentHint,\n kind: \"skill\",\n body,\n });\n } catch {\n /* skip */\n }\n }\n return out;\n}\n\nexport async function loadCodexSlashEntries(cwd: string, opts?: { skipHome?: boolean }): Promise {\n const home = homedir();\n const parts = await Promise.all([\n opts?.skipHome ? Promise.resolve([]) : readPromptFiles(join(home, \".codex\", \"prompts\")),\n readPromptFiles(join(cwd, \".codex\", \"prompts\")),\n opts?.skipHome ? Promise.resolve([]) : readSkillDirs(join(home, \".codex\", \"skills\")),\n readSkillDirs(join(cwd, \".codex\", \"skills\")),\n ]);\n const byName = new Map();\n for (const list of parts) {\n for (const e of list) {\n if (!byName.has(e.name)) byName.set(e.name, e);\n }\n }\n return sortSlashCommands([...byName.values()]) as CodexSlashEntry[];\n}\n\nexport function expandCodexSlash(text: string, entries: CodexSlashEntry[]): string {\n const parsed = parseSlashInput(text);\n if (!parsed) return text;\n const hit = entries.find((e) => e.name === parsed.name);\n if (!hit) return text;\n return hit.body.replace(/\\$ARGUMENTS/g, parsed.args);\n}\n\nexport function codexSlashCommandsFromEntries(entries: CodexSlashEntry[]): SlashCommand[] {\n return entries.map(({ body: _b, ...rest }) => rest);\n}\n","// Codex ProviderSession (§7.3.3/7.3.5): codex app-server JSON-RPC session.\nimport type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from \"../types.js\";\nimport { buildCodexInput } from \"./input.js\";\nimport { tr } from \"../../util/i18n.js\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { AsyncQueue } from \"../../util/queue.js\";\nimport { CodexRpc } from \"./rpc.js\";\nimport { argvFor } from \"../../util/bin.js\";\nimport { mapNotification, newCodexMapState, type CodexMapState } from \"./map.js\";\nimport {\n codexSlashCommandsFromEntries,\n expandCodexSlash,\n loadCodexSlashEntries,\n type CodexSlashEntry,\n} from \"./commands.js\";\nimport { log } from \"../../log.js\";\nimport { launchArgv } from \"../launch.js\";\n\nconst rid = () => Math.random().toString(36).slice(2, 10);\n\n// §7.3.3 permission presets (per the four modes). Note the two shapes differ:\n// `sandbox` in thread/start|resume is a kebab-case enum (\"read-only\"…);\n// `sandboxPolicy` in turn/start is an object ({type:\"readOnly\"}…).\nconst MODE_PRESETS: Record }> = {\n plan: { approvalPolicy: \"on-request\", sandbox: \"read-only\", sandboxPolicy: { type: \"readOnly\" } },\n default: { approvalPolicy: \"on-request\", sandbox: \"read-only\", sandboxPolicy: { type: \"readOnly\" } },\n acceptEdits: { approvalPolicy: \"on-request\", sandbox: \"workspace-write\", sandboxPolicy: { type: \"workspaceWrite\" } },\n bypassPermissions: { approvalPolicy: \"never\", sandbox: \"danger-full-access\", sandboxPolicy: { type: \"dangerFullAccess\" } },\n ask: { approvalPolicy: \"on-request\", sandbox: \"read-only\", sandboxPolicy: { type: \"readOnly\" } },\n};\n\ntype PendingReq = {\n kind: \"permission\" | \"question\";\n resolve: (a: RespondAnswer) => void;\n};\n\nexport class CodexSession implements ProviderSession {\n events: AsyncIterable;\n private q = new AsyncQueue();\n private rpc: CodexRpc | null = null;\n private st: CodexMapState = newCodexMapState();\n private sessionThreadId: string | null = null;\n private pending = new Map();\n private closed = false;\n private started: Promise | null = null;\n private interruptWanted = false;\n private ourTurnId: string | null = null; // The current turn's turnId in the timeline (generated on send)\n private staleCodexTurns = new Set();\n private codexSlash: CodexSlashEntry[] | null = null;\n\n constructor(\n private o: {\n threadId: string;\n cwd: string;\n model: string | null;\n mode: Mode;\n effort: string | null;\n resumeId: string | null;\n binCmd: string;\n binPrefixArgs: string[];\n binVia?: string;\n binShim?: string;\n version: string;\n launch?: LaunchCommand;\n },\n ) {\n this.events = this.q;\n }\n\n private emit(ev: ProviderEvent): void {\n if (ev.type === \"turn_ended\") {\n // A late completion for the previous turn (already ended by the interrupt fallback): drop it so it doesn't end the new turn\n if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) return;\n // turn_started uses our own turnId, so the end must use the same one,\n // otherwise the manager's per-turn dedupe breaks (interrupt fallback + late completion would end the next turn)\n if (this.ourTurnId) ev.turnId = this.ourTurnId;\n this.ourTurnId = null;\n this.st.currentTurnId = null;\n this.interruptWanted = false;\n }\n this.q.push(ev);\n }\n\n private async start(): Promise {\n if (this.started) return this.started;\n const attempt = (async () => {\n const rpc = new CodexRpc(\n argvFor(\n { ok: true, cmd: this.o.binCmd, prefixArgs: this.o.binPrefixArgs, display: this.o.binCmd, via: this.o.binVia ?? \"path\", shim: this.o.binShim },\n launchArgv([\"app-server\"], this.o.launch),\n ),\n { cwd: this.o.cwd },\n );\n this.rpc = rpc;\n rpc.onNotification = (m, p) => {\n for (const ev of mapNotification(m, p, this.st)) this.emit(ev);\n if (this.interruptWanted && this.st.currentTurnId) void this.interrupt();\n };\n rpc.onServerRequest = (m, p) => this.onServerRequest(m, p);\n rpc.onExit = () => {\n for (const [, p] of this.pending) p.resolve({ cancelled: true });\n this.pending.clear();\n if (!this.closed) this.q.close();\n };\n await rpc.request(\"initialize\", {\n clientInfo: { name: \"agent-console\", title: \"Agent Console\", version: this.o.version },\n capabilities: { experimentalApi: true },\n });\n rpc.notify(\"initialized\", {});\n const preset = MODE_PRESETS[this.o.mode];\n let threadId: string;\n if (this.o.resumeId) {\n const res = (await rpc.request(\"thread/resume\", {\n threadId: this.o.resumeId,\n cwd: this.o.cwd,\n model: this.o.model,\n approvalPolicy: preset.approvalPolicy,\n sandbox: preset.sandbox,\n })) as { thread?: { id?: string } };\n threadId = res.thread?.id ?? this.o.resumeId;\n } else {\n const res = (await rpc.request(\"thread/start\", {\n cwd: this.o.cwd,\n model: this.o.model,\n approvalPolicy: preset.approvalPolicy,\n sandbox: preset.sandbox,\n })) as { thread?: { id?: string } };\n threadId = res.thread?.id ?? \"\";\n }\n if (threadId) {\n this.sessionThreadId = threadId;\n this.emit({ type: \"provider_session_id\", id: threadId });\n }\n })();\n // Don't cache a failed start: clear it so the next send starts app-server again\n this.started = attempt.catch((e) => {\n if (this.started === guarded) {\n this.started = null;\n const rpc = this.rpc;\n this.rpc = null;\n if (rpc) {\n rpc.onExit = () => {};\n void Promise.resolve(rpc.close()).catch(() => {});\n }\n }\n throw e;\n });\n const guarded = this.started;\n return this.started;\n }\n\n async send(input: SendInput): Promise {\n if (this.closed) throw new Error(tr(\"codex.closed\"));\n await this.start();\n const rpc = this.rpc!;\n const preset = MODE_PRESETS[this.o.mode];\n const entries = this.codexSlash ?? (await loadCodexSlashEntries(this.o.cwd));\n this.codexSlash = entries;\n const wireText = expandCodexSlash(input.text, entries);\n const { items, warnings } = await buildCodexInput(wireText, input.images ?? []);\n this.interruptWanted = false;\n const turnId = \"u_\" + Date.now().toString(36) + \"_\" + rid();\n // A new turn started before the previous one completed (interrupt fallback) → remember its Codex turnId\n if (this.ourTurnId && this.st.currentTurnId) this.staleCodexTurns.add(this.st.currentTurnId);\n this.ourTurnId = turnId;\n this.st.currentTurnId = null; // Filled in by this turn's turn/started, so we never interrupt/steer with the previous turn's id\n this.emit({\n type: \"turn_started\",\n turnId,\n model: this.o.model,\n mode: this.o.mode,\n effort: this.o.effort,\n });\n for (const w of warnings) this.emit({ type: \"notice\", level: \"warn\", message: tr(\"notice.attachmentIssue\", { detail: w }) });\n try {\n await rpc.request(\"turn/start\", {\n threadId: this.sessionThreadId ?? undefined,\n input: items,\n model: this.o.model,\n effort: this.o.effort,\n approvalPolicy: preset.approvalPolicy,\n sandboxPolicy: preset.sandboxPolicy,\n });\n } catch (e) {\n this.emit({\n type: \"turn_ended\",\n turnId,\n status: \"failed\",\n error: String((e as Error)?.message ?? e),\n });\n }\n }\n\n async steer(input: SendInput): Promise {\n // No Codex turnId yet (turn/started hasn't arrived) → throw; the manager queues instead so the message isn't lost\n if (!this.rpc || !this.st.currentTurnId) throw new Error(tr(\"codex.noTurnSteer\"));\n const { items, warnings } = await buildCodexInput(input.text, input.images ?? []);\n for (const w of warnings) this.emit({ type: \"notice\", level: \"warn\", message: tr(\"notice.attachmentIssue\", { detail: w }) });\n try {\n await this.rpc.request(\"turn/steer\", {\n threadId: this.threadId(),\n expectedTurnId: this.st.currentTurnId,\n input: items,\n });\n } catch (e) {\n log(\"warn\", \"codex steer 失败\", { err: String(e) });\n }\n }\n\n async interrupt(): Promise {\n for (const [, p] of this.pending) p.resolve({ cancelled: true });\n this.pending.clear();\n if (!this.rpc) return;\n if (!this.st.currentTurnId) {\n // turn/started hasn't arrived yet: remember it and send the interrupt as soon as the turnId is known\n this.interruptWanted = true;\n return;\n }\n this.interruptWanted = false;\n try {\n await this.rpc.request(\n \"turn/interrupt\",\n { threadId: this.threadId(), turnId: this.st.currentTurnId },\n 5000,\n );\n } catch (e) {\n // \"Already idle\"-type errors count as success\n const msg = String((e as Error)?.message ?? e);\n if (!/idle|not running|no.*turn/i.test(msg)) {\n log(\"warn\", \"codex interrupt 失败\", { err: msg });\n }\n }\n }\n\n private threadId(): string | undefined {\n return this.sessionThreadId ?? undefined;\n }\n\n // ---- server requests (§7.3.5 approvals) ----\n private async onServerRequest(method: string, params: Record): Promise {\n switch (method) {\n case \"item/commandExecution/requestApproval\": {\n const command = String(params.command ?? \"\");\n const requestId = \"perm_\" + rid();\n this.emit({\n type: \"permission_request\",\n requestId,\n title: tr(\"tool.run\", { x: command.slice(0, 80) }),\n kind: \"tool\",\n detail: { command, cwd: params.cwd, reason: params.reason, approvalId: params.approvalId, itemId: params.itemId },\n options: [\n { id: \"accept\", label: tr(\"perm.allow\"), kind: \"allow_once\" },\n { id: \"acceptForSession\", label: tr(\"perm.allowSession\"), kind: \"allow_always\" },\n { id: \"decline\", label: tr(\"perm.deny\"), kind: \"reject_once\" },\n ],\n });\n const a = await this.waitFor(requestId);\n if (a.cancelled) return { decision: \"cancel\" };\n const opt = a.optionId === \"acceptForSession\" ? \"acceptForSession\" : a.optionId === \"decline\" ? \"decline\" : \"accept\";\n return { decision: opt };\n }\n case \"item/fileChange/requestApproval\": {\n const itemId = typeof params.itemId === \"string\" ? params.itemId : \"\";\n const changes = Array.isArray(params.changes) && params.changes.length\n ? params.changes\n : (itemId ? this.st.fileChangesByItemId.get(itemId) ?? [] : []);\n const requestId = \"perm_\" + rid();\n this.emit({\n type: \"permission_request\",\n requestId,\n title: tr(\"perm.editFiles\"),\n kind: \"tool\",\n detail: { changes, approvalId: params.approvalId, itemId: params.itemId, reason: params.reason },\n options: [\n { id: \"accept\", label: tr(\"perm.allow\"), kind: \"allow_once\" },\n { id: \"acceptForSession\", label: tr(\"perm.allowSession\"), kind: \"allow_always\" },\n { id: \"decline\", label: tr(\"perm.deny\"), kind: \"reject_once\" },\n ],\n });\n const a = await this.waitFor(requestId);\n if (a.cancelled) return { decision: \"cancel\" };\n const opt = a.optionId === \"acceptForSession\" ? \"acceptForSession\" : a.optionId === \"decline\" ? \"decline\" : \"accept\";\n return { decision: opt };\n }\n case \"item/tool/requestUserInput\": {\n const requestId = \"q_\" + rid();\n this.emit({\n type: \"question\",\n requestId,\n questions: (params.questions as unknown[]) ?? [],\n });\n const a = await this.waitFor(requestId);\n if (a.cancelled) return { answers: {} };\n // schema: { answers: { : { answers: [..] } } }\n const raw = a.answers ?? {};\n const shaped: Record = {};\n for (const [k, v] of Object.entries(raw)) shaped[k] = { answers: [v] };\n return { answers: shaped };\n }\n default:\n throw new Error(`未识别的服务端请求 ${method}`);\n }\n }\n\n private waitFor(requestId: string): Promise {\n return new Promise((resolve) => {\n this.pending.set(requestId, { kind: \"permission\", resolve });\n });\n }\n\n respond(requestId: string, answer: RespondAnswer): void {\n const p = this.pending.get(requestId);\n if (p) {\n this.pending.delete(requestId);\n p.resolve(answer);\n // Writing back resolved events is the manager's job (permission_resolved/question_answered)\n }\n }\n\n async setModel(model: string | null): Promise {\n this.o.model = model; // Takes effect on the next turn/start\n }\n async setMode(mode: Mode): Promise {\n this.o.mode = mode; // Takes effect on the next turn/start\n }\n async setEffort(effort: string | null): Promise {\n this.o.effort = effort; // Takes effect on the next turn/start\n }\n\n async listCommands(): Promise {\n try {\n const entries = this.codexSlash ?? (await loadCodexSlashEntries(this.o.cwd));\n this.codexSlash = entries;\n return codexSlashCommandsFromEntries(entries);\n } catch {\n return [];\n }\n }\n\n async close(): Promise {\n this.closed = true;\n for (const [, p] of this.pending) p.resolve({ cancelled: true });\n this.pending.clear();\n if (this.rpc) await this.rpc.close();\n this.q.close();\n }\n}\n","// Provider / ProviderSession interfaces (EXEC §7.1)\nimport type { ProviderEvent } from \"../timeline/types.js\";\nimport type { SlashCommand } from \"./slash.js\";\n\nexport type Mode = \"plan\" | \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"ask\";\n\nexport type Capabilities = {\n resume: boolean;\n interrupt: boolean;\n steer: boolean;\n /** The Agent takes images in a prompt (sees them itself). For ACP Agents: what initialize advertised, false until known */\n images: boolean;\n /** false while an ACP Agent's image support is not known yet (before its probe or first session); absent = known */\n imagesKnown?: boolean;\n plan: boolean;\n questions: boolean;\n cost: boolean;\n effort: string[];\n modes: Mode[];\n /** Each mode's name in this Agent (like Paseo, show the Agent's own naming); our default names are used when absent */\n modeLabels?: Partial>;\n /** The Agent only streams text deltas and never sends the complete message (ACP): the manager saves each text segment itself */\n deltasOnly?: boolean;\n};\n\nexport type ThinkingOption = { id: string; label: string };\n\nexport type ModelInfo = {\n id: string;\n name: string;\n /** @deprecated use thinkingOptions */\n efforts?: string[];\n thinkingOptions?: ThinkingOption[];\n defaultThinking?: string | null;\n isDefault?: boolean;\n /** Parameter name when the level is sent as a model parameter (Cursor: effort / reasoning_effort / reasoning) */\n thinkingParam?: string;\n};\nexport type DetectResult = { available: boolean; bin?: string; version?: string; reason?: string; installHint?: string };\n/** Custom launch (Settings › Launch command). args are appended after the built-in arguments; prefixArgs (internal) go before them. */\nexport type LaunchCommand = { cmd: string; prefixArgs?: string[]; args?: string[] };\nexport type HistoryItem = { provider: string; sessionId: string; title: string; updatedAt: number; messageCount: number; imported: boolean };\nexport type SendInput = { text: string; images: { path: string; mime: string }[] };\nexport type RespondAnswer = { optionId?: string; answers?: Record; cancelled?: boolean };\n\nexport interface Provider {\n id: string;\n name: string;\n capabilities: Capabilities;\n detect(launch?: LaunchCommand): Promise;\n listModels(launch?: LaunchCommand): Promise;\n createSession(o: {\n threadId: string;\n cwd: string;\n model: string | null;\n mode: Mode;\n effort: string | null;\n resumeId: string | null;\n cursorFast?: boolean;\n cursorAutoReview?: boolean;\n launch?: LaunchCommand;\n }): Promise;\n listHistory?(cwd: string): Promise;\n readHistory?(sessionId: string, cwd: string): Promise;\n}\n\nexport interface ProviderSession {\n events: AsyncIterable;\n send(input: SendInput): Promise;\n steer?(input: SendInput): Promise;\n interrupt(): Promise;\n setModel(model: string | null): Promise;\n setMode(mode: Mode): Promise;\n setEffort(effort: string | null): Promise;\n respond(requestId: string, answer: RespondAnswer): void;\n close(): Promise;\n listCommands(): Promise;\n}\n\nexport type { SlashCommand, SlashCommandKind } from \"./slash.js\";\n\n/** Name of our own \"Default\" placeholder model row (id \"default\") */\nexport const PLACEHOLDER_MODEL_NAME = \"Default\";\n","// Codex Provider (§7.3): detect + listModels (temporary app-server → model/list, cached 10 minutes) + createSession.\nimport type { Provider, ProviderSession, DetectResult, ModelInfo, Capabilities, HistoryItem, LaunchCommand } from \"../types.js\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { listCodexHistory, readCodexHistory } from \"../../history/codex.js\";\nimport { argvFor, resolveBin, killTree, spawnBin, type ResolveResult } from \"../../util/bin.js\";\nimport { CodexRpc, CodexProcessExitedError } from \"./rpc.js\";\nimport { CodexSession } from \"./session.js\";\nimport { log } from \"../../log.js\";\nimport { tr } from \"../../util/i18n.js\";\nimport { launchArgv, resolveLaunch } from \"../launch.js\";\nimport { PLACEHOLDER_MODEL_NAME } from \"../types.js\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { readFile } from \"node:fs/promises\";\n\nconst INSTALL_HINT = \"npm i -g @openai/codex\";\n\nexport const codexCapabilities: Capabilities = {\n resume: true,\n interrupt: true,\n steer: true,\n images: true,\n plan: true,\n questions: true,\n cost: false, // tokenUsage yes, cost no\n effort: [], // effort values depend on the model — filled from model/list after detect\n // No \"plan\": app-server 0.16x has no plan/collaboration mode on turn/start, and a read-only \"plan\" was the same preset as default (B9)\n modes: [\"default\", \"acceptEdits\", \"bypassPermissions\"],\n modeLabels: { default: \"Read Only\", acceptEdits: \"Auto\", bypassPermissions: \"Full Access\" },\n};\n\nlet modelCache: { at: number; models: ModelInfo[] } | null = null;\nconst MODEL_CACHE_MS = 10 * 60 * 1000;\n\nfunction runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 5000): Promise {\n return new Promise((resolvePromise, reject) => {\n let out = \"\";\n const p = spawnBin(r, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n const t = setTimeout(() => {\n try {\n void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes\n } catch {}\n reject(new Error(\"timeout\"));\n }, timeoutMs);\n p.stdout?.on(\"data\", (c: Buffer) => (out += c.toString()));\n p.stderr?.on(\"data\", (c: Buffer) => (out += c.toString()));\n p.on(\"error\", reject);\n p.on(\"close\", (code) => {\n clearTimeout(t);\n if (code === 0) resolvePromise(out);\n else reject(new Error(\"exit \" + code));\n });\n });\n}\n\n/** Normalize the level list to strings: accepts string[] and { reasoningEffort, description }[]; other shapes are dropped */\nexport function normalizeEfforts(raw: unknown[] | undefined): string[] {\n const out: string[] = [];\n for (const e of raw ?? []) {\n const v = typeof e === \"string\" ? e : (e as { reasoningEffort?: unknown } | null)?.reasoningEffort;\n if (typeof v === \"string\" && v && !out.includes(v)) out.push(v);\n }\n return out;\n}\n\nasync function fetchModels(r: ResolveResult & { ok: true }, cwd: string, launch?: LaunchCommand): Promise {\n const rpc = new CodexRpc(argvFor(r, launchArgv([\"app-server\"], launch)), { cwd });\n try {\n await rpc.request(\"initialize\", {\n clientInfo: { name: \"agent-console\", title: \"Agent Console\", version: \"0\" },\n capabilities: { experimentalApi: true },\n }, 15000);\n rpc.notify(\"initialized\", {});\n const res = (await rpc.request(\"model/list\", {}, 15000)) as {\n data?: {\n id?: string;\n displayName?: string;\n isDefault?: boolean;\n // Newer app-server returns { reasoningEffort, description }[], older ones string[]\n supportedReasoningEfforts?: unknown[];\n defaultReasoningEffort?: string;\n }[];\n };\n const rows = res.data ?? [];\n return rows\n .filter((m) => typeof m.id === \"string\" && m.id)\n .map((m) => {\n const efforts = normalizeEfforts(m.supportedReasoningEfforts);\n const thinkingOptions = efforts.map((e) => ({ id: e, label: e }));\n const defaultThinking = (typeof m.defaultReasoningEffort === \"string\" ? m.defaultReasoningEffort : null) ?? thinkingOptions[0]?.id ?? null;\n return {\n id: m.id!,\n name: m.displayName ?? m.id!,\n isDefault: m.isDefault,\n efforts,\n thinkingOptions,\n defaultThinking,\n };\n });\n } finally {\n await rpc.close();\n }\n}\n\nexport type CodexConfig = { modelProvider: string | null; model: string | null; providerModels: string[] };\n\nfunction tomlValue(raw: string): string | string[] | null {\n const v = raw.trim().replace(/\\s+#.*$/, \"\");\n const quoted = v.match(/^\"([\\s\\S]*)\"$/) ?? v.match(/^'([\\s\\S]*)'$/);\n if (quoted) return quoted[1];\n if (v.startsWith(\"[\") && v.endsWith(\"]\")) {\n return v.slice(1, -1).split(\",\").map((x) => tomlValue(x)).filter((x): x is string => typeof x === \"string\");\n }\n return null;\n}\n\nexport function parseCodexConfig(text: string): CodexConfig {\n let section = \"\";\n const values = new Map();\n for (const line of text.split(/\\r?\\n/)) {\n const s = line.trim();\n if (!s || s.startsWith(\"#\")) continue;\n const header = s.match(/^\\[([^\\]]+)\\]$/);\n if (header) { section = header[1]; continue; }\n const m = s.match(/^([A-Za-z0-9_.-]+)\\s*=\\s*(.+)$/);\n if (!m) continue;\n const value = tomlValue(m[2]);\n if (typeof value === \"string\" || Array.isArray(value)) values.set(`${section}\\0${m[1]}`, value);\n }\n const top = (key: string) => values.get(`\\0${key}`);\n const profile = top(\"profile\");\n const profileName = typeof profile === \"string\" ? profile : null;\n const profileValue = (key: string) => profileName ? values.get(`profiles.${profileName}\\0${key}`) : undefined;\n const modelProvider = (profileValue(\"model_provider\") ?? top(\"model_provider\"));\n const model = (profileValue(\"model\") ?? top(\"model\"));\n const provider = typeof modelProvider === \"string\" ? modelProvider : null;\n const models = new Set();\n if (typeof model === \"string\" && model) models.add(model);\n for (const [key, value] of values) {\n if (provider && key === `model_providers.${provider}\\0models` && Array.isArray(value)) {\n for (const m of value) models.add(m);\n }\n }\n return { modelProvider: provider, model: typeof model === \"string\" ? model : null, providerModels: [...models] };\n}\n\nasync function readCodexConfig(): Promise {\n const home = process.env.CODEX_HOME?.trim() || join(homedir(), \".codex\");\n const file = home.toLowerCase().endsWith(\".toml\") ? home : join(home, \"config.toml\");\n try { return parseCodexConfig(await readFile(file, \"utf8\")); } catch { return { modelProvider: null, model: null, providerModels: [] }; }\n}\n\nfunction isChatGptProvider(id: string | null): boolean {\n return !id || /^(openai|chatgpt)$/i.test(id);\n}\n\nexport function createCodexProvider(version: string): Provider {\n return {\n id: \"codex\",\n name: \"Codex\",\n capabilities: codexCapabilities,\n async detect(launch?: LaunchCommand): Promise {\n const bin = launch ? await resolveLaunch(launch) : await resolveBin(\"codex\");\n if (!bin.ok) {\n return { available: false, reason: bin.reason, installHint: INSTALL_HINT };\n }\n try {\n const v = await runVersion(bin, [...(launch?.prefixArgs ?? []), \"--version\"]);\n return { available: true, bin: bin.display, version: v.trim().split(\"\\n\")[0] || \"\" };\n } catch (e) {\n return { available: true, bin: bin.display, version: \"\", reason: String(e) };\n }\n },\n async listModels(launch?: LaunchCommand): Promise {\n const config = await readCodexConfig();\n if (!isChatGptProvider(config.modelProvider)) {\n const rows = config.providerModels.map((id, i) => ({ id, name: id, isDefault: i === 0 }));\n return rows.length ? rows : [{ id: \"\", name: `${PLACEHOLDER_MODEL_NAME} (${config.modelProvider})`, isDefault: true }];\n }\n if (!launch && modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;\n const bin = launch ? await resolveLaunch(launch) : await resolveBin(\"codex\");\n if (!bin.ok) return [{ id: \"\", name: PLACEHOLDER_MODEL_NAME }];\n try {\n const models = await fetchModels(bin, process.cwd(), launch);\n modelCache = { at: Date.now(), models };\n return models;\n } catch (e) {\n // Gateway region errors etc. — the frontend shows a single \"Default\" entry (§7.3.6)\n log(\"warn\", \"codex model/list 失败\", { err: String(e) });\n return [{ id: \"\", name: PLACEHOLDER_MODEL_NAME }];\n }\n },\n async createSession(o): Promise {\n const bin = o.launch ? await resolveLaunch(o.launch) : await resolveBin(\"codex\");\n if (!bin.ok) throw new Error(tr(\"codex.notFound\", { detail: bin.reason, hint: INSTALL_HINT }));\n return new CodexSession({\n threadId: o.threadId,\n cwd: o.cwd,\n model: o.model,\n mode: o.mode,\n effort: o.effort,\n resumeId: o.resumeId,\n binCmd: bin.cmd,\n binPrefixArgs: bin.prefixArgs,\n binVia: bin.via,\n binShim: bin.shim,\n launch: o.launch,\n version,\n });\n },\n // §7.6: ~/.codex/sessions/**/rollout-*.jsonl matched by cwd\n async listHistory(cwd: string): Promise {\n const items = await listCodexHistory(cwd);\n return items.map((i) => ({ provider: \"codex\", ...i, imported: false }));\n },\n async readHistory(sessionId: string, cwd: string): Promise {\n return (await readCodexHistory(sessionId, cwd)) as unknown as ProviderEvent[];\n },\n };\n}\n","import { tr } from \"../util/i18n.js\";\n/** Provider catalog (fixed, 8 entries).\n * status: verified=accepted on a real machine | experimental=usable but not guaranteed | planned=integration not confirmed\n * All 8 are currently verified; default toggle: verified ones are on by default (see enabled.ts). */\nexport type ProviderStatus = \"verified\" | \"experimental\" | \"planned\";\n\nexport type ProviderCatalogEntry = {\n id: string;\n name: string;\n bins: string[];\n installHint: string;\n status: ProviderStatus;\n};\n\nexport const PROVIDER_CATALOG: ProviderCatalogEntry[] = [\n { id: \"claude\", name: \"Claude Code\", bins: [\"claude\"], installHint: \"npm i -g @anthropic-ai/claude-code\", status: \"verified\" },\n { id: \"codex\", name: \"Codex\", bins: [\"codex\"], installHint: \"npm i -g @openai/codex\", status: \"verified\" },\n { id: \"cursor\", name: \"Cursor\", bins: [\"cursor-agent\", \"cursor\"], installHint: \"curl https://cursor.com/install -fsS | bash\", status: \"verified\" },\n { id: \"copilot\", name: \"Copilot\", bins: [\"copilot\"], installHint: \"npm i -g @github/copilot\", status: \"verified\" },\n { id: \"opencode\", name: \"OpenCode\", bins: [\"opencode\"], installHint: \"npm i -g opencode-ai\", status: \"verified\" },\n { id: \"pi\", name: \"Pi\", bins: [\"pi-acp\", \"pi\", \"pi-coding-agent\"], installHint: \"npm i -g pi-acp\", status: \"verified\" },\n { id: \"devin\", name: \"Devin CLI\", bins: [\"devin\"], installHint: \"https://docs.devin.ai/cli\", status: \"verified\" },\n { id: \"dsh\", name: \"dsh\", bins: [\"dsh\"], installHint: \"npm i -g @deepseek-ai/dsh\", status: \"verified\" },\n];\n\nexport function catalogById(id: string): ProviderCatalogEntry | undefined {\n return PROVIDER_CATALOG.find((p) => p.id === id);\n}\n\nexport function providerCreatable(status: ProviderStatus): boolean {\n return status !== \"planned\";\n}\n","import type { ChildProcess } from \"node:child_process\";\nimport { Readable, Writable } from \"node:stream\";\nimport { resolve as resolvePath } from \"node:path\";\nimport * as acp from \"@agentclientprotocol/sdk\";\nimport type { ResolveResult } from \"../../util/bin.js\";\nimport { killTree, spawnBin } from \"../../util/bin.js\";\n\nexport function spawnResolved(r: ResolveResult & { ok: true }, args: string[], o: { cwd?: string } = {}): ChildProcess {\n // group: on non-Windows it gets its own process group so killTree also ends the tool processes it started\n return spawnBin(r, args, {\n cwd: o.cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: { ...process.env, NO_COLOR: \"1\", FORCE_COLOR: \"0\" },\n group: true,\n });\n}\n\nexport function acpStreamFromChild(child: ChildProcess): acp.Stream {\n if (!child.stdin || !child.stdout) throw new Error(\"ACP 子进程缺少 stdio 管道\");\n const output = Writable.toWeb(child.stdin) as WritableStream;\n const input = Readable.toWeb(child.stdout) as ReadableStream;\n return acp.ndJsonStream(output, input);\n}\n\nexport function absCwd(cwd: string): string {\n return resolvePath(cwd);\n}\n\nexport async function killAcpChild(child: ChildProcess | null): Promise {\n await killTree(child);\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport type { ClientApp } from \"@agentclientprotocol/sdk\";\nimport { methods } from \"@agentclientprotocol/sdk\";\nimport type { RespondAnswer } from \"../types.js\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { tr } from \"../../util/i18n.js\";\n\nexport type PermBridge = {\n push(ev: ProviderEvent): void;\n waitFor(requestId: string): Promise;\n /** Cursor Auto-review: no permission card, allow is chosen automatically */\n autoAcceptPermissions?: () => boolean;\n};\n\nexport function registerAcpClientHandlers(app: ClientApp, bridge: PermBridge): void {\n app.onRequest(methods.client.fs.readTextFile, async (ctx) => {\n const text = await readFile(ctx.params.path, \"utf8\");\n return { content: text };\n });\n app.onRequest(methods.client.fs.writeTextFile, async (ctx) => {\n await writeFile(ctx.params.path, ctx.params.content, \"utf8\");\n return {};\n });\n app.onRequest(methods.client.session.requestPermission, async (ctx) => {\n const tc = ctx.params.toolCall;\n const options = ctx.params.options.map((o) => ({\n id: o.optionId,\n label: o.name,\n kind: o.kind,\n }));\n if (bridge.autoAcceptPermissions?.()) {\n const allow =\n options.find((o) => o.kind === \"allow_once\" || o.kind === \"allow_always\") ?? options[0];\n if (allow) return { outcome: { outcome: \"selected\", optionId: allow.id } };\n }\n const requestId = \"p\" + Math.random().toString(36).slice(2, 10);\n bridge.push({\n type: \"permission_request\",\n requestId,\n title: tc.title ?? tc.name ?? tr(\"tool.needsApproval\"),\n kind: tc.kind ?? \"tool\",\n detail: tc.rawInput ?? undefined,\n options,\n });\n const answer = await bridge.waitFor(requestId);\n if (answer.cancelled) return { outcome: { outcome: \"cancelled\" } };\n const optionId = answer.optionId ?? options[0]?.id;\n if (!optionId) return { outcome: { outcome: \"cancelled\" } };\n return { outcome: { outcome: \"selected\", optionId } };\n });\n}\n","import type * as schema from \"@agentclientprotocol/sdk\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport type { ToolKind } from \"../../timeline/types.js\";\n\nconst rid = () => Math.random().toString(36).slice(2, 8);\n\nfunction mapToolKind(k: schema.ToolKind | null | undefined): ToolKind {\n switch (k) {\n case \"read\":\n case \"edit\":\n case \"search\":\n return k;\n case \"execute\":\n return \"bash\";\n case \"fetch\":\n return \"web\";\n default:\n return \"other\";\n }\n}\n\nfunction mapToolStatus(s: schema.ToolCallStatus | null | undefined): \"running\" | \"ok\" | \"failed\" {\n if (s === \"completed\") return \"ok\";\n if (s === \"failed\") return \"failed\";\n return \"running\";\n}\n\nfunction textFromContent(content: schema.ContentBlock): string {\n if (content.type === \"text\") return content.text;\n return \"\";\n}\n\n/** seg: text segment number, bumped when a tool call / plan comes between two runs of text, so the text before and\n * after a tool call are separate items (live and persisted alike: the manager saves each segment when the next item starts). */\nexport type MapCtx = { itemPrefix: string; messageIds: Map; seg: number; lastWasText: boolean };\n\nexport function newMapCtx(): MapCtx {\n return { itemPrefix: \"a\" + rid() + \"_\", messageIds: new Map(), seg: 0, lastWasText: false };\n}\n\nfunction endTextSegment(ctx: MapCtx): void {\n if (ctx.lastWasText) {\n ctx.seg++;\n ctx.lastWasText = false;\n }\n}\n\nexport function mapSessionUpdate(update: schema.SessionUpdate, ctx: MapCtx): ProviderEvent[] {\n const out: ProviderEvent[] = [];\n const mid = \"messageId\" in update && update.messageId ? String(update.messageId) : null;\n\n switch (update.sessionUpdate) {\n case \"agent_message_chunk\": {\n const text = textFromContent(update.content);\n if (!text) break;\n const itemId = `${ctx.itemPrefix}${mid ?? \"msg\"}_${ctx.seg}`;\n if (mid) ctx.messageIds.set(mid, itemId);\n ctx.lastWasText = true;\n out.push({ type: \"assistant_delta\", itemId, text });\n break;\n }\n case \"agent_thought_chunk\": {\n const text = textFromContent(update.content);\n if (!text) break;\n const itemId = `${ctx.itemPrefix}t_${mid ?? \"think\"}_${ctx.seg}`;\n ctx.lastWasText = true;\n out.push({ type: \"reasoning_delta\", itemId, text });\n break;\n }\n case \"tool_call\":\n endTextSegment(ctx);\n out.push({\n type: \"tool_call\",\n itemId: ctx.itemPrefix + update.toolCallId,\n kind: mapToolKind(update.kind),\n title: update.title,\n status: mapToolStatus(update.status),\n input: update.rawInput,\n });\n break;\n case \"tool_call_update\":\n endTextSegment(ctx);\n out.push({\n type: \"tool_call\",\n itemId: ctx.itemPrefix + update.toolCallId,\n kind: mapToolKind(update.kind),\n title: update.title ?? update.name ?? \"\",\n status: mapToolStatus(update.status),\n input: update.rawInput,\n output: typeof update.rawOutput === \"string\" ? update.rawOutput : undefined,\n });\n break;\n case \"plan\":\n endTextSegment(ctx);\n out.push({\n type: \"plan\",\n itemId: ctx.itemPrefix + \"plan\",\n markdown: update.entries.map((e) => `- ${e.content}`).join(\"\\n\"),\n entries: update.entries.map((e) => ({ step: e.content, status: e.status ?? \"\" })),\n });\n break;\n case \"notice\":\n out.push({\n type: \"notice\",\n level: update.severity === \"error\" ? \"error\" : update.severity === \"warning\" ? \"warn\" : \"info\",\n message: update.description ? `${update.title}: ${update.description}` : update.title,\n });\n break;\n case \"usage_update\":\n out.push({\n type: \"usage\",\n inputTokens: update.used,\n outputTokens: 0,\n cacheReadTokens: 0,\n costUsd: typeof update.cost?.amount === \"number\" ? update.cost.amount : 0,\n contextWindow: update.size,\n });\n break;\n default:\n break;\n }\n return out;\n}\n\nexport function stopToTurnEnd(stopReason: schema.StopReason, turnId: string, err?: string): ProviderEvent {\n if (stopReason === \"cancelled\") {\n return { type: \"turn_ended\", turnId, status: \"interrupted\" };\n }\n if (stopReason === \"refusal\" || stopReason === \"max_tokens\") {\n return { type: \"turn_ended\", turnId, status: \"failed\", error: err ?? stopReason };\n }\n return { type: \"turn_ended\", turnId, status: \"completed\" };\n}\n","// What each ACP Agent says it accepts in a prompt: initialize → agentCapabilities.promptCapabilities.\n// ACP's baseline is text and resource_link; image / audio / embedded resources are opt-in per Agent.\n// Learned from the model probe (startup warm-up, providers.list) and from every session's initialize,\n// kept in memory per provider id, and read by the provider's capabilities (images) and by AcpSession.send.\nexport type AcpPromptCaps = { image: boolean; audio: boolean; embeddedContext: boolean };\n\nconst learned = new Map();\n\n/** Normalize an initialize response (anything: Agents may leave fields out, which means false) */\nexport function promptCapsFromInitialize(res: unknown): AcpPromptCaps {\n const pc = (res as { agentCapabilities?: { promptCapabilities?: Record | null } | null } | null)\n ?.agentCapabilities?.promptCapabilities;\n return {\n image: pc?.image === true,\n audio: pc?.audio === true,\n embeddedContext: pc?.embeddedContext === true,\n };\n}\n\nexport function rememberPromptCaps(providerId: string | undefined, caps: AcpPromptCaps): void {\n if (providerId) learned.set(providerId, caps);\n}\n\n/** undefined until the Agent has been probed or a session has initialized */\nexport function knownPromptCaps(providerId: string): AcpPromptCaps | undefined {\n return learned.get(providerId);\n}\n\nexport function forgetPromptCaps(providerId?: string): void {\n if (providerId) learned.delete(providerId);\n else learned.clear();\n}\n","// How an ACP Agent reopens an old conversation: initialize → agentCapabilities.\n// - loadSession (top-level): session/load — returns prior messages as session/update\n// - sessionCapabilities.resume: session/resume — reconnects without replaying history\n// Prefer load when both are advertised (OpenCode); resume when only resume (dsh);\n// neither → the caller starts a new session and tells the user prior context wasn't restored.\nexport type AcpSessionOpen = { load: boolean; resume: boolean };\nexport type AcpReconnect = \"load\" | \"resume\" | \"none\";\n\n/** Normalize an initialize response: missing/false/null means the Agent doesn't advertise that method */\nexport function sessionOpenFromInitialize(res: unknown): AcpSessionOpen {\n const caps = (res as { agentCapabilities?: {\n loadSession?: unknown;\n sessionCapabilities?: { resume?: unknown } | null;\n } | null } | null)?.agentCapabilities;\n // ACP: omitted or null = no; {} (any object) = yes\n const resume = caps?.sessionCapabilities?.resume != null && typeof caps.sessionCapabilities.resume === \"object\";\n return { load: caps?.loadSession === true, resume };\n}\n\nexport function pickReconnect(open: AcpSessionOpen): AcpReconnect {\n if (open.load) return \"load\";\n if (open.resume) return \"resume\";\n return \"none\";\n}\n","// Turn one user message (text + attachments) into an ACP prompt (ContentBlock[]) for what this Agent accepts.\n// - PNG/JPEG/GIF/WebP: an image block (base64 + mimeType) when the Agent advertises promptCapabilities.image;\n// otherwise the saved file's absolute path, as a resource_link (ACP baseline) and as a line of text,\n// so an Agent with file tools can still open it; the caller shows a notice that it can't see the image.\n// - audio/* : an audio block when promptCapabilities.audio, else the same path fallback.\n// - text : an embedded resource (its text) when promptCapabilities.embeddedContext and small enough, else a path.\n// Every attachment is either sent or named by path: nothing is dropped silently.\nimport type { ContentBlock } from \"@agentclientprotocol/sdk\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { basename } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { resolveImagePath } from \"../../util/attachmentRefs.js\";\nimport type { AcpPromptCaps } from \"./promptCaps.js\";\nimport { attachmentKind } from \"../../util/attachmentKinds.js\";\n\n/** Largest image / audio sent inline as base64 (above it, the path is sent instead) */\nexport const MAX_INLINE_MEDIA_BYTES = 10 * 1024 * 1024;\n/** All inline media of one prompt together. Base64 adds a third, and an Agent built on the ACP SDK refuses an incoming\n * line over 32 MB (DEFAULT_MAX_MESSAGE_BYTES), so one prompt stays well under that; the rest goes by path. */\nexport const MAX_INLINE_TOTAL_BYTES = 16 * 1024 * 1024;\n/** Largest text file embedded as a resource */\nexport const MAX_EMBED_TEXT_BYTES = 1024 * 1024;\n\nexport type AcpPromptBuild = {\n blocks: ContentBlock[];\n /** Images that went by path because the Agent doesn't take image blocks */\n imagesByPath: string[];\n /** Other problems worth a notice (unreadable file, too large) */\n warnings: string[];\n};\n\nconst isText = (mime: string) => attachmentKind(mime) === \"text\";\n\nexport async function buildAcpPrompt(\n text: string,\n attachments: { path: string; mime: string }[],\n caps: AcpPromptCaps,\n): Promise {\n const media: ContentBlock[] = [];\n const links: ContentBlock[] = [];\n const pathLines: string[] = [];\n const imagesByPath: string[] = [];\n const warnings: string[] = [];\n let inlineBytes = 0;\n\n const byPath = (file: string, mime: string, size: number | null, label: string) => {\n links.push({ type: \"resource_link\", uri: pathToFileURL(file).href, name: basename(file), mimeType: mime, ...(size !== null ? { size } : {}) });\n pathLines.push(`${label}: ${file}`);\n };\n\n for (const a of attachments) {\n const mime = a.mime || \"application/octet-stream\";\n let file: string;\n let size: number | null = null;\n try {\n file = await resolveImagePath(a.path);\n size = (await stat(file)).size;\n } catch (e) {\n warnings.push(`${a.path}: ${String((e as Error)?.message ?? e)}`);\n continue;\n }\n // Only the four image types model APIs take (svg, bmp… go by path like any other file)\n const image = attachmentKind(mime) === \"image\";\n const audio = mime.startsWith(\"audio/\");\n if ((image && caps.image) || (audio && caps.audio)) {\n if (size > MAX_INLINE_MEDIA_BYTES || inlineBytes + size > MAX_INLINE_TOTAL_BYTES) {\n const limit = size > MAX_INLINE_MEDIA_BYTES ? MAX_INLINE_MEDIA_BYTES : MAX_INLINE_TOTAL_BYTES;\n warnings.push(`${basename(file)}: ${(size / 1024 / 1024).toFixed(1)} MB, over the ${limit / 1024 / 1024} MB inline limit; sent as a file path`);\n byPath(file, mime, size, image ? \"Attached image\" : \"Attached audio\");\n if (image) imagesByPath.push(file);\n continue;\n }\n try {\n const data = (await readFile(file)).toString(\"base64\");\n media.push(image ? { type: \"image\", data, mimeType: mime } : { type: \"audio\", data, mimeType: mime });\n inlineBytes += size;\n } catch (e) {\n warnings.push(`${basename(file)}: ${String((e as Error)?.message ?? e)}`);\n byPath(file, mime, size, image ? \"Attached image\" : \"Attached audio\");\n if (image) imagesByPath.push(file);\n }\n continue;\n }\n if (image || audio) {\n byPath(file, mime, size, image ? \"Attached image\" : \"Attached audio\");\n if (image) imagesByPath.push(file);\n continue;\n }\n if (isText(mime) && caps.embeddedContext && size <= MAX_EMBED_TEXT_BYTES && inlineBytes + size <= MAX_INLINE_TOTAL_BYTES) {\n try {\n const body = await readFile(file, \"utf8\");\n media.push({ type: \"resource\", resource: { uri: pathToFileURL(file).href, mimeType: mime, text: body } });\n inlineBytes += size;\n continue;\n } catch {\n /* fall back to the path */\n }\n }\n byPath(file, mime, size, \"Attached file\");\n }\n\n const fullText = [text, ...(pathLines.length ? [pathLines.join(\"\\n\")] : [])].filter(Boolean).join(\"\\n\\n\");\n const blocks: ContentBlock[] = [];\n if (fullText) blocks.push({ type: \"text\", text: fullText });\n blocks.push(...media, ...links);\n return { blocks, imagesByPath, warnings };\n}\n","// Persistent ACP session: cursor-agent acp / devin acp and others.\nimport type { ActiveSession, ClientConnection, ClientContext } from \"@agentclientprotocol/sdk\";\nimport { client, methods, PROTOCOL_VERSION } from \"@agentclientprotocol/sdk\";\nimport type { ChildProcess } from \"node:child_process\";\nimport type { LaunchCommand, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from \"../types.js\";\nimport { mapAcpAvailableCommands, sortSlashCommands } from \"../slash.js\";\nimport type { ProviderEvent } from \"../../timeline/types.js\";\nimport { AsyncQueue } from \"../../util/queue.js\";\nimport { resolveFirstBin, type ResolveResult } from \"../../util/bin.js\";\nimport { launchArgv, resolveLaunch } from \"../launch.js\";\nimport { absCwd, acpStreamFromChild, killAcpChild, spawnResolved } from \"./spawn.js\";\nimport { registerAcpClientHandlers } from \"./clientHandlers.js\";\nimport { mapSessionUpdate, newMapCtx, stopToTurnEnd, type MapCtx } from \"./mapUpdate.js\";\nimport { promptCapsFromInitialize, rememberPromptCaps, type AcpPromptCaps } from \"./promptCaps.js\";\nimport { pickReconnect, sessionOpenFromInitialize } from \"./sessionCaps.js\";\nimport { buildAcpPrompt } from \"./prompt.js\";\nimport { tr } from \"../../util/i18n.js\";\n\ntype AcpSelectValue = { value?: string; name?: string; options?: AcpSelectValue[] };\ntype AcpConfigOption = { id: string; category?: string | null; type?: string; currentValue?: unknown; options?: AcpSelectValue[] };\nimport { log } from \"../../log.js\";\n\nconst rid = () => Math.random().toString(36).slice(2, 10);\n\ntype AttachableCtx = {\n attachSession(response: { sessionId: string; modes?: unknown; configOptions?: unknown }): ActiveSession;\n};\n\nexport type AcpSessionOpts = {\n threadId: string;\n /** Provider id and display name: the Agent's prompt capabilities are remembered under the id; notices name the Agent */\n providerId?: string;\n providerName?: string;\n cwd: string;\n model: string | null;\n mode: Mode;\n effort: string | null;\n resumeId: string | null;\n binName: string;\n binCandidates: string[];\n acpArgs: string[];\n /** initialize's image answer holds for the start model only (dsh): after a switch, images go by path */\n imagesFollowStartModel?: boolean;\n appVersion: string;\n flavor: \"cursor\" | \"generic\";\n modeMap?: Partial>;\n cursorFast?: boolean;\n cursorAutoReview?: boolean;\n launch?: LaunchCommand;\n};\n\nexport class AcpSession implements ProviderSession {\n events: AsyncIterable;\n private q = new AsyncQueue();\n private child: ChildProcess | null = null;\n private conn: ClientConnection | null = null;\n private ctx: ClientContext | null = null;\n private active: ActiveSession | null = null;\n private initErr: Error | null = null;\n private initPromise: Promise;\n private closed = false;\n private turnId: string | null = null;\n private turnNum = 0;\n private running = false;\n private permPending = new Map void>();\n private mapCtx: MapCtx = newMapCtx();\n private modelConfigId: string | null = null;\n private thoughtConfigId: string | null = null;\n private cursorFast = false;\n private cursorAutoReview = false;\n private slashCommands: SlashCommand[] = [];\n private activeTurnId: string | null = null;\n private configOptions: AcpConfigOption[] | null = null;\n // initialize → agentCapabilities.promptCapabilities (ACP baseline until initialize answers: text + resource_link)\n private promptCaps: AcpPromptCaps = { image: false, audio: false, embeddedContext: false };\n private initCaps: AcpPromptCaps = this.promptCaps;\n private startModel: string | null = null;\n private wakePump: (() => void) | null = null;\n // listCommands waits for the first batch of commands (or confirmation there are none), following Paseo's waitForInitialCommands\n private commandsReady!: Promise;\n private settleCommands!: () => void;\n\n constructor(private o: AcpSessionOpts) {\n this.events = this.q;\n this.startModel = o.model; // the model the process is launched for (argsFor), before any setModel\n this.cursorFast = o.cursorFast ?? false;\n // The shield (auto-accept permission prompts) UI was removed: never auto-approve, so conversations that once turned it on don't keep approving with the toggle hidden\n this.cursorAutoReview = false;\n this.commandsReady = new Promise((r) => (this.settleCommands = r));\n this.initPromise = this.boot();\n }\n\n private async boot(): Promise {\n const bin = this.o.launch\n ? await resolveLaunch(this.o.launch).then((r) => r.ok ? ({ ...r, binName: \"custom\" } as ResolveResult & { ok: true; binName: string }) : r)\n : await resolveFirstBin(this.o.binCandidates?.length ? this.o.binCandidates : [this.o.binName]);\n if (!bin.ok) throw new Error(bin.reason);\n try {\n this.child = spawnResolved(bin, launchArgv(this.o.acpArgs, this.o.launch), { cwd: this.o.cwd });\n this.child.stderr?.on(\"data\", (d: Buffer) => {\n const t = d.toString().trim();\n if (t) log(\"info\", `[${this.o.binName} acp] ${t.slice(0, 500)}`);\n });\n this.child.on(\"error\", (e) => this.failInit(e));\n this.child.on(\"close\", (code) => {\n if (!this.closed && code !== 0) {\n this.q.push({ type: \"notice\", level: \"error\", message: tr(\"acp.exited\", { name: this.o.binName, code: String(code) }) });\n }\n });\n\n const app = client({ name: \"magpie-agent-console\" });\n registerAcpClientHandlers(app, {\n push: (ev) => this.q.push(ev),\n waitFor: (id) => this.waitPerm(id),\n autoAcceptPermissions: () => this.cursorAutoReview,\n });\n const stream = acpStreamFromChild(this.child);\n this.conn = app.connect(stream);\n this.ctx = this.conn.agent;\n const initRes = await this.ctx.request(methods.agent.initialize, {\n protocolVersion: PROTOCOL_VERSION,\n // Cursor: declare support for the parameterized model picker (as Paseo does); only then does it expose levels / Fast as separate config options\n clientCapabilities: this.o.flavor === \"cursor\" ? { _meta: { parameterizedModelPicker: true } } : {},\n clientInfo: { name: \"Agent Console\", version: this.o.appVersion },\n });\n this.promptCaps = promptCapsFromInitialize(initRes);\n this.initCaps = this.promptCaps;\n rememberPromptCaps(this.o.providerId, this.promptCaps);\n\n const cwd = absCwd(this.o.cwd);\n const ctx = this.ctx;\n if (!ctx) throw new Error(\"ACP 未连接\");\n if (this.o.resumeId) {\n // Prefer the method the Agent's initialize advertises: load (replays history) over resume (reconnects only); neither → new session + notice\n const how = pickReconnect(sessionOpenFromInitialize(initRes));\n if (how === \"load\" || how === \"resume\") {\n const method = how === \"load\" ? methods.agent.session.load : methods.agent.session.resume;\n const restored = (await ctx.request(method, {\n sessionId: this.o.resumeId,\n cwd,\n mcpServers: [],\n })) as { modes?: unknown; configOptions?: AcpConfigOption[] };\n this.active = (ctx as unknown as AttachableCtx).attachSession({\n sessionId: this.o.resumeId,\n modes: restored.modes,\n configOptions: restored.configOptions,\n });\n if (Array.isArray(restored.configOptions)) this.configOptions = restored.configOptions;\n } else {\n this.active = await ctx.buildSession(cwd).start();\n const agent = this.o.providerName ?? this.o.binName;\n this.q.push({ type: \"notice\", level: \"warn\", message: tr(\"notice.acpSessionNotRestored\", { agent }) });\n }\n } else {\n this.active = await ctx.buildSession(cwd).start();\n }\n this.syncModelConfigId();\n this.syncThoughtConfigId();\n await this.applySessionMode(this.o.mode);\n await this.applySessionModel(this.o.model); // Also applies the thinking level\n await this.applyCursorAutoReviewConfig(this.cursorAutoReview);\n this.q.push({ type: \"provider_session_id\", id: this.active.sessionId });\n const init = (this.active.newSessionResponse as { availableCommands?: { name: string; description: string; input?: { hint?: string } | null }[] })\n ?.availableCommands;\n if (init?.length) this.applyAvailableCommands(init);\n void this.pumpUpdates();\n } catch (e) {\n this.failInit(e);\n throw e;\n }\n }\n\n private failInit(e: unknown): void {\n this.initErr = e instanceof Error ? e : new Error(String(e));\n }\n\n private applyAvailableCommands(\n raw: { name: string; description: string; input?: { hint?: string } | null }[],\n ): void {\n this.slashCommands = sortSlashCommands(mapAcpAvailableCommands(raw));\n this.q.push({ type: \"slash_commands\", commands: this.slashCommands });\n this.settleCommands();\n }\n\n private async ready(): Promise {\n await this.initPromise.catch(() => {});\n if (this.initErr) throw this.initErr;\n if (!this.active) throw new Error(\"ACP 会话未就绪\");\n }\n\n /** The config options currently in effect: each set_config_option response returns the latest set (levels change after switching models); otherwise use session/new's */\n private currentConfig(): AcpConfigOption[] {\n return (this.configOptions ?? this.active?.newSessionResponse.configOptions ?? []) as AcpConfigOption[];\n }\n\n private syncModelConfigId(): void {\n for (const o of this.currentConfig()) {\n if (o.type === \"select\" && (o.category === \"model\" || o.id === \"model\")) {\n this.modelConfigId = o.id;\n return;\n }\n }\n if (this.o.flavor === \"cursor\") this.modelConfigId = \"model\";\n }\n\n // Level options belong to the current model: recompute on every refresh (cleared when switching to a model without levels)\n private syncThoughtConfigId(): void {\n this.thoughtConfigId = null;\n const opts = this.currentConfig().filter((o) => o.type === \"select\");\n const hit =\n opts.find((o) => o.category === \"thought_level\") ??\n opts.find((o) => /thought|thinking|effort|reasoning/i.test(o.id ?? \"\"));\n if (hit) this.thoughtConfigId = hit.id;\n }\n\n /** set_config_option, then refresh local state from the latest config options it returns */\n private async setOption(configId: string, value: string): Promise {\n if (!this.ctx || !this.active) return false;\n try {\n const res = (await this.ctx.request(methods.agent.session.setConfigOption, {\n sessionId: this.active.sessionId,\n configId,\n value,\n })) as { configOptions?: AcpConfigOption[] } | null;\n if (Array.isArray(res?.configOptions)) {\n this.configOptions = res.configOptions;\n this.syncThoughtConfigId();\n }\n return true;\n } catch (e) {\n log(\"info\", `ACP set_config_option(${configId}=${value}): ${String(e)}`);\n return false;\n }\n }\n\n private async applySessionThought(effort: string | null): Promise {\n if (!effort || !this.thoughtConfigId) return;\n // Don't send a level the current model doesn't support (the level set changes after switching models)\n const opt = this.currentConfig().find((o) => o.id === this.thoughtConfigId);\n const values = (opt?.options ?? []).flatMap((x) => (x.options ? x.options : [x])).map((x) => x.value);\n if (values.length && !values.includes(effort)) return;\n await this.setOption(this.thoughtConfigId, effort);\n }\n\n /** Mode choices the Agent reports: prefer a category=mode select in configOptions, otherwise ACP modes.availableModes */\n private modeChoices(): { id: string; name: string; configId: string | null }[] {\n const opt = this.currentConfig().find(\n (o) => o.type === \"select\" && (o.category === \"mode\" || o.id === \"mode\"),\n ) as { id: string; options?: { value?: string; name?: string }[] } | undefined;\n if (opt?.options?.length) {\n return opt.options\n .filter((x) => typeof x.value === \"string\")\n .map((x) => ({ id: x.value!, name: x.name ?? x.value!, configId: opt.id }));\n }\n return (this.active?.modes?.availableModes ?? []).map((m) => ({ id: m.id, name: m.name, configId: null }));\n }\n\n private resolveAcpModeId(mode: Mode): string | null {\n if (this.o.modeMap) {\n // Find the Agent's real mode via the table; Copilot's mode ids are URLs (…/session-modes#agent), so match on the # suffix\n const want = this.o.modeMap[mode];\n if (!want) return null;\n const hit = this.modeChoices().find(\n (m) => m.id === want || m.id.endsWith(`#${want}`) || m.name.toLowerCase() === want,\n );\n return hit?.id ?? want;\n }\n if (this.o.flavor === \"cursor\") {\n const map: Partial> = { default: \"agent\", plan: \"plan\", ask: \"ask\" };\n const want = map[mode] ?? \"agent\";\n const avail = this.active?.modes?.availableModes ?? [];\n const hit = avail.find((m) => m.id === want || m.name.toLowerCase() === want);\n return hit?.id ?? want;\n }\n return mode === \"plan\" ? \"plan\" : \"default\";\n }\n\n private async applySessionMode(mode: Mode): Promise {\n if (!this.ctx || !this.active) return;\n // Copilot \"Allow All\" (as Paseo does): use the agent mode, then turn the allow_all config on; turn it off for other modes\n const hasAllowAll = this.currentConfig().some((o) => o.id === \"allow_all\");\n if (this.o.modeMap?.[mode] === \"allow-all\") {\n const agentId = this.modeChoices().find((m) => m.id === \"agent\" || m.id.endsWith(\"#agent\"));\n if (agentId?.configId) await this.setOption(agentId.configId, agentId.id);\n if (hasAllowAll) await this.setOption(\"allow_all\", \"on\");\n return;\n }\n if (hasAllowAll && this.o.modeMap) await this.setOption(\"allow_all\", \"off\");\n const modeId = this.resolveAcpModeId(mode);\n if (!modeId) return; // This Agent has no such mode: don't send anything\n try {\n // Modes offered as a config option (Devin / OpenCode / Copilot) use set_config_option, otherwise set_mode\n const viaConfig = this.modeChoices().find((m) => m.id === modeId)?.configId;\n if (viaConfig) {\n await this.setOption(viaConfig, modeId);\n return;\n }\n await this.ctx.request(methods.agent.session.setMode, {\n sessionId: this.active.sessionId,\n modeId,\n });\n } catch (e) {\n log(\"info\", `ACP setMode(${mode}): ${String(e)}`);\n }\n }\n\n /**\n * Switch model → refresh level options from the new config options it returns → then apply the level (as Paseo does).\n * Cursor connects with parameterizedModelPicker: only the base model name is sent (grok-4.6); level / Fast are separate config options.\n */\n private async applySessionModel(model: string | null): Promise {\n if (!this.ctx || !this.active) return;\n const value = model && this.o.flavor === \"cursor\" ? model.replace(/\\[.*\\]$/u, \"\") : model;\n if (value) {\n const modelOption = this.currentConfig().find((o) => o.id === (this.modelConfigId ?? \"model\"));\n const values = (modelOption?.options ?? []).flatMap((x) => x.options ? x.options : [x])\n .map((x) => x.value).filter((x): x is string => typeof x === \"string\");\n // Old sessions may have saved another Agent's model ID. Skip invalid values and let ACP keep its current model.\n if (!values.length || values.includes(value)) {\n await this.setOption(this.modelConfigId ?? \"model\", value);\n } else {\n log(\"info\", `忽略 ${this.o.binName} 的无效模型:${value}`);\n }\n }\n if (this.o.flavor === \"cursor\" && this.cursorFast && this.currentConfig().some((o) => o.id === \"fast\")) {\n await this.setOption(\"fast\", \"true\");\n }\n await this.applySessionThought(this.o.effort);\n }\n\n private async applyCursorAutoReviewConfig(on: boolean): Promise {\n if (this.o.flavor !== \"cursor\" || !this.ctx || !this.active) return;\n for (const configId of [\"auto_review\", \"autoReview\", \"smart_auto\"]) {\n try {\n await this.ctx.request(methods.agent.session.setConfigOption, {\n sessionId: this.active.sessionId,\n configId,\n type: \"boolean\",\n value: on,\n });\n return;\n } catch {\n /* try the next configId */\n }\n }\n }\n\n /** Cursor only: Fast / Auto-review (can be changed while the session is open) */\n async updateCursorOpts(fast: boolean, autoReview: boolean): Promise {\n this.cursorFast = fast;\n void autoReview; // See the constructor: auto-approval is no longer supported\n await this.ready();\n await this.applySessionModel(this.o.model);\n await this.applyCursorAutoReviewConfig(false);\n }\n\n private waitPerm(requestId: string): Promise {\n return new Promise((resolve) => {\n this.permPending.set(requestId, resolve);\n });\n }\n\n respond(requestId: string, answer: RespondAnswer): void {\n const r = this.permPending.get(requestId);\n if (r) {\n this.permPending.delete(requestId);\n r(answer);\n this.q.push({\n type: \"permission_resolved\",\n requestId,\n optionId: answer.optionId,\n cancelled: answer.cancelled,\n });\n }\n }\n\n async send(input: SendInput): Promise {\n await this.ready();\n if (this.running) throw new Error(\"当前轮次尚未结束\");\n this.turnNum++;\n this.turnId = \"u_\" + Date.now().toString(36) + \"_\" + this.turnNum;\n this.mapCtx = newMapCtx();\n this.running = true;\n this.q.push({\n type: \"turn_started\",\n turnId: this.turnId,\n model: this.o.model,\n mode: this.o.mode,\n effort: this.o.effort,\n });\n const text = input.text.trim();\n const attachments = input.images ?? [];\n if (!text && !attachments.length) {\n this.running = false;\n this.q.push({ type: \"turn_ended\", turnId: this.turnId, status: \"completed\" });\n return;\n }\n // An image-only message is still a prompt: images go as image blocks when the Agent takes them, else by file path\n const built = await buildAcpPrompt(text, attachments, this.promptCaps);\n const agent = this.o.providerName ?? this.o.binName;\n if (built.imagesByPath.length && !this.promptCaps.image) {\n const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel;\n this.q.push({ type: \"notice\", level: \"warn\", message: tr(switched ? \"notice.acpImageByPathSwitched\" : \"notice.acpImageByPath\", { agent, paths: built.imagesByPath.join(\", \") }) });\n }\n for (const w of built.warnings) this.q.push({ type: \"notice\", level: \"warn\", message: tr(\"notice.attachmentIssue\", { detail: w }) });\n if (!built.blocks.length) {\n // Every attachment failed to resolve and there was no text: nothing to send\n this.running = false;\n this.q.push({ type: \"turn_ended\", turnId: this.turnId, status: \"completed\" });\n return;\n }\n void this.runTurn(built.blocks);\n }\n\n // Send this turn's prompt; reading updates is the job of the persistent pumpUpdates() (following Paseo: session/update is handled at session level)\n private async runTurn(prompt: Parameters[0]): Promise {\n this.activeTurnId = this.turnId;\n this.wakePump?.();\n this.wakePump = null;\n this.active!.prompt(prompt).catch(() => {\n /* failures surface through nextUpdate() and pumpUpdates ends the turn */\n });\n }\n\n private endTurn(ev: ProviderEvent): void {\n this.q.push(ev);\n this.activeTurnId = null;\n this.running = false;\n }\n\n /**\n * Read session/update for the whole lifetime of the session.\n * It used to read only during a turn: the available_commands_update an Agent pushes after session/new and before the first message went unread,\n * so the slash menu stayed empty. Now command updates are cached at any time; conversation content becomes timeline events only while a turn is in progress.\n */\n private async pumpUpdates(): Promise {\n const session = this.active;\n if (!session) return;\n while (!this.closed) {\n let msg: Awaited>;\n try {\n msg = await session.nextUpdate();\n } catch (e) {\n if (this.closed) return;\n const turnId = this.activeTurnId;\n if (turnId) {\n this.endTurn({ type: \"turn_ended\", turnId, status: \"failed\", error: String((e as Error)?.message ?? e) });\n }\n // After an error the queue keeps throwing the same error until the next prompt clears it: wait for the next turn before reading again\n await new Promise((r) => (this.wakePump = r));\n continue;\n }\n if (msg.kind === \"session_update\") {\n const u = msg.update;\n if (u.sessionUpdate === \"available_commands_update\") {\n this.applyAvailableCommands(u.availableCommands ?? []);\n continue;\n }\n if (!this.activeTurnId) continue; // Other updates outside a turn (e.g. mode change echoes) don't go to the timeline\n for (const ev of mapSessionUpdate(u, this.mapCtx)) this.q.push(ev);\n } else if (this.activeTurnId) {\n this.endTurn(stopToTurnEnd(msg.stopReason, this.activeTurnId));\n }\n }\n }\n\n async interrupt(): Promise {\n await this.ready();\n if (!this.ctx || !this.active) return;\n try {\n await this.ctx.request(methods.agent.session.cancel, { sessionId: this.active.sessionId });\n } catch (e) {\n log(\"info\", `ACP cancel: ${String(e)}`);\n }\n }\n\n async setModel(model: string | null): Promise {\n this.o.model = model;\n await this.ready();\n if (this.o.imagesFollowStartModel) {\n // dsh answered initialize for the model it started on; another model may not take image blocks (it refuses the prompt)\n this.promptCaps = model === this.startModel ? this.initCaps : { ...this.initCaps, image: false };\n }\n await this.applySessionModel(model);\n }\n\n async setMode(mode: Mode): Promise {\n this.o.mode = mode;\n await this.ready();\n await this.applySessionMode(mode);\n }\n\n async setEffort(effort: string | null): Promise {\n this.o.effort = effort;\n await this.ready();\n await this.applySessionThought(effort);\n }\n\n async listCommands(): Promise {\n try {\n await this.ready();\n } catch {\n return [];\n }\n // Commands are pushed asynchronously after session/new: wait at most 10 s for the first batch (Agents that report none return empty after the timeout)\n if (!this.slashCommands.length) {\n await Promise.race([this.commandsReady, new Promise((r) => setTimeout(r, 10000))]);\n }\n return this.slashCommands;\n }\n\n async close(): Promise {\n this.closed = true;\n this.wakePump?.();\n this.settleCommands();\n for (const r of this.permPending.values()) r({ cancelled: true });\n this.permPending.clear();\n try {\n this.active?.dispose();\n } catch {}\n try {\n this.conn?.close();\n } catch {}\n await killAcpChild(this.child);\n this.child = null;\n this.q.close();\n }\n}\n","import type { Provider, DetectResult, ModelInfo, Capabilities, Mode, LaunchCommand } from \"../types.js\";\nimport { killTree, spawnBin, type ResolveResult } from \"../../util/bin.js\";\nimport { resolveFirstBin } from \"../../util/bin.js\";\nimport { resolveLaunch } from \"../launch.js\";\nimport { PLACEHOLDER_MODEL_NAME } from \"../types.js\";\nimport { AcpSession } from \"./session.js\";\nimport { knownPromptCaps } from \"./promptCaps.js\";\n\nexport type AcpProviderConfig = {\n id: string;\n name: string;\n binName: string;\n /** Takes precedence over binName: detect / listModels / session resolve these in order */\n binCandidates?: string[];\n acpArgs: string[];\n /** Arguments for one session's ACP process from its model (dsh starts on the conversation's route); default acpArgs */\n argsFor?: (model: string | null) => Promise;\n /** The Agent decides at initialize whether it takes images, for the model it started on (dsh): a model picked later sends images by path */\n imagesFollowStartModel?: boolean;\n installHint: string;\n appVersion?: string;\n flavor?: \"cursor\" | \"generic\";\n capabilities?: Capabilities;\n fetchModels?: (r: ResolveResult & { ok: true }, launchArgs?: string[]) => Promise;\n /** Our permission modes → this Agent's mode names over ACP; when given, only modes in the table are shown */\n modeMap?: Partial>;\n /** Mode names shown in the UI (the Agent's own naming) */\n modeLabels?: Partial>;\n};\n\nexport const acpCapabilities: Capabilities = {\n resume: true,\n interrupt: true,\n steer: false,\n images: false,\n plan: true,\n questions: false,\n cost: false,\n effort: [],\n modes: [\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\"],\n deltasOnly: true,\n};\n\nexport const cursorAcpCapabilities: Capabilities = {\n ...acpCapabilities,\n questions: true,\n modes: [\"default\", \"plan\", \"ask\"],\n};\n\nfunction runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 8000): Promise {\n return new Promise((resolvePromise, reject) => {\n let out = \"\";\n const p = spawnBin(r, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"], env: { ...process.env, NO_COLOR: \"1\" } });\n const t = setTimeout(() => {\n try {\n void killTree(p, { graceMs: 500 }); // On Windows a .cmd wrapper must be killed together with its child processes\n } catch {}\n reject(new Error(\"timeout\"));\n }, timeoutMs);\n p.stdout?.on(\"data\", (c: Buffer) => (out += c.toString()));\n p.stderr?.on(\"data\", (c: Buffer) => (out += c.toString()));\n p.on(\"error\", reject);\n p.on(\"close\", (code) => {\n clearTimeout(t);\n if (code === 0 || out.trim()) resolvePromise(out.trim());\n else reject(new Error(\"exit \" + code));\n });\n });\n}\n\nasync function resolveProviderBin(cfg: AcpProviderConfig) {\n const names = cfg.binCandidates?.length ? cfg.binCandidates : [cfg.binName];\n return resolveFirstBin(names);\n}\n\nexport function createAcpProvider(cfg: AcpProviderConfig): Provider {\n const base = cfg.capabilities ?? acpCapabilities;\n // With a mode table, expose only the modes the Agent really has (in our fixed order)\n const ORDER: Mode[] = [\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\"];\n const caps: Capabilities = cfg.modeMap\n ? { ...base, modes: ORDER.filter((m) => cfg.modeMap![m] !== undefined), modeLabels: cfg.modeLabels }\n : base;\n return {\n id: cfg.id,\n name: cfg.name,\n // images is what the Agent's own initialize says (probe at warm-up / providers.list, or any session); until then unknown\n get capabilities(): Capabilities {\n const learned = knownPromptCaps(cfg.id);\n return learned ? { ...caps, images: learned.image, imagesKnown: true } : { ...caps, images: false, imagesKnown: false };\n },\n async detect(launch?: LaunchCommand): Promise {\n const r = launch ? await resolveLaunch(launch) : await resolveProviderBin(cfg);\n if (!r.ok) {\n return { available: false, reason: r.reason, installHint: cfg.installHint };\n }\n let version: string | undefined;\n const versionArgs = cfg.id === \"devin\" ? [\"version\"] : [\"cursor\", \"opencode\"].includes(cfg.id) ? [\"--version\"] : null;\n try {\n if (versionArgs) {\n // Only the internal prefix: the user's extra args are meant for the ACP command, not for --version\n version = (await runVersion(r, [...(launch?.prefixArgs ?? []), ...versionArgs])).split(/\\r?\\n/)[0]?.trim();\n }\n } catch {\n /* Having the binary is enough */\n }\n return { available: true, bin: r.display, version };\n },\n async listModels(launch?: LaunchCommand): Promise {\n const resolved = launch ? await resolveLaunch(launch) : await resolveProviderBin(cfg);\n if (!resolved.ok) return [{ id: \"default\", name: PLACEHOLDER_MODEL_NAME, isDefault: true }];\n // The internal prefix rides on the resolution (fetchModels puts its own ACP args after it), the user's args go last\n const r = launch?.prefixArgs?.length && resolved.via !== \"cmd-shim\"\n ? { ...resolved, prefixArgs: [...resolved.prefixArgs, ...launch.prefixArgs] }\n : resolved;\n if (cfg.fetchModels) return cfg.fetchModels(r, launch?.args ?? []);\n return [{ id: \"default\", name: PLACEHOLDER_MODEL_NAME, isDefault: true }];\n },\n async createSession(o) {\n return new AcpSession({\n threadId: o.threadId,\n providerId: cfg.id,\n providerName: cfg.name,\n cwd: o.cwd,\n model: o.model,\n mode: o.mode,\n effort: o.effort,\n resumeId: o.resumeId,\n binName: cfg.binName,\n binCandidates: cfg.binCandidates ?? [cfg.binName],\n acpArgs: cfg.argsFor ? await cfg.argsFor(o.model) : cfg.acpArgs,\n imagesFollowStartModel: cfg.imagesFollowStartModel,\n appVersion: cfg.appVersion ?? \"0.0.1\",\n flavor: cfg.flavor ?? \"generic\",\n modeMap: cfg.modeMap,\n cursorFast: o.cursorFast,\n cursorAutoReview: o.cursorAutoReview,\n launch: o.launch,\n });\n },\n };\n}\n","// dsh (DeepSeek Harness) over ACP: start it on the model the conversation uses, so it can take images.\n//\n// dsh decides at ACP initialize whether it accepts image blocks, from the route in its `acp` config row\n// (`dsh-acp`'s supportsAcpImagePrompts), not from the session's model. That row ships as\n// deepseek-official / deepseek-v4-flash, which isn't in dsh's own catalog (deepseek-flash is) and isn't a\n// route Magpie writes (Magpie writes `agent-default-model` and its `magpie*` routes, not the `acp` row).\n// So dsh 0.2.1-rc.5 / 0.2.2-alpha.2 answer promptCapabilities.image: false and then refuse every image\n// block (\"inline image prompts were not advertised by this connection\"), even on a model that sees images.\n//\n// The launcher takes `--patch ` overlays, applied after the profile and home patches. We start dsh\n// with one that sets the `acp` row to the conversation's route ([provider, model], the value dsh's ACP model\n// option uses). dsh then advertises image input exactly when that route declares it (a Magpie model it can\n// see images with is written as `input: [text, image]`) and passes the image to the model.\n// A model picked later in the same session goes by path: dsh's read_image tool opens it on a model that sees images.\nimport { createHash } from \"node:crypto\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const DSH_ACP_ARGS = [\"--profile\", \"acp\"];\n\nexport type DshRoute = { provider: string; model: string };\n\n/** dsh's ACP model value is JSON [provider, model]; anything else isn't a route */\nexport function dshRoute(model: string | null | undefined): DshRoute | null {\n if (!model) return null;\n try {\n const v = JSON.parse(model) as unknown;\n if (Array.isArray(v) && v.length === 2 && typeof v[0] === \"string\" && typeof v[1] === \"string\" && v[0] && v[1]) {\n return { provider: v[0], model: v[1] };\n }\n } catch {\n /* not a dsh route */\n }\n return null;\n}\n\n/** The patch list that starts dsh's ACP on this route (JSON strings are valid YAML double-quoted scalars) */\nexport function dshRoutePatch(route: DshRoute): string {\n return [\n \"# Agent Console: the route dsh's ACP starts on, so initialize advertises image input for it\",\n \"- id: acp\",\n \" config:\",\n ` provider: ${JSON.stringify(route.provider)}`,\n ` model: ${JSON.stringify(route.model)}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/** Arguments for `dsh`: the ACP profile, plus a --patch overlay naming the route when the model is one */\nexport async function dshAcpArgs(model: string | null | undefined, dir = join(tmpdir(), \"agent-console-dsh\")): Promise {\n const route = dshRoute(model);\n if (!route) return [...DSH_ACP_ARGS];\n const body = dshRoutePatch(route);\n const file = join(dir, `acp-route-${createHash(\"sha256\").update(body).digest(\"hex\").slice(0, 16)}.yml`);\n await mkdir(dir, { recursive: true });\n await writeFile(file, body, { mode: 0o600 });\n return [...DSH_ACP_ARGS, \"--patch\", file];\n}\n\n/** The route a new dsh conversation starts on, as the manager picks it: a Magpie route first, else dsh's current one */\nexport function dshDefaultModel(models: { id: string }[], current: string | null): string | null {\n return models.find((m) => /magpie/i.test(m.id))?.id ?? current ?? models[0]?.id ?? null;\n}\n","// ACP probe: start the Agent's ACP process once → initialize → session/new, read the models and thinking levels it reports, then close it.\n// Sends no prompt and costs nothing. This is the Agent's own model list (as Paseo does), more reliable than parsing CLI text.\nimport { tmpdir } from \"node:os\";\nimport type { ModelInfo } from \"../types.js\";\nimport type { ResolveResult } from \"../../util/bin.js\";\nimport { spawnResolved, killAcpChild } from \"./spawn.js\";\nimport { log } from \"../../log.js\";\nimport { promptCapsFromInitialize, rememberPromptCaps, type AcpPromptCaps } from \"./promptCaps.js\";\nimport { DSH_ACP_ARGS, dshAcpArgs, dshDefaultModel, dshRoute } from \"./dsh.js\";\n\ntype SelectOption = { value?: unknown; name?: unknown; options?: SelectOption[] };\ntype ConfigOption = { id?: string; category?: string; type?: string; currentValue?: unknown; options?: SelectOption[] };\n\nexport type AcpProbeResult = {\n models: { id: string; name: string }[];\n currentModel: string | null;\n thinking: { id: string; label: string }[];\n currentThinking: string | null;\n};\n\nfunction flatten(opts: SelectOption[] | undefined): { id: string; name: string }[] {\n const out: { id: string; name: string }[] = [];\n for (const o of opts ?? []) {\n if (o.options) out.push(...flatten(o.options));\n else if (typeof o.value === \"string\" && o.value) {\n out.push({ id: o.value, name: typeof o.name === \"string\" && o.name ? o.name : o.value });\n }\n }\n // Dedupe (Copilot reports auto twice)\n return out.filter((m, i) => out.findIndex((x) => x.id === m.id) === i);\n}\n\n/** Extract models and thinking levels from a session/new response (pure function, easy to test) */\nexport function parseAcpSession(res: { configOptions?: ConfigOption[]; models?: { currentModelId?: string; availableModels?: { modelId?: string; name?: string }[] } }): AcpProbeResult {\n const opts = res.configOptions ?? [];\n const modelOpt = opts.find((o) => o.type === \"select\" && (o.category === \"model\" || o.id === \"model\"));\n const thoughtOpt = opts.find((o) => o.type === \"select\" && (o.category === \"thought_level\" || o.id === \"thought_level\"));\n let models = flatten(modelOpt?.options);\n let currentModel = typeof modelOpt?.currentValue === \"string\" ? modelOpt.currentValue : null;\n if (!models.length && res.models?.availableModels?.length) {\n models = res.models.availableModels\n .filter((m) => typeof m.modelId === \"string\" && m.modelId)\n .map((m) => ({ id: m.modelId!, name: m.name || m.modelId! }));\n models = models.filter((m, i) => models.findIndex((x) => x.id === m.id) === i);\n currentModel = res.models.currentModelId ?? currentModel;\n }\n const thinking = flatten(thoughtOpt?.options).map((t) => ({ id: t.id, label: t.name }));\n const currentThinking = typeof thoughtOpt?.currentValue === \"string\" ? thoughtOpt.currentValue : null;\n return { models, currentModel, thinking, currentThinking };\n}\n\n/** providerId: remember what the Agent's initialize advertised for prompts (images) under this id */\nexport function probeAcp(r: ResolveResult & { ok: true }, acpArgs: string[], timeoutMs = 30000, providerId?: string): Promise {\n return probeAcpRaw(r, acpArgs, timeoutMs).then((x) => {\n rememberPromptCaps(providerId, x.promptCaps);\n return x.parsed;\n });\n}\n\n/** Like probeAcp, but also calls an Agent-specific method after session/new (e.g. Cursor's cursor/list_available_models) */\nexport function probeAcpRaw(\n r: ResolveResult & { ok: true },\n acpArgs: string[],\n timeoutMs = 30000,\n extMethod?: string,\n): Promise<{ parsed: AcpProbeResult; ext: unknown; promptCaps: AcpPromptCaps }> {\n return new Promise((resolvePromise, reject) => {\n const child = spawnResolved(r, acpArgs, { cwd: tmpdir() });\n let buf = \"\";\n let nextId = 0;\n const pending = new Map void; rej: (e: Error) => void }>();\n let done = false;\n const finish = (err: Error | null, v?: { parsed: AcpProbeResult; ext: unknown; promptCaps: AcpPromptCaps }) => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n void killAcpChild(child).catch(() => {});\n if (err) reject(err);\n else resolvePromise(v!);\n };\n const timer = setTimeout(() => finish(new Error(\"ACP 探测超时\")), timeoutMs);\n const send = (method: string, params: unknown) =>\n new Promise((res, rej) => {\n const id = ++nextId;\n pending.set(id, { res, rej });\n child.stdin?.write(JSON.stringify({ jsonrpc: \"2.0\", id, method, params }) + \"\\n\");\n });\n child.on(\"error\", (e) => finish(e));\n child.on(\"close\", () => finish(new Error(\"ACP 进程提前退出\")));\n child.stderr?.on(\"data\", () => {});\n child.stdout?.on(\"data\", (d: Buffer) => {\n buf += d.toString();\n let n: number;\n while ((n = buf.indexOf(\"\\n\")) >= 0) {\n const line = buf.slice(0, n).trim();\n buf = buf.slice(n + 1);\n if (!line) continue;\n let m: { id?: number; method?: string; result?: unknown; error?: unknown };\n try {\n m = JSON.parse(line);\n } catch {\n continue;\n }\n if (m.id !== undefined && !m.method && pending.has(m.id)) {\n const p = pending.get(m.id)!;\n pending.delete(m.id);\n if (m.error) p.rej(new Error(JSON.stringify(m.error)));\n else p.res(m.result);\n } else if (m.id !== undefined && m.method) {\n // Requests from the Agent (shouldn't happen during a probe): always answer empty so it doesn't hang\n child.stdin?.write(JSON.stringify({ jsonrpc: \"2.0\", id: m.id, result: null }) + \"\\n\");\n }\n }\n });\n void (async () => {\n try {\n const init = await send(\"initialize\", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: \"Agent Console\", version: \"probe\" } });\n const res = (await send(\"session/new\", { cwd: tmpdir(), mcpServers: [] })) as Parameters[0];\n let ext: unknown = null;\n if (extMethod) ext = await send(extMethod, {}).catch(() => null);\n finish(null, { parsed: parseAcpSession(res ?? {}), ext, promptCaps: promptCapsFromInitialize(init) });\n } catch (e) {\n finish(e instanceof Error ? e : new Error(String(e)));\n }\n })();\n });\n}\n\n/** Probe result → model list: the current model is the default; thinking levels hang on the current model (other models' levels are only known after switching, so reuse the same set for now) */\nexport function probeToModels(p: AcpProbeResult): ModelInfo[] {\n return p.models.map((m) => ({\n id: m.id,\n name: m.name,\n isDefault: m.id === p.currentModel,\n ...(p.thinking.length\n ? { thinkingOptions: p.thinking, defaultThinking: p.currentThinking ?? undefined }\n : {}),\n }));\n}\n\nconst EFFORT_LABEL: Record = {\n none: \"None\", minimal: \"Minimal\", low: \"Low\", medium: \"Medium\", high: \"High\", xhigh: \"Extra High\", max: \"Max\",\n};\n\ntype CursorCatalog = {\n models?: { value?: string; name?: string; configOptions?: ConfigOption[] }[];\n};\n\n/**\n * Cursor: a model's thinking levels are not in the session-level thought_level but in each model's own parameter (effort / reasoning_effort / reasoning).\n * Following Paseo's resolveCursorCatalogModels: call Cursor's extension method cursor/list_available_models to get each model's parameter definitions.\n * The model id is the base name without parameters (grok-4.6); thinkingParam records the level parameter name, sent as grok-4.6[effort=high].\n */\nexport function cursorCatalogToModels(catalog: CursorCatalog, currentModel: string | null): ModelInfo[] {\n const currentBase = currentModel?.replace(/\\[.*\\]$/u, \"\") ?? null;\n const out: ModelInfo[] = [];\n for (const m of catalog.models ?? []) {\n if (typeof m.value !== \"string\" || !m.value) continue;\n const id = m.value.replace(/\\[.*\\]$/u, \"\");\n const thought = (m.configOptions ?? []).find((o) => o.category === \"thought_level\");\n const levels = flatten(thought?.options);\n out.push({\n id,\n name: typeof m.name === \"string\" && m.name ? m.name : id,\n isDefault: id === currentBase,\n ...(thought && levels.length\n ? {\n thinkingOptions: levels.map((l) => ({ id: l.id, label: EFFORT_LABEL[l.id] ?? l.name })),\n defaultThinking: typeof thought.currentValue === \"string\" ? thought.currentValue : undefined,\n thinkingParam: thought.id,\n }\n : {}),\n });\n }\n return out;\n}\n\nexport function cursorProbeModels(acpArgs: string[], providerId?: string) {\n return async (r: ResolveResult & { ok: true }, launchArgs: string[] = []): Promise => {\n try {\n const { parsed, ext, promptCaps } = await probeAcpRaw(r, [...acpArgs, ...launchArgs], 40000, \"cursor/list_available_models\");\n rememberPromptCaps(providerId, promptCaps);\n const fromCatalog = ext ? cursorCatalogToModels(ext as CursorCatalog, parsed.currentModel) : [];\n // If the extension method is unavailable (older Cursor CLI), fall back to the model list reported by the session (no levels)\n return fromCatalog.length ? fromCatalog : probeToModels(parsed);\n } catch (e) {\n log(\"warn\", \"Cursor 模型探测失败\", { err: String(e) });\n return [];\n }\n };\n}\n\n/**\n * dsh: the model list from a plain `dsh --profile acp`, then whether it takes images from an initialize started on the\n * route a new conversation uses (dsh answers for the route it starts on, see dsh.ts).\n */\nexport function dshProbeModels(providerId?: string) {\n return async (r: ResolveResult & { ok: true }, launchArgs: string[] = []): Promise => {\n try {\n const first = await probeAcpRaw(r, [...DSH_ACP_ARGS, ...launchArgs], 30000);\n let caps = first.promptCaps;\n const start = dshDefaultModel(first.parsed.models, first.parsed.currentModel);\n if (start && start !== first.parsed.currentModel && dshRoute(start)) {\n caps = await probeAcpRaw(r, [...await dshAcpArgs(start), ...launchArgs], 30000).then((x) => x.promptCaps, () => caps);\n }\n rememberPromptCaps(providerId, caps);\n return probeToModels(first.parsed);\n } catch (e) {\n log(\"warn\", \"ACP 探测模型失败\", { err: String(e) });\n return [];\n }\n };\n}\n\nexport function acpProbeModels(acpArgs: string[], providerId?: string) {\n return async (r: ResolveResult & { ok: true }, launchArgs: string[] = []): Promise => {\n try {\n return probeToModels(await probeAcp(r, [...acpArgs, ...launchArgs], 30000, providerId));\n } catch (e) {\n log(\"warn\", \"ACP 探测模型失败\", { err: String(e) });\n return [];\n }\n };\n}\n","import type { ProviderCatalogEntry } from \"../catalog.js\";\nimport type { AcpProviderConfig } from \"./provider.js\";\nimport { cursorAcpCapabilities } from \"./provider.js\";\nimport { acpProbeModels, cursorProbeModels, dshProbeModels } from \"./probe.js\";\nimport { DSH_ACP_ARGS, dshAcpArgs } from \"./dsh.js\";\n\nconst ACP_IDS = new Set([\"cursor\", \"devin\", \"opencode\", \"dsh\", \"pi\", \"copilot\"]);\n\nexport function isAcpCatalogId(id: string): boolean {\n return ACP_IDS.has(id);\n}\n\n// Model lists and thinking levels always come from what the Agent reports over ACP (acpProbeModels), no longer from parsing each CLI's text output.\n// modeMap: our permission modes → the Agent's real mode names (from what session/new actually reports); \"\" means keep the entry but send nothing.\nexport function acpConfigForEntry(entry: ProviderCatalogEntry, appVersion: string): AcpProviderConfig | null {\n if (!ACP_IDS.has(entry.id)) return null;\n const base: Omit = {\n id: entry.id,\n name: entry.name,\n binName: entry.bins[0] ?? entry.id,\n binCandidates: entry.bins,\n installHint: entry.installHint,\n appVersion,\n };\n\n switch (entry.id) {\n case \"cursor\":\n // Modes: agent / plan / ask (see cursorAcpCapabilities)\n return {\n ...base,\n acpArgs: [\"acp\"],\n flavor: \"cursor\",\n capabilities: cursorAcpCapabilities,\n // Each model's own thinking levels come from cursor/list_available_models (as Paseo does)\n fetchModels: cursorProbeModels([\"acp\"], entry.id),\n };\n case \"devin\":\n // Modes: Code(accept-edits) / Smart / Ask / Plan / Bypass Permissions\n return {\n ...base,\n acpArgs: [\"acp\"],\n fetchModels: acpProbeModels([\"acp\"], entry.id),\n modeMap: { plan: \"plan\", default: \"ask\", acceptEdits: \"accept-edits\", bypassPermissions: \"bypass\" },\n modeLabels: { plan: \"Plan\", default: \"Ask\", acceptEdits: \"Code\", bypassPermissions: \"Bypass Permissions\" },\n };\n case \"opencode\":\n // Modes: build / plan; thinking level effort (low…ultra, including fast variants)\n return {\n ...base,\n acpArgs: [\"acp\"],\n fetchModels: acpProbeModels([\"acp\"], entry.id),\n modeMap: { plan: \"plan\", default: \"build\" },\n modeLabels: { plan: \"Plan\", default: \"Build\" },\n };\n case \"copilot\":\n // As Paseo: Agent / Plan / Allow All. Allow All = agent mode + allow_all config on (autopilot is not used)\n return {\n ...base,\n acpArgs: [\"--acp\"],\n fetchModels: acpProbeModels([\"--acp\"], entry.id),\n modeMap: { plan: \"plan\", default: \"agent\", bypassPermissions: \"allow-all\" },\n modeLabels: { plan: \"Plan\", default: \"Agent\", bypassPermissions: \"Allow All\" },\n };\n case \"pi\":\n // pi-acp has no mode options; thinking level thought_level (low…max)\n return { ...base, acpArgs: [], fetchModels: acpProbeModels([], entry.id), modeMap: { default: \"\" } };\n case \"dsh\":\n // Started on the conversation's route (--patch), so its initialize advertises image input for that model (see dsh.ts)\n return {\n ...base,\n acpArgs: DSH_ACP_ARGS,\n argsFor: (model) => dshAcpArgs(model),\n imagesFollowStartModel: true,\n fetchModels: dshProbeModels(entry.id),\n };\n default:\n return null;\n }\n}\n","// Provider registry: 8 in the catalog; claude/codex native, the rest over ACP (including copilot --acp).\nimport type { Provider } from \"./types.js\";\nimport { createMockProvider } from \"./mock.js\";\nimport { createClaudeProvider } from \"./claude/provider.js\";\nimport { createCodexProvider } from \"./codex/provider.js\";\nimport { PROVIDER_CATALOG } from \"./catalog.js\";\nimport { createAcpProvider } from \"./acp/provider.js\";\nimport { acpConfigForEntry } from \"./acp/specs.js\";\n\nconst providers = new Map();\n\nexport function registerProvider(p: Provider): void {\n providers.set(p.id, p);\n}\n\nexport function getProvider(id: string): Provider | undefined {\n return providers.get(id);\n}\n\nexport function listProviders(): Provider[] {\n return [...providers.values()];\n}\n\nexport function initProviders(version: string = \"\"): void {\n providers.clear();\n for (const entry of PROVIDER_CATALOG) {\n if (entry.id === \"claude\") registerProvider(createClaudeProvider());\n else if (entry.id === \"codex\") registerProvider(createCodexProvider(version));\n else {\n const acp = acpConfigForEntry(entry, version);\n if (acp) registerProvider(createAcpProvider(acp));\n }\n }\n if (process.env.AGENT_CONSOLE_MOCK === \"1\") {\n registerProvider(createMockProvider());\n }\n}\n","// Whether the user enabled this Provider in settings.\n// Never toggled by hand: catalog status=verified is on by default, others off; entries outside the catalog (mock etc.) are on.\nimport type { Settings } from \"../store/settings.js\";\nimport { catalogById } from \"./catalog.js\";\n\nexport function isProviderEnabled(settings: Settings, id: string): boolean {\n const m = settings.providerEnabled;\n if (m && typeof m === \"object\" && typeof m[id] === \"boolean\") return m[id];\n const entry = catalogById(id);\n if (!entry) return true;\n return entry.status === \"verified\";\n}\n","import { execFile } from \"node:child_process\";\n\n/** Parse PowerShell stdout into a folder path (handles Base64 and CP936 consoles) */\nexport function decodePickFolderStdout(stdout: string | Buffer): string | null {\n const buf = Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout, \"utf8\");\n const line = buf.toString(\"utf8\").trim().split(/\\r?\\n/).pop()?.trim() ?? \"\";\n if (!line) return null;\n\n // New format: Base64 of the UTF-8 path, so a GBK-encoded Chinese Windows console isn't garbled when Node decodes it as UTF-8\n if (/^[A-Za-z0-9+/]+=*$/.test(line)) {\n const decoded = Buffer.from(line, \"base64\").toString(\"utf8\");\n if (decoded && !decoded.includes(\"\\uFFFD\")) return decoded;\n }\n\n if (!line.includes(\"\\uFFFD\")) return line;\n\n const gbkLine = new TextDecoder(\"gbk\").decode(buf).trim().split(/\\r?\\n/).pop()?.trim() ?? \"\";\n return gbkLine || null;\n}\n\nexport function pickFolderWindows(initial?: string): Promise<{ available: boolean; path: string | null }> {\n return new Promise((resolvePromise) => {\n if (process.platform !== \"win32\") return resolvePromise({ available: false, path: null });\n const init = (initial ?? \"\").replace(/'/g, \"''\");\n const script =\n \"Add-Type -AssemblyName System.Windows.Forms;\" +\n \"$d = New-Object System.Windows.Forms.FolderBrowserDialog;\" +\n \"$d.Description = '选择项目文件夹';\" +\n \"$d.ShowNewFolderButton = $true;\" +\n (init ? `$d.SelectedPath = '${init}';` : \"\") +\n \"if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { \" +\n \"[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($d.SelectedPath)) \" +\n \"}\";\n execFile(\n \"powershell.exe\",\n [\"-NoProfile\", \"-STA\", \"-NonInteractive\", \"-Command\", script],\n { timeout: 120000, windowsHide: false, encoding: \"buffer\" },\n (e, stdout) => {\n if (e) return resolvePromise({ available: true, path: null });\n resolvePromise({ available: true, path: decodePickFolderStdout(stdout ?? Buffer.alloc(0)) });\n },\n );\n });\n}\n","// Native folder picker: Windows uses PowerShell FolderBrowserDialog (pickFolderWin.ts),\n// macOS osascript's choose folder, Linux zenity / kdialog when present; with none, report unavailable and the frontend falls back to typing.\n// Everything starts processes directly via execFile, no shell; the initial directory is passed only as an argument or an escaped AppleScript string.\nimport { execFile } from \"node:child_process\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { findOnPath } from \"../../../lib/pathscan.mjs\";\nimport { pickFolderWindows } from \"./pickFolderWin.js\";\n\nexport type PickResult = { available: boolean; path: string | null };\nconst TIMEOUT = 10 * 60 * 1000; // The user may keep the dialog open for a while\n\n/** AppleScript string literal: only backslashes and double quotes need escaping. */\nexport function appleScriptString(s: string): string {\n return '\"' + s.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"') + '\"';\n}\n\nfunction isDir(p: string | undefined): p is string {\n try {\n return !!p && existsSync(p) && statSync(p).isDirectory();\n } catch {\n return false;\n }\n}\n\n/** Command-line arguments (for testability). Returns null when the platform has no picker. */\nexport function pickFolderCommand(\n platform: NodeJS.Platform,\n initial: string | undefined,\n find: (name: string) => string | null = (n) => findOnPath(n)[0] ?? null,\n env: NodeJS.ProcessEnv = process.env,\n): { cmd: string; args: string[] } | null {\n const init = isDir(initial) ? initial : undefined;\n if (platform === \"darwin\") {\n const prompt = appleScriptString(\"选择项目文件夹 / Choose a project folder\");\n const loc = init ? ` default location (POSIX file ${appleScriptString(init)})` : \"\";\n return { cmd: \"/usr/bin/osascript\", args: [\"-e\", `POSIX path of (choose folder with prompt ${prompt}${loc})`] };\n }\n if (platform === \"linux\" || platform === \"freebsd\" || platform === \"openbsd\") {\n // No graphical session (magpie web on a server): no window can open, so the frontend asks for a typed path\n if (!env.DISPLAY && !env.WAYLAND_DISPLAY) return null;\n const zenity = find(\"zenity\");\n if (zenity) {\n const args = [\"--file-selection\", \"--directory\", \"--title=选择项目文件夹 / Choose a project folder\"];\n if (init) args.push(`--filename=${init.endsWith(\"/\") ? init : init + \"/\"}`);\n return { cmd: zenity, args };\n }\n const kdialog = find(\"kdialog\");\n if (kdialog) return { cmd: kdialog, args: [\"--getexistingdirectory\", init ?? env.HOME ?? \"/\"] };\n }\n return null;\n}\n\nexport function pickFolder(initial?: string): Promise {\n if (process.platform === \"win32\") return pickFolderWindows(initial);\n const c = pickFolderCommand(process.platform, initial);\n if (!c) return Promise.resolve({ available: false, path: null });\n return new Promise((resolvePromise) => {\n execFile(c.cmd, c.args, { timeout: TIMEOUT, encoding: \"utf8\" }, (e, stdout) => {\n // Cancel: osascript / zenity / kdialog all exit non-zero\n if (e) return resolvePromise({ available: true, path: null });\n let p = String(stdout ?? \"\").replace(/\\r?\\n$/, \"\").trim();\n // osascript's POSIX path ends with / (except for the root)\n if (p.length > 1) p = p.replace(/\\/+$/, \"\");\n resolvePromise({ available: true, path: p || null });\n }).on(\"error\", () => resolvePromise({ available: false, path: null }));\n });\n}\n","// magpie gateway: magpie points each Agent's models at the local gateway (applied.json records the model currently applied to each).\n// Here we fill in, for those Agents, the model list, the default model and each model's thinking levels. Read-only; no configuration is changed.\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { ModelInfo } from \"./types.js\";\nimport { log } from \"../log.js\";\n\n/** Agent Console provider id → the key in magpie's applied.json + the model id prefix used inside that Agent */\nconst MAGPIE_TOOLS: Record = {\n claude: { key: \"claude\", prefix: \"\" },\n codex: { key: \"codex\", prefix: \"\" },\n opencode: { key: \"opencode\", prefix: \"magpie/\" },\n pi: { key: \"pi\", prefix: \"magpie/\" },\n dsh: { key: \"dsh\", prefix: \"magpie/\" },\n};\n\nconst EFFORT_LABEL: Record = {\n low: \"Low\", medium: \"Medium\", high: \"High\", xhigh: \"Extra High\", max: \"Max\",\n};\n\ntype Applied = Record;\n\nasync function readJson(path: string): Promise {\n try {\n return JSON.parse(await readFile(path, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n\nasync function readApplied(): Promise {\n return (await readJson(join(homedir(), \".config\", \"magpie\", \"applied.json\"))) ?? {};\n}\n\nasync function readClaudeEnv(): Promise> {\n const s = await readJson<{ env?: Record }>(join(homedir(), \".claude\", \"settings.json\"));\n return s?.env ?? {};\n}\n\n/** Gateway address: ANTHROPIC_BASE_URL from the Claude config (written by magpie), otherwise the default 3425 */\nasync function gatewayBase(): Promise {\n const env = await readClaudeEnv();\n const raw = env.ANTHROPIC_BASE_URL?.trim();\n return (raw && /^https?:\\/\\/(127\\.0\\.0\\.1|localhost)(:\\d+)?/i.test(raw) ? raw : \"http://127.0.0.1:3425\").replace(/\\/+$/, \"\");\n}\n\nasync function fetchGatewayModelIds(): Promise {\n const base = await gatewayBase();\n try {\n const res = await fetch(`${base}/v1/models`, { signal: AbortSignal.timeout(5000) });\n if (!res.ok) return [];\n const j = (await res.json()) as { data?: { id?: unknown }[] };\n return (j.data ?? []).map((m) => m.id).filter((id): id is string => typeof id === \"string\" && !!id);\n } catch (e) {\n log(\"warn\", \"读取 magpie 网关模型列表失败\", { err: String(e) });\n return [];\n }\n}\n\n/** CLAUDE_CODE_MODEL_CAPABILITIES: `id=effort,xhigh_effort,max_effort;id2=effort` → each model's levels */\nexport function parseCapabilities(raw: string | undefined): Map {\n const out = new Map();\n for (const part of (raw ?? \"\").split(\";\")) {\n const i = part.indexOf(\"=\");\n if (i <= 0) continue;\n const flags = new Set(part.slice(i + 1).split(\",\").map((s) => s.trim()));\n if (!flags.has(\"effort\")) continue;\n const levels = [\"low\", \"medium\", \"high\"];\n if (flags.has(\"xhigh_effort\")) levels.push(\"xhigh\");\n if (flags.has(\"max_effort\")) levels.push(\"max\");\n out.set(part.slice(0, i).trim(), levels);\n }\n return out;\n}\n\nfunction isPlaceholder(m: ModelInfo): boolean {\n return !m.id || /^(default|auto)$/i.test(m.id);\n}\n\n/**\n * Fill in model info for Agents managed by magpie; if magpie doesn't manage this Agent (not in applied.json) return it unchanged.\n * - The Agent's own list knows magpie models (e.g. OpenCode, Codex): keep its list with magpie's first (only what it knows, so picks never fail)\n * - The Agent can't report models (Claude, Pi, dsh): use the gateway's /v1/models with the prefix that Agent uses\n * - Default model = the model magpie currently applies to it; thinking levels from magpie's capability table\n */\nexport async function withMagpie(providerId: string, own: ModelInfo[]): Promise {\n const tool = MAGPIE_TOOLS[providerId];\n if (!tool) return own;\n const applied = (await readApplied())[tool.key]?.fields;\n if (!applied?.model) return own;\n\n const caps = parseCapabilities((await readClaudeEnv()).CLAUDE_CODE_MODEL_CAPABILITIES);\n const real = own.filter((m) => !isPlaceholder(m));\n\n // Over ACP, DSH returns its own real model IDs (JSON-array strings).\n // We must not push an old / another Agent's model ID from applied.json into DSH,\n // otherwise DSH treats it as a routed model and sends it to the wrong provider.\n if (providerId === \"dsh\") {\n const appliedId = applied.model.replace(/^magpie\\//, \"\");\n const selected = real.find((m) =>\n m.id === applied.model ||\n m.id === appliedId ||\n (appliedId.includes(\"/\") && m.id.includes(appliedId)),\n );\n const fallback = selected ?? real.find((m) => m.isDefault) ?? real[0];\n return real.map((m) => ({ ...m, isDefault: m.id === fallback?.id }));\n }\n\n const knowsMagpie = tool.prefix ? real.some((m) => m.id.startsWith(tool.prefix)) : real.length > 0;\n\n let list: ModelInfo[];\n if (knowsMagpie) {\n const mine = real.filter((m) => !tool.prefix || m.id.startsWith(tool.prefix));\n const others = tool.prefix ? real.filter((m) => !m.id.startsWith(tool.prefix)) : [];\n list = [...mine, ...others];\n } else {\n list = (await fetchGatewayModelIds()).map((gid) => ({ id: tool.prefix + gid, name: gid }));\n }\n\n // Default model = the one magpie currently applies; if it's not in the list, add it at the top\n const defId = applied.model;\n if (!list.some((m) => m.id === defId)) list.unshift({ id: defId, name: defId.slice(tool.prefix.length) || defId });\n list = list.map((m) => ({ ...m, isDefault: m.id === defId }));\n list.sort((a, b) => Number(!!b.isDefault) - Number(!!a.isDefault));\n\n // Thinking levels: use the Agent's own if it reports them, otherwise magpie's capability table\n return list.map((m) => {\n const name = tool.prefix && m.name.startsWith(tool.prefix) ? m.name.slice(tool.prefix.length) : m.name;\n if (m.thinkingOptions?.length && providerId !== \"claude\") return { ...m, name };\n const levels = caps.get(m.id.slice(tool.prefix.length) || m.id);\n if (!levels) return { ...m, name, thinkingOptions: providerId === \"claude\" ? [] : m.thinkingOptions };\n const def = applied.effort && levels.includes(applied.effort) ? applied.effort : levels.includes(\"high\") ? \"high\" : levels[0];\n return {\n ...m,\n name,\n thinkingOptions: levels.map((id) => ({ id, label: EFFORT_LABEL[id] ?? id })),\n defaultThinking: m.isDefault ? def : m.defaultThinking ?? def,\n };\n });\n}\n","// In-memory cache of Provider detection results and model lists.\n// detect / listModels often have to start a CLI (seconds); without a cache every page open and model pick would wait.\nimport type { Provider, DetectResult, ModelInfo, LaunchCommand } from \"./types.js\";\nimport { PLACEHOLDER_MODEL_NAME } from \"./types.js\";\nimport { withMagpie } from \"./magpieGateway.js\";\nimport { launchKey } from \"./launch.js\";\nimport { tr } from \"../util/i18n.js\";\n\n\nconst DETECT_MS = 60 * 1000;\nconst MODELS_MS = 10 * 60 * 1000;\nconst STEP_TIMEOUT_MS = 15000;\n// Fetching models may start an ACP session (Cursor launches slowly through PowerShell), so it gets a longer timeout\nconst MODELS_TIMEOUT_MS = 35000;\n\ntype Entry = { at: number; value: T } | undefined;\nconst detects = new Map>();\nconst models = new Map>();\n// Concurrent requests for the same Provider share one in-flight detection\nconst inflightDetect = new Map>();\nconst inflightModels = new Map>();\n\nfunction withTimeout(p: Promise, ms: number, fb: T): Promise {\n return Promise.race([p, new Promise((r) => setTimeout(() => r(fb), ms))]);\n}\n\nfunction fresh(e: Entry, ttl: number): e is { at: number; value: T } {\n return !!e && Date.now() - e.at < ttl;\n}\n\nfunction cacheKey(p: Provider, launch?: LaunchCommand): string {\n return launch ? `${p.id}\\0${launchKey(launch)}` : p.id;\n}\n\nexport async function cachedDetect(p: Provider, launch?: LaunchCommand): Promise {\n const key = cacheKey(p, launch);\n const hit = detects.get(key);\n if (fresh(hit, DETECT_MS)) return hit.value;\n let job = inflightDetect.get(key);\n if (!job) {\n const timedOut: DetectResult = { available: false, reason: tr(\"provider.timeout\") };\n job = withTimeout(\n p.detect(launch).catch((e): DetectResult => ({ available: false, reason: String((e as Error)?.message ?? e) })),\n STEP_TIMEOUT_MS,\n timedOut,\n ).then((v) => {\n // Don't cache a timeout; try again next time\n if (v !== timedOut) detects.set(key, { at: Date.now(), value: v });\n return v;\n }).finally(() => inflightDetect.delete(key));\n inflightDetect.set(key, job);\n }\n return job;\n}\n\nexport async function cachedModels(p: Provider, launch?: LaunchCommand): Promise {\n const key = cacheKey(p, launch);\n const hit = models.get(key);\n if (fresh(hit, MODELS_MS)) return hit.value;\n let job = inflightModels.get(key);\n if (!job) {\n job = withTimeout(p.listModels(launch).catch(() => []), MODELS_TIMEOUT_MS, null)\n .then(async (v) => {\n // Timeout: don't cache, fall back to the old value for now\n if (v === null) return models.get(key)?.value ?? [];\n // Agents behind the magpie gateway: fill in gateway models, the default model and thinking levels\n const list = await withMagpie(p.id, dropPlaceholder(v)).catch(() => dropPlaceholder(v));\n models.set(key, { at: Date.now(), value: list });\n return list;\n })\n .finally(() => inflightModels.delete(key));\n inflightModels.set(key, job);\n }\n return job;\n}\n\n/** A list holding only our own \"Default\" placeholder (id=default, name \"默认\") counts as having no real models.\n * An auto / Auto the Agent itself reports (e.g. Copilot) is a real option and is kept. */\nexport function dropPlaceholder(list: ModelInfo[]): ModelInfo[] {\n if (list.length === 1 && list[0].id === \"default\" && (list[0].name === \"默认\" || list[0].name === PLACEHOLDER_MODEL_NAME)) return [];\n return list;\n}\n\n/** Return the cached value immediately if there is one (may be stale), else undefined */\nexport function peekModels(id: string): ModelInfo[] | undefined {\n return models.get(id)?.value;\n}\n\nexport function clearProviderCache(id?: string): void {\n if (id) {\n for (const m of [detects, models] as Map[]) {\n for (const k of [...m.keys()]) if (k === id || k.startsWith(id + \"\\0\")) m.delete(k);\n }\n } else {\n detects.clear();\n models.clear();\n }\n}\n","import type { Mode } from \"./types.js\";\n\n/** Map a permission mode onto an Agent's modes: kept when it has it, else that Agent's \"default\", else its first mode. */\nexport function clampMode(modes: Mode[], mode: Mode | null | undefined): Mode {\n if (mode && modes.includes(mode)) return mode;\n if (modes.includes(\"default\")) return \"default\";\n return modes[0] ?? \"default\";\n}\n","// Method registry: zod-validated params → call the service → return. P0-5 skeleton; filled in from P1 on.\nimport { z } from \"zod\";\nimport type { Gateway, ConnCtx } from \"./gateway.js\";\nimport type { Config } from \"../config.js\";\nimport type { SettingsStore, Settings } from \"../store/settings.js\";\nimport { parseSettingsPatch } from \"../store/settings.js\";\nimport type { ProjectsStore } from \"../store/projects.js\";\nimport type { ThreadsStore } from \"../store/threads.js\";\nimport { listProviders, getProvider } from \"../providers/registry.js\";\nimport { PROVIDER_CATALOG, catalogById, providerCreatable } from \"../providers/catalog.js\";\nimport { isProviderEnabled } from \"../providers/enabled.js\";\nimport type { SlashCommand } from \"../providers/types.js\";\nimport { GitService } from \"../git/service.js\";\nimport { FileService } from \"../files/service.js\";\nimport type { TerminalService } from \"../terminal/service.js\";\nimport { existsSync, statSync } from \"node:fs\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, win32 as win32Path } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { pickFolder } from \"../util/pickFolder.js\";\nimport { clearBinCache } from \"../util/bin.js\";\nimport { cachedDetect, cachedModels, clearProviderCache } from \"../providers/infoCache.js\";\nimport { launchFromSettings } from \"../providers/launch.js\";\nimport { clampMode } from \"../providers/modes.js\";\nimport { tr, intlLocale } from \"../util/i18n.js\";\n\nconst threadModeSchema = z.enum([\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\", \"ask\"]);\n\nexport type Services = {\n cfg: Config;\n settings: SettingsStore;\n gateway: Gateway;\n projects: ProjectsStore;\n threads: ThreadsStore;\n git: GitService;\n files: FileService;\n terminals: TerminalService;\n // AgentManager provides runtime info once wired in at P1-4; may be empty (no session started)\n runtime?: (threadId: string) => { status: string; queue: unknown[]; pending: unknown[] } | null;\n manager?: {\n send(threadId: string, input: { text: string; attachments?: { path: string; mime: string; name?: string }[] }, behavior?: \"queue\" | \"steer\"): Promise<\"started\" | \"steered\" | \"queued\" | void>;\n interrupt(threadId: string): Promise;\n respond(threadId: string, requestId: string, answer: { optionId?: string; answers?: Record; cancelled?: boolean }): Promise;\n setModel(threadId: string, model: string | null): Promise;\n setMode(threadId: string, mode: \"plan\" | \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"ask\"): Promise;\n setEffort(threadId: string, effort: string | null): Promise;\n setCursorOpts(threadId: string, patch: { cursorFast?: boolean; cursorAutoReview?: boolean }): Promise;\n setProvider(threadId: string, providerId: string): Promise;\n close(threadId: string): Promise;\n deleteThread(threadId: string): Promise;\n listCommands(threadId: string, opts?: { load?: boolean }): Promise;\n removeQueued(threadId: string, queueId: string): boolean;\n };\n};\n\nexport class ApiError extends Error {\n code: string;\n constructor(code: string, message: string) {\n super(message);\n this.code = code;\n }\n}\n\nfunction wrap(schema: T, fn: (p: z.infer, ctx: ConnCtx) => unknown) {\n return (params: unknown, ctx: ConnCtx) => {\n const r = schema.safeParse(params ?? {});\n if (!r.success) {\n throw new ApiError(\"bad_params\", tr(\"err.badParams\", { detail: r.error.issues.map((i) => i.message).join(\"; \") }));\n }\n return fn(r.data, ctx);\n };\n}\n\nexport function registerMethods(gw: Gateway, svc: Services): void {\n const zEmpty = z.object({}).passthrough().optional();\n\n gw.method(\"app.info\", wrap(zEmpty, () => ({\n version: svc.cfg.version,\n dataDir: svc.cfg.dataDir,\n pid: process.pid,\n port: svc.cfg.port,\n })));\n\n gw.method(\"app.shutdown\", wrap(zEmpty, () => {\n setTimeout(() => process.exit(0), 100);\n return { ok: true };\n }));\n\n gw.method(\"settings.get\", wrap(zEmpty, () => svc.settings.get()));\n\n gw.method(\"settings.set\", wrap(z.object({ patch: z.record(z.string(), z.unknown()) }), async (p) => {\n const checked = parseSettingsPatch(p.patch);\n if (!checked.ok) throw new ApiError(\"bad_params\", `Invalid setting: ${checked.error}`);\n const before = await svc.settings.get();\n const next = await svc.settings.set(checked.patch as Partial);\n // A changed launch command only invalidates that Agent's detection / model cache (B2: toggling never wipes the rest)\n for (const id of Object.keys(checked.patch.providerCommand ?? {})) {\n if (JSON.stringify(before.providerCommand?.[id] ?? null) !== JSON.stringify(next.providerCommand?.[id] ?? null)) {\n clearProviderCache(id);\n }\n }\n return next;\n }));\n\n gw.method(\"sub.add\", wrap(\n z.object({ ch: z.string().min(1).max(120), afterSeq: z.number().int().nonnegative().optional() }),\n async (p, ctx) => {\n svc.gateway.subscribe(ctx.conn, p.ch);\n // The thread: channel replays persisted events after afterSeq (late subscribers / reconnects lose nothing)\n const m = /^thread:(.+)$/.exec(p.ch);\n if (m && p.afterSeq != null) {\n const events = await svc.threads.readEvents(m[1], p.afterSeq, 5000).catch(() => []);\n for (const ev of events) ctx.conn.send({ t: \"evt\", ch: p.ch, d: { type: \"event\", event: ev } });\n }\n return { ok: true };\n }\n ));\n\n gw.method(\"sub.remove\", wrap(z.object({ ch: z.string().min(1).max(120) }), (p, ctx) => {\n svc.gateway.unsubscribe(ctx.conn, p.ch);\n return { ok: true };\n }));\n\n // ---- providers.list (§6): detection + model list + capabilities ----\n // detect/listModels in parallel; 8s total per provider (listModels may start a temporary process).\n gw.method(\"providers.list\", wrap(\n z.object({ refresh: z.boolean().optional() }).passthrough().optional(),\n async (p) => {\n if (p?.refresh) {\n clearBinCache();\n clearProviderCache();\n }\n const settings = await svc.settings.get();\n const rows = await Promise.all(\n listProviders().map(async (p) => {\n const entry = catalogById(p.id);\n const enabled = isProviderEnabled(settings, p.id);\n const launch = launchFromSettings(settings, p.id);\n // Disabled / not-integrated ones are neither detected nor asked for models (saves seconds of CLI startup)\n const skip = !enabled || entry?.status === \"planned\";\n const det: import(\"../providers/types.js\").DetectResult = skip\n ? { available: false, reason: !enabled ? tr(\"provider.disabled\") : tr(\"provider.planned\") }\n : await cachedDetect(p, launch);\n const models = !skip && det.available ? await cachedModels(p, launch) : [];\n return {\n id: p.id,\n name: p.name,\n available: det.available,\n enabled,\n status: entry?.status ?? \"verified\",\n ready: entry?.status === \"verified\",\n bin: det.bin,\n version: det.version,\n reason: !enabled ? tr(\"provider.disabled\") : det.reason,\n installHint: det.installHint,\n capabilities: p.capabilities,\n models,\n };\n }),\n );\n const byId = new Map(rows.map((r) => [r.id, r]));\n const ordered = PROVIDER_CATALOG.map((e) => byId.get(e.id)).filter(Boolean) as typeof rows;\n for (const r of rows) {\n if (!PROVIDER_CATALOG.some((e) => e.id === r.id)) ordered.push(r);\n }\n return ordered;\n }\n ));\n\n // ---- projects.* ----\n gw.method(\"projects.list\", wrap(zEmpty, () => svc.projects.list()));\n\n gw.method(\"projects.create\", wrap(\n z.object({ path: z.string().min(1), name: z.string().optional() }),\n async (p) => {\n const proj = await svc.projects.create(p.path, p.name);\n // Record recent directories (deduped, case-insensitive, at most 12)\n const s = await svc.settings.get();\n const dirs = (s.recentDirs ?? []).filter((d) => d.toLowerCase() !== p.path.toLowerCase());\n await svc.settings.set({ recentDirs: [p.path, ...dirs].slice(0, 12) });\n gw.publish(\"sidebar\", { type: \"project.upsert\", project: proj });\n return proj;\n }\n ));\n\n gw.method(\"projects.rename\", wrap(z.object({ id: z.string(), name: z.string() }), async (p) => {\n const proj = await svc.projects.rename(p.id, p.name);\n gw.publish(\"sidebar\", { type: \"project.upsert\", project: proj });\n return proj;\n }));\n\n gw.method(\"projects.remove\", wrap(z.object({ id: z.string() }), async (p) => {\n const proj = await svc.projects.get(p.id);\n if (!proj) throw new ApiError(\"not_found\", tr(\"err.projectMissing\"));\n // Move all of the project's conversations to the trash\n for (const t of await svc.threads.list()) {\n if (t.projectId === p.id) {\n await svc.threads.delete(t.id);\n gw.publish(\"sidebar\", { type: \"thread.remove\", id: t.id });\n }\n }\n await svc.projects.remove(p.id);\n gw.publish(\"sidebar\", { type: \"project.remove\", id: p.id });\n return { ok: true };\n }));\n\n gw.method(\"projects.open\", wrap(z.object({ id: z.string() }), async (p) => {\n const proj = await svc.projects.get(p.id);\n if (!proj) throw new ApiError(\"not_found\", tr(\"err.projectMissing\"));\n if (!existsSync(proj.path)) throw new ApiError(\"bad_path\", tr(\"err.dirMissing\"));\n const cmd = process.platform === \"win32\" ? \"explorer.exe\" : process.platform === \"darwin\" ? \"open\" : \"xdg-open\";\n // explorer.exe doesn't understand forward-slash paths (it opens \"Documents\"); a missing xdg-open must not make the daemon throw either\n const target = process.platform === \"win32\" ? win32Path.normalize(proj.path) : proj.path;\n execFile(cmd, [target], { windowsHide: true }, () => {}).on(\"error\", () => {});\n return { ok: true };\n }));\n\n // ---- fs.* ----\n gw.method(\"fs.check\", wrap(z.object({ path: z.string().min(1) }), (p) => {\n let exists = false;\n let isDir = false;\n try {\n exists = existsSync(p.path);\n isDir = exists && statSync(p.path).isDirectory();\n } catch {}\n return { exists, isDir };\n }));\n\n gw.method(\"fs.recentDirs\", wrap(zEmpty, async () => {\n const s = await svc.settings.get();\n return (s.recentDirs ?? []).slice(0, 12);\n }));\n\n // fs.pickFolder: show the native folder picker (the daemon runs locally): Windows PowerShell, macOS osascript,\n // Linux zenity/kdialog; with none, report unavailable and the frontend falls back to typing.\n gw.method(\"fs.pickFolder\", wrap(z.object({ initial: z.string().optional() }).passthrough().optional(), (p) =>\n pickFolder(p?.initial),\n ));\n\n // ---- threads.* ----\n gw.method(\"threads.list\", wrap(zEmpty, () => svc.threads.list()));\n\n gw.method(\"threads.create\", wrap(\n z.object({\n projectId: z.string().min(1),\n provider: z.string().min(1),\n model: z.string().nullable().optional(),\n mode: threadModeSchema.optional(),\n effort: z.string().nullable().optional(),\n title: z.string().optional(),\n providerSessionId: z.string().nullable().optional(),\n importedFrom: z.object({ provider: z.string(), sessionId: z.string() }).optional(),\n }),\n async (p) => {\n const proj = await svc.projects.get(p.projectId);\n if (!proj) throw new ApiError(\"not_found\", tr(\"err.projectMissing\"));\n if (!existsSync(proj.path)) throw new ApiError(\"bad_path\", tr(\"err.projectDirGone\"));\n // New conversations must use an enabled Agent (except imported sessions, which already ran)\n if (!p.providerSessionId && !isProviderEnabled(await svc.settings.get(), p.provider)) {\n throw new ApiError(\"bad_params\", tr(\"provider.disabledNamed\", { name: catalogById(p.provider)?.name ?? p.provider }));\n }\n const cat = catalogById(p.provider);\n if (!p.providerSessionId && cat && !providerCreatable(cat.status)) {\n throw new ApiError(\"bad_params\", tr(\"provider.plannedNamed\", { name: cat.name }));\n }\n // B8: the default permission mode is mapped onto this Agent's own modes (same rule as thread.setProvider)\n const provider = getProvider(p.provider);\n const mode = clampMode(provider?.capabilities.modes ?? [], p.mode);\n const meta = await svc.threads.create({ ...p, mode });\n gw.publish(\"sidebar\", { type: \"thread.upsert\", thread: meta });\n return meta;\n }\n ));\n\n gw.method(\"threads.get\", wrap(\n z.object({ id: z.string(), afterSeq: z.number().int().nonnegative().optional() }),\n async (p) => {\n const meta = await svc.threads.get(p.id);\n if (!meta) throw new ApiError(\"not_found\", tr(\"err.threadMissing\"));\n const events = await svc.threads.readEvents(p.id, p.afterSeq ?? 0, 5000);\n const rt = svc.runtime?.(p.id) ?? null;\n return {\n meta,\n events,\n queue: rt?.queue ?? [],\n pending: rt?.pending ?? [],\n runtimeStatus: rt?.status ?? meta.status,\n };\n }\n ));\n\n gw.method(\"threads.update\", wrap(\n z.object({\n id: z.string(),\n title: z.string().optional(),\n pinned: z.boolean().optional(),\n archived: z.boolean().optional(),\n }),\n async (p) => {\n const meta = await svc.threads.get(p.id);\n if (!meta) throw new ApiError(\"not_found\", tr(\"err.threadMissing\"));\n const patch: Record = {};\n if (p.title !== undefined) {\n patch.title = p.title.trim() || meta.title;\n patch.titleAuto = false; // Once renamed by hand, never auto-overwrite\n }\n if (p.pinned !== undefined) patch.pinned = p.pinned;\n if (p.archived !== undefined) patch.archived = p.archived;\n const next = await svc.threads.patch(p.id, patch);\n gw.publish(\"sidebar\", { type: \"thread.upsert\", thread: next });\n return next;\n }\n ));\n\n gw.method(\"threads.delete\", wrap(z.object({ id: z.string() }), async (p) => {\n const meta = await svc.threads.get(p.id);\n if (!meta) throw new ApiError(\"not_found\", tr(\"err.threadMissing\"));\n if (svc.manager) await svc.manager.deleteThread(p.id);\n else await svc.threads.delete(p.id);\n gw.publish(\"sidebar\", { type: \"thread.remove\", id: p.id });\n return { ok: true };\n }));\n\n // ---- git.* (§5.8) ----\n const projectPath = async (projectId: string): Promise => {\n const proj = await svc.projects.get(projectId);\n if (!proj) throw new ApiError(\"not_found\", tr(\"err.projectMissing\"));\n if (!existsSync(proj.path)) throw new ApiError(\"bad_path\", tr(\"err.projectDirGone\"));\n return proj.path;\n };\n\n gw.method(\"git.status\", wrap(z.object({ projectId: z.string() }), async (p) =>\n svc.git.status(await projectPath(p.projectId))\n ));\n\n gw.method(\"git.diff\", wrap(z.object({ projectId: z.string(), path: z.string() }), async (p) =>\n svc.git.diff(await projectPath(p.projectId), p.path)\n ));\n\n gw.method(\"git.discard\", wrap(z.object({ projectId: z.string(), path: z.string() }), async (p) =>\n svc.git.discard(await projectPath(p.projectId), p.path, svc.cfg.dataDir)\n ));\n\n // ---- files.* (§5.9) ----\n gw.method(\"files.tree\", wrap(z.object({ projectId: z.string(), dir: z.string().default(\".\") }), async (p) =>\n svc.files.tree(await projectPath(p.projectId), p.dir)\n ));\n\n gw.method(\"files.read\", wrap(z.object({ projectId: z.string(), path: z.string() }), async (p) =>\n svc.files.read(await projectPath(p.projectId), p.path)\n ));\n\n // ---- history.* (§7.6) ----\n gw.method(\"history.list\", wrap(z.object({ projectId: z.string() }), async (p) => {\n const proj = await svc.projects.get(p.projectId);\n if (!proj) throw new ApiError(\"not_found\", tr(\"err.projectMissing\"));\n const imported = new Set(\n (await svc.threads.list())\n .filter((t) => t.projectId === p.projectId && t.providerSessionId)\n .map((t) => t.providerSessionId),\n );\n const out: unknown[] = [];\n for (const provider of listProviders()) {\n if (!provider.listHistory) continue;\n const items = await provider.listHistory(proj.path).catch(() => []);\n for (const i of items) out.push({ ...i, imported: imported.has(i.sessionId) });\n }\n return out;\n }));\n\n gw.method(\"history.import\", wrap(\n z.object({\n projectId: z.string(),\n items: z.array(z.object({ provider: z.string(), sessionId: z.string(), title: z.string().optional() })).min(1).max(20),\n }),\n async (p) => {\n const proj = await svc.projects.get(p.projectId);\n if (!proj) throw new ApiError(\"not_found\", tr(\"err.projectMissing\"));\n const metas = [];\n for (const item of p.items) {\n const provider = getProvider(item.provider);\n if (!provider?.readHistory) continue;\n // Idempotent: reuse if the same providerSessionId was already imported\n const existing = (await svc.threads.list()).find(\n (t) => t.projectId === p.projectId && t.provider === item.provider && t.providerSessionId === item.sessionId,\n );\n if (existing) { metas.push(existing); continue; }\n const meta = await svc.threads.create({\n projectId: p.projectId,\n provider: item.provider,\n title: item.title,\n providerSessionId: item.sessionId,\n importedFrom: { provider: item.provider, sessionId: item.sessionId },\n });\n const events = await provider.readHistory(item.sessionId, proj.path).catch(() => []);\n for (const ev of events) {\n await svc.threads.appendEvent(meta.id, ev as Parameters[1]);\n }\n await svc.threads.patch(meta.id, { status: \"closed\" });\n gw.publish(\"sidebar\", { type: \"thread.upsert\", thread: await svc.threads.get(meta.id) });\n metas.push(await svc.threads.get(meta.id));\n }\n return metas;\n }\n ));\n\n // ---- terminal.* (§7.5) ----\n gw.method(\"terminal.list\", wrap(z.object({ projectId: z.string().optional() }).passthrough().optional(), (p) =>\n svc.terminals.list(p?.projectId)\n ));\n\n gw.method(\"terminal.create\", wrap(\n z.object({ projectId: z.string(), cols: z.number().int().min(20).max(500).default(80), rows: z.number().int().min(5).max(200).default(24) }),\n async (p) => {\n const path = await projectPath(p.projectId);\n const r = await svc.terminals.create(p.projectId, path, p.cols, p.rows);\n if (\"error\" in r) throw new ApiError(\"bad_params\", r.error);\n return r;\n }\n ));\n\n gw.method(\"terminal.attach\", wrap(z.object({ id: z.string() }), async (p, ctx) => {\n const r = svc.terminals.attach(p.id);\n if (r.error || r.index == null) throw new ApiError(\"not_found\", r.error ?? tr(\"err.terminalMissing\"));\n // attach also subscribes to the terminal: channel (input frames are gated on that subscription too)\n svc.gateway.subscribe(ctx.conn, `terminal:${r.index}`);\n return r;\n }));\n\n gw.method(\"terminal.resize\", wrap(z.object({ id: z.string(), cols: z.number().int(), rows: z.number().int() }), (p) =>\n svc.terminals.resize(p.id, p.cols, p.rows)\n ));\n\n gw.method(\"terminal.kill\", wrap(z.object({ id: z.string() }), (p) => svc.terminals.kill(p.id)));\n\n // ---- thread.* (runtime operations, need the manager) ----\n const needManager = () => {\n if (!svc.manager) throw new ApiError(\"unavailable\", tr(\"err.noManager\"));\n return svc.manager;\n };\n\n gw.method(\"thread.send\", wrap(\n z.object({\n id: z.string(),\n text: z.string(),\n attachments: z.array(z.object({ path: z.string(), mime: z.string(), name: z.string().optional() })).optional(),\n behavior: z.enum([\"queue\", \"steer\"]).optional(),\n }),\n async (p) => {\n // delivered tells the composer what happened: a steer an Agent can't take is queued (B7)\n const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? \"queue\");\n return { ok: true, delivered: delivered ?? \"started\" };\n }\n ));\n\n // The composer's queue list has a remove button; it used to call a method that didn't exist\n gw.method(\"thread.queueRemove\", wrap(z.object({ id: z.string(), queueId: z.string() }), async (p) => {\n return { ok: needManager().removeQueued(p.id, p.queueId) };\n }));\n\n gw.method(\"thread.interrupt\", wrap(z.object({ id: z.string() }), async (p) => {\n await needManager().interrupt(p.id);\n return { ok: true };\n }));\n\n gw.method(\"thread.respond\", wrap(\n z.object({\n id: z.string(),\n requestId: z.string(),\n optionId: z.string().optional(),\n answers: z.record(z.string(), z.string()).optional(),\n cancelled: z.boolean().optional(),\n }),\n async (p) => {\n await needManager().respond(p.id, p.requestId, { optionId: p.optionId, answers: p.answers, cancelled: p.cancelled });\n return { ok: true };\n }\n ));\n\n gw.method(\"thread.setModel\", wrap(z.object({ id: z.string(), model: z.string().nullable() }), async (p) => {\n await needManager().setModel(p.id, p.model);\n return { ok: true };\n }));\n\n gw.method(\"thread.setMode\", wrap(z.object({ id: z.string(), mode: threadModeSchema }), async (p) => {\n await needManager().setMode(p.id, p.mode);\n return { ok: true };\n }));\n\n gw.method(\"thread.setEffort\", wrap(z.object({ id: z.string(), effort: z.string().nullable() }), async (p) => {\n await needManager().setEffort(p.id, p.effort);\n return { ok: true };\n }));\n\n gw.method(\"thread.commands\", wrap(z.object({ id: z.string(), load: z.boolean().optional() }), async (p) => {\n const commands = await needManager().listCommands(p.id, { load: p.load });\n return { commands };\n }));\n\n gw.method(\"thread.setCursorOpts\", wrap(\n z.object({\n id: z.string(),\n cursorFast: z.boolean().optional(),\n cursorAutoReview: z.boolean().optional(),\n }),\n async (p) => {\n await needManager().setCursorOpts(p.id, {\n cursorFast: p.cursorFast,\n cursorAutoReview: p.cursorAutoReview,\n });\n return { ok: true };\n },\n ));\n\n gw.method(\"thread.setProvider\", wrap(z.object({ id: z.string(), provider: z.string().min(1) }), async (p) => {\n await needManager().setProvider(p.id, p.provider);\n return { ok: true };\n }));\n\n gw.method(\"thread.close\", wrap(z.object({ id: z.string() }), async (p) => {\n await needManager().close(p.id);\n return { ok: true };\n }));\n\n // ---- thread.exportMarkdown (P2-7): persisted events → Markdown text ----\n gw.method(\"thread.exportMarkdown\", wrap(z.object({ id: z.string() }), async (p) => {\n const meta = await svc.threads.get(p.id);\n if (!meta) throw new ApiError(\"not_found\", tr(\"err.threadMissing\"));\n const events = await svc.threads.readEvents(p.id, 0, 20000);\n const L: string[] = [];\n L.push(`# ${meta.title}`, \"\");\n L.push(`> ${meta.provider} · ${meta.model ?? tr(\"export.defaultModel\")} · ${meta.mode} · ${new Date(meta.createdAt).toLocaleString(intlLocale())}`, \"\");\n for (const e of events) {\n switch (e.type) {\n case \"user_message\": L.push(`**${tr(\"export.me\")}**${e.steered ? tr(\"export.steered\") : \"\"}:\\n\\n${e.text}`, \"\"); break;\n case \"assistant_message\": L.push(e.text, \"\"); break;\n case \"reasoning\": L.push(`
    ${tr(\"export.reasoning\")}\\n\\n${e.text}\\n
    `, \"\"); break;\n case \"tool_call\": {\n const icon = e.status === \"ok\" ? \"✓\" : e.status === \"failed\" ? \"✗\" : \"…\";\n L.push(`- \\`${e.kind}\\` ${icon} ${e.title}${e.output ? `\\n \\`\\`\\`\\n ${e.output.slice(0, 2000)}\\n \\`\\`\\`` : \"\"}`);\n break;\n }\n case \"plan\": L.push(`### ${tr(\"export.plan\")}\\n\\n` + e.markdown, \"\"); break;\n case \"todo\": L.push(`### ${tr(\"export.todo\")}\\n\\n` + e.items.map((i) => `- [${i.status === \"done\" || i.status === \"completed\" ? \"x\" : \" \"}] ${i.text}`).join(\"\\n\"), \"\"); break;\n case \"notice\": L.push(`_${e.message}_`, \"\"); break;\n case \"turn_ended\": L.push(`— ${e.status}${e.durationMs ? ` · ${Math.round(e.durationMs / 1000)}s` : \"\"}${e.error ? ` · ${e.error}` : \"\"} —`, \"\"); break;\n default: break;\n }\n }\n const markdown = L.join(\"\\n\");\n const safe = meta.title.replace(/[\\\\/:*?\"<>|\\s]+/g, \"_\").slice(0, 60) || \"thread\";\n const filename = `${safe}.md`;\n // ~/Downloads when it can be used, else /exports (B21); the file is revealed with execFile (no shell)\n let dir = join(homedir(), \"Downloads\");\n try {\n await mkdir(dir, { recursive: true });\n } catch {\n dir = join(svc.cfg.dataDir, \"exports\");\n await mkdir(dir, { recursive: true });\n }\n let dest = join(dir, filename);\n if (existsSync(dest)) {\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\").slice(0, 19);\n dest = join(dir, `${safe}-${stamp}.md`);\n }\n await writeFile(dest, markdown, \"utf8\");\n revealInFileManager(dest);\n return { markdown, filename, path: dest };\n }));\n}\n\nfunction revealInFileManager(filePath: string): void {\n if (process.platform === \"win32\") {\n execFile(\"explorer.exe\", [\"/select,\" + win32Path.normalize(filePath)], { windowsHide: true }, () => {}).on(\"error\", () => {});\n return;\n }\n if (process.platform === \"darwin\") {\n execFile(\"open\", [\"-R\", filePath], () => {}).on(\"error\", () => {});\n return;\n }\n execFile(\"xdg-open\", [dirname(filePath)], () => {}).on(\"error\", () => {});\n}\n","// Atomic JSON write: temp file + rename. On fs failure throws an ApiError with a Chinese message (P5-2: disk write failure notice).\nimport { writeFile, rename, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { ApiError } from \"../ws/methods.js\";\n\nexport async function writeJsonAtomic(file: string, obj: unknown): Promise {\n try {\n await mkdir(dirname(file), { recursive: true });\n const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;\n await writeFile(tmp, JSON.stringify(obj, null, 2), \"utf8\");\n await rename(tmp, file);\n } catch (e) {\n if (e instanceof ApiError) throw e;\n throw new ApiError(\"io_error\", `写入数据失败(${file}):${(e as Error)?.message ?? e}`);\n }\n}\n","// settings.json: defaults per EXEC §5.6; unknown fields are preserved on read.\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { z } from \"zod\";\nimport { writeJsonAtomic } from \"../util/atomic.js\";\n\nexport type Settings = {\n defaultProvider: string;\n defaultMode: \"plan\" | \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"ask\";\n sendKey: \"enter\" | \"ctrlEnter\";\n runningSend: \"queue\" | \"steer\";\n showThinking: boolean;\n theme: \"auto\" | \"light\" | \"dark\";\n idleCloseMinutes: number;\n collapsedProjects: string[];\n panel: { open: boolean; tab: string; width: number };\n sidebarWidth: number;\n lastProjectId: string | null;\n lastThreadId: string | null;\n recentDirs?: string[];\n v1Migrated?: boolean;\n /** false = turned off by the user in settings; absent means on */\n providerEnabled?: Record;\n /** Advanced: override how a Provider is launched (executable + args array, no shell) */\n providerCommand?: Record;\n [k: string]: unknown;\n};\n\nexport const DEFAULT_SETTINGS: Settings = {\n defaultProvider: \"claude\",\n defaultMode: \"default\",\n sendKey: \"enter\",\n runningSend: \"queue\",\n showThinking: true,\n theme: \"auto\",\n idleCloseMinutes: 30,\n collapsedProjects: [],\n panel: { open: false, tab: \"changes\", width: 440 },\n sidebarWidth: 248,\n lastProjectId: null,\n lastThreadId: null,\n recentDirs: [],\n};\n\nexport const IDLE_CLOSE_MIN = 5;\nexport const IDLE_CLOSE_MAX = 240;\n\nconst mode = z.enum([\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\", \"ask\"]);\nconst id = z.string().min(1).max(200);\n/** B18: what settings.set accepts. Every key the UI writes is listed; anything else or a wrong type is refused. */\nexport const settingsPatchSchema = z\n .object({\n defaultProvider: z.string().min(1).max(64),\n defaultMode: mode,\n sendKey: z.enum([\"enter\", \"ctrlEnter\"]),\n runningSend: z.enum([\"queue\", \"steer\"]),\n showThinking: z.boolean(),\n // auto = follow the host: Magpie's light/dark inside Magpie, the OS outside it\n theme: z.enum([\"auto\", \"light\", \"dark\"]),\n idleCloseMinutes: z.number().int().min(IDLE_CLOSE_MIN).max(IDLE_CLOSE_MAX),\n collapsedProjects: z.array(id).max(1000),\n panel: z.object({ open: z.boolean(), tab: z.string().max(40), width: z.number().min(0).max(5000) }).partial(),\n sidebarWidth: z.number().min(0).max(5000),\n lastProjectId: id.nullable(),\n lastThreadId: id.nullable(),\n recentDirs: z.array(z.string().max(4096)).max(50),\n providerEnabled: z.record(z.string().max(64), z.boolean()),\n providerCommand: z.record(\n z.string().max(64),\n z.object({ executable: z.string().max(4096).optional(), args: z.array(z.string().max(4096)).max(64).optional() }).strict(),\n ),\n v1Migrated: z.boolean(),\n })\n .partial()\n .strict();\n\nexport type SettingsPatch = z.infer;\n\n/** Validate a patch from the page; returns the parsed patch or a readable error. */\nexport function parseSettingsPatch(patch: unknown): { ok: true; patch: SettingsPatch } | { ok: false; error: string } {\n const r = settingsPatchSchema.safeParse(patch);\n if (r.success) return { ok: true, patch: r.data };\n return {\n ok: false,\n error: r.error.issues.map((i) => `${i.path.join(\".\") || \"(patch)\"}: ${i.message}`).join(\"; \"),\n };\n}\n\n/** Values in settings.json that have the wrong type (hand edits, older builds) fall back to the default; unknown keys are kept. */\nexport function sanitizeStored(raw: Record): Record {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return {};\n const shape = settingsPatchSchema.shape as Record;\n const out: Record = {};\n for (const [k, v] of Object.entries(raw)) {\n const field = shape[k];\n if (field && k !== \"idleCloseMinutes\" && !field.safeParse(v).success) continue;\n if (k === \"idleCloseMinutes\") {\n const n = Number(v);\n if (!Number.isFinite(n)) continue;\n out[k] = Math.min(IDLE_CLOSE_MAX, Math.max(IDLE_CLOSE_MIN, Math.round(n)));\n continue;\n }\n out[k] = v;\n }\n return out;\n}\n\nexport class SettingsStore {\n private file: string;\n private cache: Settings | null = null;\n private writing: Promise = Promise.resolve();\n constructor(dataDir: string) {\n this.file = join(dataDir, \"settings.json\");\n }\n async get(): Promise {\n if (this.cache) return this.cache;\n let raw: Record = {};\n try {\n raw = JSON.parse(await readFile(this.file, \"utf8\"));\n } catch {}\n raw = sanitizeStored(raw);\n this.cache = { ...DEFAULT_SETTINGS, ...raw, panel: { ...DEFAULT_SETTINGS.panel, ...(raw.panel as object | undefined) } };\n return this.cache;\n }\n async set(patch: Partial): Promise {\n const cur = await this.get();\n const next = { ...cur, ...patch, panel: { ...cur.panel, ...(patch.panel as object | undefined) } };\n this.cache = next;\n const snap = next;\n this.writing = this.writing.then(() => writeJsonAtomic(this.file, snap));\n await this.writing;\n return next;\n }\n}\n","// JSONL read/write: serialized appends, corrupt lines skipped. Write failures throw an ApiError with a Chinese message (P5-2: disk write failure notice).\nimport { appendFile, readFile, mkdir, rename, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { ApiError } from \"../ws/methods.js\";\n\nexport async function readJsonl(file: string): Promise {\n let text = \"\";\n try {\n text = await readFile(file, \"utf8\");\n } catch {\n return [];\n }\n const out: T[] = [];\n for (const line of text.split(\"\\n\")) {\n const t = line.trim();\n if (!t) continue;\n try {\n out.push(JSON.parse(t) as T);\n } catch {\n // Skip corrupt lines\n }\n }\n return out;\n}\n\n// One serialized write queue per file to keep append order.\nconst writers = new Map>();\n\nexport function appendJsonl(file: string, obj: unknown): Promise {\n const prev = writers.get(file) ?? Promise.resolve();\n const next = prev.then(async () => {\n try {\n await mkdir(dirname(file), { recursive: true });\n await appendFile(file, JSON.stringify(obj) + \"\\n\", \"utf8\");\n } catch (e) {\n if (e instanceof ApiError) throw e;\n throw new ApiError(\"io_error\", `写入数据失败(${file}):${(e as Error)?.message ?? e}`);\n }\n });\n writers.set(\n file,\n next.catch(() => {})\n );\n return next;\n}\n\n// Full rewrite (rare path, e.g. cleanup)\nexport async function writeJsonl(file: string, items: unknown[]): Promise {\n try {\n await mkdir(dirname(file), { recursive: true });\n const tmp = file + \".tmp-\" + process.pid;\n await writeFile(tmp, items.map((o) => JSON.stringify(o)).join(\"\\n\") + (items.length ? \"\\n\" : \"\"), \"utf8\");\n await rename(tmp, file);\n } catch (e) {\n if (e instanceof ApiError) throw e;\n throw new ApiError(\"io_error\", `写入数据失败(${file}):${(e as Error)?.message ?? e}`);\n }\n}\n","// Legacy data migration (§10.1): runs once when the daemon starts.\n// Old: sessions//{meta.json,events.jsonl} + projects in settings.json →\n// New: projects.json + threads//{meta.json,timeline.jsonl}. Old files are read-only and copied to trash/legacy-/ as a backup.\nimport { cp, mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { SettingsStore } from \"../store/settings.js\";\nimport type { ProjectsStore } from \"../store/projects.js\";\nimport type { ThreadsStore, ThreadMeta } from \"../store/threads.js\";\nimport type { Mode, TimelineEvent } from \"../timeline/types.js\";\nimport { appendJsonl } from \"../util/jsonl.js\";\nimport { writeJsonAtomic } from \"../util/atomic.js\";\nimport { validId } from \"../util/paths.js\";\nimport { log } from \"../log.js\";\n\ntype OldMeta = {\n id: string; agent: string; cwd: string; model: string; permission: string;\n title: string; titleAuto: boolean; pinned: boolean; cliSessionId: string | null;\n created: number; updated: number; lastStatus?: string; totalCost?: number; totalUsage?: { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number } | null;\n};\ntype OldEvt = Record & { type: string; seq?: number; ts?: number };\n\nconst SKIP_TITLE = /^\\/(slow|deny|error|long|codex)/;\nconst MODE_MAP: Record = {\n plan: \"plan\", default: \"default\", acceptEdits: \"acceptEdits\", bypassPermissions: \"bypassPermissions\",\n auto: \"acceptEdits\", full: \"bypassPermissions\",\n};\nconst belongsTo = (cwd: string, parent: string) => {\n const c = cwd.replace(/\\\\/g, \"/\").toLowerCase().replace(/\\/+$/, \"\");\n const p = parent.replace(/\\\\/g, \"/\").toLowerCase().replace(/\\/+$/, \"\");\n return c === p || c.startsWith(p + \"/\");\n};\n\nfunction stamp(): string {\n const d = new Date();\n const p = (n: number) => String(n).padStart(2, \"0\");\n return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;\n}\n\nexport async function migrateLegacy(dataDir: string, stores: {\n settings: SettingsStore; projects: ProjectsStore; threads: ThreadsStore;\n}): Promise<{ migrated: number; skipped: boolean }> {\n const settings = await stores.settings.get();\n if (settings.v1Migrated) return { migrated: 0, skipped: true };\n const oldDir = join(dataDir, \"sessions\");\n const oldSettingsPath = join(dataDir, \"settings.json\");\n if (!existsSync(oldDir) && !existsSync(oldSettingsPath)) {\n await stores.settings.set({ v1Migrated: true });\n return { migrated: 0, skipped: true };\n }\n\n // 1. Backup\n const backup = join(dataDir, \"trash\", `legacy-${stamp()}`);\n await mkdir(backup, { recursive: true });\n if (existsSync(oldDir)) await cp(oldDir, join(backup, \"sessions\"), { recursive: true }).catch(() => {});\n if (existsSync(oldSettingsPath)) await cp(oldSettingsPath, join(backup, \"settings.json\")).catch(() => {});\n\n // Read the old settings (read the file directly; SettingsStore already loaded the same path, the fields coexist without conflict)\n const oldSettings = existsSync(oldSettingsPath)\n ? (JSON.parse(await readFile(oldSettingsPath, \"utf8\").catch(() => \"{}\")) as Record)\n : {};\n\n // 2. Projects: old settings.projects → projects.json; orphan cwds are added per the adoptOrphans rule\n const projectIdByPath = new Map();\n const lc = (p: string) => p.replace(/\\\\/g, \"/\").toLowerCase().replace(/\\/+$/, \"\");\n for (const p of (oldSettings.projects as { name?: string; path?: string }[] | undefined) ?? []) {\n if (!p?.path) continue;\n try {\n const proj = await stores.projects.create(p.path, p.name);\n projectIdByPath.set(lc(proj.path), proj.id);\n } catch (e) {\n log(\"warn\", \"迁移:建项目失败\", { path: p.path, err: String(e) });\n }\n }\n\n // Old session list\n let sessionIds: string[] = [];\n try {\n sessionIds = (await readdir(oldDir)).filter((d) => validId(d) && existsSync(join(oldDir, d, \"meta.json\")));\n } catch {}\n const metas: OldMeta[] = [];\n for (const id of sessionIds) {\n try {\n const m = JSON.parse(await readFile(join(oldDir, id, \"meta.json\"), \"utf8\")) as OldMeta;\n if (m?.cwd) metas.push(m);\n } catch {}\n }\n // Orphan cwd → add a project (subdirectories fold into their parent)\n const extraDirs: string[] = [];\n const projPaths = [...projectIdByPath.keys()];\n for (const m of metas) {\n const covered = projPaths.some((pp) => belongsTo(m.cwd, pp)) || extraDirs.some((d) => belongsTo(m.cwd, d));\n if (covered) continue;\n for (let i = extraDirs.length - 1; i >= 0; i--) if (belongsTo(extraDirs[i], m.cwd)) extraDirs.splice(i, 1);\n extraDirs.push(m.cwd);\n }\n for (const d of extraDirs) {\n if (!existsSync(d)) continue; // Skip directories that no longer exist (same as the old adoptOrphans)\n try {\n const name = d.replace(/\\\\/g, \"/\").split(\"/\").filter(Boolean).pop() ?? d;\n const proj = await stores.projects.create(d, name);\n projectIdByPath.set(lc(proj.path), proj.id);\n projPaths.push(lc(proj.path));\n } catch (e) {\n log(\"warn\", \"迁移:补建孤儿项目失败\", { path: d, err: String(e) });\n }\n }\n\n const projectOf = (cwd: string): string | null => {\n const l = lc(cwd);\n // Take the longest match (a subdirectory joins the most specific project)\n let best: string | null = null;\n for (const [pp, id] of projectIdByPath) {\n if (belongsTo(l, pp) && (best == null || pp.length > best.length)) best = pp;\n }\n return best ? projectIdByPath.get(best)! : null;\n };\n\n // 3. Sessions\n let migrated = 0;\n const threadsDir = join(dataDir, \"threads\");\n for (const m of metas) {\n try {\n const projectId = projectOf(m.cwd);\n if (!projectId) { log(\"warn\", \"迁移:无项目可归,跳过\", { id: m.id, cwd: m.cwd }); continue; }\n const testTitle = SKIP_TITLE.test(m.title ?? \"\") || m.title === \"默认剧本演示\";\n const provider = m.agent === \"claude\" || m.agent === \"codex\" ? m.agent : \"mock\";\n const archived = testTitle || (m.agent !== \"claude\" && m.agent !== \"codex\");\n const now = Date.now();\n const meta: ThreadMeta = {\n id: `t_${m.id.replace(/^s?_?/, \"\")}`.slice(0, 80),\n projectId,\n title: m.title || \"旧对话\",\n titleAuto: false,\n provider,\n model: m.model || null,\n mode: MODE_MAP[m.permission] ?? \"default\",\n effort: null,\n providerSessionId: m.cliSessionId || null,\n status: \"closed\",\n pinned: !!m.pinned,\n archived,\n createdAt: m.created || now,\n updatedAt: m.updated || now,\n lastTurnStatus: m.lastStatus === \"ok\" ? \"completed\" : m.lastStatus === \"error\" ? \"failed\" : null,\n usage: {\n inputTokens: m.totalUsage?.inputTokens ?? 0,\n outputTokens: m.totalUsage?.outputTokens ?? 0,\n cacheReadTokens: m.totalUsage?.cacheReadTokens ?? 0,\n costUsd: m.totalCost ?? 0,\n },\n importedFrom: m.cliSessionId ? { provider, sessionId: m.cliSessionId } : undefined,\n seq: 0,\n };\n const tdir = join(threadsDir, meta.id);\n if (existsSync(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80);\n await mkdir(join(threadsDir, meta.id), { recursive: true });\n\n // Event mapping\n const oldEvts = (await readFile(join(oldDir, m.id, \"events.jsonl\"), \"utf8\").catch(() => \"\"))\n .split(\"\\n\").filter((l) => l.trim())\n .map((l) => { try { return JSON.parse(l) as OldEvt; } catch { return null; } })\n .filter((x): x is OldEvt => !!x);\n const lines: TimelineEvent[] = [];\n const openTools = new Map();\n let seq = 0;\n const push = (ev: Record & { type: TimelineEvent[\"type\"] }) => {\n seq++;\n lines.push({ ...ev, seq, ts: Date.now(), threadId: meta.id } as TimelineEvent);\n };\n for (const e of oldEvts) {\n switch (e.type) {\n case \"user\": push({ type: \"user_message\", text: String(e.text ?? \"\") }); break;\n case \"text\": push({ type: \"assistant_message\", itemId: `lg_${seq}`, text: String(e.text ?? \"\") }); break;\n case \"thinking\": push({ type: \"reasoning\", itemId: `lg_${seq}`, text: String(e.text ?? \"\") }); break;\n case \"tool.call\": {\n const key = String(e.itemId ?? e.callId ?? `c${seq}`);\n openTools.set(key, { kind: String(e.kind ?? \"other\"), title: String(e.title ?? e.kind ?? \"工具\"), input: e.input, detail: e.detail });\n push({ type: \"tool_call\", itemId: key, kind: \"other\", title: String(e.title ?? \"工具\"), status: \"running\", input: e.input, detail: e.detail });\n break;\n }\n case \"tool.result\": {\n const key = String(e.itemId ?? e.callId ?? `c${seq}`);\n const open = openTools.get(key);\n openTools.delete(key);\n push({\n type: \"tool_call\", itemId: key,\n kind: (open?.kind ?? \"other\") as import(\"../timeline/types.js\").ToolKind,\n title: open?.title ?? \"工具\",\n status: e.ok === false || e.error ? \"failed\" : \"ok\",\n output: typeof e.output === \"string\" ? e.output.slice(0, 20000) : undefined,\n detail: open?.detail,\n } as Record & { type: \"tool_call\" });\n break;\n }\n case \"todo\": {\n const items = (e.items as { text?: string; status?: string }[] | undefined) ?? [];\n push({ type: \"todo\", items: items.map((i) => ({ text: String(i.text ?? \"\"), status: i.status === \"done\" ? \"done\" : i.status === \"in_progress\" ? \"in_progress\" : \"todo\" })) });\n break;\n }\n case \"permission.denied\": push({ type: \"notice\", level: \"warn\", message: `已拒绝:${String(e.title ?? e.kind ?? \"\")}` }); break;\n case \"permission.request\": case \"permission.resolved\": break; // Old permission cards are stale; don't recreate them\n case \"notice\": push({ type: \"notice\", level: (e.level as \"info\" | \"warn\" | \"error\") ?? \"info\", message: String(e.message ?? \"\") }); break;\n case \"run.end\": {\n const u = e.usage as { inputTokens?: number; outputTokens?: number; cacheReadTokens?: number } | undefined;\n if (u) push({ type: \"usage\", turnId: `lg_t${seq}`, inputTokens: u.inputTokens ?? 0, outputTokens: u.outputTokens ?? 0, cacheReadTokens: u.cacheReadTokens ?? 0, costUsd: (e.costUsd as number) ?? 0 });\n push({ type: \"turn_ended\", turnId: `lg_t${seq}`, status: e.status === \"error\" ? \"failed\" : e.status === \"interrupted\" ? \"interrupted\" : \"completed\", durationMs: (e.ms as number) ?? undefined, error: e.error as string | undefined });\n break;\n }\n case \"run.start\": break;\n case \"init\": break;\n default: break;\n }\n }\n // Unclosed tool.call → mark failed\n for (const [key, o] of openTools) {\n seq++;\n lines.push({ type: \"tool_call\", itemId: key, kind: \"other\", title: o.title, status: \"failed\", seq, ts: Date.now(), threadId: meta.id } as TimelineEvent);\n }\n for (const ev of lines) await appendJsonl(join(threadsDir, meta.id, \"timeline.jsonl\"), ev);\n meta.seq = seq;\n await writeJsonAtomic(join(threadsDir, meta.id, \"meta.json\"), meta);\n migrated++;\n } catch (e) {\n log(\"warn\", \"迁移:会话失败\", { id: m.id, err: String(e) });\n }\n }\n\n // 4. Merge settings (UI preference fields only)\n const patch: Record = { v1Migrated: true };\n if (typeof oldSettings.theme === \"string\") patch.theme = oldSettings.theme;\n if (typeof oldSettings.sendKey === \"string\") patch.sendKey = oldSettings.sendKey;\n if (typeof oldSettings.showThinking === \"boolean\") patch.showThinking = oldSettings.showThinking;\n if (typeof oldSettings.defaultAgent === \"string\") patch.defaultProvider = oldSettings.defaultAgent === \"claude\" || oldSettings.defaultAgent === \"codex\" ? oldSettings.defaultAgent : \"claude\";\n if (typeof oldSettings.defaultPermission === \"string\") patch.defaultMode = MODE_MAP[oldSettings.defaultPermission] ?? \"default\";\n await stores.settings.set(patch);\n\n log(\"info\", `旧数据迁移完成:${migrated} 个会话、${projectIdByPath.size} 个项目,备份在 ${backup}`);\n return { migrated, skipped: false };\n}\n","// Startup warm-up: for enabled, non-planned Providers, detect then fetch models; results go into infoCache.\nimport type { Settings } from \"../store/settings.js\";\nimport { listProviders } from \"./registry.js\";\nimport { catalogById } from \"./catalog.js\";\nimport { isProviderEnabled } from \"./enabled.js\";\nimport { cachedDetect, cachedModels } from \"./infoCache.js\";\n\nexport async function warmProviderCache(settings: Settings): Promise {\n await Promise.all(\n listProviders().map(async (p) => {\n if (!isProviderEnabled(settings, p.id) || catalogById(p.id)?.status === \"planned\") return;\n const det = await cachedDetect(p);\n if (det.available) await cachedModels(p);\n }),\n );\n}\n","// Daemon entry: parse arguments, initialize services, start HTTP+WS, write daemon.json, handle exit.\nimport { mkdirSync, existsSync, rmSync, chmodSync } from \"node:fs\";\nimport { join, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { parseConfig } from \"./config.js\";\nimport { initLog, log } from \"./log.js\";\nimport { createHttpServer } from \"./http.js\";\nimport { AttachmentStore } from \"./store/attachments.js\";\nimport { SettingsStore } from \"./store/settings.js\";\nimport { ProjectsStore } from \"./store/projects.js\";\nimport { ThreadsStore } from \"./store/threads.js\";\nimport { Gateway } from \"./ws/gateway.js\";\nimport { registerMethods } from \"./ws/methods.js\";\nimport { writeJsonAtomic } from \"./util/atomic.js\";\nimport { initProviders } from \"./providers/registry.js\";\nimport { AgentManager } from \"./agents/manager.js\";\nimport { GitService } from \"./git/service.js\";\nimport { FileService } from \"./files/service.js\";\nimport { TerminalService } from \"./terminal/service.js\";\nimport { augmentPath, pidAlive } from \"./util/proc.js\";\n\n// The bundle targets node20: an older Node (or being started by Bun by mistake) gets a clear message instead of crashing on some API\nconst nodeMajor = Number(/^v?(\\d+)/.exec(process.versions.node ?? \"\")?.[1] ?? 0);\nif (nodeMajor < 20) {\n console.error(`[agent-console] 需要 Node.js 20 或更高版本,当前 ${process.version}(${process.execPath})`);\n process.exit(3);\n}\n\n// Agent CLI .js entries and the Claude SDK look up \"node\" by name; GUI apps launched from the macOS Dock get a minimal PATH,\n// so append the current node's directory and common install directories to PATH (existing order unchanged)\nprocess.env.PATH = augmentPath(process.env, dirname(process.execPath));\n\nconst cfg = parseConfig(process.argv.slice(2));\n\n// Top-level safety net: log, don't exit\nprocess.on(\"uncaughtException\", (e) => {\n // A console write after the host's pipe closed (EPIPE) is expected while exiting, not a crash worth logging\n if ((e as NodeJS.ErrnoException)?.code === \"EPIPE\") return;\n log(\"error\", \"uncaughtException\", { err: String(e?.stack ?? e) });\n});\nprocess.on(\"unhandledRejection\", (e) => {\n log(\"error\", \"unhandledRejection\", { err: String(e) });\n});\n\nasync function main(): Promise {\n initLog(cfg.dataDir);\n for (const d of [\"threads\", \"attachments\", \"trash\", \"logs\"]) {\n mkdirSync(join(cfg.dataDir, d), { recursive: true });\n }\n\n const appDir = join(dirname(fileURLToPath(import.meta.url)), \"..\", \"..\", \"app\");\n const attachments = new AttachmentStore(join(cfg.dataDir, \"attachments\"));\n const { bindAttachmentStore } = await import(\"./util/attachmentRefs.js\");\n bindAttachmentStore(attachments);\n const settings = new SettingsStore(cfg.dataDir);\n const projects = new ProjectsStore(cfg.dataDir);\n const threads = new ThreadsStore(cfg.dataDir);\n const gateway = new Gateway(cfg);\n\n initProviders(cfg.version);\n // Legacy data migration (§10.1): runs once, skipped after v1Migrated; old files are read-only\n const { migrateLegacy } = await import(\"./migrate/legacy.js\");\n try {\n await migrateLegacy(cfg.dataDir, { settings, projects, threads });\n } catch (e) {\n log(\"error\", \"旧数据迁移失败\", { err: String(e) });\n }\n const manager = new AgentManager(gateway, threads, projects, settings, attachments);\n await manager.recoverOnStart();\n const terminals = new TerminalService(gateway);\n registerMethods(gateway, {\n cfg,\n settings,\n gateway,\n projects,\n threads,\n manager,\n git: new GitService(),\n files: new FileService(),\n terminals,\n runtime: (id) => manager.runtimeInfo(id),\n });\n\n const server = createHttpServer(cfg, appDir, attachments, {\n onUpgrade: (req, socket, head) => gateway.handleUpgrade(req, socket, head),\n });\n\n // Retry 5 times if the port is in use\n let attempts = 0;\n await new Promise((resolveListen, rejectListen) => {\n const tryListen = () => {\n attempts++;\n server.once(\"error\", (e: NodeJS.ErrnoException) => {\n if (e.code === \"EADDRINUSE\" && attempts < 6) {\n log(\"warn\", `端口 ${cfg.port} 被占用,500ms 后重试(第 ${attempts} 次)`);\n setTimeout(tryListen, 500);\n } else {\n rejectListen(e);\n }\n });\n server.listen(cfg.port, \"127.0.0.1\");\n };\n server.once(\"listening\", () => resolveListen());\n tryListen();\n }).catch((e) => {\n log(\"error\", `端口 ${cfg.port} 无法监听`, { err: String(e) });\n process.exit(2);\n });\n\n // --port 0: after listening on a random port, write the actual port back into cfg.port. Host/Origin checks read cfg.port,\n // and no request can arrive before this (listen has only just completed), so there is no window checking against the old port.\n const bound = server.address();\n if (bound && typeof bound === \"object\") cfg.port = bound.port;\n // Ready line: the plugin host reads this line from stdout to learn the actual port (port and pid only, no token)\n process.stdout.write(JSON.stringify({ agentConsoleReady: true, port: cfg.port, pid: process.pid }) + \"\\n\");\n // Background warm-up: after start, pull detection/models for enabled providers into the cache so the first page open doesn't wait\n void (async () => {\n const { warmProviderCache } = await import(\"./providers/warm.js\");\n await warmProviderCache(await settings.get());\n })().catch((e) => log(\"warn\", \"Provider 预热失败\", { err: String(e) }));\n\n const daemonJsonPath = join(cfg.dataDir, \"daemon.json\");\n await writeJsonAtomic(daemonJsonPath, {\n pid: process.pid,\n port: cfg.port,\n token: cfg.token,\n version: cfg.version,\n buildStamp: cfg.buildStamp,\n startedAt: Date.now(),\n });\n chmodSync(daemonJsonPath, 0o600);\n log(\"info\", `daemon 已启动 端口 ${cfg.port} 数据目录 ${cfg.dataDir} 版本 ${cfg.version} pid ${process.pid}`);\n // Standalone dev mode: print the open URL with the token to the console (console only, never the log file)\n // B20: standalone (dev) runs only: the token goes to an interactive terminal, never to a redirected stdout or a log\n if (!cfg.parentPid) {\n console.log(process.stdout.isTTY\n ? `[agent-console] open http://127.0.0.1:${cfg.port}/#t=${cfg.token}`\n : `[agent-console] listening on http://127.0.0.1:${cfg.port}/ (token not printed: stdout is not a terminal)`);\n }\n\n // Idle exit: check every minute; no WS connection + no running conversation + no open terminal → exit after idleExitMinutes\n let idleSince = Date.now();\n setInterval(() => {\n const busy = gateway.connectionCount > 0 || manager.anyBusy() || terminals.count > 0;\n if (busy) idleSince = Date.now();\n if (Date.now() - idleSince > cfg.idleExitMinutes * 60 * 1000) {\n log(\"info\", \"空闲超时,daemon 退出\");\n shutdown(0);\n }\n }, 60 * 1000).unref();\n\n let shuttingDown = false;\n function shutdown(code: number): void {\n if (shuttingDown) return;\n shuttingDown = true;\n log(\"info\", \"daemon 关闭中\");\n terminals.killAll();\n gateway.closeAll();\n try {\n rmSync(daemonJsonPath, { force: true });\n } catch {}\n // Wait for Agent sessions to close cleanly (at most 2.5 s) before exiting; process trees still alive are cleaned up by util/bin's exit hook\n const sessionsClosed = Promise.race([manager.shutdown(), new Promise((r) => setTimeout(r, 2500))]);\n void sessionsClosed.then(() => server.close(() => process.exit(code)));\n setTimeout(() => process.exit(code), 4000).unref();\n }\n process.on(\"SIGINT\", () => shutdown(0));\n process.on(\"SIGTERM\", () => shutdown(0));\n // Lifeline: when spawned by the plugin host (Magpie's Bun plugin process) we get --parent-pid, and stdin is a pipe the host holds.\n // Host exits (normally or killed) → pipe closes → stdin end/close → exit;\n // also check every 2 seconds whether the parent is still alive, in case stdin was inherited by another process and never closed.\n // Not enabled in standalone dev mode (npm run dev, no --parent-pid); there we rely on idle exit only.\n if (cfg.parentPid) {\n const parentPid = cfg.parentPid;\n const parentWatch = setInterval(() => {\n if (!pidAlive(parentPid)) {\n clearInterval(parentWatch);\n log(\"info\", `父进程 ${parentPid} 已退出,daemon 跟随退出`);\n shutdown(0);\n }\n }, 2000);\n parentWatch.unref();\n // Logged so a daemon that went away with its plugin host (Magpie restarting it) can be told from an idle exit\n // 'end' and 'close' both fire when the pipe goes away: handle it once\n let lifelineGone = false;\n const lifelineClosed = () => {\n if (lifelineGone) return;\n lifelineGone = true;\n log(\"info\", \"plugin host closed the lifeline (stdin); daemon exiting with it\");\n shutdown(0);\n };\n process.stdin.on(\"end\", lifelineClosed);\n process.stdin.on(\"close\", lifelineClosed);\n process.stdin.on(\"error\", lifelineClosed);\n process.stdin.resume();\n }\n}\n\nmain().catch((e) => {\n console.error(\"[agent-console] 启动失败\", e);\n process.exit(1);\n});\n","// Arguments and environment: port, dataDir, token, version, idleExitMinutes\nimport { randomBytes } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve, dirname } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { daemonBuildStamp } from \"./util/buildStamp.js\";\n\nexport type Config = {\n port: number;\n dataDir: string;\n token: string;\n version: string;\n idleExitMinutes: number;\n buildStamp: string;\n parentPid?: number;\n};\n\nfunction pkgVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url));\n // dist/main.js → ../../package.json; src/main.ts also ends up in dist via esbuild\n const pkg = JSON.parse(readFileSync(join(here, \"..\", \"..\", \"package.json\"), \"utf8\"));\n return String(pkg.version || \"0.0.0\");\n } catch {\n return \"0.0.0\";\n }\n}\n\n// --data sets the data root (equivalent to setting XDG_CONFIG_HOME and then joining magpie/agent-console?\n// EXEC §5.2: --data (data root, equivalent to setting XDG_CONFIG_HOME; default $XDG_CONFIG_HOME\n// or ~/.config, then joined with magpie/agent-console). i.e. the --data value has XDG_CONFIG_HOME semantics.\nexport function parseConfig(argv: string[]): Config {\n let port: number | null = null;\n let data: string | null = null;\n let token: string | null = null;\n let parentPid: number | undefined;\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i];\n if (a === \"--port\" && argv[i + 1]) port = Number(argv[++i]);\n else if (a.startsWith(\"--port=\")) port = Number(a.slice(7));\n else if (a === \"--data\" && argv[i + 1]) data = argv[++i];\n else if (a.startsWith(\"--data=\")) data = a.slice(7);\n else if (a === \"--token\" && argv[i + 1]) token = argv[++i];\n else if (a.startsWith(\"--token=\")) token = a.slice(8);\n else if (a === \"--parent-pid\" && argv[i + 1]) parentPid = Number(argv[++i]);\n else if (a.startsWith(\"--parent-pid=\")) parentPid = Number(a.slice(13));\n }\n if (port == null || !Number.isInteger(port) || port < 0 || port > 65535) {\n const envPort = Number(process.env.AGENT_CONSOLE_PORT || \"\");\n port = Number.isInteger(envPort) && envPort >= 0 && envPort <= 65535 ? envPort : 3488;\n }\n const xdg = data ?? process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n const dataDir = resolve(join(xdg, \"magpie\", \"agent-console\"));\n const idleEnv = Number(process.env.AGENT_CONSOLE_IDLE_EXIT_MIN || \"\");\n return {\n port,\n dataDir,\n token: token ?? process.env.AGENT_CONSOLE_TOKEN ?? randomBytes(16).toString(\"hex\"),\n version: pkgVersion(),\n idleExitMinutes: Number.isFinite(idleEnv) && idleEnv > 0 ? idleEnv : 60,\n buildStamp: daemonBuildStamp(),\n parentPid: Number.isInteger(parentPid) ? parentPid : undefined,\n };\n}\n","import { existsSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nfunction resolveDaemonMainJs(): string | null {\n const self = fileURLToPath(import.meta.url);\n const norm = self.replace(/\\\\/g, \"/\");\n // esbuild single-file bundle: the whole package is dist/main.js\n if (norm.endsWith(\"/daemon/dist/main.js\") || norm.endsWith(\"/dist/main.js\")) return self;\n\n const here = dirname(self);\n const candidates = [\n join(here, \"..\", \"..\", \"dist\", \"main.js\"), // src/util → daemon/dist/main.js (vitest/tsc)\n join(here, \"main.js\"), // Already in the dist directory\n join(here, \"..\", \"main.js\"),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n/** mtime of daemon/dist/main.js, used by the plugin to detect code updates and restart the process */\nexport function daemonBuildStamp(): string {\n try {\n const mainJs = resolveDaemonMainJs();\n if (!mainJs) return \"0\";\n return String(statSync(mainJs).mtimeMs);\n } catch {\n return \"0\";\n }\n}\n","// HTTP routes: / → app/index.html (no token), static assets, /api/ping, /api/upload, /attachments/*\nimport { createServer, type IncomingMessage, type ServerResponse, type Server } from \"node:http\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, normalize, extname } from \"node:path\";\nimport { checkHost, classifyOrigin, tokenEqual } from \"./security.js\";\nimport type { Config } from \"./config.js\";\nimport type { AttachmentStore } from \"./store/attachments.js\";\nimport { log } from \"./log.js\";\nimport { tr } from \"./util/i18n.js\";\n\nconst MIME: Record = {\n \".html\": \"text/html; charset=utf-8\",\n \".js\": \"text/javascript; charset=utf-8\",\n \".css\": \"text/css; charset=utf-8\",\n \".svg\": \"image/svg+xml\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".woff2\": \"font/woff2\",\n \".map\": \"application/json\",\n \".json\": \"application/json; charset=utf-8\",\n};\n\nconst MAX_UPLOAD = 50 * 1024 * 1024; // 50MB\nconst MAX_MSG = 200 * 1024; // Ordinary messages: 200KB\n\nexport type HttpHooks = {\n onUpgrade?: (req: IncomingMessage, socket: import(\"node:net\").Socket, head: Buffer) => void;\n};\n\n// A malformed %xx must not become a 500\nfunction safeDecode(s: string): string | null {\n try {\n return decodeURIComponent(s);\n } catch {\n return null;\n }\n}\n\nfunction send(res: ServerResponse, code: number, body: string | Buffer, headers: Record = {}): void {\n res.writeHead(code, headers);\n res.end(body);\n}\n\nfunction sendJson(res: ServerResponse, code: number, obj: unknown, headers: Record = {}): void {\n send(res, code, JSON.stringify(obj), { \"content-type\": \"application/json; charset=utf-8\", \"cache-control\": \"no-store\", ...headers });\n}\n\n// Common headers for static responses: no caching (the page has no token, but don't let old versions linger), no sniffing, no Referer\nconst STATIC_HEADERS: Record = {\n \"cache-control\": \"no-store\",\n \"x-content-type-options\": \"nosniff\",\n \"referrer-policy\": \"no-referrer\",\n};\n\nexport function createHttpServer(cfg: Config, appDir: string, attachments: AttachmentStore, hooks: HttpHooks = {}): Server {\n const server = createServer(async (req, res) => {\n try {\n await route(req, res);\n } catch (e) {\n log(\"error\", \"HTTP 处理异常\", { url: req.url, err: String(e) });\n if (!res.headersSent) sendJson(res, 500, { ok: false, e: { code: \"internal\", message: tr(\"http.internal\") } });\n else res.end();\n }\n });\n\n // Origin policy per request (see classifyOrigin in security.ts):\n // foreign (another site) → always 403, even with a token\n // opaque (Origin: null) → may only \"present\" the token on token routes (/api/*, /attachments/*);\n // it confers no trust by itself. Static routes are always refused.\n // none / self → static routes allowed (static files contain no token); token routes still need the token.\n // The CORS header is only given (as null) on responses that carry a valid token + Origin: null; preflight only for /api/upload.\n async function route(req: IncomingMessage, res: ServerResponse): Promise {\n // Host must be loopback + this process's actual port: blocks DNS rebinding (a rebound page's GET carries no Origin)\n const hostCheck = checkHost(req.headers.host, cfg.port);\n if (!hostCheck.ok) {\n sendJson(res, hostCheck.code, { ok: false, e: { code: \"bad_host\", message: hostCheck.message } });\n return;\n }\n const origin = classifyOrigin(req.headers.origin, cfg.port);\n if (origin === \"foreign\") {\n sendJson(res, 403, { ok: false, e: { code: \"bad_origin\", message: tr(\"http.badOrigin\") } });\n return;\n }\n\n const url = new URL(req.url ?? \"/\", `http://127.0.0.1:${cfg.port}`);\n const pathname = url.pathname;\n const isApi = pathname.startsWith(\"/api/\");\n const isAttachment = pathname.startsWith(\"/attachments/\");\n\n // OPTIONS preflight: browsers don't send custom headers on a preflight, so there is no token here.\n // Only allow /api/upload, the one cross-origin POST the frontend really makes, and only for null / our own origin;\n // the preflight itself returns no data, and the real request still has to pass the token check.\n if (req.method === \"OPTIONS\") {\n if (pathname !== \"/api/upload\" || origin === \"none\") {\n sendJson(res, 403, { ok: false, e: { code: \"bad_preflight\", message: tr(\"http.badPreflight\") } });\n return;\n }\n send(res, 204, \"\", {\n \"access-control-allow-origin\": origin === \"opaque\" ? \"null\" : `http://127.0.0.1:${cfg.port}`,\n \"access-control-allow-headers\": \"x-agent-console, content-type\",\n \"access-control-allow-methods\": \"GET, POST, OPTIONS\",\n \"access-control-max-age\": \"600\",\n vary: \"origin\",\n });\n return;\n }\n\n // Token routes: the token is the only authorization\n if (isApi || isAttachment) {\n const headerToken = req.headers[\"x-agent-console\"];\n // Attachments accept ?t= ( can't send custom headers); the API only accepts the header\n const queryToken = isAttachment ? url.searchParams.get(\"t\") : null;\n const validToken =\n (typeof headerToken === \"string\" && tokenEqual(headerToken, cfg.token)) ||\n (typeof queryToken === \"string\" && tokenEqual(queryToken, cfg.token));\n if (!validToken) {\n sendJson(res, 403, { ok: false, e: { code: \"bad_token\", message: tr(\"http.badToken\") } });\n return;\n }\n // In a sandbox iframe (no allow-same-origin) the page's origin is null, so even a same-address fetch is cross-origin:\n // the response needs allow-origin: null to be readable. It's only sent after the token is verified,\n // so any Origin: null page without the token can read nothing.\n if (origin === \"opaque\") {\n res.setHeader(\"access-control-allow-origin\", \"null\");\n res.setHeader(\"vary\", \"origin\");\n }\n if (isApi) {\n await routeApi(req, res, pathname, url);\n return;\n }\n const id = safeDecode(pathname.slice(\"/attachments/\".length));\n const a = id === null ? null : await attachments.get(id);\n if (!a) {\n sendJson(res, 404, { ok: false, e: { code: \"not_found\", message: tr(\"http.noAttachment\") } });\n return;\n }\n const data = await attachments.read(a.id);\n send(res, 200, data ?? Buffer.alloc(0), { ...STATIC_HEADERS, \"content-type\": a.mime });\n return;\n }\n\n // Static assets: refuse Origin: null. Ordinary navigations and `;\n const head = /]*)?>/i.exec(html);\n if (head) return html.slice(0, head.index + head[0].length) + tag + html.slice(head.index + head[0].length);\n const root = /]*)?>/i.exec(html);\n if (root) return html.slice(0, root.index + root[0].length) + tag + html.slice(root.index + root[0].length);\n const doctype = /^\\s*]*>/i.exec(html);\n if (doctype) return html.slice(0, doctype[0].length) + tag + html.slice(doctype[0].length);\n return tag + html;\n}\n","// Preview proxy (1.2): a local-only reverse proxy, one 127.0.0.1: listener per loopback target origin.\n//\n// Why: Magpie's page frame is sandbox=\"allow-scripts\" and the sandbox is inherited by every child frame, so a plain\n// `); +}); +const attackerPort = await listen(attacker); + +// ---- legit: Magpie-like page → sandboxed console-like frame → the preview iframe ---- +const PING = "/__agent_console__/ping"; +const consoleJs = ` +(async () => { + const pingOnce = async (origin, expect) => { + try { + const r = await fetch(origin + ${JSON.stringify(PING)}, { cache: "no-store", credentials: "omit", referrerPolicy: "no-referrer" }); + const body = await r.text(); + return r.status + " " + (body === expect ? "nonce-ok" : ("nonce-bad:" + body.slice(0, 40))); + } catch (e) { return "ERR " + e.name; } + }; + let ping = "n/a"; + let canary = "n/a"; + if (${JSON.stringify(proxyOrigin)}.indexOf(".localhost:") > 0) { + canary = await pingOnce(${JSON.stringify(canaryOrigin)}, ${JSON.stringify(canaryNonce)}); + ping = await pingOnce(${JSON.stringify(proxyOrigin)}, ${JSON.stringify(nonce)}); + } + addEventListener("message", (e) => { if (e.data && e.data.app) parent.postMessage({ legit: Object.assign({ ping, canary }, e.data.app) }, "*"); }); + if (!/nonce-ok/.test(canary) || !/nonce-ok/.test(ping)) { + parent.postMessage({ legit: { ping, canary, module: "SKIPPED", secret: "SKIPPED", admin: "SKIPPED", image: false, ws: "SKIPPED" } }, "*"); + return; + } + const f = document.createElement("iframe"); f.src = ${JSON.stringify(proxyHref)}; f.referrerPolicy = "no-referrer"; document.body.appendChild(f); +})();`; +const magpieSim = http.createServer((_q, res) => { + res.writeHead(200, { "content-type": "text/html" }); + res.end(` +`); +}); +const magpiePort = await listen(magpieSim); + +async function run(name, type, opts) { + hits.length = 0; + const browser = await type.launch({ headless: true, ...opts }); + const page = await browser.newPage(); + const get = async (url) => { + await page.goto(url); + for (let i = 0; i < 80; i++) { const r = await page.evaluate(() => window.__r); if (r) return r; await sleep(150); } + return "no result"; + }; + const attack = await get(`http://127.0.0.1:${attackerPort}/`); + await sleep(500); + const attackerHits = hits.filter((h) => h.includes("attacker")); + const legit = await get(`http://127.0.0.1:${magpiePort}/`); + await browser.close(); + return { browser: name, attack, attackerHitsOnDevServer: attackerHits, legit }; +} + +const results = []; +const browsers = []; +if (which === "chromium" || which === "all") browsers.push(["chromium", chromium, { executablePath: findBrowser(), args: ["--no-sandbox"] }]); +if (which === "webkit" || which === "all") browsers.push(["webkit", webkit, {}]); +for (const [n, t, o] of browsers) { + try { results.push(await run(n, t, o)); } catch (e) { results.push({ browser: n, error: String(e).split("\n")[0] }); } +} +ws.close(); +daemon.kill(); +dev.close(); attacker.close(); magpieSim.close(); +await sleep(200); +rmSync(data, { recursive: true, force: true }); + +let bad = false; +for (const r of results) { + if (r.error) { bad = true; continue; } + const leaked = Object.values(r.attack).some((v) => /DEV-SECRET|ADMIN-ACTION|READ /.test(String(v))) || r.attackerHitsOnDevServer.length > 0; + const l = r.legit; + const works = l && /nonce-ok/.test(l.canary) && /nonce-ok/.test(l.ping) && l.module === "MODULE-OK" && l.secret === "DEV-SECRET-4242" && /ADMIN-ACTION-DONE legit/.test(l.admin) && l.image === true && l.ws === "echo:hi"; + r.verdict = { attackerGotIn: leaked, legitPreviewWorks: !!works }; + if (leaked || !works) bad = true; +} +console.log(JSON.stringify({ daemon: daemonPath.replace(root + "/", ""), proxyOrigin: proxyOrigin.replace(/ac[0-9a-f]{32}/, "ac"), results }, null, 2)); +process.exit(bad ? 1 : 0); diff --git a/packages/agent-console/test/v1/ac12.test.ts b/packages/agent-console/test/v1/ac12.test.ts new file mode 100644 index 0000000..dcd9748 --- /dev/null +++ b/packages/agent-console/test/v1/ac12.test.ts @@ -0,0 +1,488 @@ +// 1.2: preview proxy security rules, local-link detection, path chips, content width / chat font size, live Magpie theme. +import { describe, expect, it, afterEach } from "vitest"; +import http from "node:http"; +import net from "node:net"; +import { existsSync, mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve, sep } from "node:path"; +import { pathToFileURL } from "node:url"; +import { request as netRequest } from "./helpers-net.js"; + +// Preview listeners answer only at ac.localhost: (#582): requests below go there unless a test sets Host itself +const proxyHosts = new Map(); +function remember(r: T): T { + const u = new URL(r.proxyOrigin); + proxyHosts.set(Number(u.port), u.host); + return r; +} +const request = (port: number, path: string, headers: Record = {}, method?: string) => + netRequest(port, path, { host: proxyHosts.get(port) ?? `127.0.0.1:${port}`, ...headers }, method); +import { checkPreviewUrl, deniedPort, displayHref, externalHref, withScheme } from "../../daemon/src/preview/url.js"; +import { PreviewProxy, rewriteLocation, stripFrameAncestors } from "../../daemon/src/preview/proxy.js"; +import { injectScriptTag, PREVIEW_SCRIPT_PATH } from "../../daemon/src/preview/inject.js"; +import { previewDeniedPorts } from "../../daemon/src/preview/ports.js"; +import { openExternal, openerFor } from "../../daemon/src/util/openExternal.js"; +import { insideRoot, mentionSection, resolveMentions, withMentions } from "../../daemon/src/util/mentions.js"; +import { buildAcpPrompt } from "../../daemon/src/providers/acp/prompt.js"; +import { parseSettingsPatch, sanitizeStored, DEFAULT_SETTINGS } from "../../daemon/src/store/settings.js"; +import { parseConfig } from "../../daemon/src/config.js"; +import { findLocalLinks, localHref, splitLocalLinks } from "../../web/src/util/localLinks.js"; +import { addMention, joinProjectPath, mentionsForSend, parseMentionDrag, relFromAbs } from "../../web/src/composer/mentions.js"; +import { colValue, normalizeChatFont, normalizeContentWidth } from "../../web/src/layout/chatLayout.js"; +import { parseMagpieTheme, themeFromMessage } from "../../web/src/layout/magpieBridge.js"; +import { magpieTokenVars } from "../../web/src/layout/applyMagpieTokens.js"; + +describe("preview URL rules", () => { + it("normalizes what people type", () => { + expect(withScheme("5173")).toBe("http://localhost:5173/"); + expect(withScheme(":5173/x")).toBe("http://localhost:5173/x"); + expect(withScheme("localhost:5173")).toBe("http://localhost:5173"); + const ok = (s: string) => { const c = checkPreviewUrl(s); return c.ok ? c.target.href : null; }; + expect(ok("5173")).toBe("http://localhost:5173/"); + expect(ok("localhost:3000/a?b=1#c")).toBe("http://localhost:3000/a?b=1#c"); + expect(ok("http://127.0.0.1:5173/x")).toBe("http://127.0.0.1:5173/x"); + expect(ok("127.1.2.3:80")).toBe("http://127.1.2.3/"); + expect(ok("0.0.0.0:8080")).toBe("http://0.0.0.0:8080/"); + expect(ok("http://[::1]:4000/")).toBe("http://[::1]:4000/"); + expect(ok("app.localhost:3000")).toBe("http://app.localhost:3000/"); + expect(ok("https://localhost:8443")).toBe("https://localhost:8443/"); + }); + it("refuses anything that isn't a loopback http(s) URL", () => { + const why = (s: string) => { const c = checkPreviewUrl(s); return c.ok ? "ok" : c.reason; }; + expect(why("")).toBe("empty"); + expect(why("example.com")).toBe("not_local"); + expect(why("192.168.1.10:3000")).toBe("not_local"); + expect(why("10.0.0.1:80")).toBe("not_local"); + expect(why("localhost.evil.com:80")).toBe("not_local"); + expect(why("127.0.0.1.nip.io:80")).toBe("not_local"); + expect(why("http://user:pw@localhost:3000")).toBe("userinfo"); + expect(why("file:///etc/passwd")).toBe("scheme"); + expect(why("javascript:alert(1)")).toBe("scheme"); + expect(why("ftp://localhost:21")).toBe("scheme"); + expect(why("localhost:99999")).toBe("bad_url"); + expect(why("http://localhost:3000/" + "a".repeat(2100))).toBe("too_long"); + }); + it("connects localhost to IPv4 first, then ::1; 0.0.0.0 to 127.0.0.1", () => { + const c = checkPreviewUrl("localhost:5173"); + expect(c.ok && c.target.connect).toEqual(["127.0.0.1", "::1"]); + const z = checkPreviewUrl("0.0.0.0:5173"); + expect(z.ok && z.target.connect).toEqual(["127.0.0.1"]); + const v6 = checkPreviewUrl("[::1]:5173"); + expect(v6.ok && v6.target.connect).toEqual(["::1"]); + }); + it("denies the daemon, gate and Magpie ports", () => { + const d = previewDeniedPorts({ port: 41000, gatePort: 3499 }, { MAGPIE_ADDR: "127.0.0.1:3525" }); + for (const p of [41000, 3499, 3488, 3425, 3430, 3525]) expect(deniedPort(p, d)).toBe(true); + expect(deniedPort(5173, d)).toBe(false); + expect(previewDeniedPorts({ port: 1 }, { AGENT_CONSOLE_PREVIEW_DENY: "9000, 9001" })).toEqual(expect.arrayContaining([9000, 9001])); + expect(parseConfig(["--port", "0", "--gate-port", "3555"]).gatePort).toBe(3555); + expect(parseConfig(["--gate-port", "nope"]).gatePort).toBeUndefined(); + }); + it("maps a proxied href back to the target for the address bar", () => { + expect(displayHref("http://127.0.0.1:4444/a?b#c", "http://127.0.0.1:4444", "http://localhost:5173")).toBe("http://localhost:5173/a?b#c"); + expect(displayHref("http://127.0.0.1:4444/", "http://127.0.0.1:4444", "http://localhost:80")).toBe("http://localhost/"); + }); +}); + +describe("app.openExternal", () => { + it("only takes http(s), re-serialized", () => { + expect(externalHref("https://example.com/a b")).toBe("https://example.com/a%20b"); + expect(externalHref("javascript:alert(1)")).toBeNull(); + expect(externalHref("file:///C:/Windows/system32/calc.exe")).toBeNull(); + expect(externalHref("vscode://open?x")).toBeNull(); + expect(externalHref("not a url")).toBeNull(); + expect(externalHref("https://x.com/?q=a&b=|c")).toBeNull(); // odd characters left by URL: refused + }); + it("uses a no-shell opener per OS", () => { + const href = "https://example.com/?a=1&b=2"; + expect(openerFor("win32", href)).toEqual({ cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", href] }); + expect(openerFor("darwin", href)).toEqual({ cmd: "open", args: [href] }); + expect(openerFor("linux", href)).toEqual({ cmd: "xdg-open", args: [href] }); + }); + it("runs execFile with one argument and reports a missing opener", async () => { + const calls: { cmd: string; args: string[] }[] = []; + const ok = await openExternal("https://example.com/x?y=1&z=2", { + platform: "win32", + exec: (cmd, args, _o, cb) => { calls.push({ cmd, args }); setTimeout(() => cb(null), 1); return { on: () => {} }; }, + }); + expect(ok.ok).toBe(true); + expect(calls).toEqual([{ cmd: "rundll32.exe", args: ["url.dll,FileProtocolHandler", "https://example.com/x?y=1&z=2"] }]); + const missing = await openExternal("https://example.com/", { + platform: "linux", + exec: () => ({ on: (_e: string, fn: (e: Error) => void) => setTimeout(() => fn(new Error("ENOENT")), 1) }), + }); + expect(missing.ok).toBe(false); + expect((await openExternal("file:///etc/passwd", { exec: () => { throw new Error("must not run"); } })).ok).toBe(false); + }); +}); + +// ---- the proxy against a real upstream ---- +type Up = { server: http.Server; port: number; seen: http.IncomingHttpHeaders[] }; +async function upstream(handler: (req: http.IncomingMessage, res: http.ServerResponse) => void): Promise { + const seen: http.IncomingHttpHeaders[] = []; + const server = http.createServer((req, res) => { seen.push(req.headers); handler(req, res); }); + server.on("upgrade", (req, socket) => { + seen.push(req.headers); + socket.write("HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\n\r\n"); + socket.on("data", (d) => socket.write(Buffer.concat([Buffer.from("echo:"), d]))); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", () => r())); + return { server, port: (server.address() as net.AddressInfo).port, seen }; +} + +describe("preview proxy", () => { + const cleanup: (() => void)[] = []; + afterEach(() => { for (const f of cleanup.splice(0)) f(); }); + + async function setup(handler: Parameters[0], opts: Partial[0]> = {}) { + const up = await upstream(handler); + const proxy = new PreviewProxy({ deniedPorts: () => [], ...opts }); + cleanup.push(() => { proxy.closeAll(); up.server.close(); }); + const r = remember(await proxy.open(`http://localhost:${up.port}/start`)); + const port = Number(new URL(r.proxyOrigin).port); + return { up, proxy, r, port }; + } + + it("opens one random-port listener per target and refuses denied ports", async () => { + const { proxy, r, up, port } = await setup((_q, s) => s.end("ok")); + expect(r.proxyOrigin).toMatch(/^http:\/\/ac[0-9a-f]{32}\.localhost:\d+$/); + expect(r.proxyHref).toBe(`${r.proxyOrigin}/start`); + expect(r.target).toBe(`http://localhost:${up.port}`); + const again = await proxy.open(`localhost:${up.port}/other`); + expect(again.proxyOrigin).toBe(r.proxyOrigin); + await expect(proxy.open(`localhost:${port}`)).rejects.toMatchObject({ code: "denied_port" }); // the proxy itself + const p2 = new PreviewProxy({ deniedPorts: () => [up.port] }); + await expect(p2.open(`localhost:${up.port}`)).rejects.toMatchObject({ code: "denied_port" }); + await expect(p2.open("example.com:80")).rejects.toMatchObject({ code: "not_local" }); + p2.closeAll(); + }); + + it("checks Host and Origin; rewrites Host/Origin/Referer upstream; strips cookies", async () => { + const { up, port } = await setup((_q, s) => s.end("hi")); + expect((await request(port, "/", { host: `evil.test:${port}` })).status).toBe(421); + expect((await request(port, "/", { host: `127.0.0.1:${port + 1}` })).status).toBe(421); + // the bare loopback address (no key) is refused, with nothing a page could read (#582) + for (const host of [`127.0.0.1:${port}`, `localhost:${port}`, `ac${"0".repeat(32)}.localhost:${port}`]) { + const no = await request(port, "/", { host, origin: "null" }); + expect([403, 421]).toContain(no.status); + expect(no.headers["access-control-allow-origin"]).toBeUndefined(); + } + expect((await request(port, "/", { origin: "https://evil.test" })).status).toBe(403); + expect((await request(port, "/", { origin: "http://localhost:3430" })).status).toBe(403); + const ok = await request(port, "/x", { origin: "null", cookie: "magpie=secret", referer: `http://${proxyHosts.get(port)}/a`, "sec-fetch-site": "cross-site" }); + expect(ok.status).toBe(200); + expect(ok.headers["access-control-allow-origin"]).toBe("null"); + const h = up.seen.at(-1)!; + expect(h.host).toBe(`localhost:${up.port}`); + expect(h.origin).toBe(`http://localhost:${up.port}`); + expect(h.referer).toBe(`http://localhost:${up.port}/a`); + expect(h["sec-fetch-site"]).toBe("same-origin"); + expect(h.cookie).toBeUndefined(); + expect(h["accept-encoding"]).toBe("identity"); + // no Origin stays no Origin + await request(port, "/y"); + expect(up.seen.at(-1)!.origin).toBeUndefined(); + }); + + it("drops X-Frame-Options, frame-ancestors and Set-Cookie; rewrites a redirect to the target", async () => { + const { up, port, r } = await setup((req, s) => { + if (req.url === "/go") { s.writeHead(302, { location: `http://localhost:${up.port}/there?q=1` }); s.end(); return; } + if (req.url === "/away") { s.writeHead(302, { location: "https://example.com/" }); s.end(); return; } + s.writeHead(200, { "x-frame-options": "DENY", "content-security-policy": "default-src 'self'; frame-ancestors 'none'", "set-cookie": "sid=1", "access-control-allow-origin": "*" }); + s.end("x"); + }); + const res = await request(port, "/"); + expect(res.headers["x-frame-options"]).toBeUndefined(); + expect(res.headers["content-security-policy"]).toBe("default-src 'self'"); + expect(res.headers["set-cookie"]).toBeUndefined(); + expect(res.headers["access-control-allow-origin"]).toBe("null"); + expect((await request(port, "/go")).headers.location).toBe(`${r.proxyOrigin}/there?q=1`); + expect((await request(port, "/away")).headers.location).toBe("https://example.com/"); + expect(stripFrameAncestors("frame-ancestors 'self'")).toBe(""); + }); + + it("injects the bridge script into HTML (chunked, no ) and serves it itself", async () => { + const { port } = await setup((req, s) => { + s.writeHead(200, { "content-type": "text/html; charset=utf-8" }); + if (req.url === "/nohead") { s.write(""); s.end("hi"); return; } + s.write("t"); + s.end("é"); + }); + const a = await request(port, "/"); + expect(a.body).toContain(``); + expect(a.body).toContain("é"); + expect(Number(a.headers["content-length"])).toBe(Buffer.byteLength(a.body)); + const b = await request(port, "/nohead"); + expect(b.body.startsWith(`<!doctype html><script src="${PREVIEW_SCRIPT_PATH}">`)).toBe(true); + const js = await request(port, PREVIEW_SCRIPT_PATH); + expect(js.status).toBe(200); + expect(js.headers["content-type"]).toContain("javascript"); + expect(js.body).toContain("ac_preview"); + expect(injectScriptTag("<p>x</p>")).toBe(`<script src="${PREVIEW_SCRIPT_PATH}"></script><p>x</p>`); + expect(injectScriptTag("<header>x</header>")).toBe(`<script src="${PREVIEW_SCRIPT_PATH}"></script><header>x</header>`); + }); + + it("answers CORS preflight for the opaque frame", async () => { + const { port } = await setup((_q, s) => s.end()); + const r = await request(port, "/api", { origin: "null", "access-control-request-method": "POST", "access-control-request-headers": "content-type" }, "OPTIONS"); + expect(r.status).toBe(204); + expect(r.headers["access-control-allow-origin"]).toBe("null"); + expect(r.headers["access-control-allow-headers"]).toBe("content-type"); + }); + + it("shows an error page when the dev server isn't running", async () => { + const dead = await upstream((_q, s) => s.end()); + const deadPort = dead.port; + await new Promise((r) => dead.server.close(r)); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + const r = remember(await proxy.open(`localhost:${deadPort}`)); + const res = await request(Number(new URL(r.proxyOrigin).port), "/"); + expect(res.status).toBe(502); + expect(res.body).toContain(`localhost:${deadPort}`); + expect(res.body).toContain("Retry"); + }); + + it("tunnels WebSocket upgrades (HMR) with the Origin rewritten, and refuses a foreign Origin", async () => { + const { up, port } = await setup((_q, s) => s.end()); + const talk = (origin: string, host = proxyHosts.get(port)!) => new Promise<string>((resolve) => { + const s = net.connect(port, "127.0.0.1", () => { + s.write(`GET /hmr HTTP/1.1\r\nhost: ${host}\r\nupgrade: websocket\r\nconnection: Upgrade\r\norigin: ${origin}\r\nsec-websocket-key: x\r\nsec-websocket-version: 13\r\n\r\n`); + }); + let got = ""; + s.on("data", (d) => { + got += d.toString(); + if (got.includes("101") && !got.includes("echo:")) s.write("ping"); + if (got.includes("echo:ping") || got.includes("403") || got.includes("421")) { s.destroy(); resolve(got); } + }); + s.on("close", () => resolve(got)); + }); + const ok = await talk("null"); + expect(ok).toContain("101 Switching Protocols"); + expect(ok).toContain("echo:ping"); + expect(up.seen.at(-1)!.origin).toBe(`http://localhost:${up.port}`); + expect(up.seen.at(-1)!.host).toBe(`localhost:${up.port}`); + expect(await talk("https://evil.test")).toContain("403"); + expect(await talk("null", `127.0.0.1:${port}`)).toContain("403"); // no key (#582) + }); + + it("closes idle listeners (fake clock), on release, and keeps at most N targets", async () => { + let now = 1000; + const a = await upstream((_q, s) => s.end("a")); + const b = await upstream((_q, s) => s.end("b")); + const proxy = new PreviewProxy({ deniedPorts: () => [], now: () => now, idleMs: 10_000, maxTargets: 1 }); + cleanup.push(() => { proxy.closeAll(); a.server.close(); b.server.close(); }); + const ra = remember(await proxy.open(`localhost:${a.port}`)); + const rb = remember(await proxy.open(`localhost:${b.port}`)); + expect(proxy.size).toBe(1); // a was closed for b + expect(proxy.ports()).toEqual([Number(new URL(rb.proxyOrigin).port)]); + await expect(request(Number(new URL(ra.proxyOrigin).port), "/")).rejects.toThrow(); + now += 5_000; + proxy.sweep(); + expect(proxy.size).toBe(1); + now += 20_000; + proxy.sweep(); + expect(proxy.size).toBe(0); + await proxy.open(`localhost:${b.port}`); + expect(proxy.release(`http://localhost:${b.port}/anything`)).toBe(true); + expect(proxy.size).toBe(0); + }); + + it("rewriteLocation leaves relative and foreign redirects alone", () => { + const c = checkPreviewUrl("localhost:5173"); + if (!c.ok) throw new Error("x"); + expect(rewriteLocation("/login", c.target, "http://127.0.0.1:9")).toBe("/login"); + expect(rewriteLocation("http://localhost:5173/a", c.target, "http://127.0.0.1:9")).toBe("http://127.0.0.1:9/a"); + expect(rewriteLocation("http://localhost:5174/a", c.target, "http://127.0.0.1:9")).toBe("http://localhost:5174/a"); + }); +}); + +describe("local links in chat", () => { + const urls = (s: string) => findLocalLinks(s).map((l) => l.text); + it("finds local addresses, with or without a scheme", () => { + expect(urls("open http://localhost:5173/ now")).toEqual(["http://localhost:5173/"]); + expect(urls("跑在 localhost:3000 上了")).toEqual(["localhost:3000"]); + expect(urls("地址:127.0.0.1:8080/api?x=1,然后")).toEqual(["127.0.0.1:8080/api?x=1"]); + expect(urls("bind 0.0.0.0:8000 and [::1]:4000")).toEqual(["0.0.0.0:8000", "[::1]:4000"]); + expect(urls("app.localhost:3000.")).toEqual(["app.localhost:3000"]); + expect(urls("(see localhost:3000)")).toEqual(["localhost:3000"]); + expect(urls("Local: http://localhost:5173/,")).toEqual(["http://localhost:5173/"]); + expect(urls("go to localhost:3000/a/(b)")).toEqual(["localhost:3000/a/(b)"]); + expect(urls("(见 localhost:3000/a)")).toEqual(["localhost:3000/a"]); + }); + it("leaves other text alone", () => { + expect(urls("runs on localhost")).toEqual([]); + expect(urls("xlocalhost:3000 foo/localhost:3000 user@localhost:22")).toEqual([]); + expect(urls("http://192.168.1.2:3000 and 10.0.0.1:80")).toEqual([]); + expect(urls("localhost.evil.com:80")).toEqual([]); + }); + it("normalizes to a URL the preview opens", () => { + expect(findLocalLinks("localhost:3000")[0]!.url).toBe("http://localhost:3000/"); + expect(splitLocalLinks("a localhost:1 b")).toEqual(["a ", expect.objectContaining({ text: "localhost:1" }), " b"]); + expect(localHref("http://localhost:3000/x")).toBe("http://localhost:3000/x"); + expect(localHref("https://example.com")).toBeNull(); + expect(localHref("localhost:3000")).toBeNull(); // hrefs need a scheme + }); +}); + +describe("path chips (mentions)", () => { + let dir = ""; + afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; }); + it("resolves inside the project only (../, absolute, symlink escape, missing)", async () => { + dir = mkdtempSync(join(tmpdir(), "ac12-m-")); + const proj = join(dir, "proj"); + mkdirSync(join(proj, "src"), { recursive: true }); + writeFileSync(join(proj, "src", "a b.ts"), "x"); + writeFileSync(join(dir, "secret.txt"), "s"); + try { symlinkSync(join(dir, "secret.txt"), join(proj, "link.txt")); } catch {} + const r = await resolveMentions(proj, [ + { rel: "src/a b.ts" }, { rel: "src", isDir: true }, { rel: "src/a b.ts" }, + { rel: "../secret.txt" }, { rel: "/etc/passwd" }, { rel: "C:/x" }, { rel: "link.txt" }, { rel: "nope.ts" }, + ]); + // the path as the project was opened, with this OS's separators (#582: not the realpath, not always "/") + expect(r.mentions.map((m) => [m.path, m.isDir])).toEqual([[join(proj, "src", "a b.ts"), false], [join(proj, "src"), true]]); + expect(r.warnings).toEqual(expect.arrayContaining(["../secret.txt", "/etc/passwd", "C:/x", "nope.ts"])); + if (process.platform !== "win32") expect(r.warnings).toContain("link.txt"); + }); + it("keeps the project path as opened when it goes through a symlink (macOS /var → /private/var, a linked workspace)", async () => { + dir = realpathSync(mkdtempSync(join(tmpdir(), "ac12-ml-"))); + const realProj = join(dir, "real", "proj"); + mkdirSync(join(realProj, "src"), { recursive: true }); + writeFileSync(join(realProj, "src", "a.ts"), "x"); + writeFileSync(join(dir, "outside.txt"), "o"); + const alias = join(dir, "alias"); + try { symlinkSync(join(dir, "real"), alias, "junction"); } catch { return; } // no symlinks allowed here: nothing to check + const proj = join(alias, "proj"); + // a link inside the project that points back into it through the real path is fine; one that leaves it is not + try { symlinkSync(join(realProj, "src", "a.ts"), join(realProj, "inner.ts")); } catch {} + try { symlinkSync(join(dir, "outside.txt"), join(realProj, "out.txt")); } catch {} + const r = await resolveMentions(proj, [{ rel: "src/a.ts" }, { rel: "src", isDir: true }, { rel: "." , isDir: true }, { rel: "../../outside.txt" }, { rel: "out.txt" }]); + expect(r.mentions.map((m) => m.path)).toEqual([join(proj, "src", "a.ts"), join(proj, "src"), proj]); + expect(r.warnings).toEqual(expect.arrayContaining(["../../outside.txt"])); + if (existsSync(join(realProj, "out.txt"))) expect(r.warnings).toContain("out.txt"); + if (existsSync(join(realProj, "inner.ts"))) { + const r2 = await resolveMentions(proj, [{ rel: "inner.ts" }]); + expect(r2.mentions.map((m) => m.path)).toEqual([join(proj, "inner.ts")]); + } + // a project opened with a trailing separator or a "." segment is the same project + const r3 = await resolveMentions(proj + sep + "." + sep, [{ rel: "src/a.ts" }]); + expect(r3.mentions.map((m) => m.path)).toEqual([join(proj, "src", "a.ts")]); + }); + it("serializes for every Agent; ACP also gets resource_link blocks", async () => { + const P = resolve(sep, "p"); + const m = [{ path: join(P, "src", "a b.ts"), isDir: false }, { path: join(P, "src"), isDir: true }]; + const slash = sep === "\\" ? "\\" : "/"; + expect(mentionSection(m)).toBe(`Referenced files (read them as needed):\n- \`${m[0]!.path}\`\n- ${m[1]!.path}${slash} (folder)`); + expect(mentionSection([{ path: "/p/src/a b.ts", isDir: false }, { path: "/p/src", isDir: true }])).toBe("Referenced files (read them as needed):\n- `/p/src/a b.ts`\n- /p/src/ (folder)"); + expect(withMentions("fix it", m)).toBe("fix it\n\n" + mentionSection(m)); + expect(withMentions("", m)).toBe(mentionSection(m)); + expect(withMentions("x", [])).toBe("x"); + expect(mentionSection([{ path: "C:\\p\\src", isDir: true }])).toContain("C:\\p\\src\\ (folder)"); + const built = await buildAcpPrompt(withMentions("fix", m), [], { image: false, audio: false, embeddedContext: false }, m); + expect(built.blocks[0]).toMatchObject({ type: "text" }); + expect(built.blocks.filter((b) => b.type === "resource_link").map((b) => (b as { uri: string }).uri)).toEqual([pathToFileURL(m[0]!.path).href, pathToFileURL(m[1]!.path).href]); + if (sep === "/") expect(pathToFileURL(m[0]!.path).href).toBe("file:///p/src/a%20b.ts"); + }); + it("insideRoot handles Windows case and prefixes", () => { + expect(insideRoot("C:\\Work\\App", "c:\\work\\app\\src", "win32")).toBe(true); + expect(insideRoot("C:\\Work\\App", "C:\\Work\\App2\\x", "win32")).toBe(false); + expect(insideRoot("/a/b", "/a/bc", "linux")).toBe(false); + }); + it("composer side: drag data, dedupe, send shape, resend paths", () => { + expect(parseMentionDrag(JSON.stringify({ projectId: "p1", rel: "src/a.ts", isDir: false }))).toEqual({ projectId: "p1", rel: "src/a.ts", isDir: false }); + expect(parseMentionDrag("{bad")).toBeNull(); + expect(parseMentionDrag(JSON.stringify({ projectId: 1, rel: "x" }))).toBeNull(); + let list = addMention([], { projectId: "p", rel: "a", isDir: false }); + list = addMention(list, { projectId: "p", rel: "a", isDir: false }); + list = addMention(list, { projectId: "p", rel: "d", isDir: true }); + expect(mentionsForSend(list)).toEqual([{ rel: "a", isDir: false }, { rel: "d", isDir: true }]); + expect(joinProjectPath("/home/u/p", "src/a.ts")).toBe("/home/u/p/src/a.ts"); + expect(joinProjectPath("C:\\work\\p\\", "src/a.ts")).toBe("C:\\work\\p\\src\\a.ts"); + expect(relFromAbs("/home/u/p", "/home/u/p/src/a.ts")).toBe("src/a.ts"); + expect(relFromAbs("C:\\Work\\P", "c:\\work\\p\\src")).toBe("src"); + expect(relFromAbs("/home/u/p", "/home/u/p2/x")).toBeNull(); + }); +}); + +describe("content width and chat font size", () => { + it("settings accept the presets and 12–18 px only", () => { + expect(DEFAULT_SETTINGS.contentWidth).toBe("default"); + expect(DEFAULT_SETTINGS.chatFontSize).toBe(13); + for (const w of ["narrow", "default", "wide", "full"]) expect(parseSettingsPatch({ contentWidth: w }).ok).toBe(true); + expect(parseSettingsPatch({ contentWidth: "huge" }).ok).toBe(false); + expect(parseSettingsPatch({ chatFontSize: 12 }).ok).toBe(true); + expect(parseSettingsPatch({ chatFontSize: 18 }).ok).toBe(true); + expect(parseSettingsPatch({ chatFontSize: 11 }).ok).toBe(false); + expect(parseSettingsPatch({ chatFontSize: 19 }).ok).toBe(false); + expect(parseSettingsPatch({ chatFontSize: 13.5 }).ok).toBe(false); + expect(parseSettingsPatch({ sidebarHidden: true }).ok).toBe(true); + expect(sanitizeStored({ contentWidth: "x", chatFontSize: 40, theme: "dark" })).toEqual({ theme: "dark" }); + }); + it("maps to CSS values", () => { + expect(colValue("narrow")).toBe("640px"); + expect(colValue("default")).toBe("720px"); + expect(colValue("wide")).toBe("880px"); + expect(colValue("full")).toBe("100%"); + expect(colValue("bogus")).toBe("720px"); + expect(normalizeContentWidth(undefined)).toBe("default"); + expect(normalizeChatFont(undefined)).toBe(13); + expect(normalizeChatFont(9)).toBe(12); + expect(normalizeChatFont(30)).toBe(18); + expect(normalizeChatFont("16")).toBe(16); + }); +}); + +describe("live Magpie theme (bridge messages after the redirect)", () => { + it("reads theme events and our hello answer only", () => { + expect(themeFromMessage({ magpie: 1, event: "theme", data: { dark: true, lang: "zh", tokens: { bg: "#111" } } }, 5)).toEqual({ dark: true, lang: "zh", tokens: { bg: "#111" } }); + expect(themeFromMessage({ magpie: 1, id: 5, result: { dark: false, tokens: {} } }, 5)).toEqual({ dark: false, tokens: {} }); + expect(themeFromMessage({ magpie: 1, id: 6, result: { dark: false } }, 5)).toBeNull(); + expect(themeFromMessage({ event: "theme", data: { dark: true } }, 5)).toBeNull(); + expect(themeFromMessage({ magpie: 1, event: "theme", data: { dark: "yes" } }, 5)).toBeNull(); + expect(parseMagpieTheme({ dark: true, tokens: [1] })).toEqual({ dark: true, tokens: {} }); + }); + it("keeps neutral tokens, drops the accent and odd values", () => { + expect(magpieTokenVars({ bg: "#111", "fg-2": "#eee", accent: "#f00", "accent-soft": "#f00", bad: "red;}", "x y": "1", font: "Inter, sans-serif" })).toEqual({ + "--magpie-bg": "#111", "--magpie-fg-2": "#eee", "--magpie-font": "Inter, sans-serif", + }); + }); +}); + +describe("1.2 QA fixes", () => { + it("Claude Write says Create for a new file, Overwrite for an existing one", async () => { + const { targetExists, callInfo } = await import("../../daemon/src/agents/kinds.js"); + const dir = mkdtempSync(join(tmpdir(), "ac12-k-")); + writeFileSync(join(dir, "old.txt"), "x"); + expect(targetExists({ file_path: join(dir, "old.txt") })).toBe(true); + expect(targetExists({ file_path: "old.txt" }, dir)).toBe(true); + expect(targetExists({ file_path: join(dir, "new.txt") })).toBe(false); + expect(targetExists({})).toBe(false); + const create = callInfo("Write", { file_path: join(dir, "new.txt"), _exists: targetExists({ file_path: join(dir, "new.txt") }) }, dir); + expect(create.title).toMatch(/新建|Create/); + rmSync(dir, { recursive: true, force: true }); + }); + it("the theme bridge carries Magpie's language, and the UI language can switch at runtime", async () => { + expect(parseMagpieTheme({ dark: false, lang: "en", tokens: {} })).toEqual({ dark: false, lang: "en", tokens: {} }); + expect(parseMagpieTheme({ dark: false, lang: "x".repeat(40) })).toEqual({ dark: false, tokens: {} }); + const i18n = await import("../../web/src/i18n/index.js"); + i18n.initLocale("?lang=zh"); + expect(i18n.t("sidebar.newProject")).toBe("新建项目"); + expect(i18n.setLocale("en")).toBe(true); + expect(i18n.t("sidebar.newProject")).toBe("New project"); + expect(i18n.setLocale("en-US")).toBe(false); + expect(i18n.setLocale("zh-TW")).toBe(true); + expect(i18n.tf("timeline.toolSummaryOne", { n: 1, parts: "读取 1" })).toBe("已执行 1 步 · 读取 1"); + }); + it("every new 1.2 key exists in both languages", async () => { + const { messages } = await import("../../web/src/i18n/messages.js"); + const keys = (o: Record<string, unknown>, p = ""): string[] => Object.entries(o).flatMap(([k, v]) => (typeof v === "object" && v ? keys(v as Record<string, unknown>, p + k + ".") : [p + k])); + const zh = new Set(keys(messages.zh as unknown as Record<string, unknown>)); + const en = new Set(keys(messages.en as unknown as Record<string, unknown>)); + for (const k of ["preview.tab", "preview.empty", "preview.limits", "preview.noLocalhost", "links.openPreviewTitle", "links.externalFailed", "mention.add", "mention.drop", "sidebar.collapse", "sidebar.expand", "settings.contentWidth", "settings.chatFont", "timeline.toolSummaryOne"]) { + expect(zh.has(k), "zh " + k).toBe(true); + expect(en.has(k), "en " + k).toBe(true); + } + expect([...zh].filter((k) => !en.has(k) && !k.startsWith("composer.agentMode."))).toEqual([]); + expect([...en].filter((k) => !zh.has(k))).toEqual([]); + }); +}); diff --git a/packages/agent-console/test/v1/fix582.test.ts b/packages/agent-console/test/v1/fix582.test.ts new file mode 100644 index 0000000..6a9c197 --- /dev/null +++ b/packages/agent-console/test/v1/fix582.test.ts @@ -0,0 +1,463 @@ +// #582 review fixes: the preview proxy's key (Host ac<key>.localhost), Magpie's gateway found by its settings.json port +// and by how it answers, the per-open nonce the ping must echo (and the keyless canary before the keyed host is looked +// up), and Apple WebKit refused only when the daemon host is before macOS 26 (Darwin < 25 from os.release(); the UA is +// frozen at 10_15_7). The real-browser attack check is scripts/preview-attack.mjs (Chromium / WebKit). +import { describe, expect, it, afterEach, vi } from "vitest"; +import http from "node:http"; +import net from "node:net"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { platform as osPlatform, release as osRelease, tmpdir } from "node:os"; +import { join } from "node:path"; +import { request } from "./helpers-net.js"; +import { PreviewProxy, PREVIEW_PING_PATH, identify, looksLikeMagpie, magpieIndex } from "../../daemon/src/preview/proxy.js"; +import { magpieConfigDirs, magpieDirFromInstall, previewDeniedPorts, savedGatewayPort } from "../../daemon/src/preview/ports.js"; +import { checkPreviewUrl, deniedPort } from "../../daemon/src/preview/url.js"; +import { + PREVIEW_PING_PATH as WEB_PING, + canReachProxy, + confirmPreviewReachable, + DARWIN_LOCALHOST_LOOPBACK as WEB_DARWIN_LOCALHOST_LOOPBACK, + isAppleWebKit, + isUnsafeLocalhostResolver, + usePreview, +} from "../../web/src/stores/preview.js"; +import { DARWIN_LOCALHOST_LOOPBACK, previewHost } from "../../daemon/src/preview/host.js"; + +const cleanup: (() => void)[] = []; +afterEach(() => { for (const f of cleanup.splice(0)) f(); }); + +async function serve(handler: http.RequestListener): Promise<{ server: http.Server; port: number }> { + const server = http.createServer(handler); + await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r())); + cleanup.push(() => server.close()); + return { server, port: (server.address() as net.AddressInfo).port }; +} +const MAGPIE_INDEX = JSON.stringify({ apis: ["/v1/chat/completions"], models: 2, name: "magpie", pid: 1, version: "0.1.2391" }); +const hostOf = (proxyOrigin: string) => new URL(proxyOrigin).host; +const portOf = (proxyOrigin: string) => Number(new URL(proxyOrigin).port); + +describe("preview key (#582 finding 1)", () => { + it("each listener gets its own unguessable ac<key>.localhost name; only that Host is served", async () => { + const up = await serve((_q, s) => { s.setHeader("content-type", "text/plain"); s.end("DEV-SECRET"); }); + const up2 = await serve((_q, s) => s.end("two")); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + const a = await proxy.open(`localhost:${up.port}`); + const b = await proxy.open(`localhost:${up2.port}`); + expect(a.proxyOrigin).toMatch(/^http:\/\/ac[0-9a-f]{32}\.localhost:\d+$/); + expect(hostOf(a.proxyOrigin).split(".")[0]).not.toBe(hostOf(b.proxyOrigin).split(".")[0]); + const port = portOf(a.proxyOrigin); + // what any page can send: Origin null, the bare loopback port, a guessed name, b's key on a's port + for (const host of [`127.0.0.1:${port}`, `localhost:${port}`, `AC${"f".repeat(32)}.localhost:${port}`, `${hostOf(b.proxyOrigin).split(":")[0]}:${port}`]) { + for (const method of ["GET", "POST", "OPTIONS"]) { + const r = await request(port, "/", { host, origin: "null", "access-control-request-method": "POST" }, method); + expect([403, 421], `${method} ${host}`).toContain(r.status); + expect(r.headers["access-control-allow-origin"]).toBeUndefined(); + expect(r.body).not.toContain("DEV-SECRET"); + } + expect([403, 421]).toContain((await request(port, PREVIEW_PING_PATH, { host })).status); + } + // the right name: served, readable by the opaque frame, the key never sent on as a Referer + const ok = await request(port, "/", { host: hostOf(a.proxyOrigin), origin: "null" }); + expect(ok.status).toBe(200); + expect(ok.body).toBe("DEV-SECRET"); + expect(ok.headers["access-control-allow-origin"]).toBe("null"); + expect(ok.headers["referrer-policy"]).toBe("no-referrer"); + const ping = await request(port, PREVIEW_PING_PATH, { host: hostOf(a.proxyOrigin), origin: "null" }); + expect(ping.status).toBe(200); + expect(ping.body).toBe(a.nonce); + expect(ping.body).not.toBe("ok"); + expect(ping.headers["access-control-allow-origin"]).toBe("null"); + expect(a.nonce).toMatch(/^[0-9a-f]{32}$/); + expect(a.canaryOrigin).toMatch(/^http:\/\/acprobe[0-9a-f]{32}\.localhost:\d+$/); + expect(a.canaryNonce).toMatch(/^[0-9a-f]{32}$/); + expect(a.canaryNonce).not.toBe(a.nonce); + const canary = await request(port, PREVIEW_PING_PATH, { host: hostOf(a.canaryOrigin), origin: "null" }); + expect([canary.status, canary.body]).toEqual([200, a.canaryNonce]); + // canary is ping-only + expect((await request(port, "/", { host: hostOf(a.canaryOrigin), origin: "null" })).status).toBe(403); + expect(WEB_PING).toBe(PREVIEW_PING_PATH); + // the name is case-insensitive like any host name; the proxy's own origin is accepted, another is not + expect((await request(port, "/", { host: hostOf(a.proxyOrigin).toUpperCase() })).status).toBe(200); + expect((await request(port, "/", { host: hostOf(a.proxyOrigin), origin: a.proxyOrigin })).status).toBe(200); + expect((await request(port, "/", { host: hostOf(a.proxyOrigin), origin: `http://127.0.0.1:${port}` })).status).toBe(403); + }); + + it("a refused WebSocket upgrade never reaches the dev server", async () => { + let upgrades = 0; + const up = await serve((_q, s) => s.end()); + up.server.on("upgrade", (_q, sock) => { upgrades++; sock.destroy(); }); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + const r = await proxy.open(`localhost:${up.port}`); + const port = portOf(r.proxyOrigin); + const reply = await new Promise<string>((resolve) => { + const s = net.connect(port, "127.0.0.1", () => s.write(`GET /hmr HTTP/1.1\r\nhost: 127.0.0.1:${port}\r\nupgrade: websocket\r\nconnection: Upgrade\r\norigin: null\r\nsec-websocket-key: x\r\nsec-websocket-version: 13\r\n\r\n`)); + let got = ""; + s.on("data", (d) => { got += d; }); + s.on("close", () => resolve(got)); + }); + expect(reply).toContain("403"); + expect(upgrades).toBe(0); + }); +}); + +describe("Magpie's gateway is never previewed (#582 finding 2)", () => { + let dir = ""; + afterEach(() => { if (dir) rmSync(dir, { recursive: true, force: true }); dir = ""; }); + + it("reads the gateway port from Magpie's settings.json (XDG, ~/.config, portable, plugin-work)", () => { + dir = mkdtempSync(join(tmpdir(), "ac582-")); + const home = join(dir, "home"); + const xdg = join(dir, "xdg"); + const portable = join(dir, "Magpie", "data"); + for (const [d, port] of [[join(home, ".config", "magpie"), 3561], [join(xdg, "magpie"), 3562], [portable, 3563]] as const) { + mkdirSync(d, { recursive: true }); + writeFileSync(join(d, "settings.json"), JSON.stringify({ theme: "dark", port })); + } + const self = join(portable, "plugins", "node_modules", "@magpie-community", "page-agent-console", "daemon", "dist", "main.js"); + const dirs = magpieConfigDirs({ HOME: home, XDG_CONFIG_HOME: xdg }, { self, cwd: join(portable, "plugin-work"), platform: "linux" }); + expect(dirs).toEqual([portable, join(xdg, "magpie"), join(home, ".config", "magpie")]); + const denied = previewDeniedPorts({ port: 41000 }, {}, { configDirs: dirs }); + for (const p of [3561, 3562, 3563, 3425, 3430, 3488, 41000]) expect(deniedPort(p, denied), String(p)).toBe(true); + expect(deniedPort(5173, denied)).toBe(false); + // Windows: the home folder is USERPROFILE; paths with backslashes + expect(magpieConfigDirs({ USERPROFILE: "C:\\Users\\me" }, { self: "", cwd: "", platform: "win32" })).toEqual(process.platform === "win32" ? ["C:\\Users\\me\\.config\\magpie"] : []); + expect(magpieDirFromInstall("C:\\Magpie\\data\\plugins\\node_modules\\@magpie-community\\page-agent-console\\daemon\\dist\\main.js")).toBe("C:\\Magpie\\data"); + expect(magpieDirFromInstall("/opt/x/main.js")).toBeNull(); + }); + + it("settings.json without a port (or a bad one) means the default; unreadable means nothing", () => { + const read = (body: string) => () => body; + expect(savedGatewayPort("x", read("{}"))).toBe(3425); + expect(savedGatewayPort("x", read('{"port":0}'))).toBe(3425); + expect(savedGatewayPort("x", read('{"port":80}'))).toBe(3425); + expect(savedGatewayPort("x", read('{"port":3561}'))).toBe(3561); + expect(savedGatewayPort("x", read("garbled"))).toBeNull(); + expect(savedGatewayPort("x", () => { throw new Error("ENOENT"); })).toBeNull(); + // read again on every open: a port changed in Settings while the daemon runs is denied at once + let body = '{"port":3561}'; + const opts = { configDirs: ["/m"], read: () => body }; + expect(previewDeniedPorts({ port: 1 }, {}, opts)).toContain(3561); + body = '{"port":3999}'; + expect(previewDeniedPorts({ port: 1 }, {}, opts)).toContain(3999); + }); + + it("refuses a target that answers GET / like the gateway, on any port (open and later)", async () => { + const gw = await serve((req, s) => { + if (req.url === "/") { s.writeHead(200, { "content-type": "application/json" }); s.end(MAGPIE_INDEX); return; } + s.writeHead(200, { "content-type": "application/json" }); s.end('{"data":[],"object":"list"}'); + }); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + await expect(proxy.open(`localhost:${gw.port}/v1/models`)).rejects.toMatchObject({ code: "denied_port" }); + expect(proxy.size).toBe(0); + + // a dev server that is later replaced by the gateway on the same port: refused once it is asked again + let magpie = false; + let now = 1_000_000; + const dev = await serve((req, s) => { + if (magpie && req.url === "/") { s.writeHead(200, { "content-type": "application/json" }); s.end(MAGPIE_INDEX); return; } + s.writeHead(200, { "content-type": magpie ? "application/json" : "text/plain" }); s.end(magpie ? '{"data":[]}' : "dev"); + }); + const p2 = new PreviewProxy({ deniedPorts: () => [], now: () => now }); + cleanup.push(() => p2.closeAll()); + const r = await p2.open(`localhost:${dev.port}`); + const port = portOf(r.proxyOrigin); + expect((await request(port, "/v1/models", { host: hostOf(r.proxyOrigin) })).body).toBe("dev"); + magpie = true; + now += 61_000; + const refused = await request(port, "/v1/models", { host: hostOf(r.proxyOrigin), origin: "null" }); + expect(refused.status).toBe(403); + expect(refused.body).not.toContain("data"); + expect(refused.headers["access-control-allow-origin"]).toBeUndefined(); + // and stays refused + magpie = false; + expect((await request(port, "/", { host: hostOf(r.proxyOrigin) })).status).toBe(403); + }); + + it("refuses any reply that carries X-Magpie-* headers", async () => { + const gw = await serve((req, s) => { + if (req.url === "/") { s.end("hello"); return; } // index not recognisable + s.writeHead(200, { "content-type": "application/json", "x-magpie-provider": "deepseek" }); s.end('{"secret":1}'); + }); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + const r = await proxy.open(`localhost:${gw.port}`); + const port = portOf(r.proxyOrigin); + const res = await request(port, "/v1/chat/completions", { host: hostOf(r.proxyOrigin) }); + expect(res.status).toBe(403); + expect(res.body).not.toContain("secret"); + expect((await request(port, "/", { host: hostOf(r.proxyOrigin) })).status).toBe(403); + }); + + it("fails closed when the target doesn't answer the identity check in time", async () => { + const hang = net.createServer((s) => { s.on("error", () => {}); /* accepts, never answers */ }); + await new Promise<void>((r) => hang.listen(0, "127.0.0.1", () => r())); + cleanup.push(() => hang.close()); + const hp = (hang.address() as net.AddressInfo).port; + const proxy = new PreviewProxy({ deniedPorts: () => [], identityTimeoutMs: 300 }); + cleanup.push(() => proxy.closeAll()); + const r = await proxy.open(`localhost:${hp}`); + const res = await request(portOf(r.proxyOrigin), "/", { host: hostOf(r.proxyOrigin) }); + expect(res.status).toBe(502); // the "not responding" page; nothing was forwarded + }); + + it("recognises the gateway's index and headers only", async () => { + expect(magpieIndex(MAGPIE_INDEX)).toBe(true); + expect(magpieIndex('{"name":"magpie"}')).toBe(false); + expect(magpieIndex('{"name":"my-app","apis":[]}')).toBe(false); + expect(magpieIndex("<html>")).toBe(false); + expect(looksLikeMagpie({ "X-Magpie-Provider": "x" } as never)).toBe(true); + expect(looksLikeMagpie({ "content-type": "text/html" })).toBe(false); + const c = checkPreviewUrl("localhost:1"); + if (!c.ok) throw new Error("x"); + expect(await identify(c.target, ["127.0.0.1"], 500)).toBe("none"); + }); +}); + + +describe("preview ping nonce + canary (#582 WebKit DNS)", () => { + it("rotates nonces on every open; ping never answers a generic ok", async () => { + const up = await serve((_q, s) => s.end("dev")); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + const a = await proxy.open(`localhost:${up.port}`); + const b = await proxy.open(`localhost:${up.port}/again`); + expect(a.proxyOrigin).toBe(b.proxyOrigin); + expect(b.nonce).not.toBe(a.nonce); + expect(b.canaryNonce).not.toBe(a.canaryNonce); + expect(b.canaryOrigin).not.toBe(a.canaryOrigin); + const port = portOf(a.proxyOrigin); + // old nonce is gone; retired canary Host is unknown → 421 (not a bare loopback address) + expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(a.proxyOrigin) })).body).toBe(b.nonce); + expect([403, 421]).toContain((await request(port, PREVIEW_PING_PATH, { host: hostOf(a.canaryOrigin) })).status); + expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(b.canaryOrigin) })).body).toBe(b.canaryNonce); + }); + + it("a non-proxy server that answers 200 ok fails canReachProxy; navigate releases the listener", async () => { + const up = await serve((_q, s) => s.end("DEV-SECRET")); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + const opened = await proxy.open(`localhost:${up.port}/`); + expect(proxy.size).toBe(1); + + // Real proxy ping body (Host header, connect to 127.0.0.1) — must be the nonce, never "ok" + const port = portOf(opened.proxyOrigin); + expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(opened.proxyOrigin) })).body).toBe(opened.nonce); + expect((await request(port, PREVIEW_PING_PATH, { host: hostOf(opened.canaryOrigin) })).body).toBe(opened.canaryNonce); + + // Attacker DNS: answers with plain 200 "ok" (what canReachProxy used to accept). Fetch via 127.0.0.1 + // so the test does not depend on this machine's *.localhost resolver. + const fake = await serve((_q, s) => { + s.writeHead(200, { "content-type": "text/plain", "access-control-allow-origin": "null" }); + s.end("ok"); + }); + const good = await serve((_q, s) => { + s.writeHead(200, { "content-type": "text/plain", "access-control-allow-origin": "null" }); + s.end(opened.nonce); + }); + expect(await canReachProxy(`http://127.0.0.1:${fake.port}`, opened.nonce)).toBe(false); + expect(await canReachProxy(`http://127.0.0.1:${good.port}`, "ok")).toBe(false); + expect(await canReachProxy(`http://127.0.0.1:${good.port}`, opened.nonce)).toBe(true); + expect(await confirmPreviewReachable({ + proxyOrigin: `http://127.0.0.1:${fake.port}`, + proxyHref: `http://127.0.0.1:${fake.port}/`, + url: opened.url, + nonce: opened.nonce, + canaryOrigin: `http://127.0.0.1:${fake.port}`, + canaryNonce: opened.canaryNonce, + })).toBe(false); + + // Panel path: preview.open returns real listener, but fetch is hijacked to the fake server → must release + const released: string[] = []; + const prevFetch = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = String(input); + const u = new URL(url); + // rewrite any *.localhost lookup → fake server (simulates hostile DNS answering the lookup) + return prevFetch(`http://127.0.0.1:${fake.port}${u.pathname}${u.search}`, { + cache: "no-store", + credentials: "omit", + referrerPolicy: "no-referrer", + }); + }) as typeof fetch; + cleanup.push(() => { globalThis.fetch = prevFetch; }); + + usePreview.setState({ byThread: {} }); + const call = async (m: string, p?: unknown) => { + if (m === "preview.open") { + return { + proxyOrigin: opened.proxyOrigin, + proxyHref: opened.proxyHref, + url: opened.url, + nonce: opened.nonce, + canaryOrigin: opened.canaryOrigin, + canaryNonce: opened.canaryNonce, + }; + } + if (m === "preview.release") { + const url = String((p as { url?: string } | undefined)?.url ?? ""); + released.push(url); + proxy.release(url); + return { ok: true }; + } + return {}; + }; + const ok = await usePreview.getState().navigate(call, "t1", null, `http://localhost:${up.port}/`, { push: true }); + expect(ok).toBe(false); + expect(released).toEqual([`http://localhost:${up.port}`]); + expect(proxy.size).toBe(0); + const entry = usePreview.getState().byThread["t1"]; + expect(entry?.proxyHref).toBeNull(); + expect(entry?.error).toBeTruthy(); + // real ping would have worked; the failure was the fake answer + expect(entry?.error?.length ?? 0).toBeGreaterThan(10); + }); + +}); + +// #582 third review: Apple froze the UA at "Mac OS X 10_15_7", so the macOS version comes from the daemon +// (os.platform() + os.release(), Darwin 25 = macOS 26) via preview.open, never from the UA. +describe("Apple WebKit + daemon Darwin version (#582 frozen UA)", () => { + // Literal UAs Apple WebKit sends on every macOS, 26+ included (a plain WKWebView on macOS 27.2, and Safari) + const WKWEBVIEW_FROZEN = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)"; + const SAFARI_FROZEN = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15"; + const IPAD_SAFARI = "Mozilla/5.0 (iPad; CPU OS 18_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Mobile/15E148 Safari/604.1"; + const CHROME_MAC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; + const EDGE_WIN = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0"; + const WEBKITGTK = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15"; + + const macos26 = previewHost("darwin", "25.0.0"); + const macos27 = previewHost("darwin", "26.2.0"); + const macos15 = previewHost("darwin", "24.6.0"); + const macos12 = previewHost("darwin", "21.6.0"); + const linux = previewHost("linux", "6.8.0-45-generic"); + const win = previewHost("win32", "10.0.26100"); + + it("the daemon reads the Darwin major from os.release()", () => { + expect(macos26).toEqual({ platform: "darwin", darwinMajor: 25 }); + expect(macos27).toEqual({ platform: "darwin", darwinMajor: 26 }); + expect(macos15).toEqual({ platform: "darwin", darwinMajor: 24 }); + expect(linux).toEqual({ platform: "linux", darwinMajor: null }); + expect(win).toEqual({ platform: "win32", darwinMajor: null }); + expect(previewHost("darwin", "")).toEqual({ platform: "darwin", darwinMajor: null }); + expect(previewHost("darwin", "garbage")).toEqual({ platform: "darwin", darwinMajor: null }); + expect(DARWIN_LOCALHOST_LOOPBACK).toBe(WEB_DARWIN_LOCALHOST_LOOPBACK); + // default arguments = this host + const here = previewHost(); + expect(here.platform).toBe(osPlatform()); + if (here.platform === "darwin") expect(here.darwinMajor).toBe(Number(osRelease().split(".")[0])); + else expect(here.darwinMajor).toBeNull(); + }); + + it("the frozen 10_15_7 UA on a macOS 26+ host is safe; on Darwin 24 or an unknown host it is refused", () => { + for (const ua of [WKWEBVIEW_FROZEN, SAFARI_FROZEN, IPAD_SAFARI]) { + expect(isAppleWebKit(ua)).toBe(true); + expect(isUnsafeLocalhostResolver(macos26, ua)).toBe(false); + expect(isUnsafeLocalhostResolver(macos27, ua)).toBe(false); + expect(isUnsafeLocalhostResolver(macos15, ua)).toBe(true); + expect(isUnsafeLocalhostResolver(macos12, ua)).toBe(true); + // missing / unparseable daemon info fails closed + expect(isUnsafeLocalhostResolver(undefined, ua)).toBe(true); + expect(isUnsafeLocalhostResolver(null, ua)).toBe(true); + expect(isUnsafeLocalhostResolver({ platform: "darwin", darwinMajor: null }, ua)).toBe(true); + expect(isUnsafeLocalhostResolver({ platform: "", darwinMajor: null }, ua)).toBe(true); + // non-darwin daemon hosts are left to the canary + nonce probe + expect(isUnsafeLocalhostResolver(linux, ua)).toBe(false); + expect(isUnsafeLocalhostResolver(win, ua)).toBe(false); + } + }); + + it("Chromium / Edge / WebKitGTK are never refused, whatever the host", () => { + for (const ua of [CHROME_MAC, EDGE_WIN, WEBKITGTK]) { + expect(isAppleWebKit(ua)).toBe(false); + for (const h of [macos12, macos15, macos26, linux, win, null]) expect(isUnsafeLocalhostResolver(h, ua)).toBe(false); + } + }); + + // Panel path against a real listener. fetch is routed to 127.0.0.1:<port> with the name's Host header, so the test + // doesn't depend on this machine's *.localhost resolver. + async function panel(ua: string, host: unknown) { + const up = await serve((_q, s) => s.end("DEV")); + const proxy = new PreviewProxy({ deniedPorts: () => [] }); + cleanup.push(() => proxy.closeAll()); + vi.stubGlobal("navigator", { userAgent: ua }); + cleanup.push(() => vi.unstubAllGlobals()); + const pinged: string[] = []; + const prevFetch = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const u = new URL(String(input)); + pinged.push(u.hostname); + const r = await request(Number(u.port), u.pathname + u.search, { host: u.host }); + return new Response(r.body, { status: r.status }); + }) as typeof fetch; + cleanup.push(() => { globalThis.fetch = prevFetch; }); + const calls: string[] = []; + const released: string[] = []; + const call = async (m: string, p?: unknown) => { + calls.push(m); + if (m === "preview.open") { + const opened = await proxy.open(String((p as { url: string }).url)); + return host === undefined ? opened : { ...opened, host }; + } + if (m === "preview.release") { + const url = String((p as { url?: string } | undefined)?.url ?? ""); + released.push(url); + proxy.release(url); + return { ok: true }; + } + return {}; + }; + usePreview.setState({ byThread: {} }); + const ok = await usePreview.getState().navigate(call, "mac", null, `http://localhost:${up.port}/`, { push: true }); + return { ok, calls, released, pinged, proxy, up, entry: usePreview.getState().byThread["mac"] }; + } + + it("Magpie's Mac app (frozen WKWebView UA) on a macOS 26 host (Darwin 25.x) opens the preview", async () => { + const r = await panel(WKWEBVIEW_FROZEN, previewHost("darwin", "25.0.0")); + expect(r.ok).toBe(true); + expect(r.calls).toEqual(["preview.open"]); + expect(r.released).toEqual([]); + expect(r.proxy.size).toBe(1); + expect(r.entry?.error).toBeNull(); + expect(r.entry?.proxyHref).toMatch(/^http:\/\/ac[0-9a-f]+\.localhost:\d+\/$/); + // canary first, then the keyed name + expect(r.pinged).toHaveLength(2); + expect(r.pinged[0]).toMatch(/^acprobe[0-9a-f]+\.localhost$/); + expect(r.pinged[1]).toBe(new URL(r.entry!.proxyHref!).hostname); + }); + + it("Safari (frozen UA) with magpie web on a macOS 27 host opens the preview", async () => { + const r = await panel(SAFARI_FROZEN, previewHost("darwin", "26.2.0")); + expect(r.ok).toBe(true); + expect(r.entry?.proxyHref).toBeTruthy(); + expect(r.released).toEqual([]); + }); + + it("Apple WebKit on a Darwin 24.x host (macOS 15) is refused: no *.localhost lookup, listener released", async () => { + const r = await panel(WKWEBVIEW_FROZEN, previewHost("darwin", "24.6.0")); + expect(r.ok).toBe(false); + expect(r.pinged).toEqual([]); + expect(r.released).toEqual([`http://localhost:${r.up.port}`]); + expect(r.proxy.size).toBe(0); + expect(r.entry?.proxyHref).toBeNull(); + expect(r.entry?.error).toBeTruthy(); + }); + + it("Apple WebKit with no host info from the daemon fails closed the same way", async () => { + const r = await panel(SAFARI_FROZEN, undefined); + expect(r.ok).toBe(false); + expect(r.pinged).toEqual([]); + expect(r.proxy.size).toBe(0); + }); + + it("a non-darwin daemon host is unaffected (frozen Safari UA and Chromium both open)", async () => { + const a = await panel(SAFARI_FROZEN, previewHost("linux", "6.8.0")); + expect(a.ok).toBe(true); + expect(a.released).toEqual([]); + const b = await panel(EDGE_WIN, previewHost("win32", "10.0.26100")); + expect(b.ok).toBe(true); + expect(b.released).toEqual([]); + }); +}); diff --git a/packages/agent-console/test/v1/ws.test.ts b/packages/agent-console/test/v1/ws.test.ts index a004606..6ccf3fd 100644 --- a/packages/agent-console/test/v1/ws.test.ts +++ b/packages/agent-console/test/v1/ws.test.ts @@ -1,6 +1,7 @@ // WS gateway tests: hello authentication, app.info, wrong token 4401, subscription push import { describe, it, expect, beforeAll, afterAll } from "vitest"; import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import http from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Server } from "node:http"; @@ -16,6 +17,8 @@ import { registerMethods } from "../../daemon/src/ws/methods.js"; import { GitService } from "../../daemon/src/git/service.js"; import { FileService } from "../../daemon/src/files/service.js"; import { TerminalService } from "../../daemon/src/terminal/service.js"; +import { PreviewProxy } from "../../daemon/src/preview/proxy.js"; +import { previewHost } from "../../daemon/src/preview/host.js"; import type { Config } from "../../daemon/src/config.js"; const TOKEN = "testtoken123"; @@ -23,6 +26,7 @@ let dir = ""; let server: Server; let port = 0; let gateway: Gateway; +let preview: PreviewProxy; beforeAll(async () => { dir = mkdtempSync(join(tmpdir(), "ac-ws-")); @@ -32,7 +36,8 @@ beforeAll(async () => { const cfg: Config = { port: 0, dataDir: dir, token: TOKEN, version: "9.9.9", idleExitMinutes: 60, buildStamp: "0" }; gateway = new Gateway(cfg); const settings = new SettingsStore(dir); - registerMethods(gateway, { cfg, settings, gateway, projects: new ProjectsStore(dir), threads: new ThreadsStore(dir), git: new GitService(), files: new FileService(), terminals: new TerminalService(gateway) }); + preview = new PreviewProxy({ deniedPorts: () => [] }); + registerMethods(gateway, { cfg, settings, gateway, projects: new ProjectsStore(dir), threads: new ThreadsStore(dir), git: new GitService(), files: new FileService(), terminals: new TerminalService(gateway), preview }); server = createHttpServer(cfg, appDir, new AttachmentStore(join(dir, "attachments")), { onUpgrade: (req, socket, head) => gateway.handleUpgrade(req, socket, head), }); @@ -42,6 +47,7 @@ beforeAll(async () => { }); afterAll(() => { + preview.closeAll(); gateway.closeAll(); server.close(); rmSync(dir, { recursive: true, force: true }); @@ -124,4 +130,31 @@ describe("ws gateway", () => { expect(e.ch).toBe("sidebar"); ws.close(); }); + + // #582 review: methods.ts rewrites host via previewHost(); bare `return r;` must make this red + it("preview.open returns host from previewHost()", async () => { + const up = http.createServer((_q, s) => { s.end("dev"); }); + await new Promise<void>((r) => up.listen(0, "127.0.0.1", () => r())); + const upPort = (up.address() as AddressInfo).port; + try { + const ws = await connect(); + const hello = nextMsg(ws, (o) => o.t === "hello.ok"); + ws.send(JSON.stringify({ t: "hello", token: TOKEN })); + await hello; + const res = nextMsg(ws, (o) => o.t === "res" && o.id === 30); + ws.send(JSON.stringify({ t: "req", id: 30, m: "preview.open", p: { url: `http://localhost:${upPort}/` } })); + const r = await res; + expect(r.ok).toBe(true); + const body = r.r as { host?: unknown; proxyOrigin?: string }; + expect(body.host).toEqual(previewHost()); + if (body.proxyOrigin) { + const rel = nextMsg(ws, (o) => o.t === "res" && o.id === 31); + ws.send(JSON.stringify({ t: "req", id: 31, m: "preview.release", p: { url: `http://localhost:${upPort}/` } })); + await rel; + } + ws.close(); + } finally { + up.close(); + } + }); }); diff --git a/packages/agent-console/web/src/api/ws.ts b/packages/agent-console/web/src/api/ws.ts index 9bedacd..8d56189 100644 --- a/packages/agent-console/web/src/api/ws.ts +++ b/packages/agent-console/web/src/api/ws.ts @@ -21,6 +21,11 @@ export class WsClient { constructor(private token: string, private lang = "zh") {} + /** Language sent in the next hello (reconnects) */ + setLang(lang: string): void { + this.lang = lang; + } + onState(fn: (s: ConnState) => void): () => void { this.stateListeners.add(fn); fn(this.state); diff --git a/packages/agent-console/web/src/components/Chat.tsx b/packages/agent-console/web/src/components/Chat.tsx index 1a80672..f188c77 100644 --- a/packages/agent-console/web/src/components/Chat.tsx +++ b/packages/agent-console/web/src/components/Chat.tsx @@ -10,6 +10,7 @@ import { Composer } from "./Composer"; import { Icon } from "./Icons"; import { ws } from "../main"; import { toast } from "./Toast"; +import { relFromAbs } from "../composer/mentions"; import { useLiveSettings } from "./Settings"; import { errMsg, localizeDaemonMessage, t as tr, tf } from "../i18n/index.js"; @@ -82,9 +83,14 @@ export function Chat() { setHasNew(false); }; - const resend = (text: string) => { + const resend = (text: string, mentions?: { path: string; isDir: boolean }[]) => { if (!activeThreadId) return; - void ws.call("thread.send", { id: activeThreadId, text }); + // chips go along again (as project-relative paths; the daemon re-checks them) + const root = project?.path; + const rels = root && mentions?.length + ? mentions.map((m) => ({ rel: relFromAbs(root, m.path), isDir: m.isDir })).filter((m): m is { rel: string; isDir: boolean } => !!m.rel) + : []; + void ws.call("thread.send", { id: activeThreadId, text, ...(rels.length ? { mentions: rels } : {}) }); }; const retryLast = () => { if (tl.lastUserText) resend(tl.lastUserText); diff --git a/packages/agent-console/web/src/components/Composer.tsx b/packages/agent-console/web/src/components/Composer.tsx index 4d4791a..baeed7c 100644 --- a/packages/agent-console/web/src/components/Composer.tsx +++ b/packages/agent-console/web/src/components/Composer.tsx @@ -8,7 +8,8 @@ import { useTimeline } from "../stores/timeline"; import { ws } from "../main"; import { getToken } from "../api/token"; import { Icon } from "./Icons"; -import { attachmentUrl } from "./Timeline"; +import { attachmentUrl, MentionChip } from "./Timeline"; +import { MENTION_MIME, addMention, joinProjectPath, mentionsForSend, parseMentionDrag, type MentionDraft } from "../composer/mentions"; import type { Mode, ModelInfo } from "../types/models"; import type { SlashCommand } from "../composer/slashMenu"; import { toast } from "./Toast"; @@ -34,10 +35,12 @@ const MODEL_LIST_CAP = 150; export function Composer() { const ui = useUi(); - const { threads, providers } = useData(); + const { threads, providers, projects } = useData(); const tl = useTimeline(); const [text, setText] = useState(""); const [attachments, setAttachments] = useState<Attachment[]>([]); + const [mentions, setMentions] = useState<MentionDraft[]>([]); + const [dropHint, setDropHint] = useState(false); const [agentPop, setAgentPop] = useState(false); const [pickerProviderId, setPickerProviderId] = useState<string | null>(null); const [modelQ, setModelQ] = useState(""); @@ -173,22 +176,26 @@ export function Composer() { const ta = taRef.current; if (!ta) return; ta.style.height = "auto"; - ta.style.height = Math.min(ta.scrollHeight, 12 * 22) + "px"; + // 12 lines at the current chat font size (line-height follows --chat-fs) + const lh = parseFloat(getComputedStyle(ta).lineHeight) || 22; + ta.style.height = Math.min(ta.scrollHeight, Math.round(12 * lh)) + "px"; }, [text]); const send = useCallback(async (behavior: "queue" | "steer" = "queue") => { const id = ui.currentThreadId; const msg = text.trim(); - if (!id || (!msg && attachments.length === 0)) return; + if (!id || (!msg && attachments.length === 0 && mentions.length === 0)) return; if (running && behavior === "queue") setLastSent((s) => [...s, msg]); setText(""); try { const r = (await ws.call("thread.send", { id, text: msg, attachments: attachments.map((a) => ({ path: a.path, mime: a.mime, name: a.name })), + ...(mentions.length ? { mentions: mentionsForSend(mentions) } : {}), behavior: running && behavior === "steer" && steerOk ? "steer" : "queue", })) as { delivered?: "started" | "steered" | "queued" } | undefined; setAttachments([]); + setMentions([]); // Say what really happened to a message sent mid-turn (B7: agents without steer queue it) if (r?.delivered === "queued" && running) toast(tr("composer.queuedToast")); else if (r?.delivered === "steered") toast(tr("composer.steeredToast")); @@ -197,7 +204,7 @@ export function Composer() { setText(msg); toast(tr("composer.failSend") + errMsg(e), true); } - }, [text, attachments, ui.currentThreadId, running, steerOk]); + }, [text, attachments, mentions, ui.currentThreadId, running, steerOk]); const onKey = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { if (isImeComposing(e.nativeEvent)) return; @@ -291,8 +298,33 @@ export function Composer() { } }; + const project = projects.find((p) => p.id === thread?.projectId) ?? null; + const takeMention = (m: MentionDraft | null) => { + if (!m) return; + if (!thread || m.projectId !== thread.projectId) { + toast(tr("mention.otherProject"), true); + return; + } + setMentions((list) => addMention(list, m)); + taRef.current?.focus(); + }; + // Files panel → context menu "Add to chat" + useEffect(() => { + const on = (e: Event) => takeMention((e as CustomEvent).detail as MentionDraft); + window.addEventListener("ac-insert-mention", on); + return () => window.removeEventListener("ac-insert-mention", on); + }); + // A new conversation starts with no chips + useEffect(() => { setMentions([]); }, [ui.currentThreadId]); + const onDrop = async (e: React.DragEvent) => { e.preventDefault(); + setDropHint(false); + // A row from our Files panel: a path chip, not an upload. Files from the OS file manager keep the old behaviour. + if (e.dataTransfer.types.includes(MENTION_MIME)) { + takeMention(parseMentionDrag(e.dataTransfer.getData(MENTION_MIME))); + return; + } for (const f of e.dataTransfer.files) { if (f.type.startsWith("image/") || f.type.startsWith("text/")) await upload(f); } @@ -339,7 +371,14 @@ export function Composer() { if (!ui.currentThreadId) return null; return ( - <div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop} onDragOver={(e) => e.preventDefault()}> + <div className={`composer${waiting ? " waiting" : ""}`} onDrop={onDrop} + onDragOver={(e) => { + e.preventDefault(); + const ours = e.dataTransfer.types.includes(MENTION_MIME); + if (ours) e.dataTransfer.dropEffect = "copy"; + if (ours !== dropHint) setDropHint(ours); + }} + onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDropHint(false); }}> {/* queue list */} {tl.queue.length > 0 && ( <div className="q-list"> @@ -356,12 +395,17 @@ export function Composer() { {mode === "bypassPermissions" && ( <div className="cp-danger">{tr("composer.bypassWarn")}</div> )} - <div className={`cp-card${waiting ? " waiting" : ""}${mode === "bypassPermissions" ? " danger" : ""}`}> + <div className={`cp-card${waiting ? " waiting" : ""}${mode === "bypassPermissions" ? " danger" : ""}${dropHint ? " drop-on" : ""}`}> + {dropHint && <div className="cp-drop-hint">{tr("mention.drop")}</div>} {imagesByPath && attachments.some((a) => a.mime.startsWith("image/")) && ( <div className="att-note">{tf("composer.imagesByPath", { agent: provider?.name ?? "" })}</div> )} - {attachments.length > 0 && ( + {(attachments.length > 0 || mentions.length > 0) && ( <div className="att-bar"> + {mentions.map((m) => ( + <MentionChip key={m.rel} path={project ? joinProjectPath(project.path, m.rel) : m.rel} isDir={m.isDir} + onRemove={() => setMentions((list) => list.filter((x) => x !== m))} /> + ))} {attachments.map((a, i) => ( <span key={i} className={`att${a.uploading ? " up" : ""}`}> {a.mime.startsWith("image/") && a.path @@ -640,7 +684,7 @@ export function Composer() { {running ? ( <> <span className="cp-clock">{elapsed}s</span> - {(text.trim() || attachments.length > 0) && ( + {(text.trim() || attachments.length > 0 || mentions.length > 0) && ( <button className="cp-send" title={tr(steerOk && prefs.runningSend === "steer" ? "settings.steer" : "settings.queue")} disabled={waiting || attachments.some((a) => a.uploading)} onClick={() => void send(prefs.runningSend === "steer" && steerOk ? "steer" : "queue")}> @@ -652,7 +696,7 @@ export function Composer() { </button> </> ) : ( - <button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0) || attachments.some((a) => a.uploading)} + <button className="cp-send" title={tr("common.send")} disabled={waiting || (!text.trim() && attachments.length === 0 && mentions.length === 0) || attachments.some((a) => a.uploading)} onClick={() => void send("queue")}> <Icon name="arrowUp" /> </button> diff --git a/packages/agent-console/web/src/components/Icons.tsx b/packages/agent-console/web/src/components/Icons.tsx index d6ae53f..8728406 100644 --- a/packages/agent-console/web/src/components/Icons.tsx +++ b/packages/agent-console/web/src/components/Icons.tsx @@ -1,6 +1,13 @@ // Small line icons (stroke=currentColor, 1.6px); no third-party icon pack, keeps the bundle small. const PATHS: Record<string, string> = { plus: "M12 5v14M5 12h14", + file: "M6 3h8l4 4v14H6zM14 3v4h4", + arrowLeft: "M19 12H5m6-6-6 6 6 6", + arrowRight: "M5 12h14m-6-6 6 6-6 6", + external: "M14 4h6v6M20 4l-9 9M18 14v6H4V6h6", + globe: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-9 9h18M12 3c2.5 2.6 3.8 5.6 3.8 9s-1.3 6.4-3.8 9c-2.5-2.6-3.8-5.6-3.8-9S9.5 5.6 12 3Z", + panelLeft: "M4 5h16v14H4zM9.5 5v14", + widen: "M4 12h16M8 8l-4 4 4 4M16 8l4 4-4 4", search: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm10 17-4.5-4.5", caret: "M9 6l6 6-6 6", dots: "M5 12h.01M12 12h.01M19 12h.01", diff --git a/packages/agent-console/web/src/components/Layout.tsx b/packages/agent-console/web/src/components/Layout.tsx index 97bf572..67a394c 100644 --- a/packages/agent-console/web/src/components/Layout.tsx +++ b/packages/agent-console/web/src/components/Layout.tsx @@ -104,9 +104,7 @@ export function Layout({ const k = e.key.toLowerCase(); if (k === "b") { e.preventDefault(); - const s = useUi.getState(); - if (window.matchMedia("(max-width: 759px)").matches) s.setSbOpen(!s.sbOpen); - else s.toggleSidebarHidden(); + useUi.getState().toggleSidebar(); } else if (k === "j") { e.preventDefault(); const s = useUi.getState(); diff --git a/packages/agent-console/web/src/components/Markdown.tsx b/packages/agent-console/web/src/components/Markdown.tsx index a0949fa..1474d29 100644 --- a/packages/agent-console/web/src/components/Markdown.tsx +++ b/packages/agent-console/web/src/components/Markdown.tsx @@ -3,11 +3,14 @@ import { useMemo, useRef, useEffect } from "react"; import { marked } from "marked"; import DOMPurify from "dompurify"; import hljs from "highlight.js/lib/common"; +import { linkifyLocal } from "../util/localLinks"; +import { onChatLinkClick } from "../preview/open"; +import { t } from "../i18n/index.js"; marked.setOptions({ gfm: true, breaks: true }); const purify = (html: string) => - DOMPurify.sanitize(html, { USE_PROFILES: { html: true }, ADD_ATTR: ["target", "rel"] }); + DOMPurify.sanitize(html, { USE_PROFILES: { html: true } }); export function renderMarkdown(text: string): string { return purify(marked.parse(text, { async: false })); @@ -17,14 +20,12 @@ export function Markdown({ text, streaming }: { text: string; streaming?: boolea const ref = useRef<HTMLDivElement>(null); const html = useMemo(() => renderMarkdown(text), [text]); - // After rendering: highlight code blocks + copy button; external links target=_blank + // After rendering: highlight code blocks + copy button, then local addresses become Preview links (1.2). + // Link clicks are handled by onChatLinkClick (system browser / Preview tab): target=_blank can't open anything in + // Magpie's sandboxed frame, and a plain click would navigate the whole page away. useEffect(() => { const el = ref.current; if (!el) return; - for (const a of el.querySelectorAll("a[href^='http']")) { - (a as HTMLAnchorElement).target = "_blank"; - (a as HTMLAnchorElement).rel = "noopener"; - } for (const pre of el.querySelectorAll("pre")) { const code = pre.querySelector("code"); if (code && !code.dataset.hl) { @@ -34,20 +35,24 @@ export function Markdown({ text, streaming }: { text: string; streaming?: boolea if (!pre.querySelector(".cb-copy")) { const btn = document.createElement("button"); btn.className = "cb-copy"; - btn.textContent = "复制"; + btn.type = "button"; + btn.textContent = t("common.copy"); btn.onclick = () => { - const t = code?.textContent ?? ""; - void copyText(t).then(() => { btn.textContent = "已复制"; setTimeout(() => (btn.textContent = "复制"), 1200); }); + const txt = code?.textContent ?? ""; + void copyText(txt).then(() => { btn.textContent = t("common.copied"); setTimeout(() => (btn.textContent = t("common.copy")), 1200); }); }; pre.appendChild(btn); } } - }, [html]); + // While streaming the text changes many times a second: link once it settles (and on every final render) + if (!streaming) linkifyLocal(el, t("links.openPreviewTitle")); + }, [html, streaming]); return ( <div ref={ref} className={`md${streaming ? " streaming" : ""}`} + onClick={onChatLinkClick} dangerouslySetInnerHTML={{ __html: html }} /> ); diff --git a/packages/agent-console/web/src/components/Panel.tsx b/packages/agent-console/web/src/components/Panel.tsx index 48ed09a..f350a97 100644 --- a/packages/agent-console/web/src/components/Panel.tsx +++ b/packages/agent-console/web/src/components/Panel.tsx @@ -10,6 +10,9 @@ import { ConfirmDialog } from "./Dialog"; import { toast } from "./Toast"; import { errMsg, t, tf } from "../i18n/index.js"; import { TerminalPanel } from "./TerminalPanel"; +import { PreviewPanel } from "./PreviewPanel"; +import { Menu, type MenuItem } from "./Menu"; +import { MENTION_MIME, joinProjectPath, type MentionDraft } from "../composer/mentions"; import { copyText } from "./Markdown"; import hljs from "highlight.js/lib/common"; @@ -19,6 +22,7 @@ export function Panel() { { tab: "changes", label: t("panel.changes") }, { tab: "files", label: t("panel.files") }, { tab: "terminal", label: t("panel.terminal") }, + { tab: "preview", label: t("preview.tab") }, ]; return ( <> @@ -42,6 +46,7 @@ export function Panel() { {ui.panelTab === "changes" && <ChangesPanel />} {ui.panelTab === "files" && <FilesPanel />} {ui.panelTab === "terminal" && <TerminalPanel />} + {ui.panelTab === "preview" && ui.panelOpen && <PreviewPanel />} </div> </> ); @@ -230,6 +235,10 @@ function ChangesPanel() { } // ---------- files panel ---------- +/** Context menu "Add to chat": the composer listens for this */ +export function insertMention(m: MentionDraft): void { + window.dispatchEvent(new CustomEvent("ac-insert-mention", { detail: m })); +} type TreeEntry = { name: string; path: string; isDir: boolean }; function FilesPanel() { @@ -245,6 +254,7 @@ function FilesPanel() { const [dirs, setDirs] = useState<Record<string, TreeEntry[] | "loading" | string>>({}); const [sel, setSel] = useState<string | null>(null); const [file, setFile] = useState<{ text?: string; language?: string; binary?: boolean; tooLarge?: boolean; error?: string; loading?: boolean } | null>(null); + const [ctx, setCtx] = useState<{ x: number; y: number; entry: TreeEntry } | null>(null); const loadDir = useCallback(async (dir: string) => { if (!projectId) return; @@ -314,6 +324,17 @@ function FilesPanel() { style={{ paddingLeft: 8 + depth * 14 }} onClick={() => toggle(e)} title={e.path} + draggable + onDragStart={(ev) => { + // 1.2: drag into the composer → a path chip; other drop targets get the absolute path as text + ev.dataTransfer.effectAllowed = "copy"; + ev.dataTransfer.setData(MENTION_MIME, JSON.stringify({ projectId: project.id, rel: e.path, isDir: e.isDir })); + ev.dataTransfer.setData("text/plain", joinProjectPath(project.path, e.path)); + }} + onContextMenu={(ev) => { + ev.preventDefault(); + setCtx({ x: ev.clientX, y: ev.clientY, entry: e }); + }} > {e.isDir ? ( <> @@ -333,8 +354,18 @@ function FilesPanel() { )); }; + const ctxItems: MenuItem[] = ctx + ? [ + { kind: "item", label: t("mention.add"), onClick: () => insertMention({ projectId: project.id, rel: ctx.entry.path, isDir: ctx.entry.isDir }) }, + { kind: "sep" }, + { kind: "item", label: t("common.copyPath"), onClick: () => { void copyText(joinProjectPath(project.path, ctx.entry.path)); toast(t("common.copiedPath")); } }, + { kind: "item", label: t("mention.copyRel"), onClick: () => { void copyText(ctx.entry.path); toast(t("common.copiedPath")); } }, + ] + : []; + return ( <> + {ctx && <Menu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />} <div className="ft-crumbs"> {sel ? ( <> diff --git a/packages/agent-console/web/src/components/PreviewPanel.tsx b/packages/agent-console/web/src/components/PreviewPanel.tsx new file mode 100644 index 0000000..6a71e8d --- /dev/null +++ b/packages/agent-console/web/src/components/PreviewPanel.tsx @@ -0,0 +1,186 @@ +// Preview tab (1.2): a light browser for local dev URLs. The page loads through the daemon's preview proxy +// (preview/proxy.ts): inside Magpie the frame is sandboxed and opaque, and a direct iframe of localhost breaks module scripts, +// fetch and storage. Back/forward/reload go through the injected bridge when the page has it, else through our own URL stack. +// Messages from the frame are only read when they come from this iframe and carry {ac_preview:1, href, title}; they only +// update the address bar and title. The parent page's history is never touched (it is Magpie's whole window). +import { useEffect, useRef, useState } from "react"; +import { ws } from "../main"; +import { useUi, PN_MAX } from "../stores/ui"; +import { useData } from "../stores/data"; +import { usePreview, threadKey, addressText } from "../stores/preview"; +import { checkPreviewUrl, displayHref, externalHref } from "../../../daemon/src/preview/url.js"; +import { openExternal } from "../preview/open"; +import { localizeDaemonMessage, t } from "../i18n/index.js"; +import { Icon } from "./Icons"; +import { maxPanelWidth } from "../layout/bounds"; + +const call = (m: string, p?: unknown) => ws.call(m, p); + +export function PreviewPanel() { + const ui = useUi(); + const threads = useData((s) => s.threads); + const threadId = ui.currentThreadId; + const key = threadKey(threadId); + const entry = usePreview((s) => s.byThread[key]); + const thread = threads.find((x) => x.id === threadId) ?? null; + const frameRef = useRef<HTMLIFrameElement>(null); + const [addr, setAddr] = useState(""); + const [editing, setEditing] = useState(false); + const [bad, setBad] = useState<string | null>(null); + const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null); + + // Restore this conversation's last URL (or re-open the proxy after a release) + useEffect(() => { + const st = usePreview.getState(); + const cur = st.byThread[key]; + if (cur && cur.proxyHref) return; + const url = cur?.url ?? thread?.previewUrl ?? null; + if (url) void st.navigate(call, key, threadId, url, { push: false }); + }, [key, threadId, thread?.previewUrl]); + + // Leaving the tab / the conversation: let the proxy go (it is re-opened when the tab shows this URL again) + const origin = entry?.origin; + const proxied = !!entry?.proxyOrigin; + useEffect(() => { + if (!origin || !proxied) return; + return () => { + // another conversation may show the same target right now: only release when none does + const st = usePreview.getState(); + const nowKey = threadKey(useUi.getState().currentThreadId); + const stillShown = useUi.getState().panelOpen && useUi.getState().panelTab === "preview" && st.byThread[nowKey]?.origin === origin && nowKey !== key; + st.detach(key); + if (!stillShown) void ws.call("preview.release", { url: origin }).catch(() => {}); + }; + }, [origin, proxied, key]); + + // Address bar follows the page unless the user is typing + useEffect(() => { + if (!editing) setAddr(entry ? addressText(entry.url) : ""); + }, [entry?.url, editing]); + + // Navigation bridge messages from our iframe only + useEffect(() => { + const onMsg = (e: MessageEvent) => { + const win = frameRef.current?.contentWindow; + if (!win || e.source !== win) return; + const d = e.data as { ac_preview?: unknown; href?: unknown; title?: unknown }; + if (!d || typeof d !== "object" || d.ac_preview !== 1 || typeof d.href !== "string") return; + const cur = usePreview.getState().byThread[key]; + if (!cur?.proxyOrigin) return; + const shown = displayHref(d.href.slice(0, 2048), cur.proxyOrigin, cur.origin); + const c = checkPreviewUrl(shown); + if (!c.ok || c.target.origin !== cur.origin) return; + const title = typeof d.title === "string" ? d.title.slice(0, 200) : ""; + usePreview.getState().reported(key, c.target.href, title); + // remember in-page navigation on the conversation (debounced) + if (threadId && c.target.href !== cur.url) { + if (saveTimer.current) clearTimeout(saveTimer.current); + saveTimer.current = setTimeout(() => void ws.call("threads.update", { id: threadId, previewUrl: c.target.href }).catch(() => {}), 800); + } + }; + window.addEventListener("message", onMsg); + return () => window.removeEventListener("message", onMsg); + }, [key, threadId]); + + const go = (raw: string) => { + const v = raw.trim(); + if (!v) return; + const c = checkPreviewUrl(v); + if (!c.ok) { + setBad(v); + return; + } + setBad(null); + setEditing(false); + void usePreview.getState().navigate(call, key, threadId, c.target.href, { push: true }); + }; + + const post = (cmd: "back" | "forward" | "reload") => { + try { frameRef.current?.contentWindow?.postMessage({ ac_preview_cmd: cmd }, "*"); } catch {} + }; + const back = () => { + if (entry?.bridged) return post("back"); + const u = usePreview.getState().step(key, -1); + if (u) void usePreview.getState().navigate(call, key, threadId, u, { push: false }); + }; + const forward = () => { + if (entry?.bridged) return post("forward"); + const u = usePreview.getState().step(key, 1); + if (u) void usePreview.getState().navigate(call, key, threadId, u, { push: false }); + }; + const reload = () => { + if (!entry) return; + if (entry.error || !entry.proxyHref) { + void usePreview.getState().navigate(call, key, threadId, entry.url, { push: false }); + return; + } + if (entry.bridged) post("reload"); + else usePreview.getState().reload(key); + }; + + const canBack = !!entry && (entry.bridged || entry.idx > 0); + const canFwd = !!entry && (entry.bridged || entry.idx < entry.stack.length - 1); + const external = entry ? externalHref(entry.url) : null; + const badExternal = bad ? externalHref(/^[a-z][a-z0-9+.-]*:\/\//i.test(bad) ? bad : `https://${bad}`) : null; + const widen = () => ui.setPanelWidth(Math.min(PN_MAX, maxPanelWidth({ ...useUi.getState(), panelOpen: true }))); + + return ( + <div className="pv"> + <div className="pv-bar"> + <button type="button" className="ibtn" title={t("preview.back")} aria-label={t("preview.back")} disabled={!canBack} onClick={back}><Icon name="arrowLeft" size={15} /></button> + <button type="button" className="ibtn" title={t("preview.forward")} aria-label={t("preview.forward")} disabled={!canFwd} onClick={forward}><Icon name="arrowRight" size={15} /></button> + <button type="button" className="ibtn" title={t("preview.reload")} aria-label={t("preview.reload")} disabled={!entry} onClick={reload}><Icon name="refresh" size={14} /></button> + <input + className={`pv-addr${bad ? " err" : ""}`} + value={addr} + spellCheck={false} + placeholder={t("preview.placeholder")} + aria-label={t("preview.address")} + onFocus={(e) => { setEditing(true); e.currentTarget.select(); }} + onBlur={() => { setEditing(false); }} + onChange={(e) => { setAddr(e.target.value); if (bad) setBad(null); }} + onKeyDown={(e) => { + if (e.nativeEvent.isComposing) return; + if (e.key === "Enter") { e.preventDefault(); go(addr); } + else if (e.key === "Escape") { setEditing(false); setBad(null); setAddr(entry ? addressText(entry.url) : ""); (e.target as HTMLInputElement).blur(); } + }} + /> + <button type="button" className="ibtn" title={t("preview.openExternal")} aria-label={t("preview.openExternal")} disabled={!external} onClick={() => external && void openExternal(external)}><Icon name="external" size={14} /></button> + <button type="button" className="ibtn" title={t("preview.widen")} aria-label={t("preview.widen")} onClick={widen}><Icon name="widen" size={15} /></button> + </div> + {bad && ( + <div className="pv-note err"> + <span>{t("preview.onlyLocal")}</span> + {badExternal && <button type="button" className="btn" onClick={() => { void openExternal(badExternal); setBad(null); }}>{t("preview.openExternal")}</button>} + </div> + )} + {entry?.error && ( + <div className="pv-note err"> + <span>{t("preview.failed")}{localizeDaemonMessage(entry.error)}</span> + {external && <button type="button" className="btn" onClick={() => void openExternal(external)}>{t("preview.openExternal")}</button>} + <button type="button" className="btn" onClick={reload}>{t("common.retry")}</button> + </div> + )} + {!entry ? ( + <div className="pv-empty"> + <div>{t("preview.empty")}</div> + <div className="pv-hint">{t("preview.limits")}</div> + </div> + ) : ( + <div className="pv-frame-wrap"> + {entry.loading && <div className="pv-loading" />} + {entry.proxyHref && ( + <iframe + key={`${entry.proxyOrigin}|${entry.nonce}`} + ref={frameRef} + className="pv-frame" + title={entry.title || addressText(entry.url)} + src={entry.proxyHref} + referrerPolicy="no-referrer" + /> + )} + </div> + )} + </div> + ); +} diff --git a/packages/agent-console/web/src/components/Settings.tsx b/packages/agent-console/web/src/components/Settings.tsx index b1c051d..01768d3 100644 --- a/packages/agent-console/web/src/components/Settings.tsx +++ b/packages/agent-console/web/src/components/Settings.tsx @@ -10,11 +10,13 @@ import type { ProviderInfo } from "../types/models.js"; import { useData } from "../stores/data.js"; import { IDLE_MAX, IDLE_MIN, parseArgsDraft, parseIdleDraft } from "./settingsFields.js"; import { applyTheme, embeddedInMagpie, normalizeThemeSetting } from "../layout/theme.js"; +import { applyChatLayout, normalizeChatFont, normalizeContentWidth, CHAT_FONT_MIN, CHAT_FONT_MAX, CHAT_FONT_DEFAULT } from "../layout/chatLayout.js"; type Settings = { defaultProvider?: string; defaultMode?: string; sendKey?: string; runningSend?: string; showThinking?: boolean; theme?: string; idleCloseMinutes?: number; + contentWidth?: string; chatFontSize?: number; providerEnabled?: Record<string, boolean>; providerCommand?: Record<string, { executable?: string; args?: string[] }>; [k: string]: unknown; @@ -63,6 +65,8 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr const next = { ...s, ...patch } as Settings; setS(next); if (patch.theme) applyTheme(patch.theme); + const layout = patch.contentWidth !== undefined || patch.chatFontSize !== undefined; + if (layout) applyChatLayout(next); try { await ws.call("settings.set", { patch }); window.dispatchEvent(new CustomEvent("settings-changed", { detail: next })); @@ -70,6 +74,7 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr } catch (e) { setS(prev); if (patch.theme) applyTheme(prev?.theme); + if (layout) applyChatLayout(prev ?? {}); toast(t("settings.failSave") + errMsg(e), true); return false; } @@ -232,6 +237,24 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr { value: "dark", label: t("settings.themeDark") }, ]} /> ))} + {row(t("settings.contentWidth"), ( + <SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.contentWidth")} + value={normalizeContentWidth(s.contentWidth)} onChange={(v) => void set({ contentWidth: v })} + options={[ + { value: "narrow", label: t("settings.widthNarrow") }, + { value: "default", label: t("settings.widthDefault") }, + { value: "wide", label: t("settings.widthWide") }, + { value: "full", label: t("settings.widthFull") }, + ]} /> + ))} + {row(t("settings.chatFont"), ( + <SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.chatFont")} + value={String(normalizeChatFont(s.chatFontSize))} onChange={(v) => void set({ chatFontSize: Number(v) })} + options={Array.from({ length: CHAT_FONT_MAX - CHAT_FONT_MIN + 1 }, (_, i) => CHAT_FONT_MIN + i).map((n) => ({ + value: String(n), + label: `${n} px${n === CHAT_FONT_DEFAULT ? t("settings.chatFontDefault") : ""}`, + }))} /> + ), t("settings.chatFontHint"))} {row(t("settings.sendKey"), ( <SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.sendKey")} value={s.sendKey ?? "enter"} onChange={(v) => void set({ sendKey: v })} diff --git a/packages/agent-console/web/src/components/Sidebar.tsx b/packages/agent-console/web/src/components/Sidebar.tsx index 75f75b2..a2a236f 100644 --- a/packages/agent-console/web/src/components/Sidebar.tsx +++ b/packages/agent-console/web/src/components/Sidebar.tsx @@ -153,6 +153,7 @@ export function Sidebar({ pendingByThread }: { pendingByThread: Set<string> }) { return ( <> <div className="sb-row"> + <SidebarToggle /> <button className="sb-new" onClick={() => setNewProjOpen(true)}> <span className="sb-new-tile"><Icon name="plus" size={12} /></span>{tr("sidebar.newProject")} </button> @@ -512,3 +513,16 @@ async function exportThread(t: ThreadMeta) { toast(tr("sidebar.failExport") + errMsg(e), true); } } + +/** Collapse / expand the sidebar (the same button sits in the top bar while the sidebar is collapsed); Ctrl/⌘+B */ +export function SidebarToggle({ className = "" }: { className?: string }) { + const hidden = useUi((s) => s.sbHidden); + const open = useUi((s) => s.sbOpen); + const label = tr(hidden && !open ? "sidebar.expand" : "sidebar.collapse"); + return ( + <button type="button" className={`ibtn sb-toggle ${className}`} title={`${label} (Ctrl+B)`} aria-label={label} + aria-expanded={!hidden || open} onClick={() => useUi.getState().toggleSidebar()}> + <Icon name="panelLeft" /> + </button> + ); +} diff --git a/packages/agent-console/web/src/components/Timeline.tsx b/packages/agent-console/web/src/components/Timeline.tsx index f6a2e10..aa3ecd1 100644 --- a/packages/agent-console/web/src/components/Timeline.tsx +++ b/packages/agent-console/web/src/components/Timeline.tsx @@ -11,6 +11,8 @@ import { fmtDur, fmtTokens, fmtCost } from "../util/format"; import { useUi } from "../stores/ui"; import { localizeDaemonMessage, t, tf } from "../i18n/index.js"; import { toast } from "./Toast"; +import { splitLocalLinks } from "../util/localLinks"; +import { onChatLinkClick } from "../preview/open"; const token = () => getToken(); @@ -18,18 +20,59 @@ export function attachmentUrl(id: string): string { return `/attachments/${id}?t=${token()}`; } +/** Plain text with local addresses as Preview links (tool output; React nodes, no innerHTML) */ +export function LinkifiedText({ text }: { text: string }) { + const parts = useMemo(() => splitLocalLinks(text), [text]); + if (parts.length === 1 && typeof parts[0] === "string") return <>{text}</>; + return ( + <> + {parts.map((p, i) => + typeof p === "string" ? p : ( + <a key={i} href={p.url} data-ac-local={p.url} className="ac-local" title={t("links.openPreviewTitle")}>{p.text}</a> + ), + )} + </> + ); +} + +const baseName = (p: string) => p.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || p; + +/** A path chip (composer, user bubble): icon + name (folders end with /), full path on hover */ +const isImageMime = (m: string | undefined): boolean => !m || m.startsWith("image/"); + +export function MentionChip({ path, isDir, onRemove }: { path: string; isDir: boolean; onRemove?: () => void }) { + return ( + <span className="mention" title={path}> + <Icon name={isDir ? "files" : "file"} size={12} /> + <span className="mention-name">{baseName(path)}{isDir ? "/" : ""}</span> + {onRemove && <button type="button" className="att-x" aria-label={t("mention.remove")} onClick={onRemove}>×</button>} + </span> + ); +} + // ---------- user message ---------- -export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "user" }>; onRetry?: (text: string) => void }) { +export function UserItem({ it, onRetry }: { it: Extract<DisplayItem, { kind: "user" }>; onRetry?: (text: string, mentions?: { path: string; isDir: boolean }[]) => void }) { return ( <div className="um-row"> <div className="um"> - {it.attachments?.map((a) => ( + {it.attachments?.filter((a) => isImageMime(a.mime)).map((a) => ( <img key={a.id} className="um-img" src={`/attachments/${a.id}?t=${token()}`} alt={a.name} /> ))} + {/* text / PDF / other files: a name chip (they used to render as a broken <img>) */} + {it.attachments?.some((a) => !isImageMime(a.mime)) && ( + <span className="um-mentions"> + {it.attachments.filter((a) => !isImageMime(a.mime)).map((a) => ( + <span key={a.id} className="mention" title={a.name}><Icon name="file" size={12} /><span className="mention-name">{a.name}</span></span> + ))} + </span> + )} + {it.mentions && it.mentions.length > 0 && ( + <span className="um-mentions">{it.mentions.map((m) => <MentionChip key={m.path} path={m.path} isDir={m.isDir} />)}</span> + )} <span className="um-text">{it.text}</span> <div className="um-act"> <button className="ibtn" title={t("common.copy")} onClick={() => void copyText(it.text)}><Icon name="copy" size={13} /></button> - {onRetry && <button className="ibtn" title={t("timeline.editResend")} onClick={() => onRetry(it.text)}><Icon name="send" size={13} /></button>} + {onRetry && <button className="ibtn" title={t("timeline.editResend")} onClick={() => onRetry(it.text, it.mentions)}><Icon name="send" size={13} /></button>} </div> </div> {it.steered && <div className="um-tag">{t("timeline.steer")}</div>} @@ -84,12 +127,14 @@ export function ToolGroupItem({ it }: { it: Extract<DisplayItem, { kind: "toolgr useEffect(() => { if (!userToggled.current && (hasFail || hasDiff)) setOpen(true); }, [hasFail, hasDiff]); - const summary = useMemo(() => { + // Not memoized on it.steps: the reducer appends steps to the same array while a turn streams, + // so a memo keyed on the array kept the first count ("1 step · Read 1" next to five steps). + const summary = (() => { const counts = new Map<string, number>(); for (const s of it.steps) counts.set(s.kind, (counts.get(s.kind) ?? 0) + 1); const parts = [...counts.entries()].map(([k, n]) => `${toolKind(k)} ${n}`); - return tf("timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") }); - }, [it.steps]); + return tf(it.steps.length === 1 ? "timeline.toolSummaryOne" : "timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") }); + })(); const runningStep = it.steps.find((s) => s.status === "running"); return ( <div className="tg"> @@ -142,7 +187,7 @@ function ToolDetail({ s }: { s: ToolStep }) { return ( <div className="ts-out"> {tail && <button className="ts-more" onClick={() => setFull(true)}>{tf("timeline.showAllLines", { n: lines.length })}</button>} - <pre>{text}</pre> + <pre onClick={onChatLinkClick}><LinkifiedText text={text} /></pre> </div> ); } @@ -340,7 +385,7 @@ export function TurnEndItem({ it, onRetry, replyText }: { it: Extract<DisplayIte // ---------- dispatch ---------- export function TimelineRow({ it, threadId, onEditResend, onRetryLast, replyText }: { it: DisplayItem; threadId: string; replyText?: string; - onEditResend?: (text: string) => void; + onEditResend?: (text: string, mentions?: { path: string; isDir: boolean }[]) => void; onRetryLast?: () => void; }) { switch (it.kind) { diff --git a/packages/agent-console/web/src/components/Topbar.tsx b/packages/agent-console/web/src/components/Topbar.tsx index b3943e2..1c7588f 100644 --- a/packages/agent-console/web/src/components/Topbar.tsx +++ b/packages/agent-console/web/src/components/Topbar.tsx @@ -6,6 +6,7 @@ import { useUi, type PanelTab } from "../stores/ui"; import { useConnection } from "../stores/connection"; import { ws } from "../main"; import { Icon } from "./Icons"; +import { SidebarToggle } from "./Sidebar"; import { Menu, useMenu, type MenuItem } from "./Menu"; import { Dialog } from "./Dialog"; import { copyText } from "./Markdown"; @@ -55,6 +56,7 @@ export function Topbar({ pendingCount }: { pendingCount: number }) { { tab: "changes", icon: "changes", title: t("topbar.panelChanges") }, { tab: "files", icon: "files", title: t("topbar.panelFiles") }, { tab: "terminal", icon: "term", title: t("topbar.panelTerminal") }, + { tab: "preview", icon: "globe", title: t("preview.tab") }, ]; const moreItems: MenuItem[] = thread @@ -72,13 +74,8 @@ export function Topbar({ pendingCount }: { pendingCount: number }) { return ( <header className="topbar"> - <button - className="ibtn tb-menu-btn" - title={t("topbar.sidebar")} - onClick={() => ui.setSbOpen(!ui.sbOpen)} - > - <Icon name="menu" /> - </button> + {/* sidebar collapsed (or a narrow window's drawer): the toggle lives here, before the breadcrumb */} + <SidebarToggle className={`tb-menu-btn${ui.sbHidden ? " tb-sb-collapsed" : ""}`} /> {project && <span className="tb-crumb">{project.name}</span>} {project && thread && <span className="tb-sep">/</span>} {thread ? ( diff --git a/packages/agent-console/web/src/composer/mentions.ts b/packages/agent-console/web/src/composer/mentions.ts new file mode 100644 index 0000000..b3390d9 --- /dev/null +++ b/packages/agent-console/web/src/composer/mentions.ts @@ -0,0 +1,49 @@ +// Path chips from the Files panel (1.2): drag data, de-duplication, what thread.send gets. Pure, unit tested. + +/** dataTransfer type of a Files-panel row dragged into the composer */ +export const MENTION_MIME = "application/x-agent-console-path"; +export const MAX_MENTIONS = 50; +export type MentionDraft = { projectId: string; rel: string; isDir: boolean }; + +/** Absolute path of a project-relative path, with the project's own separator (Windows paths keep backslashes) */ +export function joinProjectPath(root: string, rel: string): string { + const win = /^[a-zA-Z]:[\\/]/.test(root) || root.startsWith("\\\\"); + const sep = win ? "\\" : "/"; + const r = rel === "." ? "" : win ? rel.replace(/\//g, "\\") : rel; + return r ? root.replace(/[\\/]+$/, "") + sep + r : root; +} + +/** The drag payload (any page could forge one: the daemon checks the path again) */ +export function parseMentionDrag(raw: string | null | undefined): MentionDraft | null { + if (!raw || raw.length > 10000) return null; + try { + const o = JSON.parse(raw) as Partial<MentionDraft>; + if (typeof o.projectId !== "string" || typeof o.rel !== "string" || !o.rel || o.rel.length > 4096) return null; + return { projectId: o.projectId, rel: o.rel, isDir: o.isDir === true }; + } catch { + return null; + } +} + +export function addMention(list: MentionDraft[], m: MentionDraft): MentionDraft[] { + if (list.some((x) => x.projectId === m.projectId && x.rel === m.rel)) return list; + if (list.length >= MAX_MENTIONS) return list; + return [...list, m]; +} + +/** thread.send's mentions field */ +export function mentionsForSend(list: MentionDraft[]): { rel: string; isDir: boolean }[] { + return list.map((m) => ({ rel: m.rel, isDir: m.isDir })); +} + +/** A sent message's absolute paths → project-relative again (edit & resend); paths outside the project are dropped */ +export function relFromAbs(root: string, abs: string): string | null { + const norm = (s: string) => s.replace(/\\/g, "/").replace(/\/+$/, ""); + const r = norm(root); + const a = norm(abs); + const win = /^[a-zA-Z]:\//.test(r); + const eq = (x: string, y: string) => (win ? x.toLowerCase() === y.toLowerCase() : x === y); + if (eq(a, r)) return "."; + if (a.length > r.length && eq(a.slice(0, r.length), r) && a[r.length] === "/") return a.slice(r.length + 1); + return null; +} diff --git a/packages/agent-console/web/src/i18n/index.ts b/packages/agent-console/web/src/i18n/index.ts index 270c07f..53672f1 100644 --- a/packages/agent-console/web/src/i18n/index.ts +++ b/packages/agent-console/web/src/i18n/index.ts @@ -24,6 +24,15 @@ export function initLocale(search: string): LocaleId { return locale; } +/** Switch the UI language at runtime (Magpie's language changed); returns whether it changed */ +export function setLocale(raw: string | null | undefined): boolean { + const next = normalizeLang(raw); + if (next === locale) return false; + locale = next; + if (typeof document !== "undefined") document.documentElement.lang = locale === "zh" ? "zh-CN" : "en"; + return true; +} + export function getLocale(): LocaleId { return locale; } diff --git a/packages/agent-console/web/src/i18n/messages.ts b/packages/agent-console/web/src/i18n/messages.ts index c92ac5d..84bc167 100644 --- a/packages/agent-console/web/src/i18n/messages.ts +++ b/packages/agent-console/web/src/i18n/messages.ts @@ -28,7 +28,7 @@ export const messages: Record<LocaleId, MessageTree> = { panelChanges: "改动(Ctrl+J)", panelFiles: "文件", panelTerminal: "终端", }, sidebar: { - newProject: "新建项目", filterPlaceholder: "过滤对话标题", searchTitle: "搜索(Ctrl+K)", + newProject: "新建项目", collapse: "收起侧栏", expand: "展开侧栏", filterPlaceholder: "过滤对话标题", searchTitle: "搜索(Ctrl+K)", noProjectsTitle: "还没有项目", noProjectsSub: "项目对应一个本机目录,对话都在目录里干活。", newThread: "新建对话", projectMenu: "项目菜单", showAll: "显示全部 {n} 条", noThreads: "还没有对话", rename: "重命名", pin: "置顶", unpin: "取消置顶", archive: "归档", unarchive: "取消归档", @@ -95,6 +95,8 @@ export const messages: Record<LocaleId, MessageTree> = { effort: { low: "低", medium: "中", high: "高", xhigh: "超高", max: "最高", minimal: "最低", none: "关闭" }, }, settings: { + contentWidth: "内容宽度", widthNarrow: "窄(640)", widthDefault: "默认(720)", widthWide: "宽(880)", widthFull: "铺满", + chatFont: "聊天字号", chatFontDefault: "(默认)", chatFontHint: "对话正文、输入框、工具输出和代码一起缩放(代码小 1px)", title: "设置", defaultAgent: "默认 Agent", defaultMode: "默认权限模式", theme: "主题", themeAuto: "跟随系统", themeMagpie: "跟随 Magpie", themeLight: "浅色", themeDark: "深色", sendKey: "发送键", sendEnter: "Enter 发送 / Shift+Enter 换行", sendCtrl: "Ctrl+Enter 发送 / Enter 换行", @@ -152,7 +154,7 @@ export const messages: Record<LocaleId, MessageTree> = { read: "读取", edit: "修改", write: "写入", bash: "运行", search: "搜索", glob: "搜索", web: "联网", task: "子任务", mcp: "工具", todo: "待办", other: "工具", processing: "处理", }, - toolSummary: "已执行 {n} 步 · {parts}", toolRunning: "正在{kind}:{title}", + toolSummary: "已执行 {n} 步 · {parts}", toolSummaryOne: "已执行 1 步 · {parts}", toolRunning: "正在{kind}:{title}", showAllLines: "显示全部 {n} 行", diffClip: "(只显示前 {n} 行)", }, api: { @@ -160,6 +162,22 @@ export const messages: Record<LocaleId, MessageTree> = { busy: "正忙,请稍后再试", bad_path: "路径无效", connClosed: "连接中断", notConnected: "连接未建立", timeout: "请求超时", }, + preview: { + tab: "预览", address: "预览地址", placeholder: "localhost:5173", back: "后退", forward: "前进", reload: "刷新", + openExternal: "用系统浏览器打开", widen: "加宽面板", onlyLocal: "预览只支持本机地址(localhost、127.0.0.1 等)", + failed: "打不开预览:", + empty: "还没有预览地址。在对话里点 localhost 链接,或在上方输入,例如 localhost:5173", + limits: "预览在沙箱里运行:弹窗、alert 和原生表单提交不可用;localStorage 和登录 cookie 刷新后会丢失,需要时请用系统浏览器打开。", + noLocalhost: "这台电脑的网页内核打不开 *.localhost 地址(macOS 26 以前的系统会这样)。预览靠这个地址挡住别的网页读取你的 dev server,所以这里不能预览,请用系统浏览器打开。", + }, + links: { + openPreviewTitle: "在预览中打开(Ctrl/⌘+点击用浏览器打开)", + externalFailed: "打不开系统浏览器,已复制链接", + }, + mention: { + drop: "松开以插入到聊天", add: "插入到聊天", copyRel: "复制相对路径", remove: "移除", + otherProject: "只能插入当前对话所在项目里的文件", + }, }, en: { app: { title: "Agent Console", subtitle: "Create or select a project in the sidebar" }, @@ -185,7 +203,7 @@ export const messages: Record<LocaleId, MessageTree> = { panelChanges: "Changes (Ctrl+J)", panelFiles: "Files", panelTerminal: "Terminal", }, sidebar: { - newProject: "New project", filterPlaceholder: "Filter conversations", searchTitle: "Search (Ctrl+K)", + newProject: "New project", collapse: "Collapse sidebar", expand: "Expand sidebar", filterPlaceholder: "Filter conversations", searchTitle: "Search (Ctrl+K)", noProjectsTitle: "No projects yet", noProjectsSub: "A project maps to a folder on this machine.", newThread: "New conversation", projectMenu: "Project menu", showAll: "Show all {n}", noThreads: "No conversations yet", @@ -251,6 +269,8 @@ export const messages: Record<LocaleId, MessageTree> = { effort: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max", minimal: "Minimal", none: "Off" }, }, settings: { + contentWidth: "Content width", widthNarrow: "Narrow (640)", widthDefault: "Default (720)", widthWide: "Wide (880)", widthFull: "Full", + chatFont: "Chat font size", chatFontDefault: " (default)", chatFontHint: "Scales the conversation, the input, tool output and code (code 1px smaller)", title: "Settings", defaultAgent: "Default agent", defaultMode: "Default permission mode", theme: "Theme", themeAuto: "System", themeMagpie: "Follow Magpie", themeLight: "Light", themeDark: "Dark", sendKey: "Send shortcut", sendEnter: "Enter sends / Shift+Enter newline", @@ -309,7 +329,7 @@ export const messages: Record<LocaleId, MessageTree> = { read: "Read", edit: "Edit", write: "Write", bash: "Run", search: "Search", glob: "Search", web: "Web", task: "Subtask", mcp: "Tool", todo: "Todo", other: "Tool", processing: "Working", }, - toolSummary: "{n} step(s) · {parts}", toolRunning: "{kind}: {title}", + toolSummary: "{n} steps · {parts}", toolSummaryOne: "1 step · {parts}", toolRunning: "{kind}: {title}", showAllLines: "Show all {n} lines", diffClip: "(first {n} lines only)", }, api: { @@ -317,5 +337,21 @@ export const messages: Record<LocaleId, MessageTree> = { busy: "Busy — try again later", bad_path: "Invalid path", connClosed: "Connection lost", notConnected: "Not connected", timeout: "Request timed out", }, + preview: { + tab: "Preview", address: "Preview address", placeholder: "localhost:5173", back: "Back", forward: "Forward", reload: "Reload", + openExternal: "Open in browser", widen: "Widen panel", onlyLocal: "Preview only supports local addresses (localhost, 127.0.0.1, …)", + failed: "Can't open the preview: ", + empty: "Nothing to preview yet. Click a localhost link in the chat, or type an address above, e.g. localhost:5173", + limits: "The preview runs sandboxed: popups, alert and native form posts don't work; localStorage and login cookies are lost on reload. Open it in your browser when you need them.", + noLocalhost: "This system's web view can't open *.localhost addresses (macOS before 26 can't). The preview needs one to keep other web pages out of your dev server, so it can't run here: open it in your browser instead.", + }, + links: { + openPreviewTitle: "Open in Preview (Ctrl/⌘+click opens the browser)", + externalFailed: "Couldn't open the browser; the link was copied", + }, + mention: { + drop: "Drop to add to the chat", add: "Add to chat", copyRel: "Copy relative path", remove: "Remove", + otherProject: "Only files of this conversation's project can be added", + }, }, }; diff --git a/packages/agent-console/web/src/layout/applyMagpieTokens.ts b/packages/agent-console/web/src/layout/applyMagpieTokens.ts index e4bb935..ab078e2 100644 --- a/packages/agent-console/web/src/layout/applyMagpieTokens.ts +++ b/packages/agent-console/web/src/layout/applyMagpieTokens.ts @@ -13,11 +13,26 @@ export function applyMagpieTokensFromSearch(search: string): void { } catch { return; } - const root = document.documentElement; + applyMagpieTokens(obj); +} + +/** Magpie token map → CSS variables name → value (accent dropped; odd names / values skipped). Pure, for tests. */ +export function magpieTokenVars(obj: Record<string, unknown> | null | undefined): Record<string, string> { + const out: Record<string, string> = {}; + if (!obj || typeof obj !== "object") return out; for (const [k, v] of Object.entries(obj)) { - const s = String(v ?? "").trim(); - if (!s || isAccentToken(k)) continue; - const varName = k.startsWith("--") ? k : k.startsWith("magpie-") ? `--${k}` : `--magpie-${k}`; - root.style.setProperty(varName, s); + if (typeof v !== "string" && typeof v !== "number") continue; + const s = String(v).trim(); + if (!s || s.length > 300 || /[;{}<>]/.test(s) || isAccentToken(k)) continue; + const name = k.replace(/^--/, "").replace(/^magpie-/i, ""); + if (!/^[a-zA-Z0-9-]{1,48}$/.test(name)) continue; + out[`--magpie-${name}`] = s; } + return out; +} + +/** Write Magpie's tokens as --magpie-* variables (at load from ?tokens=, and live from the bridge's theme events) */ +export function applyMagpieTokens(obj: Record<string, unknown> | null | undefined): void { + const root = document.documentElement; + for (const [k, v] of Object.entries(magpieTokenVars(obj))) root.style.setProperty(k, v); } diff --git a/packages/agent-console/web/src/layout/chatLayout.ts b/packages/agent-console/web/src/layout/chatLayout.ts new file mode 100644 index 0000000..4055b3f --- /dev/null +++ b/packages/agent-console/web/src/layout/chatLayout.ts @@ -0,0 +1,32 @@ +// Conversation column width and chat text size (1.2 settings). Both are CSS variables on <html>: +// --col the column the timeline and the composer share (720px by default) +// --chat-fs chat text size; tokens.css derives code (1px smaller), headings and line heights from it +export type ContentWidth = "narrow" | "default" | "wide" | "full"; +export const CONTENT_WIDTHS: ContentWidth[] = ["narrow", "default", "wide", "full"]; +export const WIDTH_PX: Record<Exclude<ContentWidth, "full">, number> = { narrow: 640, default: 720, wide: 880 }; +export const CHAT_FONT_MIN = 12; +export const CHAT_FONT_MAX = 18; +export const CHAT_FONT_DEFAULT = 13; + +export function normalizeContentWidth(v: unknown): ContentWidth { + return v === "narrow" || v === "wide" || v === "full" ? v : "default"; +} + +/** CSS value of --col for a width setting */ +export function colValue(v: unknown): string { + const w = normalizeContentWidth(v); + return w === "full" ? "100%" : `${WIDTH_PX[w]}px`; +} + +export function normalizeChatFont(v: unknown): number { + const n = typeof v === "number" ? v : Number(v); + if (!Number.isFinite(n)) return CHAT_FONT_DEFAULT; + return Math.min(CHAT_FONT_MAX, Math.max(CHAT_FONT_MIN, Math.round(n))); +} + +export function applyChatLayout(s: { contentWidth?: unknown; chatFontSize?: unknown }): void { + const root = document.documentElement; + root.style.setProperty("--col", colValue(s.contentWidth)); + root.style.setProperty("--chat-fs", `${normalizeChatFont(s.chatFontSize)}px`); + root.dataset.contentWidth = normalizeContentWidth(s.contentWidth); +} diff --git a/packages/agent-console/web/src/layout/magpieBridge.ts b/packages/agent-console/web/src/layout/magpieBridge.ts new file mode 100644 index 0000000..9f774bd --- /dev/null +++ b/packages/agent-console/web/src/layout/magpieBridge.ts @@ -0,0 +1,53 @@ +// Live theme from Magpie (1.2 fix). The plugin page (page/boot.js) navigates its frame to the daemon page, so Magpie's +// bridge.js is gone from the frame; but Magpie's window keeps posting {magpie:1, event:"theme", data:{dark, lang, tokens}} +// to the frame's window, and answers a {magpie:1, method:"hello"} call with the current theme. This page speaks that small +// part of the bridge protocol itself: at load (the theme may have changed during the redirect, or after a self-heal) and on +// every switch, so the page follows Magpie's light/dark and neutral colours without a reload. +// Only messages from window.parent with magpie:1 are read, and only the theme fields (and the language) are used; no commands are taken. +import { applyMagpieTokens } from "./applyMagpieTokens.js"; +import { setHostTheme } from "./theme.js"; + +export type MagpieTheme = { dark: boolean; tokens: Record<string, unknown>; lang?: string }; + +/** A theme payload from Magpie (event data, or a hello answer) → {dark, tokens}, or null if it isn't one */ +export function parseMagpieTheme(d: unknown): MagpieTheme | null { + if (!d || typeof d !== "object") return null; + const o = d as { dark?: unknown; tokens?: unknown; lang?: unknown }; + if (typeof o.dark !== "boolean") return null; + const tokens = o.tokens && typeof o.tokens === "object" && !Array.isArray(o.tokens) ? (o.tokens as Record<string, unknown>) : {}; + const out: MagpieTheme = { dark: o.dark, tokens }; + if (typeof o.lang === "string" && o.lang.length <= 32) out.lang = o.lang; + return out; +} + +/** Which theme a bridge message carries, given the id of our own hello call */ +export function themeFromMessage(m: unknown, helloId: number): MagpieTheme | null { + if (!m || typeof m !== "object") return null; + const msg = m as { magpie?: unknown; event?: unknown; data?: unknown; id?: unknown; result?: unknown }; + if (msg.magpie !== 1) return null; + if (msg.event === "theme") return parseMagpieTheme(msg.data); + if (msg.id === helloId && msg.result) return parseMagpieTheme(msg.result); + return null; +} + +let started = false; + +export function startMagpieThemeBridge(onTheme?: (t: MagpieTheme) => void): void { + if (started || typeof window === "undefined") return; + const parentWin = window.parent; + if (!parentWin || parentWin === window) return; + started = true; + // a large id of our own, far from what bridge.js used before the navigation + const helloId = 1_000_000 + Math.floor(Math.random() * 1_000_000); + window.addEventListener("message", (e) => { + if (e.source !== parentWin) return; + const t = themeFromMessage(e.data, helloId); + if (!t) return; + applyMagpieTokens(t.tokens); + setHostTheme(t.dark ? "dark" : "light"); + onTheme?.(t); + }); + try { + parentWin.postMessage({ magpie: 1, id: helloId, method: "hello" }, "*"); + } catch {} +} diff --git a/packages/agent-console/web/src/layout/theme.ts b/packages/agent-console/web/src/layout/theme.ts index 53f7d51..e0744d3 100644 --- a/packages/agent-console/web/src/layout/theme.ts +++ b/packages/agent-console/web/src/layout/theme.ts @@ -38,6 +38,16 @@ export function embeddedInMagpie(): boolean { return hostTheme !== null; } +/** Magpie switched light/dark while the page is open (bridge theme event, see magpieBridge.ts) */ +export function setHostTheme(t: Theme): void { + hostTheme = t; + applyTheme(current); +} + +export function currentSetting(): ThemeSetting { + return current; +} + export function applyTheme(setting: unknown): void { current = normalizeThemeSetting(setting); const { theme, hostColors } = resolveTheme(current, hostTheme, osTheme()); diff --git a/packages/agent-console/web/src/main.tsx b/packages/agent-console/web/src/main.tsx index 9258497..014a0ba 100644 --- a/packages/agent-console/web/src/main.tsx +++ b/packages/agent-console/web/src/main.tsx @@ -1,4 +1,5 @@ // Entry: read the hash token and theme params, mount <App/>. +import { usePreview } from "./stores/preview"; import "./styles/tokens.css"; import "./styles/base.css"; import "./styles/layout.css"; @@ -7,8 +8,10 @@ import "./styles/composer.css"; import { createRoot } from "react-dom/client"; import { applyMagpieTokensFromSearch } from "./layout/applyMagpieTokens.js"; import { applyTheme, initTheme } from "./layout/theme.js"; +import { startMagpieThemeBridge } from "./layout/magpieBridge.js"; +import { applyChatLayout } from "./layout/chatLayout.js"; import { goBackToMagpie, watchReconnect } from "./api/backToMagpie.js"; -import { initLocale, getLocale } from "./i18n/index.js"; +import { initLocale, getLocale, setLocale } from "./i18n/index.js"; import { WsClient } from "./api/ws"; import { useConnection } from "./stores/connection"; import { useUi } from "./stores/ui"; @@ -24,11 +27,18 @@ const params = new URLSearchParams(location.search); initLocale(location.search); applyMagpieTokensFromSearch(location.search); initTheme(location.search); - +// Follow Magpie's light/dark live (the frame no longer has bridge.js after boot.js navigated it here) export const ws = new WsClient(token, getLocale()); +// ...and its language: re-render the tree in the new language (t() isn't reactive), tell the daemon for its own text +startMagpieThemeBridge((th) => { + if (!th.lang || !setLocale(th.lang)) return; + ws.setLang(getLocale()); + void ws.call("app.setLocale", { lang: getLocale() }).catch(() => {}); + renderApp(); +}); // For the debug page (P1-8) and e2e driving: expose the authenticated client and internal stores. (window as unknown as { __ws?: WsClient; __stores?: unknown }).__ws = ws; -(window as unknown as { __stores?: unknown }).__stores = { useData, useUi, useConnection }; +(window as unknown as { __stores?: unknown }).__stores = { useData, useUi, useConnection, usePreview }; void import("./stores/timeline").then((m) => { (window as unknown as { __tl?: unknown }).__tl = m.useTimeline; }); @@ -44,6 +54,7 @@ ws.waitHello().then(async (h) => { const s = (await ws.call("settings.get")) as Record<string, unknown>; useUi.getState().hydrate(s); applyTheme(s.theme); + applyChatLayout(s); } catch {} // Fetch the project/conversation/provider lists and subscribe to the sidebar channel await useData.getState().bind(ws); @@ -51,7 +62,13 @@ ws.waitHello().then(async (h) => { setInterval(() => ws.ping(), 10000); const isDebug = params.get("debug") === "1"; -createRoot(document.getElementById("root")!).render(isDebug ? <DebugApp /> : <App />); +const root = createRoot(document.getElementById("root")!); +let renders = 0; +function renderApp(): void { + renders++; + root.render(isDebug ? <DebugApp /> : <App key={`${getLocale()}-${renders}`} />); +} +renderApp(); // ?audit=1 (§11.3 screenshot self-check metrics): count visible borders on the first screen, font-size set, accent-colored elements, horizontal scroll, // written to <pre id="audit"> (after 1.5s so the first screen settles). diff --git a/packages/agent-console/web/src/preview/open.ts b/packages/agent-console/web/src/preview/open.ts new file mode 100644 index 0000000..05fde00 --- /dev/null +++ b/packages/agent-console/web/src/preview/open.ts @@ -0,0 +1,41 @@ +// Opening links from chat (1.2): local addresses go to the Preview tab, everything http(s) else to the system browser +// (the sandboxed page can't open popups, so target=_blank did nothing). Only a user's click gets here. +import { ws } from "../main"; +import { useUi } from "../stores/ui"; +import { usePreview, threadKey } from "../stores/preview"; +import { localHref } from "../util/localLinks"; +import { copyText } from "../components/Markdown"; +import { toast } from "../components/Toast"; +import { t } from "../i18n/index.js"; + +export function openPreview(url: string): void { + const ui = useUi.getState(); + const threadId = ui.currentThreadId; + ui.openPanel("preview"); + void usePreview.getState().navigate((m, p) => ws.call(m, p), threadKey(threadId), threadId, url, { push: true }); +} + +export async function openExternal(url: string): Promise<void> { + try { + const r = (await ws.call("app.openExternal", { url })) as { ok?: boolean }; + if (r?.ok) return; + } catch {} + await copyText(url); + toast(t("links.externalFailed")); +} + +/** Delegated click handler for chat content: handles <a> clicks, never lets the frame navigate away */ +export function onChatLinkClick(e: React.MouseEvent | MouseEvent): void { + const target = e.target as HTMLElement | null; + const a = target?.closest?.("a"); + if (!a) return; + const href = a.getAttribute("href") ?? ""; + e.preventDefault(); + const local = (a as HTMLElement).dataset.acLocal || localHref(href); + const modified = e.ctrlKey || e.metaKey; + if (local && !modified) { + openPreview(local); + return; + } + if (/^https?:\/\//i.test(local || href)) void openExternal(local || href); +} diff --git a/packages/agent-console/web/src/stores/preview.ts b/packages/agent-console/web/src/stores/preview.ts new file mode 100644 index 0000000..5a98e52 --- /dev/null +++ b/packages/agent-console/web/src/stores/preview.ts @@ -0,0 +1,249 @@ +// Preview tab state per conversation (1.2): target URL, the proxy serving it, title, and a URL stack for back/forward +// when the page has no navigation bridge (the bridge, when present, drives back/forward inside the frame instead). +import { create } from "zustand"; +import { checkPreviewUrl, displayOrigin } from "../../../daemon/src/preview/url.js"; +import { t as tr } from "../i18n/index.js"; + +const t_noLocalhost = () => tr("preview.noLocalhost"); + +export type PreviewEntry = { + /** normalized target URL currently shown */ + url: string; + /** scheme://host:port of the target */ + origin: string; + proxyOrigin: string | null; + /** what the iframe loads (proxy origin + path); null until the proxy is up */ + proxyHref: string | null; + title: string; + loading: boolean; + error: string | null; + /** bumped to force the iframe to reload */ + nonce: number; + /** the injected bridge has reported at least once */ + bridged: boolean; + stack: string[]; + idx: number; +}; + +type Caller = (method: string, params?: unknown) => Promise<unknown>; + +type PreviewStore = { + byThread: Record<string, PreviewEntry>; + /** Load a URL in this conversation's preview (push = a new history entry) */ + navigate(call: Caller, key: string, threadId: string | null, raw: string, opts?: { push?: boolean }): Promise<boolean>; + /** The frame reported where it is now (bridge) */ + reported(key: string, url: string, title: string): void; + /** The proxy for this entry was released: re-open it next time */ + detach(key: string): void; + reload(key: string): void; + step(key: string, delta: -1 | 1): string | null; +}; + +export const threadKey = (threadId: string | null | undefined) => threadId ?? "_"; + +const inflight = new Map<string, Promise<boolean>>(); + +// The proxy answers only at http://ac<key>.localhost:<port> (#582, daemon/src/preview/proxy.ts). Before showing the frame, +// check that this web view resolves that name (Chromium/WebView2, WebKitGTK and WebKit on macOS 26+ do, WebKit on macOS +// before 26 doesn't): otherwise say why instead of a blank "can't find server" frame. Checked with a per-open nonce so a +// hostile DNS answer that returns a plain 200 "ok" can't pass. +export const PREVIEW_PING_PATH = "/__agent_console__/ping"; + +/** The daemon's OS as preview.open reports it (daemon/src/preview/host.ts) */ +export type PreviewHost = { platform: string; darwinMajor: number | null }; + +/** Darwin 25 = macOS 26 (same constant as daemon/src/preview/host.ts) */ +export const DARWIN_LOCALHOST_LOOPBACK = 25; + +/** + * Apple WebKit (Magpie's Mac app = WKWebView, Safari with magpie web): no Chrome / Chromium / Edge / Opera / iOS + * Chrome or Firefox token, and a Mac or iOS device. Linux WebKitGTK / WPE carry AppleWebKit but no Macintosh → not it. + */ +export function isAppleWebKit(ua = typeof navigator !== "undefined" ? navigator.userAgent : ""): boolean { + return /AppleWebKit\//i.test(ua) + && /Macintosh|iPhone|iPad|iPod/i.test(ua) + && !/Chrome\//i.test(ua) + && !/Chromium\//i.test(ua) + && !/Edg(?:e|A|iOS)?\//i.test(ua) + && !/OPR\//i.test(ua) + && !/CriOS\//i.test(ua) + && !/FxiOS\//i.test(ua); +} + +/** + * Apple WebKit before macOS 26 asks the system DNS for *.localhost (Magpie's Mac app on 12–15, Safari with magpie web). + * The UA can't tell: Apple froze it at "Mac OS X 10_15_7" on every macOS, 26+ included. So the version comes from the + * daemon (os.platform() + os.release() on the same Mac, it listens on 127.0.0.1 only). Refused: Apple WebKit on a + * Darwin < 25 host, or when the daemon's answer is missing / unparseable (fail closed). Non-darwin hosts and every + * other engine are left to the canary + nonce probe. + */ +export function isUnsafeLocalhostResolver( + host: PreviewHost | null | undefined, + ua = typeof navigator !== "undefined" ? navigator.userAgent : "", +): boolean { + if (!isAppleWebKit(ua)) return false; + if (!host || typeof host.platform !== "string" || !host.platform) return true; + if (host.platform !== "darwin") return false; + const major = host.darwinMajor; + if (typeof major !== "number" || !Number.isInteger(major)) return true; + return major < DARWIN_LOCALHOST_LOOPBACK; +} + +/** GET origin+/__agent_console__/ping must return exactly expectedNonce (from preview.open over the authenticated WS). */ +export async function canReachProxy(origin: string, expectedNonce: string, timeoutMs = 5000): Promise<boolean> { + if (!expectedNonce) return false; + const ac = new AbortController(); + const timer = setTimeout(() => ac.abort(), timeoutMs); + try { + const r = await fetch(origin + PREVIEW_PING_PATH, { + cache: "no-store", + credentials: "omit", + referrerPolicy: "no-referrer", + signal: ac.signal, + }); + if (!r.ok) return false; + const text = await r.text(); + return text === expectedNonce; + } catch { + return false; + } finally { + clearTimeout(timer); + } +} + +type PreviewOpenResult = { + proxyOrigin: string; + proxyHref: string; + url: string; + nonce: string; + canaryOrigin: string; + canaryNonce: string; + host?: PreviewHost; +}; + +/** + * Prove loopback resolution (keyless canary) then that the keyed host is our listener (nonce echo). + * On any failure the caller must preview.release so a leaked key dies with the listener. + */ +export async function confirmPreviewReachable(r: PreviewOpenResult, timeoutMs = 5000): Promise<boolean> { + // Canary first: the keyed name is never looked up if *.localhost goes to hostile DNS + if (!(await canReachProxy(r.canaryOrigin, r.canaryNonce, timeoutMs))) return false; + return canReachProxy(r.proxyOrigin, r.nonce, timeoutMs); +} + +export const usePreview = create<PreviewStore>((set, get) => ({ + byThread: {}, + navigate: async (call, key, threadId, raw, opts) => { + const c = checkPreviewUrl(raw); + if (!c.ok) return false; + const t = c.target; + const prev = get().byThread[key]; + const sameProxy = prev && prev.origin === t.origin && prev.proxyOrigin; + let stack = prev?.stack ?? []; + let idx = prev?.idx ?? -1; + if (opts?.push !== false) { + if (stack[idx] !== t.href) { + stack = [...stack.slice(0, idx + 1), t.href].slice(-50); + idx = stack.length - 1; + } + } else if (!stack.length) { + stack = [t.href]; + idx = 0; + } + if (sameProxy) { + set((s) => ({ byThread: { ...s.byThread, [key]: { ...prev!, url: t.href, proxyHref: prev!.proxyOrigin + t.path, error: null, nonce: prev!.nonce + 1, stack, idx } } })); + // remember it on the conversation + if (threadId) void call("threads.update", { id: threadId, previewUrl: t.href }).catch(() => {}); + return true; + } + set((s) => ({ + byThread: { + ...s.byThread, + [key]: { + url: t.href, origin: t.origin, proxyOrigin: null, proxyHref: null, title: prev?.origin === t.origin ? prev.title : "", + loading: true, error: null, nonce: (prev?.nonce ?? 0) + 1, bridged: false, stack, idx, + }, + }, + })); + const flightKey = `${key}\n${t.href}`; + let p = inflight.get(flightKey); + if (!p) { + p = (async () => { + try { + const r = (await call("preview.open", { url: t.href, ...(threadId ? { threadId } : {}) })) as PreviewOpenResult; + // Fail closed before any *.localhost name is looked up on an engine that sends it to network DNS (#582): the + // key only travelled over the authenticated WS, and the listener is released right away + if (isUnsafeLocalhostResolver(r?.host)) { + void call("preview.release", { url: t.origin }).catch(() => {}); + throw new Error(t_noLocalhost()); + } + if (!(await confirmPreviewReachable(r))) { + void call("preview.release", { url: t.origin }).catch(() => {}); + throw new Error(t_noLocalhost()); + } + set((s) => { + const cur = s.byThread[key]; + if (!cur || cur.url !== t.href) return s; + return { byThread: { ...s.byThread, [key]: { ...cur, proxyOrigin: r.proxyOrigin, proxyHref: r.proxyHref, loading: false, error: null } } }; + }); + return true; + } catch (e) { + const msg = String((e as Error)?.message ?? e); + set((s) => { + const cur = s.byThread[key]; + if (!cur || cur.url !== t.href) return s; + return { byThread: { ...s.byThread, [key]: { ...cur, loading: false, error: msg } } }; + }); + return false; + } finally { + inflight.delete(flightKey); + } + })(); + inflight.set(flightKey, p); + } + return p; + }, + reported: (key, url, title) => { + set((s) => { + const cur = s.byThread[key]; + if (!cur) return s; + let { stack, idx } = cur; + if (stack[idx] !== url) { + // in-page navigation: keep our fallback stack in step + if (stack[idx - 1] === url) idx -= 1; + else if (stack[idx + 1] === url) idx += 1; + else { stack = [...stack.slice(0, idx + 1), url].slice(-50); idx = stack.length - 1; } + } + return { byThread: { ...s.byThread, [key]: { ...cur, url, title, bridged: true, stack, idx } } }; + }); + }, + detach: (key) => { + set((s) => { + const cur = s.byThread[key]; + if (!cur) return s; + return { byThread: { ...s.byThread, [key]: { ...cur, proxyOrigin: null, proxyHref: null, bridged: false } } }; + }); + }, + reload: (key) => { + set((s) => { + const cur = s.byThread[key]; + if (!cur) return s; + return { byThread: { ...s.byThread, [key]: { ...cur, nonce: cur.nonce + 1, error: null } } }; + }); + }, + step: (key, delta) => { + const cur = get().byThread[key]; + if (!cur) return null; + const idx = cur.idx + delta; + if (idx < 0 || idx >= cur.stack.length) return null; + set((s) => ({ byThread: { ...s.byThread, [key]: { ...cur, idx } } })); + return cur.stack[idx]!; + }, +})); + +/** Address-bar text for a target URL (default ports hidden, like a browser) */ +export function addressText(url: string): string { + const c = checkPreviewUrl(url); + if (!c.ok) return url; + return displayOrigin(c.target.origin) + c.target.path; +} diff --git a/packages/agent-console/web/src/stores/ui.ts b/packages/agent-console/web/src/stores/ui.ts index a1af934..c0dbdee 100644 --- a/packages/agent-console/web/src/stores/ui.ts +++ b/packages/agent-console/web/src/stores/ui.ts @@ -4,10 +4,12 @@ import { create } from "zustand"; import type { WsClient } from "../api/ws.js"; import { clampLayoutWidths, maxPanelWidth, maxSidebarWidth } from "../layout/bounds.js"; -export type PanelTab = "changes" | "files" | "terminal"; +export type PanelTab = "changes" | "files" | "terminal" | "preview"; +export const PANEL_TABS: PanelTab[] = ["changes", "files", "terminal", "preview"]; export type UiSettings = { sidebarWidth?: number; + sidebarHidden?: boolean; panel?: { open?: boolean; tab?: PanelTab; width?: number }; collapsedProjects?: string[]; lastProjectId?: string | null; @@ -35,6 +37,8 @@ type UiStore = { closePanel(): void; setPanelTab(tab: PanelTab): void; toggleSidebarHidden(): void; + /** The sidebar toggle button / Ctrl+B: the drawer on narrow windows, else collapse the column (persisted) */ + toggleSidebar(): void; setSbOpen(open: boolean): void; toggleCollapsed(projectId: string): void; select(projectId: string | null, threadId: string | null): void; @@ -71,13 +75,14 @@ export const useUi = create<UiStore>((set, get) => ({ sidebarWidth: s.sidebarWidth ?? 248, panelWidth: s.panel?.width ?? 440, panelOpen: s.panel?.open ?? false, - sbHidden: false, + sbHidden: s.sidebarHidden === true, }; const sized = clampLayoutWidths(draft); set({ sidebarWidth: sized.sidebarWidth, + sbHidden: draft.sbHidden, panelOpen: draft.panelOpen, - panelTab: s.panel?.tab ?? "changes", + panelTab: PANEL_TABS.includes(s.panel?.tab as PanelTab) ? (s.panel!.tab as PanelTab) : "changes", panelWidth: sized.panelWidth, collapsed, currentProjectId: s.lastProjectId ?? null, @@ -113,7 +118,15 @@ export const useUi = create<UiStore>((set, get) => ({ set({ panelTab: tab }); persist(get, { panel: { open: get().panelOpen, tab, width: get().panelWidth } }); }, - toggleSidebarHidden: () => set((s) => ({ sbHidden: !s.sbHidden })), + toggleSidebarHidden: () => { + const next = !get().sbHidden; + set({ sbHidden: next }); + persist(get, { sidebarHidden: next }); + }, + toggleSidebar: () => { + if (typeof window !== "undefined" && window.matchMedia?.("(max-width: 759px)").matches) get().setSbOpen(!get().sbOpen); + else get().toggleSidebarHidden(); + }, setSbOpen: (open) => set({ sbOpen: open }), toggleCollapsed: (projectId) => { const collapsed = { ...get().collapsed }; diff --git a/packages/agent-console/web/src/styles/chat.css b/packages/agent-console/web/src/styles/chat.css index 6fe4c88..6868a32 100644 --- a/packages/agent-console/web/src/styles/chat.css +++ b/packages/agent-console/web/src/styles/chat.css @@ -5,36 +5,42 @@ .um { position: relative; max-width: 78%; background: var(--accent-soft); border-radius: 14px 14px 4px 14px; color: var(--fg); - padding: 6px 12px; font-size: var(--fs-l); line-height: 1.6; + padding: 6px 12px; font-size: var(--chat-fs); line-height: 1.6; white-space: pre-wrap; word-break: normal; overflow-wrap: break-word; } .um:hover .um-act { display: flex; } .um-act { position: absolute; left: -62px; top: 4px; display: none; gap: 2px; } .um-act .ibtn { width: 24px; height: 24px; } .um-img { display: block; max-width: 200px; max-height: 140px; border-radius: var(--r-s); margin-bottom: 6px; cursor: zoom-in; } -.um-tag { font-size: var(--fs-s); color: var(--muted); margin-top: 2px; } +.um-tag { font-size: var(--chat-fs-s); color: var(--muted); margin-top: 2px; } /* Streaming cursor for the body */ .as { margin: 4px 0; } .md.streaming::after { content: "▍"; color: var(--accent); animation: breathe 1s infinite; } /* Markdown */ -.md { font-size: var(--fs-l); line-height: 1.75; color: var(--text); word-break: normal; overflow-wrap: break-word; } -.md p { margin: 0 0 8px; } +.md { font-size: var(--chat-fs); line-height: var(--chat-lh); color: var(--text); word-break: normal; overflow-wrap: break-word; } +.md p { margin: 0 0 0.6em; } .md > :last-child { margin-bottom: 0; } .md a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; text-decoration-color: color-mix(in oklab, var(--accent) 40%, transparent); } .md a:hover { text-decoration: underline; } .md pre { position: relative; background: var(--code-bg); border: 1px solid var(--code-line); border-radius: var(--r-m); - padding: 10px 12px; overflow-x: auto; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.55; + padding: 10px 12px; overflow-x: auto; font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.55; } -.md code { font-family: var(--font-mono); font-size: 12.5px; background: var(--code-bg); color: var(--code-fg); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--code-line); } -.md pre code { background: none; padding: 0; border: 0; color: inherit; } -.md ul, .md ol { margin: 6px 0; padding-left: 22px; } -.md h1, .md h2, .md h3, .md h4 { margin: 12px 0 6px; font-size: var(--fs-l); font-weight: 600; } +.md code { font-family: var(--font-mono); font-size: var(--chat-code-fs); background: var(--code-bg); color: var(--code-fg); padding: 1px 5px; border-radius: 4px; border: 1px solid var(--code-line); } +.md pre code { background: none; padding: 0; border: 0; color: inherit; font-size: inherit; } +.md ul, .md ol { margin: 0.45em 0; padding-left: 1.7em; } +.md li + li { margin-top: 0.15em; } +.md h1, .md h2, .md h3, .md h4 { margin: 0.95em 0 0.4em; font-weight: 600; line-height: 1.4; } +.md h1 { font-size: calc(var(--chat-fs) + 4px); } +.md h2 { font-size: calc(var(--chat-fs) + 2px); } +.md h3 { font-size: calc(var(--chat-fs) + 1px); } +.md h4 { font-size: var(--chat-fs); } +.md > h1:first-child, .md > h2:first-child, .md > h3:first-child, .md > h4:first-child { margin-top: 0.2em; } .md blockquote { margin: 6px 0; padding-left: 12px; border-left: 3px solid var(--line); color: var(--muted); } .md table { border-collapse: collapse; margin: 8px 0; } -.md th, .md td { border: 1px solid var(--line); padding: 4px 10px; font-size: var(--fs-s); } +.md th, .md td { border: 1px solid var(--line); padding: 4px 10px; font-size: var(--chat-fs-s); } .cb-copy { position: absolute; top: 6px; right: 6px; font-size: var(--fs-s); color: var(--muted); padding: 2px 8px; border-radius: var(--r-s); background: var(--bg); opacity: 0; transition: opacity var(--dur-1); @@ -46,13 +52,13 @@ .rs-item { margin: 4px 0 6px; } .rs-head { display: inline-flex; align-items: center; gap: 4px; height: 22px; padding: 0; - color: var(--meta); font-size: var(--fs-s); + color: var(--meta); font-size: var(--chat-fs-s); } .rs-head:hover { color: var(--fg); } .rs-head .caret { display: inline-block; transition: transform var(--dur-1); } .rs-head .caret.open { transform: rotate(90deg); } -.rs-body { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); color: var(--muted); font-size: var(--fs-s); line-height: 1.65; white-space: pre-wrap; } -.todo-list { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); list-style: none; font-size: var(--fs-s); } +.rs-body { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); color: var(--muted); font-size: var(--chat-fs-s); line-height: 1.65; white-space: pre-wrap; } +.todo-list { margin: 2px 0 6px 5px; padding-left: 12px; border-left: 1px solid var(--line); list-style: none; font-size: var(--chat-fs-s); } .todo { color: var(--muted); } .todo.in_progress { color: var(--fg); } @@ -60,7 +66,7 @@ .tg { margin: 4px 0 10px; } .tg-head { display: flex; align-items: center; gap: 6px; width: 100%; height: 24px; padding: 0; - color: var(--meta); font-size: var(--fs-s); text-align: left; + color: var(--meta); font-size: var(--chat-fs-s); text-align: left; } .tg-head:hover { color: var(--fg); } .tg-head .caret { transition: transform var(--dur-1); } @@ -69,7 +75,7 @@ .tg-list { margin: 2px 0 0 5px; border-left: 1px solid var(--line); padding-left: 6px; } .ts-head { display: flex; align-items: center; gap: 8px; width: 100%; height: 26px; padding: 0 6px; - border-radius: var(--r-s); font-size: 12.5px; text-align: left; color: var(--text); + border-radius: var(--r-s); font-size: calc(var(--chat-fs) - 0.5px); text-align: left; color: var(--text); } .ts-head:hover { background: var(--surface-hover); } .ts-ic { width: 14px; flex: none; text-align: center; } @@ -82,15 +88,15 @@ .ts-out { margin: 2px 8px 6px 30px; } .ts-out pre { background: var(--code-bg); border-radius: var(--r-s); padding: 8px 10px; - font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.5; + font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.5; overflow-x: auto; white-space: pre-wrap; word-break: break-all; margin: 0; } -.ts-more { font-size: var(--fs-s); color: var(--accent); margin-bottom: 4px; } +.ts-more { font-size: var(--chat-fs-s); color: var(--accent); margin-bottom: 4px; } /* diff (unified view, red/green backgrounds) */ .diff { margin: 2px 6px 6px 22px; border: 1px solid var(--line); border-radius: var(--r-m); overflow: hidden; } -.diff-path { padding: 4px 10px; font-size: var(--fs-s); color: var(--muted); background: var(--surface); border-bottom: 1px solid var(--line); font-family: var(--font-mono); } -.diff-pre { margin: 0; padding: 6px 0; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.5; overflow-x: auto; } +.diff-path { padding: 4px 10px; font-size: var(--chat-code-fs); color: var(--muted); background: var(--surface); border-bottom: 1px solid var(--line); font-family: var(--font-mono); } +.diff-pre { margin: 0; padding: 6px 0; font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.5; overflow-x: auto; } .dh-head { display: block; color: var(--muted); padding: 0 10px; } .dl { display: block; padding: 0 10px; white-space: pre-wrap; word-break: break-all; } .dl.add { background: var(--add-bg); } @@ -104,29 +110,29 @@ .card.ask { border: 1px solid color-mix(in oklab, var(--info) 45%, var(--bg)); } .card.ask.done { border-color: var(--line); opacity: .75; } .err-card { border: 1px solid color-mix(in oklab, var(--danger) 45%, var(--bg)); } -.err-line { color: var(--danger); font-size: var(--fs-m); } -.perm-title { font-size: var(--fs-m); font-weight: 500; } +.err-line { color: var(--danger); font-size: var(--chat-fs); } +.perm-title { font-size: var(--chat-fs); font-weight: 500; } .perm-cmd { margin: 8px 0 0; background: var(--code-bg); border-radius: var(--r-s); padding: 8px 10px; - font-family: var(--font-mono); font-size: var(--fs-s); white-space: pre-wrap; word-break: break-all; + font-family: var(--font-mono); font-size: var(--chat-code-fs); white-space: pre-wrap; word-break: break-all; } -.perm-path { margin-top: 6px; font-family: var(--font-mono); font-size: var(--fs-s); color: var(--muted); } +.perm-path { margin-top: 6px; font-family: var(--font-mono); font-size: var(--chat-code-fs); color: var(--muted); } .perm-btns { display: flex; gap: 8px; margin-top: 10px; } -.perm-done { margin-top: 8px; font-size: var(--fs-s); color: var(--muted); } +.perm-done { margin-top: 8px; font-size: var(--chat-fs-s); color: var(--muted); } .ask-q { margin-bottom: 10px; } -.ask-t { font-size: var(--fs-m); font-weight: 500; margin-bottom: 6px; } +.ask-t { font-size: var(--chat-fs); font-weight: 500; margin-bottom: 6px; } .ask-opts { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 6px; } .ask-free { margin-top: 4px; } .ask .btn.primary { margin-top: 4px; } /* Notices */ -.nt { margin: 8px 0; text-align: center; font-size: var(--fs-s); color: var(--muted); } +.nt { margin: 8px 0; text-align: center; font-size: var(--chat-fs-s); color: var(--muted); } .nt.warn { color: var(--warn); } .nt.error { color: var(--danger); } /* Turn end: small right-aligned text */ /* Turn end: "3s · copy · retry" left-aligned under the reply */ -.te { display: flex; justify-content: flex-start; align-items: center; gap: 2px; margin: 4px 0 18px -6px; font-size: var(--fs-s); color: var(--meta); } +.te { display: flex; justify-content: flex-start; align-items: center; gap: 2px; margin: 4px 0 18px -6px; font-size: var(--chat-fs-s); color: var(--meta); } .te-meta { padding: 0 6px; font-variant-numeric: tabular-nums; } .te-act { height: 24px; min-width: 24px; display: inline-flex; align-items: center; justify-content: center; gap: 4px; @@ -155,3 +161,19 @@ } .q-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .q-item .ibtn { width: 20px; height: 20px; } + +/* 1.2: local addresses in chat open in the Preview tab (same look as other links, monochrome) */ +a.ac-local { cursor: pointer; } +.ts-out pre a.ac-local, .md pre a.ac-local { color: inherit; text-decoration: underline; text-decoration-color: color-mix(in oklab, currentColor 45%, transparent); text-underline-offset: 2px; } +.md code a.ac-local { color: inherit; } + +/* Path chips (Files panel → composer), also in the sent bubble */ +.mention { + display: inline-flex; align-items: center; gap: 4px; max-width: 260px; height: 22px; padding: 0 6px; + border-radius: var(--r-s); background: var(--chip-bg); border: 1px solid var(--chip-line); color: var(--pill-fg); + font-size: var(--fs-s); font-family: var(--font-mono); white-space: nowrap; vertical-align: middle; +} +.mention svg { flex: none; } +.mention-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.um-mentions { display: flex; flex-wrap: wrap; gap: 4px; margin: 2px 0 4px; white-space: normal; } +.um .mention { background: color-mix(in oklab, var(--fg) 5%, var(--accent-soft)); } diff --git a/packages/agent-console/web/src/styles/composer.css b/packages/agent-console/web/src/styles/composer.css index 24402ff..3083f6f 100644 --- a/packages/agent-console/web/src/styles/composer.css +++ b/packages/agent-console/web/src/styles/composer.css @@ -37,7 +37,7 @@ .cp-ta { width: 100%; border: 0; resize: none; background: none; outline: none; color: var(--text); - font-size: var(--fs-l); line-height: 22px; min-height: 34px; max-height: calc(22px * 12); overflow-y: auto; + font-size: var(--chat-fs); line-height: calc(var(--chat-fs) * 1.62); min-height: 34px; max-height: calc(var(--chat-fs) * 1.62 * 12); overflow-y: auto; display: block; padding: 0; } .cp-ta::placeholder { color: var(--meta); } @@ -204,3 +204,8 @@ @media (max-width: 560px) { .composer { padding: 0 10px 10px; } } + +/* 1.2: drop target while a Files-panel row is dragged over the composer */ +.cp-card.drop-on { outline: 1.5px dashed var(--cp-focus); outline-offset: 2px; } +.cp-drop-hint { padding: 4px 10px 0; font-size: var(--fs-s); color: var(--muted); } +.att-bar .mention { height: 24px; } diff --git a/packages/agent-console/web/src/styles/layout.css b/packages/agent-console/web/src/styles/layout.css index dc22e26..04fb063 100644 --- a/packages/agent-console/web/src/styles/layout.css +++ b/packages/agent-console/web/src/styles/layout.css @@ -105,6 +105,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; } padding: 0 10px; border-bottom: 1px solid var(--line); } .tb-menu-btn { display: none; } +.tb-menu-btn.tb-sb-collapsed { display: inline-flex; margin-right: 2px; } .tb-crumb { flex: none; max-width: 26%; font-size: var(--fs-m); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .tb-sep { flex: none; color: var(--muted); } .tb-title { @@ -134,7 +135,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; } /* Timeline: content max width 760, centered */ .scroll { flex: 1; overflow-y: auto; overscroll-behavior: contain; position: relative; } -/* Conversation and composer share one 720px column */ +/* Conversation and composer share one column: --col, 720px by default (Settings → Content width: 640 / 720 / 880 / full) */ .tl-wrap { max-width: calc(var(--col) + 40px); min-width: 0; margin: 0 auto; padding: 24px 20px 16px; } /* ↓ jump-to-bottom button */ @@ -144,6 +145,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; } display: flex; align-items: center; justify-content: center; color: var(--muted); z-index: 5; } .jump:hover { color: var(--fg); } +.jump svg { transform: rotate(90deg); } .jump .jd { position: absolute; top: 4px; right: 4px; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); } /* ---- right panel ---- */ @@ -218,7 +220,7 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; } .ft-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .ft-err { color: var(--danger); font-size: var(--fs-s); padding: 2px 0; } .ft-view { flex: 1; min-height: 0; overflow: auto; border-top: 1px solid var(--line); } -.ft-pre { margin: 0; padding: 10px 12px; font-family: var(--font-mono); font-size: var(--fs-s); line-height: 1.55; } +.ft-pre { margin: 0; padding: 10px 12px; font-family: var(--font-mono); font-size: var(--chat-code-fs); line-height: 1.55; } .ft-pre code { background: none; padding: 0; display: block; white-space: pre; } /* Terminal panel */ @@ -263,9 +265,17 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; } /* Wide screens: Ctrl+B hides the whole column / Ctrl+J hides the panel */ @media (min-width: 760px) { - .sidebar.w-hide { display: none; } + /* collapse slides the column out (quick, and none with reduced motion); hidden afterwards so it can't take focus */ + .sidebar { transition: margin-left var(--dur-2) var(--ease), visibility 0s linear 0s; } + .sidebar.w-hide { + margin-left: calc(-1 * var(--sb-w, 248px)); visibility: hidden; + transition: margin-left var(--dur-2) var(--ease), visibility 0s linear var(--dur-2); + } .sidebar.w-hide + .rs-l { display: none; } } +@media (prefers-reduced-motion: reduce) { .sidebar, .sidebar.w-hide { transition: none; } } +.sb-row .sb-toggle { flex: none; color: var(--muted); } +.sb-toggle:hover { color: var(--fg); } @media (min-width: 900px) { .panel.w-hide { display: none; } } @@ -311,3 +321,30 @@ body.col-drag iframe, body.col-drag .xterm { pointer-events: none; } .cpal-item.on { background: var(--surface-hover); } .cpal-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .cpal-hint { flex: none; font-size: var(--fs-s); color: var(--muted); } + +/* ---- 1.2 Preview tab ---- */ +.pv { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.pv-bar { flex: none; display: flex; align-items: center; gap: 2px; height: 38px; padding: 0 6px; border-bottom: 1px solid var(--line); } +.pv-bar .ibtn { width: 26px; height: 26px; flex: none; color: var(--muted); } +.pv-bar .ibtn:hover:not(:disabled) { color: var(--fg); } +.pv-bar .ibtn:disabled { opacity: .35; cursor: default; } +.pv-addr { + flex: 1; min-width: 0; height: 26px; padding: 0 8px; margin: 0 2px; border-radius: var(--r-s); + background: var(--search-bg); border: 1px solid transparent; color: var(--fg); + font-family: var(--font-mono); font-size: var(--fs-s); outline: none; +} +.pv-addr:focus { border-color: var(--cp-focus); background: var(--bg); } +.pv-addr.err { border-color: color-mix(in oklab, var(--danger) 60%, var(--bg)); } +.pv-note { flex: none; display: flex; align-items: center; gap: 8px; padding: 6px 10px; font-size: var(--fs-s); color: var(--muted); border-bottom: 1px solid var(--line); } +.pv-note.err { color: var(--danger); } +.pv-note .btn { height: 24px; font-size: var(--fs-s); } +.pv-frame-wrap { flex: 1; min-height: 0; position: relative; background: var(--bg); } +.pv-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #fff; } +.pv-loading { position: absolute; top: 0; left: 0; right: 0; height: 2px; background: var(--accent-2); opacity: .5; animation: breathe 1s infinite; } +.pv-empty { padding: 28px 22px; color: var(--muted); font-size: var(--fs-m); text-align: center; line-height: 1.7; } +.pv-empty code { font-family: var(--font-mono); font-size: var(--fs-s); background: var(--code-bg); border: 1px solid var(--code-line); border-radius: 4px; padding: 0 4px; color: var(--code-fg); } +.pv-hint { margin-top: 10px; font-size: var(--fs-s); color: var(--meta); } + +/* Files panel rows can be dragged into the composer */ +.ft-row[draggable="true"] { cursor: default; } +.ft-row.dragging { opacity: .5; } diff --git a/packages/agent-console/web/src/styles/tokens.css b/packages/agent-console/web/src/styles/tokens.css index 26affa4..2f1c2f5 100644 --- a/packages/agent-console/web/src/styles/tokens.css +++ b/packages/agent-console/web/src/styles/tokens.css @@ -38,6 +38,12 @@ --fs-hero: 18px; --lh: 1.6; --col: 720px; + /* Chat text size (Settings → Chat font size, 12–18, default 13): timeline, composer, tool output, diffs. + Code is 1px smaller, secondary rows (tool steps, thinking, notices) 1px smaller but never under 12px. */ + --chat-fs: 13px; + --chat-fs-s: max(12px, calc(var(--chat-fs) - 1px)); + --chat-code-fs: max(11.5px, calc(var(--chat-fs) - 1px)); + --chat-lh: 1.7; --row: 26px; --shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .16), 0 0 0 1px var(--line); --term-bg: #ffffff; diff --git a/packages/agent-console/web/src/timeline/reducer.ts b/packages/agent-console/web/src/timeline/reducer.ts index 0b15b30..d62f056 100644 --- a/packages/agent-console/web/src/timeline/reducer.ts +++ b/packages/agent-console/web/src/timeline/reducer.ts @@ -12,7 +12,7 @@ export type ToolStep = { }; export type DisplayItem = - | { kind: "user"; key: string; text: string; attachments?: { id: string; name: string; mime: string }[]; steered?: boolean; ts: number } + | { kind: "user"; key: string; text: string; attachments?: { id: string; name: string; mime: string }[]; mentions?: { path: string; isDir: boolean }[]; steered?: boolean; ts: number } | { kind: "assistant"; key: string; itemId: string; text: string; streaming: boolean } | { kind: "reasoning"; key: string; itemId: string; text: string; streaming: boolean } | { kind: "toolgroup"; key: string; steps: ToolStep[] } @@ -164,7 +164,7 @@ export function applyEvent(st: State, ev: TimelineEvent): void { case "user_message": breakGroup(st); st.lastUserIdx.set(ev.turnId ?? "", st.items.length); - st.items.push({ kind: "user", key: `u:${ev.seq}`, text: ev.text, attachments: ev.attachments, steered: ev.steered, ts: ev.ts }); + st.items.push({ kind: "user", key: `u:${ev.seq}`, text: ev.text, attachments: ev.attachments, ...(ev.mentions?.length ? { mentions: ev.mentions } : {}), steered: ev.steered, ts: ev.ts }); return; case "assistant_delta": applyDelta(st, ev.itemId, "assistant", ev.text); diff --git a/packages/agent-console/web/src/timeline/types.ts b/packages/agent-console/web/src/timeline/types.ts index 90f02eb..591096f 100644 --- a/packages/agent-console/web/src/timeline/types.ts +++ b/packages/agent-console/web/src/timeline/types.ts @@ -9,7 +9,7 @@ export type AttachmentRef = { id: string; name: string; mime: string }; export type PermissionOption = { id: string; label: string; kind: "allow_once" | "allow_always" | "reject_once" }; export type TimelineEvent = - | { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean } + | { seq: number; ts: number; threadId: string; turnId?: string; type: "user_message"; text: string; attachments?: AttachmentRef[]; steered?: boolean; mentions?: { path: string; isDir: boolean }[] } | { seq: number; ts: number; threadId: string; turnId: string; type: "turn_started"; model: string | null; mode: string; effort: string | null } | { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_delta" | "reasoning_delta" | "tool_output_delta"; itemId: string; text: string } | { seq: number; ts: number; threadId: string; turnId?: string; type: "assistant_message" | "reasoning"; itemId: string; text: string } diff --git a/packages/agent-console/web/src/types/models.ts b/packages/agent-console/web/src/types/models.ts index 90180a2..58d7e7c 100644 --- a/packages/agent-console/web/src/types/models.ts +++ b/packages/agent-console/web/src/types/models.ts @@ -16,6 +16,8 @@ export type ThreadMeta = { seq: number; cursorFast?: boolean; cursorAutoReview?: boolean; + /** 1.2: last Preview tab URL (target, not proxy) */ + previewUrl?: string | null; }; export type Capabilities = { diff --git a/packages/agent-console/web/src/util/localLinks.ts b/packages/agent-console/web/src/util/localLinks.ts new file mode 100644 index 0000000..9505dcf --- /dev/null +++ b/packages/agent-console/web/src/util/localLinks.ts @@ -0,0 +1,133 @@ +// Local addresses in chat text (1.2): localhost:3000, http://127.0.0.1:5173/x, 0.0.0.0:8080, [::1]:4000, app.localhost:3000. +// Pure functions (unit tested) plus a DOM pass for rendered Markdown. A bare host needs a port to count +// ("runs on localhost" stays text); trailing punctuation (English and Chinese) is left out; LAN addresses (192.168.x, 10.x) +// are not local and stay ordinary external links. +import { checkPreviewUrl } from "../../../daemon/src/preview/url.js"; + +export type LocalLink = { start: number; end: number; text: string; url: string }; + +const HOST = String.raw`(?:localhost|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1?\])`; +const RE = new RegExp(String.raw`(https?:\/\/)?${HOST}(:\d{1,5})?((?:[/?#][^\s<>"'\`)】」』,。;!?、]*)?)`, "gi"); +const TRAIL = /[.,;:!?。,;:!?…'"’”]+$/; + +export function findLocalLinks(text: string): LocalLink[] { + const out: LocalLink[] = []; + if (!text) return out; + RE.lastIndex = 0; + let m: RegExpExecArray | null; + while ((m = RE.exec(text))) { + let start = m.index; + let raw = m[0]; + const scheme = m[1]; + const port = m[2]; + // Must not be part of a longer word / host / path (xlocalhost:1, foo/localhost:1, user@localhost:1) + const before = start > 0 ? text[start - 1]! : ""; + if (before && /[\w.@/\\:-]/.test(before)) continue; + if (!scheme && !port) continue; + // Drop trailing punctuation, and a closing bracket that has no opening one inside the match + let trimmed = raw.replace(TRAIL, ""); + while (/[)\]]$/.test(trimmed)) { + const close = trimmed.endsWith(")") ? ")" : "]"; + const open = close === ")" ? "(" : "["; + const opens = trimmed.split(open).length - 1; + const closes = trimmed.split(close).length - 1; + if (closes > opens) trimmed = trimmed.slice(0, -1).replace(TRAIL, ""); + else break; + } + raw = trimmed; + const c = checkPreviewUrl(raw); + if (!c.ok) continue; + out.push({ start, end: start + raw.length, text: raw, url: c.target.href }); + RE.lastIndex = start + Math.max(1, raw.length); + } + return out; +} + +/** Text → alternating plain strings and links (for React rendering without innerHTML) */ +export function splitLocalLinks(text: string): (string | LocalLink)[] { + const links = findLocalLinks(text); + if (!links.length) return [text]; + const parts: (string | LocalLink)[] = []; + let at = 0; + for (const l of links) { + if (l.start > at) parts.push(text.slice(at, l.start)); + parts.push(l); + at = l.end; + } + if (at < text.length) parts.push(text.slice(at)); + return parts; +} + +/** Is this href a local address the preview can open? → its normalized URL */ +export function localHref(href: string | null | undefined): string | null { + if (!href || !/^https?:\/\//i.test(href)) return null; + const c = checkPreviewUrl(href); + return c.ok ? c.target.href : null; +} + +const SKIP = new Set(["A", "BUTTON", "SCRIPT", "STYLE", "TEXTAREA"]); + +function textNodesUnder(root: Node): Text[] { + const out: Text[] = []; + const walk = (n: Node) => { + if (n.nodeType === 3) { out.push(n as Text); return; } + if (n.nodeType !== 1) return; + if (SKIP.has((n as Element).tagName)) return; + for (let c = n.firstChild; c; c = c.nextSibling) walk(c); + }; + walk(root); + return out; +} + +function wrapLinks(root: Node, nodes: Text[]): void { + const full = nodes.map((n) => n.data).join(""); + const links = findLocalLinks(full); + if (!links.length) return; + // offsets → (node, offset) + const starts: number[] = []; + let acc = 0; + for (const n of nodes) { starts.push(acc); acc += n.data.length; } + const locate = (pos: number, end: boolean): [Text, number] => { + for (let i = nodes.length - 1; i >= 0; i--) { + const s = starts[i]!; + if (end ? pos > s : pos >= s) return [nodes[i]!, pos - s]; + } + return [nodes[0]!, 0]; + }; + const doc = root.ownerDocument ?? document; + // Back to front so earlier offsets stay valid + for (const l of [...links].reverse()) { + const [sn, so] = locate(l.start, false); + const [en, eo] = locate(l.end, true); + const range = doc.createRange(); + range.setStart(sn, so); + range.setEnd(en, eo); + const a = doc.createElement("a"); + a.href = l.url; + a.dataset.acLocal = l.url; + a.className = "ac-local"; + a.appendChild(range.extractContents()); + range.insertNode(a); + } +} + +/** Rendered Markdown: mark local <a href> links, and turn bare local addresses into links (code blocks too, across hljs spans) */ +export function linkifyLocal(root: HTMLElement, title?: string): void { + for (const a of Array.from(root.querySelectorAll("a[href]"))) { + const u = localHref(a.getAttribute("href")); + if (u) { (a as HTMLElement).dataset.acLocal = u; a.classList.add("ac-local"); } + } + // Code blocks: one pass over the whole block (a URL may be split across highlight spans) + for (const pre of Array.from(root.querySelectorAll("pre"))) { + if ((pre as HTMLElement).dataset.acLinked) continue; + (pre as HTMLElement).dataset.acLinked = "1"; + wrapLinks(pre, textNodesUnder(pre)); + } + // Everything else: per text node + for (const n of textNodesUnder(root)) { + if (n.parentElement?.closest("pre")) continue; + if (!n.parentNode) continue; + wrapLinks(n.parentNode, [n]); + } + if (title) for (const a of Array.from(root.querySelectorAll("a.ac-local"))) (a as HTMLElement).title = title; +}