diff --git a/packages/agent-console/README.md b/packages/agent-console/README.md index a2f31a6..b1cb061 100644 --- a/packages/agent-console/README.md +++ b/packages/agent-console/README.md @@ -1,5 +1,19 @@ # Agent Console +**把终端里的 Agent CLI 搬进 magpie 窗口,直接对话使用。** + +作者 qingnian108,源码在 [qingnian108/magpie-agent-console](https://github.com/qingnian108/magpie-agent-console),欢迎提问题和建议。 + +支持 Claude Code、Codex、Cursor 等,直接用你电脑上已安装的 CLI。左边是项目和对话,中间聊天,右边看改动、文件和终端。 + +**Use your terminal Agent CLIs right inside magpie, by chat.** + +By qingnian108. Source: [qingnian108/magpie-agent-console](https://github.com/qingnian108/magpie-agent-console). Issues welcome. + +Works with Claude Code, Codex, Cursor and more, using the CLIs you already have. + +--- + A Magpie page plugin that drives real local Agent CLIs (Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh). Each conversation is a **persistent Agent session** on a standalone Node daemon. Close or refresh the page — the Agent keeps running while Magpie is open. Reopen the page and you pick up where you left off. When Magpie quits, the daemon and its Agents stop; threads are persisted and can be resumed next time. ## Install @@ -68,12 +82,14 @@ The daemon can run Agents with full access to your machine, so the token that un - **Host is checked on every request and WebSocket upgrade** (gate and daemon): it must be `127.0.0.1:` or `localhost:` with the actually bound port, otherwise 421. This blocks DNS rebinding, where the attacker's requests carry no `Origin` at all. - The gate answers only `GET /open?k=` (the daemon token is not accepted there), refuses any request that carries an `Origin` header, and sends `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`. - 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. ## Lifecycle - Importing `index.mjs` has no side effects (no port, no process, no files). - `server()` (called by Magpie's plugin host at host start-up — this includes short-lived hosts started by CLI commands such as `magpie plugin add` or `magpie plugin list`) binds the gate and writes `page/session.js`. If the port is busy it retries every 2 s in the background without blocking the host; a detached 0.1.0 daemon still holding the port is shut down once, only after it proves its identity by answering `/api/ping` with the token from `daemon.json`. - The daemon starts when the page is opened for the first time and is reused for later opens. It is a normal (non-detached) child of the plugin host. +- `server()` waits ~1.2 s before binding the gate (`AGENT_CONSOLE_BIND_DELAY_MS`), so the short-lived hosts started by `magpie` CLI commands usually exit before they take the gate or write `session.js`; a gate port held by the long-lived host is logged only if it stays busy for ~10 s. - The daemon exits when its stdin pipe closes or its parent pid disappears (checked every 2 s) — i.e. when Magpie quits or the plugin host restarts — and after 60 minutes idle. - Magpie's plugin host treats the value returned by `server()` as OpenCode hooks and never calls `stop()`; it exits the Bun process when Magpie closes its stdin. A synchronous `exit` handler therefore closes the daemon's lifeline, signals it, and removes the `session.js` this host wrote. `stop()` (used by tests and other hosts) closes the gate, ends the daemon (graceful, then forced) and removes `session.js`. - Agents stop with the daemon. Threads are persisted and can be resumed after reopening the page. On macOS/Linux every Agent CLI, the Codex app-server and the no-PTY shell run in their own process group, so stopping one ends everything it started; on Windows the same is done with `taskkill /T`. A process `exit` hook reaps any tree still alive when the daemon exits. diff --git a/packages/agent-console/app/app.css b/packages/agent-console/app/app.css index c8dc28f..981b65a 100644 --- a/packages/agent-console/app/app.css +++ b/packages/agent-console/app/app.css @@ -1,4 +1,4 @@ -:root{--bg: var(--magpie-bg, #ffffff);--fg: var(--magpie-fg, #1f1f1f);--muted: var(--magpie-muted, #737373);--accent: var(--magpie-accent, #0d9488);--accent-fg: #ffffff;--accent-soft: color-mix(in oklab, var(--accent) 12%, var(--bg));--surface: color-mix(in oklab, var(--fg) 3%, var(--bg));--surface-hover: color-mix(in oklab, var(--fg) 6%, var(--bg));--line: color-mix(in oklab, var(--fg) 9%, var(--bg));--ok: #16a34a;--warn: #d97706;--danger: #dc2626;--info: #2563eb;--code-bg: color-mix(in oklab, var(--fg) 4%, var(--bg));--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: "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;--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}@media(prefers-color-scheme:dark){:root:not([data-theme=light]){--bg: var(--magpie-bg, #1a1a1a);--fg: var(--magpie-fg, #ececec);--muted: var(--magpie-muted, #9b9b9b);--accent: var(--magpie-accent, #2dd4bf);--accent-fg: #04201c;--info: #60a5fa;--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .5), 0 0 0 1px var(--line);--term-bg: #0c0c0c;--term-fg: #cccccc}}[data-theme=dark]{--bg: var(--magpie-bg, #1a1a1a);--fg: var(--magpie-fg, #ececec);--muted: var(--magpie-muted, #9b9b9b);--accent: var(--magpie-accent, #2dd4bf);--accent-fg: #04201c;--info: #60a5fa;--shadow-pop: 0 8px 24px -6px rgb(0 0 0 / .5), 0 0 0 1px var(--line);--term-bg: #0c0c0c;--term-fg: #cccccc}@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,select{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}select.tinput{padding-right:26px;appearance:none;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}.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);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)}.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(--surface);border-right:1px solid var(--line)}.sb-row{display:flex;align-items:center;gap:2px;height:40px;padding:6px 6px 4px;flex:none}.sb-new{flex:1;display:flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:var(--r-s);font-size:var(--fs-m);text-align:left;transition:background var(--dur-1)}.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(--surface-hover);color:var(--muted)}.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 6px 8px}.pj-group{margin-top:2px}.pj{display:flex;align-items:center;gap:2px;height:30px;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:20px;height:20px;flex:none;border-radius:5px;display:inline-flex;align-items:center;justify-content:center;background:var(--surface-hover);color:var(--fg);font-size:var(--fs-s);font-weight:600;line-height:1;text-transform:uppercase}.pj:hover .pj-badge{background:var(--bg)}.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(--muted)}.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}.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:28px;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,.t-item.on{background:var(--surface-hover)}.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:var(--fs-s);color:var(--muted)}.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{color:var(--accent)}.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:760px;min-width:0;margin:0 auto;padding:16px 20px 12px}.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(--err, #b91c1c)}.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(--err, #b91c1c);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:10px 0}.um{position:relative;max-width:78%;min-width:min(100%,12em);background:var(--accent-soft);border-radius:var(--r-l) var(--r-l) 4px var(--r-l);padding:7px 12px;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:10px 0}.md.streaming:after{content:"\258d";color:var(--accent);animation:breathe 1s infinite}.md{font-size:var(--fs-m);word-break:normal;overflow-wrap:break-word}.md p{margin:6px 0}.md pre{position:relative;background:var(--code-bg);border-radius:var(--r-s);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:.92em;background:var(--code-bg);padding:1px 5px;border-radius:4px}.md pre code{background:none;padding:0}.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:8px 0}.rs-head{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 8px;border-radius:var(--r-s);color:var(--muted);font-size:var(--fs-s)}.rs-head:hover{background:var(--surface-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:4px 0 4px 14px;padding-left:12px;border-left:2px solid var(--line);color:var(--muted);font-size:var(--fs-s);white-space:pre-wrap}.todo-list{margin:4px 0 4px 14px;padding-left:12px;border-left:2px solid var(--line);list-style:none;font-size:var(--fs-s)}.todo{color:var(--muted)}.todo.in_progress{color:var(--fg)}.tg{margin:8px 0}.tg-head{display:flex;align-items:center;gap:6px;width:100%;height:26px;padding:0 8px;border-radius:var(--r-s);color:var(--muted);font-size:var(--fs-s);text-align:left}.tg-head:hover{background:var(--surface-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)}.tg-list{margin:2px 0 4px 14px;border-left:2px solid var(--line);padding-left:4px}.ts-head{display:flex;align-items:center;gap:8px;width:100%;height:26px;padding:0 8px;border-radius:var(--r-s);font-size:var(--fs-s);text-align:left;color:var(--fg)}.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);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(--muted)}.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:4px 8px 8px 30px;border:1px solid var(--line);border-radius:var(--r-s);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:color-mix(in oklab,var(--ok) 14%,transparent)}.dl.del{background:color-mix(in oklab,var(--danger) 12%,transparent)}.card{margin:10px 0;border-radius:var(--r-m);padding:10px 12px}.card.plan{border:1px solid var(--line)}.card.perm{border:1px solid color-mix(in oklab,var(--warn) 45%,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-end;align-items:center;gap:8px;margin:10px 0 4px;font-size:var(--fs-s);color:var(--muted)}.te-files{color:var(--accent);font-size:var(--fs-s)}.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:680px;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 12px}.cp-card{width:100%;max-width:680px;margin:0 auto;background:var(--surface);border-radius:var(--r-l);border:1px solid transparent;padding:8px 10px 6px;transition:border-color var(--dur-2) var(--ease)}.cp-card:focus-within{border-color:color-mix(in oklab,var(--fg) 18%,var(--bg))}.cp-card.waiting{box-shadow:inset 2px 0 0 var(--warn)}.cp-card.danger{box-shadow:inset 2px 0 0 var(--danger)}.cp-danger{max-width:680px;margin:0 auto 6px;display:flex;align-items:center;gap:6px;color:var(--danger);font-size:var(--fs-s);padding:0 2px}.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;font-size:var(--fs-m);line-height:1.55;max-height:17em;overflow-y:auto;display:block}.cp-ta::placeholder{color:var(--muted)}.cp-bar{display:flex;align-items:center;flex-wrap:wrap;gap:4px 6px;margin-top:4px;min-width:0}.pill-wrap{position:relative;flex:0 1 auto;min-width:0;max-width:100%}.pill{display:inline-flex;align-items:center;gap:6px;height:26px;padding:0 10px;border-radius:var(--r-full);background:var(--surface-hover);color:var(--fg);font-size:var(--fs-s);max-width:min(220px,100%);min-width:0}.pill .p-a{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}.pill .p-t{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1 1 auto}.pill.sel{appearance:none;border:0;padding:0 22px 0 10px;cursor:pointer;max-width:min(140px,100%);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;background:var(--surface-hover) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath fill='%23737373' d='M1 1l4 4 4-4'/%3E%3C/svg%3E") no-repeat right 8px center}.pill.sel.danger{color:var(--danger)}.pill.cursor-shield{padding:0 8px;color:var(--muted);border:0;cursor:pointer}.pill.cursor-shield.on{color:var(--ok, #3ecf8e);background:color-mix(in oklab,var(--ok, #3ecf8e) 14%,var(--surface-hover))}.pill.sel.cursor-fast{max-width:min(72px,100%)}.cp-bar>.ibtn{flex:none}.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%)}.pill.sel{max-width:min(104px,100%);font-size:11px;padding-right:20px}}@container composer (max-width: 380px){.pill{max-width:min(120px,100%);padding:0 8px}.pill.sel{max-width:min(80px,100%);padding-left:7px;padding-right:18px}}.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(--muted)}.cp-send,.cp-stop{width:28px;height:28px;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:.3;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;--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} /*! 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 9e9f6e6..30f98b2 100644 --- a/packages/agent-console/app/app.js +++ b/packages/agent-console/app/app.js @@ -1,49 +1,49 @@ -(()=>{var zM=Object.create;var Iu=Object.defineProperty;var PM=Object.getOwnPropertyDescriptor;var UM=Object.getOwnPropertyNames;var HM=Object.getPrototypeOf,FM=Object.prototype.hasOwnProperty;var jb=e=>{throw TypeError(e)};var qM=(e,t,i)=>t in e?Iu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var ce=(e,t,i)=>()=>{if(i)throw i[0];try{return e&&(t=e(e=0)),t}catch(n){throw i=[n],n}};var ge=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}},Vb=(e,t)=>{for(var i in t)Iu(e,i,{get:t[i],enumerable:!0})},KM=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of UM(t))!FM.call(e,s)&&s!==i&&Iu(e,s,{get:()=>t[s],enumerable:!(n=PM(t,s))||n.enumerable});return e};var oe=(e,t,i)=>(i=e!=null?zM(HM(e)):{},KM(t||!e||!e.__esModule?Iu(i,"default",{value:e,enumerable:!0}):i,e));var de=(e,t,i)=>qM(e,typeof t!="symbol"?t+"":t,i),WM=(e,t,i)=>t.has(e)||jb("Cannot "+i);var Xb=(e,t,i)=>t.has(e)?jb("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i);var tp=(e,t,i)=>(WM(e,t,"access private method"),i);var Zb=ce(()=>{});var Qb=ce(()=>{});var Jb=ce(()=>{});var e0=ce(()=>{});var t0=ce(()=>{});var h0=ge(mt=>{"use strict";function rp(e,t){var i=e.length;e.push(t);e:for(;0>>1,s=e[n];if(0>>1;nzu(o,i))lzu(c,o)?(e[n]=c,e[l]=i,n=l):(e[n]=o,e[a]=i,n=a);else if(lzu(c,i))e[n]=c,e[l]=i,n=l;else break e}}return t}function zu(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"?(i0=performance,mt.unstable_now=function(){return i0.now()}):(ip=Date,n0=ip.now(),mt.unstable_now=function(){return ip.now()-n0});var i0,ip,n0,Ms=[],ar=[],GM=1,_n=null,Si=3,ap=!1,Il=!1,zl=!1,op=!1,a0=typeof setTimeout=="function"?setTimeout:null,o0=typeof clearTimeout=="function"?clearTimeout:null,s0=typeof setImmediate<"u"?setImmediate:null;function Pu(e){for(var t=es(ar);t!==null;){if(t.callback===null)Uu(ar);else if(t.startTime<=e)Uu(ar),t.sortIndex=t.expirationTime,rp(Ms,t);else break;t=es(ar)}}function lp(e){if(zl=!1,Pu(e),!Il)if(es(Ms)!==null)Il=!0,ao||(ao=!0,ro());else{var t=es(ar);t!==null&&cp(lp,t.startTime-e)}}var ao=!1,Pl=-1,l0=5,c0=-1;function u0(){return op?!0:!(mt.unstable_now()-c0e&&u0());){var n=_n.callback;if(typeof n=="function"){_n.callback=null,Si=_n.priorityLevel;var s=n(_n.expirationTime<=e);if(e=mt.unstable_now(),typeof s=="function"){_n.callback=s,Pu(e),t=!0;break t}_n===es(Ms)&&Uu(Ms),Pu(e)}else Uu(Ms);_n=es(Ms)}if(_n!==null)t=!0;else{var r=es(ar);r!==null&&cp(lp,r.startTime-e),t=!1}}break e}finally{_n=null,Si=i,ap=!1}t=void 0}}finally{t?ro():ao=!1}}}var ro;typeof s0=="function"?ro=function(){s0(np)}:typeof MessageChannel<"u"?(sp=new MessageChannel,r0=sp.port2,sp.port1.onmessage=np,ro=function(){r0.postMessage(null)}):ro=function(){a0(np,0)};var sp,r0;function cp(e,t){Pl=a0(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,rp(ar,e),es(Ms)===null&&e===es(ar)&&(zl?(o0(Pl),Pl=-1):zl=!0,cp(lp,i-n))):(e.sortIndex=s,rp(Ms,e),Il||ap||(Il=!0,ao||(ao=!0,ro()))),e};mt.unstable_shouldYield=u0;mt.unstable_wrapCallback=function(e){var t=Si;return function(){var i=Si;Si=t;try{return e.apply(this,arguments)}finally{Si=i}}}});var f0=ge((tP,d0)=>{"use strict";d0.exports=h0()});var k0=ge(be=>{"use strict";var dp=Symbol.for("react.transitional.element"),$M=Symbol.for("react.portal"),YM=Symbol.for("react.fragment"),jM=Symbol.for("react.strict_mode"),VM=Symbol.for("react.profiler"),XM=Symbol.for("react.consumer"),ZM=Symbol.for("react.context"),QM=Symbol.for("react.forward_ref"),JM=Symbol.for("react.suspense"),eO=Symbol.for("react.memo"),v0=Symbol.for("react.lazy"),tO=Symbol.for("react.activity"),iO=Symbol.for("react.view_transition"),p0=Symbol.iterator;function nO(e){return e===null||typeof e!="object"?null:(e=p0&&e[p0]||e["@@iterator"],typeof e=="function"?e:null)}var b0={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y0=Object.assign,S0={};function lo(e,t,i){this.props=e,this.context=t,this.refs=S0,this.updater=i||b0}lo.prototype.isReactComponent={};lo.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")};lo.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function w0(){}w0.prototype=lo.prototype;function fp(e,t,i){this.props=e,this.context=t,this.refs=S0,this.updater=i||b0}var pp=fp.prototype=new w0;pp.constructor=fp;y0(pp,lo.prototype);pp.isPureReactComponent=!0;var m0=Array.isArray;function hp(){}var rt={H:null,A:null,T:null,S:null},E0=Object.prototype.hasOwnProperty;function mp(e,t,i){var n=i.ref;return{$$typeof:dp,type:e,key:t,ref:n!==void 0?n:null,props:i}}function sO(e,t){return mp(e.type,t,e.props)}function gp(e){return typeof e=="object"&&e!==null&&e.$$typeof===dp}function rO(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(i){return t[i]})}var g0=/\/+/g;function up(e,t){return typeof e=="object"&&e!==null&&e.key!=null?rO(""+e.key):t.toString(36)}function aO(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(hp,hp):(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 oo(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 dp:case $M:a=!0;break;case v0:return a=e._init,oo(a(e._payload),t,i,n,s)}}if(a)return s=s(e),a=n===""?"."+up(e,0):n,m0(s)?(i="",a!=null&&(i=a.replace(g0,"$&/")+"/"),oo(s,t,i,"",function(c){return c})):s!=null&&(gp(s)&&(s=sO(s,i+(s.key==null||e&&e.key===s.key?"":(""+s.key).replace(g0,"$&/")+"/")+a)),t.push(s)),1;a=0;var o=n===""?".":n+":";if(m0(e))for(var l=0;l{"use strict";T0.exports=k0()});var M0=ge(wi=>{"use strict";var cO=Ot();function A0(e){var t="https://react.dev/errors/"+e;if(1{"use strict";function O0(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(O0)}catch(e){console.error(e)}}O0(),R0.exports=M0()});var vE=ge(wd=>{"use strict";var qt=f0(),_S=Ot(),fO=co();function B(e){var t="https://react.dev/errors/"+e;if(1bo||(e.current=im[bo],im[bo]=null,bo--)}function lt(e,t){bo++,im[bo]=e.current,e.current=t}var us=fs(null),uc=fs(null),yr=fs(null),Nh=fs(null);function Ah(e,t){switch(lt(yr,t),lt(uc,e),lt(us,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Xy(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Xy(t),e=Y1(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}pi(us),lt(us,e)}function Uo(){pi(us),pi(uc),pi(yr)}function nm(e){var t=e.memoizedState;t!==null&&(Vo._currentValue=t.memoizedState,lt(Nh,e)),t=us.current;var i=Y1(t,e.type);t!==i&&(lt(uc,e),lt(us,i))}function Mh(e){uc.current===e&&(pi(us),pi(uc)),Nh.current===e&&(pi(Nh),Vo._currentValue=la)}var _p,z0;function cr(e){if(_p===void 0)try{throw Error()}catch(i){var t=i.stack.trim().match(/\n( *(at )?)/);_p=t&&t[1]||"",z0=-1{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)":-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{vp=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?cr(i):""}function wO(e,t){switch(e.tag){case 26:case 27:case 5:return cr(e.type);case 16:return cr("Lazy");case 13:return e.child!==t&&t!==null?cr("Suspense Fallback"):cr("Suspense");case 19:return cr("SuspenseList");case 0:case 15:return bp(e.type,!1);case 11:return bp(e.type.render,!1);case 1:return bp(e.type,!0);case 31:return cr("Activity");case 30:return cr("ViewTransition");default:return""}}function P0(e){try{var t="",i=null;do t+=wO(e,i),i=e,e=e.return;while(e);return t}catch(n){return` +`+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` Error generating stack: `+n.message+` -`+n.stack}}var sm=Object.prototype.hasOwnProperty,og=qt.unstable_scheduleCallback,yp=qt.unstable_cancelCallback,EO=qt.unstable_shouldYield,xO=qt.unstable_requestPaint,sn=qt.unstable_now,CO=qt.unstable_getCurrentPriorityLevel,kS=qt.unstable_ImmediatePriority,TS=qt.unstable_UserBlockingPriority,Oh=qt.unstable_NormalPriority,kO=qt.unstable_LowPriority,NS=qt.unstable_IdlePriority,TO=qt.log,NO=qt.unstable_setDisableYieldValue,Tc=null,rn=null;function pr(e){if(typeof TO=="function"&&NO(e),rn&&typeof rn.setStrictMode=="function")try{rn.setStrictMode(Tc,e)}catch{}}var an=Math.clz32?Math.clz32:OO,AO=Math.log,MO=Math.LN2;function OO(e){return e>>>=0,e===0?32:31-(AO(e)/MO|0)|0}var Ku=256,Wu=262144,Gu=4194304;function na(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 nd(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=na(n):(a&=o,a!==0?s=na(a):i||(i=o&~e,i!==0&&(s=na(i))))):(o=n&~r,o!==0?s=na(o):a!==0?s=na(a):i||(i=n&~e,i!==0&&(s=na(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 Nc(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function AS(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 Ac(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function DO(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"),lm=!1;if(zs)try{uo={},Object.defineProperty(uo,"passive",{get:function(){lm=!0}}),window.addEventListener("test",uo,uo),window.removeEventListener("test",uo,uo)}catch{lm=!1}var uo,mr=null,dg=null,hh=null;function GS(){if(hh)return hh;var e,t=dg,i=t.length,n,s="value"in mr?mr.value:mr.textContent,r=s.length;for(e=0;e=Zl),Z0=" ",Q0=!1;function YS(e,t){switch(e){case"keyup":return mR.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jS(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var So=!1;function _R(e,t){switch(e){case"compositionend":return jS(t);case"keypress":return t.which!==32?null:(Q0=!0,Z0);case"textInput":return e=t.data,e===Z0&&Q0?null:e;default:return null}}function vR(e,t){if(So)return e==="compositionend"||!pg&&YS(e,t)?(e=GS(),hh=dg=mr=null,So=!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 iy(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ny(e,t){var i=iy(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=iy(i)}}function QS(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?QS(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function JS(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=cm(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=cm(e.document)}return t}function mg(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 kR=zs&&"documentMode"in document&&11>=document.documentMode,wo=null,um=null,Jl=null,hm=!1;function sy(e,t,i){var n=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;hm||wo==null||wo!==cm(n)||(n=wo,"selectionStart"in n&&mg(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}),Jl&&fc(Jl,n)||(Jl=n,n=ed(um,"onSelect"),0>=a,s-=a,ls=1<<32-an(t)+s|i<M?(O=N,N=null):O=N.sibling;var F=d(g,N,b[M],S);if(F===null){N===null&&(N=O);break}e&&N&&F.alternate===null&&t(g,N),m=r(F,m,M),C===null?x=F:C.sibling=F,C=F,N=O}if(M===b.length)return i(g,N),ke&&Ds(g,M),x;if(N===null){for(;MM?(O=N,N=null):O=N.sibling;var W=d(g,N,F.value,S);if(W===null){N===null&&(N=O);break}e&&N&&W.alternate===null&&t(g,N),m=r(W,m,M),C===null?x=W:C.sibling=W,C=W,N=O}if(F.done)return i(g,N),ke&&Ds(g,M),x;if(N===null){for(;!F.done;M++,F=b.next())F=h(g,F.value,S),F!==null&&(m=r(F,m,M),C===null?x=F:C.sibling=F,C=F);return ke&&Ds(g,M),x}for(N=n(N);!F.done;M++,F=b.next())F=f(N,g,M,F.value,S),F!==null&&(e&&(O=F.alternate,O!==null&&N.delete(O.key===null?M:O.key)),m=r(F,m,M),C===null?x=F:C.sibling=F,C=F);return e&&N.forEach(function(z){return t(g,z)}),ke&&Ds(g,M),x}function v(g,m,b,S){if(typeof b=="object"&&b!==null&&b.type===vo&&b.key===null&&b.props.ref===void 0&&(b=b.props.children),typeof b=="object"&&b!==null){switch(b.$$typeof){case qu:e:{for(var x=b.key;m!==null;){if(m.key===x){if(x=b.type,x===vo){if(m.tag===7){i(g,m.sibling),S=s(m,b.props.children),lr(S,b),S.return=g,g=S;break e}}else if(m.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===hr&&sa(x)===m.type){i(g,m.sibling),S=s(m,b.props),lr(S,b),S.return=g,g=S;break e}i(g,m);break}else t(g,m);m=m.sibling}b.type===vo?(S=ca(b.props.children,g.mode,S,b.key),lr(S,b),S.return=g,g=S):(S=fh(b.type,b.key,b.props,null,g.mode,S),lr(S,b),S.return=g,g=S)}return a(g);case $l:e:{for(x=b.key;m!==null;){if(m.key===x)if(m.tag===4&&m.stateNode.containerInfo===b.containerInfo&&m.stateNode.implementation===b.implementation){i(g,m.sibling),S=s(m,b.children||[]),S.return=g,g=S;break e}else{i(g,m);break}else t(g,m);m=m.sibling}S=Mp(b,g.mode,S),S.return=g,g=S}return a(g);case hr:return b=sa(b),v(g,m,b,S)}if(Yl(b))return p(g,m,b,S);if(Hl(b)){if(x=Hl(b),typeof x!="function")throw Error(B(150));return b=x.call(b),_(g,m,b,S)}if(typeof b.then=="function")return v(g,m,Zu(b),S);if(b.$$typeof===as)return v(g,m,Xu(g,b),S);Qu(g,b)}return typeof b=="string"&&b!==""||typeof b=="number"||typeof b=="bigint"?(b=""+b,m!==null&&m.tag===6?(i(g,m.sibling),S=s(m,b),S.return=g,g=S):(i(g,m),S=Ap(b,g.mode,S),S.return=g,g=S),a(g)):i(g,m)}return function(g,m,b,S){try{gc=0;var x=v(g,m,b,S);return Do=null,x}catch(N){if(N===el||N===hd)throw N;var C=Gi(29,N,null,g.mode);return C.lanes=S,C.return=g,C}}}var _a=pw(!0),mw=pw(!1),dr=!1;function Eg(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function _m(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 wr(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Er(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=Lh(e),aw(e,null,i),t}return cd(e,n,t,i),Lh(e)}function tc(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,RS(e,i)}}function Rp(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 vm=!1;function ic(){if(vm){var e=Ro;if(e!==null)throw e}}function nc(e,t,i,n){vm=!1;var s=e.updateQueue;dr=!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?(Ie&d)===d:(n&d)===d){d!==0&&d===ga&&(vm=!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 v=i;switch(_.tag){case 1:if(p=_.payload,typeof p=="function"){h=p.call(v,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(v,h,d):p,d==null)break e;h=nt({},h,d);break e;case 2:dr=!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),Lr|=a,e.lanes=a,e.memoizedState=h}}function gw(e,t){if(typeof e!="function")throw Error(B(191,e));e.call(t)}function _w(e,t){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;er?r:8;var a=_e.T,o={};o.types=a!==null?a.types:null,_e.T=o,zg(e,!1,t,i);try{var l=s(),c=_e.S;if(c!==null&&c(o,l),l!==null&&typeof l=="object"&&typeof l.then=="function"){var u=zR(l,n);sc(e,t,u,on(e))}else sc(e,t,n,on(e))}catch(h){sc(e,t,{then:function(){},status:"rejected",reason:h},on())}finally{We.p=r,a!==null&&o.types!==null&&(a.types=o.types),_e.T=a}}function KR(){}function Em(e,t,i,n){if(e.tag!==5)throw Error(B(476));var s=qw(e).queue;Fw(e,s,t,la,i===null?KR:function(){return Kw(e),i(n)})}function qw(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:la,baseState:la,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Hs,lastRenderedState:la},next:null};var i={};return t.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Hs,lastRenderedState:i},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Kw(e){var t=qw(e);t.next===null&&(t=e.alternate.memoizedState),sc(e,t.next.queue,{},on())}function Ig(){return fi(Vo)}function Ww(){return Nt().memoizedState}function Gw(){return Nt().memoizedState}function WR(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var i=on();e=wr(i);var n=Er(t,e,i);n!==null&&($i(n,t,i),tc(n,t,i)),t={cache:yg()},e.payload=t;return}t=t.return}}function GR(e,t,i){var n=on();i={lane:n,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},md(e)?Yw(t,i):(i=_g(e,t,i,n),i!==null&&($i(i,e,n),jw(i,t,n)))}function $w(e,t,i){var n=on();sc(e,t,i,n)}function sc(e,t,i,n){var s={lane:n,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(md(e))Yw(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,ln(o,a))return cd(e,t,s,0),it===null&&ld(),!1}catch{}if(i=_g(e,t,s,n),i!==null)return $i(i,e,n),jw(i,t,n),!0}return!1}function zg(e,t,i,n){if(n={lane:2,revertLane:jg(),gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},md(e)){if(t)throw Error(B(479))}else t=_g(e,i,n,2),t!==null&&$i(t,e,2)}function md(e){var t=e.alternate;return e===Se||t!==null&&t===Se}function Yw(e,t){Lo=Fh=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function jw(e,t,i){if((i&4194048)!==0){var n=t.lanes;n&=e.pendingLanes,i|=n,t.lanes=i,RS(e,i)}}var Kh={readContext:fi,use:fd,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},Vw={readContext:fi,use:fd,useCallback:function(e,t){return Bi().memoizedState=[e,t===void 0?null:t],e},useContext:fi,useEffect:yy,useImperativeHandle:function(e,t,i){i=i!=null?i.concat([e]):null,_h(4194308,4,Iw.bind(null,t,e),i)},useLayoutEffect:function(e,t){return _h(4194308,4,e,t)},useInsertionEffect:function(e,t){_h(4,2,e,t)},useMemo:function(e,t){var i=Bi();t=t===void 0?null:t;var n=e();if(va){pr(!0);try{e()}finally{pr(!1)}}return i.memoizedState=[n,t],n},useReducer:function(e,t,i){var n=Bi();if(i!==void 0){var s=i(t);if(va){pr(!0);try{i(t)}finally{pr(!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=GR.bind(null,Se,e),[n.memoizedState,e]},useRef:function(e){var t=Bi();return e={current:e},t.memoizedState=e},useState:function(e){e=Sm(e);var t=e.queue,i=$w.bind(null,Se,t);return t.dispatch=i,[e.memoizedState,i]},useDebugValue:Lg,useDeferredValue:function(e,t){var i=Bi();return Bg(i,e,t)},useTransition:function(){var e=Sm(!1);return e=Fw.bind(null,Se,e.queue,!0,!1),Bi().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,i){var n=Se,s=Bi();if(ke){if(i===void 0)throw Error(B(407));i=i()}else{if(i=t(),it===null)throw Error(B(349));(Ie&127)!==0||ww(n,t,i)}s.memoizedState=i;var r={value:i,getSnapshot:t};return s.queue=r,yy(xw.bind(null,n,r,e),[e]),n.flags|=2048,qo(9,{destroy:void 0},Ew.bind(null,n,r,i,t),null),i},useId:function(){var e=Bi(),t=it.identifierPrefix;if(ke){var i=cs,n=ls;i=(n&~(1<<32-an(n)-1)).toString(32)+i,t="_"+t+"R_"+i,i=qh++,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[di]=t,r[ji]=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(gi(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&&Rs(t)}}return at(t),t.subtreeFlags&=-33554433,Ip(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,i),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==n&&Rs(t);else{if(typeof n!="string"&&t.stateNode===null)throw Error(B(166));if(e=yr.current,ho(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[di]=t,e=!!(e.nodeValue===i||n!==null&&n.suppressHydrationWarning===!0||$1(e.nodeValue,i)),e||Or(t,!0)}else e=Sc(e).createTextNode(n),e[di]=t,t.stateNode=e}return at(t),null;case 31:if(i=t.memoizedState,e===null||e.memoizedState!==null){if(n=ho(t),i!==null){if(e===null){if(!n)throw Error(B(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(B(557));e[di]=t}else fa(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;at(t),e=!1}else i=Op(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return t.flags&256?(en(t),t):(en(t),null);if((t.flags&128)!==0)throw Error(B(558))}return at(t),null;case 13:if(n=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(s=ho(t),n!==null&&n.dehydrated!==null){if(e===null){if(!s)throw Error(B(318));if(s=t.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(B(317));s[di]=t}else fa(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;at(t),s=!1}else s=Op(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),s=!0;if(!s)return t.flags&256?(en(t),t):(en(t),null)}return en(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),th(t,t.updateQueue),at(t),null);case 4:return Uo(),e===null&&Vg(t.stateNode.containerInfo),t.flags|=67108864,at(t),null;case 10:return Is(t.type),at(t),null;case 19:if(Cg(t),n=t.memoizedState,n===null)return at(t),null;if(s=(t.flags&128)!==0,r=n.rendering,r===null)if(s)ql(n,!1);else{if(Et!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(r=Hh(e),r!==null){for(t.flags|=128,ql(n,!1),e=r.updateQueue,t.updateQueue=e,th(t,e),t.subtreeFlags=0,e=i,i=t.child;i!==null;)ow(i,e),i=i.sibling;return _c(t,mi.current&1|2),ke&&Ds(t,n.treeForkCount),t.child}e=e.sibling}n.tail!==null&&sn()>Xh&&(t.flags|=128,s=!0,ql(n,!1),t.lanes=4194304)}else{if(!s)if(e=Hh(r),e!==null){if(t.flags|=128,s=!0,e=e.updateQueue,t.updateQueue=e,th(t,e),ql(n,!0),n.tail===null&&n.tailMode!=="collapsed"&&n.tailMode!=="visible"&&!r.alternate&&!ke)return at(t),null}else 2*sn()-n.renderingStartTime>Xh&&i!==536870912&&(t.flags|=128,s=!0,ql(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=sn(),e.sibling=null,r=mi.current,r=s?r&1|2:r&1,n.tailMode==="visible"||n.tailMode==="collapsed"||!i||ke?_c(t,r):(i=r,lt(_i,t),lt(mi,i),Ei===null&&(Ei=t)),ke&&Ds(t,n.treeForkCount),e}return at(t),null;case 22:case 23:return en(t),xg(),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&&th(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&&pi(ua),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),Is(Dt),at(t),null;case 25:return null;case 30:return t.flags|=33554432,at(t),null}throw Error(B(156,t.tag))}function QR(e,t){switch(bg(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Is(Dt),Uo(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Mh(t),null;case 31:if(t.memoizedState!==null){if(en(t),t.alternate===null)throw Error(B(340));fa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(en(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(B(340));fa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Cg(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 Uo(),null;case 10:return Is(t.type),null;case 22:case 23:return en(t),xg(),e!==null&&pi(ua),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Is(Dt),null;case 25:return null;default:return null}}function a1(e,t){switch(bg(t),t.tag){case 3:Is(Dt),Uo();break;case 26:case 27:case 5:Mh(t);break;case 4:Uo();break;case 31:t.memoizedState!==null&&en(t);break;case 13:en(t);break;case 19:Cg(t);break;case 10:Is(t.type);break;case 22:case 23:en(t),xg(),e!==null&&pi(ua);break;case 24:Is(Dt)}}function Lc(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 Dr(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 o1(e){var t=e.updateQueue;if(t!==null){var i=e.stateNode;try{_w(t,i)}catch(n){Qe(e,e.return,n)}}}function l1(e,t,i){i.props=ba(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(n){Qe(e,t,n)}}function ss(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=Ps(e.memoizedProps,s);(s.ref===null||s.ref.name!==r)&&(s.ref=Q1(r)),n=s.ref;break;case 7:if(e.stateNode===null){var a=new cn(e);Yi(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 hi(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 Gh(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var i=0;i title"))),gi(n,t,i),n[di]=e,Vt(n),t=n;break e;case"link":if(r=lS("link","href",s).get(t+(i.href||""))){for(a=0;av&&(a=v,v=_,_=a);var g=ny(o,_),m=ny(o,v);if(g&&m&&(f.rangeCount!==1||f.anchorNode!==g.node||f.anchorOffset!==g.offset||f.focusNode!==m.node||f.focusOffset!==m.offset)){var b=h.createRange();b.setStart(g.node,g.offset),f.removeAllRanges(),_>v?(f.addRange(b),f.extend(m.node,m.offset)):(b.setEnd(m.node,m.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,_e.T=null,i=qm,qm=null;var r=qn,a=hs;if(yt=0,ya=qn=null,hs=0,(Ke&6)!==0)throw Error(B(331));var o=Ke;if(Ke|=4,T1(r.current),x1(r,r.current,a,i),Ke=o,Bc(0,!1),rn&&typeof rn.onPostCommitFiberRoot=="function")try{rn.onPostCommitFiberRoot(Tc,r)}catch{}return!0}finally{We.p=s,_e.T=n,U1(e,t)}}function qy(e,t,i){t=En(i,t),t=Cm(e.stateNode,t,2),e=Er(e,t,2),e!==null&&(Ac(e,2),ps(e))}function Qe(e,t,i){if(e.tag===3)qy(e,e,i);else for(;t!==null;){if(t.tag===3){qy(t,e,i);break}else if(t.tag===1){var n=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof n.componentDidCatch=="function"&&(kr===null||!kr.has(n))){e=En(i,e),i=e1(2),n=Er(t,i,2),n!==null&&(t1(i,n,t,e),Ac(n,2),ps(n));break}}t=t.return}}function Fp(e,t,i){var n=e.pingCache;if(n===null){n=e.pingCache=new iD;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)||($g=!0,s.add(i),e=uD.bind(null,e,t,i),t.then(e,e))}function uD(e,t,i){var n=e.pingCache;n!==null&&n.delete(t),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,it===e&&(Ie&i)===i&&((Et===4||Et===3&&(Ie&62914560)===Ie&&300>sn()-_d)&&(Ke&2)===0?Go(e,0):Vh|=i,Ko===Ie&&(Ko=0)),ps(e)}function H1(e,t){t===0&&(t=MS()),e=xa(e,t),e!==null&&(Ac(e,t),ps(e))}function hD(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),H1(e,i)}function dD(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(B(314))}n!==null&&n.delete(t),H1(e,i)}function fD(e,t){return og(e,t)}var $o=null,go=null,Ym=!1,Jh=!1,qp=!1,br=0;function ps(e){e!==go&&e.next===null&&(go===null?$o=go=e:go=go.next=e),Jh=!0,Ym||(Ym=!0,mD())}function Bc(e,t){if(!qp&&Jh){qp=!0;do for(var i=!1,n=$o;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-an(42|e)+1)-1,r&=s&~(a&~o),r=r&201326741?r&201326741|1:r?r|2:0}r!==0&&(i=!0,Ky(n,r))}else r=Ie,r=nd(n,n===it?r:0,n.cancelPendingCommit!==null||n.timeoutHandle!==-1),(r&3)===0||Nc(n,r)||(i=!0,Ky(n,r));n=n.next}while(i);qp=!1}}function pD(){F1()}function F1(){Jh=Ym=!1;var e=0;br!==0&&xD()&&(e=br);for(var t=sn(),i=null,n=$o;n!==null;){var s=n.next,r=q1(n,t);r===0?(n.next=null,i===null?$o=s:i.next=s,s===null&&(go=i)):(i=n,(e!==0||(r&3)!==0)&&(Jh=!0)),n=s}yt!==0&&yt!==5||Bc(e,!1),br!==0&&(br=0)}function q1(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&&Vy(h)&&(l=l.responseEnd,a+=u*(lCh){_.length=p;break}b=new Promise(MD.bind(b)),_.push(b)}}}if(0<_.length)return d=Promise.race([Promise.all(_),new Promise(function(x){return setTimeout(x,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 aE(e,t,i){var n=nl;if(n&&typeof t=="string"&&t){var s=wn(t);s='link[rel="'+e+'"][href="'+s+'"]',typeof i=="string"&&(s+='[crossorigin="'+i+'"]'),rS.has(s)||(rS.add(s),e={rel:e,crossOrigin:i,href:t},n.querySelector(s)===null&&(t=n.createElement("link"),gi(t,"link",e),Vt(t),n.head.appendChild(t)))}}function VD(e){Gs.D(e),aE("dns-prefetch",e,null)}function XD(e,t){Gs.C(e,t),aE("preconnect",e,t)}function ZD(e,t,i){Gs.L(e,t,i);var n=nl;if(n&&e&&t){var s='link[rel="preload"][as="'+wn(t)+'"]';t==="image"&&i&&i.imageSrcSet?(s+='[imagesrcset="'+wn(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(s+='[imagesizes="'+wn(i.imageSizes)+'"]')):s+='[href="'+wn(e)+'"]';var r=s;switch(t){case"style":r=jo(e);break;case"script":r=sl(e)}if(!(kn.has(r)||(e=nt({rel:"preload",href:t==="image"&&i&&i.imageSrcSet?void 0:e,as:t},i),kn.set(r,e),n.querySelector(s)!==null||t==="style"&&n.querySelector(Ic(r))||t==="script"&&n.querySelector(zc(r))))){var a=n.createElement("link");gi(a,"link",e),t==="style"&&(a[Rh]=!0,a.onload=a.onerror=function(){BS(a)}),Vt(a),n.head.appendChild(a)}}}function QD(e,t){Gs.m(e,t);var i=nl;if(i&&e){var n=t&&typeof t.as=="string"?t.as:"script",s='link[rel="modulepreload"][as="'+wn(n)+'"][href="'+wn(e)+'"]',r=s;switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":r=sl(e)}if(!kn.has(r)&&(e=nt({rel:"modulepreload",href:e},t),kn.set(r,e),i.querySelector(s)===null)){switch(n){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(zc(r)))return}n=i.createElement("link"),gi(n,"link",e),Vt(n),i.head.appendChild(n)}}}function JD(e,t,i){Gs.S(e,t,i);var n=nl;if(n&&e){var s=Ao(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(Ic(r)))o.loading=5;else{e=nt({rel:"stylesheet",href:e,"data-precedence":t},i),(i=kn.get(r))&&Jg(e,i);var l=a=n.createElement("link");Vt(l),gi(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,Eh(a,t,n)}a={type:"stylesheet",instance:a,count:1,state:o},s.set(r,a)}}}function e2(e,t){Gs.X(e,t);var i=nl;if(i&&e){var n=Ao(i).hoistableScripts,s=sl(e),r=n.get(s);r||(r=i.querySelector(zc(s)),r||(e=nt({src:e,async:!0},t),(t=kn.get(s))&&e_(e,t),r=i.createElement("script"),Vt(r),gi(r,"link",e),i.head.appendChild(r)),r={type:"script",instance:r,count:1,state:null},n.set(s,r))}}function t2(e,t){Gs.M(e,t);var i=nl;if(i&&e){var n=Ao(i).hoistableScripts,s=sl(e),r=n.get(s);r||(r=i.querySelector(zc(s)),r||(e=nt({src:e,async:!0,type:"module"},t),(t=kn.get(s))&&e_(e,t),r=i.createElement("script"),Vt(r),gi(r,"link",e),i.head.appendChild(r)),r={type:"script",instance:r,count:1,state:null},n.set(s,r))}}function aS(e,t,i,n){var s=(s=yr.current)?wc(s):null;if(!s)throw Error(B(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=Ao(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=Ao(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(Ic(e)))?r._p||(a.instance=r,a.state.loading=5):(r=kn.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},kn.set(e,r)),i2(s,e,r,a.state))),t&&n===null)throw Error(B(528,""));return a}if(t&&n!==null)throw Error(B(529,""));return null;case"script":return t=i.async,i=i.src,typeof i=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(i=sl(i),t=Ao(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(B(444,e))}}function jo(e){return'href="'+wn(e)+'"'}function Ic(e){return'link[rel="stylesheet"]['+e+"]"}function oE(e){return nt({},e,{"data-precedence":e.precedence,precedence:null})}function i2(e,t,i,n){if(t=e.querySelector('link[rel="preload"][as="style"]['+t+"]")){if(t[Rh]!==!0){n.loading=1;return}}else t=e.createElement("link"),t[Rh]=!0,t.onload=t.onerror=BS.bind(null,t),gi(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 sl(e){return'[src="'+wn(e)+'"]'}function zc(e){return"script[async]"+e}function oS(e,t,i){if(t.count++,t.instance===null)switch(t.type){case"style":var n=e.querySelector('style[data-href~="'+wn(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),gi(n,"style",s),Eh(n,i.precedence,e),t.instance=n;case"stylesheet":s=jo(i.href);var r=e.querySelector(Ic(s));if(r)return t.state.loading|=4,t.instance=r,Vt(r),r;n=oE(i),(s=kn.get(s))&&Jg(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}),gi(r,"link",n),t.state.loading|=4,Eh(r,i.precedence,e),t.instance=r;case"script":return r=sl(i.src),(s=e.querySelector(zc(r)))?(t.instance=s,Vt(s),s):(n=i,(s=kn.get(r))&&(n=nt({},i),e_(n,s)),e=e.ownerDocument||e,s=e.createElement("script"),Vt(s),gi(s,"link",n),e.head.appendChild(s),t.instance=s);case"void":return null;default:throw Error(B(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(n=t.instance,t.state.loading|=4,Eh(n,i.precedence,e));return t.instance}function Eh(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 n2(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 cS(e,t){return e==="img"&&t.src!=null&&t.src!==""&&t.onLoad==null&&t.loading!=="lazy"}function lE(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function cE(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function uS(e,t){typeof t.decode=="function"&&(e.imgCount++,t.complete||(e.imgBytes+=cE(t),e.suspenseyImages.push(t)),e=a2.bind(e),t.decode().then(e,e))}function s2(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(Ic(s));if(r){t=r._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Ec.bind(e),t.then(e,e)),i.state.loading|=4,i.instance=r,Vt(r);return}r=t.ownerDocument||t,n=oE(n),(s=kn.get(s))&&Jg(n,s),r=r.createElement("link"),Vt(r);var a=r;a._p=new Promise(function(o,l){a.onload=o,a.onerror=l}),gi(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=Ec.bind(e),t.addEventListener("load",i),t.addEventListener("error",i))}}var Ch=0;function r2(e,t){return e.stylesheets&&e.count===0&&kh(e,e.stylesheets),0Ch?50:800)+t);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(n),clearTimeout(s)}}:null}function uE(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)kh(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function Ec(){this.count--,uE(this)}function a2(){this.imgCount--,uE(this)}var td=null;function kh(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,td=new Map,t.forEach(o2,e),td=null,Ec.call(e))}function o2(e,t){if(!(t.state.loading&4)){var i=td.get(e);if(i)var n=i.get(null);else{i=new Map,td.set(e,i);for(var s=e.querySelectorAll("link[data-precedence],style[data-precedence]"),r=0;r{"use strict";function bE(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(bE)}catch(e){console.error(e)}}bE(),yE.exports=vE()});function wE(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)continue;let o=s.startsWith("--")?s:s.startsWith("magpie-")?`--${s}`:`--magpie-${s}`;n.style.setProperty(o,a)}}var EE=ce(()=>{});var r_,xE=ce(()=>{r_={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\u8FDE\u2026",starting:"\u6B63\u5728\u542F\u52A8\u672C\u5730\u670D\u52A1\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",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",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:"Providers",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:"Default",defaultEffort:"Default",defaultEffortNamed:"Default ({level})",effortTitle:"\u601D\u8003\u5F3A\u5EA6",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:"Plan Mode",desc:"\u53EA\u5206\u6790\u4EE3\u7801\u5E93\uFF0C\u4E0D\u6267\u884C\u5DE5\u5177\u6216\u4FEE\u6539"},default:{label:"Always Ask",desc:"\u9996\u6B21\u4F7F\u7528\u5DE5\u5177\u65F6\u4F1A\u8BF7\u6C42\u6388\u6743"},acceptEdits:{label:"Accept File Edits",desc:"\u81EA\u52A8\u6279\u51C6\u7F16\u8F91\u7C7B\u5DE5\u5177\uFF0C\u4E0D\u518D\u9010\u9879\u8BE2\u95EE"},bypass:{label:"Bypass",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:"Plan",desc:"\u53EA\u8BFB\u89C4\u5212\uFF1A\u5206\u6790\u5E76\u63D0\u51FA\u65B9\u6848\uFF0C\u4E0D\u6539\u6587\u4EF6"},cursorAsk:{label:"Ask",desc:"\u95EE\u7B54\u6A21\u5F0F\uFF1A\u89E3\u91CA\u4E0E\u8BA8\u8BBA\uFF0C\u53EA\u8BFB"}}},settings:{title:"\u8BBE\u7F6E",defaultAgent:"\u9ED8\u8BA4 Agent",defaultMode:"\u9ED8\u8BA4\u6743\u9650\u6A21\u5F0F",theme:"\u4E3B\u9898",themeAuto:"\u8DDF\u968F\u7CFB\u7EDF",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",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",versionLine:"\u7248\u672C v{ver} \xB7 PID {pid}",dataDir:"\u6570\u636E\u76EE\u5F55\uFF1A",failSave:"\u4FDD\u5B58\u5931\u8D25\uFF1A",providers:"Providers",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",providerLaunchArgs:"\u53C2\u6570\uFF08JSON \u6570\u7EC4\uFF09"},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"}},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"},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: "},composer:{waitPerm:"Waiting for your approval above",queuePlaceholder:"Queue a message (Ctrl+Enter to steer)",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",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)"}}},settings:{title:"Settings",defaultAgent:"Default agent",defaultMode:"Default permission mode",theme:"Theme",themeAuto:"System",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)",thinking:"Reasoning",showThinking:"Show agent reasoning/thinking",idleClose:"Idle cleanup",idleMinutes:"minutes before closing idle sessions",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",providerLaunchArgs:"Args (JSON array)"},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"}}}});function kE(e){let t=String(e??"").trim().toLowerCase();return t?t==="zh"||t.startsWith("zh-")?"zh":"en":m2()}function m2(){let e=typeof navigator<"u"?navigator.language:"";return kE(e||"zh")}function TE(e){let t=new URLSearchParams(e).get("lang");ka=kE(t);let i=ka==="zh"?"zh-CN":"en";return typeof document<"u"&&(document.documentElement.lang=i),ka}function Ed(){return ka}function xd(){return ka==="zh"?"zh-CN":"en-US"}function CE(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 w(e){return CE(r_[ka],e)??CE(r_.en,e)??e}function Ce(e,t){let i=w(e);for(let[n,s]of Object.entries(t))i=i.replaceAll(`{${n}}`,String(s));return i}function ft(e){let t=e,i=t?.code;if(i){let s=w(`api.${i}`);if(s!==`api.${i}`)return s}let n=String(t?.message??e);return Ta(n)}function Ta(e){if(ka==="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 Cd(e,t){return t&&(e==="\u65B0\u5BF9\u8BDD"||e==="New chat")?w("thread.new"):e}var ka,xi=ce(()=>{xE();ka="zh"});var kd,NE=ce(()=>{xi();kd=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??w("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("\u8FDE\u63A5\u4E2D\u65AD")),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("\u8FDE\u63A5\u672A\u5EFA\u7ACB"));return}let o=++this.seq,l=setTimeout(()=>{this.pending.delete(o),r(new Error("\u8BF7\u6C42\u8D85\u65F6"))},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 AE,ME,a_=ce(()=>{AE=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},ME=(e=>e?AE(e):AE)});function _2(e,t=g2){let i=Td.default.useSyncExternalStore(e.subscribe,Td.default.useCallback(()=>t(e.getState()),[e,t]),()=>t(e.getInitialState()));return Td.default.useDebugValue(i),i}var Td,g2,OE,ms,RE=ce(()=>{Td=oe(Ot(),1);a_();g2=e=>e;OE=e=>{let t=ME(e),i=n=>_2(t,n);return Object.assign(i,t),i},ms=(e=>e?OE(e):OE)});var rl=ce(()=>{a_();RE()});var gs,Pc=ce(()=>{rl();gs=ms(e=>({state:"connecting",version:null,set:t=>e(t)}))});function Na(e,t=window.innerWidth){if(t<900)return l_;let i=e.sbHidden?0:e.sidebarWidth;return al(t-i-LE-DE,zr,l_)}function ol(e,t=window.innerWidth){if(t<760)return o_;let i=e.panelOpen?e.panelWidth:0;return al(t-i-LE-DE,Aa,o_)}function Nd(e,t=window.innerWidth){let i=al(e.sidebarWidth,Aa,ol(e,t)),n=al(e.panelWidth,zr,Na({...e,sidebarWidth:i},t));return i=al(i,Aa,ol({...e,sidebarWidth:i,panelWidth:n},t)),n=al(n,zr,Na({...e,sidebarWidth:i,panelWidth:n},t)),{sidebarWidth:i,panelWidth:n}}var DE,LE,al,c_=ce(()=>{un();DE=300,LE=10,al=(e,t,i)=>Math.max(t,Math.min(i,e))});function Ma(e,t){let i=e().ws;i&&i.call("settings.set",{patch:t}).catch(()=>{})}var Aa,o_,zr,l_,u_,pe,un=ce(()=>{rl();c_();Aa=200,o_=360,zr=320,l_=900,u_=(e,t,i)=>Math.max(t,Math.min(i,e));pe=ms((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=Nd(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=ol(n);i=u_(Math.round(i),Aa,s),e({sidebarWidth:i}),Ma(t,{sidebarWidth:i})},setPanelWidth:i=>{let n=t(),s=Na(n);i=u_(Math.round(i),zr,s),e({panelWidth:i}),Ma(t,{panel:{open:t().panelOpen,tab:t().panelTab,width:i}})},openPanel:i=>{let n=i??t().panelTab,s=t(),r=u_(s.panelWidth,zr,Na({...s,panelOpen:!0}));e({panelOpen:!0,panelTab:n,panelWidth:r}),Ma(t,{panel:{open:!0,tab:n,width:r}})},closePanel:()=>{e({panelOpen:!1}),Ma(t,{panel:{open:!1,tab:t().panelTab,width:t().panelWidth}})},setPanelTab:i=>{e({panelTab:i}),Ma(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}),Ma(t,{collapsedProjects:Object.keys(n)})},select:(i,n)=>{e({currentProjectId:i,currentThreadId:n,sbOpen:!1}),Ma(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 ll(){let e="claude";try{e=(await ct.getState().ws.call("settings.get")).defaultProvider??"claude"}catch{}let t=ct.getState().providers;return t.length?t.find(i=>i.id===e&&BE(i))?.id??t.find(i=>BE(i))?.id??e:e}function BE(e){return e.enabled===!1||!e.available||e.status==="planned"?!1:e.status==="verified"||e.status==="experimental"?!0:e.ready!==!1}var ct,Wn=ce(()=>{rl();un();ct=ms((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)}),pe.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)}),pe.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}),pe.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 zE=ge(Ad=>{"use strict";var v2=Symbol.for("react.transitional.element"),b2=Symbol.for("react.fragment");function IE(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:v2,type:e,key:n,ref:t!==void 0?t:null,props:i}}Ad.Fragment=b2;Ad.jsx=IE;Ad.jsxs=IE});var De=ge((RP,PE)=>{"use strict";PE.exports=zE()});function HE(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 FE(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 qE({sidebar:e,topbar:t,children:i,panel:n}){let s=pe(),r=HE("(max-width: 759px)"),a=HE("(max-width: 899px)"),o=(0,xt.useRef)(!1),l=(0,xt.useRef)(!1),c=FE((0,xt.useCallback)(()=>pe.getState().sidebarWidth,[]),(0,xt.useCallback)((d,f)=>{o.current=!0;let p=pe.getState(),_=ol(p);pe.setState({sidebarWidth:UE(Math.round(d+f),Aa,_)})},[]),(0,xt.useCallback)(()=>{o.current&&(o.current=!1,pe.getState().setSidebarWidth(pe.getState().sidebarWidth))},[])),u=FE((0,xt.useCallback)(()=>pe.getState().panelWidth,[]),(0,xt.useCallback)((d,f)=>{l.current=!0;let p=pe.getState(),_=Na(p);pe.setState({panelWidth:UE(Math.round(d-f),zr,_)})},[]),(0,xt.useCallback)(()=>{l.current&&(l.current=!1,pe.getState().setPanelWidth(pe.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 _=pe.getState();window.matchMedia("(max-width: 759px)").matches?_.setSbOpen(!_.sbOpen):_.toggleSidebarHidden()}else if(p==="j"){f.preventDefault();let _=pe.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=pe.getState(),p=Nd(f);p.sidebarWidth!==f.sidebarWidth&&pe.getState().setSidebarWidth(p.sidebarWidth),p.panelWidth!==f.panelWidth&&pe.getState().setPanelWidth(p.panelWidth)};return window.addEventListener("resize",d),d(),()=>window.removeEventListener("resize",d)},[]);let h=s.sbOpen||s.panelOpen&&a;return(0,$s.jsxs)("div",{className:"app",children:[(0,$s.jsx)("aside",{className:`sidebar${s.sbHidden&&!r?" w-hide":""}${s.sbOpen?" open":""}`,children:e}),(0,$s.jsx)("div",{className:`rs rs-l${c.drag?" drag":""}`,onPointerDown:c.down}),(0,$s.jsxs)("main",{className:"main",children:[t,i]}),(0,$s.jsx)("div",{className:`rs rs-r${u.drag?" drag":""}`,onPointerDown:u.down}),(0,$s.jsx)("section",{className:`panel${s.panelOpen?" open":" w-hide"}`,"aria-hidden":!s.panelOpen,children:n}),(0,$s.jsx)("div",{className:`scrim${h?" show":""}`,onClick:()=>{pe.getState().setSbOpen(!1),pe.getState().panelOpen&&a&&pe.getState().closePanel()}})]})}var xt,$s,UE,KE=ce(()=>{xt=oe(Ot(),1);un();c_();$s=oe(De(),1),UE=(e,t,i)=>Math.max(t,Math.min(i,e))});function Tn(e){return!!e.isComposing||e.keyCode===229}var cl=ce(()=>{});function h_(e,t=Date.now()){let i=Math.max(0,t-e),n=Math.floor(i/6e4);if(n<1)return w("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=xd();return Ed()==="zh"?`${a.getMonth()+1}/${a.getDate()}`:a.toLocaleDateString(o,{month:"short",day:"numeric"})}function ul(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:String(e)}function Md(e){return`$${e.toFixed(2)}`}function d_(e){let t=Math.round(e/1e3);return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60?` ${t%60}s`:""}`}var Od=ce(()=>{xi()});function Uc({x:e,y:t,items:i,onClose:n}){let s=(0,Ys.useRef)(null),[r,a]=(0,Ys.useState)({left:e,top:t});return(0,Ys.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,Ys.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,WE.createPortal)((0,Pr.jsx)("div",{ref:s,className:"menu",style:r,role:"menu",children:i.map((o,l)=>o.kind==="sep"?(0,Pr.jsx)("div",{className:"msep"},l):o.kind==="label"?(0,Pr.jsx)("div",{className:"mlabel",children:o.text},l):(0,Pr.jsxs)("button",{className:`mi${o.danger?" danger":""}`,disabled:o.disabled,role:"menuitem",onClick:()=>{n(),o.onClick()},children:[(0,Pr.jsx)("span",{children:o.label}),o.checked&&(0,Pr.jsx)("span",{className:"mi-check",children:"\u2713"})]},l))}),document.body)}function Hc(){let[e,t]=(0,Ys.useState)(null);return[e,n=>{n.preventDefault(),n.stopPropagation(),t({x:n.clientX,y:n.clientY})},()=>t(null)]}var Ys,WE,Pr,f_=ce(()=>{Ys=oe(Ot(),1),WE=oe(co(),1),Pr=oe(De(),1)});function _s({title:e,children:t,footer:i,onClose:n,wide:s}){return(0,GE.useEffect)(()=>{let r=a=>{a.key==="Escape"&&(a.stopPropagation(),n())};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[n]),(0,$E.createPortal)((0,Vi.jsx)("div",{className:"dlg-scrim",onPointerDown:r=>{r.target===r.currentTarget&&n()},children:(0,Vi.jsxs)("div",{className:"dlg",style:s?{width:560}:void 0,role:"dialog","aria-label":e,children:[(0,Vi.jsx)("div",{className:"dlg-title",children:e}),(0,Vi.jsx)("div",{className:"dlg-body",children:t}),i&&(0,Vi.jsx)("div",{className:"dlg-foot",children:i})]})}),document.body)}function hl({title:e,body:t,okLabel:i,danger:n,onOk:s,onClose:r}){let a=i??w("common.ok");return(0,Vi.jsx)(_s,{title:e,onClose:r,footer:(0,Vi.jsxs)(Vi.Fragment,{children:[(0,Vi.jsx)("button",{className:"btn ghost",onClick:r,children:w("common.cancel")}),(0,Vi.jsx)("button",{className:`btn${n?" danger":" primary"}`,onClick:()=>{r(),s()},children:a})]}),children:(0,Vi.jsx)("div",{className:"dlg-hint",style:{fontSize:"var(--fs-m)",color:"var(--fg)"},children:t})})}var GE,$E,Vi,dl=ce(()=>{GE=oe(Ot(),1),$E=oe(co(),1);xi();Vi=oe(De(),1)});function Me({name:e,size:t=16}){let i=y2[e];return i?(0,p_.jsx)("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,p_.jsx)("path",{d:i})}):null}var p_,y2,Ur=ce(()=>{p_=oe(De(),1),y2={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",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"}});function jE(){let e=YE(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_,S2,YE,ze,vs=ce(()=>{rl();m_=oe(De(),1),S2=0,YE=ms(e=>({list:[],push:(t,i)=>{let n=++S2;e(s=>({list:[...s.list,{id:n,text:t,err:i}]})),setTimeout(()=>e(s=>({list:s.list.filter(r=>r.id!==n)})),3500)}})),ze=(e,t=!1)=>YE.getState().push(e,t)});function w2(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 XE({pendingByThread:e}){let{projects:t,threads:i}=ct(),n=pe(),[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),[v,g]=(0,je.useState)(null),[m,b]=(0,je.useState)(null),[S,x]=(0,je.useState)(null),[C,N,M]=Hc(),[O,F,W]=Hc(),z=(0,je.useRef)({}),I=(0,je.useRef)(null);(0,je.useEffect)(()=>{let L=Ne=>{let he=Ne.detail?.projectId,Be=t.find(J=>J.id===he)??t[0];Be&&g(Be)},Q=()=>_(!0);return window.addEventListener("open-import",L),window.addEventListener("open-new-project",Q),()=>{window.removeEventListener("open-import",L),window.removeEventListener("open-new-project",Q)}},[t]);let R=(0,je.useMemo)(()=>{let L=s.trim().toLowerCase();return L?i.filter(Q=>Q.title.toLowerCase().includes(L)):i},[i,s]),q=(0,je.useMemo)(()=>{let L=new Map;for(let Q of R)(!Q.archived||a[Q.projectId])&&(L.get(Q.projectId)??L.set(Q.projectId,[]).get(Q.projectId)).push(Q);for(let Q of L.values())Q.sort((Ne,he)=>Number(Ne.archived)-Number(he.archived)||Number(he.pinned)-Number(Ne.pinned)||he.updatedAt-Ne.updatedAt);return L},[R,a]),T=(0,je.useMemo)(()=>{let L=new Map;for(let Q of R)Q.archived&&L.set(Q.projectId,(L.get(Q.projectId)??0)+1);return L},[R]);async function D(L){try{let Q=await x2(),Ne=await ll(),he=await te.call("threads.create",{projectId:L,provider:Ne,model:null,mode:Q.defaultMode??"default",effort:Q.defaultEffort??null});n.select(L,he.id)}catch(Q){ze(w("sidebar.failNewThread")+ft(Q),!0)}}function A(L){return[{kind:"item",label:w("common.rename"),onClick:()=>{h(L.id),f(L.title)}},{kind:"item",label:L.pinned?w("sidebar.unpin"):w("sidebar.pin"),onClick:()=>{te.call("threads.update",{id:L.id,pinned:!L.pinned})}},{kind:"item",label:L.archived?w("sidebar.unarchive"):w("sidebar.archive"),onClick:()=>{$(L)}},{kind:"item",label:w("sidebar.exportMd"),onClick:()=>{T2(L)}},{kind:"sep"},{kind:"item",label:w("common.delete"),danger:!0,onClick:()=>b({title:w("sidebar.deleteThread"),body:Ce("sidebar.deleteThreadBody",{title:L.title}),onOk:()=>{te.call("threads.delete",{id:L.id})}})}]}async function $(L){try{await te.call("threads.update",{id:L.id,archived:!L.archived}),L.archived?ze(w("sidebar.unarchived")):(o(Q=>({...Q,[L.projectId]:!0})),ze(w("sidebar.archivedHint")))}catch(Q){ze(ft(Q),!0)}}function re(L){return[{kind:"item",label:w("sidebar.newThread"),onClick:()=>{D(L.id)}},{kind:"item",label:w("sidebar.importHist"),onClick:()=>g(L)},{kind:"item",label:w("common.rename"),onClick:()=>x(L)},{kind:"item",label:w("sidebar.openExplorer"),onClick:()=>{te.call("projects.open",{id:L.id})}},{kind:"sep"},{kind:"item",label:a[L.id]?w("sidebar.hideArchived"):w("sidebar.showArchived"),onClick:()=>o(Q=>({...Q,[L.id]:!Q[L.id]}))},{kind:"sep"},{kind:"item",label:w("sidebar.removeProject"),danger:!0,onClick:()=>b({title:w("sidebar.removeProject"),body:Ce("sidebar.removeProjectBody",{name:L.name}),onOk:()=>{te.call("projects.remove",{id:L.id})}})}]}return(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)("div",{className:"sb-row",children:[(0,X.jsxs)("button",{className:"sb-new",onClick:()=>_(!0),children:[(0,X.jsx)(Me,{name:"plus"})," ",w("sidebar.newProject")]}),(0,X.jsx)("button",{className:"ibtn",title:w("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings")),children:(0,X.jsx)(Me,{name:"settings"})}),(0,X.jsx)("button",{className:"ibtn",title:w("sidebar.searchTitle"),onClick:()=>I.current?.focus(),children:(0,X.jsx)(Me,{name:"search"})})]}),(0,X.jsx)("div",{className:"sb-row",style:{height:32,paddingTop:0},children:(0,X.jsx)("div",{className:"sb-search",children:(0,X.jsx)("input",{ref:I,placeholder:w("sidebar.filterPlaceholder"),value:s,onChange:L=>r(L.target.value),onKeyDown:L=>{L.key==="Escape"&&r("")}})})}),(0,X.jsxs)("div",{className:"sb-list",children:[t.length===0&&(0,X.jsxs)("div",{className:"sb-start",children:[(0,X.jsx)("div",{className:"sb-start-t",children:w("sidebar.noProjectsTitle")}),(0,X.jsx)("div",{className:"sb-start-s",children:w("sidebar.noProjectsSub")}),(0,X.jsx)("button",{className:"btn primary",onClick:()=>_(!0),children:w("sidebar.newProject")})]}),t.map(L=>{let Q=q.get(L.id)??[],Ne=n.collapsed[L.id],he=T.get(L.id)??0,Be=l[L.id]?Q:Q.slice(0,VE);return(0,X.jsxs)("div",{className:"pj-group",children:[(0,X.jsxs)("div",{className:"pj",onContextMenu:J=>{z.current.project=L,N(J)},children:[(0,X.jsxs)("button",{className:"pj-toggle",onClick:()=>n.toggleCollapsed(L.id),children:[(0,X.jsx)("span",{className:`pj-caret${Ne?"":" open"}`,children:(0,X.jsx)(Me,{name:"caret"})}),(0,X.jsx)("span",{className:"pj-badge",children:L.name.slice(0,1)}),(0,X.jsx)("span",{className:"pj-name",children:L.name})]}),(0,X.jsx)("span",{className:"pj-count",children:Q.length||""}),(0,X.jsx)("button",{className:"pj-act",title:w("sidebar.newThread"),onClick:()=>{D(L.id)},children:(0,X.jsx)(Me,{name:"plus"})}),(0,X.jsx)("button",{className:"pj-act",title:w("sidebar.projectMenu"),onClick:J=>{z.current.project=L,N(J)},children:(0,X.jsx)(Me,{name:"dots"})})]}),!Ne&&(0,X.jsxs)("div",{className:"pj-sessions",children:[Be.map(J=>u===J.id?(0,X.jsx)("div",{className:"t-item",children:(0,X.jsx)("input",{className:"t-rename",autoFocus:!0,value:d,onChange:qe=>f(qe.target.value),onBlur:()=>h(null),onKeyDown:qe=>{qe.key==="Enter"&&!Tn(qe.nativeEvent)&&d.trim()?(te.call("threads.update",{id:J.id,title:d.trim()}),h(null)):qe.key==="Escape"&&h(null)}})},J.id):(0,X.jsxs)("button",{className:`t-item${n.currentThreadId===J.id?" on":""}${J.archived?" archived":""}`,onClick:()=>n.select(L.id,J.id),onContextMenu:qe=>{z.current.thread=J,F(qe)},children:[(0,X.jsx)("span",{className:w2(J,e)}),J.pinned&&(0,X.jsx)("span",{className:"t-pin",children:(0,X.jsx)(Me,{name:"pin"})}),(0,X.jsx)("span",{className:"t-title",children:Cd(J.title,J.titleAuto)}),(0,X.jsx)("span",{className:"t-time",children:h_(J.updatedAt)}),(0,X.jsx)("span",{className:"t-more",role:"button",onClick:qe=>{qe.stopPropagation(),z.current.thread=J,F(qe)},children:(0,X.jsx)(Me,{name:"dots"})})]},J.id)),Q.length>VE&&!l[L.id]&&(0,X.jsx)("button",{className:"pj-more",onClick:()=>c(J=>({...J,[L.id]:!0})),children:Ce("sidebar.showAll",{n:Q.length})}),he>0&&(0,X.jsx)("button",{className:"pj-more",onClick:()=>o(J=>({...J,[L.id]:!J[L.id]})),children:a[L.id]?w("sidebar.hideArchived"):Ce("sidebar.archivedN",{n:he})}),Q.length===0&&he===0&&(0,X.jsx)("div",{className:"pj-empty",children:w("sidebar.noThreads")})]})]},L.id)})]}),C&&z.current.project&&(0,X.jsx)(Uc,{x:C.x,y:C.y,items:re(z.current.project),onClose:M}),O&&z.current.thread&&(0,X.jsx)(Uc,{x:O.x,y:O.y,items:A(z.current.thread),onClose:W}),p&&(0,X.jsx)(C2,{onClose:()=>_(!1)}),v&&(0,X.jsx)(k2,{project:v,onClose:()=>g(null)}),m&&(0,X.jsx)(hl,{title:m.title,body:m.body,danger:!0,onOk:m.onOk,onClose:()=>b(null)}),S&&(0,X.jsx)(E2,{project:S,onClose:()=>x(null)})]})}function E2({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=>ze(w("sidebar.failRename")+ft(a),!0))};return(0,X.jsx)(_s,{title:w("sidebar.renameProject"),onClose:t,footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("button",{className:"btn ghost",onClick:t,children:w("common.cancel")}),(0,X.jsx)("button",{className:"btn primary",disabled:!s,onClick:r,children:w("common.save")})]}),children:(0,X.jsxs)("div",{className:"dlg-row",children:[(0,X.jsx)("label",{children:w("sidebar.projectName")}),(0,X.jsx)("input",{className:"tinput",autoFocus:!0,value:i,onChange:a=>n(a.target.value),onKeyDown:a=>{a.key==="Enter"&&!Tn(a.nativeEvent)&&r()}})]})})}function x2(){return te.call("settings.get").then(e=>e).catch(()=>({}))}function C2({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=pe();(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){ze(w("sidebar.failAddProject")+ft(d),!0),l(!1)}}}return(0,X.jsxs)(_s,{title:w("sidebar.newProjectDlg"),onClose:e,footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("button",{className:"btn ghost",onClick:e,children:w("common.cancel")}),(0,X.jsx)("button",{className:"btn primary",disabled:!u||o,onClick:()=>{h()},children:w("common.add")})]}),children:[(0,X.jsxs)("div",{className:"dlg-row",children:[(0,X.jsx)("label",{children:w("sidebar.dirLabel")}),(0,X.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,X.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"&&!Tn(d.nativeEvent)&&h()}}),(0,X.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&&ze(w("sidebar.pickFolderUnsupported"))}).catch(()=>ze(w("sidebar.pickFolderFailed")))},children:w("common.browse")})]}),n&&!n.exists&&(0,X.jsx)("div",{className:"dlg-hint err",children:w("sidebar.dirMissing")}),n&&n.exists&&!n.isDir&&(0,X.jsx)("div",{className:"dlg-hint err",children:w("sidebar.notDir")}),u&&(0,X.jsx)("div",{className:"dlg-hint",children:w("sidebar.dirOk")})]}),r.length>0&&(0,X.jsxs)("div",{className:"dlg-row",children:[(0,X.jsx)("label",{children:w("sidebar.recent")}),r.map(d=>(0,X.jsx)("button",{className:"mi",style:{height:26},onClick:()=>i(d),children:d},d))]})]})}function k2({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=pe();(0,je.useEffect)(()=>{te.call("history.list",{projectId:e.id}).then(h=>n(h)).catch(h=>{ze(w("sidebar.failImportList")+ft(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}))});ze(Ce("sidebar.importedN",{n:d.length})),d.length>0&&l.select(e.id,d[d.length-1].id),t()}catch(h){ze(w("sidebar.failImport")+ft(h),!0)}finally{o(!1)}}}return(0,X.jsxs)(_s,{title:Ce("sidebar.importTitle",{name:e.name}),onClose:t,wide:!0,footer:(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)("button",{className:"btn ghost",onClick:t,children:w("common.cancel")}),(0,X.jsx)("button",{className:"btn primary",disabled:a||s.size===0,onClick:()=>{u()},children:a?w("sidebar.importing"):Ce("sidebar.importN",{n:s.size||0})})]}),children:[i===null&&(0,X.jsx)("div",{className:"dlg-hint",children:w("sidebar.scanning")}),i!==null&&i.length===0&&(0,X.jsx)("div",{className:"dlg-hint",children:w("sidebar.importEmpty")}),i!==null&&i.length>0&&(0,X.jsx)("div",{className:"imp-list",children:i.map(h=>(0,X.jsxs)("label",{className:`imp-row${h.imported?" done":""}`,children:[(0,X.jsx)("input",{type:"checkbox",disabled:h.imported,checked:s.has(h.sessionId),onChange:()=>c(h.sessionId)}),(0,X.jsx)("span",{className:"imp-title",children:h.title}),(0,X.jsxs)("span",{className:"imp-meta",children:[h.provider," \xB7 ",h.messageCount,w("common.messages")," \xB7 ",h_(h.updatedAt),h.imported?w("common.imported"):""]})]},h.sessionId))})]})}async function T2(e){try{let t=await te.call("thread.exportMarkdown",{id:e.id});if(t.path){ze(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){ze(w("sidebar.failExport")+ft(t),!0)}}var je,X,VE,ZE=ce(()=>{je=oe(Ot(),1);cl();Wn();un();Nn();Od();f_();dl();Ur();vs();xi();X=oe(De(),1),VE=10});function v_(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function lx(e){Ia=e}function Oa(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 ye(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 hn(e,t){if(t){if(Zt.escapeTest.test(e))return e.replace(Zt.escapeReplace,tx)}else if(Zt.escapeTestNoEncode.test(e))return e.replace(Zt.escapeReplaceNoEncode,tx);return e}function kL(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 ix(e){try{e=encodeURI(e).replace(Zt.percentDecode,"%")}catch{return null}return e}function nx(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,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 Id(e){return e.trim().toLowerCase().toUpperCase().toLowerCase()}function rx(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 Dd(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 ax(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 TL(e,t,i){let n=e.match(i.other.indentCodeCompensation);if(n===null)return t;let s=n[1];return t.split(` +`)}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 ox(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 Ra(e,t){if(Array.isArray(t))for(let i=0;i{Ia=v_();Da={exec:()=>null};N2=((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:Oa(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Oa(e=>new RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:Oa(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Oa(e=>new RegExp(`^ {0,${e}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:Oa(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Oa(e=>new RegExp(`^ {0,${e}}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|new RegExp(`^ {0,${e}}>`))},A2=/^(?:[ \t]*(?:\n|$))+/,M2=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,O2=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Kc=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,R2=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,b_=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,cx=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ux=ye(cx).replace(/bull/g,b_).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(),D2=ye(cx).replace(/bull/g,b_).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(),y_=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,L2=/^[^\n]+/,S_=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,B2=ye(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",S_).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),I2=ye(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,b_).getRegex(),Wc="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",w_=/|$))/,z2=ye("^ {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",w_).replace("tag",Wc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),hx=e=>ye(y_).replace("hr",Kc).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",U2).getRegex(),E_={blockquote:H2,code:M2,def:B2,fences:O2,heading:R2,hr:Kc,html:z2,lheading:ux,list:I2,newline:A2,paragraph:P2,table:Da,text:L2},QE=ye("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Kc).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",w_).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:Da,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ye(y_).replace("hr",Kc).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",ux).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},K2=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,W2=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,dx=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,G2=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",N2?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),px=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Z2=ye(px,"u").replace(/punct/g,bs).getRegex(),Q2=ye(px,"u").replace(/punct/g,fx).getRegex(),J2=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,eL=ye(J2,"u").replace(/openQuote/g,Y2).replace(/punct/g,bs).getRegex(),mx="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",tL=ye(mx,"gu").replace(/notPunctSpace/g,Gc).replace(/punctSpace/g,ml).replace(/punct/g,bs).getRegex(),iL=ye(mx,"gu").replace(/notPunctSpace/g,V2).replace(/punctSpace/g,j2).replace(/punct/g,fx).getRegex(),nL="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",sL=ye(nL,"gu").replace(/notPunctSpace/g,Gc).replace(/punctSpace/g,ml).replace(/punct/g,bs).getRegex(),rL=ye("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Gc).replace(/punctSpace/g,ml).replace(/punct/g,bs).getRegex(),aL="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",oL=ye(aL,"gu").replace(/notPunctSpace/g,Gc).replace(/punctSpace/g,ml).replace(/punct/g,bs).getRegex(),lL=ye(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,bs).getRegex(),cL="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",uL=ye(cL,"gu").replace(/notPunctSpace/g,Gc).replace(/punctSpace/g,ml).replace(/punct/g,bs).getRegex(),hL=ye(/\\(punct)/,"gu").replace(/punct/g,bs).getRegex(),dL=ye(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,bs).getRegex(),fL=ye(/^<(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(),pL=ye(w_).replace("(?:-->|$)","-->").getRegex(),mL=ye("^comment|^|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",pL).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),gx=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,Bd=ye(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",gx).getRegex(),gL=ye(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",Bd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),_L=ye(/^!?\[(label)\]\[(ref)\]/).replace("label",Bd).replace("ref",S_).getRegex(),vL=ye(/^!?\[(ref)\](?:\[\])?/).replace("ref",S_).getRegex(),JE=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,bL=ye(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",gx).getRegex(),yL=ye("reflink|nolink(?!\\()","g").replace("reflink",ye(/^!?\[(label)\]\[(ref)\]/).replace("label",bL).replace("ref",JE).getRegex()).replace("nolink",ye(/^!?\[(ref)\](?:\[\])?/).replace("ref",JE).getRegex()).getRegex(),ex=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,SL=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,wL=ye(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,SL).getRegex(),x_={_backpedal:Da,anyPunctuation:hL,anyPunctuationOutsideCode:dL,autolink:fL,blockSkip:X2,br:dx,code:W2,del:Da,delLDelim:Da,delRDelim:Da,emStrongLDelim:Z2,emStrongRDelimAst:tL,emStrongRDelimUnd:rL,escape:K2,link:gL,nolink:vL,punctuation:$2,reflink:_L,reflinkSearch:yL,tag:mL,text:G2,url:Da},EL={...x_,emStrongLDelim:eL,emStrongRDelimAst:sL,emStrongRDelimUnd:oL,link:ye(/^!?\[(label)\]\((.*?)\)/).replace("label",Bd).getRegex(),reflink:ye(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Bd).getRegex()},g_={...x_,emStrongRDelimAst:iL,emStrongLDelim:Q2,delLDelim:lL,delRDelim:uL,url:ye(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",wL).replace("protocol",ex).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:ye(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},tx=e=>CL[e];fl=class{constructor(e){de(this,"options");de(this,"rules");de(this,"lexer");this.options=e||Ia}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]:sx(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=TL(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=Hr(i,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceTabChar.test(n))&&(i=n.trim())}return{type:"heading",raw:Hr(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:Hr(t[0],` -`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Hr(t[0],` +`)}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],` `).split(` `),n="",s="",r=[];for(;i.length>0;){let a=!1,o=[],l;for(l=0;lp+Dd(_,p.length)).replace(this.rules.other.blockquoteSetextReplace,` +`),u=c.replace(this.rules.other.blockquoteMarkerWhitespace,(f,p,_)=>p+Fd(_,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(` `),_=f.raw+` -`+p.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(_);r[r.length-1]=v;let g=_.substring(v.raw.length).replace(/^\n/,""),m=g?g.split(` -`).length:0,b=m?i.slice(0,-m):i;b.length>0&&(n=`${n} -${b.join(` -`)}`),s=s.substring(0,s.length-f.text.length)+v.text;break}else if(d?.type==="list"){let f=d,p=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+` `+i.join(` -`),_=this.list(p);r[r.length-1]=_;let v=_.raw.length>f.raw.length?p.slice(f.raw.length+1,_.raw.length).split(` -`).length:0;if(v>0){let g=i.slice(0,v).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(` `);n=`${n} ${g}`,s=`${s} -${g}`}i=i.slice(v);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?Dd(f,p):f.replace(this.rules.other.leadingSpaceTab,S=>Dd(S,p)),v=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(v)&&(e=e.substring(v.length+1),u=!0),!u){let S=this.rules.other.nextBulletRegex(m),x=this.rules.other.hrRegex(m),C=this.rules.other.fencesBeginRegex(m),N=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(m):this.rules.other.headingBeginRegex(m),M=this.rules.other.htmlBeginRegex(m),O=this.rules.other.blockquoteBeginRegex(m);for(;e;){let F=e.split(` -`,1)[0],W;if(v=F,this.options.pedantic?(v=v.replace(this.rules.other.listReplaceNesting," "),W=v):W=v.replace(this.rules.other.leadingSpaceTab,z=>Dd(z)),C.test(v)||N.test(v)||M.test(v)||O.test(v)||S.test(v)||x.test(v))break;if(W.search(this.rules.other.nonSpaceChar)>=m||!v.trim())h+=` -`+W.slice(m);else{if(g||_.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||C.test(_)||N.test(_)||x.test(_))break;let z=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(v)&&this.rules.block.lheading.test(`${_} -${v}`)?` ${W.replace(/^ {0,3}/,"")}`:v;h+=` -`+z}g=!v.trim(),e=e.substring(F.length+1),_=W.slice(m)}}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=sx(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])&&rx(t[2],"()")!==-1)return;let i=Id(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:Hr(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=nx(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:Hr(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:Hr(t[0],` +${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],` `),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&&ox(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=Hr(n.slice(0,-1),"\\");if((n.length-a.length)%2===0)return}else{let a=rx(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)),ax(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&&ox(e,i[1],n,this.rules))return;let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[Id(s)];if(!r){let a=i[0].charAt(0);return{type:"text",raw:a,text:a}}return ax(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+_+v);let S=[...n[0]][0].length,x=e.slice(0,d+n.index+S+p);if(Math.min(d,p)%2){let N=x.slice(1,-1);return{type:"em",raw:x,text:N,tokens:this.lexer.inlineTokens(N)}}let C=x.slice(2,-2);return{type:"strong",raw:x,text:C,tokens:this.lexer.inlineTokens(C)}}}}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]:kL(t[0]),escaped:i}}}},Gn=(La=class{constructor(t){Xb(this,pl);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||Ia,this.options.tokenizer=this.options.tokenizer||new fl,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:Rd.normal,inline:Fc.normal};this.options.pedantic?(i.block=Rd.pedantic,i.inline=Fc.pedantic):this.options.gfm&&(i.block=Rd.gfm,this.options.breaks?i.inline=Fc.breaks:i.inline=Fc.gfm),this.tokenizer.rules=i}static get rules(){return{block:Rd,inline:Fc}}static lex(t,i){return new La(i).lex(t)}static lexInline(t,i){return new La(i).inlineTokens(t)}lex(t){t=t.replace(Zt.carriageReturn,` +`?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(` `)?"":` @@ -57,9 +57,9 @@ ${v}`)?` ${W.replace(/^ {0,3}/,"")}`:v;h+=` `+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(` `)?"":` `)+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,Id(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 tp(this,pl,_x).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)}},pl=new WeakSet,_x=function(t,i){let n=t.includes("*")||t.includes("_")||t.includes("~")||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==fl.prototype.emStrong||this.tokenizer.del!==fl.prototype.del?tp(this,pl,vx).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},vx=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,Id(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},La),zd=class{constructor(e){de(this,"options");de(this,"parser");this.options=e||Ia}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:hn(s,!0))+`
-`:"
"+(i?s:hn(s,!0))+`
+`+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))+`
`}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)} @@ -75,28 +75,30 @@ ${this.parser.parse(e)} `}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`${hn(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?hn(i,!0):this.parser.parseInline(n),a=ix(e);if(a===null)return r;e=hn(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=ix(e);if(s===null)return hn(i);e=s;let r=`${hn(i)}{let a=s[r].flat(1/0);Ra(i,this.walkTokens(a,t))}):s.tokens&&Ra(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 zd(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 fl(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 qc;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];qc.passThroughHooks.has(r)?s[a]=c=>{if(s.options.async&&qc.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&&Ra(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 Gn.lex(e,t??this.defaults)}parser(e,t){return $n.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?Gn.lex:Gn.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?$n.parse:$n.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?Gn.lex:Gn.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?$n.parse:$n.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:

"+hn(i.message+"",!0)+"
";return t?Promise.resolve(n):n}if(t)return Promise.reject(i);throw i}}},Ba=new NL;Ve.options=Ve.setOptions=function(e){return Ba.setOptions(e),Ve.defaults=Ba.defaults,lx(Ve.defaults),Ve};Ve.getDefaults=v_;Ve.defaults=Ia;Ve.use=AL;Ve.walkTokens=function(e,t){return Ba.walkTokens(e,t)};Ve.parseInline=Ba.parseInline;Ve.Parser=$n;Ve.parser=$n.parse;Ve.Renderer=zd;Ve.TextRenderer=C_;Ve.Lexer=Gn;Ve.lexer=Gn.lex;Ve.Tokenizer=fl;Ve.Hooks=qc;Ve.parse=Ve;iU=Ve.options,nU=Ve.setOptions,sU=Ve.walkTokens,rU=Ve.parseInline,aU=$n.parse,oU=Gn.lex});function ML(e,t){this.v=e,this.k=t}function yx(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]:za;if(Sx&&Sx(e,null),!_l(t))return e;let n=t.length;for(;n--;){let s=t[n];if(typeof s=="string"){let r=i(s);r!==s&&(IL(t)||(t[n]=r),s=r)}e[s]=!0}return e}function KL(e){for(let t=0;t0&&arguments[0]!==void 0?arguments[0]:a3(),t=K=>Hx(K);if(t.version="3.4.17",t.removed=[],!e||!e.document||e.document.nodeType!==Bt.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=An(h,"cloneNode"),f=An(h,"remove"),p=An(h,"removeAttributeNode"),_=An(h,"nextSibling"),v=An(h,"childNodes"),g=An(h,"parentNode"),m=An(h,"shadowRoot"),b=An(h,"attributes"),S=a&&a.prototype?An(a.prototype,"nodeType"):null,x=a&&a.prototype?An(a.prototype,"nodeName"):null,C=a&&a.prototype?An(a.prototype,"ownerDocument"):null,N=function(y){return S?S(y):y.nodeType},M=function(y){return x?x(y):y.nodeName},O=GL(h,"namespaceURI"),F=function(y){return O?O(y):y.namespaceURI};if(typeof r=="function"){let K=i.createElement("template");K.content&&K.content.ownerDocument&&(i=K.content.ownerDocument)}let W,z="",I,R=!1,q=0,T=function(){if(q>0)throw Vs('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.')},D=function(y){T(),q++;try{return W.createHTML(y)}finally{q--}},A=function(y){T(),q++;try{return W.createScriptURL(y)}finally{q--}},$=function(){return R||(I=o3(u,s),R=!0),I},re=i,L=re.implementation,Q=re.createNodeIterator,Ne=re.createDocumentFragment,he=re.getElementsByTagName,Be=n.importNode,J=Lx();t.isSupported=typeof Bx=="function"&&typeof g=="function"&&L&&L.createHTMLDocument!==void 0;let qe=VL,dt=XL,oi=ZL,Ai=QL,Mi=JL,li=e3,we=t3,yi=n3,ci=Ox,ue=null,ui=He({},[...Tx,...A_,...M_,...O_,...Nx]),ie=null,Xn=He({},[...Ax,...R_,...Mx,...Ud]),$e=Object.seal(gl(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}})),Pe=null,In=null,Pt=Object.seal(gl(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Ns=!0,As=!0,ee=!1,E=!0,G=!1,V=!0,ae=!1,Ue=!1,Ui=null,Zn=null,Pf=!1,Qa=!1,Au=!1,Mu=!1,xb=!0,Cb=!1,kb="user-content-",Uf=!0,Hf=!1,Jr=null,Ja={},ea=null,Tb=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"]),Nb=null,Ab=He({},["audio","video","img","source","image","track"]),Mb=null,Ob=He({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ou="http://www.w3.org/1998/Math/MathML",Ru="http://www.w3.org/2000/svg",Qn="http://www.w3.org/1999/xhtml",eo=Qn,Ff=!1,qf=null,_M=He({},[Ou,Ru,Qn],N_),Rb=Qt(["mi","mo","mn","ms","mtext"]),Kf=He({},Rb),Db=Qt(["annotation-xml"]),Wf=He({},Db),vM=He({},["title","style","font","a","script"]),Dl=null,bM=["application/xhtml+xml","text/html"],yM="text/html",Tt=null,to=null,SM=i.createElement("form"),Lb=function(y){return y instanceof RegExp||y instanceof Function},Gf=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(to&&to===y)return;(!y||typeof y!="object")&&(y={}),y=dn(y),Dl=bM.indexOf(y.PARSER_MEDIA_TYPE)===-1?yM:y.PARSER_MEDIA_TYPE,Tt=Dl==="application/xhtml+xml"?N_:za,ue=Fr(y,"ALLOWED_TAGS",ui,{transform:Tt}),ie=Fr(y,"ALLOWED_ATTR",Xn,{transform:Tt}),qf=Fr(y,"ALLOWED_NAMESPACES",_M,{transform:N_}),Mb=Fr(y,"ADD_URI_SAFE_ATTR",Ob,{transform:Tt,base:Ob}),Nb=Fr(y,"ADD_DATA_URI_TAGS",Ab,{transform:Tt,base:Ab}),ea=Fr(y,"FORBID_CONTENTS",Tb,{transform:Tt}),Pe=Fr(y,"FORBID_TAGS",dn({}),{transform:Tt}),In=Fr(y,"FORBID_ATTR",dn({}),{transform:Tt}),Ja=Xi(y,"USE_PROFILES")?y.USE_PROFILES&&typeof y.USE_PROFILES=="object"?dn(y.USE_PROFILES):y.USE_PROFILES:!1,Ns=y.ALLOW_ARIA_ATTR!==!1,As=y.ALLOW_DATA_ATTR!==!1,ee=y.ALLOW_UNKNOWN_PROTOCOLS||!1,E=y.ALLOW_SELF_CLOSE_IN_ATTR!==!1,G=y.SAFE_FOR_TEMPLATES||!1,V=y.SAFE_FOR_XML!==!1,ae=y.WHOLE_DOCUMENT||!1,Qa=y.RETURN_DOM||!1,Au=y.RETURN_DOM_FRAGMENT||!1,Mu=y.RETURN_TRUSTED_TYPE||!1,Pf=y.FORCE_BODY||!1,xb=y.SANITIZE_DOM!==!1,Cb=y.SANITIZE_NAMED_PROPS||!1,Uf=y.KEEP_CONTENT!==!1,Hf=y.IN_PLACE||!1,ci=$L(y.ALLOWED_URI_REGEXP)?y.ALLOWED_URI_REGEXP:Ox,eo=typeof y.NAMESPACE=="string"?y.NAMESPACE:Qn,Kf=L_(y,"MATHML_TEXT_INTEGRATION_POINTS",()=>He({},Rb)),Wf=L_(y,"HTML_INTEGRATION_POINTS",()=>He({},Db));let k=L_(y,"CUSTOM_ELEMENT_HANDLING",()=>gl(null));if($e=gl(null),Xi(k,"tagNameCheck")&&Lb(k.tagNameCheck)&&($e.tagNameCheck=k.tagNameCheck),Xi(k,"attributeNameCheck")&&Lb(k.attributeNameCheck)&&($e.attributeNameCheck=k.attributeNameCheck),Xi(k,"allowCustomizedBuiltInElements")&&typeof k.allowCustomizedBuiltInElements=="boolean"&&($e.allowCustomizedBuiltInElements=k.allowCustomizedBuiltInElements),bi($e),G&&(As=!1),Au&&(Qa=!0),Ja&&(ue=He({},Nx),ie=gl(null),Ja.html===!0&&(He(ue,Tx),He(ie,Ax)),Ja.svg===!0&&(He(ue,A_),He(ie,R_),He(ie,Ud)),Ja.svgFilters===!0&&(He(ue,M_),He(ie,R_),He(ie,Ud)),Ja.mathMl===!0&&(He(ue,O_),He(ie,Mx),He(ie,Ud))),Pt.tagCheck=null,Pt.attributeCheck=null,Xi(y,"ADD_TAGS")&&(typeof y.ADD_TAGS=="function"?Pt.tagCheck=y.ADD_TAGS:_l(y.ADD_TAGS)&&(ue===ui&&(ue=dn(ue)),He(ue,y.ADD_TAGS,Tt))),Xi(y,"ADD_ATTR")&&(typeof y.ADD_ATTR=="function"?Pt.attributeCheck=y.ADD_ATTR:_l(y.ADD_ATTR)&&(ie===Xn&&(ie=dn(ie)),He(ie,y.ADD_ATTR,Tt))),Xi(y,"ADD_FORBID_CONTENTS")&&_l(y.ADD_FORBID_CONTENTS)&&(ea===Tb&&(ea=dn(ea)),He(ea,y.ADD_FORBID_CONTENTS,Tt)),Uf&&(ue["#text"]=!0),ae&&He(ue,["html","head","body"]),ue.table&&(He(ue,["tbody"]),delete Pe.tbody),y.TRUSTED_TYPES_POLICY){if(typeof y.TRUSTED_TYPES_POLICY.createHTML!="function")throw Vs('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof y.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Vs('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let U=W;W=y.TRUSTED_TYPES_POLICY;try{z=D("")}catch(H){throw W=U,H}}else y.TRUSTED_TYPES_POLICY===null?(W=void 0,z=""):(W===void 0&&(W=$()),W&&typeof z=="string"&&(z=D("")));Qt&&Qt(y),to=y},Bb=He({},[...A_,...M_,...YL]),Ib=He({},[...O_,...jL]),wM=function(y,k,U){return k.namespaceURI===Qn?y==="svg":k.namespaceURI===Ou?y==="svg"&&(U==="annotation-xml"||Kf[U]):!!Bb[y]},EM=function(y,k,U){return k.namespaceURI===Qn?y==="math":k.namespaceURI===Ru?y==="math"&&Wf[U]:!!Ib[y]},xM=function(y,k,U){return k.namespaceURI===Ru&&!Wf[U]||k.namespaceURI===Ou&&!Kf[U]?!1:!Ib[y]&&(vM[y]||!Bb[y])},CM=function(y){let k=F(y),U=za(M(y)),H=g(y),le,me;return H&&N(H)===Bt.element?(le={namespaceURI:F(H)},me=za(M(H))):(le={namespaceURI:eo},me="template"),qf[k]?k===Ru?wM(U,le,me):k===Ou?EM(U,le,me):k===Qn?xM(U,le,me):!!(Dl==="application/xhtml+xml"&&qf[k]):!1},sr=function(y){$c(t.removed,{element:y});try{g(y).removeChild(y)}catch{if(f(y),!g(y))throw Vs("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},zb=function(y,k,U){try{p(y,k)}catch{try{y.removeAttribute(U)}catch{}}},$f=function(y){jf(y);let k=v(y);k&&js(PL(k),H=>{try{f(H)}catch{}});let U=N(y)===Bt.element?b(y):null;if(U)for(let H=U.length-1;H>=0;--H){let le=U[H],me=le&&le.name;typeof me=="string"&&zb(y,le,me)}},io=function(y,k,U){if(!U)try{U=k.getAttributeNode(y)}catch{U=null}$c(t.removed,{attribute:U||null,from:k});try{U?p(k,U):k.removeAttribute(y)}catch{try{k.removeAttribute(y)}catch{}}if(y==="is")if(Qa||Au)try{sr(k)}catch{}else try{k.setAttribute(y,"")}catch{}},Pb=function(y){let k=b(y);if(k)for(let U=k.length-1;U>=0;--U){let H=k[U],le=H&&H.name;typeof le!="string"||ie[Tt(le)]||zb(y,H,le)}},Yf=function(y,k){let U=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,H=[y];for(;H.length>0;){let le=H.pop();if(k(le)===!1)continue;if(U&&N(le)===Bt.element){let Ae=m(le);rr(Ae)&&H.push(Ae)}let me=v(le);if(me)for(let Ae=me.length-1;Ae>=0;--Ae)H.push(me[Ae])}},jf=function(y){Yf(y,k=>{N(k)===Bt.element&&Pb(k)})},Vf=function(y){let k=[];return Yf(y,U=>{k.push(U)},!0),k},kM=function(y,k){let U=k_();js(Vf(y),H=>{N(H)===Bt.element&&T_(U,H)}),js(k,H=>{N(H)===Bt.element&&!Yc(U,H)&&Pb(H)})},Ub=function(y,k){let U=!1;return js(t.removed,H=>{H.element&&(U=U||H.element===y,jf(H.element))}),kM(y,k),U},TM=8,NM=function(y,k){let U=Jr,H=null,le=()=>(H||(H=k_(),js(k,me=>{T_(H,me)})),H);for(let me=0;;me++){let Ae=Vf(y),Ut=[y],Jn=!1;if(js(Ae,Oi=>{N(Oi)===Bt.documentFragment?$c(Ut,Oi):!Jn&&!Yc(U,Oi)&&(Jn=Yc(le(),Oi))}),!Jn)return;if(me>=TM)throw Vs("the tree kept changing during in-place sanitization; refusing to return it");js(Ut,(Oi,Hi)=>{AM(Oi,Hi>0,y,le())})}},AM=function(y,k,U,H){let le=Xf(y),me;for(;me=le.nextNode();)!Yc(H,me)||Yc(Jr,me)||(k&&zn(J.uponSanitizeShadowNode,me,null),Qf(me,U),Jf(me,U),rr(me.content)&&Bl(me.content))},MM=function(y){Jr&&T_(Jr,y)},Hb=function(y,k){return V?y==="patchsrc"?!0:y==="for"&&k!=="label"&&k!=="output":!1},OM=function(y){V&&Yf(y,k=>{let U=N(k);if(U===Bt.processingInstruction||U===Bt.comment&&vi(Rx,k.data)){try{f(k)}catch{}return!1}if(U===Bt.element){let H=k,le=Tt(M(k));try{H.hasAttribute&&H.hasAttribute("patchsrc")&&H.removeAttribute("patchsrc"),H.hasAttribute&&H.hasAttribute("for")&&Hb("for",le)&&H.removeAttribute("for")}catch{}}return!0})},Fb=function(y){let k=null,U=null;if(Pf)y=""+y;else{let me=Ex(y,/^[\r\n\t ]+/);U=me&&me[0]}Dl==="application/xhtml+xml"&&eo===Qn&&(y=''+y+"");let H=W?D(y):y;if(eo===Qn)try{k=new c().parseFromString(H,Dl)}catch{}if(!k||!k.documentElement){k=L.createDocument(eo,"template",null);try{k.documentElement.innerHTML=Ff?z:H}catch{}}let le=k.body||k.documentElement;return y&&U&&le.insertBefore(i.createTextNode(U),le.childNodes[0]||null),eo===Qn?he.call(k,ae?"html":"body")[0]:ae?k.documentElement:le},Xf=function(y){let k=C?C(y):y.ownerDocument;return Q.call(k||y,y,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Du=function(y){return y=jc(y,qe," "),y=jc(y,dt," "),y=jc(y,oi," "),y},Zf=function(y){var k;qb(y);let U=(k=y.querySelectorAll)===null||k===void 0?void 0:k.call(y,"template");U&&js(U,H=>{rr(H.content)&&Zf(H.content)})},qb=function(y){y.normalize();let k=C?C(y):y.ownerDocument,U=Q.call(k||y,y,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),H=U.nextNode();for(;H;)H.data=Du(H.data),H=U.nextNode()},Lu=function(y){let k=x?x(y):null;return typeof k!="string"||Tt(k)!=="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!==S(y)||y.childNodes!==v(y)},rr=function(y){if(!S||typeof y!="object"||y===null)return!1;try{return S(y)===Bt.documentFragment}catch{return!1}},Ll=function(y){if(!S||typeof y!="object"||y===null)return!1;try{return typeof S(y)=="number"}catch{return!1}};function zn(K,y,k){K.length!==0&&js(K,U=>{U.call(t,y,k,to)})}let RM=function(y,k){return!!(V&&y.hasChildNodes()&&!Ll(y.firstElementChild)&&vi(D_,y.textContent)&&vi(D_,y.innerHTML)||V&&r3[k]&&N(y)===Bt.element&&F(y)===Qn&&(Ll(y.firstElementChild)||typeof y.textContent=="string"&&vi(D_,y.textContent))||y.nodeType===Bt.processingInstruction||V&&y.nodeType===Bt.comment&&vi(Rx,y.data))},Bu=function(y,k){if(y instanceof RegExp)return vi(y,k);if(y instanceof Function){for(var U=arguments.length,H=new Array(U>2?U-2:0),le=2;le=0;--Ae){let Ut=y===U?d(le[Ae],!0):le[Ae];H.insertBefore(Ut,_(y))}}}return sr(y),!0},Kb=function(y,k,U,H){return y.length===0?k:k===U||k===H?dn(k):k},no=function(y,k){return y===k||g(y)!==null?!1:(Hf&&jf(y),!0)},Qf=function(y,k){if(MM(y),zn(J.beforeSanitizeElements,y,null),no(y,k))return!0;if(Lu(y))return sr(y),!0;let U=Tt(M(y));if(ue=Kb(J.uponSanitizeElement,ue,ui,Ui),zn(J.uponSanitizeElement,y,{tagName:U,allowedTags:ue}),no(y,k))return!0;if(RM(y,U))return sr(y),!0;if(Pe[U]||!(Pt.tagCheck instanceof Function&&Pt.tagCheck(U))&&!ue[U]){let H=DM(y,U,k);return H===!1&&(zn(J.afterSanitizeElements,y,null),no(y,k))?!0:H}if(N(y)===Bt.element&&!CM(y)||(U==="noscript"||U==="noembed"||U==="noframes")&&vi(s3,y.innerHTML))return sr(y),!0;if(G&&y.nodeType===Bt.text){let H=Du(y.textContent);y.textContent!==H&&($c(t.removed,{element:y.cloneNode()}),y.textContent=H)}return zn(J.afterSanitizeElements,y,null),no(y,k)},Wb=function(y,k,U){if(In[k]||Hb(k,y)||xb&&(k==="id"||k==="name")&&(U in i||U in SM))return!1;let H=ie[k]||Pt.attributeCheck instanceof Function&&Pt.attributeCheck(k,y);return As&&vi(Ai,k)||Ns&&vi(Mi,k)?!0:H?Mb[k]||vi(ci,jc(U,we,""))||(k==="src"||k==="xlink:href"||k==="href")&&y!=="script"&&xx(U,"data:")===0&&Nb[y]||ee&&!vi(li,jc(U,we,""))?!0:!U:Gb(y)&&Bu($e.tagNameCheck,y)&&Bu($e.attributeNameCheck,k,y)||k==="is"&&$e.allowCustomizedBuiltInElements&&Bu($e.tagNameCheck,U)},LM=He({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Gb=function(y){return!LM[za(y)]&&vi(yi,y)},BM=function(y,k,U,H){if(W&&typeof u=="object"&&typeof u.getAttributeType=="function"&&!U)switch(u.getAttributeType(y,k)){case"TrustedHTML":return D(H);case"TrustedScriptURL":return A(H)}return H},IM=function(y,k,U,H){try{return U?y.setAttributeNS(U,k,H):y.setAttribute(k,H),Lu(y)?(sr(y),!1):!0}catch{return io(k,y),!1}},$b=function(y,k){return V&&vi(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,k)?!0:za(y)==="attributename"&&Ex(k,"href")!==null},Jf=function(y,k){if(zn(J.beforeSanitizeAttributes,y,null),no(y,k))return;let U=y.attributes;if(!U||Lu(y))return;ie=Kb(J.uponSanitizeAttribute,ie,Xn,Zn);let H={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ie,forceKeepAttr:void 0},le=U.length,me=Tt(y.nodeName);for(;le--;){let Ae=U[le],Ut=Ae.name,Jn=Ae.namespaceURI,Oi=Ae.value,Hi=Tt(Ut),so=Oi,Fi=Ut==="value"?so:HL(so),Yb=!1;if(H.attrName=Hi,H.attrValue=Fi,H.keepAttr=!0,H.forceKeepAttr=void 0,zn(J.uponSanitizeAttribute,y,H),Fi=H.attrValue,Cb&&(Hi==="id"||Hi==="name")&&xx(Fi,kb)!==0&&(io(Ut,y,Ae),Fi=kb+Fi,Yb=!0),$b(Ut,Fi)){io(Ut,y,Ae);continue}if(!H.forceKeepAttr){if(!H.keepAttr){io(Ut,y,Ae);continue}if(!E&&vi(Dx,Fi)){io(Ut,y,Ae);continue}if(G&&(Fi=Du(Fi)),!Wb(me,Hi,Fi)){io(Ut,y,Ae);continue}Fi=BM(me,Hi,Jn,Fi),Fi!==so&&IM(y,Ut,Jn,Fi)&&Yb&&wx(t.removed)}}zn(J.afterSanitizeAttributes,y,null),no(y,k)},Bl=function(y){let k=null,U=Xf(y);for(zn(J.beforeSanitizeShadowDOM,y,null);k=U.nextNode();)if(zn(J.uponSanitizeShadowNode,k,null),Qf(k,y),Jf(k,y),rr(k.content)&&Bl(k.content),N(k)===Bt.element){let H=m(k);rr(H)&&(ep(H),Bl(H))}G&&qb(y),zn(J.afterSanitizeShadowDOM,y,null)},ep=function(y){let k=[{node:y,shadow:null}];for(;k.length>0;){let U=k.pop();if(U.shadow){Bl(U.shadow);continue}let H=U.node,le=N(H)===Bt.element,me=v(H);if(me)for(let Ae=me.length-1;Ae>=0;--Ae)k.push({node:me[Ae],shadow:null});if(le){let Ae=x?x(H):null;if(typeof Ae=="string"&&Tt(Ae)==="template"){let Ut=H.content;rr(Ut)&&k.push({node:Ut,shadow:null})}}if(le){let Ae=m(H);rr(Ae)&&k.push({node:null,shadow:Ae},{node:Ae,shadow:null})}}};return t.sanitize=function(K){let y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=null,U=null,H=null,le=null;if(Ff=!K,Ff&&(K=""),typeof K!="string"&&!Ll(K)&&(K=WL(K),typeof K!="string"))throw Vs("dirty is not a string, aborting");if(!t.isSupported)return K;Ue?(ue=Ui,ie=Zn):Gf(y),(J.uponSanitizeElement.length>0||J.uponSanitizeAttribute.length>0)&&(ue=dn(ue)),J.uponSanitizeAttribute.length>0&&(ie=dn(ie)),t.removed=[];let me=Hf&&typeof K!="string"&&Ll(K),Ae=[],Ut=Jr;if(me){OM(K);let Hi=M(K);if(typeof Hi=="string"){let so=Tt(Hi);if(!ue[so]||Pe[so])throw $f(K),Vs("root node is forbidden and cannot be sanitized in-place")}if(Lu(K))throw $f(K),Vs("root node is clobbered and cannot be sanitized in-place");Ae=Vf(K),Jr=k_()}else if(Ll(K))k=Fb(""),U=k.ownerDocument.importNode(K,!0),U.nodeType===Bt.element&&U.nodeName==="BODY"||U.nodeName==="HTML"?k=U:k.appendChild(U),ep(k);else{if(!Qa&&!G&&!ae&&K.indexOf("<")===-1)return W&&Mu?D(K):K;if(k=Fb(K),!k)return Qa?null:Mu?z:""}k&&Pf&&sr(k.firstChild);let Jn=me?K:k;try{me&&ep(K);let Hi=Xf(Jn);for(;H=Hi.nextNode();)Qf(H,Jn),Jf(H,Jn),rr(H.content)&&Bl(H.content);me&&NM(K,Ae)}catch(Hi){throw me&&($f(K),Ub(K,Ae)),Hi}finally{Jr=Ut}if(me){if(Ub(K,Ae))throw Vs("a node selected for removal could not be safely returned; refusing to sanitize in place");return G&&Zf(K),K}if(Qa){if(G&&Zf(k),Au)for(le=Ne.call(k.ownerDocument);k.firstChild;)le.appendChild(k.firstChild);else le=k;return(ie.shadowroot||ie.shadowrootmode)&&(le=Be.call(n,le,!0)),le}let Oi=ae?k.outerHTML:k.innerHTML;return ae&&ue["!doctype"]&&k.ownerDocument&&k.ownerDocument.doctype&&k.ownerDocument.doctype.name&&vi(i3,k.ownerDocument.doctype.name)&&(Oi=" -`+Oi),G&&(Oi=Du(Oi)),W&&Mu?D(Oi):Oi},t.setConfig=function(){let K=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Gf(K),Ue=!0,Ui=ue,Zn=ie},t.clearConfig=function(){to=null,Ue=!1,Ui=null,Zn=null,W=I,z=""},t.isValidAttribute=function(K,y,k){to||Gf({});let U=Tt(K),H=Tt(y);return typeof k=="string"&&($b(y,k)||!E&&vi(Dx,k))?!1:Wb(U,H,k)},t.addHook=function(K,y){typeof y=="function"&&Xi(J,K)&&$c(J[K],y)},t.removeHook=function(K,y){if(Xi(J,K)){if(y!==void 0){let k=zL(J[K],y);return k===-1?void 0:UL(J[K],k,1)[0]}return wx(J[K])}},t.removeHooks=function(K){Xi(J,K)&&(J[K]=[])},t.removeAllHooks=function(){J=Lx()},t}var Bx,Sx,IL,Ix,zx,Qt,bi,gl,Px,B_,I_,js,zL,wx,$c,PL,UL,_l,k_,T_,Yc,za,N_,Ex,jc,xx,HL,FL,qL,Cx,kx,Xi,Vc,vi,Vs,Tx,A_,M_,YL,O_,jL,Nx,Ax,R_,Mx,Ud,VL,XL,ZL,QL,JL,Ox,e3,t3,i3,n3,D_,Rx,s3,Dx,Bt,r3,a3,o3,Lx,Fr,L_,Fx,qx=ce(()=>{Pd.prototype[typeof Symbol=="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},Pd.prototype.next=function(e){return this._invoke("next",e)},Pd.prototype.throw=function(e){return this._invoke("throw",e)},Pd.prototype.return=function(e){return this._invoke("return",e)};Bx=Object.entries,Sx=Object.setPrototypeOf,IL=Object.isFrozen,Ix=Object.getPrototypeOf,zx=Object.getOwnPropertyDescriptor,Qt=Object.freeze,bi=Object.seal,gl=Object.create,Px=typeof Reflect<"u"&&Reflect,B_=Px.apply,I_=Px.construct;Qt||(Qt=function(t){return t});bi||(bi=function(t){return t});B_||(B_=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),kx=typeof Symbol>"u"?null:_t(Symbol.prototype.toString),Xi=_t(Object.prototype.hasOwnProperty),Vc=_t(Object.prototype.toString),vi=_t(RegExp.prototype.test),Vs=Ux(TypeError);Tx=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"]),A_=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"]),M_=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"]),YL=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"]),O_=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"]),jL=Qt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Nx=Qt(["#text"]),Ax=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"]),R_=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"]),Mx=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"]),Ud=Qt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),VL=bi(/{{[\w\W]*|^[\w\W]*}}/g),XL=bi(/<%[\w\W]*|^[\w\W]*%>/g),ZL=bi(/\${[\w\W]*/g),QL=bi(/^data-[\-\w.\u00B7-\uFFFF]+$/),JL=bi(/^aria-[\-\w]+$/),Ox=bi(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),e3=bi(/^(?:\w+script|data):/i),t3=bi(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),i3=bi(/^html$/i),n3=bi(/^[a-z][.\w]*(-[.\w]+)+$/i),D_=bi(/<[/\w!]/g),Rx=bi(/<[/\w]/g),s3=bi(/<\/no(script|embed|frames)/i),Dx=bi(/\/>/i),Bt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},r3=Qt(He({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),a3=function(){return typeof window>"u"?null:window},o3=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}},Lx=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Fr=function(t,i,n,s){return Xi(t,i)&&_l(t[i])?He(s.base?dn(s.base):{},t[i],s.transform):n},L_=function(t,i,n){let s=Xi(t,i)?t[i]:void 0;return s&&typeof s=="object"?dn(s):n()};Fx=Hx()});var lC=ge((gU,oC)=>{function Vx(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)&&Vx(i)}),e}var Fd=class{constructor(t){t.data===void 0&&(t.data={}),this.data=t.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}};function Xx(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function qr(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 l3="",Kx=e=>!!e.scope,c3=(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}`},P_=class{constructor(t,i){this.buffer="",this.classPrefix=i.classPrefix,t.walk(this)}addText(t){this.buffer+=Xx(t)}openNode(t){if(!Kx(t))return;let i=c3(t.scope,{prefix:this.classPrefix});this.span(i)}closeNode(t){Kx(t)&&(this.buffer+=l3)}value(){return this.buffer}span(t){this.buffer+=``}},Wx=(e={})=>{let t={children:[]};return Object.assign(t,e),t},U_=class e{constructor(){this.rootNode=Wx(),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=Wx({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)}))}},H_=class extends U_{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 P_(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}};function Xc(e){return e?typeof e=="string"?e:e.source:null}function Zx(e){return Ua("(?=",e,")")}function u3(e){return Ua("(?:",e,")*")}function h3(e){return Ua("(?:",e,")?")}function Ua(...e){return e.map(i=>Xc(i)).join("")}function d3(e){let t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function Kd(...e){return"("+(d3(e).capture?"":"?:")+e.map(n=>Xc(n)).join("|")+")"}function Qx(e){return new RegExp(e.toString()+"|").exec("").length-1}function f3(e,t){let i=e&&e.exec(t);return i&&i.index===0}var p3=new RegExp(Kd(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));function q_(e,{joinWith:t}){let i=0;return e.map(n=>{i+=1;let s=i,r=Xc(n),a="";for(;r.length>0;){let o=p3.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 m3=/\b\B/,Jx="[a-zA-Z]\\w*",K_="[a-zA-Z_]\\w*",eC="\\b\\d+(\\.\\d+)?",tC="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",iC="\\b(0b[01]+)",g3="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",_3=(e={})=>{let t=/^#![ ]*\//;return e.binary&&(e.begin=Ua(t,/.*\b/,e.binary,/\b.*/)),qr({scope:"meta",begin:t,end:/$/,relevance:0,"on:begin":(i,n)=>{i.index!==0&&n.ignoreMatch()}},e)},Zc={begin:"\\\\[\\s\\S]",relevance:0},v3={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[Zc]},b3={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[Zc]},y3={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/},Wd=function(e,t,i={}){let n=qr({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=Kd("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:Ua(/[ ]+/,"(",s,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),n},S3=Wd("//","$"),w3=Wd("/\\*","\\*/"),E3=Wd("#","$"),x3={scope:"number",begin:eC,relevance:0},C3={scope:"number",begin:tC,relevance:0},k3={scope:"number",begin:iC,relevance:0},T3={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[Zc,{begin:/\[/,end:/\]/,relevance:0,contains:[Zc]}]},N3={scope:"title",begin:Jx,relevance:0},A3={scope:"title",begin:K_,relevance:0},M3={begin:"\\.\\s*"+K_,relevance:0},O3=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()}})},Hd=Object.freeze({__proto__:null,APOS_STRING_MODE:v3,BACKSLASH_ESCAPE:Zc,BINARY_NUMBER_MODE:k3,BINARY_NUMBER_RE:iC,COMMENT:Wd,C_BLOCK_COMMENT_MODE:w3,C_LINE_COMMENT_MODE:S3,C_NUMBER_MODE:C3,C_NUMBER_RE:tC,END_SAME_AS_BEGIN:O3,HASH_COMMENT_MODE:E3,IDENT_RE:Jx,MATCH_NOTHING_RE:m3,METHOD_GUARD:M3,NUMBER_MODE:x3,NUMBER_RE:eC,PHRASAL_WORDS_MODE:y3,QUOTE_STRING_MODE:b3,REGEXP_MODE:T3,RE_STARTERS_RE:g3,SHEBANG:_3,TITLE_MODE:N3,UNDERSCORE_IDENT_RE:K_,UNDERSCORE_TITLE_MODE:A3});function R3(e,t){e.input[e.index-1]==="."&&t.ignoreMatch()}function D3(e,t){e.className!==void 0&&(e.scope=e.className,delete e.className)}function L3(e,t){t&&e.beginKeywords&&(e.begin="\\b("+e.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",e.__beforeBegin=R3,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function B3(e,t){Array.isArray(e.illegal)&&(e.illegal=Kd(...e.illegal))}function I3(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 z3(e,t){e.relevance===void 0&&(e.relevance=1)}var P3=(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=Ua(i.beforeMatch,Zx(i.begin)),e.starts={relevance:0,contains:[Object.assign(i,{endsParent:!0})]},e.relevance=0,delete i.beforeMatch},U3=["of","and","for","in","not","or","if","then","parent","list","value"],H3="keyword";function nC(e,t,i=H3){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,nC(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,F3(l[0],l[1])]})}}function F3(e,t){return t?Number(t):q3(e)?0:1}function q3(e){return U3.includes(e.toLowerCase())}var Gx={},Pa=e=>{console.error(e)},$x=(e,...t)=>{console.log(`WARN: ${e}`,...t)},vl=(e,t)=>{Gx[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),Gx[`${e}/${t}`]=!0)},qd=new Error;function sC(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+=Qx(t[o-1]);e[i]=a,e[i]._emit=r,e[i]._multi=!0}function K3(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw Pa("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),qd;if(typeof e.beginScope!="object"||e.beginScope===null)throw Pa("beginScope must be object"),qd;sC(e,e.begin,{key:"beginScope"}),e.begin=q_(e.begin,{joinWith:""})}}function W3(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw Pa("skip, excludeEnd, returnEnd not compatible with endScope: {}"),qd;if(typeof e.endScope!="object"||e.endScope===null)throw Pa("endScope must be object"),qd;sC(e,e.end,{key:"endScope"}),e.end=q_(e.end,{joinWith:""})}}function G3(e){e.scope&&typeof e.scope=="object"&&e.scope!==null&&(e.beginScope=e.scope,delete e.scope)}function $3(e){G3(e),typeof e.beginScope=="string"&&(e.beginScope={_wrap:e.beginScope}),typeof e.endScope=="string"&&(e.endScope={_wrap:e.endScope}),K3(e),W3(e)}function Y3(e){function t(a,o){return new RegExp(Xc(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+=Qx(o)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);let o=this.regexes.map(l=>l[1]);this.matcherRe=t(q_(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;[D3,I3,$3,P3].forEach(u=>u(a,o)),e.compilerExtensions.forEach(u=>u(a,o)),a.__beforeBegin=null,[L3,B3,z3].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=nC(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=Xc(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 j3(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=qr(e.classNameAliases||{}),r(e)}function rC(e){return e?e.endsWithParent||rC(e.starts):!1}function j3(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return qr(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:rC(e)?qr(e,{starts:e.starts?qr(e.starts):null}):Object.isFrozen(e)?qr(e):e}var V3="11.12.0",F_=class extends Error{constructor(t,i){super(t),this.name="HTMLInjectionError",this.html=i}},z_=Xx,Yx=qr,jx=Symbol("nomatch"),X3=7,aC=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:H_};function l(T){return o.noHighlightRe.test(T)}function c(T){let D=T.className+" ";D+=T.parentNode?T.parentNode.className:"";let A=o.languageDetectRe.exec(D);if(A){let $=M(A[1]);return $||($x(r.replace("{}",A[1])),$x("Falling back to no-highlight mode for this block.",T)),$?A[1]:"no-highlight"}return D.split(/\s+/).find($=>l($)||M($))}function u(T,D,A){let $="",re="";typeof D=="object"?($=T,A=D.ignoreIllegals,re=D.language):(vl("10.7.0","highlight(lang, code, ...args) has been deprecated."),vl("10.7.0",`Please use highlight(code, options) instead. -https://github.com/highlightjs/highlight.js/issues/2277`),re=T,$=D),A===void 0&&(A=!0);let L={code:$,language:re};R("before:highlight",L);let Q=L.result?L.result:h(L.language,L.code,A);return Q.code=L.code,R("after:highlight",Q),Q}function h(T,D,A,$){let re=Object.create(null);function L(ee,E){return ee.keywords[E]}function Q(){if(!ie.keywords){$e.addText(Pe);return}let ee=0;ie.keywordPatternRe.lastIndex=0;let E=ie.keywordPatternRe.exec(Pe),G="";for(;E;){G+=Pe.substring(ee,E.index);let V=ci.case_insensitive?E[0].toLowerCase():E[0],ae=L(ie,V);if(ae){let[Ue,Ui]=ae;if($e.addText(G),G="",re[V]=(re[V]||0)+1,re[V]<=X3&&(In+=Ui),Ue.startsWith("_"))G+=E[0];else{let Zn=ci.classNameAliases[Ue]||Ue;Be(E[0],Zn)}}else G+=E[0];ee=ie.keywordPatternRe.lastIndex,E=ie.keywordPatternRe.exec(Pe)}G+=Pe.substring(ee),$e.addText(G)}function Ne(){if(Pe==="")return;let ee=null;if(typeof ie.subLanguage=="string"){if(!t[ie.subLanguage]){$e.addText(Pe);return}ee=h(ie.subLanguage,Pe,!0,Xn[ie.subLanguage]),Xn[ie.subLanguage]=ee._top}else ee=f(Pe,ie.subLanguage.length?ie.subLanguage:null);ie.relevance>0&&(In+=ee.relevance),$e.__addSublanguage(ee._emitter,ee.language)}function he(){ie.subLanguage!=null?Ne():Q(),Pe=""}function Be(ee,E){ee!==""&&($e.startScope(E),$e.addText(ee),$e.endScope())}function J(ee,E){let G=1,V=E.length-1;for(;G<=V;){if(!ee._emit[G]){G++;continue}let ae=ci.classNameAliases[ee[G]]||ee[G],Ue=E[G];ae?Be(Ue,ae):(Pe=Ue,Q(),Pe=""),G++}}function qe(ee,E){return ee.scope&&typeof ee.scope=="string"&&$e.openNode(ci.classNameAliases[ee.scope]||ee.scope),ee.beginScope&&(ee.beginScope._wrap?(Be(Pe,ci.classNameAliases[ee.beginScope._wrap]||ee.beginScope._wrap),Pe=""):ee.beginScope._multi&&(J(ee.beginScope,E),Pe="")),ie=Object.create(ee,{parent:{value:ie}}),ie}function dt(ee,E,G){let V=f3(ee.endRe,G);if(V){if(ee["on:end"]){let ae=new Fd(ee);ee["on:end"](E,ae),ae.isMatchIgnored&&(V=!1)}if(V){for(;ee.endsParent&&ee.parent;)ee=ee.parent;return ee}}if(ee.endsWithParent)return dt(ee.parent,E,G)}function oi(ee){return ie.matcher.regexIndex===0?(Pe+=ee[0],1):(As=!0,0)}function Ai(ee){let E=ee[0],G=ee.rule,V=new Fd(G),ae=[G.__beforeBegin,G["on:begin"]];for(let Ue of ae)if(Ue&&(Ue(ee,V),V.isMatchIgnored))return oi(E);return G.skip?Pe+=E:(G.excludeBegin&&(Pe+=E),he(),!G.returnBegin&&!G.excludeBegin&&(Pe=E)),qe(G,ee),G.returnBegin?0:E.length}function Mi(ee){let E=ee[0],G=D.substring(ee.index),V=dt(ie,ee,G);if(!V)return jx;let ae=ie;ie.endScope&&ie.endScope._wrap?(he(),Be(E,ie.endScope._wrap)):ie.endScope&&ie.endScope._multi?(he(),J(ie.endScope,ee)):ae.skip?Pe+=E:(ae.returnEnd||ae.excludeEnd||(Pe+=E),he(),ae.excludeEnd&&(Pe=E));do ie.scope&&$e.closeNode(),!ie.skip&&!ie.subLanguage&&(In+=ie.relevance),ie=ie.parent;while(ie!==V.parent);return V.starts&&qe(V.starts,ee),ae.returnEnd?0:E.length}function li(){let ee=[];for(let E=ie;E!==ci;E=E.parent)E.scope&&ee.unshift(E.scope);ee.forEach(E=>$e.openNode(E))}let we={};function yi(ee,E){let G=E&&E[0];if(Pe+=ee,G==null)return he(),0;if(we.type==="begin"&&E.type==="end"&&we.index===E.index&&G===""){if(Pe+=D.slice(E.index,E.index+1),!s){let V=new Error(`0 width match regex (${T})`);throw V.languageName=T,V.badRule=we.rule,V}return 1}if(we=E,E.type==="begin")return Ai(E);if(E.type==="illegal"&&!A){let V=new Error('Illegal lexeme "'+G+'" for mode "'+(ie.scope||"")+'"');throw V.mode=ie,V}else if(E.type==="end"){let V=Mi(E);if(V!==jx)return V}if(E.type==="illegal"&&G==="")return E.index===D.length||(Pe+=` -`),1;if(Ns>1e5&&Ns>E.index*3)throw new Error("potential infinite loop, way more iterations than matches");return Pe+=G,G.length}let ci=M(T);if(!ci)throw Pa(r.replace("{}",T)),new Error('Unknown language: "'+T+'"');let ue=Y3(ci),ui="",ie=$||ue,Xn={},$e=new o.__emitter(o);li();let Pe="",In=0,Pt=0,Ns=0,As=!1;try{if(ci.__emitTokens)ci.__emitTokens(D,$e);else{for(ie.matcher.considerAll();;){Ns++,As?As=!1:ie.matcher.considerAll(),ie.matcher.lastIndex=Pt;let ee=ie.matcher.exec(D);if(!ee)break;let E=D.substring(Pt,ee.index),G=yi(E,ee);Pt=ee.index+G}yi(D.substring(Pt))}return $e.finalize(),ui=$e.toHTML(),{language:T,value:ui,relevance:In,illegal:!1,_emitter:$e,_top:ie}}catch(ee){if(ee.message&&ee.message.includes("Illegal"))return{language:T,value:z_(D),illegal:!0,relevance:0,_illegalBy:{message:ee.message,index:Pt,context:D.slice(Pt-100,Pt+100),mode:ee.mode,resultSoFar:ui},_emitter:$e};if(s)return{language:T,value:z_(D),illegal:!1,relevance:0,errorRaised:ee,_emitter:$e,_top:ie};throw ee}}function d(T){let D={value:z_(T),illegal:!1,relevance:0,_top:a,_emitter:new o.__emitter(o)};return D._emitter.addText(T),D}function f(T,D){D=D||o.languages||Object.keys(t);let A=d(T),$=D.filter(M).filter(F).map(he=>h(he,T,!1));$.unshift(A);let re=$.sort((he,Be)=>{if(he.relevance!==Be.relevance)return Be.relevance-he.relevance;if(he.language&&Be.language){if(M(he.language).supersetOf===Be.language)return 1;if(M(Be.language).supersetOf===he.language)return-1}return 0}),[L,Q]=re,Ne=L;return Ne.secondBest=Q,Ne}function p(T,D,A){let $=D&&i[D]||A;T.classList.add("hljs"),T.classList.add(`language-${$}`)}function _(T){let D=null,A=c(T);if(l(A))return;if(R("before:highlightElement",{el:T,language:A}),T.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",T);return}if(T.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(T)),o.throwUnescapedHTML))throw new F_("One of your code blocks includes unescaped HTML.",T.innerHTML);D=T;let $=D.textContent,re=A?u($,{language:A,ignoreIllegals:!0}):f($);T.innerHTML=re.value,T.dataset.highlighted="yes",p(T,A,re.language),T.result={language:re.language,re:re.relevance,relevance:re.relevance},re.secondBest&&(T.secondBest={language:re.secondBest.language,relevance:re.secondBest.relevance}),R("after:highlightElement",{el:T,result:re,text:$})}function v(T){o=Yx(o,T)}let g=()=>{S(),vl("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function m(){S(),vl("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let b=!1;function S(){function T(){S()}if(document.readyState==="loading"){b||window.addEventListener("DOMContentLoaded",T,!1),b=!0;return}document.querySelectorAll(o.cssSelector).forEach(_)}function x(T,D){let A=null;try{A=D(e)}catch($){if(Pa("Language definition for '{}' could not be registered.".replace("{}",T)),s)Pa($);else throw $;A=a}A.name||(A.name=T),t[T]=A,A.rawDefinition=D.bind(null,e),A.aliases&&O(A.aliases,{languageName:T})}function C(T){delete t[T];for(let D of Object.keys(i))i[D]===T&&delete i[D]}function N(){return Object.keys(t)}function M(T){return T=(T||"").toLowerCase(),t[T]||t[i[T]]}function O(T,{languageName:D}){typeof T=="string"&&(T=[T]),T.forEach(A=>{i[A.toLowerCase()]=D})}function F(T){let D=M(T);return D&&!D.disableAutodetect}function W(T){T["before:highlightBlock"]&&!T["before:highlightElement"]&&(T["before:highlightElement"]=D=>{T["before:highlightBlock"](Object.assign({block:D.el},D))}),T["after:highlightBlock"]&&!T["after:highlightElement"]&&(T["after:highlightElement"]=D=>{T["after:highlightBlock"](Object.assign({block:D.el},D))})}function z(T){W(T),n.push(T)}function I(T){let D=n.indexOf(T);D!==-1&&n.splice(D,1)}function R(T,D){let A=T;n.forEach(function($){$[A]&&$[A](D)})}function q(T){return vl("10.7.0","highlightBlock will be removed entirely in v12.0"),vl("10.7.0","Please use highlightElement now."),_(T)}Object.assign(e,{highlight:u,highlightAuto:f,highlightAll:S,highlightElement:_,highlightBlock:q,configure:v,initHighlighting:g,initHighlightingOnLoad:m,registerLanguage:x,unregisterLanguage:C,listLanguages:N,getLanguage:M,registerAliases:O,autoDetection:F,inherit:Yx,addPlugin:z,removePlugin:I}),e.debugMode=function(){s=!1},e.safeMode=function(){s=!0},e.versionString=V3,e.regex={concat:Ua,lookahead:Zx,either:Kd,optional:h3,anyNumberOfTimes:u3};for(let T in Hd)typeof Hd[T]=="object"&&Vx(Hd[T]);return Object.assign(e,Hd),e},bl=aC({});bl.newInstance=()=>aC({});oC.exports=bl;bl.HighlightJS=bl;bl.default=bl});var uC=ge((_U,cC)=>{function Z3(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}]}]}}cC.exports=Z3});var dC=ge((vU,hC)=>{function Q3(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"],v=["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"],b=["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"],x=["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:v,built_in:[...m,...b,"set","shopt",...S,...x]},contains:[f,e.SHEBANG(),p,h,r,a,g,o,l,c,u,i]}}hC.exports=Q3});var pC=ge((bU,fC)=>{function J3(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},v=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"},x=[...p,l,i,e.C_BLOCK_COMMENT_MODE,h,u],C={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:S,contains:x.concat([{begin:/\(/,end:/\)/,keywords:S,contains:x.concat(["self"]),relevance:0}]),relevance:0},N={begin:"("+a+"[\\*&\\s]+){1,"+g+"}"+v,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:S,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:S,relevance:0},{begin:v,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}}}fC.exports=J3});var gC=ge((yU,mC)=>{function eB(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*\\(",v=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"],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"],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"],N={type:m,keyword:g,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:b},M={className:"function.dispatch",relevance:0,keywords:{_hint:S},begin:t.concat(/\b/,`(?!${g.join("|")})`,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},O=[M,...f,o,i,e.C_BLOCK_COMMENT_MODE,u,c],F={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:N,contains:O.concat([{begin:/\(/,end:/\)/,keywords:N,contains:O.concat(["self"]),relevance:0}]),relevance:0},W={className:"function",begin:"("+a+"[\\*&\\s]+){1,"+v+"}"+_,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:N,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:n,keywords:N,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:N,relevance:0,contains:[i,e.C_BLOCK_COMMENT_MODE,c,u,o,{begin:/\(/,end:/\)/,keywords:N,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:N,illegal:"",keywords:N,contains:["self",o]},{begin:e.IDENT_RE+"::",keywords:N},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}mC.exports=eB});var vC=ge((SU,_C)=>{function tB(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},v=e.inherit(_,{illegal:/\n/}),g={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,v]},m={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},_]},b=e.inherit(m,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},v]});_.contains=[m,g,f,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,h,e.C_BLOCK_COMMENT_MODE],v.contains=[b,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]},x={begin:"<",end:">",contains:[{beginKeywords:"in out"},o]},C=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",N={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,x,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,x,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:"("+C+"\\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,x],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]},N]}}_C.exports=tB});var yC=ge((wU,bC)=>{var iB=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_-]*/}}),nB=["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"],sB=["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"],rB=[...nB,...sB],aB=["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(),oB=["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(),lB=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),cB=["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 uB(e){let t=e.regex,i=iB(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:":("+oB.join("|")+")"},{begin:":(:)?("+lB.join("|")+")"}]},i.CSS_VARIABLE,{className:"attribute",begin:"\\b("+cB.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:aB.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...o,i.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+rB.join("|")+")\\b"}]}}bC.exports=uB});var wC=ge((EU,SC)=>{function hB(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});/}]}}SC.exports=hB});var xC=ge((xU,EC)=>{function dB(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:/$/}]}}EC.exports=dB});var kC=ge((CU,CC)=>{function fB(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}]},C=[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=C,_.contains=C;let F=[{begin:/^\s*=>/,starts:{end:"$",contains:C}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:a,contains:C}}];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(C)}}CC.exports=fB});var NC=ge((kU,TC)=>{function pB(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 mB(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/]}}AC.exports=mB});var RC=ge((NU,OC)=>{function gB(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]}}]}}OC.exports=gB});var IC=ge((AU,BC)=>{var yl="[0-9](_*[0-9])*",Gd=`\\.(${yl})`,$d="[0-9a-fA-F](_*[0-9a-fA-F])*",DC={className:"number",variants:[{begin:`(\\b(${yl})((${Gd})|\\.)?|(${Gd}))[eE][+-]?(${yl})[fFdD]?\\b`},{begin:`\\b(${yl})((${Gd})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Gd})[fFdD]?\\b`},{begin:`\\b(${yl})[fFdD]\\b`},{begin:`\\b0[xX]((${$d})\\.?|(${$d})?\\.(${$d}))[pP][+-]?(${yl})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${$d})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function LC(e,t,i){return i===-1?"":e.replace(t,n=>LC(e,t,i-1))}function _B(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=LC("(?:\\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,DC,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},DC,f]}}BC.exports=_B});var qC=ge((MU,FC)=>{var zC="[A-Za-z$_][0-9A-Za-z$_]*",vB=["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"],bB=["true","false","null","undefined","NaN","Infinity"],PC=["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"],UC=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],HC=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],yB=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],SB=[].concat(HC,PC,UC);function wB(e){let t=e.regex,i=(A,{after:$})=>{let re="",end:""},r=/<[A-Za-z0-9\\._:-]+\s*\/>/,a={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(A,$)=>{let re=A[0].length+A.index,L=A.input[re];if(L==="<"||L===","){$.ignoreMatch();return}L===">"&&(i(A,{after:re})||$.ignoreMatch());let Q,Ne=A.input.substring(re);if(Q=Ne.match(/^\s*=/)){$.ignoreMatch();return}if((Q=Ne.match(/^\s+extends\s+/))&&Q.index===0){$.ignoreMatch();return}}},o={$pattern:zC,keyword:vB,literal:bB,built_in:SB,"variable.language":yB},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"}},v={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]},b=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,v,{match:/\$\d+/},h];d.contains=b.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(b)});let S=[].concat(m,d.contains),x=S.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(S)}]),C={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:x},N={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"}}]},M={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:{_:[...PC,...UC]}},O={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:[C],illegal:/%/},W={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function z(A){return t.concat("(?!",A.join("|"),")")}let I={match:t.concat(/\b/,z([...HC,"super","import","await"].map(A=>`${A}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},R={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},q={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},C]},T="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",D={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(T)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[C]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:x,CLASS_REFERENCE:M},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),O,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,v,m,{match:/\$\d+/},h,M,{scope:"attr",match:n+t.lookahead(":"),relevance:0},D,{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:T,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:x}]}]},{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:[C,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},R,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[C]},I,W,N,q,{match:/\$[(.]/}]}}FC.exports=wB});var WC=ge((OU,KC)=>{var EB="([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity",xB={scope:"number",match:EB,relevance:0};function CB(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,xB,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}KC.exports=CB});var $C=ge((RU,GC)=>{var Sl="[0-9](_*[0-9])*",Yd=`\\.(${Sl})`,jd="[0-9a-fA-F](_*[0-9a-fA-F])*",kB={className:"number",variants:[{begin:`(\\b(${Sl})((${Yd})|\\.)?|(${Yd}))[eE][+-]?(${Sl})[fFdD]?\\b`},{begin:`\\b(${Sl})((${Yd})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Yd})[fFdD]?\\b`},{begin:`\\b(${Sl})[fFdD]\\b`},{begin:`\\b0[xX]((${jd})\\.?|(${jd})?\\.(${jd}))[pP][+-]?(${Sl})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${jd})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function TB(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=kB,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]}}GC.exports=TB});var XC=ge((DU,VC)=>{var NB=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_-]*/}}),AB=["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"],MB=["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"],OB=[...AB,...MB],RB=["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(),YC=["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(),jC=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),DB=["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(),LB=YC.concat(jC).sort().reverse();function BB(e){let t=NB(e),i=LB,n="and or not only",s="[\\w-]+",r="("+s+"|@\\{"+s+"\\})",a=[],o=[],l=function(b){return{className:"string",begin:"~?"+b+".*?"+b}},c=function(b,S,x){return{className:b,begin:S,relevance:x}},u={$pattern:/[a-z-]+/,keyword:n,attribute:RB.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("+DB.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}},v={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("+OB.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:":("+YC.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+jC.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,_,v,m,p,g,f,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:a}}VC.exports=BB});var QC=ge((LU,ZC)=>{function IB(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}])}}ZC.exports=IB});var ek=ge((BU,JC)=>{function zB(e){let t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%{function PB(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=(_,v,g="\\1")=>{let m=g==="\\1"?g:t.concat(g,v);return t.concat(t.concat("(?:",_,")"),v,/(?:\\.|[^\\\/])*?/,m,/(?:\\.|[^\\\/])*?/,g,n)},f=(_,v,g)=>t.concat(t.concat("(?:",_,")"),v,/(?:\\.|[^\\\/])*?/,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}}tk.exports=PB});var sk=ge((zU,nk)=>{function UB(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}]}}nk.exports=UB});var ak=ge((PU,rk)=>{function HB(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":(R,q)=>{q.data._beginMatch=R[1]||R[2]},"on:end":(R,q)=>{q.data._beginMatch!==R[1]&&q.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},v=["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:(R=>{let q=[];return R.forEach(T=>{q.push(T),T.toLowerCase()===T?q.push(T.toUpperCase()):q.push(T.toLowerCase())}),q})(v),built_in:m},x=R=>R.map(q=>q.replace(/\|\d+$/,"")),C={variants:[{match:[/new/,t.concat(f,"+"),t.concat("(?!",x(m).join("\\b|"),"\\b)"),s],scope:{1:"keyword",4:"title.class"}}]},N=t.concat(n,"\\b(?!\\()"),M={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),N],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[s,t.concat(/::/,t.lookahead(/(?!class\b)/)),N],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"}}]},O={scope:"attr",match:t.concat(n,t.lookahead(":"),t.lookahead(/(?!::)/))},F={relevance:0,begin:/\(/,end:/\)/,keywords:S,contains:[O,a,M,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_,C]},W={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",x(g).join("\\b|"),"|",x(m).join("\\b|"),"\\b)"),n,t.concat(f,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[F]};F.contains.push(W);let z=[O,M,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,p,_,C],I={begin:t.concat(/#\[\s*\\?/,t.either(s,r)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:v,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:v,keyword:["new","array"]},contains:["self",...z]},...z,{scope:"meta",variants:[{match:s},{match:r}]}]};return{case_insensitive:!1,keywords:S,contains:[I,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,W,M,{match:[/const/,/\s/,n],scope:{1:"keyword",3:"variable.constant"}},C,{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",I,a,M,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,_]}}rk.exports=HB});var lk=ge((UU,ok)=>{function FB(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})]}]}}ok.exports=FB});var uk=ge((HU,ck)=>{function qB(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}ck.exports=qB});var dk=ge((FU,hk)=>{function KB(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})`}]},v={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,v,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]}]}}hk.exports=KB});var pk=ge((qU,fk)=>{function WB(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}fk.exports=WB});var gk=ge((KU,mk)=>{function GB(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:/\\./}]}]}}mk.exports=GB});var vk=ge((WU,_k)=>{function $B(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]}}_k.exports=$B});var yk=ge((GU,bk)=>{var YB=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_-]*/}}),jB=["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"],VB=["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"],XB=[...jB,...VB],ZB=["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(),QB=["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(),JB=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),eI=["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 tI(e){let t=YB(e),i=JB,n=QB,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("+XB.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("+eI.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:ZB.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]}}bk.exports=tI});var wk=ge(($U,Sk)=>{function iI(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[./~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}Sk.exports=iI});var xk=ge((YU,Ek)=>{function nI(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(x=>!u.includes(x)),_={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},v={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},g={match:t.concat(/\b/,t.either(...f),/\s*\(/),relevance:0,keywords:{built_in:f}};function m(x){return t.concat(/\b/,t.either(...x.map(C=>C.replace(/\s+/,"\\s+"))),/\b/)}let b={scope:"keyword",match:m(d),relevance:0};function S(x,{exceptions:C,when:N}={}){let M=N;return C=C||[],x.map(O=>O.match(/\|\d+$/)||C.includes(O)?O:M(O)?`${O}|0`:O)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:S(p,{when:x=>x.length<3}),literal:r,type:o,built_in:h},contains:[{scope:"type",match:m(a)},b,g,_,n,s,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,i,v]}}Ek.exports=nI});var Dk=ge((jU,Rk)=>{function Nk(e){return e?typeof e=="string"?e:e.source:null}function Qc(e){return et("(?=",e,")")}function et(...e){return e.map(i=>Nk(i)).join("")}function sI(e){let t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function Ci(...e){return"("+(sI(e).capture?"":"?:")+e.map(n=>Nk(n)).join("|")+")"}new RegExp(Ci(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));var $_=e=>et(/\b/,e,/\w$/.test(e)?/\b/:/\B/),rI=["Protocol","Type"].map($_),Ck=["init","self"].map($_),aI=["Any","Self"],W_=["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"],kk=["false","nil","true"],oI=["assignment","associativity","higherThan","left","lowerThan","none","right"],lI=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],Tk=["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"],Ak=Ci(/[/=\-+!*%<>&|^~?]/,/[\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]/),Mk=Ci(Ak,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),G_=et(Ak,Mk,"*"),Ok=Ci(/[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]/),Xd=Ci(Ok,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),ys=et(Ok,Xd,"*"),Vd=et(/[A-Z]/,Xd,"*"),cI=["attached","autoclosure",et(/convention\(/,Ci("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",et(/objc\(/,ys,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],uI=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function hI(e){let t={match:/\s+/,relevance:0},i=e.COMMENT("/\\*","\\*/",{contains:["self"]}),n=[e.C_LINE_COMMENT_MODE,i],s={match:[/\./,Ci(...rI,...Ck)],className:{2:"keyword"}},r={match:et(/\./,Ci(...W_)),relevance:0},a=W_.filter(ue=>typeof ue=="string").concat(["_|0"]),o=W_.filter(ue=>typeof ue!="string").concat(aI).map($_),l={variants:[{className:"keyword",match:Ci(...o,...Ck)}]},c={$pattern:Ci(/\b\w+/,/#\w+/),keyword:a.concat(lI),literal:kk},u=[s,r,l],h={match:et(/\./,Ci(...Tk)),relevance:0},d={className:"built_in",match:et(/\b/,Ci(...Tk),/(?=\()/)},f=[h,d],p={match:/->/,relevance:0},_={className:"operator",relevance:0,variants:[{match:G_},{match:`\\.(\\.|${Mk})+`}]},v=[p,_],g="([0-9]_*)+",m="([0-9a-fA-F]_*)+",b={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=(ue="")=>({className:"subst",variants:[{match:et(/\\/,ue,/[0\\tnr"']/)},{match:et(/\\/,ue,/u\{[0-9a-fA-F]{1,8}\}/)}]}),x=(ue="")=>({className:"subst",match:et(/\\/,ue,/[\t ]*(?:[\r\n]|\r\n)/)}),C=(ue="")=>({className:"subst",label:"interpol",begin:et(/\\/,ue,/\(/),end:/\)/}),N=(ue="")=>({begin:et(ue,/"""/),end:et(/"""/,ue),contains:[S(ue),x(ue),C(ue)]}),M=(ue="")=>({begin:et(ue,/"/),end:et(/"/,ue),contains:[S(ue),C(ue)]}),O={className:"string",variants:[N(),N("#"),N("##"),N("###"),M(),M("#"),M("##"),M("###")]},F=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],W={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:F},z=ue=>{let ui=et(ue,/\//),ie=et(/\//,ue);return{begin:ui,end:ie,contains:[...F,{scope:"comment",begin:`#(?!.*${ie})`,end:/$/}]}},I={scope:"regexp",variants:[z("###"),z("##"),z("#"),W]},R={match:et(/`/,ys,/`/)},q={className:"variable",match:/\$\d+/},T={className:"variable",match:`\\$${Xd}+`},D=[R,q,T],A={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:uI,contains:[...v,b,O]}]}},$={scope:"keyword",match:et(/@/,Ci(...cI),Qc(Ci(/\(/,/\s+/)))},re={scope:"meta",match:et(/@/,ys)},L=[A,$,re],Q={match:Qc(/\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)/,Xd,"+")},{className:"type",match:Vd,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:et(/\s+&\s+/,Qc(Vd)),relevance:0}]},Ne={begin://,keywords:c,contains:[...n,...u,...L,p,Q]};Q.contains.push(Ne);let he={match:et(ys,/\s*:/),keywords:"_|0",relevance:0},Be={begin:/\(/,end:/\)/,relevance:0,keywords:c,contains:["self",he,...n,I,...u,...f,...v,b,O,...D,...L,Q]},J={begin://,keywords:"repeat each",contains:[...n,Q]},qe={begin:Ci(Qc(et(ys,/\s*:/)),Qc(et(ys,/\s+/,ys,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:ys}]},dt={begin:/\(/,end:/\)/,keywords:c,contains:[qe,...n,...u,...v,b,O,...L,Q,Be],endsParent:!0,illegal:/["']/},oi={match:[/(func|macro)/,/\s+/,Ci(R.match,ys,G_)],className:{1:"keyword",3:"title.function"},contains:[J,dt,t],illegal:[/\[/,/%/]},Ai={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[J,dt,t],illegal:/\[|%/},Mi={match:[/operator/,/\s+/,G_],className:{1:"keyword",3:"title"}},li={begin:[/precedencegroup/,/\s+/,Vd],className:{1:"keyword",3:"title"},contains:[Q],keywords:[...oI,...kk],end:/}/},we={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},yi={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},ci={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,ys,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:c,contains:[J,...u,{begin:/:/,end:/\{/,keywords:c,contains:[{scope:"title.class.inherited",match:Vd},...u],relevance:0}]};for(let ue of O.variants){let ui=ue.contains.find(Xn=>Xn.label==="interpol");ui.keywords=c;let ie=[...u,...f,...v,b,O,...D];ui.contains=[...ie,{begin:/\(/,end:/\)/,contains:["self",...ie]}]}return{name:"Swift",keywords:c,contains:[...n,oi,Ai,we,yi,ci,Mi,li,{beginKeywords:"import",end:/$/,contains:[...n],relevance:0},I,...u,...f,...v,b,O,...D,...L,Q,Be]}}Rk.exports=hI});var Bk=ge((VU,Lk)=>{function dI(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},v=[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=[...v];return g.pop(),g.push(o),f.contains=g,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:v}}Lk.exports=dI});var Wk=ge((XU,Kk)=>{var Zd="[A-Za-z$_][0-9A-Za-z$_]*",Ik=["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"],zk=["true","false","null","undefined","NaN","Infinity"],Pk=["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"],Uk=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],Hk=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],Fk=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],qk=[].concat(Hk,Pk,Uk);function fI(e){let t=e.regex,i=(A,{after:$})=>{let re="",end:""},r=/<[A-Za-z0-9\\._:-]+\s*\/>/,a={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(A,$)=>{let re=A[0].length+A.index,L=A.input[re];if(L==="<"||L===","){$.ignoreMatch();return}L===">"&&(i(A,{after:re})||$.ignoreMatch());let Q,Ne=A.input.substring(re);if(Q=Ne.match(/^\s*=/)){$.ignoreMatch();return}if((Q=Ne.match(/^\s+extends\s+/))&&Q.index===0){$.ignoreMatch();return}}},o={$pattern:Zd,keyword:Ik,literal:zk,built_in:qk,"variable.language":Fk},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"}},v={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]},b=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,v,{match:/\$\d+/},h];d.contains=b.concat({begin:/\{/,end:/\}/,keywords:o,contains:["self"].concat(b)});let S=[].concat(m,d.contains),x=S.concat([{begin:/(\s*)\(/,end:/\)/,keywords:o,contains:["self"].concat(S)}]),C={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,contains:x},N={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"}}]},M={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:{_:[...Pk,...Uk]}},O={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:[C],illegal:/%/},W={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function z(A){return t.concat("(?!",A.join("|"),")")}let I={match:t.concat(/\b/,z([...Hk,"super","import","await"].map(A=>`${A}\\s*\\(`)),n,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},R={begin:t.concat(/\./,t.lookahead(t.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},q={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},C]},T="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",D={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(T)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[C]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:o,exports:{PARAMS_CONTAINS:x,CLASS_REFERENCE:M},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),O,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,f,p,_,v,m,{match:/\$\d+/},h,M,{scope:"attr",match:n+t.lookahead(":"),relevance:0},D,{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:T,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:x}]}]},{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:[C,e.inherit(e.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},R,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[C]},I,W,N,q,{match:/\$[(.]/}]}}function pI(e){let t=e.regex,i=fI(e),n=Zd,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:Zd,keyword:Ik.concat(l),literal:zk,built_in:qk.concat(s),"variable.language":Fk},u={className:"meta",begin:"@"+n},h=(_,v,g)=>{let m=_.contains.findIndex(b=>b.label===v);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}Kk.exports=pI});var $k=ge((ZU,Gk)=>{function mI(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]}]}}Gk.exports=mI});var jk=ge((QU,Yk)=>{function gI(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]}}Yk.exports=gI});var Xk=ge((JU,Vk)=>{var Ee=lC();Ee.registerLanguage("xml",uC());Ee.registerLanguage("bash",dC());Ee.registerLanguage("c",pC());Ee.registerLanguage("cpp",gC());Ee.registerLanguage("csharp",vC());Ee.registerLanguage("css",yC());Ee.registerLanguage("markdown",wC());Ee.registerLanguage("diff",xC());Ee.registerLanguage("ruby",kC());Ee.registerLanguage("go",NC());Ee.registerLanguage("graphql",MC());Ee.registerLanguage("ini",RC());Ee.registerLanguage("java",IC());Ee.registerLanguage("javascript",qC());Ee.registerLanguage("json",WC());Ee.registerLanguage("kotlin",$C());Ee.registerLanguage("less",XC());Ee.registerLanguage("lua",QC());Ee.registerLanguage("makefile",ek());Ee.registerLanguage("perl",ik());Ee.registerLanguage("objectivec",sk());Ee.registerLanguage("php",ak());Ee.registerLanguage("php-template",lk());Ee.registerLanguage("plaintext",uk());Ee.registerLanguage("python",dk());Ee.registerLanguage("python-repl",pk());Ee.registerLanguage("r",gk());Ee.registerLanguage("rust",vk());Ee.registerLanguage("scss",yk());Ee.registerLanguage("shell",wk());Ee.registerLanguage("sql",xk());Ee.registerLanguage("swift",Dk());Ee.registerLanguage("yaml",Bk());Ee.registerLanguage("typescript",Wk());Ee.registerLanguage("vbnet",$k());Ee.registerLanguage("wasm",jk());Ee.HighlightJS=Ee;Ee.default=Ee;Vk.exports=Ee});var Zk,Qd,Y_=ce(()=>{Zk=oe(Xk(),1),Qd=Zk.default});function vI(e){return _I(Ve.parse(e,{async:!1}))}function j_({text:e,streaming:t}){let i=(0,wl.useRef)(null),n=(0,wl.useMemo)(()=>vI(e),[e]);return(0,wl.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{Qd.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??"";Ha(l).then(()=>{o.textContent="\u5DF2\u590D\u5236",setTimeout(()=>o.textContent="\u590D\u5236",1200)})},r.appendChild(o)}}}},[n]),(0,Qk.jsx)("div",{ref:i,className:`md${t?" streaming":""}`,dangerouslySetInnerHTML:{__html:n}})}async function Ha(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 wl,Qk,_I,Jd=ce(()=>{wl=oe(Ot(),1);bx();qx();Y_();Qk=oe(De(),1);Ve.setOptions({gfm:!0,breaks:!0});_I=e=>Fx.sanitize(e,{USE_PROFILES:{html:!0},ADD_ATTR:["target","rel"]})});function bI(e){let[t,i]=(0,Fa.useState)(Date.now());return(0,Fa.useEffect)(()=>{if(!e)return;let n=setInterval(()=>i(Date.now()),1e3);return()=>clearInterval(n)},[e]),t}function Jk({pendingCount:e}){let{projects:t,threads:i}=ct(),n=pe(),{version:s}=gs(),[r,a]=(0,Fa.useState)(!1),[o,l]=(0,Fa.useState)(!1),[c,u]=(0,Fa.useState)(""),[h,d,f]=Hc(),p=i.find(C=>C.id===n.currentThreadId)??null,_=p?t.find(C=>C.id===p.projectId):t.find(C=>C.id===n.currentProjectId),v=p?.status==="running"||p?.status==="initializing",g=bI(v),m=v&&p?Math.max(0,g-p.updatedAt):0,b=p?e>0?{cls:"wait",text:w("topbar.waitAuth")}:v?{cls:"run",text:Ce("topbar.running",{s:Math.floor(m/1e3)})}:p.status==="error"?{cls:"err",text:w("topbar.error")}:p.status==="closed"?{cls:"",text:w("topbar.closedResume")}:null:null,S=[{tab:"changes",icon:"changes",title:w("topbar.panelChanges")},{tab:"files",icon:"files",title:w("topbar.panelFiles")},{tab:"terminal",icon:"term",title:w("topbar.panelTerminal")}],x=p?[{kind:"item",label:w("common.rename"),onClick:()=>{u(p.title),a(!0)}},{kind:"item",label:w("topbar.threadInfo"),onClick:()=>l(!0)},{kind:"sep"},{kind:"item",label:w("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings"))},{kind:"label",text:s?`v${s}`:""}]:[{kind:"item",label:w("common.settings"),onClick:()=>window.dispatchEvent(new CustomEvent("open-settings"))},{kind:"label",text:s?`v${s}`:""}];return(0,ut.jsxs)("header",{className:"topbar",children:[(0,ut.jsx)("button",{className:"ibtn tb-menu-btn",title:w("topbar.sidebar"),onClick:()=>n.setSbOpen(!n.sbOpen),children:(0,ut.jsx)(Me,{name:"menu"})}),_&&(0,ut.jsx)("span",{className:"tb-crumb",children:_.name}),_&&p&&(0,ut.jsx)("span",{className:"tb-sep",children:"/"}),p?r?(0,ut.jsx)("input",{className:"tb-rename",autoFocus:!0,value:c,onChange:C=>u(C.target.value),onBlur:()=>a(!1),onKeyDown:C=>{C.key==="Enter"&&!Tn(C.nativeEvent)&&c.trim()?(te.call("threads.update",{id:p.id,title:c.trim()}),a(!1)):C.key==="Escape"&&a(!1)}}):(0,ut.jsx)("span",{className:"tb-title",title:w("topbar.clickRename"),onClick:()=>{u(p.title),a(!0)},children:Cd(p.title,p.titleAuto)}):(0,ut.jsx)("span",{className:"tb-title ghost",children:_?w("topbar.pickThread"):w("app.title")}),b&&(0,ut.jsx)("span",{className:`tb-pill ${b.cls}`,children:b.text}),(0,ut.jsxs)("div",{className:"tb-right",children:[p?.model&&(0,ut.jsx)("span",{className:"tb-model",children:p.model}),S.map(C=>(0,ut.jsx)("button",{className:`ibtn${n.panelOpen&&n.panelTab===C.tab?" on":""}`,title:C.title,onClick:()=>n.panelOpen&&n.panelTab===C.tab?n.closePanel():n.openPanel(C.tab),children:(0,ut.jsx)(Me,{name:C.icon})},C.tab)),(0,ut.jsx)("button",{className:"ibtn",title:w("common.more"),onClick:C=>d(C),children:(0,ut.jsx)(Me,{name:"dots"})})]}),h&&(0,ut.jsx)(Uc,{x:h.x,y:h.y,items:x,onClose:f}),o&&p&&(0,ut.jsx)(yI,{thread:p,project:_,onClose:()=>l(!1)})]})}function yI({thread:e,project:t,onClose:i}){let n=e.usage,s=xd(),r=[[w("thread.agent"),e.provider],[w("thread.model"),e.model??w("common.default")],[w("thread.mode"),e.mode],[w("thread.effort"),e.effort??w("common.default")],[w("thread.sessionId"),e.providerSessionId??w("thread.sessionNone")],[w("thread.tokens"),Ce("thread.tokensFmt",{in:ul(n.inputTokens),out:ul(n.outputTokens),cache:ul(n.cacheReadTokens)})],[w("thread.cost"),n.costUsd>0?Md(n.costUsd):"\u2014"],[w("thread.created"),new Date(e.createdAt).toLocaleString(s)],[w("thread.workdir"),t?.path??"\u2014"]];e.importedFrom&&r.push([w("thread.importedFrom"),`${e.importedFrom.provider} / ${e.importedFrom.sessionId.slice(0,8)}\u2026`]);let a=new Set([w("thread.sessionId"),w("thread.workdir")]);return(0,ut.jsx)(_s,{title:w("thread.info"),onClose:i,children:(0,ut.jsx)("div",{className:"info-grid",children:r.map(([o,l])=>(0,ut.jsxs)("div",{className:"info-row",children:[(0,ut.jsx)("span",{className:"info-k",children:o}),(0,ut.jsx)("span",{className:"info-v",title:l,children:l}),a.has(o)&&l!=="\u2014"&&l!==w("thread.sessionNone")&&(0,ut.jsx)("button",{className:"ibtn",title:w("common.copy"),onClick:()=>{Ha(l),ze(w("common.copied"))},children:(0,ut.jsx)(Me,{name:"copy",size:12})})]},o))})})}var Fa,ut,eT=ce(()=>{Fa=oe(Ot(),1);cl();Wn();un();Pc();Nn();Ur();f_();dl();Jd();vs();Od();xi();ut=oe(De(),1)});function tT(e){return typeof e=="object"?e.key:e}function iT(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 qa(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 V_(e,t){if(e===void 0)throw new Error(`Unexpected undefined${t?`: ${t}`:""}`);return e}var Xs,sT,X_=ce(()=>{Xs=(e,t)=>Math.abs(e-t)<1.01,sT=(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 rT({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 aT({kind:e,offset:t,command:i,target:n}){return e!=="spurious"&&e!=="readBack"&&e!=="clampedReadBack"&&i?.index!=null&&i.phase!=="queued"&&!SI(i.phase)&&!Xs(t,i.lastTargetOffset)&&!Xs(t,n())&&e!=="clampedEcho"}function oT(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 lT(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 SI,Z_,cT=ce(()=>{X_();SI=e=>e==="smooth"||e==="smoothFinishing";Z_=40});var Jc,eu,Q_,wI,uT,El,ef,hT=ce(()=>{eu=()=>{if(Jc!==void 0)return Jc;if(typeof navigator>"u")return Jc=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Jc=!0;let e=navigator.maxTouchPoints;return Jc=navigator.platform==="MacIntel"&&e!==void 0&&e>0},wI=()=>Q_!==void 0?Q_:Q_=eu()&&typeof CSS<"u"&&typeof CSS.supports=="function"&&CSS.supports("overflow-anchor: auto"),uT=()=>!eu()||wI(),El={capture:!0,passive:!0},ef=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,El),i.addEventListener("touchend",s,El),i.addEventListener("touchcancel",s,El),()=>{i.removeEventListener("touchstart",n,El),i.removeEventListener("touchend",s,El),i.removeEventListener("touchcancel",s,El),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 AI(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 OI(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=MI(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 dT,mT,EI,xI,gT,fT,CI,kI,_T,TI,NI,vT,pT,tu,tf,bT,J_=ce(()=>{nT();X_();cT();hT();dT=e=>{let{clientWidth:t,clientHeight:i}=e;return{width:t,height:i}},mT=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()}}},EI=e=>e,xI=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(dT(i)),!n.ResizeObserver)return()=>{};let r=mT(n),a=new n.ResizeObserver(()=>{let o=()=>{s(dT(i))};e.options.useAnimationFrameWithResizeObserver?r.schedule(o):o()});return a.observe(i,{box:"content-box"}),()=>{a.unobserve(i),r.cancel()}},fT={passive:!0},CI=typeof window>"u"?!0:"onscrollend"in window,kI=(e,t,i)=>{let n=e.scrollElement;if(!n)return;let s=e.targetWindow;if(!s)return;let r=e.options.useScrollendEvent&&CI,a=0,o=r?null:sT(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,fT),r&&n.addEventListener("scrollend",u,fT),()=>{n.removeEventListener("scroll",c),r&&n.removeEventListener("scrollend",u),o?.cancel()}},_T=(e,t)=>kI(e,t,i=>{let{horizontal:n,isRtl:s}=e.options;return n?i.scrollLeft*(s&&-1||1):i.scrollTop}),TI=(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"]},NI=(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})},vT=NI,pT=(e,t)=>e==="smooth"?t?"smoothLanded":"smooth":"instant",tu=e=>e?.phase==="smooth"||e?.phase==="smoothLanded";tf=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 ef({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"&&lT(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=mT(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:EI,rangeExtractor:xI,onChange:()=>{},measureElement:TI,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=b=>tT(f[b]),_=u>0?p(0):null,v=u>0?p(u-1):null;if(h!==u||u>0&&h>0&&(s.getItemKey(0)!==_||s.getItemKey(h-1)!==v)){l=!0;let b=u>0?this.getVirtualItemForOffset(this.getScrollOffset())??d[0]:null;b&&(a=[b.key,this.getScrollOffset()-b.start]);let S=s.followOnAppend===!0?"auto":s.followOnAppend||null;S&&h>0&&this.isAtEnd(r.scrollEndThreshold)&&(u===0||s.getItemKey(h-1)!==v)&&(h>u||AI(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=qa(()=>(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(),v=this.scrollDirection;this.scrollDirection=a?_===r?this.scrollDirection:_m-b.t<=200),{t:m,offset:f}],(v!==null&&this.scrollDirection!==v||oT(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()?tu(this.scrollState)&&!Xs(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 rT({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=pT(n,i.index!=null&&Xs(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=()=>!(eu()&&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=qa(()=>[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,b=(h=this._singleLaneMeasurements)==null?void 0:h.flat;if(!b||b.length0&&N.set(b.subarray(0,f*2)),b=N}let S=f===0?new Array(i):this._singleLaneMeasurements.items.slice(),x;if(f===0)x=n+s;else{let N=f-1;x=b[N*2]+b[N*2+1]+c}for(let N=f;N1){x=S;let W=_[x],z=W!==void 0?p[W]:void 0;C=z?z.end+c:n+s}else if(g===o){let W=0,z=v[0],I=_[0];for(let R=1;Rthis.options.debug}),this.calculateRange=qa(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(i,n,s,r)=>i.length===0||n===0?(this.range=null,null):(this.range=OI(i,n,s,r,r===1&&this._singleLaneMeasurements!==null?this._singleLaneMeasurements.flat:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=qa(()=>{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(!tu(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"&&!tu(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=!tu(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=bT(0,s.length-1,a?l=>r[l*2]:l=>V_(s[l]).start,i);return V_(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!(eu()&&this._iosGesture.dragging())&&i!==null&&!Xs(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&&Xs(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=tu(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"&&uT()){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:pT(n,t.index!=null&&Xs(i,this.getScrollOffset()))},this._scrollToOffset(i,{behavior:n}),this.scheduleScrollReconcile()}},bT=(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 RI({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:i="transform",...n}){let s=Yn.useReducer(d=>d+1,0)[1],r=Yn.useRef({enabled:t,mode:i,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});r.current.enabled=t,r.current.mode=i;let a=Yn.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,v=!!d.options.horizontal,g=f.start-d.options.scrollMargin;_.lastPositions.get(p)!==g&&(_.lastPositions.set(p,g),_.mode==="transform"?p.style.transform=v?`translate3d(${g}px, 0, 0)`:`translate3d(0, ${g}px, 0)`:p.style[v?"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,v=!0;if(_.enabled){c(d);let g=d.range,m=_.prevRange;v=!m||m.isScrolling!==d.isScrolling||m.startIndex!==g?.startIndex||m.endIndex!==g?.endIndex,v&&(_.prevRange=g?{startIndex:g.startIndex,endIndex:g.endIndex,isScrolling:d.isScrolling}:null)}v&&(e&&f&&!a.current?(0,yT.flushSync)(s):s()),(p=n.onChange)==null||p.call(n,d,f)}},[h]=Yn.useState(()=>{let d=new tf(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 v=d.measurementsCache[d.indexFromElement(p)];v&&l(d,v,p)}},Object.assign(d,{containerRef:p=>{let _=r.current;_.container=p,_.lastSize=null,p!==null&&c(d)}})});return h.setOptions(u),ev(()=>h._didMount(),[]),ev(()=>(o(h),h._willUpdate())),ev(()=>{c(h)}),h}function ST(e){return RI({observeElementRect:gT,observeElementOffset:_T,scrollToFn:vT,...e})}var Yn,yT,ev,wT=ce(()=>{Yn=oe(Ot(),1),yT=oe(co(),1);J_();J_();ev=typeof document<"u"?Yn.useLayoutEffect:Yn.useEffect});function xl(){return{items:[],seenSeq:new Set,byItemId:new Map,toolLoc:new Map,openGroup:null,reqLoc:new Map,turnUsage:new Map,lastUserIdx:new Map}}function Zs(e){e.openGroup=null}function ET(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}Zs(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 DI(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 xT(e,t,i,n){DI(e,t,i);let s=e.byItemId.get(t);if(s){let o=e.items[s.idx];o.text=n,o.streaming=!1;return}Zs(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 LI(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 nf(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":Zs(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":ET(e,t.itemId,"assistant",t.text);return;case"reasoning_delta":ET(e,t.itemId,"reasoning",t.text);return;case"assistant_message":xT(e,t.itemId,"assistant",t.text);return;case"reasoning":xT(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":LI(e,t);return;case"plan":Zs(e),e.items.push({kind:"plan",key:`plan:${t.itemId}`,itemId:t.itemId,markdown:t.markdown});return;case"todo":Zs(e),e.items.push({kind:"todo",key:`todo:${t.seq}`,items:t.items});return;case"permission_request":Zs(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":Zs(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":Zs(e),e.items.push({kind:"notice",key:`n:${t.seq}`,level:t.level,message:t.message});return;case"turn_ended":Zs(e),e.items.push({kind:"turnend",key:`te:${t.seq}`,status:t.status,durationMs:t.durationMs,error:t.error,filesChanged:t.filesChanged,usage:e.turnUsage.get(t.turnId)});return;case"turn_started":return;case"status":return;default:return}}function CT(e,t={}){let i=xl();for(let r of e)nf(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 kT=ce(()=>{});var NT={};Vb(NT,{useTimeline:()=>Mn});function TT(){let e=Kr!=="running"&&Kr!=="initializing";for(let t of Ss.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 Ss,Ka,Kr,sf,Mn,Cl=ce(()=>{rl();kT();Nn();Ss=xl(),Ka=0,Kr="idle",sf=null;Mn=ms((e,t)=>{let i=n=>{sf?.(),sf=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<=Ka)return;Ka=Math.max(Ka,o.seq)}o.type==="user_message"&&e({lastUserText:o.text}),nf(Ss,o);let l=Ss.items.filter(c=>(c.kind==="permission"||c.kind==="question")&&c.status==="pending").map(c=>({requestId:c.requestId,kind:c.kind}));e({items:Ss.items.slice(),pending:l});return}if(a.type==="status"&&a.status){Kr=a.status,TT(),e({status:Kr,items:Ss.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}}},()=>Ka)};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:[]}),Ss=xl(),Ka=0,Kr="initializing",(async()=>{try{let s=await te.call("threads.get",{id:n});if(t().threadId!==n)return;Kr=s.runtimeStatus??s.meta.status;let r=CT(s.events,{runtimeStatus:Kr});Ss=xl();for(let a of s.events)nf(Ss,a);Ka=Math.max(0,...s.events.map(a=>a.seq??0)),TT(),e({items:Ss.items.slice(),status:Kr,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:()=>{sf?.(),sf=null,Ss=xl(),Ka=0,e({threadId:null,items:[],queue:[],pending:[],lastUserText:null,error:null,status:"idle",slashCommands:[]})}}})});var rf,AT=ce(()=>{rf=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 kl(){let e=location.hash.startsWith("#")?location.hash.slice(1):location.hash;return new URLSearchParams(e).get("t")??""}var af=ce(()=>{});function BI(e){return e==="+"||e==="-"?e:" "}function MT(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:BI(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 OT=ce(()=>{});function LT(e){return`/attachments/${e}?t=${DT()}`}function II({it:e,onRetry:t}){return(0,Y.jsxs)("div",{className:"um-row",children:[(0,Y.jsxs)("div",{className:"um",children:[e.attachments?.map(i=>(0,Y.jsx)("img",{className:"um-img",src:`/attachments/${i.id}?t=${DT()}`,alt:i.name},i.id)),(0,Y.jsx)("span",{className:"um-text",children:e.text}),(0,Y.jsxs)("div",{className:"um-act",children:[(0,Y.jsx)("button",{className:"ibtn",title:w("common.copy"),onClick:()=>{Ha(e.text)},children:(0,Y.jsx)(Me,{name:"copy",size:13})}),t&&(0,Y.jsx)("button",{className:"ibtn",title:w("timeline.editResend"),onClick:()=>t(e.text),children:(0,Y.jsx)(Me,{name:"send",size:13})})]})]}),e.steered&&(0,Y.jsx)("div",{className:"um-tag",children:w("timeline.steer")})]})}function zI({it:e}){let[t,i]=(0,It.useState)(e.streaming?"":e.text),n=(0,It.useRef)(null);return(0,It.useEffect)(()=>{n.current||(n.current=new rf(i)),n.current.push(e.text),e.streaming||n.current.flush()},[e.text,e.streaming]),(0,It.useEffect)(()=>()=>n.current?.stop(),[]),(0,Y.jsx)(j_,{text:t,streaming:e.streaming})}function PI({it:e}){let[t,i]=(0,It.useState)(!1),n=Math.max(1,Math.round(e.text.length/40));return(0,Y.jsxs)("div",{className:"rs-item",children:[(0,Y.jsxs)("button",{className:"rs-head",onClick:()=>i(!t),children:[(0,Y.jsx)("span",{className:`caret${t?" open":""}`,children:"\u203A"})," ",Ce("timeline.thinking",{s:n})]}),t&&(0,Y.jsx)("div",{className:"rs-body",children:e.text})]})}function RT(e){let t=`timeline.tool.${e}`,i=w(t);return i.startsWith("timeline.tool.")?w("timeline.tool.other"):i}function UI({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,It.useState)(t||i),r=(0,It.useRef)(!1);(0,It.useEffect)(()=>{!r.current&&(t||i)&&s(!0)},[t,i]);let a=(0,It.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])=>`${RT(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,Y.jsxs)("div",{className:"tg",children:[(0,Y.jsxs)("button",{className:"tg-head",onClick:()=>{r.current=!0,s(!n)},children:[(0,Y.jsx)("span",{className:`caret${n?" open":""}`,children:"\u203A"}),(0,Y.jsx)("span",{children:a}),o&&(0,Y.jsx)("span",{className:"tg-live",children:Ce("timeline.toolRunning",{kind:RT(o.kind),title:o.title})})]}),n&&(0,Y.jsx)("div",{className:"tg-list",children:e.steps.map(l=>(0,Y.jsx)(HI,{s:l},l.itemId))})]})}function HI({s:e}){let t=e.detail,[i,n]=(0,It.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,Y.jsxs)("div",{className:"ts",children:[(0,Y.jsxs)("button",{className:"ts-head",onClick:()=>a&&n(!i),children:[(0,Y.jsx)("span",{className:`ts-ic ${r}`,children:s}),(0,Y.jsx)("span",{className:"ts-title",children:e.title}),e.durationMs!=null&&(0,Y.jsx)("span",{className:"ts-meta",children:d_(e.durationMs)}),e.exitCode!=null&&e.exitCode!==0&&(0,Y.jsxs)("span",{className:"ts-meta err",children:["exit ",e.exitCode]})]}),i&&(0,Y.jsx)(FI,{s:e})]})}function FI({s:e}){let[t,i]=(0,It.useState)(!1),n=e.detail,s=n?.hunks??n?.diff?.hunks;if(s)return(0,Y.jsx)(of,{hunks:MT(s),path:n?.diff?.path??n?.path});if(e.output!=null){let r=e.output.split(` +`}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,Y.jsxs)("div",{className:"ts-out",children:[a&&(0,Y.jsx)("button",{className:"ts-more",onClick:()=>i(!0),children:Ce("timeline.showAllLines",{n:r.length})}),(0,Y.jsx)("pre",{children:o})]})}return e.input!=null?(0,Y.jsx)("pre",{className:"ts-out",children:JSON.stringify(e.input,null,2).slice(0,4e3)}):null}function of({hunks:e,path:t,max:i=3e3}){let n=0,s=!1;return(0,Y.jsxs)("div",{className:"diff",children:[t&&(0,Y.jsx)("div",{className:"diff-path",children:t}),(0,Y.jsx)("pre",{className:"diff-pre",children:e.map((r,a)=>(0,Y.jsxs)("span",{className:"dh",children:[(0,Y.jsx)("span",{className:"dh-head",children:r.head??"@@"}),r.lines.map((o,l)=>(n++,n>i?(s=!0,null):(0,Y.jsxs)("span",{className:`dl ${o.t==="+"?"add":o.t==="-"?"del":""}`,children:[o.t," ",o.text,` -`]},l)))]},a))}),s&&(0,Y.jsx)("div",{className:"dlg-hint",children:Ce("timeline.diffClip",{n:i})})]})}function qI({it:e}){return(0,Y.jsx)("div",{className:"card plan",children:(0,Y.jsx)(j_,{text:e.markdown})})}function KI({it:e}){let[t,i]=(0,It.useState)(!1),n=e.items.filter(s=>s.status==="done"||s.status==="completed").length;return(0,Y.jsxs)("div",{className:"rs-item",children:[(0,Y.jsxs)("button",{className:"rs-head",onClick:()=>i(!t),children:[(0,Y.jsx)("span",{className:`caret${t?" open":""}`,children:"\u203A"})," ",Ce("timeline.todo",{done:n,total:e.items.length})]}),t&&(0,Y.jsx)("ul",{className:"todo-list",children:e.items.map((s,r)=>(0,Y.jsxs)("li",{className:`todo ${s.status}`,children:[s.status==="done"||s.status==="completed"?"\u2611":s.status==="in_progress"?"\u25D0":"\u2610"," ",s.text]},r))})]})}function WI({it:e,threadId:t}){let[i,n]=(0,It.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"?w("timeline.permAllowSession"):e.choice==="deny"||e.choice==="reject"||e.choice==="decline"?w("timeline.permDenied"):e.choice==="implement"?w("timeline.permAllowed"):w("timeline.permAllowed"):w("timeline.permCancelled");return(0,Y.jsxs)("div",{className:`card perm${e.status!=="pending"?" done":""}`,children:[(0,Y.jsx)("div",{className:"perm-title",children:e.title}),r?.command&&(0,Y.jsx)("pre",{className:"perm-cmd",children:r.command}),r?.path&&(0,Y.jsx)("div",{className:"perm-path",children:r.path}),a&&(0,Y.jsx)(of,{hunks:a,path:r?.diff?.path??r?.path,max:200}),e.status==="pending"?(0,Y.jsx)("div",{className:"perm-btns",children:e.options.map(l=>(0,Y.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,Y.jsx)("div",{className:"perm-done",children:o})]})}function GI({it:e,threadId:t}){let[i,n]=(0,It.useState)({}),[s,r]=(0,It.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,Y.jsxs)("div",{className:`card ask${e.status!=="pending"?" done":""}`,children:[a.map((c,u)=>(0,Y.jsxs)("div",{className:"ask-q",children:[(0,Y.jsx)("div",{className:"ask-t",children:c.header??c.question}),e.status==="pending"?(0,Y.jsxs)(Y.Fragment,{children:[(0,Y.jsx)("div",{className:"ask-opts",children:c.options?.map(h=>(0,Y.jsx)("button",{className:`btn${s[u]===h.label?" primary":""}`,onClick:()=>r(d=>({...d,[u]:h.label})),children:h.label},h.label))}),(0,Y.jsx)("input",{className:"tinput ask-free",placeholder:w("common.other"),value:i[u]??"",onChange:h=>n(d=>({...d,[u]:h.target.value}))})]}):(0,Y.jsx)("div",{className:"perm-done",children:e.answers?Ce("timeline.submitted",{ans:Object.values(e.answers).join("\u3001")}):w("timeline.permCancelled")})]},u)),e.status==="pending"&&(0,Y.jsx)("button",{className:"btn primary",onClick:l,children:w("common.submit")})]})}function $I({it:e,onRetry:t}){let i=pe(),[n,s]=(0,It.useState)(!1);if(e.status==="failed")return(0,Y.jsxs)("div",{className:"card err-card",children:[(0,Y.jsx)("div",{className:"err-line",children:Ce("timeline.turnError",{err:Ta(e.error??w("timeline.unknownError"))})}),(0,Y.jsxs)("div",{className:"perm-btns",children:[t&&(0,Y.jsx)("button",{className:"btn",onClick:t,children:w("common.retry")}),e.error&&e.error.length>60&&(0,Y.jsx)("button",{className:"btn ghost",onClick:()=>s(!n),children:w("common.details")})]}),n&&(0,Y.jsx)("pre",{className:"perm-cmd",children:Ta(e.error??"")})]});let r=[];if(e.durationMs!=null&&r.push(d_(e.durationMs)),e.usage){let a=e.usage.inputTokens+e.usage.outputTokens;a&&r.push(`${ul(a)} tokens`),e.usage.costUsd&&r.push(Md(e.usage.costUsd))}return e.status==="interrupted"&&r.push(w("timeline.interrupted")),(0,Y.jsxs)("div",{className:"te",children:[(0,Y.jsx)("span",{children:r.join(" \xB7 ")||e.status}),e.filesChanged!=null&&e.filesChanged>0&&(0,Y.jsx)("button",{className:"te-files",onClick:()=>i.openPanel("changes"),children:Ce("timeline.filesChanged",{n:e.filesChanged})})]})}function BT({it:e,threadId:t,onEditResend:i,onRetryLast:n}){switch(e.kind){case"user":return(0,Y.jsx)(II,{it:e,onRetry:i});case"assistant":return(0,Y.jsx)("div",{className:"as",children:(0,Y.jsx)(zI,{it:e})});case"reasoning":return(0,Y.jsx)(PI,{it:e});case"toolgroup":return(0,Y.jsx)(UI,{it:e});case"plan":return(0,Y.jsx)(qI,{it:e});case"todo":return(0,Y.jsx)(KI,{it:e});case"permission":return(0,Y.jsx)(WI,{it:e,threadId:t});case"question":return(0,Y.jsx)(GI,{it:e,threadId:t});case"notice":return(0,Y.jsx)("div",{className:`nt ${e.level}`,children:Ta(e.message)});case"turnend":return(0,Y.jsx)($I,{it:e,onRetry:n});case"gone":return null;default:return null}}var It,Y,DT,lf=ce(()=>{It=oe(Ot(),1);Jd();AT();Ur();Nn();af();OT();Od();un();xi();Y=oe(De(),1),DT=()=>kl()});function tv(){return[{id:"plan",label:w("composer.mode.plan.label"),desc:w("composer.mode.plan.desc")},{id:"default",label:w("composer.mode.default.label"),desc:w("composer.mode.default.desc")},{id:"acceptEdits",label:w("composer.mode.acceptEdits.label"),desc:w("composer.mode.acceptEdits.desc")},{id:"bypassPermissions",label:w("composer.mode.bypass.label"),desc:w("composer.mode.bypass.desc"),danger:!0}]}function YI(){return[{id:"default",label:w("composer.mode.cursorAgent.label"),desc:w("composer.mode.cursorAgent.desc")},{id:"plan",label:w("composer.mode.cursorPlan.label"),desc:w("composer.mode.cursorPlan.desc")},{id:"ask",label:w("composer.mode.cursorAsk.label"),desc:w("composer.mode.cursorAsk.desc")}]}function IT(e,t,i){return(e==="cursor"?YI():tv()).filter(s=>t.includes(s.id)).map(s=>i?.[s.id]?{...s,label:i[s.id]}:s)}var iv=ce(()=>{xi()});var HT={};Vb(HT,{SettingsDialog:()=>nv,applyTheme:()=>UT,useLiveSettings:()=>Tl});function zT(e){return!(e.enabled===!1||!e.available||e.status==="planned")}function jI(e){return e.status==="verified"?w("settings.providerVerified"):e.status==="experimental"?w("settings.providerExperimental"):e.status==="planned"?w("settings.providerPlanned"):w("settings.providerPending")}function nv({onClose:e,providers:t}){let i=ct(v=>v.ws),[n,s]=(0,Wr.useState)(null),[r,a]=(0,Wr.useState)({}),[o,l]=(0,Wr.useState)(null),c=tv();(0,Wr.useEffect)(()=>{te.call("settings.get").then(v=>s(v)),te.call("app.info").then(v=>a(v)).catch(()=>{})},[]);let u=async v=>{let g={...n,...v};s(g);try{await te.call("settings.set",{patch:v}),window.dispatchEvent(new CustomEvent("settings-changed",{detail:g})),v.theme&&UT(v.theme),v.providerEnabled&&i&&te.call("providers.list",{refresh:!0}).then(m=>{ct.setState({providers:m})})}catch(m){ze(w("settings.failSave")+ft(m),!0)}},h=(v,g)=>{let m=n?.providerEnabled??{};u({providerEnabled:{...m,[v]:g}})},d=()=>{te.call("providers.list",{refresh:!0}).then(v=>{ct.setState({providers:v}),ze(w("settings.providerRedetect")+" \u2713")}).catch(v=>ze(ft(v),!0))},f=(v,g)=>{let m={...n?.providerCommand??{}};m[v]={...m[v],...g},u({providerCommand:m})},p=v=>{if(v.enabled===!1)return{dot:"off",text:w("settings.providerOff")};if(!v.available)return{dot:"off",text:v.reason??w("common.notDetected")};let g=v.models?.length??0,m=jI(v),b=g>0?` \xB7 ${Ce("settings.providerModels",{n:String(g)})}`:"";return{dot:v.status==="verified"?"on":"pending",text:m+b}};if(!n)return(0,fe.jsx)(_s,{title:w("settings.title"),onClose:e,children:(0,fe.jsx)("div",{className:"dlg-hint",children:w("common.loading")})});let _=(v,g)=>(0,fe.jsxs)("div",{className:"dlg-row",children:[(0,fe.jsx)("label",{children:v}),g]});return(0,fe.jsxs)(_s,{title:w("settings.title"),onClose:e,wide:!0,footer:(0,fe.jsx)("button",{className:"btn primary",onClick:e,children:w("common.done")}),children:[_(w("settings.defaultAgent"),(0,fe.jsx)("select",{className:"tinput",value:n.defaultProvider??"claude",onChange:v=>{u({defaultProvider:v.target.value})},children:t.map(v=>(0,fe.jsxs)("option",{value:v.id,disabled:!zT(v),children:[v.name,zT(v)?"":w("common.notInstalled")]},v.id))})),(0,fe.jsxs)("div",{className:"dlg-row dlg-row-top",children:[(0,fe.jsx)("label",{children:w("settings.providers")}),(0,fe.jsxs)("div",{className:"provider-list",children:[(0,fe.jsx)("button",{type:"button",className:"btn sm provider-redetect",onClick:d,children:w("settings.providerRedetect")}),t.map(v=>{let g=p(v),m=v.enabled!==!1,b=o===v.id,S=n.providerCommand?.[v.id];return(0,fe.jsxs)("div",{className:`provider-row${b?" open":""}`,children:[(0,fe.jsxs)("button",{type:"button",className:"provider-head",onClick:()=>l(b?null:v.id),children:[(0,fe.jsx)("span",{className:`provider-dot provider-dot-${g.dot}`,"aria-hidden":!0}),(0,fe.jsxs)("div",{className:"provider-meta",children:[(0,fe.jsx)("span",{className:"provider-name",children:v.name}),(0,fe.jsx)("span",{className:"dlg-hint",children:g.text})]}),(0,fe.jsx)("span",{className:"mi-caret",children:b?"\u25BE":"\u25B8"})]}),(0,fe.jsx)("label",{className:"provider-switch",title:v.name,children:(0,fe.jsx)("input",{type:"checkbox",checked:m,onChange:x=>h(v.id,x.target.checked)})}),b&&(0,fe.jsxs)("div",{className:"provider-detail",children:[v.bin&&(0,fe.jsxs)("div",{className:"dlg-hint",children:[v.bin,v.version?` \xB7 ${v.version}`:""]}),v.installHint&&(0,fe.jsxs)("div",{className:"provider-hint-row",children:[(0,fe.jsx)("span",{className:"dlg-hint",children:v.installHint}),(0,fe.jsx)("button",{type:"button",className:"te-files",onClick:()=>{navigator.clipboard?.writeText(v.installHint??"").then(()=>ze(w("common.copied")))},children:w("settings.providerCopyHint")})]}),(0,fe.jsx)("div",{className:"dlg-hint",children:w("settings.providerLaunchCmd")}),(0,fe.jsx)("input",{className:"tinput",placeholder:w("settings.providerLaunchExe"),value:S?.executable??"",onChange:x=>f(v.id,{executable:x.target.value||void 0})}),(0,fe.jsx)("input",{className:"tinput",placeholder:'["--acp"]',value:S?.args?JSON.stringify(S.args):"",onChange:x=>{try{let C=x.target.value.trim();f(v.id,{args:C?JSON.parse(C):void 0})}catch{}}})]})]},v.id)})]})]}),_(w("settings.defaultMode"),(0,fe.jsx)("select",{className:"tinput",value:n.defaultMode??"default",onChange:v=>{u({defaultMode:v.target.value})},children:c.map(v=>(0,fe.jsx)("option",{value:v.id,children:v.label},v.id))})),_(w("settings.theme"),(0,fe.jsxs)("select",{className:"tinput",value:n.theme??"auto",onChange:v=>{u({theme:v.target.value})},children:[(0,fe.jsx)("option",{value:"auto",children:w("settings.themeAuto")}),(0,fe.jsx)("option",{value:"light",children:w("settings.themeLight")}),(0,fe.jsx)("option",{value:"dark",children:w("settings.themeDark")})]})),_(w("settings.sendKey"),(0,fe.jsxs)("select",{className:"tinput",value:n.sendKey??"enter",onChange:v=>{u({sendKey:v.target.value})},children:[(0,fe.jsx)("option",{value:"enter",children:w("settings.sendEnter")}),(0,fe.jsx)("option",{value:"ctrlEnter",children:w("settings.sendCtrl")})]})),_(w("settings.runningSend"),(0,fe.jsxs)("select",{className:"tinput",value:n.runningSend??"queue",onChange:v=>{u({runningSend:v.target.value})},children:[(0,fe.jsx)("option",{value:"queue",children:w("settings.queue")}),(0,fe.jsx)("option",{value:"steer",children:w("settings.steer")})]})),_(w("settings.thinking"),(0,fe.jsxs)("label",{style:{display:"flex",gap:8,alignItems:"center",fontSize:"var(--fs-m)",color:"var(--fg)"},children:[(0,fe.jsx)("input",{type:"checkbox",checked:n.showThinking!==!1,onChange:v=>{u({showThinking:v.target.checked})}}),w("settings.showThinking")]})),_(w("settings.idleClose"),(0,fe.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[(0,fe.jsx)("input",{className:"tinput",type:"number",min:5,max:240,style:{width:90},value:n.idleCloseMinutes??30,onChange:v=>{u({idleCloseMinutes:Math.max(5,Number(v.target.value)||30)})}}),(0,fe.jsx)("span",{className:"dlg-hint",children:w("settings.idleMinutes")})]})),(0,fe.jsx)("div",{className:"msep"}),(0,fe.jsxs)("div",{className:"dlg-hint",children:[Ce("settings.versionLine",{ver:r.version??"?",pid:r.pid??"?"}),(0,fe.jsx)("br",{}),w("settings.dataDir"),r.dataDir??"?"," ",(0,fe.jsx)("button",{className:"te-files",onClick:()=>{navigator.clipboard?.writeText(r.dataDir??"").catch(()=>{})},children:w("common.copy")})]})]})}function UT(e){let t=window.matchMedia?.("(prefers-color-scheme: dark)").matches;document.documentElement.dataset.theme=e==="light"||e==="dark"?e:t?"dark":"light"}function PT(e){return{sendKey:e?.sendKey==="ctrlEnter"?"ctrlEnter":"enter",runningSend:e?.runningSend==="steer"?"steer":"queue",showThinking:e?.showThinking!==!1}}function Tl(){let[e,t]=(0,Wr.useState)(VI);return(0,Wr.useEffect)(()=>{te.call("settings.get").then(n=>t(PT(n))).catch(()=>{});let i=n=>t(PT(n.detail));return window.addEventListener("settings-changed",i),()=>window.removeEventListener("settings-changed",i)},[]),e}var Wr,fe,VI,iu=ce(()=>{Wr=oe(Ot(),1);dl();Nn();vs();iv();xi();Wn();fe=oe(De(),1);VI={sendKey:"enter",runningSend:"queue",showThinking:!0}});function FT(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 qT(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 KT(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 WT(e){return e.filter(t=>t.type==="item").map(t=>t.command)}function sv(e){return`/${e} `}function GT(e,t){return!!t&&e.trim()===`/${t}`}function rv(e,t){return t<=0?0:e<0?t-1:e>=t?0:e}var $T=ce(()=>{});function YT(){let e=pe(),{threads:t,providers:i}=ct(),n=Mn(),[s,r]=(0,Ge.useState)(""),[a,o]=(0,Ge.useState)([]),[l,c]=(0,Ge.useState)(!1),[u,h]=(0,Ge.useState)(null),[d,f]=(0,Ge.useState)(""),p=(0,Ge.useRef)(null),_=(0,Ge.useRef)(null),v=(0,Ge.useRef)(null),[g,m]=(0,Ge.useState)([]),[b,S]=(0,Ge.useState)(0),[x,C]=(0,Ge.useState)(0),N=(0,Ge.useRef)(!1),M=(0,Ge.useRef)(new Set),[O,F]=(0,Ge.useState)(!1),W=Tl(),z=t.find(E=>E.id===e.currentThreadId),I=i.find(E=>E.id===z?.provider),R=n.status==="running"||n.status==="initializing",q=n.pending.length>0,T=I?.capabilities.steer??!1,D=!!I&&!I.capabilities.images&&I.capabilities.imagesKnown!==!1,A=z?.mode??"default",$=IT(z?.provider,I?.capabilities.modes??[],I?.capabilities.modeLabels),re=$.find(E=>E.id===A),L=n.items.some(E=>E.kind==="user"),Q=(0,Ge.useMemo)(()=>FT(s,N.current),[s]),Ne=(0,Ge.useMemo)(()=>qT(n.slashCommands,Q.query),[n.slashCommands,Q.query]),he=(0,Ge.useMemo)(()=>KT(Ne),[Ne]),Be=(0,Ge.useMemo)(()=>WT(he),[he]),J=Q.open&&!q;(0,Ge.useEffect)(()=>{C(0)},[Q.query,J]),(0,Ge.useEffect)(()=>{let E=z?.id;!J||!E||M.current.has(E)||(M.current.add(E),F(!0),te.call("thread.commands",{id:E,load:!0},3e4).then(G=>{let V=G.commands??[];(V.length||!Mn.getState().slashCommands.length)&&Mn.setState({slashCommands:V})}).catch(()=>{}).finally(()=>F(!1)))},[J,z?.id]);let qe=(0,Ge.useMemo)(()=>i.filter(E=>E.enabled!==!1||E.id===z?.provider),[i,z?.provider]),dt=qe.find(E=>E.id===(u??z?.provider)),oi=E=>E.enabled!==!1&&E.available&&E.status!=="planned",Ai=E=>{c(E),E&&(h(null),f(""))};(0,Ge.useEffect)(()=>{if(!l)return;let E=V=>{p.current&&!p.current.contains(V.target)&&Ai(!1)},G=V=>{V.key==="Escape"&&(V.stopPropagation(),Ai(!1))};return document.addEventListener("pointerdown",E,!0),window.addEventListener("keydown",G,!0),()=>{document.removeEventListener("pointerdown",E,!0),window.removeEventListener("keydown",G,!0)}},[l]);let Mi=async(E,G)=>{if(z){Ai(!1);try{!L&&E!==z.provider&&await te.call("thread.setProvider",{id:z.id,provider:E}),await te.call("thread.setModel",{id:z.id,model:G})}catch(V){ze(w("composer.failSwitchAgent")+ft(V),!0)}}},li=(0,Ge.useMemo)(()=>{let E=d.trim().toLowerCase();if(!E)return[];let G=[];for(let V of qe)if(oi(V))for(let ae of V.models??[])(ae.name.toLowerCase().includes(E)||ae.id.toLowerCase().includes(E))&&G.push({providerId:V.id,providerName:V.name,model:ae});return G.slice(0,100)},[d,qe]),we=!!(u&&!d.trim());(0,Ge.useEffect)(()=>{if(!R)return;let E=Date.now(),G=setInterval(()=>S(Math.floor((Date.now()-E)/1e3)),1e3);return()=>clearInterval(G)},[R]),(0,Ge.useEffect)(()=>{let E=_.current;E&&(E.style.height="auto",E.style.height=Math.min(E.scrollHeight,264)+"px")},[s]);let yi=(0,Ge.useCallback)(async(E="queue")=>{let G=e.currentThreadId,V=s.trim();if(!(!G||!V&&a.length===0)){R&&E==="queue"&&m(ae=>[...ae,V]),r("");try{await te.call("thread.send",{id:G,text:V,attachments:a.map(ae=>({path:ae.path,mime:ae.mime,name:ae.name})),behavior:R&&E==="steer"&&T?"steer":"queue"}),o([]),R||m(ae=>[...ae.slice(-9),V])}catch(ae){r(V),ze(w("composer.failSend")+ft(ae),!0)}}},[s,a,e.currentThreadId,R,T]),ci=E=>{if(Tn(E.nativeEvent))return;if(J&&Be.length>0){if(E.key==="ArrowDown"){E.preventDefault(),C(Ui=>rv(Ui+1,Be.length));return}if(E.key==="ArrowUp"){E.preventDefault(),C(Ui=>rv(Ui-1,Be.length));return}if(E.key==="Escape"){E.preventDefault(),N.current=!0,C(0);return}let ae=Be[x]??Be[0],Ue=E.key==="Enter"&>(s,ae?.name);if((E.key==="Enter"&&!E.shiftKey||E.key==="Tab")&&!Ue){E.preventDefault(),ae&&(N.current=!1,r(sv(ae.name)));return}}let G=E.ctrlKey||E.metaKey;if(W.sendKey==="ctrlEnter"?E.key==="Enter"&&G:E.key==="Enter"&&!E.shiftKey&&!G){E.preventDefault(),R&&W.runningSend==="steer"&&T?yi("steer"):yi("queue");return}if(W.sendKey==="enter"&&E.key==="Enter"&&G&&R){E.preventDefault(),yi(T?"steer":"queue");return}E.key==="ArrowUp"&&s===""&&g.length>0&&(E.preventDefault(),r(g[g.length-1]))},ue=async E=>{let G=E.clipboardData?.items;if(!G)return;for(let ae of G)if(ae.type.startsWith("image/")){E.preventDefault();let Ue=ae.getAsFile();Ue&&await ui(Ue);return}let V=E.clipboardData.getData("text/plain");if(V&&V.length>32*1024){E.preventDefault();let ae=new File([V],"paste.txt",{type:"text/plain"});await ui(ae)}},ui=async E=>{let G=kl(),V={path:"",name:E.name,mime:E.type||"application/octet-stream",uploading:!0};o(ae=>[...ae,V]);try{let Ue=await(await fetch(`/api/upload?name=${encodeURIComponent(E.name)}`,{method:"POST",headers:{"x-agent-console":G},body:E})).json();if(!Ue.ok)throw new Error(Ue.e?.message??w("composer.uploadFailed"));o(Ui=>Ui.map(Zn=>Zn===V?{...Zn,path:Ue.id,name:Ue.name??E.name,uploading:!1}:Zn))}catch(ae){o(Ue=>Ue.filter(Ui=>Ui!==V)),ze(w("composer.failUpload")+ft(ae),!0)}},ie=async E=>{E.preventDefault();for(let G of E.dataTransfer.files)(G.type.startsWith("image/")||G.type.startsWith("text/"))&&await ui(G)},Xn=E=>{z&&te.call("thread.setMode",{id:z.id,mode:E})},$e=E=>{z&&te.call("thread.setEffort",{id:z.id,effort:E})},Pe=E=>{z&&te.call("thread.setCursorOpts",{id:z.id,...E}).catch(G=>ze(ft(G),!0))},In=z?.model?I?.models?.find(E=>E.id===z.model):I?.models?.find(E=>E.isDefault)??I?.models?.[0],Pt=(In?.thinkingOptions??[]).map(E=>{let G=E,V=typeof G.id=="string"?G.id:typeof G.reasoningEffort=="string"?G.reasoningEffort:null,ae=G.id,Ue=V??(ae&&typeof ae.reasoningEffort=="string"?ae.reasoningEffort:null);return Ue?{id:Ue,label:typeof G.label=="string"?G.label:Ue}:null}).filter(E=>E!==null),Ns=typeof In?.defaultThinking=="string"?In.defaultThinking:null,As=Pt.length>0,ee=(()=>{if(!z?.model){let V=I?.models?.find(ae=>ae.isDefault);return V?`${w("composer.defaultModel")} \xB7 ${V.name}`:w("composer.defaultModel")}let G=I?.models?.find(V=>V.id===z.model)?.name??z.model;return z.cursorFast&&(G+=" \xB7 Fast"),G})();return e.currentThreadId?(0,j.jsxs)("div",{className:`composer${q?" waiting":""}`,onDrop:ie,onDragOver:E=>E.preventDefault(),children:[n.queue.length>0&&(0,j.jsx)("div",{className:"q-list",children:n.queue.map(E=>(0,j.jsxs)("div",{className:"q-item",children:[(0,j.jsx)("span",{className:"q-text",children:E.text}),(0,j.jsx)("button",{className:"ibtn",title:w("common.remove"),onClick:()=>{te.call("thread.queueRemove",{id:z?.id,queueId:E.id}).catch(()=>{})},children:(0,j.jsx)(Me,{name:"x",size:12})})]},E.id))}),A==="bypassPermissions"&&(0,j.jsx)("div",{className:"cp-danger",children:w("composer.bypassWarn")}),(0,j.jsxs)("div",{className:`cp-card${q?" waiting":""}${A==="bypassPermissions"?" danger":""}`,children:[D&&a.some(E=>E.mime.startsWith("image/"))&&(0,j.jsx)("div",{className:"att-note",children:Ce("composer.imagesByPath",{agent:I?.name??""})}),a.length>0&&(0,j.jsx)("div",{className:"att-bar",children:a.map((E,G)=>(0,j.jsxs)("span",{className:`att${E.uploading?" up":""}`,children:[E.mime.startsWith("image/")&&E.path?(0,j.jsx)("img",{src:LT(E.path),alt:E.name}):(0,j.jsx)(Me,{name:"attach",size:12}),(0,j.jsx)("span",{className:"att-name",children:E.name}),E.uploading&&(0,j.jsx)("span",{className:"att-prog",children:"\u2026"}),(0,j.jsx)("button",{className:"att-x",onClick:()=>o(V=>V.filter((ae,Ue)=>Ue!==G)),children:"\xD7"})]},G))}),(0,j.jsxs)("div",{className:"cp-ta-wrap",children:[J&&(0,j.jsx)("div",{className:"pop agent-picker slash-pop",role:"listbox",children:(0,j.jsx)("div",{className:"ap-scroll",children:he.length===0?(0,j.jsx)("div",{className:"ap-empty",children:w(O?"composer.slashLoading":"composer.slashNoCommands")}):he.map(E=>{if(E.type==="heading")return(0,j.jsx)("div",{className:"slash-h",children:E.labelKey==="slashGroupCommand"?w("composer.slashGroupCommand"):w("composer.slashGroupSkill")},E.id);let V=Be.indexOf(E.command)===x;return(0,j.jsxs)("button",{type:"button",role:"option","aria-selected":V,className:`mi slash-item${V?" sel":""}`,onMouseDown:ae=>ae.preventDefault(),onClick:()=>{N.current=!1,r(sv(E.command.name))},children:[(0,j.jsxs)("span",{className:"slash-name",children:["/",E.command.name]}),(0,j.jsx)("span",{className:"slash-desc",children:E.command.description}),E.command.argumentHint?(0,j.jsx)("span",{className:"slash-hint",children:E.command.argumentHint}):null]},E.id)})})}),(0,j.jsx)("textarea",{ref:_,className:"cp-ta",rows:1,placeholder:q?w("composer.waitPerm"):R?w("composer.queuePlaceholder"):w("composer.inputPlaceholder"),value:s,disabled:q,onChange:E=>{N.current=!1,r(E.target.value)},onKeyDown:ci,onPaste:ue})]}),(0,j.jsxs)("div",{className:"cp-bar",children:[(0,j.jsxs)("div",{className:"pill-wrap",ref:p,children:[(0,j.jsxs)("button",{className:"pill",onClick:()=>Ai(!l),title:w("composer.agentModel"),children:[(0,j.jsx)("span",{className:"p-a",children:I?.name??z?.provider??w("composer.agent")}),(0,j.jsx)("span",{className:"p-t",children:ee})]}),l&&(0,j.jsxs)("div",{className:"pop agent-pop agent-picker",children:[(0,j.jsxs)("div",{className:"ap-search",children:[(0,j.jsx)(Me,{name:"search",size:14}),(0,j.jsx)("input",{className:"ap-search-in",autoFocus:!0,placeholder:w("composer.searchAllModels"),value:d,onChange:E=>f(E.target.value)})]}),d.trim()?(0,j.jsxs)("div",{className:"ap-scroll",children:[li.length===0&&(0,j.jsx)("div",{className:"ap-empty",children:w("composer.noModelMatch")}),li.map(({providerId:E,providerName:G,model:V})=>{let ae=L&&E!==z?.provider;return(0,j.jsxs)("button",{className:"mi mi-row",disabled:ae,onClick:()=>{Mi(E,V.id)},children:[(0,j.jsx)("span",{className:"mi-sub",children:G}),(0,j.jsx)("span",{className:"mi-name",children:V.name}),z?.provider===E&&z?.model===V.id&&(0,j.jsx)("span",{className:"mi-check",children:"\u2713"})]},`${E}:${V.id}`)})]}):we&&dt?(0,j.jsxs)("div",{className:"ap-scroll",children:[(0,j.jsxs)("button",{type:"button",className:"ap-back mi",onClick:()=>h(null),children:[(0,j.jsx)("span",{className:"ap-back-icon",children:(0,j.jsx)(Me,{name:"caret",size:14})}),dt.name]}),(0,j.jsxs)("button",{className:"mi model-pick-row",title:dt.models?.find(E=>E.isDefault)?.name??w("composer.defaultModel"),onClick:()=>{Mi(dt.id,null)},children:[(0,j.jsx)("span",{className:"model-pick-name",children:w("composer.defaultModel")}),(()=>{let E=dt.models?.find(G=>G.isDefault);return E?(0,j.jsxs)("span",{className:"mi-sub model-pick-default",children:[" (",E.name,")"]}):null})(),z?.provider===dt.id&&!z?.model?(0,j.jsx)("span",{className:"mi-check",children:"\u2713"}):""]}),(dt.models??[]).filter(E=>!E.isDefault).slice(0,av).map(E=>(0,j.jsxs)("button",{className:"mi model-pick-row",title:E.name,onClick:()=>{Mi(dt.id,E.id)},children:[(0,j.jsx)("span",{className:"model-pick-name",children:E.name}),z?.provider===dt.id&&z?.model===E.id?(0,j.jsx)("span",{className:"mi-check",children:"\u2713"}):""]},E.id)),(dt.models?.length??0)>av&&(0,j.jsx)("div",{className:"ap-empty",children:Ce("composer.moreModels",{n:String((dt.models?.length??0)-av)})})]}):(0,j.jsxs)("div",{className:"ap-scroll",children:[(0,j.jsx)("div",{className:"mlabel",children:L?w("composer.agentLocked"):w("composer.providers")}),L&&(0,j.jsx)("div",{className:"ap-empty",children:w("composer.agentLockedHint")}),qe.length===0&&(0,j.jsx)("div",{className:"ap-empty",children:w("composer.providersLoading")}),qe.map(E=>{let V=oi(E)&&(!L||E.id===z?.provider),ae=E.models?.length??0,Ue=E.name?.trim()||E.id;return(0,j.jsxs)("button",{className:"mi mi-row provider-pick-row",disabled:!V,onClick:()=>{V&&h(E.id)},children:[(0,j.jsx)("span",{className:"provider-pick-name",children:Ue}),(0,j.jsxs)("span",{className:"provider-pick-meta",children:[E.id===z?.provider&&(0,j.jsx)("span",{className:"mi-tag",children:"Current"}),(0,j.jsx)("span",{className:"mi-meta",children:ae===1?"1 model":`${ae} models`}),V&&(0,j.jsx)("span",{className:"mi-caret",children:(0,j.jsx)(Me,{name:"caret",size:14})}),E.enabled===!1&&(0,j.jsx)("span",{className:"dlg-hint",children:"Disabled"}),E.enabled!==!1&&E.status==="planned"&&(0,j.jsx)("span",{className:"dlg-hint",children:"Not available"}),E.enabled!==!1&&E.status!=="planned"&&!E.available&&(0,j.jsx)("span",{className:"dlg-hint",children:"Not detected"})]})]},E.id)})]})]})]}),As&&(0,j.jsxs)("select",{className:"pill sel",value:z?.effort??"",title:w("composer.effortTitle"),onChange:E=>$e(E.target.value||null),children:[(0,j.jsx)("option",{value:"",children:Ns?Ce("composer.defaultEffortNamed",{level:Ns}):w("composer.defaultEffort")}),Pt.map(E=>(0,j.jsx)("option",{value:E.id,children:E.label},E.id))]}),$.length>1&&(0,j.jsx)("select",{className:`pill sel${A==="bypassPermissions"?" danger":""}`,value:$.some(E=>E.id===A)?A:$[0].id,title:re?.desc,onChange:E=>Xn(E.target.value),children:$.map(E=>(0,j.jsx)("option",{value:E.id,children:E.label},E.id))}),z?.provider==="cursor"&&(0,j.jsxs)("select",{className:"pill sel cursor-fast",value:z.cursorFast?"fast":"off",title:"Fast",onChange:E=>Pe({cursorFast:E.target.value==="fast"}),children:[(0,j.jsx)("option",{value:"off",children:"Fast: Off"}),(0,j.jsx)("option",{value:"fast",children:"Fast: On"})]}),(0,j.jsx)("button",{className:"ibtn",title:w("composer.attachTitle"),onClick:()=>v.current?.click(),children:(0,j.jsx)(Me,{name:"attach"})}),(0,j.jsx)("input",{ref:v,type:"file",hidden:!0,multiple:!0,accept:"image/*,.txt,.md,.log,.json,.csv",onChange:E=>{for(let G of E.target.files??[])ui(G);E.target.value=""}}),(0,j.jsx)("div",{className:"cp-right",children:R?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)("span",{className:"cp-clock",children:[b,"s"]}),(0,j.jsx)("button",{className:"cp-stop",title:w("common.stop"),onClick:()=>{te.call("thread.interrupt",{id:z?.id})},children:(0,j.jsx)(Me,{name:"stop"})})]}):(0,j.jsx)("button",{className:"cp-send",title:w("common.send"),disabled:q||!s.trim()&&a.length===0||a.some(E=>E.uploading),onClick:()=>{yi("queue")},children:(0,j.jsx)(Me,{name:"send"})})})]})]})]}):null}var Ge,j,av,jT=ce(()=>{Ge=oe(Ot(),1);cl();un();Wn();Cl();Nn();af();Ur();lf();vs();iu();iv();xi();$T();j=oe(De(),1),av=150});function XT(){let e=pe(),{projects:t,threads:i}=ct(),n=Mn(),r=Tl().showThinking?n.items:n.items.filter(C=>C.kind!=="reasoning"),a=(0,On.useRef)(null),[o,l]=(0,On.useState)(!0),[c,u]=(0,On.useState)(!1),h=t.find(C=>C.id===e.currentProjectId)??null,d=e.currentThreadId,f=d?i.find(C=>C.id===d)??null:null,p=h&&f&&f.projectId===h.id?f.id:null;(0,On.useEffect)(()=>{p?n.open(p):n.close(),l(!0),u(!1)},[p]);let _=(0,On.useCallback)(C=>{let N=r[C];if(!N)return 80;switch(N.kind){case"user":return 60;case"assistant":case"reasoning":return 120;case"toolgroup":return 30+N.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]),v=ST({count:r.length,getScrollElement:()=>a.current,estimateSize:_,getItemKey:C=>r[C]?.key??C,overscan:8,measureElement:C=>C.getBoundingClientRect().height}),g=r.length;(0,On.useEffect)(()=>{let C=a.current;C&&(o?C.scrollTop=C.scrollHeight:u(!0))},[g,o]);let m=()=>{let C=a.current;if(!C)return;let N=C.scrollHeight-C.scrollTop-C.clientHeight<60;l(N),N&&u(!1)},b=()=>{a.current?.scrollTo({top:a.current.scrollHeight,behavior:"smooth"}),l(!0),u(!1)},S=C=>{p&&te.call("thread.send",{id:p,text:C})},x=()=>{n.lastUserText&&S(n.lastUserText)};return t.length===0?(0,Le.jsx)("div",{className:"scroll",ref:a,children:(0,Le.jsx)(VT,{kind:"no-projects"})}):p?(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)("div",{className:"scroll",ref:a,onScroll:m,children:(0,Le.jsxs)("div",{className:"tl-wrap",children:[(0,Le.jsx)("div",{style:{height:v.getTotalSize(),position:"relative"},children:v.getVirtualItems().map(C=>{let N=r[C.index];return N?(0,Le.jsx)("div",{"data-index":C.index,ref:v.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${C.start}px)`},children:(0,Le.jsx)(BT,{it:N,threadId:p,onEditResend:S,onRetryLast:x})},C.key):null})}),n.items.length===0&&!n.error&&(0,Le.jsx)("div",{className:"sb-empty",children:w("chat.emptyHint")}),n.error&&(0,Le.jsx)("div",{className:"nt error",children:Ta(n.error)})]})}),!o&&(0,Le.jsxs)("button",{className:"jump",onClick:b,title:w("chat.jumpBottom"),children:[(0,Le.jsx)(Me,{name:"caret"}),c&&(0,Le.jsx)("span",{className:"jd"})]}),(0,Le.jsx)(YT,{})]}):(0,Le.jsx)("div",{className:"scroll",ref:a,children:(0,Le.jsx)("div",{className:"empty-wrap",children:h?(0,Le.jsxs)(Le.Fragment,{children:[(0,Le.jsx)("div",{className:"cp-hero-t",children:Ce("chat.newInProject",{name:h.name})}),(0,Le.jsx)(XI,{projectId:h.id})]}):(0,Le.jsx)(VT,{kind:"no-projects"})})})}function VT({kind:e}){return(0,Le.jsxs)("div",{className:"empty-wrap workspace-empty",children:[(0,Le.jsx)("div",{className:"cp-hero-t",children:w("sidebar.noProjectsTitle")}),(0,Le.jsx)("div",{className:"cp-hero-s",children:w("sidebar.noProjectsSub")}),(0,Le.jsx)("div",{className:"empty-actions",children:(0,Le.jsx)("button",{type:"button",className:"btn primary",onClick:()=>window.dispatchEvent(new CustomEvent("open-new-project")),children:w("sidebar.newProject")})})]})}function XI({projectId:e}){let t=pe(),i=Tl(),[n,s]=(0,On.useState)(""),[r,a]=(0,On.useState)(!1),o=async()=>{if(!(!n.trim()||r)){a(!0);try{let l=await ll(),c=await te.call("settings.get"),u=await te.call("threads.create",{projectId:e,provider:l,model:null,mode:c.defaultMode??"default",effort:c.defaultEffort??null});t.select(e,u.id),await te.call("thread.send",{id:u.id,text:n.trim()})}catch(l){ze(w("chat.failSend")+ft(l),!0),a(!1)}}};return(0,Le.jsxs)("div",{className:"cp-card",style:{marginTop:18},children:[(0,Le.jsx)("textarea",{className:"cp-ta",rows:3,placeholder:w("chat.emptyPlaceholder"),value:n,onChange:l=>s(l.target.value),onKeyDown:l=>{if(Tn(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,Le.jsxs)("div",{className:"cp-bar",children:[(0,Le.jsx)("span",{className:"dlg-hint",children:w("chat.autoNewThread")}),(0,Le.jsx)("div",{className:"cp-right",children:(0,Le.jsx)("button",{className:"cp-send",disabled:!n.trim()||r,onClick:()=>{o()},title:w("common.send"),children:(0,Le.jsx)(Me,{name:"send"})})})]})]})}var On,Le,ZT=ce(()=>{On=oe(Ot(),1);cl();wT();un();Wn();Cl();lf();jT();Ur();Nn();vs();iu();xi();Le=oe(De(),1)});function JT({onClose:e}){let{projects:t,threads:i,providers:n}=ct(),s=pe(),[r,a]=(0,Es.useState)(""),[o,l]=(0,Es.useState)(0),c=(0,Es.useRef)(null);(0,Es.useEffect)(()=>{c.current?.focus()},[]);let u=(0,Es.useMemo)(()=>{let f=[],p=r.trim().toLowerCase(),_=g=>!p||g.toLowerCase().includes(p),v=[[w("palette.actNewThread"),()=>{let g=s.currentProjectId??t[0]?.id;g&&d(g)}],[w("palette.actSettings"),()=>window.dispatchEvent(new CustomEvent("open-settings"))],[w("palette.actTheme"),()=>{ZI()}],[w("palette.actChanges"),()=>s.openPanel("changes")],[w("palette.actFiles"),()=>s.openPanel("files")],[w("palette.actTerminal"),()=>s.openPanel("terminal")],[w("palette.actImport"),()=>{let g=s.currentProjectId??t[0]?.id;g&&window.dispatchEvent(new CustomEvent("open-import",{detail:{projectId:g}}))}]];for(let[g,m]of v)_(g)&&f.push({id:`act:${g}`,label:g,hint:w("palette.hintAction"),run:m});for(let g of t)_(g.name)&&f.push({id:`p:${g.id}`,label:g.name,hint:w("palette.hintProject"),run:()=>s.select(g.id,null)});for(let g of i){let m=t.find(S=>S.id===g.projectId),b=`${g.title} ${m?.name??""}`;_(b)&&f.push({id:`t:${g.id}`,label:g.title,hint:m?.name??w("palette.hintThread"),run:()=>s.select(g.projectId,g.id)})}return f.slice(0,30)},[r,t,i]);(0,Es.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"&&!Tn(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 ll(),v=await te.call("threads.create",{projectId:f,provider:_,mode:p.defaultMode??"default",effort:p.defaultEffort??null});pe.getState().select(f,v.id)}catch(p){ze(w("palette.failNew")+ft(p),!0)}}return(0,QT.createPortal)((0,ws.jsx)("div",{className:"dlg-scrim",style:{alignItems:"flex-start",paddingTop:"14vh"},onPointerDown:f=>{f.target===f.currentTarget&&e()},children:(0,ws.jsxs)("div",{className:"dlg cpal",role:"dialog","aria-label":w("palette.aria"),children:[(0,ws.jsx)("input",{ref:c,className:"cpal-in",placeholder:w("palette.placeholder"),value:r,onChange:f=>a(f.target.value),onKeyDown:h}),(0,ws.jsxs)("div",{className:"cpal-list",children:[u.map((f,p)=>(0,ws.jsxs)("button",{className:`cpal-item${p===o?" on":""}`,onMouseEnter:()=>l(p),onClick:()=>{e(),f.run()},children:[(0,ws.jsx)("span",{className:"cpal-label",children:f.label}),f.hint&&(0,ws.jsx)("span",{className:"cpal-hint",children:f.hint})]},f.id)),u.length===0&&(0,ws.jsx)("div",{className:"sb-empty",children:w("palette.noMatch")})]})]})}),document.body)}async function ZI(){let e=document.documentElement.dataset.theme==="dark"?"light":"dark";document.documentElement.dataset.theme=e;try{await te.call("settings.set",{patch:{theme:e}})}catch{}}var Es,QT,ws,eN=ce(()=>{Es=oe(Ot(),1);cl();QT=oe(co(),1);Wn();un();Nn();vs();xi();ws=oe(De(),1)});function ez(e){return e.replace(/\r?\n/g,"\r")}function tz(e,t){return t?"\x1B[200~"+e+"\x1B[201~":e}function iz(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()}function nz(e,t,i,n){if(e.stopPropagation(),e.clipboardData){let s=e.clipboardData.getData("text/plain");lA(s,t,i,n)}}function lA(e,t,i,n){e=ez(e),e=tz(e,i.decPrivateModes.bracketedPasteMode&&n.rawOptions.ignoreBracketedPasteMode!==!0),i.triggerDataEvent(e,!0),t.value=""}function cA(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 nN(e,t,i,n,s){cA(e,t,i),s&&n.rightClickSelect(e),t.value=n.selectionText,t.select()}function Vr(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function Of(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 az(e){return e[Cv]||[]}function si(e){if(ov.has(e))return ov.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");oz(t,i,s)};return t._id=e,ov.set(e,t),t}function oz(e,t,i){t[sN]===t?t[Cv].push({id:e,index:i}):(t[Cv]=[{id:e,index:i}],t[sN]=t)}function uz(e,t){if(confirm(`Do you want to navigate to ${t}? +`):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(` -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 pf(e){pz(e)||fz.onUnexpectedError(e)}function pz(e){return e instanceof mz?!0:e instanceof Error&&e.name===Tv&&e.message===Tv}function gz(e){return e?new Error(`Illegal argument: ${e}`):new Error("Illegal argument")}function _z(e,t,i=0,n=e.length){let s=i,r=n;for(;st(e(i),e(n))}function Sz(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 Ez(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 kz(e){ja=e}function Df(e){return ja?.trackDisposable(e),e}function Lf(e){ja?.markAsDisposed(e)}function yu(e,t){ja?.setParent(e,t)}function Tz(e,t){if(ja)for(let i of e)ja.setParent(i,t)}function cN(e){return ja?.markAsSingleton(e),e}function Va(e){if(Rv.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 Nz(...e){let t=pt(()=>Va(e));return Tz(e,t),t}function pt(e){let t=Df({dispose:Ez(()=>{Lf(t),e()})});return t}function Fz(e,t,i){typeof t=="string"&&(t=e.matchMedia(t)),t.addEventListener("change",i)}function qz(e){return fb.INSTANCE.getZoomFactor(e)}function Kz(){return vf}function r5(e){if(e.charCode){let i=String.fromCharCode(e.charCode).toUpperCase();return Hv.fromString(i)}let t=e.keyCode;if(t===3)return 7;if(Uv)switch(t){case 59:return 85;case 60:if(Zz)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(ks)return 57;break}else if(_f&&(ks&&t===93||!ks&&t===92))return 57;return i5[t]||0}function u5(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 m5(e){return 55296<=e&&e<=56319}function wN(e){return 56320<=e&&e<=57343}function g5(e,t){return(e-55296<<10)+(t-56320)+65536}function _5(e){return _b(e,0)}function _b(e,t){switch(typeof e){case"object":return e===null?er(349,t):Array.isArray(e)?b5(e,t):y5(e,t);case"string":return BA(e,t);case"boolean":return v5(e,t);case"number":return er(e,t);case"undefined":return er(937,t);default:return er(617,t)}}function er(e,t){return(t<<5)-t+e|0}function v5(e,t){return er(e?433:863,t)}function BA(e,t){t=er(149417,t);for(let i=0,n=e.length;i_b(n,i),t)}function y5(e,t){return t=er(181387,t),Object.keys(e).sort().reduce((i,n)=>(i=BA(n,i),_b(e[n],i)),t)}function dv(e,t,i=32){let n=i-t,s=~((1<>>n)>>>0}function EN(e,t=0,i=e.byteLength,n=0){for(let s=0;si.toString(16).padStart(2,"0")).join(""):S5((e>>>0).toString(16),t/4)}function ve(e,t,i,n){return new x5(e,t,i,n)}function C5(e,t){return function(i){return t(new uu(e,i))}}function k5(e){return function(t){return e(new Fv(t))}}function A5(e){let t=e.getBoundingClientRect(),i=Vn(e);return{left:t.left+i.scrollX,top:t.top+i.scrollY,width:t.width,height:t.height}}function zA(e,t,i,...n){let s=M5.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 O5(e,t,...i){return zA("http://www.w3.org/1999/xhtml",e,t,...i)}function Zi(e){return typeof e=="number"?`${e}px`:e}function _u(e){return new R5(e)}function D5(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 pv(e,t){let i=t-e;return function(n){return e+i*H5(n)}}function P5(e,t,i){return function(n){return ne?"D":"C",wu(Math.abs(s-e),Su(a,n));a=r>t?"D":"C";let o=Math.abs(r-t),l=x6(r>t?e:s,i)+(o-1)*i.cols+1+E6(r>t?s:e,i);return wu(l,Su(a,n))}function E6(e,t){return e-1}function x6(e,t){return t.cols-e}function C6(e,t,i,n,s,r){return If(t,n,s,r).length===0?"":wu(VA(e,t,e,t-Xa(t,s),!1,s).length,Su("D",r))}function If(e,t,i,n){let s=e-Xa(e,i),r=t-Xa(t,i),a=Math.abs(s-r)-T6(e,t,i);return wu(a,Su(jA(e,t),n))}function k6(e,t,i,n,s,r){let a;If(t,n,s,r).length>0?a=n-Xa(n,s):a=t;let o=n,l=N6(e,t,i,n,s,r);return wu(VA(e,a,i,o,l==="C",s).length,Su(l,r))}function T6(e,t,i){let n=0,s=e-Xa(e,i),r=t-Xa(t,i);for(let a=0;a=0&&e0?a=n-Xa(n,s):a=t,e=i&&at?"A":"B"}function VA(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 Su(e,t){let i=t?"O":"[";return P.ESC+i+e}function wu(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 F6(e,t,i,n,s,r){let a=[];for(let o=0;o=o&&n0&&(v>h||u[v].getTrimmedLength()===0);v--)_++;_>0&&(a.push(o+u.length-_),a.push(_)),o+=u.length-1}return a}function q6(e,t){let i=[],n=0,s=t[n],r=0;for(let a=0;aEu(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 Eu(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 V6(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 vv(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 Z6(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 Sv(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 l4(e,t=16){let[i,n,s]=e;return`rgb:${Sv(i,t)}/${Sv(n,t)}/${Sv(s,t)}`}function ZN(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 g4(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=P.ESC+"OA":s.key=P.ESC+"[A":e.key==="UIKeyInputLeftArrow"?t?s.key=P.ESC+"OD":s.key=P.ESC+"[D":e.key==="UIKeyInputRightArrow"?t?s.key=P.ESC+"OC":s.key=P.ESC+"[C":e.key==="UIKeyInputDownArrow"&&(t?s.key=P.ESC+"OB":s.key=P.ESC+"[B");break;case 8:s.key=e.ctrlKey?"\b":P.DEL,e.altKey&&(s.key=P.ESC+s.key);break;case 9:if(e.shiftKey){s.key=P.ESC+"[Z";break}s.key=P.HT,s.cancel=!0;break;case 13:s.key=e.altKey?P.ESC+P.CR:P.CR,s.cancel=!0;break;case 27:s.key=P.ESC,e.altKey&&(s.key=P.ESC+P.ESC),s.cancel=!0;break;case 37:if(e.metaKey)break;r?s.key=P.ESC+"[1;"+(r+1)+"D":t?s.key=P.ESC+"OD":s.key=P.ESC+"[D";break;case 39:if(e.metaKey)break;r?s.key=P.ESC+"[1;"+(r+1)+"C":t?s.key=P.ESC+"OC":s.key=P.ESC+"[C";break;case 38:if(e.metaKey)break;r?s.key=P.ESC+"[1;"+(r+1)+"A":t?s.key=P.ESC+"OA":s.key=P.ESC+"[A";break;case 40:if(e.metaKey)break;r?s.key=P.ESC+"[1;"+(r+1)+"B":t?s.key=P.ESC+"OB":s.key=P.ESC+"[B";break;case 45:!e.shiftKey&&!e.ctrlKey&&(s.key=P.ESC+"[2~");break;case 46:r?s.key=P.ESC+"[3;"+(r+1)+"~":s.key=P.ESC+"[3~";break;case 36:r?s.key=P.ESC+"[1;"+(r+1)+"H":t?s.key=P.ESC+"OH":s.key=P.ESC+"[H";break;case 35:r?s.key=P.ESC+"[1;"+(r+1)+"F":t?s.key=P.ESC+"OF":s.key=P.ESC+"[F";break;case 33:e.shiftKey?s.type=2:e.ctrlKey?s.key=P.ESC+"[5;"+(r+1)+"~":s.key=P.ESC+"[5~";break;case 34:e.shiftKey?s.type=3:e.ctrlKey?s.key=P.ESC+"[6;"+(r+1)+"~":s.key=P.ESC+"[6~";break;case 112:r?s.key=P.ESC+"[1;"+(r+1)+"P":s.key=P.ESC+"OP";break;case 113:r?s.key=P.ESC+"[1;"+(r+1)+"Q":s.key=P.ESC+"OQ";break;case 114:r?s.key=P.ESC+"[1;"+(r+1)+"R":s.key=P.ESC+"OR";break;case 115:r?s.key=P.ESC+"[1;"+(r+1)+"S":s.key=P.ESC+"OS";break;case 116:r?s.key=P.ESC+"[15;"+(r+1)+"~":s.key=P.ESC+"[15~";break;case 117:r?s.key=P.ESC+"[17;"+(r+1)+"~":s.key=P.ESC+"[17~";break;case 118:r?s.key=P.ESC+"[18;"+(r+1)+"~":s.key=P.ESC+"[18~";break;case 119:r?s.key=P.ESC+"[19;"+(r+1)+"~":s.key=P.ESC+"[19~";break;case 120:r?s.key=P.ESC+"[20;"+(r+1)+"~":s.key=P.ESC+"[20~";break;case 121:r?s.key=P.ESC+"[21;"+(r+1)+"~":s.key=P.ESC+"[21~";break;case 122:r?s.key=P.ESC+"[23;"+(r+1)+"~":s.key=P.ESC+"[23~";break;case 123:r?s.key=P.ESC+"[24;"+(r+1)+"~":s.key=P.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=P.NUL:e.keyCode>=51&&e.keyCode<=55?s.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?s.key=P.DEL:e.keyCode===219?s.key=P.ESC:e.keyCode===220?s.key=P.FS:e.keyCode===221&&(s.key=P.GS);else if((!i||n)&&e.altKey&&!e.metaKey){let a=m4[e.keyCode]?.[e.shiftKey?1:0];if(a)s.key=P.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=P.ESC+l}else if(e.keyCode===32)s.key=P.ESC+(e.ctrlKey?P.NUL:" ");else if(e.key==="Dead"&&e.code.startsWith("Key")){let o=e.code.slice(3,4);e.shiftKey||(o=o.toLowerCase()),s.key=P.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=P.US),e.key==="@"&&(s.key=P.NUL));break}return s}function w4(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 x4(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var oA,QI,JI,kt,ne,tN,Ev,iN,xv,sz,rz,uA,Xr,xu,wf,Bn,sN,Cv,ov,zi,pA,Za,lz,hb,mA,Pi,gA,cz,Cu,kv,Rf,ir,db,nr,hz,_A,Ol,vA,dz,fz,Tv,mz,rN,Av,vz,Mv,yz,aN,oN,lN,q8,wz,Rv,xz,ja,Cz,wA,Zr,xe,Ml,gn,Dv,St,uN,Az,Mz,Oz,hN,Rz,ni,Bv,Dz,dN,CA,Lz,zv,Bz,Iz,zz,mf,Pz,Uz,gf,Z,Hz,Pv,fb,W8,G8,Rl,Uv,_f,pb,NA,$8,Y8,vf,Al,Ef,xf,gu,Wz,AA,MA,Gz,$z,Yz,jz,cf,bf,fN,Vz,Js,tr,mn,OA,Xz,lv,RA,ks,Zz,cv,Qz,j8,Ts,Gr,pN,Jz,e5,t5,V8,X8,Z8,Q8,$r,J8,mb,uv,mN,gN,i5,Hv,n5,s5,a5,o5,l5,c5,Fv,_N,h5,uu,vN,LA,bN,d5,gb,f5,p5,hv,yN,SN,w5,e9,Vn,t9,i9,n9,xN,s9,r9,E5,a9,o9,x5,CN,T5,Cf,N5,fv,kN,l9,Jt,M5,R5,PA,jn,hu,L5,vb,TN,B5,I5,z5,NN,AN,F5,q5,UA,HA,K5,W5,G5,MN,ON,$5,Gv,Y5,j5,V5,$v,Yv,Z5,xs,Yr,su,kf,P,vu,jv,Vv,ei,ti,ii,Ct,RN,Mt,ht,vt,Ti,bu,Q5,Tf,Xv,n6,s6,mv,Rn,hf,LN,ru,df,a6,Zv,Qv,FA,o6,l6,c6,u6,h6,Jv,f6,qA,Bf,ku,Tu,KA,p6,WA,Nf,g6,_6,GA,yb,$A,YA,v6,b6,Af,y6,eb,S6,A6,gv,M6,O6,R6,D6,L6,tb,IN,zN,Kt,Ga,du,PN,UN,au,B6,ib,I6,z6,P6,U6,nb,H6,HN,Te,zt,ff,_v,fu,ZA,G6,Gt,$a,FN,qN,$6,JA,eM,sb,Nl,Y6,j6,KN,WN,rb,GN,bv,$N,ab,yv,X6,Wt,Q6,Ya,J6,ou,e4,tM,lu,t4,pn,cu,i4,mu,jN,n4,Ln,s4,r4,a4,o4,c4,jr,XN,QN,JN,u4,lb,h4,tA,d4,f4,cb,iA,p4,m4,At,_4,wv,nA,v4,b4,y4,S4,sA,rA,Mf,ub,E4,C4,k4,aA,T4,N4,A4,M4,Cs,iM,nM=ce(()=>{oA=Object.defineProperty,QI=Object.getOwnPropertyDescriptor,JI=(e,t)=>{for(var i in t)oA(e,i,{get:t[i],enumerable:!0})},kt=(e,t,i,n)=>{for(var s=n>1?void 0:n?QI(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&&oA(t,i,s),s},ne=(e,t)=>(i,n)=>t(i,n,e),tN="Terminal input",Ev={get:()=>tN,set:e=>tN=e},iN="Too much output to announce, navigate to rows manually to read",xv={get:()=>iN,set:e=>iN=e};sz=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}},rz=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 v=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,g=v-p;for(;c=i)return 0;if(_=e[c++],(_&192)!==128){c--,d=!0;break}else this.interim[p++]=_,f<<=6,f|=_&63}d||(v===2?f<128?c--:t[n++]=f:v===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}},uA="",Xr=" ",xu=class hA{constructor(){this.fg=0,this.bg=0,this.extended=new wf}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 hA;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}},wf=class dA{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 dA(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Bn=class fA extends xu{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new wf,this.combinedData=""}static fromCharData(t){let i=new fA;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?Vr(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()]}},sN="di$target",Cv="di$dependencies",ov=new Map;zi=si("BufferService"),pA=si("CoreMouseService"),Za=si("CoreService"),lz=si("CharsetService"),hb=si("InstantiationService"),mA=si("LogService"),Pi=si("OptionsService"),gA=si("OscLinkService"),cz=si("UnicodeService"),Cu=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 Bn,a=i.getTrimmedLength(),o=-1,l=-1,c=!1;for(let u=0;us?s.activate(p,_,d):uz(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([ne(0,zi),ne(1,Pi),ne(2,gA)],kv);Rf=si("CharSizeService"),ir=si("CoreBrowserService"),db=si("MouseService"),nr=si("RenderService"),hz=si("SelectionService"),_A=si("CharacterJoinerService"),Ol=si("ThemeService"),vA=si("LinkProviderService"),dz=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?rN.isErrorNoTelemetry(e)?new rN(e.message+` +`)};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}? + +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+` `+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)}},fz=new dz;Tv="Canceled";mz=class extends Error{constructor(){super(Tv),this.name=this.message}};rN=class Nv extends Error{constructor(t){super(t),this.name="CodeExpectedError"}static fromError(t){if(t instanceof Nv)return t;let i=new Nv;return i.message=t.message,i.stack=t.stack,i}static isErrorNoTelemetry(t){return t.name==="CodeExpectedError"}},Av=class bA extends Error{constructor(t){super(t||"An unexpected bug occurred."),Object.setPrototypeOf(this,bA.prototype)}};vz=class yA{constructor(t){this._array=t,this._findLastMonotonousLastIdx=0}findLastMonotonous(t){if(yA.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=_z(this._array,t,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=i+1,i===-1?void 0:this._array[i]}};vz.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})(Mv||(Mv={}));yz=(e,t)=>e-t,aN=class Ov{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 Ov(i=>this.iterate(n=>t(n)?i(n):!0))}map(t){return new Ov(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||Mv.isGreaterThan(t(s,i)))&&(n=!1,i=s),!0)),i}};aN.empty=new aN(e=>{});q8=class{constructor(e,t){this.toKey=t,this._map=new Map,this[oN]="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))}[(lN=Symbol.iterator,oN=Symbol.toStringTag,lN)](){return this.values()}},wz=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 x=S.length-1;x>=0;x--)yield S[x]}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,x){let C=0;for(let N of S)if(x(N,C++))return!0;return!1}e.some=u;function h(S,x){for(let C of S)if(x(C))return C}e.find=h;function*d(S,x){for(let C of S)x(C)&&(yield C)}e.filter=d;function*f(S,x){let C=0;for(let N of S)yield x(N,C++)}e.map=f;function*p(S,x){let C=0;for(let N of S)yield*x(N,C++)}e.flatMap=p;function*_(...S){for(let x of S)yield*x}e.concat=_;function v(S,x,C){let N=C;for(let M of S)N=x(N,M);return N}e.reduce=v;function*g(S,x,C=S.length){for(x<0&&(x+=S.length),C<0?C+=S.length:C>S.length&&(C=S.length);xi.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 wz;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(bz(l=>l.idx,yz));let a="",o=0;for(let l of n.slice(0,t)){o++;let c=s(l),u=[];for(let h=0;h{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[_,v]of Object.entries(p))u.unshift(` - stacktraces of ${v.length} other leaks continue with ${_}`);u.unshift(d)}a+=` +`)),p=n5([...f].map(_=>s(_)[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+=` ==================== Leaking disposable ${o}/${n.length}: ${l.value.constructor.name} ==================== @@ -109,21 +111,21 @@ ${u.join(` ... and ${n.length-t} more leaking disposables -`),{leaks:n,details:a}}};Cz.idx=0;if(xz){let e="__is_disposable_tracked__";kz(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!==xe.None)try{t[e]=!0}catch{}}markAsDisposed(t){if(t&&t!==xe.None)try{t[e]=!0}catch{}}markAsSingleton(t){}})}wA=class EA{constructor(){this._toDispose=new Set,this._isDisposed=!1,Df(this)}dispose(){this._isDisposed||(Lf(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Va(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 yu(t,this),this._isDisposed?EA.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),yu(t,null))}};wA.DISABLE_DISPOSED_WARNING=!1;Zr=wA,xe=class{constructor(){this._store=new Zr,Df(this),yu(this._store,this)}dispose(){Lf(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};xe.None=Object.freeze({dispose(){}});Ml=class{constructor(){this._isDisposed=!1,Df(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&yu(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,Lf(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&yu(e,null),e}},gn=typeof window=="object"?window:globalThis,Dv=class Lv{constructor(t){this.element=t,this.next=Lv.Undefined,this.prev=Lv.Undefined}};Dv.Undefined=new Dv(void 0);St=Dv,uN=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}},Az=globalThis.performance&&typeof globalThis.performance.now=="function",Mz=class xA{static create(t){return new xA(t)}constructor(t){this._now=Az&&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}},Oz=!1,hN=!1,Rz=!1;(e=>{e.None=()=>xe.None;function t(I){if(Rz){let{onDidAddListener:R}=I,q=zv.create(),T=0;I.onDidAddListener=()=>{++T===2&&(console.warn("snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here"),q.print()),R?.()}}}function i(I,R){return d(I,()=>{},0,void 0,!0,void 0,R)}e.defer=i;function n(I){return(R,q=null,T)=>{let D=!1,A;return A=I($=>{if(!D)return A?A.dispose():D=!0,R.call(q,$)},null,T),D&&A.dispose(),A}}e.once=n;function s(I,R,q){return u((T,D=null,A)=>I($=>T.call(D,R($)),null,A),q)}e.map=s;function r(I,R,q){return u((T,D=null,A)=>I($=>{R($),T.call(D,$)},null,A),q)}e.forEach=r;function a(I,R,q){return u((T,D=null,A)=>I($=>R($)&&T.call(D,$),null,A),q)}e.filter=a;function o(I){return I}e.signal=o;function l(...I){return(R,q=null,T)=>{let D=Nz(...I.map(A=>A($=>R.call(q,$))));return h(D,T)}}e.any=l;function c(I,R,q,T){let D=q;return s(I,A=>(D=R(D,A),D),T)}e.reduce=c;function u(I,R){let q,T={onWillAddFirstListener(){q=I(D.fire,D)},onDidRemoveLastListener(){q?.dispose()}};R||t(T);let D=new Z(T);return R?.add(D),D.event}function h(I,R){return R instanceof Array?R.push(I):R&&R.add(I),I}function d(I,R,q=100,T=!1,D=!1,A,$){let re,L,Q,Ne=0,he,Be={leakWarningThreshold:A,onWillAddFirstListener(){re=I(qe=>{Ne++,L=R(L,qe),T&&!Q&&(J.fire(L),L=void 0),he=()=>{let dt=L;L=void 0,Q=void 0,(!T||Ne>1)&&J.fire(dt),Ne=0},typeof q=="number"?(clearTimeout(Q),Q=setTimeout(he,q)):Q===void 0&&(Q=0,queueMicrotask(he))})},onWillRemoveListener(){D&&Ne>0&&he?.()},onDidRemoveLastListener(){he=void 0,re.dispose()}};$||t(Be);let J=new Z(Be);return $?.add(J),J.event}e.debounce=d;function f(I,R=0,q){return e.debounce(I,(T,D)=>T?(T.push(D),T):[D],R,void 0,!0,void 0,q)}e.accumulate=f;function p(I,R=(T,D)=>T===D,q){let T=!0,D;return a(I,A=>{let $=T||!R(A,D);return T=!1,D=A,$},q)}e.latch=p;function _(I,R,q){return[e.filter(I,R,q),e.filter(I,T=>!R(T),q)]}e.split=_;function v(I,R=!1,q=[],T){let D=q.slice(),A=I(L=>{D?D.push(L):re.fire(L)});T&&T.add(A);let $=()=>{D?.forEach(L=>re.fire(L)),D=null},re=new Z({onWillAddFirstListener(){A||(A=I(L=>re.fire(L)),T&&T.add(A))},onDidAddFirstListener(){D&&(R?setTimeout($):$())},onDidRemoveLastListener(){A&&A.dispose(),A=null}});return T&&T.add(re),re.event}e.buffer=v;function g(I,R){return(q,T,D)=>{let A=R(new b);return I(function($){let re=A.evaluate($);re!==m&&q.call(T,re)},void 0,D)}}e.chain=g;let m=Symbol("HaltChainable");class b{constructor(){this.steps=[]}map(R){return this.steps.push(R),this}forEach(R){return this.steps.push(q=>(R(q),q)),this}filter(R){return this.steps.push(q=>R(q)?q:m),this}reduce(R,q){let T=q;return this.steps.push(D=>(T=R(T,D),T)),this}latch(R=(q,T)=>q===T){let q=!0,T;return this.steps.push(D=>{let A=q||!R(D,T);return q=!1,T=D,A?D:m}),this}evaluate(R){for(let q of this.steps)if(R=q(R),R===m)break;return R}}function S(I,R,q=T=>T){let T=(...re)=>$.fire(q(...re)),D=()=>I.on(R,T),A=()=>I.removeListener(R,T),$=new Z({onWillAddFirstListener:D,onDidRemoveLastListener:A});return $.event}e.fromNodeEventEmitter=S;function x(I,R,q=T=>T){let T=(...re)=>$.fire(q(...re)),D=()=>I.addEventListener(R,T),A=()=>I.removeEventListener(R,T),$=new Z({onWillAddFirstListener:D,onDidRemoveLastListener:A});return $.event}e.fromDOMEventEmitter=x;function C(I){return new Promise(R=>n(I)(R))}e.toPromise=C;function N(I){let R=new Z;return I.then(q=>{R.fire(q)},()=>{R.fire(void 0)}).finally(()=>{R.dispose()}),R.event}e.fromPromise=N;function M(I,R){return I(q=>R.fire(q))}e.forward=M;function O(I,R,q){return R(q),I(T=>R(T))}e.runAndSubscribe=O;class F{constructor(R,q){this._observable=R,this._counter=0,this._hasChanged=!1;let T={onWillAddFirstListener:()=>{R.addObserver(this)},onDidRemoveLastListener:()=>{R.removeObserver(this)}};q||t(T),this.emitter=new Z(T),q&&q.add(this.emitter)}beginUpdate(R){this._counter++}handlePossibleChange(R){}handleChange(R,q){this._hasChanged=!0}endUpdate(R){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function W(I,R){return new F(I,R).emitter.event}e.fromObservable=W;function z(I){return(R,q,T)=>{let D=0,A=!1,$={beginUpdate(){D++},endUpdate(){D--,D===0&&(I.reportChanges(),A&&(A=!1,R.call(q)))},handlePossibleChange(){},handleChange(){A=!0}};I.addObserver($),I.reportChanges();let re={dispose(){I.removeObserver($)}};return T instanceof Zr?T.add(re):Array.isArray(T)&&T.push(re),re}}e.fromObservableLight=z})(ni||(ni={}));Bv=class Iv{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${Iv._idPool++}`,Iv.all.add(this)}start(t){this._stopWatch=new Mz,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}}};Bv.all=new Set,Bv._idPool=0;Dz=Bv,dN=-1,CA=class kA{constructor(t,i,n=(kA._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!==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{if(e instanceof mf)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),gf=new FinalizationRegistry(t=>{typeof t=="string"&&e.push(t)})}Z=class{constructor(e){this._size=0,this._options=e,this._leakageMon=dN>0||this._options?.leakWarningThreshold?new Lz(e?.onListenerError??pf,this._options?.leakWarningThreshold??dN):void 0,this._perfMon=this._options?._profName?new Dz(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(hN){let e=this._listeners;queueMicrotask(()=>{Uz(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 Iz(`${o}. HINT: Stack shows most frequent listener (${l[1]}-times)`,l[0]);return(this._options?.onListenerError||pf)(c),xe.None}if(this._disposed)return xe.None;t&&(e=e.bind(t));let n=new mf(e),s,r;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=zv.create(),s=this._leakageMon.check(n.stack,this._size+1)),hN&&(n.stack=r??zv.create()),this._listeners?this._listeners instanceof mf?(this._deliveryQueue??(this._deliveryQueue=new Hz),this._listeners=[this._listeners,n]):this._listeners.push(n):(this._options?.onWillAddFirstListener?.(this),this._listeners=n,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=pt(()=>{gf?.unregister(a),s?.(),this._removeListener(n)});if(i instanceof Zr?i.add(a):Array.isArray(i)&&i.push(a),gf){let o=new Error().stack.split(` +`))}},_5=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},v5=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},b5=0,Tf=class{constructor(e){this.value=e,this.id=b5++}},y5=2,S5=(e,t)=>{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(` `).slice(2,3).join(` -`).trim(),l=/(file:|vscode-file:\/\/vscode-app)?(\/[^:]*:\d+:\d+)/.exec(o);gf.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*Pz<=t.length){let s=0;for(let r=0;r0}},Hz=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}},Pv=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}};Pv.INSTANCE=new Pv;fb=Pv;W8=fb.INSTANCE.onDidChangeZoomLevel;G8=fb.INSTANCE.onDidChangeFullscreen,Rl=typeof navigator=="object"?navigator.userAgent:"",Uv=Rl.indexOf("Firefox")>=0,_f=Rl.indexOf("AppleWebKit")>=0,pb=Rl.indexOf("Chrome")>=0,NA=!pb&&Rl.indexOf("Safari")>=0,$8=Rl.indexOf("Electron/")>=0,Y8=Rl.indexOf("Android")>=0,vf=!1;if(typeof gn.matchMedia=="function"){let e=gn.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)"),t=gn.matchMedia("(display-mode: fullscreen)");vf=e.matches,Fz(gn,e,({matches:i})=>{vf&&t.matches||(vf=i)})}Al="en",Ef=!1,xf=!1,gu=!1,Wz=!1,AA=!1,MA=!1,Gz=!1,$z=!1,Yz=!1,jz=!1,bf=Al,fN=Al,tr=globalThis;typeof tr.vscode<"u"&&typeof tr.vscode.process<"u"?mn=tr.vscode.process:typeof process<"u"&&typeof process?.versions?.node=="string"&&(mn=process);OA=typeof mn?.versions?.electron=="string",Xz=OA&&mn?.type==="renderer";if(typeof mn=="object"){Ef=mn.platform==="win32",xf=mn.platform==="darwin",gu=mn.platform==="linux",Wz=gu&&!!mn.env.SNAP&&!!mn.env.SNAP_REVISION,Gz=OA,Yz=!!mn.env.CI||!!mn.env.BUILD_ARTIFACTSTAGINGDIRECTORY,cf=Al,bf=Al;let e=mn.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);cf=t.userLocale,fN=t.osLocale,bf=t.resolvedLanguage||Al,Vz=t.languagePack?.translationsConfigFile}catch{}AA=!0}else typeof navigator=="object"&&!Xz?(Js=navigator.userAgent,Ef=Js.indexOf("Windows")>=0,xf=Js.indexOf("Macintosh")>=0,$z=(Js.indexOf("Macintosh")>=0||Js.indexOf("iPad")>=0||Js.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,gu=Js.indexOf("Linux")>=0,jz=Js?.indexOf("Mobi")>=0,MA=!0,bf=globalThis._VSCODE_NLS_LANGUAGE||Al,cf=navigator.language.toLowerCase(),fN=cf):console.error("Unable to resolve platform.");lv=0;xf?lv=1:Ef?lv=3:gu&&(lv=2);RA=Ef,ks=xf,Zz=gu,cv=AA,Qz=MA&&typeof tr.importScripts=="function",j8=Qz?tr.origin:void 0,Ts=Js,Gr=bf;(e=>{function t(){return Gr}e.value=t;function i(){return Gr.length===2?Gr==="en":Gr.length>=3?Gr[0]==="e"&&Gr[1]==="n"&&Gr[2]==="-":!1}e.isDefaultVariant=i;function n(){return Gr==="en"}e.isDefault=n})(pN||(pN={}));Jz=typeof tr.postMessage=="function"&&!tr.importScripts,e5=(()=>{if(Jz){let e=[];tr.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}),tr.postMessage({vscodeScheduleAsyncWork:n},"*")}}return e=>setTimeout(e)})(),t5=!!(Ts&&Ts.indexOf("Chrome")>=0),V8=!!(Ts&&Ts.indexOf("Firefox")>=0),X8=!!(!t5&&Ts&&Ts.indexOf("Safari")>=0),Z8=!!(Ts&&Ts.indexOf("Edg/")>=0),Q8=!!(Ts&&Ts.indexOf("Android")>=0),$r=typeof navigator=="object"?navigator:{},J8={clipboard:{writeText:cv||document.queryCommandSupported&&document.queryCommandSupported("copy")||!!($r&&$r.clipboard&&$r.clipboard.writeText),readText:cv||!!($r&&$r.clipboard&&$r.clipboard.readText)},keyboard:cv||Kz()?0:$r.keyboard||NA?1:2,touch:"ontouchstart"in gn||$r.maxTouchPoints>0,pointerEvents:gn.PointerEvent&&("ontouchstart"in gn||navigator.maxTouchPoints>0)},mb=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}},uv=new mb,mN=new mb,gN=new mb,i5=new Array(230);(e=>{function t(o){return uv.keyCodeToStr(o)}e.toString=t;function i(o){return uv.strToKeyCode(o)}e.fromString=i;function n(o){return mN.keyCodeToStr(o)}e.toUserSettingsUS=n;function s(o){return gN.keyCodeToStr(o)}e.toUserSettingsGeneral=s;function r(o){return mN.strToKeyCode(o)||gN.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 uv.keyCodeToStr(o)}e.toElectronAccelerator=a})(Hv||(Hv={}));n5=class DA{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 DA&&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 s5([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},s5=class{constructor(e){if(e.length===0)throw gz("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 d5?!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:LA})})(bN||(bN={}));d5=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?LA:(this._emitter||(this._emitter=new Z),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}},gb=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 Av("Calling 'cancelAndSet' on a disposed TimeoutTimer");this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new Av("Calling 'setIfNotSet' on a disposed TimeoutTimer");this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},f5=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 Av("Calling 'cancelAndSet' on a disposed IntervalTimer");this.cancel();let n=i.setInterval(()=>{e()},t);this.disposable=pt(()=>{i.clearInterval(n),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!="function"||typeof globalThis.cancelIdleCallback!="function"?hv=(e,t)=>{e5(()=>{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)}}}:hv=(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))}}},p5=e=>hv(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})(yN||(yN={}));SN=class Dn{static fromArray(t){return new Dn(i=>{i.emitMany(t)})}static fromPromise(t){return new Dn(async i=>{i.emitMany(await t)})}static fromPromises(t){return new Dn(async i=>{await Promise.all(t.map(async n=>i.emitOne(await n)))})}static merge(t){return new Dn(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 Z,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 Dn(async n=>{for await(let s of t)n.emitOne(i(s))})}map(t){return Dn.map(this,t)}static filter(t,i){return new Dn(async n=>{for await(let s of t)i(s)&&n.emitOne(s)})}filter(t){return Dn.filter(this,t)}static coalesce(t){return Dn.filter(t,i=>!!i)}coalesce(){return Dn.coalesce(this)}static async toPromise(t){let i=[];for await(let n of t)i.push(n);return i}toPromise(){return Dn.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())}};SN.EMPTY=SN.fromArray([]);w5=class IA{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(m5(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()),nu(this._h0)+nu(this._h1)+nu(this._h2)+nu(this._h3)+nu(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,EN(this._buff,this._buffLen),this._buffLen>56&&(this._step(),EN(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=IA._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,dv(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=dv(n,5)+l+o+c+t.getUint32(h*4,!1)&4294967295,o=a,a=r,r=dv(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}};w5._bigBlock32=new DataView(new ArrayBuffer(320));({registerWindow:e9,getWindow:Vn,getDocument:t9,getWindows:i9,getWindowsCount:n9,getWindowId:xN,getWindowById:s9,hasWindow:r9,onDidRegisterWindow:E5,onWillUnregisterWindow:a9,onDidUnregisterWindow:o9}=(function(){let e=new Map,t={window:gn,disposables:new Zr};e.set(gn.vscodeWindowId,t);let i=new Z,n=new Z,s=new Z;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 xe.None;let o=new Zr,l={window:a,disposables:o.add(new Zr)};return e.set(a.vscodeWindowId,l),o.add(pt(()=>{e.delete(a.vscodeWindowId),n.fire(a)})),o.add(ve(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:gn},getDocument(a){return Vn(a).document}}})()),x5=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)}};CN=function(e,t,i,n){let s=i;return t==="click"||t==="mousedown"||t==="contextmenu"?s=C5(Vn(e),i):(t==="keydown"||t==="keypress"||t==="keyup")&&(s=k5(i)),ve(e,t,s,n)},N5=class extends f5{constructor(e){super(),this.defaultTarget=e&&Vn(e)}cancelAndSet(e,t,i){return super.cancelAndSet(e,t,i??this.defaultTarget)}},fv=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){pf(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(fv.sort),a.shift().execute();n.set(r,!1)};Cf=(r,a,o=0)=>{let l=xN(r),c=new fv(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},T5=(r,a,o)=>{let l=xN(r);if(n.get(l)){let c=new fv(a,o),u=t.get(l);return u||(u=[],t.set(l,u)),u.push(c),c}else return Cf(r,a,o)}})();kN=class yf{constructor(t,i){this.width=t,this.height=i}with(t=this.width,i=this.height){return t!==this.width||i!==this.height?new yf(t,i):this}static is(t){return typeof t=="object"&&typeof t.height=="number"&&typeof t.width=="number"}static lift(t){return t instanceof yf?t:new yf(t.width,t.height)}static equals(t,i){return t===i?!0:!t||!i?!1:t.width===i.width&&t.height===i.height}};kN.None=new kN(0,0);l9=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=_5(i),r=n.get(s);if(r)r.users+=1;else{let a=new Z,o=new MutationObserver(c=>a.fire(c));o.observe(e,i);let l=r={users:1,observer:o,onDidMutate:a.event};t.add(pt(()=>{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:_f?"webkitAnimationStart":"animationstart",ANIMATION_END:_f?"webkitAnimationEnd":"animationend",ANIMATION_ITERATION:_f?"webkitAnimationIteration":"animationiteration"},M5=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;O5.SVG=function(e,t,...i){return zA("http://www.w3.org/2000/svg",e,t,...i)};R5=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=Zi(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Zi(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Zi(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Zi(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Zi(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Zi(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Zi(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Zi(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Zi(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Zi(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Zi(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=Zi(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=Zi(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Zi(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)}};PA=class{constructor(){this._hooks=new Zr,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(pt(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{r=Vn(e)}this._hooks.add(ve(r,Jt.POINTER_MOVE,a=>{if(a.buttons!==i){this.stopMonitoring(!0);return}a.preventDefault(),this._pointerMoveCallback(a)})),this._hooks.add(ve(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={}));hu=class ki extends xe{constructor(){super(),this.dispatched=!1,this.targets=new uN,this.ignoreTargets=new uN,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(ni.runAndSubscribe(E5,({window:t,disposables:i})=>{i.add(ve(t.document,"touchstart",n=>this.onTouchStart(n),{passive:!1})),i.add(ve(t.document,"touchend",n=>this.onTouchEnd(t,n))),i.add(ve(t.document,"touchmove",n=>this.onTouchMove(n),{passive:!1}))},{window:gn,disposables:this._store}))}static addTarget(t){if(!ki.isTouchDevice())return xe.None;ki.INSTANCE||(ki.INSTANCE=cN(new ki));let i=ki.INSTANCE.targets.push(t);return pt(i)}static ignoreTarget(t){if(!ki.isTouchDevice())return xe.None;ki.INSTANCE||(ki.INSTANCE=cN(new ki));let i=ki.INSTANCE.ignoreTargets.push(t);return pt(i)}static isTouchDevice(){return"ontouchstart"in gn||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=ki.HOLD_DELAY&&Math.abs(l.initialPageX-fn(l.rollingPageX))<30&&Math.abs(l.initialPageY-fn(l.rollingPageY))<30){let u=this.newGestureEvent(jn.Contextmenu,l.initialTarget);u.pageX=fn(l.rollingPageX),u.pageY=fn(l.rollingPageY),this.dispatchEvent(u)}else if(s===1){let u=fn(l.rollingPageX),h=fn(l.rollingPageY),d=fn(l.rollingTimestamps)-l.rollingTimestamps[0],f=u-l.rollingPageX[0],p=h-l.rollingPageY[0],_=[...this.targets].filter(v=>l.initialTarget instanceof Node&&v.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>ki.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=Cf(t,()=>{let u=Date.now(),h=u-n,d=0,f=0,p=!0;s+=ki.SCROLL_FRICTION*h,o+=ki.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(v=>v.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)}};hu.SCROLL_FRICTION=-.005,hu.HOLD_DELAY=700,hu.CLEAR_TAP_COUNT_TIME=400,kt([D5],hu,"isTouchDevice",1);L5=hu,vb=class extends xe{onclick(e,t){this._register(ve(e,Jt.CLICK,i=>t(new uu(Vn(e),i))))}onmousedown(e,t){this._register(ve(e,Jt.MOUSE_DOWN,i=>t(new uu(Vn(e),i))))}onmouseover(e,t){this._register(ve(e,Jt.MOUSE_OVER,i=>t(new uu(Vn(e),i))))}onmouseleave(e,t){this._register(ve(e,Jt.MOUSE_LEAVE,i=>t(new uu(Vn(e),i))))}onkeydown(e,t){this._register(ve(e,Jt.KEY_DOWN,i=>t(new Fv(i))))}onkeyup(e,t){this._register(ve(e,Jt.KEY_UP,i=>t(new Fv(i))))}oninput(e,t){this._register(ve(e,Jt.INPUT,t))}onblur(e,t){this._register(ve(e,Jt.BLUR,t))}onfocus(e,t){this._register(ve(e,Jt.FOCUS,t))}onchange(e,t){this._register(ve(e,Jt.CHANGE,t))}ignoreGesture(e){return L5.ignoreTarget(e)}},TN=11,B5=class extends vb{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=TN+"px",this.domNode.style.height=TN+"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 PA),this._register(CN(this.bgDomNode,Jt.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._register(CN(this.domNode,Jt.POINTER_DOWN,t=>this._arrowPointerDown(t))),this._pointerdownRepeatTimer=this._register(new N5),this._pointerdownScheduleRepeatTimer=this._register(new gb)}_arrowPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,Vn(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()}},I5=class qv{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 qv(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 qv(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}}},z5=class extends xe{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 I5(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 AN(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=AN.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)))}},NN=class{constructor(e,t,i){this.scrollLeft=e,this.scrollTop=t,this.isDone=i}};AN=class Kv{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":"")))}},q5=140,UA=class extends vb{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 F5(e.visibility,"visible scrollbar "+e.extraScrollbarClassName,"invisible scrollbar "+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new PA),this._shouldRender=!0,this.domNode=_u(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(ve(this.domNode.domNode,Jt.POINTER_DOWN,t=>this._domNodePointerDown(t)))}_createArrow(e){let t=this._register(new B5(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,i,n){this.slider=_u(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(ve(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=A5(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(RA&&a>q5){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()}},HA=class Wv{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 Wv(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=Wv._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}};Gv.INSTANCE=new Gv;Y5=Gv,j5=class extends vb{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=X5(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 W5(this._scrollable,this._options,n)),this._horizontalScrollbar=this._register(new K5(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=_u(document.createElement("div")),this._leftShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=_u(document.createElement("div")),this._topShadowDomNode.setClassName("shadow"),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=_u(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 gb),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Va(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,ks&&(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 vN(e))}_setListeningToMouseWheel(e){if(this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Va(this._mouseWheelToDispose),e)){let t=i=>{this._onMouseWheel(new vN(i))};this._mouseWheelToDispose.push(ve(this._listenOnDomNode,Jt.MOUSE_WHEEL,t,{passive:!1}))}}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Y5.INSTANCE;ON&&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=!ks&&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=MN*s,u=o.scrollTop-(c<0?Math.floor(c):Math.ceil(c));this._verticalScrollbar.writeScrollPosition(l,u)}if(r){let c=MN*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)&&(ON&&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(),G5)}},V5=class extends j5{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()}};$v=class extends xe{constructor(e,t,i,n,s,r,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 z5({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:c=>Cf(n.window,c)}));this._register(this._optionsService.onSpecificOptionChange("smoothScrollDuration",()=>{l.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new V5(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(pt(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=n.mainDocument.createElement("style"),t.appendChild(this._styleElement),this._register(pt(()=>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}};$v=kt([ne(2,zi),ne(3,ir),ne(4,pA),ne(5,Ol),ne(6,Pi),ne(7,nr)],$v);Yv=class extends xe{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(pt(()=>{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()}};Yv=kt([ne(1,zi),ne(2,ir),ne(3,Cu),ne(4,nr)],Yv);Z5=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)}},xs={full:0,left:0,center:0,right:0},Yr={full:0,left:0,center:0,right:0},su={full:0,left:0,center:0,right:0},kf=class extends xe{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 Z5,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(pt(()=>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);Yr.full=this._canvas.width,Yr.left=e,Yr.center=t,Yr.right=e,this._refreshDrawHeightConstants(),su.full=1,su.left=1,su.center=1+Yr.left,su.right=1+Yr.left+Yr.center}_refreshDrawHeightConstants(){xs.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);xs.left=t,xs.center=t,xs.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xs.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xs.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xs.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*xs.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(su[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-xs[e.position||"full"]/2),Yr[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+xs[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}))}};kf=kt([ne(2,zi),ne(3,Cu),ne(4,nr),ne(5,Pi),ne(6,Ol),ne(7,ir)],kf);(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"))(P||(P={}));(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"))(vu||(vu={}));(e=>e.ST=`${P.ESC}\\`)(jv||(jv={}));Vv=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)}}};Vv=kt([ne(2,zi),ne(3,Pi),ne(4,Za),ne(5,nr)],Vv);ei=0,ti=0,ii=0,Ct=0,RN={css:"#00000000",rgba:0};(e=>{function t(s,r,a,o){return o!==void 0?`#${Wa(s)}${Wa(r)}${Wa(a)}${Wa(o)}`:`#${Wa(s)}${Wa(r)}${Wa(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})(Mt||(Mt={}));(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 v=Mt.toCss(ei,ti,ii),g=Mt.toRgba(ei,ti,ii);return{css:v,rgba:g}}e.blend=t;function i(l){return(l.rgba&255)===255}e.isOpaque=i;function n(l,c,u){let h=bu.ensureContrastRatio(l.rgba,c.rgba,u);if(h)return Mt.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]=bu.toChannels(c),{css:Mt.toCss(ei,ti,ii),rgba:c}}e.opaque=s;function r(l,c){return Ct=Math.round(c*255),[ei,ti,ii]=bu.toChannels(l.rgba),{css:Mt.toCss(ei,ti,ii,Ct),rgba:Mt.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),Mt.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),Mt.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),Mt.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:Mt.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})(Ti||(Ti={}));(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),Mt.toRgba(ei,ti,ii)}e.blend=t;function i(a,o,l){let c=Ti.relativeLuminance(a>>8),u=Ti.relativeLuminance(o>>8);if(Qs(c,u)>8));if(p>8));return p>v?f:_}return f}let h=s(a,o,l),d=Qs(c,Ti.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,_=Qs(Ti.relativeLuminance2(d,f,p),Ti.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)),_=Qs(Ti.relativeLuminance2(d,f,p),Ti.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,_=Qs(Ti.relativeLuminance2(d,f,p),Ti.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})(bu||(bu={}));Q5=class extends xu{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()]}},Tf=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Bn}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,D=I,A=this._workCell;if(d.length>0&&I===d[0][0]&&T){let we=d.shift(),yi=this._isCellInSelection(we[0],t);for(m=we[0]+1;m=we[1]),T?(q=!0,A=new Q5(this._workCell,e.translateToString(!0,we[0],we[1]),we[1]-we[0]),D=we[1]-1,R=A.getWidth()):F=we[1]}let $=this._isCellInSelection(I,t),re=i&&I===r,L=z&&I>=c&&I<=u,Q=!1;this._decorationService.forEachDecorationAtCell(I,t,void 0,we=>{Q=!0});let Ne=A.getChars()||Xr;if(Ne===" "&&(A.isUnderline()||A.isOverline())&&(Ne="\xA0"),O=R*o-l.get(Ne,A.isBold(),A.isItalic()),!_)_=this._document.createElement("span");else if(v&&($&&M||!$&&!M&&A.bg===b)&&($&&M&&f.selectionForeground||A.fg===S)&&A.extended.ext===x&&L===C&&O===N&&!re&&!q&&!Q&&T){A.isInvisible()?g+=Xr:g+=Ne,v++;continue}else v&&(_.textContent=g),_=this._document.createElement("span"),v=0,g="";if(b=A.bg,S=A.fg,x=A.extended.ext,C=L,N=O,M=$,q&&r>=I&&r<=D&&(r=I),!this._coreService.isCursorHidden&&re&&this._coreService.isCursorInitialized){if(W.push("xterm-cursor"),this._coreBrowserService.isFocused)a&&W.push("xterm-cursor-blink"),W.push(n==="bar"?"xterm-cursor-bar":n==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(s)switch(s){case"outline":W.push("xterm-cursor-outline");break;case"block":W.push("xterm-cursor-block");break;case"bar":W.push("xterm-cursor-bar");break;case"underline":W.push("xterm-cursor-underline");break;default:break}}if(A.isBold()&&W.push("xterm-bold"),A.isItalic()&&W.push("xterm-italic"),A.isDim()&&W.push("xterm-dim"),A.isInvisible()?g=Xr:g=A.getChars()||Xr,A.isUnderline()&&(W.push(`xterm-underline-${A.extended.underlineStyle}`),g===" "&&(g="\xA0"),!A.isUnderlineColorDefault()))if(A.isUnderlineColorRGB())_.style.textDecorationColor=`rgb(${xu.toColorRGB(A.getUnderlineColor()).join(",")})`;else{let we=A.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&A.isBold()&&we<8&&(we+=8),_.style.textDecorationColor=f.ansi[we].css}A.isOverline()&&(W.push("xterm-overline"),g===" "&&(g="\xA0")),A.isStrikethrough()&&W.push("xterm-strikethrough"),L&&(_.style.textDecoration="underline");let he=A.getFgColor(),Be=A.getFgColorMode(),J=A.getBgColor(),qe=A.getBgColorMode(),dt=!!A.isInverse();if(dt){let we=he;he=J,J=we;let yi=Be;Be=qe,qe=yi}let oi,Ai,Mi=!1;this._decorationService.forEachDecorationAtCell(I,t,void 0,we=>{we.options.layer!=="top"&&Mi||(we.backgroundColorRGB&&(qe=50331648,J=we.backgroundColorRGB.rgba>>8&16777215,oi=we.backgroundColorRGB),we.foregroundColorRGB&&(Be=50331648,he=we.foregroundColorRGB.rgba>>8&16777215,Ai=we.foregroundColorRGB),Mi=we.options.layer==="top")}),!Mi&&$&&(oi=this._coreBrowserService.isFocused?f.selectionBackgroundOpaque:f.selectionInactiveBackgroundOpaque,J=oi.rgba>>8&16777215,qe=50331648,Mi=!0,f.selectionForeground&&(Be=50331648,he=f.selectionForeground.rgba>>8&16777215,Ai=f.selectionForeground)),Mi&&W.push("xterm-decoration-top");let li;switch(qe){case 16777216:case 33554432:li=f.ansi[J],W.push(`xterm-bg-${J}`);break;case 50331648:li=Mt.toColor(J>>16,J>>8&255,J&255),this._addStyle(_,`background-color:#${DN((J>>>0).toString(16),"0",6)}`);break;default:dt?(li=f.foreground,W.push("xterm-bg-257")):li=f.background}switch(oi||A.isDim()&&(oi=ht.multiplyOpacity(li,.5)),Be){case 16777216:case 33554432:A.isBold()&&he<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(he+=8),this._applyMinimumContrast(_,li,f.ansi[he],A,oi,void 0)||W.push(`xterm-fg-${he}`);break;case 50331648:let we=Mt.toColor(he>>16&255,he>>8&255,he&255);this._applyMinimumContrast(_,li,we,A,oi,Ai)||this._addStyle(_,`color:#${DN(he.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(_,li,f.foreground,A,oi,Ai)||dt&&W.push("xterm-fg-257")}W.length&&(_.className=W.join(" "),W.length=0),!re&&!q&&!Q&&T?v++:_.textContent=g,O!==this.defaultSpacing&&(_.style.letterSpacing=`${O}px`),h.push(_),I=D}return _&&v&&(_.textContent=g),h}_applyMinimumContrast(e,t,i,n,s,r){if(this._optionsService.rawOptions.minimumContrastRatio===1||t6(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]}};Xv=kt([ne(1,_A),ne(2,Pi),ne(3,ir),ne(4,Za),ne(5,Cu),ne(6,Ol)],Xv);n6=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}},s6=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}};mv="xterm-dom-renderer-owner-",Rn="xterm-rows",hf="xterm-fg-",LN="xterm-bg-",ru="xterm-focus",df="xterm-selection",a6=1,Zv=class extends xe{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=a6++,this._rowElements=[],this._selectionRenderModel=r6(),this.onRequestRedraw=this._register(new Z).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(Rn),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(df),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=i6(),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(Xv,document),this._element.classList.add(mv+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(pt(()=>{this._element.classList.remove(mv+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new n6(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} .${Rn} 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} .${Rn} { 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} .${Rn} .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} .${Rn}.${ru} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${Rn}.${ru} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${Rn}.${ru} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${s} 1s step-end infinite;}${this._terminalSelector} .${Rn} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${Rn} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${Rn} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${Rn} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${Rn} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${df} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${df} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${df} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[r,a]of e.ansi.entries())t+=`${this._terminalSelector} .${hf}${r} { color: ${a.css}; }${this._terminalSelector} .${hf}${r}.xterm-dim { color: ${ht.multiplyOpacity(a,.5).css}; }${this._terminalSelector} .${LN}${r} { background-color: ${a.css}; }`;t+=`${this._terminalSelector} .${hf}257 { color: ${ht.opaque(e.background).css}; }${this._terminalSelector} .${hf}257.xterm-dim { color: ${ht.multiplyOpacity(ht.opaque(e.background),.5).css}; }${this._terminalSelector} .${LN}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(ru),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(ru),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`.${mv}${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],v=o.lines.get(p);if(!_||!v)break;_.replaceChildren(...this._rowFactory.createRow(v,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))}}};Zv=kt([ne(7,hb),ne(8,Rf),ne(9,Pi),ne(10,zi),ne(11,Za),ne(12,ir),ne(13,Ol)],Zv);Qv=class extends xe{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 l6(this._optionsService))}catch{this._measureStrategy=this._register(new o6(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())}};Qv=kt([ne(2,Pi)],Qv);FA=class extends xe{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)}},o6=class extends FA{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}},l6=class extends FA{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}},c6=class extends xe{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 u6(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(ni.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(ve(this._textarea,"focus",()=>this._isFocused=!0)),this._register(ve(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}},u6=class extends xe{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Ml),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(pt(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=ve(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)}},h6=class extends xe{constructor(){super(),this.linkProviders=[],this._register(pt(()=>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)}}}};Jv=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,n,s){return d6(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=bb(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])}}};Jv=kt([ne(0,nr),ne(1,Rf)],Jv);f6=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=[]}},qA={};JI(qA,{getSafariVersion:()=>m6,isChromeOS:()=>$A,isFirefox:()=>KA,isIpad:()=>g6,isIphone:()=>_6,isLegacyEdge:()=>p6,isLinux:()=>yb,isMac:()=>Nf,isNode:()=>Bf,isSafari:()=>WA,isWindows:()=>GA});Bf=typeof process<"u"&&"title"in process,ku=Bf?"node":navigator.userAgent,Tu=Bf?"node":navigator.platform,KA=ku.includes("Firefox"),p6=ku.includes("Edge"),WA=/^((?!chrome|android).)*safari/i.test(ku);Nf=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(Tu),g6=Tu==="iPad",_6=Tu==="iPhone",GA=["Windows","Win16","Win32","WinCE"].includes(Tu),yb=Tu.indexOf("Linux")>=0,$A=/\bCrOS\b/.test(ku),YA=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()}},v6=class extends YA{_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())}}},b6=class extends YA{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},Af=!Bf&&"requestIdleCallback"in window?b6:v6,y6=class{constructor(){this._queue=new Af}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},eb=class extends xe{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 Ml),this._pausedResizeTask=new y6,this._observerDisposable=this._register(new Ml),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 f6((c,u)=>this._renderRows(c,u),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new S6(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(pt(()=>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=pt(()=>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()}};eb=kt([ne(2,Pi),ne(3,Rf),ne(4,Za),ne(5,Cu),ne(6,zi),ne(7,ir),ne(8,Ol)],eb);S6=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)}};A6=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)}};gv=50,M6=15,O6=50,R6=500,D6="\xA0",L6=new RegExp(D6,"g"),tb=class extends xe{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 Bn,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 A6(this._bufferService),this._activeSelectionMode=0,this._register(pt(()=>{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(L6," ")).join(GA?`\r +`).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 `:` -`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),yb&&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=BN(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=bb(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,-gv),gv),t/=gv,t/Math.abs(t)+Math.round(t*(M6-1)))}shouldForceSelection(e){return Nf?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(),O6)}_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&&!(Nf&&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);v>0&&o>0&&!this._isCharWordSeparator(r.loadCell(v-1,this._workCell));){r.loadCell(v-1,this._workCell);let b=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,v--):b>1&&(d+=b-1,o-=b-1),o--,v--}for(;g1&&(f+=b-1,l+=b-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 v=s.lines.get(e[1]-1);if(v&&r.isWrapped&&v.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 v=s.lines.get(e[1]+1);if(v?.isWrapped&&v.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=BN(i,this._bufferService.cols)}};tb=kt([ne(3,zi),ne(4,Za),ne(5,db),ne(6,Pi),ne(7,nr),ne(8,ir)],tb);IN=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={}}},zN=class{constructor(){this._color=new IN,this._css=new IN}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:Mt.toCss(n,s,r),rgba:Mt.toRgba(n,s,r)})}for(let i=0;i<24;i++){let n=8+i*10;e.push({css:Mt.toCss(n,n,n),rgba:Mt.toRgba(n,n,n)})}return e})()),Ga=vt.toColor("#ffffff"),du=vt.toColor("#000000"),PN=vt.toColor("#ffffff"),UN=du,au={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117},B6=Ga,ib=class extends xe{constructor(e){super(),this._optionsService=e,this._contrastCache=new zN,this._halfContrastCache=new zN,this._onChangeColors=this._register(new Z),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:Ga,background:du,cursor:PN,cursorAccent:UN,selectionForeground:void 0,selectionBackgroundTransparent:au,selectionBackgroundOpaque:ht.blend(du,au),selectionInactiveBackgroundTransparent:au,selectionInactiveBackgroundOpaque:ht.blend(du,au),scrollbarSliderBackground:ht.opacity(Ga,.2),scrollbarSliderHoverBackground:ht.opacity(Ga,.4),scrollbarSliderActiveBackground:ht.opacity(Ga,.5),overviewRulerBorder:Ga,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,Ga),t.background=tt(e.background,du),t.cursor=ht.blend(t.background,tt(e.cursor,PN)),t.cursorAccent=ht.blend(t.background,tt(e.cursorAccent,UN)),t.selectionBackgroundTransparent=tt(e.selectionBackground,au),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,RN):void 0,t.selectionForeground===RN&&(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,B6),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)}},P6={trace:0,debug:1,info:2,warn:3,error:4,off:5},U6="xterm.js: ",nb=class extends xe{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),H6=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=P6[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*Te+1]=i[0],i[1].length>1?(this._combined[t]=i[1],this._data[t*Te+0]=t|2097152|i[2]<<22):this._data[t*Te+0]=i[1].charCodeAt(0)|i[2]<<22}getWidth(t){return this._data[t*Te+0]>>22}hasWidth(t){return this._data[t*Te+0]&12582912}getFg(t){return this._data[t*Te+1]}getBg(t){return this._data[t*Te+2]}hasContent(t){return this._data[t*Te+0]&4194303}getCodePoint(t){let i=this._data[t*Te+0];return i&2097152?this._combined[t].charCodeAt(this._combined[t].length-1):i&2097151}isCombined(t){return this._data[t*Te+0]&2097152}getString(t){let i=this._data[t*Te+0];return i&2097152?this._combined[t]:i&2097151?Vr(i&2097151):""}isProtected(t){return this._data[t*Te+2]&536870912}loadCell(t,i){return ff=t*Te,i.content=this._data[ff+0],i.fg=this._data[ff+1],i.bg=this._data[ff+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*Te+0]=i.content,this._data[t*Te+1]=i.fg,this._data[t*Te+2]=i.bg}setCellFromCodepoint(t,i,n,s){s.bg&268435456&&(this._extendedAttrs[t]=s.extended),this._data[t*Te+0]=i|n<<22,this._data[t*Te+1]=s.fg,this._data[t*Te+2]=s.bg}addCodepointToCell(t,i,n){let s=this._data[t*Te+0];s&2097152?this._combined[t]+=Vr(i):s&2097151?(this._combined[t]=Vr(s&2097151)+Vr(i),s&=-2097152,s|=2097152):s=i|1<<22,n&&(s&=-12582913,s|=n<<22),this._data[t*Te+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*_v=0;--t)if(this._data[t*Te+0]&4194303)return t+(this._data[t*Te+0]>>22);return 0}getNoBgTrimmedLength(){for(let t=this.length-1;t>=0;--t)if(this._data[t*Te+0]&4194303||this._data[t*Te+2]&50331648)return t+(this._data[t*Te+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}};ZA=class QA{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=QA._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(),Va(this._disposables),this._disposables.length=0)}register(t){return this._disposables.push(t),t}};ZA._nextId=1;G6=ZA,Gt={},$a=Gt.B;Gt[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"};Gt.A={"#":"\xA3"};Gt.B=void 0;Gt[4]={"#":"\xA3","@":"\xBE","[":"ij","\\":"\xBD","]":"|","{":"\xA8","|":"f","}":"\xBC","~":"\xB4"};Gt.C=Gt[5]={"[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};Gt.R={"#":"\xA3","@":"\xE0","[":"\xB0","\\":"\xE7","]":"\xA7","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xA8"};Gt.Q={"@":"\xE0","[":"\xE2","\\":"\xE7","]":"\xEA","^":"\xEE","`":"\xF4","{":"\xE9","|":"\xF9","}":"\xE8","~":"\xFB"};Gt.K={"@":"\xA7","[":"\xC4","\\":"\xD6","]":"\xDC","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xDF"};Gt.Y={"#":"\xA3","@":"\xA7","[":"\xB0","\\":"\xE7","]":"\xE9","`":"\xF9","{":"\xE0","|":"\xF2","}":"\xE8","~":"\xEC"};Gt.E=Gt[6]={"@":"\xC4","[":"\xC6","\\":"\xD8","]":"\xC5","^":"\xDC","`":"\xE4","{":"\xE6","|":"\xF8","}":"\xE5","~":"\xFC"};Gt.Z={"#":"\xA3","@":"\xA7","[":"\xA1","\\":"\xD1","]":"\xBF","{":"\xB0","|":"\xF1","}":"\xE7"};Gt.H=Gt[7]={"@":"\xC9","[":"\xC4","\\":"\xD6","]":"\xC5","^":"\xDC","`":"\xE9","{":"\xE4","|":"\xF6","}":"\xE5","~":"\xFC"};Gt["="]={"#":"\xF9","@":"\xE0","[":"\xE9","\\":"\xE7","]":"\xEA","^":"\xEE",_:"\xE8","`":"\xF4","{":"\xE4","|":"\xF6","}":"\xFC","~":"\xFB"};FN=4294967295,qN=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=zt.clone(),this.savedCharset=$a,this.markers=[],this._nullCell=Bn.fromCharData([0,uA,1,0]),this._whitespaceCell=Bn.fromCharData([0,Xr,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new Af,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new HN(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 wf),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 wf),this._whitespaceCell}getBlankLine(e,t){return new fu(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&&eFN?FN:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=zt);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 HN(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let i=this.getNullCell(zt),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 fu(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=F6(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(zt),i);if(n.length>0){let s=q6(this.lines,n);K6(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){let n=this.getNullCell(zt),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 b=this.ybase+this.y;if(b>=a&&b0&&(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 v=l.length-h-1,g=c;for(;v>=0;){let b=Math.min(g,_);if(l[p]===void 0)break;if(l[p].copyCellsFrom(l[v],g-b,_-b,b,!0),_-=b,_===0&&(p--,_=u[p]),g-=b,g===0){v--;let S=Math.max(v,0);g=Eu(l,S,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 v=h.newLines.length-1;v>=0;v--)this.lines.set(_--,h.newLines[v]);_++,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)}},$6=class extends xe{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 qN(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new qN(!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)}},JA=2,eM=1,sb=class extends xe{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,JA),this.rows=Math.max(e.rawOptions.rows||0,eM),this.buffers=this._register(new $6(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([ne(0,Pi)],sb);Nl={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:Nf,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRuler:{}},Y6=["normal","bold","100","200","300","400","500","600","700","800","900"],j6=class extends xe{constructor(e){super(),this._onOptionChange=this._register(new Z),this.onOptionChange=this._onOptionChange.event;let t={...Nl};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(pt(()=>{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 Nl))throw new Error(`No option with key "${i}"`);return this.rawOptions[i]},t=(i,n)=>{if(!(i in Nl))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=Nl[e]),!V6(t))throw new Error(`"${t}" is not a valid value for ${e}`);break;case"wordSeparator":t||(t=Nl[e]);break;case"fontWeight":case"fontWeightBold":if(typeof t=="number"&&1<=t&&t<=1e3)break;t=Y6.includes(t)?t:Nl[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}};KN=Object.freeze({insertMode:!1}),WN=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),rb=class extends xe{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(KN),this.decPrivateModes=pu(WN)}reset(){this.modes=pu(KN),this.decPrivateModes=pu(WN)}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))}};rb=kt([ne(0,zi),ne(1,mA),ne(2,Pi)],rb);GN={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}};bv=String.fromCharCode,$N={DEFAULT:e=>{let t=[vv(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`\x1B[M${bv(t[0])}${bv(t[1])}${bv(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${vv(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?"m":"M";return`\x1B[<${vv(e,!0)};${e.x};${e.y}${t}`}},ab=class extends xe{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(GN))this.addProtocol(n,GN[n]);for(let n of Object.keys($N))this.addEncoding(n,$N[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)}};ab=kt([ne(0,zi),ne(1,Za),ne(2,Pi)],ab);yv=[[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]],X6=[[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]];Q6=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=Ya.extractWidth(t);s===0?n=!1:s>i&&(i=s)}return Ya.createPropertyValue(0,i,n)}},Ya=class Sf{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new Z,this.onChange=this._onChange.event;let t=new Q6;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=Sf.extractWidth(o);Sf.extractShouldJoin(o)&&(l-=Sf.extractWidth(n)),i+=l,n=o}return i}charProperties(t,i){return this._activeProvider.charProperties(t,i)}},J6=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)}};ou=2147483647,e4=256,tM=class ob{constructor(t=32,i=32){if(this.maxLength=t,this.maxSubParamsLength=i,i>e4)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 ob;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>ou?ou: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>ou?ou: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,ou):t}},lu=[],t4=class{constructor(){this._state=0,this._active=lu,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=lu}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=lu,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||lu,!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",Of(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=lu,this._id=-1,this._state=0}}},pn=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+=Of(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}},cu=[],i4=class{constructor(){this._handlers=Object.create(null),this._active=cu,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=cu}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=cu,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||cu,!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",Of(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=cu,this._ident=0}},mu=new tM;mu.addParam(0);jN=class{constructor(e){this._handler=e,this._data="",this._params=mu,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():mu,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=Of(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=mu,this._data="",this._hitLimit=!1,i));return this._params=mu,this._data="",this._hitLimit=!1,t}},n4=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(Ln,0,2,0),e.add(Ln,8,5,8),e.add(Ln,6,0,6),e.add(Ln,11,0,11),e.add(Ln,13,13,13),e})(),r4=class extends xe{constructor(e=s4){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 tM,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(pt(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new t4),this._dcsParser=this._register(new i4),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(P.BEL,()=>this.bell()),this._parser.setExecuteHandler(P.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(P.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(P.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(P.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(P.BS,()=>this.backspace()),this._parser.setExecuteHandler(P.HT,()=>this.tab()),this._parser.setExecuteHandler(P.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(P.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(vu.IND,()=>this.index()),this._parser.setExecuteHandler(vu.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(vu.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new pn(c=>(this.setTitle(c),this.setIconName(c),!0))),this._parser.registerOscHandler(1,new pn(c=>this.setIconName(c))),this._parser.registerOscHandler(2,new pn(c=>this.setTitle(c))),this._parser.registerOscHandler(4,new pn(c=>this.setOrReportIndexedColor(c))),this._parser.registerOscHandler(8,new pn(c=>this.setHyperlink(c))),this._parser.registerOscHandler(10,new pn(c=>this.setOrReportFgColor(c))),this._parser.registerOscHandler(11,new pn(c=>this.setOrReportBgColor(c))),this._parser.registerOscHandler(12,new pn(c=>this.setOrReportCursorColor(c))),this._parser.registerOscHandler(104,new pn(c=>this.restoreIndexedColor(c))),this._parser.registerOscHandler(110,new pn(c=>this.restoreFgColor(c))),this._parser.registerOscHandler(111,new pn(c=>this.restoreBgColor(c))),this._parser.registerOscHandler(112,new pn(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 Gt)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 jN((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"),QN))]).catch(t=>{if(t!=="#SLOW_TIMEOUT")throw t;console.warn(`async parser handler taking longer than ${QN} 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>jr&&(r=this._parseStack.position+jr)}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.lengthjr)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-v;for(this._activeBuffer.x=v,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),v>0&&h instanceof fu&&h.copyCellsFrom(g,m,0,v,!1);m=0;)h.setCellFromCodepoint(this._activeBuffer.x++,0,0,u);continue}if(c&&(h.insertCells(this._activeBuffer.x,s-v,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=>ZN(i.params[0],this._optionsService.rawOptions.windowOptions)?t(i):!0):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new jN(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new pn(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(P.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(P.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(P.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(P.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(P.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=(_,v)=>(a.triggerDataEvent(`${P.ESC}[${t?"":"?"}${_};${v}$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|=xu.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=zt.fg,e.bg=zt.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|=zt.fg&16777215):i===49?(n.bg&=-67108864,n.bg|=zt.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|=zt.fg&16777215,n.bg&=-67108864,n.bg|=zt.bg&16777215):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${P.ESC}[0n`);break;case 6:let t=this._activeBuffer.y+1,i=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${P.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(`${P.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=zt.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(!ZN(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(`${P.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>XN&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>XN&&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=VN(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=VN(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=zt.clone(),this._eraseAttrDataInternal=zt.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 Bn;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(`${P.ESC}${a}${P.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)}},lb=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&&(JN=e,e=t,t=JN),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};lb=kt([ne(0,zi)],lb);h4=5e7,tA=12,d4=50,f4=class extends xe{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>h4)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>=tA?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>=tA)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>d4&&(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()}},cb=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)))}};cb=kt([ne(0,zi)],cb);iA=!1,p4=class extends xe{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Ml),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 z6,this.optionsService=this._register(new j6(e)),this._instantiationService.setService(Pi,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(sb)),this._instantiationService.setService(zi,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(nb)),this._instantiationService.setService(mA,this._logService),this.coreService=this._register(this._instantiationService.createInstance(rb)),this._instantiationService.setService(Za,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(ab)),this._instantiationService.setService(pA,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Ya)),this._instantiationService.setService(cz,this.unicodeService),this._charsetService=this._instantiationService.createInstance(J6),this._instantiationService.setService(lz,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(cb),this._instantiationService.setService(gA,this._oscLinkService),this._inputHandler=this._register(new u4(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 f4((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 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&&!iA&&(this._logService.warn("writeSync is unreliable and will be removed soon."),iA=!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,JA),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(YN.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},()=>(YN(this._bufferService),!1))),this._windowsWrappingHeuristics.value=pt(()=>{for(let t of e)t.dispose()})}}},m4={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:["'",'"']};At=0,_4=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new Af,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new Af,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||(At=this._search(t),At===-1)||this._getKey(this._array[At])!==t)return!1;do if(this._array[At]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(At),!0;while(++Ats-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&&(At=this._search(e),!(At<0||At>=this._array.length)&&this._getKey(this._array[At])===e))do yield this._array[At];while(++At=this._array.length)&&this._getKey(this._array[At])===e))do t(this._array[At]);while(++At=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}},wv=0,nA=0,v4=class extends xe{constructor(){super(),this._decorations=new _4(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(pt(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new b4(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{wv=s.options.x??0,nA=wv+(s.options.width??1),e>=wv&&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)}},sA=20,rA=!1,Mf=class extends xe{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 S4(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");rA?(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(ve(s,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(pt(()=>{rA?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===sA+1&&(this._liveRegion.textContent+=xv.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{Va(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(ve(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(ve(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(ve(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(ve(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&&w4(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,Va(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}}};ub=kt([ne(1,db),ne(2,nr),ne(3,zi),ne(4,vA)],ub);E4=class extends p4{constructor(e={}){super(e),this._linkifier=this._register(new Ml),this.browser=qA,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Ml),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(v4),this._instantiationService.setService(Cu,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(h6),this._instantiationService.setService(vA,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(pt(()=>{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(`${P.ESC}]${n};${l4(s)}${jv.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(r=>r.ansi[t.index]=Mt.toColor(...t.color));else{let r=i;this._themeService.modifyColors(a=>a[r]=Mt.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(Mf,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(P.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(P.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(ve(this.element,"copy",t=>{this.hasSelection()&&iz(t,this._selectionService)}));let e=t=>nz(t,this.textarea,this.coreService,this.optionsService);this._register(ve(this.textarea,"paste",e)),this._register(ve(this.element,"paste",e)),KA?this._register(ve(this.element,"mousedown",t=>{t.button===2&&nN(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(ve(this.element,"contextmenu",t=>{nN(t,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),yb&&this._register(ve(this.element,"auxclick",t=>{t.button===1&&cA(t,this.textarea,this.screenElement)}))}_bindKeys(){this._register(ve(this.textarea,"keyup",e=>this._keyUp(e),!0)),this._register(ve(this.textarea,"keydown",e=>this._keyDown(e),!0)),this._register(ve(this.textarea,"keypress",e=>this._keyPress(e),!0)),this._register(ve(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(ve(this.textarea,"compositionupdate",e=>this._compositionHelper.compositionupdate(e))),this._register(ve(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(ve(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(ve(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",Ev.get()),$A||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(c6,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ir,this._coreBrowserService),this._register(ve(this.textarea,"focus",s=>this._handleTextAreaFocus(s))),this._register(ve(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(Qv,this._document,this._helperContainer),this._instantiationService.setService(Rf,this._charSizeService),this._themeService=this._instantiationService.createInstance(ib),this._instantiationService.setService(Ol,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Tf),this._instantiationService.setService(_A,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(eb,this.rows,this.screenElement)),this._instantiationService.setService(nr,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(Vv,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(Jv),this._instantiationService.setService(db,this._mouseService);let n=this._linkifier.value=this._register(this._instantiationService.createInstance(ub,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($v,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(tb,this.element,this.screenElement,n)),this._instantiationService.setService(hz,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(Yv,this.screenElement)),this._register(ve(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(Mf,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",s=>this._handleScreenReaderModeOptionChange(s))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(kf,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",s=>{!this._overviewRulerRenderer&&s&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(kf,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(Zv,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(ve(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(ve(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=P.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){lA(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=g4(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===P.ETX||i.key===P.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)&&(x4(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 Bn)}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 k4(t)}getNullCell(){return new Bn}},T4=class extends xe{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Z),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)}},N4=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)}},A4=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}},M4=["cols","rows"],Cs=0,iM=class extends xe{constructor(e){super(),this._core=this._register(new E4(e)),this._addonManager=this._register(new C4),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(M4.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 N4(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new A4(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 T4(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 Ev.get()},set promptLabel(e){Ev.set(e)},get tooMuchOutput(){return xv.get()},set tooMuchOutput(e){xv.set(e)}}}_verifyIntegers(...e){for(Cs of e)if(Cs===1/0||isNaN(Cs)||Cs%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(Cs of e)if(Cs&&(Cs===1/0||isNaN(Cs)||Cs%1!==0||Cs<0))throw new Error("This API only accepts positive integers")}}});var O4,R4,sM,rM=ce(()=>{O4=2,R4=1,sM=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(O4,Math.floor(u/e.css.cell.width)),rows:Math.max(R4,Math.floor(c/e.css.cell.height))}}}});var aM=ce(()=>{});function D4(){let e=document.documentElement.dataset.theme;return e==="dark"?!0:e==="light"?!1:window.matchMedia("(prefers-color-scheme: dark)").matches}function Sb(){return D4()?{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 oM=ce(()=>{});function lM(){let{projects:e,threads:t}=ct(),i=pe(),n=t.find(v=>v.id===i.currentThreadId)??null,s=n?e.find(v=>v.id===n.projectId):e.find(v=>v.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 v=await te.call("terminal.list",{projectId:r});o(v),c(g=>g&&v.some(m=>m.id===g)?g:v[0]?.id??null)}catch{}},[r]);(0,ri.useEffect)(()=>{d()},[d]),(0,ri.useEffect)(()=>te.subscribe("terminals",(g,m)=>{let b=m;b?.type==="terminal.exit"&&(o(S=>S.filter(x=>x.id!==b.id)),c(S=>S===b.id?null:S))}),[]);let f=async()=>{if(r)try{let v=await te.call("terminal.create",{projectId:r,cols:100,rows:28});await d(),c(v.id)}catch(v){ze(w("terminal.failNew")+ft(v),!0)}},p=async v=>{try{await te.call("terminal.kill",{id:v.id}),o(g=>g.filter(m=>m.id!==v.id)),c(g=>g===v.id?null:g)}catch(g){ze(w("terminal.failKill")+ft(g),!0)}};if(!s)return(0,$t.jsx)("div",{className:"pn-empty",children:w("panel.pickProject")});let _=a.find(v=>v.id===l)??null;return(0,$t.jsxs)($t.Fragment,{children:[(0,$t.jsxs)("div",{className:"tm-tabs",children:[a.map(v=>(0,$t.jsxs)("button",{className:`tm-tab${v.id===l?" on":""}`,onClick:()=>c(v.id),title:v.title,children:[v.title,(0,$t.jsx)("span",{className:"tm-x",onClick:g=>{g.stopPropagation(),h(v)},children:"\xD7"})]},v.id)),(0,$t.jsx)("button",{className:"ibtn",title:w("terminal.new"),onClick:()=>{f()},children:(0,$t.jsx)(Me,{name:"plus",size:14})})]}),_?.simple&&(0,$t.jsx)("div",{className:"tm-note",children:w("terminal.simpleNote")}),(0,$t.jsxs)("div",{className:"tm-body",children:[a.length===0&&(0,$t.jsxs)("div",{className:"pn-empty",children:[w("terminal.noTerm"),(0,$t.jsx)("div",{style:{marginTop:8},children:(0,$t.jsx)("button",{className:"btn primary",onClick:()=>{f()},children:w("terminal.new")})})]}),a.map(v=>(0,$t.jsx)(L4,{term:v,visible:v.id===l},v.id))]}),u&&(0,$t.jsx)(hl,{title:w("terminal.closeTitle"),body:Ce("terminal.closeBody",{title:u.title}),okLabel:w("terminal.closeOk"),danger:!0,onOk:()=>{p(u)},onClose:()=>h(null)})]})}function L4({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 iM({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:Sb()}),c=new sM;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(w("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=Sb())},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,$t.jsx)("div",{className:"tm-view",ref:i,style:{display:t?"block":"none"}})}var ri,$t,cM=ce(()=>{ri=oe(Ot(),1);nM();rM();un();Wn();Nn();Ur();dl();vs();xi();aM();oM();$t=oe(De(),1)});function uM(){let e=pe(),t=[{tab:"changes",label:w("panel.changes")},{tab:"files",label:w("panel.files")},{tab:"terminal",label:w("panel.terminal")}];return(0,se.jsxs)(se.Fragment,{children:[(0,se.jsxs)("div",{className:"pn-head",children:[(0,se.jsx)("div",{className:"pn-tabs",children:t.map(i=>(0,se.jsx)("button",{className:`pn-tab${e.panelTab===i.tab?" on":""}`,onClick:()=>e.setPanelTab(i.tab),children:i.label},i.tab))}),(0,se.jsx)("button",{className:"ibtn pn-close",title:w("panel.closeTitle"),onClick:()=>e.closePanel(),children:(0,se.jsx)(Me,{name:"x"})})]}),(0,se.jsxs)("div",{className:"pn-body",children:[e.panelTab==="changes"&&(0,se.jsx)(P4,{}),e.panelTab==="files"&&(0,se.jsx)(U4,{}),e.panelTab==="terminal"&&(0,se.jsx)(lM,{})]})]})}function I4(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 z4(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 P4(){let{projects:e,threads:t}=ct(),i=pe(),n=Mn(M=>M.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)({}),v=(0,bt.useRef)(n),g=(0,bt.useRef)(null);g.current=l;let m=t.find(M=>M.id===i.currentThreadId)??null,b=m?e.find(M=>M.id===m.projectId):e.find(M=>M.id===i.currentProjectId),S=b?.id??null,x=(0,bt.useCallback)(async()=>{if(!S){r(null);return}try{let M=await te.call("git.status",{projectId:S});r(M);let O=g.current;O&&!M.files?.some(F=>F.path===O)&&(c(null),h(null))}catch(M){r({isRepo:!1,error:String(M?.message??M)})}},[S]);(0,bt.useEffect)(()=>{x();let M=setInterval(()=>{x()},3e3);return()=>clearInterval(M)},[x]),(0,bt.useEffect)(()=>{let M=v.current;v.current=n,(M==="running"||M==="initializing")&&n!=="running"&&n!=="initializing"&&x()},[n,x]);let C=(0,bt.useCallback)(async M=>{if(S){c(M.path),h({loading:!0});try{let O=await te.call("git.diff",{projectId:S,path:M.path});if(O.tooLarge)h({tooLarge:!0});else if(O.error)h({error:O.error});else{let F=I4(O.diff??"");h({hunks:F}),_(W=>({...W,[M.path]:z4(O.diff??"")}))}}catch(O){h({error:String(O?.message??O)})}}},[S]),N=(0,bt.useCallback)(async M=>{if(S){o(!0);try{await te.call("git.discard",{projectId:S,path:M.path}),l===M.path&&(c(null),h(null)),await x()}catch(O){ze(w("panel.failDiscard")+ft(O),!0)}finally{o(!1)}}},[S,l,x]);return b?s&&!s.isRepo?(0,se.jsxs)("div",{className:"pn-empty",children:[w("panel.notGit"),s.error&&(0,se.jsx)("div",{className:"pn-empty-sub",children:s.error})]}):(0,se.jsxs)(se.Fragment,{children:[(0,se.jsxs)("div",{className:"chg-head",children:[(0,se.jsxs)("span",{className:"chg-branch",title:w("panel.branch"),children:[(0,se.jsx)(Me,{name:"changes",size:13})," ",s?.branch??"\u2026"]}),(0,se.jsx)("button",{className:"ibtn",title:w("common.refresh"),onClick:()=>{x()},children:(0,se.jsx)(Me,{name:"refresh",size:14})})]}),(0,se.jsxs)("div",{className:"chg-list",children:[(s?.files??[]).length===0&&(0,se.jsx)("div",{className:"pn-empty",children:w("panel.clean")}),s?.files?.map(M=>{let O=p[M.path];return(0,se.jsxs)("div",{className:`chg-row${l===M.path?" on":""}`,onClick:()=>{C(M)},children:[(0,se.jsx)("span",{className:`chg-kind k-${M.kind}`,title:M.kind,children:B4(M.kind)}),(0,se.jsx)("span",{className:"chg-path",title:M.path,children:M.path}),O&&(0,se.jsxs)("span",{className:"chg-stat",children:[(0,se.jsxs)("em",{className:"add",children:["+",O.add]})," ",(0,se.jsxs)("em",{className:"del",children:["\u2212",O.del]})]}),(0,se.jsx)("button",{className:"ibtn chg-discard",title:w("panel.discardBtn"),disabled:a,onClick:F=>{F.stopPropagation(),f(M)},children:(0,se.jsx)(Me,{name:"x",size:13})})]},M.path)})]}),(0,se.jsxs)("div",{className:"chg-diff",children:[u?.loading&&(0,se.jsx)("div",{className:"pn-empty",children:w("panel.loadingDiff")}),u?.tooLarge&&(0,se.jsx)("div",{className:"pn-empty",children:w("panel.diffTooLarge")}),u?.error&&(0,se.jsx)("div",{className:"pn-empty",children:u.error}),u?.hunks&&(0,se.jsx)(of,{hunks:u.hunks,path:l??void 0})]}),d&&(0,se.jsx)(hl,{title:w("panel.discardTitle"),body:d.kind==="untracked"?Ce("panel.discardUntracked",{path:d.path}):Ce("panel.discardTracked",{path:d.path}),okLabel:w("common.discard"),danger:!0,onOk:()=>{N(d)},onClose:()=>f(null)})]}):(0,se.jsx)("div",{className:"pn-empty",children:w("panel.pickProject")})}function U4(){let{projects:e,threads:t}=ct(),i=pe(),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(b=>({...b,[m]:"loading"}));try{let b=await te.call("files.tree",{projectId:r,dir:m});o(S=>({...S,[m]:b.error?`err:${b.error}`:b.entries??[]}))}catch(b){o(S=>({...S,[m]:`err:${String(b?.message??b)}`}))}}},[r]);(0,bt.useEffect)(()=>{o({}),c(null),h(null),r&&d(".")},[r,d]);let f=m=>{if(!m.isDir){p(m.path);return}let b=a[m.path];b&&b!=="loading"?o(S=>{let x={...S};return delete x[m.path],x}):b||d(m.path)},p=async m=>{if(r){c(m),h({loading:!0});try{let b=await te.call("files.read",{projectId:r,path:m});h(b)}catch(b){h({error:String(b?.message??b)})}}},_=(0,bt.useRef)(null);if((0,bt.useEffect)(()=>{let m=_.current;if(!(!m||!u?.text))try{Qd.highlightElement(m)}catch{}},[u?.text,u?.language]),!s)return(0,se.jsx)("div",{className:"pn-empty",children:w("panel.pickProject")});let v=l?l.split("/"):[],g=(m,b)=>{let S=a[m];return!S||S==="loading"?null:typeof S=="string"?(0,se.jsx)("div",{className:"ft-err",style:{paddingLeft:8+b*14},children:S.slice(4)}):S.map(x=>(0,se.jsxs)("div",{children:[(0,se.jsxs)("div",{className:`ft-row${l===x.path?" on":""}`,style:{paddingLeft:8+b*14},onClick:()=>f(x),title:x.path,children:[x.isDir?(0,se.jsxs)(se.Fragment,{children:[(0,se.jsx)("span",{className:`caret${a[x.path]&&a[x.path]!=="loading"?" open":""}`,children:"\u203A"}),(0,se.jsx)(Me,{name:"files",size:13})]}):(0,se.jsxs)(se.Fragment,{children:[(0,se.jsx)("span",{className:"caret",style:{visibility:"hidden"},children:"\u203A"}),(0,se.jsx)("span",{className:"ft-dot"})]}),(0,se.jsx)("span",{className:"ft-name",children:x.name})]}),x.isDir&&g(x.path,b+1)]},x.path))};return(0,se.jsxs)(se.Fragment,{children:[(0,se.jsx)("div",{className:"ft-crumbs",children:l?(0,se.jsxs)(se.Fragment,{children:[(0,se.jsx)("button",{className:"ft-crumb",onClick:()=>c(null),title:w("panel.closePreview"),children:"\xD7"}),v.map((m,b)=>(0,se.jsxs)("span",{className:"ft-crumb-t",children:[b>0?"/":"",m]},b)),(0,se.jsx)("button",{className:"ibtn",title:w("common.copyPath"),onClick:()=>{Ha(l),ze(w("common.copiedPath"))},children:(0,se.jsx)(Me,{name:"copy",size:13})})]}):(0,se.jsx)("span",{className:"ft-crumb-t muted",children:s.name})}),(0,se.jsx)("div",{className:"ft-tree",children:g(".",0)}),l&&(0,se.jsxs)("div",{className:"ft-view",children:[u?.loading&&(0,se.jsx)("div",{className:"pn-empty",children:w("panel.reading")}),u?.binary&&(0,se.jsx)("div",{className:"pn-empty",children:w("panel.binary")}),u?.tooLarge&&(0,se.jsx)("div",{className:"pn-empty",children:w("panel.tooLarge")}),u?.error&&(0,se.jsx)("div",{className:"pn-empty",children:u.error}),u?.text!=null&&(0,se.jsx)("pre",{className:"ft-pre",children:(0,se.jsx)("code",{ref:_,className:`language-${u.language??"plaintext"}`,children:u.text})})]})]})}var bt,se,B4,hM=ce(()=>{bt=oe(Ot(),1);un();Wn();Cl();Nn();Ur();lf();dl();vs();xi();cM();Jd();Y_();se=oe(De(),1);B4=e=>w(`panel.gitKind.${e}`)});function dM(){let{state:e,version:t}=gs(),i=Mn(l=>l.pending),n=ct(l=>l.providers),[s,r]=(0,Nu.useState)(!1),[a,o]=(0,Nu.useState)(!1);return(0,Nu.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:w("boot.serviceDown")}),(0,ai.jsx)("button",{className:"btn primary",onClick:()=>location.reload(),children:w("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:w("boot.connecting")})]}):(0,ai.jsxs)(qE,{sidebar:(0,ai.jsx)(XE,{pendingByThread:new Set(i.map(l=>Mn.getState().threadId).filter(Boolean))}),topbar:(0,ai.jsx)(Jk,{pendingCount:i.length}),panel:(0,ai.jsx)(uM,{}),children:[e==="reconnecting"&&(0,ai.jsx)("div",{className:"connbar",children:w("boot.reconnecting")}),(0,ai.jsx)(XT,{}),s&&(0,ai.jsx)(JT,{onClose:()=>r(!1)}),a&&(0,ai.jsx)(nv,{onClose:()=>o(!1),providers:n}),(0,ai.jsx)(jE,{})]})}var Nu,ai,fM=ce(()=>{Pc();KE();ZE();eT();ZT();Cl();Wn();Nu=oe(Ot(),1);eN();hM();iu();vs();xi();ai=oe(De(),1)});function pM(){let{state:e,version:t}=gs(),[i,n]=(0,Ni.useState)([]),[s,r]=(0,Ni.useState)([]),[a,o]=(0,Ni.useState)(""),[l,c]=(0,Ni.useState)(""),[u,h]=(0,Ni.useState)([]),[d,f]=(0,Ni.useState)([]),[p,_]=(0,Ni.useState)([]),[v,g]=(0,Ni.useState)(""),[m,b]=(0,Ni.useState)(""),S=(0,Ni.useRef)(null);(0,Ni.useEffect)(()=>{e==="open"&&(Qr("projects.list").then(O=>n(O??[])),Qr("threads.list").then(O=>r(O??[])))},[e]),(0,Ni.useEffect)(()=>{if(S.current?.(),S.current=null,h([]),f([]),_([]),!(!l||e!=="open"))return Qr("threads.get",{id:l}).then(O=>{let F=O;h(F.events??[]),f(F.pending??[]),_(F.queue??[])}),S.current=te.subscribe(`thread:${l}`,(O,F)=>{let W=F;if(W.type==="event"&&W.event&&(h(z=>[...z,W.event]),W.event.type==="permission_resolved"||W.event.type==="question_answered")){let z=W.event.requestId;f(I=>I.filter(R=>R.requestId!==z))}W.type==="queue"&&W.queue&&_(W.queue)}),()=>S.current?.()},[l,e]),(0,Ni.useEffect)(()=>{let O=u.filter(z=>z.type==="permission_request"||z.type==="question"),F=new Set(u.filter(z=>z.type==="permission_resolved"||z.type==="question_answered").map(z=>z.requestId)),W=O.filter(z=>!F.has(z.requestId)).map(z=>({requestId:z.requestId??"",kind:z.type==="question"?"question":"permission",options:z.options}));f(z=>{let I=new Map(z.map(R=>[R.requestId,R]));for(let R of W)I.set(R.requestId,R);return[...I.values()]})},[u]);let x=async()=>{if(!l)return;let O=await Qr("threads.get",{id:l}).catch(()=>null);O&&(h(O.events??[]),f(F=>{let W=new Map(F.map(z=>[z.requestId,z]));for(let z of O.pending??[])W.set(z.requestId,z);return[...W.values()]}),_(O.queue??[]))},C=async O=>{if(b(""),!l||!v.trim())return;let F=v;g("");try{await Qr("thread.send",{id:l,text:F,behavior:O})}catch(W){b(String(W?.message??W))}await x()},N=async(O,F,W)=>{await Qr("thread.respond",{id:l,requestId:O,optionId:F,answers:W}).catch(z=>b(String(z?.message??z))),setTimeout(()=>{x()},1500)},M=async()=>{if(!a)return;let O=await Qr("threads.create",{projectId:a,provider:"mock"}).catch(F=>(b(String(F?.message??F)),null));O&&(r(F=>[O,...F]),c(O.id))};return(0,st.jsxs)("div",{style:{display:"flex",height:"100vh",font:"13px/1.5 system-ui",color:"var(--fg)"},children:[(0,st.jsxs)("div",{style:{width:260,borderRight:"1px solid var(--border)",padding:12,overflowY:"auto"},children:[(0,st.jsx)("div",{style:{marginBottom:8},children:e==="open"?`\u5DF2\u8FDE\u63A5 \xB7 ${t??""}`:"\u8FDE\u63A5\u4E2D\u2026"}),(0,st.jsxs)("select",{value:a,onChange:O=>o(O.target.value),style:{width:"100%"},children:[(0,st.jsx)("option",{value:"",children:"\u9009\u62E9\u9879\u76EE"}),i.map(O=>(0,st.jsx)("option",{value:O.id,children:O.name},O.id))]}),(0,st.jsx)("button",{onClick:()=>{M()},disabled:!a,style:{width:"100%",marginTop:8},children:"\u65B0\u5EFA\u5BF9\u8BDD\uFF08mock\uFF09"}),(0,st.jsx)("div",{style:{marginTop:12},children:s.filter(O=>!a||O.projectId===a).map(O=>(0,st.jsxs)("div",{onClick:()=>c(O.id),style:{padding:"6px 8px",cursor:"pointer",borderRadius:4,background:O.id===l?"var(--bg-active, #333)":"transparent"},children:[O.title," ",(0,st.jsxs)("span",{style:{opacity:.6},children:["(",O.status,")"]})]},O.id))})]}),(0,st.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column"},children:[(0,st.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:12},children:[u.map((O,F)=>(0,st.jsx)("pre",{style:{margin:"4px 0",fontSize:11,whiteSpace:"pre-wrap",borderBottom:"1px solid var(--border)",paddingBottom:4},children:(O.seq??"")+" "+(O.type??"?")+" "+JSON.stringify(O).slice(0,400)},F)),d.map(O=>(0,st.jsxs)("div",{style:{border:"1px solid var(--warn, orange)",borderRadius:6,padding:8,margin:"8px 0"},children:[(0,st.jsxs)("div",{children:["\u6388\u6743/\u63D0\u95EE ",O.requestId]}),O.options?.map(F=>(0,st.jsx)("button",{onClick:()=>{N(O.requestId,F.id)},style:{marginRight:8},children:F.label},F.id)),O.kind==="question"&&(0,st.jsx)("button",{onClick:()=>{N(O.requestId,void 0,{q1:"staging",q2:""})},children:"\u586B\u8868\u63D0\u4EA4"}),(0,st.jsx)("button",{onClick:()=>{N(O.requestId,void 0,void 0)},children:"\u53D6\u6D88"})]},O.requestId))]}),p.length>0&&(0,st.jsxs)("div",{style:{padding:"4px 12px",opacity:.7},children:["\u6392\u961F\u4E2D\uFF1A",p.length," \u6761"]}),m&&(0,st.jsx)("div",{style:{padding:"4px 12px",color:"var(--danger, red)"},children:m}),(0,st.jsxs)("div",{style:{display:"flex",gap:8,padding:12,borderTop:"1px solid var(--border)"},children:[(0,st.jsx)("input",{value:v,onChange:O=>g(O.target.value),onKeyDown:O=>{O.key==="Enter"&&C()},placeholder:"/perm /plan /slow /exit \u2026",style:{flex:1}}),(0,st.jsx)("button",{onClick:()=>{C()},children:"\u53D1\u9001"}),(0,st.jsx)("button",{onClick:()=>{C("steer")},children:"\u63D2\u8BDD"}),(0,st.jsx)("button",{onClick:()=>{Qr("thread.interrupt",{id:l})},children:"\u6253\u65AD"})]})]})]})}var Ni,st,Qr,mM=ce(()=>{Ni=oe(Ot(),1);Pc();Nn();st=oe(De(),1),Qr=(e,t)=>te.call(e,t)});var gM,wb,H4,Eb,zf,F4,te,q4,Nn=ce(()=>{Zb();Qb();Jb();e0();t0();gM=oe(SE(),1);EE();xi();NE();Pc();un();Wn();fM();mM();af();wb=oe(De(),1),H4=kl(),Eb=new URLSearchParams(location.search),zf=Eb.get("theme");TE(location.search);wE(location.search);F4=window.matchMedia?.("(prefers-color-scheme: dark)").matches;document.documentElement.dataset.theme=zf==="light"||zf==="dark"?zf:F4?"dark":"light";te=new kd(H4,Ed());window.__ws=te;window.__stores={useData:ct,useUi:pe,useConnection:gs};Promise.resolve().then(()=>(Cl(),NT)).then(e=>{window.__tl=e.useTimeline});te.onState(e=>gs.getState().set({state:e}));te.connect();te.waitHello().then(async e=>{gs.getState().set({version:e.version??null}),pe.getState().bind(te);try{let t=await te.call("settings.get");if(pe.getState().hydrate(t),!zf){let{applyTheme:i}=await Promise.resolve().then(()=>(iu(),HT));i(t.theme??"auto")}}catch{}await ct.getState().bind(te)});setInterval(()=>te.ping(),1e4);q4=Eb.get("debug")==="1";(0,gM.createRoot)(document.getElementById("root")).render(q4?(0,wb.jsx)(pM,{}):(0,wb.jsx)(dM,{}));Eb.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)});Nn();})(); +`)}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();})(); /*! Bundled license information: scheduler/cjs/scheduler.production.js: diff --git a/packages/agent-console/assets/icon.svg b/packages/agent-console/assets/icon.svg index d75b7e0..28a311b 100644 --- a/packages/agent-console/assets/icon.svg +++ b/packages/agent-console/assets/icon.svg @@ -1,10 +1,8 @@ - - - - - - - + + + + + + - diff --git a/packages/agent-console/daemon/dist/main.js b/packages/agent-console/daemon/dist/main.js index 322acbd..346a82c 100644 --- a/packages/agent-console/daemon/dist/main.js +++ b/packages/agent-console/daemon/dist/main.js @@ -38,6 +38,15 @@ function initLog(dataDir) { } catch { } } +function guardConsole() { + if (guarded) return; + guarded = true; + for (const stream of [process.stdout, process.stderr]) { + stream?.on?.("error", () => { + consoleGone = true; + }); + } +} function log(level, msg, extra) { const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] [${level}] ${msg}${extra !== void 0 ? " " + safeJson(extra) : ""}`; try { @@ -50,8 +59,19 @@ function log(level, msg, extra) { if (logFile) appendFileSync(logFile, line + "\n", "utf8"); } catch { } + guardConsole(); + if (consoleGone) return; + const stream = level === "info" ? process.stdout : process.stderr; + if (stream?.destroyed || stream?.writableEnded) { + consoleGone = true; + return; + } const fn = level === "error" ? console.error : level === "warn" ? console.warn : console.log; - fn(`[agent-console] ${msg}`, extra !== void 0 ? extra : ""); + try { + fn(`[agent-console] ${msg}`, extra !== void 0 ? extra : ""); + } catch { + consoleGone = true; + } } function safeJson(v) { try { @@ -60,12 +80,255 @@ function safeJson(v) { return String(v); } } -var logDir, today, logFile; +var logDir, today, logFile, consoleGone, guarded; var init_log = __esm({ "daemon/src/log.ts"() { logDir = ""; today = ""; logFile = ""; + consoleGone = false; + guarded = false; + } +}); + +// daemon/src/util/i18n.ts +function normalizeLang(raw) { + const s = String(raw ?? "").trim().toLowerCase(); + if (!s) return "zh"; + if (s === "zh" || s.startsWith("zh-")) return "zh"; + return "en"; +} +function setAppLocale(lang) { + locale = normalizeLang(lang); +} +function intlLocale() { + return locale === "zh" ? "zh-CN" : "en-US"; +} +function tr(key, params) { + let s = dict[locale][key] ?? dict.en[key] ?? key; + if (params) { + for (const [k, v] of Object.entries(params)) s = s.replaceAll(`{${k}}`, String(v)); + } + return s; +} +var locale, dict; +var init_i18n = __esm({ + "daemon/src/util/i18n.ts"() { + locale = "zh"; + dict = { + zh: { + "thread.defaultTitle": "\u65B0\u5BF9\u8BDD", + "notice.daemonRestart": "\u540E\u53F0\u5DF2\u91CD\u542F\uFF0C\u672C\u8F6E\u5DF2\u4E2D\u65AD", + "notice.sessionStartFailed": "\u4F1A\u8BDD\u542F\u52A8\u5931\u8D25\uFF1A{detail}", + "notice.sendFailed": "\u53D1\u9001\u5931\u8D25\uFF1A{detail}", + "notice.effortNextTurn": "\u601D\u8003\u5F3A\u5EA6\u5DF2\u4FDD\u5B58\uFF0C\u5C06\u5728\u4E0B\u4E00\u8F6E\u751F\u6548", + "notice.effortResetOnModel": "\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8BE5\u601D\u8003\u5F3A\u5EA6\uFF0C\u5DF2\u6062\u590D\u4E3A Default", + "turn.agentExit": "Agent \u8FDB\u7A0B\u610F\u5916\u9000\u51FA", + "attachment.missing": "\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u5931\u6548\uFF08{ref}\uFF09\uFF0C\u8BF7\u91CD\u65B0\u4E0A\u4F20", + "notice.acpImageByPath": "{agent} \u4E0D\u80FD\u76F4\u63A5\u770B\u56FE\u7247\uFF08\u5B83\u7684 ACP \u521D\u59CB\u5316\u672A\u58F0\u660E\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF09\uFF0C\u5DF2\u6539\u4E3A\u53D1\u9001\u56FE\u7247\u7684\u6587\u4EF6\u8DEF\u5F84\uFF1A{paths}", + "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}", + "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", + "claude.notRunning": "claude \u6CA1\u6709\u5728\u8FD0\u884C\uFF0C\u6D88\u606F\u672A\u53D1\u51FA", + "claude.closed": "\u4F1A\u8BDD\u5DF2\u5173\u95ED", + "export.defaultModel": "\u9ED8\u8BA4", + "bin.notOnPath": "PATH \u91CC\u627E\u4E0D\u5230 {name}", + "bin.or": " \u6216 ", + "launch.notFound": "\u627E\u4E0D\u5230\u81EA\u5B9A\u4E49\u7684\u53EF\u6267\u884C\u6587\u4EF6\uFF1A{cmd}\uFF08\u8BF7\u586B\u5199\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u6216 PATH \u91CC\u80FD\u627E\u5230\u7684\u547D\u4EE4\u540D\uFF09", + "codex.notFound": "\u627E\u4E0D\u5230 codex\uFF08{detail}\uFF09\u3002\u8BF7\u5148\u5B89\u88C5\uFF1A{hint}", + "provider.disabled": "\u5DF2\u5728\u8BBE\u7F6E\u4E2D\u7981\u7528", + "provider.planned": "\u5C1A\u672A\u63A5\u5165", + "provider.disabledNamed": "{name} \u5DF2\u5728\u8BBE\u7F6E\u4E2D\u7981\u7528", + "provider.plannedNamed": "{name} \u5C1A\u672A\u63A5\u5165\uFF0C\u6682\u4E0D\u80FD\u65B0\u5EFA\u5BF9\u8BDD", + "provider.unavailable": "{name} \u672A\u5B89\u88C5\u6216\u4E0D\u53EF\u7528", + "provider.unknown": "\u672A\u77E5 Agent\uFF1A{id}", + "provider.timeout": "\u68C0\u6D4B\u8D85\u65F6", + "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", + "err.projectDirGone": "\u9879\u76EE\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728", + "err.terminalMissing": "\u7EC8\u7AEF\u4E0D\u5B58\u5728", + "err.noManager": "\u4F1A\u8BDD\u7BA1\u7406\u5668\u672A\u542F\u52A8", + "err.badParams": "\u53C2\u6570\u4E0D\u5BF9\uFF1A{detail}", + "export.me": "\u6211", + "export.steered": "\uFF08\u63D2\u8BDD\uFF09", + "export.reasoning": "\u601D\u8003", + "export.plan": "\u8BA1\u5212", + "export.todo": "\u5F85\u529E", + "err.requestGone": "\u6388\u6743/\u63D0\u95EE\u4E0D\u5B58\u5728\u6216\u5DF2\u56DE\u5E94", + "err.badOption": "optionId \u975E\u6CD5\uFF1A{id}", + "err.cursorOnly": "\u4EC5 Cursor \u5BF9\u8BDD\u652F\u6301\u8BE5\u9009\u9879", + "err.busySwitch": "\u5BF9\u8BDD\u8FD0\u884C\u4E2D\uFF0C\u4E0D\u80FD\u66F4\u6362 Agent", + "err.hasMessages": "\u5DF2\u6709\u6D88\u606F\uFF0C\u4E0D\u80FD\u66F4\u6362 Agent", + "tool.read": "\u8BFB\u53D6 {x}", + "tool.edit": "\u7F16\u8F91 {x}", + "tool.multiEdit": "\u7F16\u8F91 {x}\uFF08{n} \u5904\uFF09", + "tool.overwrite": "\u8986\u76D6 {x}", + "tool.create": "\u65B0\u5EFA {x}", + "tool.notebook": "\u7F16\u8F91\u7B14\u8BB0\u672C {x}", + "tool.run": "\u8FD0\u884C {x}", + "tool.output": "\u67E5\u770B\u8F93\u51FA {x}", + "tool.kill": "\u7ED3\u675F\u8FDB\u7A0B {x}", + "tool.grep": '\u641C\u7D22 "{x}"', + "tool.glob": "\u67E5\u627E {x}", + "tool.fetch": "\u6253\u5F00 {x}", + "tool.webSearch": '\u641C\u7D22\u7F51\u9875 "{x}"', + "tool.todo": "\u66F4\u65B0\u5F85\u529E\uFF08{done}/{n}\uFF09", + "tool.task": "\u5B50\u4EFB\u52A1\uFF1A{x}", + "tool.generic": "\u5DE5\u5177", + "tool.editFiles": "\u4FEE\u6539 {n} \u4E2A\u6587\u4EF6", + "tool.needsApproval": "\u9700\u8981\u6388\u6743", + "perm.editFiles": "\u4FEE\u6539\u6587\u4EF6", + "perm.allow": "\u5141\u8BB8", + "perm.allowSession": "\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8", + "perm.deny": "\u62D2\u7EDD", + "perm.plan": "Agent \u63D0\u4EA4\u4E86\u8BA1\u5212", + "perm.implement": "\u5B9E\u65BD", + "http.internal": "\u670D\u52A1\u5185\u90E8\u9519\u8BEF", + "http.badOrigin": "\u6765\u6E90\u4E0D\u5141\u8BB8", + "http.badPreflight": "\u9884\u68C0\u4E0D\u5141\u8BB8", + "http.badToken": "\u4EE4\u724C\u65E0\u6548", + "http.noAttachment": "\u9644\u4EF6\u4E0D\u5B58\u5728", + "http.method": "\u65B9\u6CD5\u4E0D\u5141\u8BB8", + "http.noApp": "app \u8FD8\u6CA1\u6784\u5EFA\uFF08\u7F3A app/index.html\uFF09", + "http.badPath": "\u8DEF\u5F84\u4E0D\u5408\u6CD5", + "http.pathDenied": "\u8DEF\u5F84\u4E0D\u5141\u8BB8", + "http.noFile": "\u6587\u4EF6\u4E0D\u5B58\u5728", + "http.badType": "\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B", + "http.tooLarge": "\u6587\u4EF6\u592A\u5927\uFF08\u4E0A\u9650 50MB\uFF09", + "http.noRoute": "\u63A5\u53E3\u4E0D\u5B58\u5728", + "codex.error": "Codex \u9519\u8BEF", + "codex.closed": "\u4F1A\u8BDD\u5DF2\u5173\u95ED", + "codex.noTurnSteer": "\u5F53\u524D\u8F6E\u6B21\u8FD8\u6CA1\u5F00\u59CB\uFF0C\u65E0\u6CD5\u63D2\u8BDD", + "acp.exited": "{name} \u8FDB\u7A0B\u9000\u51FA ({code})", + "notice.apiRetry": "API \u91CD\u8BD5\u4E2D\uFF08\u7B2C {n} \u6B21\uFF09", + "notice.compacted": "\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29", + "term.max": "\u6BCF\u4E2A\u9879\u76EE\u6700\u591A {n} \u4E2A\u7EC8\u7AEF", + "term.title": "\u7EC8\u7AEF {n}", + "stub.planned": "\u8BE5 Agent \u5C1A\u672A\u5728 Agent Console \u63A5\u5165\uFF0C\u656C\u8BF7\u671F\u5F85", + "stub.unverified": "\u5DF2\u68C0\u6D4B\u5230 CLI\uFF0C\u4F1A\u8BDD\u9A71\u52A8\u5C1A\u672A\u5B8C\u5168\u9A8C\u8BC1", + "stub.notFound": "\u672A\u627E\u5230 {bin}", + "history.untitled": "\uFF08\u65E0\u6807\u9898\uFF09", + "history.toolCall": "\uFF08\u5386\u53F2\uFF09\u8C03\u7528 {name}", + "fs.pathDenied": "\u8DEF\u5F84\u4E0D\u5141\u8BB8", + "fs.dirMissing": "\u76EE\u5F55\u4E0D\u5B58\u5728", + "fs.dirUnreadable": "\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55", + "fs.fileMissing": "\u6587\u4EF6\u4E0D\u5B58\u5728", + "fs.notFile": "\u4E0D\u662F\u6587\u4EF6", + "fs.unreadable": "\u65E0\u6CD5\u8BFB\u53D6", + "git.missing": "\u627E\u4E0D\u5230 git\uFF08\u8BF7\u5148\u5B89\u88C5 git \u5E76\u52A0\u5165 PATH\uFF09", + "git.binary": "\u4E8C\u8FDB\u5236\u6216\u65E0\u6CD5\u8BFB\u53D6" + }, + en: { + "thread.defaultTitle": "New chat", + "notice.daemonRestart": "Daemon restarted \u2014 this turn was interrupted", + "notice.sessionStartFailed": "Session start failed: {detail}", + "notice.sendFailed": "Send failed: {detail}", + "notice.effortNextTurn": "Reasoning effort saved \u2014 takes effect on the next turn", + "notice.effortResetOnModel": "This model does not support that effort level; reset to Default", + "turn.agentExit": "Agent process exited unexpectedly", + "attachment.missing": "Attachment missing or expired ({ref}) \u2014 upload again", + "notice.acpImageByPath": "{agent} can't see images directly (its ACP initialize doesn't advertise image input); sent the image file path instead: {paths}", + "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}", + "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})", + "claude.notRunning": "claude is not running; the message was not sent", + "claude.closed": "The session is closed", + "export.defaultModel": "Default", + "bin.notOnPath": "{name} was not found on PATH", + "bin.or": " or ", + "launch.notFound": "Custom executable not found: {cmd} (use an absolute path or a command name on PATH)", + "codex.notFound": "codex was not found ({detail}). Install it first: {hint}", + "provider.disabled": "Disabled in Settings", + "provider.planned": "Not supported yet", + "provider.disabledNamed": "{name} is disabled in Settings", + "provider.plannedNamed": "{name} is not supported yet; it can't start new conversations", + "provider.unavailable": "{name} is not installed or not available", + "provider.unknown": "Unknown agent: {id}", + "provider.timeout": "Detection timed out", + "err.projectMissing": "Project not found", + "err.threadMissing": "Conversation not found", + "err.dirMissing": "The folder does not exist or is not a folder", + "err.projectDirGone": "The project folder no longer exists", + "err.terminalMissing": "Terminal not found", + "err.noManager": "The session manager is not running", + "err.badParams": "Invalid parameters: {detail}", + "export.me": "Me", + "export.steered": " (steer)", + "export.reasoning": "Reasoning", + "export.plan": "Plan", + "export.todo": "Todos", + "err.requestGone": "That approval or question no longer exists or was already answered", + "err.badOption": "Invalid optionId: {id}", + "err.cursorOnly": "Only Cursor conversations support this option", + "err.busySwitch": "The conversation is running; the agent can't be changed", + "err.hasMessages": "The conversation already has messages; the agent can't be changed", + "tool.read": "Read {x}", + "tool.edit": "Edit {x}", + "tool.multiEdit": "Edit {x} ({n} edits)", + "tool.overwrite": "Overwrite {x}", + "tool.create": "Create {x}", + "tool.notebook": "Edit notebook {x}", + "tool.run": "Run {x}", + "tool.output": "Read output {x}", + "tool.kill": "Stop process {x}", + "tool.grep": 'Search "{x}"', + "tool.glob": "Find {x}", + "tool.fetch": "Open {x}", + "tool.webSearch": 'Web search "{x}"', + "tool.todo": "Update todos ({done}/{n})", + "tool.task": "Subtask: {x}", + "tool.generic": "Tool", + "tool.editFiles": "Edit {n} file(s)", + "tool.needsApproval": "Needs approval", + "perm.editFiles": "Edit files", + "perm.allow": "Allow", + "perm.allowSession": "Allow for this chat", + "perm.deny": "Deny", + "perm.plan": "The agent proposed a plan", + "perm.implement": "Implement", + "http.internal": "Internal error", + "http.badOrigin": "Origin not allowed", + "http.badPreflight": "Preflight not allowed", + "http.badToken": "Invalid token", + "http.noAttachment": "Attachment not found", + "http.method": "Method not allowed", + "http.noApp": "The app is not built (app/index.html is missing)", + "http.badPath": "Invalid path", + "http.pathDenied": "Path not allowed", + "http.noFile": "File not found", + "http.badType": "Unsupported file type", + "http.tooLarge": "File too large (50 MB max)", + "http.noRoute": "No such endpoint", + "codex.error": "Codex error", + "codex.closed": "The session is closed", + "codex.noTurnSteer": "The turn hasn't started yet; can't steer", + "acp.exited": "{name} exited ({code})", + "notice.apiRetry": "Retrying the API (attempt {n})", + "notice.compacted": "Context compacted", + "term.max": "At most {n} terminals per project", + "term.title": "Terminal {n}", + "stub.planned": "This agent isn't supported in Agent Console yet", + "stub.unverified": "CLI found; its session driver isn't fully verified yet", + "stub.notFound": "{bin} was not found", + "history.untitled": "(untitled)", + "history.toolCall": "(history) called {name}", + "fs.pathDenied": "Path not allowed", + "fs.dirMissing": "Folder not found", + "fs.dirUnreadable": "Can't read the folder", + "fs.fileMissing": "File not found", + "fs.notFile": "Not a file", + "fs.unreadable": "Can't read the file", + "git.missing": "git was not found (install git and add it to PATH)", + "git.binary": "Binary or unreadable" + } + }; } }); @@ -94,8 +357,8 @@ function normPath(p, platform = process.platform) { function samePath(a, b) { return normPath(a) === normPath(b); } -function validId(id) { - return typeof id === "string" && ID_RE.test(id); +function validId(id2) { + return typeof id2 === "string" && ID_RE.test(id2); } var ID_RE; var init_paths = __esm({ @@ -394,9 +657,9 @@ async function scriptPerm(ctx) { kind: "tool", detail: { command: "npm test", cwd: ".", toolName: "Bash" }, options: [ - { id: "accept", label: "\u5141\u8BB8", kind: "allow_once" }, - { id: "acceptForSession", label: "\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8", kind: "allow_always" }, - { id: "decline", label: "\u62D2\u7EDD", kind: "reject_once" } + { id: "accept", label: tr("perm.allow"), kind: "allow_once" }, + { id: "acceptForSession", label: tr("perm.allowSession"), kind: "allow_always" }, + { id: "decline", label: tr("perm.deny"), kind: "reject_once" } ] }); const ans = await ctx.waitFor(requestId); @@ -431,7 +694,7 @@ async function scriptPlan(ctx) { detail: { markdown: "\u89C1\u4E0A\u65B9\u8BA1\u5212" }, options: [ { id: "implement", label: "\u5F00\u59CB\u5B9E\u65BD", kind: "allow_once" }, - { id: "reject", label: "\u62D2\u7EDD", kind: "reject_once" } + { id: "reject", label: tr("perm.deny"), kind: "reject_once" } ] }); const ans = await ctx.waitFor(requestId); @@ -475,10 +738,10 @@ async function scriptAsk(ctx) { async function scriptSlow(ctx) { const { emit } = ctx; for (let i = 1; i <= 6; i++) { - const id = "s" + i; - emit({ type: "tool_call", itemId: id, kind: "bash", title: `\u6B65\u9AA4 ${i}/6`, status: "running", input: { command: `step ${i}` } }); + const id2 = "s" + i; + emit({ type: "tool_call", itemId: id2, kind: "bash", title: `\u6B65\u9AA4 ${i}/6`, status: "running", input: { command: `step ${i}` } }); if (await sleepAbortable(2e3, ctx)) return; - emit({ type: "tool_call", itemId: id, kind: "bash", title: `\u6B65\u9AA4 ${i}/6`, status: "ok", output: `\u6B65\u9AA4 ${i} \u5B8C\u6210`, durationMs: 2e3 }); + emit({ type: "tool_call", itemId: id2, kind: "bash", title: `\u6B65\u9AA4 ${i}/6`, status: "ok", output: `\u6B65\u9AA4 ${i} \u5B8C\u6210`, durationMs: 2e3 }); } emit({ type: "assistant_message", itemId: "sm", text: "6 \u4E2A\u6B65\u9AA4\u5168\u90E8\u8DD1\u5B8C\u3002" }); } @@ -572,6 +835,7 @@ function createMockProvider() { var mockCapabilities, rid, sleep, MockCrash, MockSession, mockProviderMetrics; var init_mock = __esm({ "daemon/src/providers/mock.ts"() { + init_i18n(); init_queue(); init_diff(); init_slash(); @@ -639,7 +903,7 @@ var init_mock = __esm({ if (e.itemId) e.itemId = p + e.itemId; this.emit(ev); }, - waitFor: (id) => this.waitFor(id), + waitFor: (id2) => this.waitFor(id2), interrupted: () => this.interruptFlag || this.closed, steerText: () => this.steered.join("\uFF1B"), replyPrefix: () => this.resumePrefix(), @@ -680,9 +944,9 @@ var init_mock = __esm({ } async interrupt() { this.interruptFlag = true; - for (const [id, resolve2] of this.pendingReq) { + for (const [id2, resolve2] of this.pendingReq) { resolve2({ cancelled: true }); - this.pendingReq.delete(id); + this.pendingReq.delete(id2); } await sleep(120); } @@ -692,8 +956,8 @@ var init_mock = __esm({ async setModel(model) { this.o.model = model; } - async setMode(mode) { - this.o.mode = mode; + async setMode(mode2) { + this.o.mode = mode2; } async setEffort(effort) { this.o.effort = effort; @@ -924,7 +1188,7 @@ async function resolveFirstBin(names) { if (r.ok) return { ...r, binName }; } const label = uniq[0] ?? "cli"; - return { ok: false, reason: `PATH \u91CC\u627E\u4E0D\u5230 ${uniq.length > 1 ? uniq.join(" \u6216 ") : label}` }; + return { ok: false, reason: tr("bin.notOnPath", { name: uniq.length > 1 ? uniq.join(tr("bin.or")) : label }) }; } function clearBinCache(name) { if (name) cache.delete(name); @@ -939,7 +1203,7 @@ async function resolveBinWith(name, deps = {}) { const P = win ? path2.win32 : path2.posix; const exists = deps.exists ?? existsSync4; const hits = (deps.find ?? which)(name); - if (!hits.length) return { ok: false, reason: `PATH \u91CC\u627E\u4E0D\u5230 ${name}` }; + if (!hits.length) return { ok: false, reason: tr("bin.notOnPath", { name }) }; const first = hits[0]; if (!win) return { ok: true, cmd: first, prefixArgs: [], display: first, via: "path" }; const ext = P.extname(first).toLowerCase(); @@ -1031,6 +1295,7 @@ var IS_WIN, cache, CACHE_MS, CMD_META, liveTrees, exitHookInstalled; var init_bin = __esm({ "daemon/src/util/bin.ts"() { init_pathscan(); + init_i18n(); IS_WIN = process.platform === "win32"; cache = /* @__PURE__ */ new Map(); CACHE_MS = 60 * 1e3; @@ -1058,44 +1323,44 @@ function callInfo(name, input = {}, cwd = "") { const file = String(input.file_path ?? input.path ?? input.notebook_path ?? ""); switch (t) { case "Read": - return f("read", `\u8BFB\u53D6 ${relPath(file, cwd)}`, { path: file, offset: input.offset, limit: input.limit }); + return f("read", tr("tool.read", { x: relPath(file, cwd) }), { path: file, offset: input.offset, limit: input.limit }); case "Edit": - return f("edit", `\u7F16\u8F91 ${relPath(file, cwd)}`, { path: file, old: input.old_string, new: input.new_string }); + return f("edit", tr("tool.edit", { x: relPath(file, cwd) }), { path: file, old: input.old_string, new: input.new_string }); case "MultiEdit": - return f("edit", `\u7F16\u8F91 ${relPath(file, cwd)}\uFF08${(input.edits || []).length} \u5904\uFF09`, { path: file, edits: input.edits ?? [] }); + return f("edit", tr("tool.multiEdit", { x: relPath(file, cwd), n: (input.edits || []).length }), { path: file, edits: input.edits ?? [] }); case "Write": - return f("write", `${input._exists ? "\u8986\u76D6" : "\u65B0\u5EFA"} ${relPath(file, cwd)}`, { path: file, content: input.content }); + return f("write", tr(input._exists ? "tool.overwrite" : "tool.create", { x: relPath(file, cwd) }), { path: file, content: input.content }); case "NotebookEdit": - return f("edit", `\u7F16\u8F91\u7B14\u8BB0\u672C ${relPath(String(input.notebook_path || file), cwd)}`, { path: input.notebook_path ?? file }); + return f("edit", tr("tool.notebook", { x: relPath(String(input.notebook_path || file), cwd) }), { path: input.notebook_path ?? file }); case "Bash": - return f("bash", `\u8FD0\u884C ${trunc(String(input.command ?? ""))}`, { command: input.command, description: input.description }); + return f("bash", tr("tool.run", { x: trunc(String(input.command ?? "")) }), { command: input.command, description: input.description }); case "BashOutput": - return f("bash", `\u67E5\u770B\u8F93\u51FA ${String(input.bash_id ?? "")}`, { bashId: input.bash_id }); + return f("bash", tr("tool.output", { x: String(input.bash_id ?? "") }), { bashId: input.bash_id }); case "KillShell": - return f("bash", `\u7ED3\u675F\u8FDB\u7A0B ${String(input.shell_id ?? "")}`, { shellId: input.shell_id }); + return f("bash", tr("tool.kill", { x: String(input.shell_id ?? "") }), { shellId: input.shell_id }); case "Grep": - return f("search", `\u641C\u7D22 "${trunc(String(input.pattern ?? ""), 40)}"`, { pattern: input.pattern, path: input.path, glob: input.glob }); + return f("search", tr("tool.grep", { x: trunc(String(input.pattern ?? ""), 40) }), { pattern: input.pattern, path: input.path, glob: input.glob }); case "Glob": case "LS": - return f("glob", `\u67E5\u627E ${trunc(String(input.pattern ?? input.path ?? ""), 40)}`, { pattern: input.pattern, path: input.path }); + return f("glob", tr("tool.glob", { x: trunc(String(input.pattern ?? input.path ?? ""), 40) }), { pattern: input.pattern, path: input.path }); case "WebFetch": - return f("web", `\u6253\u5F00 ${hostOf(String(input.url ?? ""))}`, { url: input.url }); + return f("web", tr("tool.fetch", { x: hostOf(String(input.url ?? "")) }), { url: input.url }); case "WebSearch": - return f("web", `\u641C\u7D22\u7F51\u9875 "${trunc(String(input.query ?? ""), 40)}"`, { query: input.query }); + return f("web", tr("tool.webSearch", { x: trunc(String(input.query ?? ""), 40) }), { query: input.query }); case "TodoWrite": { const items = todoItems(input.todos ?? []); const done = items.filter((x) => x.status === "done").length; - return f("todo", `\u66F4\u65B0\u5F85\u529E\uFF08${done}/${items.length}\uFF09`, { items }); + return f("todo", tr("tool.todo", { done, n: items.length }), { items }); } case "Task": case "Agent": - return f("task", `\u5B50\u4EFB\u52A1\uFF1A${trunc(String(input.description ?? input.prompt ?? ""), 40)}`, { description: input.description }); + return f("task", tr("tool.task", { x: trunc(String(input.description ?? input.prompt ?? ""), 40) }), { description: input.description }); default: break; } const m = /^mcp__([^_]+)__(.+)$/.exec(t); if (m) return f("mcp", `${m[1]} \xB7 ${m[2]}`, { server: m[1], tool: m[2] }); - return f("other", t || "\u5DE5\u5177", {}); + return f("other", t || tr("tool.generic"), {}); } function hostOf(url) { try { @@ -1113,6 +1378,7 @@ function todoItems(todos = []) { var MAX_CMD, trunc; var init_kinds = __esm({ "daemon/src/agents/kinds.ts"() { + init_i18n(); MAX_CMD = 80; trunc = (s, n = MAX_CMD) => s.length > n ? s.slice(0, n - 1) + "\u2026" : s; } @@ -1126,9 +1392,14 @@ function itemIdFor(st, blockIdx, blkType) { const k = blockKind(blkType); const n = st.typeSeq.get(k) ?? 0; st.typeSeq.set(k, n + 1); - const id = `${st.msgId}:${k}${n}`; - st.itemIdByBlock.set(blockIdx, id); - return id; + const id2 = `${st.msgId}:${k}${n}`; + st.itemIdByBlock.set(blockIdx, id2); + return id2; +} +function costIsReal(modelUsage) { + if (!modelUsage || typeof modelUsage !== "object") return true; + const names = Object.keys(modelUsage); + return names.every((n) => /claude|opus|sonnet|haiku/i.test(n)); } function mapSdkMessage(m, st, cwd) { const out = []; @@ -1140,10 +1411,10 @@ function mapSdkMessage(m, st, cwd) { if (sid) out.push({ type: "provider_session_id", id: sid }); } if (r.subtype === "api_retry") { - out.push({ type: "notice", level: "warn", message: `API \u91CD\u8BD5\u4E2D\uFF08\u7B2C ${r.attempt ?? "?"} \u6B21\uFF09` }); + out.push({ type: "notice", level: "warn", message: tr("notice.apiRetry", { n: String(r.attempt ?? "?") }) }); } if (r.subtype === "compact_boundary") { - out.push({ type: "notice", level: "info", message: "\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29" }); + out.push({ type: "notice", level: "info", message: tr("notice.compacted") }); } return out; } @@ -1227,7 +1498,7 @@ function mapSdkMessage(m, st, cwd) { inputTokens: num("input_tokens"), outputTokens: num("output_tokens"), cacheReadTokens: num("cache_read_input_tokens"), - costUsd: typeof r.total_cost_usd === "number" ? r.total_cost_usd : 0 + costUsd: typeof r.total_cost_usd === "number" && costIsReal(r.modelUsage) ? r.total_cost_usd : 0 }); const subtype = str(r.subtype) ?? ""; const interrupted = st.sawInterrupt || /interrupt/i.test(subtype); @@ -1249,7 +1520,7 @@ function mapSdkMessage(m, st, cwd) { function mapToolUse(blk, cwd) { const input = rec(blk.input); const name = str(blk.name) ?? "tool"; - const id = str(blk.id) ?? ""; + const id2 = str(blk.id) ?? ""; const info = callInfo(name, { ...input, _exists: true }, cwd); let detail = info.detail; if (info.kind === "edit" && (input.old_string !== void 0 || Array.isArray(input.edits))) { @@ -1262,7 +1533,7 @@ function mapToolUse(blk, cwd) { const out = [ { type: "tool_call", - itemId: id, + itemId: id2, kind: info.kind, title: info.title, status: "running", @@ -1285,6 +1556,7 @@ var init_map = __esm({ "daemon/src/providers/claude/map.ts"() { init_kinds(); init_diff(); + init_i18n(); MAX_OUTPUT = 20 * 1024; ANSI_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07/g; clean = (s) => String(s ?? "").replace(ANSI_RE, ""); @@ -1294,72 +1566,6 @@ var init_map = __esm({ } }); -// daemon/src/util/i18n.ts -function normalizeLang(raw) { - const s = String(raw ?? "").trim().toLowerCase(); - if (!s) return "zh"; - if (s === "zh" || s.startsWith("zh-")) return "zh"; - return "en"; -} -function setAppLocale(lang) { - locale = normalizeLang(lang); -} -function tr(key, params) { - let s = dict[locale][key] ?? dict.en[key] ?? key; - if (params) { - for (const [k, v] of Object.entries(params)) s = s.replaceAll(`{${k}}`, String(v)); - } - return s; -} -var locale, dict; -var init_i18n = __esm({ - "daemon/src/util/i18n.ts"() { - locale = "zh"; - dict = { - zh: { - "thread.defaultTitle": "\u65B0\u5BF9\u8BDD", - "notice.daemonRestart": "\u540E\u53F0\u5DF2\u91CD\u542F\uFF0C\u672C\u8F6E\u5DF2\u4E2D\u65AD", - "notice.sessionStartFailed": "\u4F1A\u8BDD\u542F\u52A8\u5931\u8D25\uFF1A{detail}", - "notice.sendFailed": "\u53D1\u9001\u5931\u8D25\uFF1A{detail}", - "notice.effortNextTurn": "\u601D\u8003\u5F3A\u5EA6\u5DF2\u4FDD\u5B58\uFF0C\u5C06\u5728\u4E0B\u4E00\u8F6E\u751F\u6548", - "notice.effortResetOnModel": "\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8BE5\u601D\u8003\u5F3A\u5EA6\uFF0C\u5DF2\u6062\u590D\u4E3A Default", - "turn.agentExit": "Agent \u8FDB\u7A0B\u610F\u5916\u9000\u51FA", - "attachment.missing": "\u9644\u4EF6\u4E0D\u5B58\u5728\u6216\u5DF2\u5931\u6548\uFF08{ref}\uFF09\uFF0C\u8BF7\u91CD\u65B0\u4E0A\u4F20", - "notice.acpImageByPath": "{agent} \u4E0D\u80FD\u76F4\u63A5\u770B\u56FE\u7247\uFF08\u5B83\u7684 ACP \u521D\u59CB\u5316\u672A\u58F0\u660E\u652F\u6301\u56FE\u7247\u8F93\u5165\uFF09\uFF0C\u5DF2\u6539\u4E3A\u53D1\u9001\u56FE\u7247\u7684\u6587\u4EF6\u8DEF\u5F84\uFF1A{paths}", - "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}", - "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", - "claude.notRunning": "claude \u6CA1\u6709\u5728\u8FD0\u884C\uFF0C\u6D88\u606F\u672A\u53D1\u51FA", - "claude.closed": "\u4F1A\u8BDD\u5DF2\u5173\u95ED", - "export.defaultModel": "\u9ED8\u8BA4" - }, - en: { - "thread.defaultTitle": "New chat", - "notice.daemonRestart": "Daemon restarted \u2014 this turn was interrupted", - "notice.sessionStartFailed": "Session start failed: {detail}", - "notice.sendFailed": "Send failed: {detail}", - "notice.effortNextTurn": "Reasoning effort saved \u2014 takes effect on the next turn", - "notice.effortResetOnModel": "This model does not support that effort level; reset to Default", - "turn.agentExit": "Agent process exited unexpectedly", - "attachment.missing": "Attachment missing or expired ({ref}) \u2014 upload again", - "notice.acpImageByPath": "{agent} can't see images directly (its ACP initialize doesn't advertise image input); sent the image file path instead: {paths}", - "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}", - "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})", - "claude.notRunning": "claude is not running; the message was not sent", - "claude.closed": "The session is closed", - "export.defaultModel": "Default" - } - }; - } -}); - // daemon/src/util/attachmentRefs.ts var attachmentRefs_exports = {}; __export(attachmentRefs_exports, { @@ -1484,6 +1690,32 @@ var init_content = __esm({ } }); +// daemon/src/providers/launch.ts +function launchFromSettings(settings, providerId) { + const c = settings.providerCommand?.[providerId]; + const cmd = typeof c?.executable === "string" ? c.executable.trim() : ""; + if (!cmd) return void 0; + const args = Array.isArray(c?.args) ? c.args.filter((a) => typeof a === "string") : []; + return { cmd, args }; +} +function launchArgv(builtin, launch) { + return [...launch?.prefixArgs ?? [], ...builtin, ...launch?.args ?? []]; +} +async function resolveLaunch(launch) { + const r = await resolveBin(launch.cmd); + if (r.ok) return r; + return { ok: false, reason: tr("launch.notFound", { cmd: launch.cmd }) }; +} +function launchKey(launch) { + return launch ? `${launch.cmd}\0${(launch.prefixArgs ?? []).join("\0")}\0\0${(launch.args ?? []).join("\0")}` : ""; +} +var init_launch = __esm({ + "daemon/src/providers/launch.ts"() { + init_bin(); + init_i18n(); + } +}); + // daemon/src/providers/claude/cli.ts function claudeArgs(o) { const args = [ @@ -1514,6 +1746,7 @@ function claudeArgs(o) { var SAFE_ARG, ClaudeCli; var init_cli = __esm({ "daemon/src/providers/claude/cli.ts"() { + init_launch(); init_bin(); init_queue(); SAFE_ARG = /^[A-Za-z0-9][A-Za-z0-9._:\[\]\/@+-]{0,199}$/; @@ -1521,7 +1754,7 @@ var init_cli = __esm({ constructor(o, canUseTool) { this.o = o; this.canUseTool = canUseTool; - const args = claudeArgs(o); + const args = launchArgv(claudeArgs(o), o.launch); this.child = spawnBin(o.bin, args, { cwd: o.cwd, env: { ...o.env ?? process.env, NO_COLOR: "1", FORCE_COLOR: "0" }, @@ -1603,10 +1836,10 @@ var init_cli = __esm({ onMessage(m) { if (m.type === "control_response") { const r = m.response ?? {}; - const id = String(r.request_id ?? ""); - const p = this.pending.get(id); + const id2 = String(r.request_id ?? ""); + const p = this.pending.get(id2); if (!p) return; - this.pending.delete(id); + this.pending.delete(id2); if (p.timer) clearTimeout(p.timer); if (r.subtype === "success") p.resolve(r.response ?? {}); else p.reject(new Error(String(r.error ?? "control request failed"))); @@ -1617,21 +1850,21 @@ var init_cli = __esm({ return; } if (m.type === "control_cancel_request") { - const id = String(m.request_id ?? ""); - this.cancels.get(id)?.abort(); - this.cancels.delete(id); + const id2 = String(m.request_id ?? ""); + this.cancels.get(id2)?.abort(); + this.cancels.delete(id2); return; } if (m.type === "keep_alive") return; this.messages.push(m); } - async onControlRequest(id, req) { + async onControlRequest(id2, req) { if (req.subtype !== "can_use_tool") { - this.write({ type: "control_response", response: { subtype: "error", request_id: id, error: `Unsupported control request: ${String(req.subtype)}` } }); + this.write({ type: "control_response", response: { subtype: "error", request_id: id2, error: `Unsupported control request: ${String(req.subtype)}` } }); return; } const ac = new AbortController(); - this.cancels.set(id, ac); + this.cancels.set(id2, ac); try { const decision = await this.canUseTool({ toolName: String(req.tool_name ?? ""), @@ -1639,12 +1872,12 @@ var init_cli = __esm({ toolUseId: typeof req.tool_use_id === "string" ? req.tool_use_id : void 0, signal: ac.signal }); - if (ac.signal.aborted && !this.cancels.has(id)) return; - this.write({ type: "control_response", response: { subtype: "success", request_id: id, response: decision } }); + if (ac.signal.aborted && !this.cancels.has(id2)) return; + this.write({ type: "control_response", response: { subtype: "success", request_id: id2, response: decision } }); } catch (e) { - this.write({ type: "control_response", response: { subtype: "error", request_id: id, error: String(e?.message ?? e) } }); + this.write({ type: "control_response", response: { subtype: "error", request_id: id2, error: String(e?.message ?? e) } }); } finally { - this.cancels.delete(id); + this.cancels.delete(id2); } } write(o) { @@ -1659,15 +1892,15 @@ var init_cli = __esm({ /** Send one control request and wait for its answer */ request(request, timeoutMs = 1e4) { if (this.dead) return Promise.reject(new Error("claude is not running")); - const id = `ac_${++this.seq}_${Math.random().toString(36).slice(2, 8)}`; + const id2 = `ac_${++this.seq}_${Math.random().toString(36).slice(2, 8)}`; return new Promise((resolve2, reject) => { const p = { resolve: resolve2, reject }; p.timer = setTimeout(() => { - if (this.pending.delete(id)) reject(new Error(`claude did not answer ${String(request.subtype)} in ${Math.round(timeoutMs / 1e3)} s`)); + if (this.pending.delete(id2)) reject(new Error(`claude did not answer ${String(request.subtype)} in ${Math.round(timeoutMs / 1e3)} s`)); }, timeoutMs); - this.pending.set(id, p); - if (!this.write({ type: "control_request", request_id: id, request })) { - this.pending.delete(id); + this.pending.set(id2, p); + if (!this.write({ type: "control_request", request_id: id2, request })) { + this.pending.delete(id2); clearTimeout(p.timer); reject(new Error("claude is not running")); } @@ -1683,8 +1916,8 @@ var init_cli = __esm({ setModel(model) { return this.request(model ? { subtype: "set_model", model } : { subtype: "set_model" }); } - setPermissionMode(mode) { - return this.request({ subtype: "set_permission_mode", mode }); + setPermissionMode(mode2) { + return this.request({ subtype: "set_permission_mode", mode: mode2 }); } /** End stdin (the CLI finishes and exits), then end the process tree if it lingers */ async close(graceMs = 2e3) { @@ -1751,7 +1984,8 @@ var init_session = __esm({ permissionMode: MODES.includes(this.o.mode) ? this.o.mode : "default", effort, resume: this.sessionId, - env: this.o.env + env: this.o.env, + launch: this.o.launch }, (req) => this.canUseTool(req) ); @@ -1844,9 +2078,9 @@ var init_session = __esm({ kind: "tool", detail, options: [ - { id: "allow", label: "\u5141\u8BB8", kind: "allow_once" }, - { id: "allow_always", label: "\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8", kind: "allow_always" }, - { id: "deny", label: "\u62D2\u7EDD", kind: "reject_once" } + { id: "allow", label: tr("perm.allow"), kind: "allow_once" }, + { id: "allow_always", label: tr("perm.allowSession"), kind: "allow_always" }, + { id: "deny", label: tr("perm.deny"), kind: "reject_once" } ] }); return new Promise((resolve2) => { @@ -1854,14 +2088,14 @@ var init_session = __esm({ signal.addEventListener("abort", () => { if (this.pending.delete(requestId)) { this.emit({ type: "permission_resolved", requestId, cancelled: true }); - resolve2({ behavior: "deny", message: "\u5DF2\u53D6\u6D88", interrupt: true }); + resolve2({ behavior: "deny", message: "Cancelled by the user", interrupt: true }); } }, { once: true }); }); } toPermissionDecision(a, input) { if (a.cancelled || a.optionId === "deny") { - return { behavior: "deny", message: "\u7528\u6237\u62D2\u7EDD\u4E86\u6B64\u64CD\u4F5C", ...a.cancelled ? { interrupt: true } : {} }; + return { behavior: "deny", message: "The user denied this action", ...a.cancelled ? { interrupt: true } : {} }; } return { behavior: "allow", updatedInput: input }; } @@ -1873,12 +2107,12 @@ var init_session = __esm({ this.emit({ type: "permission_request", requestId, - title: "Agent \u63D0\u4EA4\u4E86\u8BA1\u5212", + title: tr("perm.plan"), kind: "plan", detail: { plan: planText }, options: [ - { id: "implement", label: "\u5B9E\u65BD", kind: "allow_once" }, - { id: "reject", label: "\u62D2\u7EDD", kind: "reject_once" } + { id: "implement", label: tr("perm.implement"), kind: "allow_once" }, + { id: "reject", label: tr("perm.deny"), kind: "reject_once" } ] }); const answer = await new Promise((resolve2) => { @@ -1891,7 +2125,7 @@ var init_session = __esm({ }, { once: true }); }); if (answer.cancelled || answer.optionId === "reject") { - return { behavior: "deny", message: "\u7528\u6237\u62D2\u7EDD\u4E86\u8BA1\u5212\uFF0C\u8BF7\u6839\u636E\u53CD\u9988\u4FEE\u6539", ...answer.cancelled ? { interrupt: true } : {} }; + return { behavior: "deny", message: "The user rejected the plan; revise it based on their feedback", ...answer.cancelled ? { interrupt: true } : {} }; } try { await this.cli?.setPermissionMode("default"); @@ -1914,7 +2148,7 @@ var init_session = __esm({ }, { once: true }); }); if (answer.cancelled) { - return { behavior: "deny", message: "\u7528\u6237\u53D6\u6D88\u4E86\u63D0\u95EE", interrupt: true }; + return { behavior: "deny", message: "The user cancelled the question", interrupt: true }; } const questions = input.questions ?? []; const normalized = {}; @@ -1935,8 +2169,8 @@ var init_session = __esm({ } async interrupt() { this.st.sawInterrupt = true; - for (const [id, p] of this.pending) { - this.emit({ type: "permission_resolved", requestId: id, cancelled: true }); + for (const [id2, p] of this.pending) { + this.emit({ type: "permission_resolved", requestId: id2, cancelled: true }); p.resolve({ cancelled: true }); } this.pending.clear(); @@ -1962,15 +2196,15 @@ var init_session = __esm({ this.needsRestart = true; } } - async setMode(mode) { - this.o.mode = mode; + async setMode(mode2) { + this.o.mode = mode2; if (!this.cli?.alive) return; - if (mode === "bypassPermissions" && this.launchedMode !== "bypassPermissions") { + if (mode2 === "bypassPermissions" && this.launchedMode !== "bypassPermissions") { this.needsRestart = true; return; } try { - await this.cli.setPermissionMode(mode); + await this.cli.setPermissionMode(mode2); } catch (e) { log("warn", "claude set_permission_mode failed", { err: String(e) }); this.needsRestart = true; @@ -2085,7 +2319,7 @@ async function listClaudeHistory(cwd) { const s = await stat4(path3).catch(() => null); out.push({ sessionId: f.replace(/\.jsonl$/, ""), - title: title || "\uFF08\u65E0\u6807\u9898\uFF09", + title: title || tr("history.untitled"), updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count }); @@ -2123,6 +2357,7 @@ var CLAUDE_ROOT, rec2, str2; var init_import = __esm({ "daemon/src/history/import.ts"() { init_paths(); + init_i18n(); CLAUDE_ROOT = join6(homedir3(), ".claude", "projects"); rec2 = (v) => v && typeof v === "object" ? v : {}; str2 = (v) => typeof v === "string" ? v : void 0; @@ -2151,16 +2386,18 @@ function runVersion(r, args, timeoutMs = 5e3) { }); }); } -function createClaudeProvider() { +function createClaudeProvider(opts = {}) { + const resolve2 = opts.resolve ?? resolveBin; + const resolveCustom = opts.resolve ? (l) => opts.resolve(l.cmd) : resolveLaunch; return { id: "claude", name: "Claude Code", capabilities: claudeCapabilities, - async detect() { - const bin = await resolveBin("claude"); + async detect(launch) { + const bin = launch ? await resolveCustom(launch) : await resolve2("claude"); if (!bin.ok) return { available: false, reason: bin.reason, installHint: INSTALL_HINT }; try { - const version = await runVersion(bin, ["--version"]); + const version = await runVersion(bin, [...launch?.prefixArgs ?? [], "--version"]); return { available: true, bin: bin.display, version: version.trim().split("\n")[0] || "" }; } catch { return { available: true, bin: bin.display, version: "" }; @@ -2170,7 +2407,7 @@ function createClaudeProvider() { return listClaudeModels(); }, async createSession(o) { - const bin = await resolveBin("claude"); + const bin = o.launch ? await resolveCustom(o.launch) : await resolve2("claude"); if (!bin.ok) throw new Error(tr("claude.notFound", { detail: bin.reason, hint: INSTALL_HINT })); return new ClaudeSession({ threadId: o.threadId, @@ -2179,7 +2416,8 @@ function createClaudeProvider() { mode: o.mode, effort: o.effort, resumeId: o.resumeId, - bin + bin, + launch: o.launch }); }, // §7.6: jsonl sessions under ~/.claude/projects matched by cwd @@ -2216,6 +2454,7 @@ var init_provider = __esm({ init_import(); init_map(); init_i18n(); + init_launch(); INSTALL_HINT = "npm i -g @anthropic-ai/claude-code"; claudeCapabilities = { resume: true, @@ -2288,7 +2527,7 @@ async function listCodexHistory(cwd) { } if (!match) continue; const s = await stat5(path3).catch(() => null); - out.push({ sessionId, title: title || "\uFF08\u65E0\u6807\u9898\uFF09", updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count }); + out.push({ sessionId, title: title || tr("history.untitled"), updatedAt: s ? Math.round(s.mtimeMs) : 0, messageCount: count }); } out.sort((a, b) => b.updatedAt - a.updatedAt); return out; @@ -2341,7 +2580,7 @@ async function readCodexHistory(sessionId, cwd) { } } else if (p.type === "function_call" || p.type === "custom_tool_call") { const name = str3(p.name) ?? "tool"; - out.push({ type: "notice", level: "info", message: `\uFF08\u5386\u53F2\uFF09\u8C03\u7528 ${name}` }); + out.push({ type: "notice", level: "info", message: tr("history.toolCall", { name }) }); } continue; } @@ -2365,7 +2604,7 @@ async function readCodexHistory(sessionId, cwd) { const p2 = rec3(r.payload); if (p2.type === "function_call" || p2.type === "custom_tool_call") { const name = str3(p2.name) ?? "tool"; - out.push({ type: "notice", level: "info", message: `\uFF08\u5386\u53F2\uFF09\u8C03\u7528 ${name}` }); + out.push({ type: "notice", level: "info", message: tr("history.toolCall", { name }) }); } } out.push({ type: "turn_ended", turnId: "import", status: "completed" }); @@ -2375,6 +2614,7 @@ var CODEX_ROOT, rec3, str3, WRAPPERS; var init_codex = __esm({ "daemon/src/history/codex.ts"() { init_paths(); + init_i18n(); CODEX_ROOT = join7(homedir4(), ".codex", "sessions"); rec3 = (v) => v && typeof v === "object" ? v : {}; str3 = (v) => typeof v === "string" ? v : void 0; @@ -2461,10 +2701,10 @@ var init_rpc = __esm({ async dispatch(msg) { const hasId = msg.id !== void 0 && msg.id !== null; if (hasId && ("result" in msg || "error" in msg)) { - const id = Number(msg.id); - const p = this.pending.get(id); + const id2 = Number(msg.id); + const p = this.pending.get(id2); if (p) { - this.pending.delete(id); + this.pending.delete(id2); if (msg.error) { const e = msg.error; p.reject(new CodexRpcError(e.message ?? "RPC error", e.code)); @@ -2475,12 +2715,12 @@ var init_rpc = __esm({ return; } if (hasId && msg.method) { - const id = Number(msg.id); + const id2 = Number(msg.id); try { const result = this.onServerRequest ? await this.onServerRequest(String(msg.method), msg.params ?? {}) : void 0; - this.send({ id, result: result ?? null }); + this.send({ id: id2, result: result ?? null }); } catch (e) { - this.send({ id, error: { code: -32603, message: String(e?.message ?? e) } }); + this.send({ id: id2, error: { code: -32603, message: String(e?.message ?? e) } }); } return; } @@ -2501,13 +2741,13 @@ var init_rpc = __esm({ } request(method, params, timeoutMs = 6e4) { if (this.exited) return Promise.reject(new CodexProcessExitedError()); - const id = this.nextId++; + const id2 = this.nextId++; return new Promise((resolvePromise, reject) => { const timer = setTimeout(() => { - this.pending.delete(id); + this.pending.delete(id2); reject(new CodexRpcError(`\u8BF7\u6C42\u8D85\u65F6\uFF1A${method}`)); }, timeoutMs); - this.pending.set(id, { + this.pending.set(id2, { resolve: (v) => { clearTimeout(timer); resolvePromise(v); @@ -2517,7 +2757,7 @@ var init_rpc = __esm({ reject(e); } }); - this.send({ jsonrpc: "2.0", id, method, params: params ?? {} }); + this.send({ jsonrpc: "2.0", id: id2, method, params: params ?? {} }); }); } notify(method, params) { @@ -2586,7 +2826,7 @@ var init_input = __esm({ // daemon/src/providers/codex/map.ts function newCodexMapState() { - return { currentTurnId: null, filesChanged: 0, diffText: "" }; + return { currentTurnId: null, filesChanged: 0, diffText: "", fileChangesByItemId: /* @__PURE__ */ new Map(), reasoningRaw: /* @__PURE__ */ new Map() }; } function mapNotification(method, params, st) { const out = []; @@ -2598,6 +2838,8 @@ function mapNotification(method, params, st) { if (tid) st.currentTurnId = tid; st.filesChanged = 0; st.diffText = ""; + st.fileChangesByItemId.clear(); + st.reasoningRaw.clear(); break; } case "item/agentMessage/delta": { @@ -2613,7 +2855,10 @@ function mapNotification(method, params, st) { case "item/reasoning/textDelta": { const itemId = str4(params.itemId) ?? ""; const delta = str4(params.delta) ?? ""; - if (itemId && delta) out.push({ type: "reasoning_delta", itemId, text: delta }); + if (itemId && delta) { + if (method === "item/reasoning/textDelta") st.reasoningRaw.set(itemId, (st.reasoningRaw.get(itemId) ?? "") + delta); + out.push({ type: "reasoning_delta", itemId, text: delta }); + } break; } case "item/commandExecution/outputDelta": @@ -2634,17 +2879,18 @@ function mapNotification(method, params, st) { type: "tool_call", itemId, kind: "bash", - title: `\u8FD0\u884C ${trunc2(cmd)}`, + title: tr("tool.run", { x: trunc2(cmd) }), status: "running", detail: { command: cmd, cwd: str4(item.cwd) } }); } else if (type === "fileChange") { const changes = Array.isArray(item.changes) ? item.changes : []; + if (itemId) st.fileChangesByItemId.set(itemId, changes); out.push({ type: "tool_call", itemId, kind: "edit", - title: `\u4FEE\u6539 ${changes.length} \u4E2A\u6587\u4EF6`, + title: tr("tool.editFiles", { n: changes.length }), status: "running", detail: { changes } }); @@ -2663,7 +2909,7 @@ function mapNotification(method, params, st) { type: "tool_call", itemId, kind: "web", - title: `\u641C\u7D22\u7F51\u9875 "${trunc2(str4(item.query) ?? "", 40)}"`, + title: tr("tool.webSearch", { x: trunc2(str4(item.query) ?? "", 40) }), status: "running" }); } @@ -2678,7 +2924,10 @@ function mapNotification(method, params, st) { if (text) out.push({ type: "assistant_message", itemId, text }); } else if (type === "reasoning") { const summary = Array.isArray(item.summary) ? item.summary : []; - const text = summary.filter((s) => typeof s === "string").join("\n"); + const content = Array.isArray(item.content) ? item.content : []; + const strings = (a) => a.filter((s) => typeof s === "string").join("\n"); + const text = strings(summary) || strings(content) || st.reasoningRaw.get(itemId) || ""; + st.reasoningRaw.delete(itemId); if (text) out.push({ type: "reasoning", itemId, text }); } else if (type === "commandExecution") { const cmd = str4(item.command) ?? ""; @@ -2688,7 +2937,7 @@ function mapNotification(method, params, st) { type: "tool_call", itemId, kind: "bash", - title: `\u8FD0\u884C ${trunc2(cmd)}`, + title: tr("tool.run", { x: trunc2(cmd) }), status: exitCode === 0 ? "ok" : "failed", output: output.length > MAX_OUTPUT2 ? output.slice(0, MAX_OUTPUT2) : output, exitCode, @@ -2696,13 +2945,14 @@ function mapNotification(method, params, st) { }); } else if (type === "fileChange") { const changes = Array.isArray(item.changes) ? item.changes : []; + if (itemId) st.fileChangesByItemId.set(itemId, changes); const istatus = str4(item.status); st.filesChanged += changes.length; out.push({ type: "tool_call", itemId, kind: "edit", - title: `\u4FEE\u6539 ${changes.length} \u4E2A\u6587\u4EF6`, + title: tr("tool.editFiles", { n: changes.length }), status: istatus === "failed" ? "failed" : "ok", detail: { changes } }); @@ -2724,7 +2974,7 @@ function mapNotification(method, params, st) { type: "tool_call", itemId, kind: "web", - title: `\u641C\u7D22\u7F51\u9875 "${trunc2(str4(item.query) ?? "", 40)}"`, + title: tr("tool.webSearch", { x: trunc2(str4(item.query) ?? "", 40) }), status: "ok" }); } else if (type === "plan") { @@ -2781,7 +3031,7 @@ function mapNotification(method, params, st) { break; } case "error": { - const msg = str4(params.message) ?? "Codex \u9519\u8BEF"; + const msg = str4(params.message) ?? tr("codex.error"); out.push({ type: "notice", level: "error", message: msg }); break; } @@ -2793,6 +3043,7 @@ function mapNotification(method, params, st) { var MAX_OUTPUT2, trunc2, rec4, str4; var init_map2 = __esm({ "daemon/src/providers/codex/map.ts"() { + init_i18n(); MAX_OUTPUT2 = 20 * 1024; trunc2 = (s, n = 80) => s.length > n ? s.slice(0, n - 1) + "\u2026" : s; rec4 = (v) => v && typeof v === "object" ? v : {}; @@ -2924,6 +3175,7 @@ var init_session2 = __esm({ init_map2(); init_commands(); init_log(); + init_launch(); rid3 = () => Math.random().toString(36).slice(2, 10); MODE_PRESETS = { plan: { approvalPolicy: "on-request", sandbox: "read-only", sandboxPolicy: { type: "readOnly" } }, @@ -2967,7 +3219,7 @@ var init_session2 = __esm({ const rpc = new CodexRpc( argvFor( { ok: true, cmd: this.o.binCmd, prefixArgs: this.o.binPrefixArgs, display: this.o.binCmd, via: this.o.binVia ?? "path", shim: this.o.binShim }, - ["app-server"] + launchArgv(["app-server"], this.o.launch) ), { cwd: this.o.cwd } ); @@ -3013,7 +3265,7 @@ var init_session2 = __esm({ } })(); this.started = attempt.catch((e) => { - if (this.started === guarded) { + if (this.started === guarded2) { this.started = null; const rpc = this.rpc; this.rpc = null; @@ -3026,11 +3278,11 @@ var init_session2 = __esm({ } throw e; }); - const guarded = this.started; + const guarded2 = this.started; return this.started; } async send(input) { - if (this.closed) throw new Error("\u4F1A\u8BDD\u5DF2\u5173\u95ED"); + if (this.closed) throw new Error(tr("codex.closed")); await this.start(); const rpc = this.rpc; const preset = MODE_PRESETS[this.o.mode]; @@ -3070,7 +3322,7 @@ var init_session2 = __esm({ } } async steer(input) { - if (!this.rpc || !this.st.currentTurnId) throw new Error("\u5F53\u524D\u8F6E\u6B21\u8FD8\u6CA1\u5F00\u59CB\uFF0C\u65E0\u6CD5\u63D2\u8BDD"); + if (!this.rpc || !this.st.currentTurnId) throw new Error(tr("codex.noTurnSteer")); const { items, warnings } = await buildCodexInput(input.text, input.images ?? []); for (const w of warnings) this.emit({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) }); try { @@ -3117,13 +3369,13 @@ var init_session2 = __esm({ this.emit({ type: "permission_request", requestId, - title: `\u8FD0\u884C ${command.slice(0, 80)}`, + title: tr("tool.run", { x: command.slice(0, 80) }), kind: "tool", detail: { command, cwd: params.cwd, reason: params.reason, approvalId: params.approvalId, itemId: params.itemId }, options: [ - { id: "accept", label: "\u5141\u8BB8", kind: "allow_once" }, - { id: "acceptForSession", label: "\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8", kind: "allow_always" }, - { id: "decline", label: "\u62D2\u7EDD", kind: "reject_once" } + { id: "accept", label: tr("perm.allow"), kind: "allow_once" }, + { id: "acceptForSession", label: tr("perm.allowSession"), kind: "allow_always" }, + { id: "decline", label: tr("perm.deny"), kind: "reject_once" } ] }); const a = await this.waitFor(requestId); @@ -3132,18 +3384,19 @@ var init_session2 = __esm({ return { decision: opt }; } case "item/fileChange/requestApproval": { - const changes = Array.isArray(params.changes) ? params.changes : []; + const itemId = typeof params.itemId === "string" ? params.itemId : ""; + const changes = Array.isArray(params.changes) && params.changes.length ? params.changes : itemId ? this.st.fileChangesByItemId.get(itemId) ?? [] : []; const requestId = "perm_" + rid3(); this.emit({ type: "permission_request", requestId, - title: "\u4FEE\u6539\u6587\u4EF6", + title: tr("perm.editFiles"), kind: "tool", detail: { changes, approvalId: params.approvalId, itemId: params.itemId, reason: params.reason }, options: [ - { id: "accept", label: "\u5141\u8BB8", kind: "allow_once" }, - { id: "acceptForSession", label: "\u672C\u5BF9\u8BDD\u90FD\u5141\u8BB8", kind: "allow_always" }, - { id: "decline", label: "\u62D2\u7EDD", kind: "reject_once" } + { id: "accept", label: tr("perm.allow"), kind: "allow_once" }, + { id: "acceptForSession", label: tr("perm.allowSession"), kind: "allow_always" }, + { id: "decline", label: tr("perm.deny"), kind: "reject_once" } ] }); const a = await this.waitFor(requestId); @@ -3184,8 +3437,8 @@ var init_session2 = __esm({ async setModel(model) { this.o.model = model; } - async setMode(mode) { - this.o.mode = mode; + async setMode(mode2) { + this.o.mode = mode2; } async setEffort(effort) { this.o.effort = effort; @@ -3210,7 +3463,18 @@ var init_session2 = __esm({ } }); +// daemon/src/providers/types.ts +var PLACEHOLDER_MODEL_NAME; +var init_types = __esm({ + "daemon/src/providers/types.ts"() { + PLACEHOLDER_MODEL_NAME = "Default"; + } +}); + // daemon/src/providers/codex/provider.ts +import { homedir as homedir6 } from "node:os"; +import { join as join9 } from "node:path"; +import { readFile as readFile8 } from "node:fs/promises"; function runVersion2(r, args, timeoutMs = 5e3) { return new Promise((resolvePromise, reject) => { let out = ""; @@ -3240,8 +3504,8 @@ function normalizeEfforts(raw) { } return out; } -async function fetchModels(r, cwd) { - const rpc = new CodexRpc(argvFor(r, ["app-server"]), { cwd }); +async function fetchModels(r, cwd, launch) { + const rpc = new CodexRpc(argvFor(r, launchArgv(["app-server"], launch)), { cwd }); try { await rpc.request("initialize", { clientInfo: { name: "agent-console", title: "Agent Console", version: "0" }, @@ -3267,39 +3531,97 @@ async function fetchModels(r, cwd) { await rpc.close(); } } +function tomlValue(raw) { + const v = raw.trim().replace(/\s+#.*$/, ""); + const quoted = v.match(/^"([\s\S]*)"$/) ?? v.match(/^'([\s\S]*)'$/); + if (quoted) return quoted[1]; + if (v.startsWith("[") && v.endsWith("]")) { + return v.slice(1, -1).split(",").map((x) => tomlValue(x)).filter((x) => typeof x === "string"); + } + return null; +} +function parseCodexConfig(text) { + let section = ""; + const values = /* @__PURE__ */ new Map(); + for (const line of text.split(/\r?\n/)) { + const s = line.trim(); + if (!s || s.startsWith("#")) continue; + const header = s.match(/^\[([^\]]+)\]$/); + if (header) { + section = header[1]; + continue; + } + const m = s.match(/^([A-Za-z0-9_.-]+)\s*=\s*(.+)$/); + if (!m) continue; + const value = tomlValue(m[2]); + if (typeof value === "string" || Array.isArray(value)) values.set(`${section}\0${m[1]}`, value); + } + const top = (key) => values.get(`\0${key}`); + const profile = top("profile"); + const profileName = typeof profile === "string" ? profile : null; + const profileValue = (key) => profileName ? values.get(`profiles.${profileName}\0${key}`) : void 0; + const modelProvider = profileValue("model_provider") ?? top("model_provider"); + const model = profileValue("model") ?? top("model"); + const provider = typeof modelProvider === "string" ? modelProvider : null; + const models2 = /* @__PURE__ */ new Set(); + if (typeof model === "string" && model) models2.add(model); + for (const [key, value] of values) { + if (provider && key === `model_providers.${provider}\0models` && Array.isArray(value)) { + for (const m of value) models2.add(m); + } + } + return { modelProvider: provider, model: typeof model === "string" ? model : null, providerModels: [...models2] }; +} +async function readCodexConfig() { + const home = process.env.CODEX_HOME?.trim() || join9(homedir6(), ".codex"); + const file = home.toLowerCase().endsWith(".toml") ? home : join9(home, "config.toml"); + try { + return parseCodexConfig(await readFile8(file, "utf8")); + } catch { + return { modelProvider: null, model: null, providerModels: [] }; + } +} +function isChatGptProvider(id2) { + return !id2 || /^(openai|chatgpt)$/i.test(id2); +} function createCodexProvider(version) { return { id: "codex", name: "Codex", capabilities: codexCapabilities, - async detect() { - const bin = await resolveBin("codex"); + async detect(launch) { + const bin = launch ? await resolveLaunch(launch) : await resolveBin("codex"); if (!bin.ok) { return { available: false, reason: bin.reason, installHint: INSTALL_HINT2 }; } try { - const v = await runVersion2(bin, ["--version"]); + const v = await runVersion2(bin, [...launch?.prefixArgs ?? [], "--version"]); return { available: true, bin: bin.display, version: v.trim().split("\n")[0] || "" }; } catch (e) { return { available: true, bin: bin.display, version: "", reason: String(e) }; } }, - async listModels() { - if (modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models; - const bin = await resolveBin("codex"); - if (!bin.ok) return [{ id: "", name: "\u9ED8\u8BA4" }]; + async listModels(launch) { + const config = await readCodexConfig(); + if (!isChatGptProvider(config.modelProvider)) { + const rows = config.providerModels.map((id2, i) => ({ id: id2, name: id2, isDefault: i === 0 })); + return rows.length ? rows : [{ id: "", name: `${PLACEHOLDER_MODEL_NAME} (${config.modelProvider})`, isDefault: true }]; + } + if (!launch && modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models; + const bin = launch ? await resolveLaunch(launch) : await resolveBin("codex"); + if (!bin.ok) return [{ id: "", name: PLACEHOLDER_MODEL_NAME }]; try { - const models2 = await fetchModels(bin, process.cwd()); + const models2 = await fetchModels(bin, process.cwd(), launch); modelCache = { at: Date.now(), models: models2 }; return models2; } catch (e) { log("warn", "codex model/list \u5931\u8D25", { err: String(e) }); - return [{ id: "", name: "\u9ED8\u8BA4" }]; + return [{ id: "", name: PLACEHOLDER_MODEL_NAME }]; } }, async createSession(o) { - const bin = await resolveBin("codex"); - if (!bin.ok) throw new Error(`\u627E\u4E0D\u5230 codex\uFF1A${bin.reason}`); + const bin = o.launch ? await resolveLaunch(o.launch) : await resolveBin("codex"); + if (!bin.ok) throw new Error(tr("codex.notFound", { detail: bin.reason, hint: INSTALL_HINT2 })); return new CodexSession({ threadId: o.threadId, cwd: o.cwd, @@ -3311,6 +3633,7 @@ function createCodexProvider(version) { binPrefixArgs: bin.prefixArgs, binVia: bin.via, binShim: bin.shim, + launch: o.launch, version }); }, @@ -3332,6 +3655,9 @@ var init_provider2 = __esm({ init_rpc(); init_session2(); init_log(); + init_i18n(); + init_launch(); + init_types(); INSTALL_HINT2 = "npm i -g @openai/codex"; codexCapabilities = { resume: true, @@ -3344,7 +3670,9 @@ var init_provider2 = __esm({ // tokenUsage yes, cost no effort: [], // effort values depend on the model — filled from model/list after detect - modes: ["plan", "default", "acceptEdits", "bypassPermissions"] + // 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) + modes: ["default", "acceptEdits", "bypassPermissions"], + modeLabels: { default: "Read Only", acceptEdits: "Auto", bypassPermissions: "Full Access" } }; modelCache = null; MODEL_CACHE_MS = 10 * 60 * 1e3; @@ -3352,8 +3680,8 @@ var init_provider2 = __esm({ }); // daemon/src/providers/catalog.ts -function catalogById(id) { - return PROVIDER_CATALOG.find((p) => p.id === id); +function catalogById(id2) { + return PROVIDER_CATALOG.find((p) => p.id === id2); } function providerCreatable(status) { return status !== "planned"; @@ -3363,12 +3691,12 @@ var init_catalog = __esm({ "daemon/src/providers/catalog.ts"() { PROVIDER_CATALOG = [ { id: "claude", name: "Claude Code", bins: ["claude"], installHint: "npm i -g @anthropic-ai/claude-code", status: "verified" }, - { id: "codex", name: "Codex", bins: ["codex"], installHint: "\u89C1 OpenAI Codex CLI \u5B89\u88C5\u8BF4\u660E", status: "verified" }, - { id: "cursor", name: "Cursor", bins: ["cursor-agent", "cursor"], installHint: "\u5B89\u88C5 Cursor \u5E76\u786E\u4FDD CLI \u5728 PATH", status: "verified" }, - { id: "copilot", name: "Copilot", bins: ["copilot"], installHint: "GitHub Copilot CLI \u5B89\u88C5\u8BF4\u660E", status: "verified" }, - { id: "opencode", name: "OpenCode", bins: ["opencode"], installHint: "npm i -g opencode / \u89C1 OpenCode \u6587\u6863", status: "verified" }, - { id: "pi", name: "Pi", bins: ["pi-acp", "pi", "pi-coding-agent"], installHint: "npm i -g pi-acp\uFF08\u6216 Pi coding agent + ACP \u9002\u914D\u5668\uFF09", status: "verified" }, - { id: "devin", name: "Devin CLI", bins: ["devin"], installHint: "Devin CLI \u5B98\u65B9\u5B89\u88C5", status: "verified" }, + { id: "codex", name: "Codex", bins: ["codex"], installHint: "npm i -g @openai/codex", status: "verified" }, + { id: "cursor", name: "Cursor", bins: ["cursor-agent", "cursor"], installHint: "curl https://cursor.com/install -fsS | bash", status: "verified" }, + { id: "copilot", name: "Copilot", bins: ["copilot"], installHint: "npm i -g @github/copilot", status: "verified" }, + { id: "opencode", name: "OpenCode", bins: ["opencode"], installHint: "npm i -g opencode-ai", status: "verified" }, + { id: "pi", name: "Pi", bins: ["pi-acp", "pi", "pi-coding-agent"], installHint: "npm i -g pi-acp", status: "verified" }, + { id: "devin", name: "Devin CLI", bins: ["devin"], installHint: "https://docs.devin.ai/cli", status: "verified" }, { id: "dsh", name: "dsh", bins: ["dsh"], installHint: "npm i -g @deepseek-ai/dsh", status: "verified" } ]; } @@ -3405,11 +3733,11 @@ var init_spawn = __esm({ }); // daemon/src/providers/acp/clientHandlers.ts -import { readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises"; +import { readFile as readFile9, writeFile as writeFile2 } from "node:fs/promises"; import { methods } from "@agentclientprotocol/sdk"; function registerAcpClientHandlers(app, bridge) { app.onRequest(methods.client.fs.readTextFile, async (ctx) => { - const text = await readFile8(ctx.params.path, "utf8"); + const text = await readFile9(ctx.params.path, "utf8"); return { content: text }; }); app.onRequest(methods.client.fs.writeTextFile, async (ctx) => { @@ -3431,7 +3759,7 @@ function registerAcpClientHandlers(app, bridge) { bridge.push({ type: "permission_request", requestId, - title: tc.title ?? tc.name ?? "\u9700\u8981\u6388\u6743", + title: tc.title ?? tc.name ?? tr("tool.needsApproval"), kind: tc.kind ?? "tool", detail: tc.rawInput ?? void 0, options @@ -3445,6 +3773,7 @@ function registerAcpClientHandlers(app, bridge) { } var init_clientHandlers = __esm({ "daemon/src/providers/acp/clientHandlers.ts"() { + init_i18n(); } }); @@ -3473,7 +3802,13 @@ function textFromContent(content) { return ""; } function newMapCtx() { - return { itemPrefix: "a" + rid4() + "_", messageIds: /* @__PURE__ */ new Map() }; + return { itemPrefix: "a" + rid4() + "_", messageIds: /* @__PURE__ */ new Map(), seg: 0, lastWasText: false }; +} +function endTextSegment(ctx) { + if (ctx.lastWasText) { + ctx.seg++; + ctx.lastWasText = false; + } } function mapSessionUpdate(update, ctx) { const out = []; @@ -3482,19 +3817,22 @@ function mapSessionUpdate(update, ctx) { case "agent_message_chunk": { const text = textFromContent(update.content); if (!text) break; - const itemId = mid ? ctx.messageIds.get(mid) ?? ctx.itemPrefix + mid : ctx.itemPrefix + "msg"; + const itemId = `${ctx.itemPrefix}${mid ?? "msg"}_${ctx.seg}`; if (mid) ctx.messageIds.set(mid, itemId); + ctx.lastWasText = true; out.push({ type: "assistant_delta", itemId, text }); break; } case "agent_thought_chunk": { const text = textFromContent(update.content); if (!text) break; - const itemId = mid ? ctx.itemPrefix + "t_" + mid : ctx.itemPrefix + "think"; + const itemId = `${ctx.itemPrefix}t_${mid ?? "think"}_${ctx.seg}`; + ctx.lastWasText = true; out.push({ type: "reasoning_delta", itemId, text }); break; } case "tool_call": + endTextSegment(ctx); out.push({ type: "tool_call", itemId: ctx.itemPrefix + update.toolCallId, @@ -3505,17 +3843,19 @@ function mapSessionUpdate(update, ctx) { }); break; case "tool_call_update": + endTextSegment(ctx); out.push({ type: "tool_call", itemId: ctx.itemPrefix + update.toolCallId, kind: mapToolKind(update.kind), - title: update.title ?? update.name ?? "tool", + title: update.title ?? update.name ?? "", status: mapToolStatus(update.status), input: update.rawInput, output: typeof update.rawOutput === "string" ? update.rawOutput : void 0 }); break; case "plan": + endTextSegment(ctx); out.push({ type: "plan", itemId: ctx.itemPrefix + "plan", @@ -3600,7 +3940,7 @@ var init_sessionCaps = __esm({ }); // daemon/src/providers/acp/prompt.ts -import { readFile as readFile9, stat as stat7 } from "node:fs/promises"; +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) { @@ -3636,7 +3976,7 @@ async function buildAcpPrompt(text, attachments, caps) { continue; } try { - const data = (await readFile9(file)).toString("base64"); + const data = (await readFile10(file)).toString("base64"); media.push(image ? { type: "image", data, mimeType: mime } : { type: "audio", data, mimeType: mime }); inlineBytes += size; } catch (e) { @@ -3653,7 +3993,7 @@ async function buildAcpPrompt(text, attachments, caps) { } if (isText(mime) && caps.embeddedContext && size <= MAX_EMBED_TEXT_BYTES && inlineBytes + size <= MAX_INLINE_TOTAL_BYTES) { try { - const body = await readFile9(file, "utf8"); + const body = await readFile10(file, "utf8"); media.push({ type: "resource", resource: { uri: pathToFileURL(file).href, mimeType: mime, text: body } }); inlineBytes += size; continue; @@ -3688,6 +4028,7 @@ var init_session3 = __esm({ init_slash(); init_queue(); init_bin(); + init_launch(); init_spawn(); init_clientHandlers(); init_mapUpdate(); @@ -3737,17 +4078,10 @@ var init_session3 = __esm({ commandsReady; settleCommands; async boot() { - const bin = this.o.launch ? { - ok: true, - cmd: this.o.launch.cmd, - prefixArgs: this.o.launch.prefixArgs, - display: this.o.launch.cmd, - via: "custom", - binName: "custom" - } : await resolveFirstBin(this.o.binCandidates?.length ? this.o.binCandidates : [this.o.binName]); + const bin = this.o.launch ? await resolveLaunch(this.o.launch).then((r) => r.ok ? { ...r, binName: "custom" } : r) : await resolveFirstBin(this.o.binCandidates?.length ? this.o.binCandidates : [this.o.binName]); if (!bin.ok) throw new Error(bin.reason); try { - this.child = spawnResolved(bin, this.o.acpArgs, { cwd: this.o.cwd }); + this.child = spawnResolved(bin, launchArgv(this.o.acpArgs, this.o.launch), { cwd: this.o.cwd }); this.child.stderr?.on("data", (d) => { const t = d.toString().trim(); if (t) log("info", `[${this.o.binName} acp] ${t.slice(0, 500)}`); @@ -3755,13 +4089,13 @@ var init_session3 = __esm({ this.child.on("error", (e) => this.failInit(e)); this.child.on("close", (code) => { if (!this.closed && code !== 0) { - this.q.push({ type: "notice", level: "error", message: `${this.o.binName} \u8FDB\u7A0B\u9000\u51FA (${code})` }); + this.q.push({ type: "notice", level: "error", message: tr("acp.exited", { name: this.o.binName, code: String(code) }) }); } }); const app = client({ name: "magpie-agent-console" }); registerAcpClientHandlers(app, { push: (ev) => this.q.push(ev), - waitFor: (id) => this.waitPerm(id), + waitFor: (id2) => this.waitPerm(id2), autoAcceptPermissions: () => this.cursorAutoReview }); const stream = acpStreamFromChild(this.child); @@ -3886,9 +4220,9 @@ var init_session3 = __esm({ } return (this.active?.modes?.availableModes ?? []).map((m) => ({ id: m.id, name: m.name, configId: null })); } - resolveAcpModeId(mode) { + resolveAcpModeId(mode2) { if (this.o.modeMap) { - const want = this.o.modeMap[mode]; + const want = this.o.modeMap[mode2]; if (!want) return null; const hit = this.modeChoices().find( (m) => m.id === want || m.id.endsWith(`#${want}`) || m.name.toLowerCase() === want @@ -3897,24 +4231,24 @@ var init_session3 = __esm({ } if (this.o.flavor === "cursor") { const map = { default: "agent", plan: "plan", ask: "ask" }; - const want = map[mode] ?? "agent"; + const want = map[mode2] ?? "agent"; const avail = this.active?.modes?.availableModes ?? []; const hit = avail.find((m) => m.id === want || m.name.toLowerCase() === want); return hit?.id ?? want; } - return mode === "plan" ? "plan" : "default"; + return mode2 === "plan" ? "plan" : "default"; } - async applySessionMode(mode) { + async applySessionMode(mode2) { if (!this.ctx || !this.active) return; const hasAllowAll = this.currentConfig().some((o) => o.id === "allow_all"); - if (this.o.modeMap?.[mode] === "allow-all") { + if (this.o.modeMap?.[mode2] === "allow-all") { const agentId = this.modeChoices().find((m) => m.id === "agent" || m.id.endsWith("#agent")); if (agentId?.configId) await this.setOption(agentId.configId, agentId.id); if (hasAllowAll) await this.setOption("allow_all", "on"); return; } if (hasAllowAll && this.o.modeMap) await this.setOption("allow_all", "off"); - const modeId = this.resolveAcpModeId(mode); + const modeId = this.resolveAcpModeId(mode2); if (!modeId) return; try { const viaConfig = this.modeChoices().find((m) => m.id === modeId)?.configId; @@ -3927,7 +4261,7 @@ var init_session3 = __esm({ modeId }); } catch (e) { - log("info", `ACP setMode(${mode}): ${String(e)}`); + log("info", `ACP setMode(${mode2}): ${String(e)}`); } } /** @@ -4091,10 +4425,10 @@ var init_session3 = __esm({ } await this.applySessionModel(model); } - async setMode(mode) { - this.o.mode = mode; + async setMode(mode2) { + this.o.mode = mode2; await this.ready(); - await this.applySessionMode(mode); + await this.applySessionMode(mode2); } async setEffort(effort) { this.o.effort = effort; @@ -4172,29 +4506,27 @@ function createAcpProvider(cfg2) { const learned2 = knownPromptCaps(cfg2.id); return learned2 ? { ...caps, images: learned2.image, imagesKnown: true } : { ...caps, images: false, imagesKnown: false }; }, - async detect() { - const r = await resolveProviderBin(cfg2); + async detect(launch) { + const r = launch ? await resolveLaunch(launch) : await resolveProviderBin(cfg2); if (!r.ok) { return { available: false, reason: r.reason, installHint: cfg2.installHint }; } let version; + const versionArgs = cfg2.id === "devin" ? ["version"] : ["cursor", "opencode"].includes(cfg2.id) ? ["--version"] : null; try { - if (cfg2.id === "cursor") { - version = (await runVersion3(r, ["--version"])).split(/\r?\n/)[0]?.trim(); - } else if (cfg2.id === "devin") { - version = (await runVersion3(r, ["version"])).split(/\r?\n/)[0]?.trim(); - } else if (cfg2.id === "opencode") { - version = (await runVersion3(r, ["--version"])).split(/\r?\n/)[0]?.trim(); + if (versionArgs) { + version = (await runVersion3(r, [...launch?.prefixArgs ?? [], ...versionArgs])).split(/\r?\n/)[0]?.trim(); } } catch { } return { available: true, bin: r.display, version }; }, - async listModels() { - const r = await resolveProviderBin(cfg2); - if (!r.ok) return [{ id: "default", name: "\u9ED8\u8BA4", isDefault: true }]; - if (cfg2.fetchModels) return cfg2.fetchModels(r); - return [{ id: "default", name: "\u9ED8\u8BA4", isDefault: true }]; + async listModels(launch) { + const resolved = launch ? await resolveLaunch(launch) : await resolveProviderBin(cfg2); + if (!resolved.ok) return [{ id: "default", name: PLACEHOLDER_MODEL_NAME, isDefault: true }]; + const r = launch?.prefixArgs?.length && resolved.via !== "cmd-shim" ? { ...resolved, prefixArgs: [...resolved.prefixArgs, ...launch.prefixArgs] } : resolved; + if (cfg2.fetchModels) return cfg2.fetchModels(r, launch?.args ?? []); + return [{ id: "default", name: PLACEHOLDER_MODEL_NAME, isDefault: true }]; }, async createSession(o) { return new AcpSession({ @@ -4225,6 +4557,8 @@ var init_provider3 = __esm({ "daemon/src/providers/acp/provider.ts"() { init_bin(); init_bin(); + init_launch(); + init_types(); init_session3(); init_promptCaps(); acpCapabilities = { @@ -4236,7 +4570,8 @@ var init_provider3 = __esm({ questions: false, cost: false, effort: [], - modes: ["plan", "default", "acceptEdits", "bypassPermissions"] + modes: ["plan", "default", "acceptEdits", "bypassPermissions"], + deltasOnly: true }; cursorAcpCapabilities = { ...acpCapabilities, @@ -4250,7 +4585,7 @@ var init_provider3 = __esm({ import { createHash as createHash2 } from "node:crypto"; import { mkdir as mkdir2, writeFile as writeFile3 } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join as join9 } from "node:path"; +import { join as join10 } from "node:path"; function dshRoute(model) { if (!model) return null; try { @@ -4272,11 +4607,11 @@ function dshRoutePatch(route) { "" ].join("\n"); } -async function dshAcpArgs(model, dir = join9(tmpdir(), "agent-console-dsh")) { +async function dshAcpArgs(model, dir = join10(tmpdir(), "agent-console-dsh")) { const route = dshRoute(model); if (!route) return [...DSH_ACP_ARGS]; const body = dshRoutePatch(route); - const file = join9(dir, `acp-route-${createHash2("sha256").update(body).digest("hex").slice(0, 16)}.yml`); + const file = join10(dir, `acp-route-${createHash2("sha256").update(body).digest("hex").slice(0, 16)}.yml`); await mkdir2(dir, { recursive: true }); await writeFile3(file, body, { mode: 384 }); return [...DSH_ACP_ARGS, "--patch", file]; @@ -4342,9 +4677,9 @@ function probeAcpRaw(r, acpArgs, timeoutMs = 3e4, extMethod) { }; const timer = setTimeout(() => finish(new Error("ACP \u63A2\u6D4B\u8D85\u65F6")), timeoutMs); const send2 = (method, params) => new Promise((res, rej) => { - const id = ++nextId; - pending.set(id, { res, rej }); - child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n"); + const id2 = ++nextId; + pending.set(id2, { res, rej }); + child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id: id2, method, params }) + "\n"); }); child.on("error", (e) => finish(e)); child.on("close", () => finish(new Error("ACP \u8FDB\u7A0B\u63D0\u524D\u9000\u51FA"))); @@ -4399,13 +4734,13 @@ function cursorCatalogToModels(catalog, currentModel) { const out = []; for (const m of catalog.models ?? []) { if (typeof m.value !== "string" || !m.value) continue; - const id = m.value.replace(/\[.*\]$/u, ""); + const id2 = m.value.replace(/\[.*\]$/u, ""); const thought = (m.configOptions ?? []).find((o) => o.category === "thought_level"); const levels = flatten(thought?.options); out.push({ - id, - name: typeof m.name === "string" && m.name ? m.name : id, - isDefault: id === currentBase, + id: id2, + name: typeof m.name === "string" && m.name ? m.name : id2, + isDefault: id2 === currentBase, ...thought && levels.length ? { thinkingOptions: levels.map((l) => ({ id: l.id, label: EFFORT_LABEL[l.id] ?? l.name })), defaultThinking: typeof thought.currentValue === "string" ? thought.currentValue : void 0, @@ -4416,9 +4751,9 @@ function cursorCatalogToModels(catalog, currentModel) { return out; } function cursorProbeModels(acpArgs, providerId) { - return async (r) => { + return async (r, launchArgs = []) => { try { - const { parsed, ext, promptCaps } = await probeAcpRaw(r, acpArgs, 4e4, "cursor/list_available_models"); + const { parsed, ext, promptCaps } = await probeAcpRaw(r, [...acpArgs, ...launchArgs], 4e4, "cursor/list_available_models"); rememberPromptCaps(providerId, promptCaps); const fromCatalog = ext ? cursorCatalogToModels(ext, parsed.currentModel) : []; return fromCatalog.length ? fromCatalog : probeToModels(parsed); @@ -4429,13 +4764,13 @@ function cursorProbeModels(acpArgs, providerId) { }; } function dshProbeModels(providerId) { - return async (r) => { + return async (r, launchArgs = []) => { try { - const first = await probeAcpRaw(r, DSH_ACP_ARGS, 3e4); + const first = await probeAcpRaw(r, [...DSH_ACP_ARGS, ...launchArgs], 3e4); let caps = first.promptCaps; const start = dshDefaultModel(first.parsed.models, first.parsed.currentModel); if (start && start !== first.parsed.currentModel && dshRoute(start)) { - caps = await probeAcpRaw(r, await dshAcpArgs(start), 3e4).then((x) => x.promptCaps, () => caps); + caps = await probeAcpRaw(r, [...await dshAcpArgs(start), ...launchArgs], 3e4).then((x) => x.promptCaps, () => caps); } rememberPromptCaps(providerId, caps); return probeToModels(first.parsed); @@ -4446,9 +4781,9 @@ function dshProbeModels(providerId) { }; } function acpProbeModels(acpArgs, providerId) { - return async (r) => { + return async (r, launchArgs = []) => { try { - return probeToModels(await probeAcp(r, acpArgs, 3e4, providerId)); + return probeToModels(await probeAcp(r, [...acpArgs, ...launchArgs], 3e4, providerId)); } catch (e) { log("warn", "ACP \u63A2\u6D4B\u6A21\u578B\u5931\u8D25", { err: String(e) }); return []; @@ -4547,8 +4882,8 @@ var init_specs = __esm({ function registerProvider(p) { providers.set(p.id, p); } -function getProvider(id) { - return providers.get(id); +function getProvider(id2) { + return providers.get(id2); } function listProviders() { return [...providers.values()]; @@ -4581,10 +4916,10 @@ var init_registry = __esm({ }); // daemon/src/providers/enabled.ts -function isProviderEnabled(settings, id) { +function isProviderEnabled(settings, id2) { const m = settings.providerEnabled; - if (m && typeof m === "object" && typeof m[id] === "boolean") return m[id]; - const entry = catalogById(id); + if (m && typeof m === "object" && typeof m[id2] === "boolean") return m[id2]; + const entry = catalogById(id2); if (!entry) return true; return entry.status === "verified"; } @@ -4685,21 +5020,21 @@ var init_pickFolder = __esm({ }); // daemon/src/providers/magpieGateway.ts -import { readFile as readFile10 } from "node:fs/promises"; -import { homedir as homedir6 } from "node:os"; -import { join as join10 } from "node:path"; +import { readFile as readFile11 } from "node:fs/promises"; +import { homedir as homedir7 } from "node:os"; +import { join as join11 } from "node:path"; async function readJson(path3) { try { - return JSON.parse(await readFile10(path3, "utf8")); + return JSON.parse(await readFile11(path3, "utf8")); } catch { return null; } } async function readApplied() { - return await readJson(join10(homedir6(), ".config", "magpie", "applied.json")) ?? {}; + return await readJson(join11(homedir7(), ".config", "magpie", "applied.json")) ?? {}; } async function readClaudeEnv() { - const s = await readJson(join10(homedir6(), ".claude", "settings.json")); + const s = await readJson(join11(homedir7(), ".claude", "settings.json")); return s?.env ?? {}; } async function gatewayBase() { @@ -4713,7 +5048,7 @@ async function fetchGatewayModelIds() { const res = await fetch(`${base}/v1/models`, { signal: AbortSignal.timeout(5e3) }); if (!res.ok) return []; const j = await res.json(); - return (j.data ?? []).map((m) => m.id).filter((id) => typeof id === "string" && !!id); + return (j.data ?? []).map((m) => m.id).filter((id2) => typeof id2 === "string" && !!id2); } catch (e) { log("warn", "\u8BFB\u53D6 magpie \u7F51\u5173\u6A21\u578B\u5217\u8868\u5931\u8D25", { err: String(e) }); return []; @@ -4773,7 +5108,7 @@ async function withMagpie(providerId, own) { return { ...m, name, - thinkingOptions: levels.map((id) => ({ id, label: EFFORT_LABEL2[id] ?? id })), + thinkingOptions: levels.map((id2) => ({ id: id2, label: EFFORT_LABEL2[id2] ?? id2 })), defaultThinking: m.isDefault ? def : m.defaultThinking ?? def }; }); @@ -4806,46 +5141,53 @@ function withTimeout(p, ms, fb) { function fresh(e, ttl) { return !!e && Date.now() - e.at < ttl; } -async function cachedDetect(p) { - const hit = detects.get(p.id); +function cacheKey(p, launch) { + return launch ? `${p.id}\0${launchKey(launch)}` : p.id; +} +async function cachedDetect(p, launch) { + const key = cacheKey(p, launch); + const hit = detects.get(key); if (fresh(hit, DETECT_MS)) return hit.value; - let job = inflightDetect.get(p.id); + let job = inflightDetect.get(key); if (!job) { + const timedOut = { available: false, reason: tr("provider.timeout") }; job = withTimeout( - p.detect().catch((e) => ({ available: false, reason: String(e?.message ?? e) })), + p.detect(launch).catch((e) => ({ available: false, reason: String(e?.message ?? e) })), STEP_TIMEOUT_MS, - { available: false, reason: "\u68C0\u6D4B\u8D85\u65F6" } + timedOut ).then((v) => { - if (v.reason !== "\u68C0\u6D4B\u8D85\u65F6") detects.set(p.id, { at: Date.now(), value: v }); + if (v !== timedOut) detects.set(key, { at: Date.now(), value: v }); return v; - }).finally(() => inflightDetect.delete(p.id)); - inflightDetect.set(p.id, job); + }).finally(() => inflightDetect.delete(key)); + inflightDetect.set(key, job); } return job; } -async function cachedModels(p) { - const hit = models.get(p.id); +async function cachedModels(p, launch) { + const key = cacheKey(p, launch); + const hit = models.get(key); if (fresh(hit, MODELS_MS)) return hit.value; - let job = inflightModels.get(p.id); + let job = inflightModels.get(key); if (!job) { - job = withTimeout(p.listModels().catch(() => []), MODELS_TIMEOUT_MS, null).then(async (v) => { - if (v === null) return models.get(p.id)?.value ?? []; + job = withTimeout(p.listModels(launch).catch(() => []), MODELS_TIMEOUT_MS, null).then(async (v) => { + if (v === null) return models.get(key)?.value ?? []; const list = await withMagpie(p.id, dropPlaceholder(v)).catch(() => dropPlaceholder(v)); - models.set(p.id, { at: Date.now(), value: list }); + models.set(key, { at: Date.now(), value: list }); return list; - }).finally(() => inflightModels.delete(p.id)); - inflightModels.set(p.id, job); + }).finally(() => inflightModels.delete(key)); + inflightModels.set(key, job); } return job; } function dropPlaceholder(list) { - if (list.length === 1 && list[0].id === "default" && list[0].name === "\u9ED8\u8BA4") return []; + if (list.length === 1 && list[0].id === "default" && (list[0].name === "\u9ED8\u8BA4" || list[0].name === PLACEHOLDER_MODEL_NAME)) return []; return list; } -function clearProviderCache(id) { - if (id) { - detects.delete(id); - models.delete(id); +function clearProviderCache(id2) { + if (id2) { + for (const m of [detects, models]) { + for (const k of [...m.keys()]) if (k === id2 || k.startsWith(id2 + "\0")) m.delete(k); + } } else { detects.clear(); models.clear(); @@ -4854,7 +5196,10 @@ function clearProviderCache(id) { var DETECT_MS, MODELS_MS, STEP_TIMEOUT_MS, MODELS_TIMEOUT_MS, detects, models, inflightDetect, inflightModels; var init_infoCache = __esm({ "daemon/src/providers/infoCache.ts"() { + init_types(); init_magpieGateway(); + init_launch(); + init_i18n(); DETECT_MS = 60 * 1e3; MODELS_MS = 10 * 60 * 1e3; STEP_TIMEOUT_MS = 15e3; @@ -4866,18 +5211,29 @@ var init_infoCache = __esm({ } }); +// daemon/src/providers/modes.ts +function clampMode(modes, mode2) { + if (mode2 && modes.includes(mode2)) return mode2; + if (modes.includes("default")) return "default"; + return modes[0] ?? "default"; +} +var init_modes = __esm({ + "daemon/src/providers/modes.ts"() { + } +}); + // daemon/src/ws/methods.ts import { z } from "zod"; import { existsSync as existsSync8, statSync as statSync4 } from "node:fs"; import { mkdir as mkdir3, writeFile as writeFile4 } from "node:fs/promises"; -import { homedir as homedir7 } from "node:os"; -import { dirname as dirname3, join as join11, win32 as win32Path } from "node:path"; +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"; function wrap(schema, fn) { return (params, ctx) => { const r = schema.safeParse(params ?? {}); if (!r.success) { - throw new ApiError("bad_params", "\u53C2\u6570\u4E0D\u5BF9\uFF1A" + r.error.issues.map((i) => i.message).join("\uFF1B")); + throw new ApiError("bad_params", tr("err.badParams", { detail: r.error.issues.map((i) => i.message).join("; ") })); } return fn(r.data, ctx); }; @@ -4895,10 +5251,18 @@ function registerMethods(gw, svc) { return { ok: true }; })); gw.method("settings.get", wrap(zEmpty, () => svc.settings.get())); - gw.method("settings.set", wrap( - z.object({ patch: z.record(z.string(), z.unknown()) }), - (p) => svc.settings.set(p.patch) - )); + gw.method("settings.set", wrap(z.object({ patch: z.record(z.string(), z.unknown()) }), async (p) => { + const checked = parseSettingsPatch(p.patch); + if (!checked.ok) throw new ApiError("bad_params", `Invalid setting: ${checked.error}`); + const before = await svc.settings.get(); + const next = await svc.settings.set(checked.patch); + for (const id2 of Object.keys(checked.patch.providerCommand ?? {})) { + if (JSON.stringify(before.providerCommand?.[id2] ?? null) !== JSON.stringify(next.providerCommand?.[id2] ?? null)) { + clearProviderCache(id2); + } + } + return next; + })); gw.method("sub.add", wrap( z.object({ ch: z.string().min(1).max(120), afterSeq: z.number().int().nonnegative().optional() }), async (p, ctx) => { @@ -4927,9 +5291,10 @@ function registerMethods(gw, svc) { listProviders().map(async (p2) => { const entry = catalogById(p2.id); const enabled = isProviderEnabled(settings, p2.id); + const launch = launchFromSettings(settings, p2.id); const skip = !enabled || entry?.status === "planned"; - const det = skip ? { available: false, reason: !enabled ? "\u5DF2\u5728\u8BBE\u7F6E\u4E2D\u7981\u7528" : "\u5C1A\u672A\u63A5\u5165" } : await cachedDetect(p2); - const models2 = !skip && det.available ? await cachedModels(p2) : []; + const det = skip ? { available: false, reason: !enabled ? tr("provider.disabled") : tr("provider.planned") } : await cachedDetect(p2, launch); + const models2 = !skip && det.available ? await cachedModels(p2, launch) : []; return { id: p2.id, name: p2.name, @@ -4939,7 +5304,7 @@ function registerMethods(gw, svc) { ready: entry?.status === "verified", bin: det.bin, version: det.version, - reason: !enabled ? "\u5DF2\u5728\u8BBE\u7F6E\u4E2D\u7981\u7528" : det.reason, + reason: !enabled ? tr("provider.disabled") : det.reason, installHint: det.installHint, capabilities: p2.capabilities, models: models2 @@ -4973,7 +5338,7 @@ function registerMethods(gw, svc) { })); gw.method("projects.remove", wrap(z.object({ id: z.string() }), async (p) => { const proj = await svc.projects.get(p.id); - if (!proj) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); for (const t of await svc.threads.list()) { if (t.projectId === p.id) { await svc.threads.delete(t.id); @@ -4986,8 +5351,8 @@ 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", "\u9879\u76EE\u4E0D\u5B58\u5728"); - if (!existsSync8(proj.path)) throw new ApiError("bad_path", "\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u662F\u6587\u4EF6\u5939"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); + if (!existsSync8(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 }, () => { @@ -5027,16 +5392,18 @@ function registerMethods(gw, svc) { }), async (p) => { const proj = await svc.projects.get(p.projectId); - if (!proj) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); - if (!existsSync8(proj.path)) throw new ApiError("bad_path", "\u9879\u76EE\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); + if (!existsSync8(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", "\u8BE5 Agent \u5DF2\u5728\u8BBE\u7F6E\u4E2D\u7981\u7528"); + throw new ApiError("bad_params", tr("provider.disabledNamed", { name: catalogById(p.provider)?.name ?? p.provider })); } const cat = catalogById(p.provider); if (!p.providerSessionId && cat && !providerCreatable(cat.status)) { - throw new ApiError("bad_params", `${cat.name} \u5C1A\u672A\u63A5\u5165\uFF0C\u6682\u4E0D\u80FD\u65B0\u5EFA\u5BF9\u8BDD`); + throw new ApiError("bad_params", tr("provider.plannedNamed", { name: cat.name })); } - const meta = await svc.threads.create(p); + const provider = getProvider(p.provider); + const mode2 = clampMode(provider?.capabilities.modes ?? [], p.mode); + const meta = await svc.threads.create({ ...p, mode: mode2 }); gw.publish("sidebar", { type: "thread.upsert", thread: meta }); return meta; } @@ -5045,7 +5412,7 @@ function registerMethods(gw, svc) { z.object({ id: z.string(), afterSeq: z.number().int().nonnegative().optional() }), async (p) => { const meta = await svc.threads.get(p.id); - if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); + if (!meta) throw new ApiError("not_found", tr("err.threadMissing")); const events = await svc.threads.readEvents(p.id, p.afterSeq ?? 0, 5e3); const rt = svc.runtime?.(p.id) ?? null; return { @@ -5066,7 +5433,7 @@ function registerMethods(gw, svc) { }), async (p) => { const meta = await svc.threads.get(p.id); - if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); + if (!meta) throw new ApiError("not_found", tr("err.threadMissing")); const patch = {}; if (p.title !== void 0) { patch.title = p.title.trim() || meta.title; @@ -5081,7 +5448,7 @@ function registerMethods(gw, svc) { )); gw.method("threads.delete", wrap(z.object({ id: z.string() }), async (p) => { const meta = await svc.threads.get(p.id); - if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); + if (!meta) throw new ApiError("not_found", tr("err.threadMissing")); if (svc.manager) await svc.manager.deleteThread(p.id); else await svc.threads.delete(p.id); gw.publish("sidebar", { type: "thread.remove", id: p.id }); @@ -5089,8 +5456,8 @@ function registerMethods(gw, svc) { })); const projectPath = async (projectId) => { const proj = await svc.projects.get(projectId); - if (!proj) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); - if (!existsSync8(proj.path)) throw new ApiError("bad_path", "\u9879\u76EE\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); + if (!existsSync8(proj.path)) throw new ApiError("bad_path", tr("err.projectDirGone")); return proj.path; }; gw.method("git.status", wrap( @@ -5115,7 +5482,7 @@ function registerMethods(gw, svc) { )); gw.method("history.list", wrap(z.object({ projectId: z.string() }), async (p) => { const proj = await svc.projects.get(p.projectId); - if (!proj) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); const imported = new Set( (await svc.threads.list()).filter((t) => t.projectId === p.projectId && t.providerSessionId).map((t) => t.providerSessionId) ); @@ -5134,7 +5501,7 @@ function registerMethods(gw, svc) { }), async (p) => { const proj = await svc.projects.get(p.projectId); - if (!proj) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); const metas = []; for (const item of p.items) { const provider = getProvider(item.provider); @@ -5179,7 +5546,7 @@ function registerMethods(gw, svc) { )); gw.method("terminal.attach", wrap(z.object({ id: z.string() }), async (p, ctx) => { const r = svc.terminals.attach(p.id); - if (r.error || r.index == null) throw new ApiError("not_found", r.error ?? "\u7EC8\u7AEF\u4E0D\u5B58\u5728"); + if (r.error || r.index == null) throw new ApiError("not_found", r.error ?? tr("err.terminalMissing")); svc.gateway.subscribe(ctx.conn, `terminal:${r.index}`); return r; })); @@ -5189,7 +5556,7 @@ function registerMethods(gw, svc) { )); gw.method("terminal.kill", wrap(z.object({ id: z.string() }), (p) => svc.terminals.kill(p.id))); const needManager = () => { - if (!svc.manager) throw new ApiError("unavailable", "\u4F1A\u8BDD\u7BA1\u7406\u5668\u672A\u542F\u52A8"); + if (!svc.manager) throw new ApiError("unavailable", tr("err.noManager")); return svc.manager; }; gw.method("thread.send", wrap( @@ -5200,10 +5567,13 @@ function registerMethods(gw, svc) { behavior: z.enum(["queue", "steer"]).optional() }), async (p) => { - await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? "queue"); - return { ok: true }; + const delivered = await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? "queue"); + return { ok: true, delivered: delivered ?? "started" }; } )); + gw.method("thread.queueRemove", wrap(z.object({ id: z.string(), queueId: z.string() }), async (p) => { + return { ok: needManager().removeQueued(p.id, p.queueId) }; + })); gw.method("thread.interrupt", wrap(z.object({ id: z.string() }), async (p) => { await needManager().interrupt(p.id); return { ok: true }; @@ -5261,15 +5631,15 @@ function registerMethods(gw, svc) { })); gw.method("thread.exportMarkdown", wrap(z.object({ id: z.string() }), async (p) => { const meta = await svc.threads.get(p.id); - if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); + if (!meta) throw new ApiError("not_found", tr("err.threadMissing")); const events = await svc.threads.readEvents(p.id, 0, 2e4); const L = []; L.push(`# ${meta.title}`, ""); - L.push(`> ${meta.provider} \xB7 ${meta.model ?? "\u9ED8\u8BA4"} \xB7 ${meta.mode} \xB7 ${new Date(meta.createdAt).toLocaleString("zh-CN")}`, ""); + 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": - L.push(`**\u6211**${e.steered ? "\uFF08\u63D2\u8BDD\uFF09" : ""}\uFF1A + L.push(`**${tr("export.me")}**${e.steered ? tr("export.steered") : ""}: ${e.text}`, ""); break; @@ -5277,7 +5647,7 @@ ${e.text}`, ""); L.push(e.text, ""); break; case "reasoning": - L.push(`
\u601D\u8003 + L.push(`
${tr("export.reasoning")} ${e.text}
`, ""); @@ -5291,10 +5661,14 @@ ${e.text} break; } case "plan": - L.push("### \u8BA1\u5212\n\n" + e.markdown, ""); + L.push(`### ${tr("export.plan")} + +` + e.markdown, ""); break; case "todo": - L.push("### \u5F85\u529E\n\n" + e.items.map((i) => `- [${i.status === "done" || i.status === "completed" ? "x" : " "}] ${i.text}`).join("\n"), ""); + L.push(`### ${tr("export.todo")} + +` + e.items.map((i) => `- [${i.status === "done" || i.status === "completed" ? "x" : " "}] ${i.text}`).join("\n"), ""); break; case "notice": L.push(`_${e.message}_`, ""); @@ -5309,12 +5683,17 @@ ${e.text} const markdown = L.join("\n"); const safe = meta.title.replace(/[\\/:*?"<>|\s]+/g, "_").slice(0, 60) || "thread"; const filename = `${safe}.md`; - const dir = join11(homedir7(), "Downloads"); - await mkdir3(dir, { recursive: true }); - let dest = join11(dir, filename); + let dir = join12(homedir8(), "Downloads"); + try { + await mkdir3(dir, { recursive: true }); + } catch { + dir = join12(svc.cfg.dataDir, "exports"); + await mkdir3(dir, { recursive: true }); + } + let dest = join12(dir, filename); if (existsSync8(dest)) { const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19); - dest = join11(dir, `${safe}-${stamp2}.md`); + dest = join12(dir, `${safe}-${stamp2}.md`); } await writeFile4(dest, markdown, "utf8"); revealInFileManager(dest); @@ -5341,12 +5720,16 @@ function revealInFileManager(filePath) { var threadModeSchema, ApiError; var init_methods = __esm({ "daemon/src/ws/methods.ts"() { + init_settings(); init_registry(); init_catalog(); init_enabled(); init_pickFolder(); init_bin(); init_infoCache(); + init_launch(); + init_modes(); + init_i18n(); threadModeSchema = z.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]); ApiError = class extends Error { code; @@ -5378,13 +5761,118 @@ var init_atomic = __esm({ } }); +// daemon/src/store/settings.ts +import { readFile as readFile12 } from "node:fs/promises"; +import { join as join13 } from "node:path"; +import { z as z2 } from "zod"; +function parseSettingsPatch(patch) { + const r = settingsPatchSchema.safeParse(patch); + if (r.success) return { ok: true, patch: r.data }; + return { + ok: false, + error: r.error.issues.map((i) => `${i.path.join(".") || "(patch)"}: ${i.message}`).join("; ") + }; +} +function sanitizeStored(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; + const shape = settingsPatchSchema.shape; + const out = {}; + for (const [k, v] of Object.entries(raw)) { + const field = shape[k]; + if (field && k !== "idleCloseMinutes" && !field.safeParse(v).success) continue; + if (k === "idleCloseMinutes") { + const n = Number(v); + if (!Number.isFinite(n)) continue; + out[k] = Math.min(IDLE_CLOSE_MAX, Math.max(IDLE_CLOSE_MIN, Math.round(n))); + continue; + } + out[k] = v; + } + return out; +} +var DEFAULT_SETTINGS, IDLE_CLOSE_MIN, IDLE_CLOSE_MAX, mode, id, settingsPatchSchema, SettingsStore; +var init_settings = __esm({ + "daemon/src/store/settings.ts"() { + init_atomic(); + DEFAULT_SETTINGS = { + defaultProvider: "claude", + defaultMode: "default", + sendKey: "enter", + runningSend: "queue", + showThinking: true, + theme: "auto", + idleCloseMinutes: 30, + collapsedProjects: [], + panel: { open: false, tab: "changes", width: 440 }, + sidebarWidth: 248, + lastProjectId: null, + lastThreadId: null, + recentDirs: [] + }; + IDLE_CLOSE_MIN = 5; + IDLE_CLOSE_MAX = 240; + mode = z2.enum(["plan", "default", "acceptEdits", "bypassPermissions", "ask"]); + id = z2.string().min(1).max(200); + settingsPatchSchema = z2.object({ + defaultProvider: z2.string().min(1).max(64), + defaultMode: mode, + sendKey: z2.enum(["enter", "ctrlEnter"]), + runningSend: z2.enum(["queue", "steer"]), + showThinking: z2.boolean(), + // auto = follow the host: Magpie's light/dark inside Magpie, the OS outside it + theme: z2.enum(["auto", "light", "dark"]), + 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), + lastProjectId: id.nullable(), + lastThreadId: id.nullable(), + recentDirs: z2.array(z2.string().max(4096)).max(50), + providerEnabled: z2.record(z2.string().max(64), z2.boolean()), + providerCommand: z2.record( + z2.string().max(64), + z2.object({ executable: z2.string().max(4096).optional(), args: z2.array(z2.string().max(4096)).max(64).optional() }).strict() + ), + v1Migrated: z2.boolean() + }).partial().strict(); + SettingsStore = class { + file; + cache = null; + writing = Promise.resolve(); + constructor(dataDir) { + this.file = join13(dataDir, "settings.json"); + } + async get() { + if (this.cache) return this.cache; + let raw = {}; + try { + raw = JSON.parse(await readFile12(this.file, "utf8")); + } catch { + } + raw = sanitizeStored(raw); + this.cache = { ...DEFAULT_SETTINGS, ...raw, panel: { ...DEFAULT_SETTINGS.panel, ...raw.panel } }; + return this.cache; + } + async set(patch) { + const cur = await this.get(); + const next = { ...cur, ...patch, panel: { ...cur.panel, ...patch.panel } }; + this.cache = next; + const snap = next; + this.writing = this.writing.then(() => writeJsonAtomic(this.file, snap)); + await this.writing; + return next; + } + }; + } +}); + // daemon/src/util/jsonl.ts -import { appendFile, readFile as readFile13, mkdir as mkdir5, rename as rename2, writeFile as writeFile6 } from "node:fs/promises"; +import { appendFile, readFile as readFile14, mkdir as mkdir5, rename as rename2, writeFile as writeFile6 } from "node:fs/promises"; import { dirname as dirname5 } from "node:path"; async function readJsonl(file) { let text = ""; try { - text = await readFile13(file, "utf8"); + text = await readFile14(file, "utf8"); } catch { return []; } @@ -5430,9 +5918,9 @@ var legacy_exports = {}; __export(legacy_exports, { migrateLegacy: () => migrateLegacy }); -import { cp as cp2, mkdir as mkdir8, readdir as readdir6, readFile as readFile17 } from "node:fs/promises"; +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 join18 } from "node:path"; +import { join as join19 } from "node:path"; function stamp() { const d = /* @__PURE__ */ new Date(); const p = (n) => String(n).padStart(2, "0"); @@ -5441,19 +5929,19 @@ function stamp() { async function migrateLegacy(dataDir, stores) { const settings = await stores.settings.get(); if (settings.v1Migrated) return { migrated: 0, skipped: true }; - const oldDir = join18(dataDir, "sessions"); - const oldSettingsPath = join18(dataDir, "settings.json"); + const oldDir = join19(dataDir, "sessions"); + const oldSettingsPath = join19(dataDir, "settings.json"); if (!existsSync12(oldDir) && !existsSync12(oldSettingsPath)) { await stores.settings.set({ v1Migrated: true }); return { migrated: 0, skipped: true }; } - const backup = join18(dataDir, "trash", `legacy-${stamp()}`); + const backup = join19(dataDir, "trash", `legacy-${stamp()}`); await mkdir8(backup, { recursive: true }); - if (existsSync12(oldDir)) await cp2(oldDir, join18(backup, "sessions"), { recursive: true }).catch(() => { + if (existsSync12(oldDir)) await cp2(oldDir, join19(backup, "sessions"), { recursive: true }).catch(() => { }); - if (existsSync12(oldSettingsPath)) await cp2(oldSettingsPath, join18(backup, "settings.json")).catch(() => { + if (existsSync12(oldSettingsPath)) await cp2(oldSettingsPath, join19(backup, "settings.json")).catch(() => { }); - const oldSettings = existsSync12(oldSettingsPath) ? JSON.parse(await readFile17(oldSettingsPath, "utf8").catch(() => "{}")) : {}; + const oldSettings = existsSync12(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 ?? []) { @@ -5467,13 +5955,13 @@ async function migrateLegacy(dataDir, stores) { } let sessionIds = []; try { - sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync12(join18(oldDir, d, "meta.json"))); + sessionIds = (await readdir6(oldDir)).filter((d) => validId(d) && existsSync12(join19(oldDir, d, "meta.json"))); } catch { } const metas = []; - for (const id of sessionIds) { + for (const id2 of sessionIds) { try { - const m = JSON.parse(await readFile17(join18(oldDir, id, "meta.json"), "utf8")); + const m = JSON.parse(await readFile18(join19(oldDir, id2, "meta.json"), "utf8")); if (m?.cwd) metas.push(m); } catch { } @@ -5500,13 +5988,13 @@ async function migrateLegacy(dataDir, stores) { const projectOf = (cwd) => { const l = lc(cwd); let best = null; - for (const [pp, id] of projectIdByPath) { + for (const [pp, id2] of projectIdByPath) { if (belongsTo(l, pp) && (best == null || pp.length > best.length)) best = pp; } return best ? projectIdByPath.get(best) : null; }; let migrated = 0; - const threadsDir = join18(dataDir, "threads"); + const threadsDir = join19(dataDir, "threads"); for (const m of metas) { try { const projectId = projectOf(m.cwd); @@ -5543,10 +6031,10 @@ async function migrateLegacy(dataDir, stores) { importedFrom: m.cliSessionId ? { provider, sessionId: m.cliSessionId } : void 0, seq: 0 }; - const tdir = join18(threadsDir, meta.id); + const tdir = join19(threadsDir, meta.id); if (existsSync12(tdir)) meta.id = `t_${m.id}_v1`.slice(0, 80); - await mkdir8(join18(threadsDir, meta.id), { recursive: true }); - const oldEvts = (await readFile17(join18(oldDir, m.id, "events.jsonl"), "utf8").catch(() => "")).split("\n").filter((l) => l.trim()).map((l) => { + 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) => { try { return JSON.parse(l); } catch { @@ -5625,9 +6113,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(join18(threadsDir, meta.id, "timeline.jsonl"), ev); + for (const ev of lines) await appendJsonl(join19(threadsDir, meta.id, "timeline.jsonl"), ev); meta.seq = seq; - await writeJsonAtomic(join18(threadsDir, meta.id, "meta.json"), meta); + await writeJsonAtomic(join19(threadsDir, meta.id, "meta.json"), meta); migrated++; } catch (e) { log("warn", "\u8FC1\u79FB\uFF1A\u4F1A\u8BDD\u5931\u8D25", { id: m.id, err: String(e) }); @@ -5692,7 +6180,7 @@ var init_warm = __esm({ // daemon/src/main.ts import { mkdirSync as mkdirSync2, rmSync as rmSync2, chmodSync as chmodSync2 } from "node:fs"; -import { join as join19, dirname as dirname7 } from "node:path"; +import { join as join20, dirname as dirname7 } from "node:path"; import { fileURLToPath as fileURLToPath3 } from "node:url"; // daemon/src/config.ts @@ -5809,6 +6297,7 @@ function tokenEqual(a, b) { // daemon/src/http.ts init_log(); +init_i18n(); var MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", @@ -5850,7 +6339,7 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { await route(req, res); } catch (e) { log("error", "HTTP \u5904\u7406\u5F02\u5E38", { url: req.url, err: String(e) }); - if (!res.headersSent) sendJson(res, 500, { ok: false, e: { code: "internal", message: "\u670D\u52A1\u5185\u90E8\u9519\u8BEF" } }); + if (!res.headersSent) sendJson(res, 500, { ok: false, e: { code: "internal", message: tr("http.internal") } }); else res.end(); } }); @@ -5862,7 +6351,7 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { } const origin = classifyOrigin(req.headers.origin, cfg2.port); if (origin === "foreign") { - sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: "\u6765\u6E90\u4E0D\u5141\u8BB8" } }); + sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: tr("http.badOrigin") } }); return; } const url = new URL(req.url ?? "/", `http://127.0.0.1:${cfg2.port}`); @@ -5871,7 +6360,7 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { const isAttachment = pathname.startsWith("/attachments/"); if (req.method === "OPTIONS") { if (pathname !== "/api/upload" || origin === "none") { - sendJson(res, 403, { ok: false, e: { code: "bad_preflight", message: "\u9884\u68C0\u4E0D\u5141\u8BB8" } }); + sendJson(res, 403, { ok: false, e: { code: "bad_preflight", message: tr("http.badPreflight") } }); return; } send(res, 204, "", { @@ -5888,7 +6377,7 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { const queryToken = isAttachment ? url.searchParams.get("t") : null; const validToken = typeof headerToken === "string" && tokenEqual(headerToken, cfg2.token) || typeof queryToken === "string" && tokenEqual(queryToken, cfg2.token); if (!validToken) { - sendJson(res, 403, { ok: false, e: { code: "bad_token", message: "\u4EE4\u724C\u65E0\u6548" } }); + sendJson(res, 403, { ok: false, e: { code: "bad_token", message: tr("http.badToken") } }); return; } if (origin === "opaque") { @@ -5899,10 +6388,10 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { await routeApi(req, res, pathname, url); return; } - const id = safeDecode(pathname.slice("/attachments/".length)); - const a = id === null ? null : await attachments.get(id); + const id2 = safeDecode(pathname.slice("/attachments/".length)); + const a = id2 === null ? null : await attachments.get(id2); if (!a) { - sendJson(res, 404, { ok: false, e: { code: "not_found", message: "\u9644\u4EF6\u4E0D\u5B58\u5728" } }); + sendJson(res, 404, { ok: false, e: { code: "not_found", message: tr("http.noAttachment") } }); return; } const data2 = await attachments.read(a.id); @@ -5910,11 +6399,11 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { return; } if (origin === "opaque") { - sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: "\u6765\u6E90\u4E0D\u5141\u8BB8" } }); + sendJson(res, 403, { ok: false, e: { code: "bad_origin", message: tr("http.badOrigin") } }); return; } if (req.method !== "GET" && req.method !== "HEAD") { - sendJson(res, 405, { ok: false, e: { code: "method", message: "\u65B9\u6CD5\u4E0D\u5141\u8BB8" } }); + sendJson(res, 405, { ok: false, e: { code: "method", message: tr("http.method") } }); return; } if (pathname === "/" || pathname === "/index.html") { @@ -5922,23 +6411,23 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { const html = await readFile(join4(appDir, "index.html"), "utf8"); send(res, 200, html, { ...STATIC_HEADERS, "content-type": "text/html; charset=utf-8" }); } catch { - send(res, 503, "app \u8FD8\u6CA1\u6784\u5EFA\uFF08\u7F3A app/index.html\uFF09", { ...STATIC_HEADERS, "content-type": "text/plain; charset=utf-8" }); + send(res, 503, tr("http.noApp"), { ...STATIC_HEADERS, "content-type": "text/plain; charset=utf-8" }); } return; } const decoded = safeDecode(pathname); if (decoded === null) { - sendJson(res, 400, { ok: false, e: { code: "bad_path", message: "\u8DEF\u5F84\u4E0D\u5408\u6CD5" } }); + sendJson(res, 400, { ok: false, e: { code: "bad_path", message: tr("http.badPath") } }); return; } const rel = normalize(decoded).replace(/^([\\/])+/, ""); const full = normalize(join4(appDir, rel)); if (!full.startsWith(normalize(appDir)) || rel.includes("..")) { - sendJson(res, 403, { ok: false, e: { code: "bad_path", message: "\u8DEF\u5F84\u4E0D\u5141\u8BB8" } }); + sendJson(res, 403, { ok: false, e: { code: "bad_path", message: tr("http.pathDenied") } }); return; } if (!existsSync2(full) || !(await stat(full)).isFile()) { - sendJson(res, 404, { ok: false, e: { code: "not_found", message: "\u6587\u4EF6\u4E0D\u5B58\u5728" } }); + sendJson(res, 404, { ok: false, e: { code: "not_found", message: tr("http.noFile") } }); return; } const data = await readFile(full); @@ -5952,13 +6441,13 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { if (pathname === "/api/upload" && req.method === "POST") { const name = url.searchParams.get("name") ?? ""; if (!attachments.allowedExt(name)) { - sendJson(res, 400, { ok: false, e: { code: "bad_type", message: "\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B" } }); + sendJson(res, 400, { ok: false, e: { code: "bad_type", message: tr("http.badType") } }); return; } const declared = Number(req.headers["content-length"] ?? 0); if (declared > MAX_UPLOAD) { res.setHeader("connection", "close"); - sendJson(res, 413, { ok: false, e: { code: "too_large", message: "\u6587\u4EF6\u592A\u5927\uFF08\u4E0A\u9650 50MB\uFF09" } }); + sendJson(res, 413, { ok: false, e: { code: "too_large", message: tr("http.tooLarge") } }); req.resume(); return; } @@ -5969,7 +6458,7 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { size += b.length; if (size > MAX_UPLOAD) { res.setHeader("connection", "close"); - sendJson(res, 413, { ok: false, e: { code: "too_large", message: "\u6587\u4EF6\u592A\u5927\uFF08\u4E0A\u9650 50MB\uFF09" } }); + sendJson(res, 413, { ok: false, e: { code: "too_large", message: tr("http.tooLarge") } }); return; } chunks.push(b); @@ -5978,7 +6467,7 @@ function createHttpServer(cfg2, appDir, attachments, hooks = {}) { sendJson(res, 200, { ok: true, id: a.id, name: a.name, mime: a.mime, size: a.size }); return; } - sendJson(res, 404, { ok: false, e: { code: "not_found", message: "\u63A5\u53E3\u4E0D\u5B58\u5728" } }); + sendJson(res, 404, { ok: false, e: { code: "not_found", message: tr("http.noRoute") } }); } if (hooks.onUpgrade) { server.on("upgrade", hooks.onUpgrade); @@ -6020,105 +6509,58 @@ var AttachmentStore = class { async save(name, data) { const ext = this.safeExt(name); if (!ext) throw new Error("\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B"); - const id = "a_" + Date.now().toString(36) + randomBytes2(3).toString("hex"); + const id2 = "a_" + Date.now().toString(36) + randomBytes2(3).toString("hex"); await mkdir(this.dir, { recursive: true }); - const file = join5(this.dir, id + ext); + const file = join5(this.dir, id2 + ext); await writeFile(file, data); - this.files.set(id, id + ext); + this.files.set(id2, id2 + ext); const mime = MIME2[ext] ?? TEXT_MIME; - return { id, name: name || "\u672A\u547D\u540D" + ext, mime, size: data.length, path: file }; + return { id: id2, name: name || "\u672A\u547D\u540D" + ext, mime, size: data.length, path: file }; } - async get(id) { - if (!validId(id)) return null; - const known = this.files.get(id); + async get(id2) { + if (!validId(id2)) return null; + const known = this.files.get(id2); if (known) { - const hit = await this.describe(id, known); + const hit = await this.describe(id2, known); if (hit) return hit; - this.files.delete(id); + this.files.delete(id2); } const { readdir: readdir7 } = await import("node:fs/promises"); try { for (const f of await readdir7(this.dir)) { - if (f.startsWith(id + ".")) { - this.files.set(id, f); - return await this.describe(id, f); + if (f.startsWith(id2 + ".")) { + this.files.set(id2, f); + return await this.describe(id2, f); } } } catch { } return null; } - async describe(id, f) { + async describe(id2, f) { const p = join5(this.dir, f); const s = await stat2(p).catch(() => null); if (!s?.isFile()) return null; const ext = extname2(f).toLowerCase(); - return { id, name: f.slice(id.length + 1) || f, mime: MIME2[ext] ?? TEXT_MIME, size: s.size, path: p }; + return { id: id2, name: f.slice(id2.length + 1) || f, mime: MIME2[ext] ?? TEXT_MIME, size: s.size, path: p }; } - async read(id) { - const a = await this.get(id); + async read(id2) { + const a = await this.get(id2); if (!a) return null; return readFile2(a.path); } }; -// daemon/src/store/settings.ts -init_atomic(); -import { readFile as readFile11 } from "node:fs/promises"; -import { join as join12 } from "node:path"; -var DEFAULT_SETTINGS = { - defaultProvider: "claude", - defaultMode: "default", - defaultEffort: null, - sendKey: "enter", - runningSend: "queue", - showThinking: true, - density: "comfortable", - theme: "auto", - idleCloseMinutes: 30, - idleExitMinutes: 60, - collapsedProjects: [], - panel: { open: false, tab: "changes", width: 440 }, - sidebarWidth: 248, - lastProjectId: null, - lastThreadId: null, - recentDirs: [] -}; -var SettingsStore = class { - file; - cache = null; - writing = Promise.resolve(); - constructor(dataDir) { - this.file = join12(dataDir, "settings.json"); - } - async get() { - if (this.cache) return this.cache; - let raw = {}; - try { - raw = JSON.parse(await readFile11(this.file, "utf8")); - } catch { - } - this.cache = { ...DEFAULT_SETTINGS, ...raw, panel: { ...DEFAULT_SETTINGS.panel, ...raw.panel } }; - return this.cache; - } - async set(patch) { - const cur = await this.get(); - const next = { ...cur, ...patch, panel: { ...cur.panel, ...patch.panel } }; - this.cache = next; - const snap = next; - this.writing = this.writing.then(() => writeJsonAtomic(this.file, snap)); - await this.writing; - return next; - } -}; +// daemon/src/main.ts +init_settings(); // daemon/src/store/projects.ts init_atomic(); init_paths(); init_methods(); -import { readFile as readFile12 } from "node:fs/promises"; +import { readFile as readFile13 } from "node:fs/promises"; import { existsSync as existsSync9, statSync as statSync5 } from "node:fs"; -import { join as join13 } from "node:path"; +import { join as join14 } from "node:path"; import { randomBytes as randomBytes3 } from "node:crypto"; function newId() { return "p_" + Date.now().toString(36) + randomBytes3(3).toString("hex"); @@ -6128,21 +6570,21 @@ var ProjectsStore = class { cache = null; writing = Promise.resolve(); constructor(dataDir) { - this.file = join13(dataDir, "projects.json"); + this.file = join14(dataDir, "projects.json"); } async list() { if (this.cache) return this.cache; try { - this.cache = JSON.parse(await readFile12(this.file, "utf8")); + this.cache = JSON.parse(await readFile13(this.file, "utf8")); if (!Array.isArray(this.cache)) this.cache = []; } catch { this.cache = []; } return this.cache; } - async get(id) { - if (!validId(id)) return null; - return (await this.list()).find((p) => p.id === id) ?? null; + async get(id2) { + if (!validId(id2)) return null; + return (await this.list()).find((p) => p.id === id2) ?? null; } async save(list) { this.cache = list; @@ -6169,17 +6611,17 @@ var ProjectsStore = class { await this.save(list); return proj; } - async rename(id, name) { + async rename(id2, name) { const list = await this.list(); - const p = list.find((x) => x.id === id); + const p = list.find((x) => x.id === id2); if (!p) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); p.name = name.trim() || p.name; await this.save(list); return p; } - async remove(id) { + async remove(id2) { const list = await this.list(); - const idx = list.findIndex((x) => x.id === id); + const idx = list.findIndex((x) => x.id === id2); if (idx < 0) return; list.splice(idx, 1); await this.save(list); @@ -6192,8 +6634,8 @@ init_jsonl(); init_paths(); init_methods(); init_i18n(); -import { mkdir as mkdir6, rename as rename3, readdir as readdir4, readFile as readFile14 } from "node:fs/promises"; -import { join as join14 } from "node:path"; +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"; function newId2() { return "t_" + Date.now().toString(36) + randomBytes4(3).toString("hex"); @@ -6212,17 +6654,17 @@ var ThreadsStore = class { return p; } constructor(dataDir) { - this.dir = join14(dataDir, "threads"); - this.trashDir = join14(dataDir, "trash", "threads"); + this.dir = join15(dataDir, "threads"); + this.trashDir = join15(dataDir, "trash", "threads"); } - tdir(id) { - return join14(this.dir, id); + tdir(id2) { + return join15(this.dir, id2); } - metaPath(id) { - return join14(this.tdir(id), "meta.json"); + metaPath(id2) { + return join15(this.tdir(id2), "meta.json"); } - timelinePath(id) { - return join14(this.tdir(id), "timeline.jsonl"); + timelinePath(id2) { + return join15(this.tdir(id2), "timeline.jsonl"); } async loadAll() { if (this.loaded) return; @@ -6233,9 +6675,9 @@ var ThreadsStore = class { } catch { return; } - for (const id of ids) { + for (const id2 of ids) { try { - const m = JSON.parse(await readFile14(this.metaPath(id), "utf8")); + const m = JSON.parse(await readFile15(this.metaPath(id2), "utf8")); if (m && typeof m.id === "string") this.metas.set(m.id, m); } catch { } @@ -6245,10 +6687,10 @@ var ThreadsStore = class { await this.loadAll(); return [...this.metas.values()].sort((a, b) => b.updatedAt - a.updatedAt); } - async get(id) { - if (!validId(id)) return null; + async get(id2) { + if (!validId(id2)) return null; await this.loadAll(); - return this.metas.get(id) ?? null; + return this.metas.get(id2) ?? null; } async saveMeta(meta) { this.metas.set(meta.id, meta); @@ -6284,9 +6726,9 @@ var ThreadsStore = class { await this.saveMeta(meta); return meta; } - async patch(id, patch) { + async patch(id2, patch) { return this.serial(async () => { - const meta = await this.get(id); + const meta = await this.get(id2); if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); if (patch.title !== void 0 && patch.titleAuto === void 0) patch = { ...patch, titleAuto: false }; const next = { ...meta, ...patch, id: meta.id, updatedAt: Date.now() }; @@ -6296,37 +6738,37 @@ var ThreadsStore = class { } // Append an event: inside the serialized section take meta.seq+1 as seq, write the jsonl and update meta. // A passed-in seq is ignored (keeps it strictly increasing); ts/threadId are filled in when missing. - async appendEvent(id, ev) { + async appendEvent(id2, ev) { return this.serial(async () => { - const meta = await this.get(id); + const meta = await this.get(id2); if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); const full = { ...ev, seq: meta.seq + 1, ts: ev.ts ?? Date.now(), - threadId: id + threadId: id2 }; - await appendJsonl(this.timelinePath(id), full); + await appendJsonl(this.timelinePath(id2), full); meta.seq = full.seq; meta.updatedAt = Date.now(); - this.metas.set(id, meta); - await writeJsonAtomic(this.metaPath(id), meta); + this.metas.set(id2, meta); + await writeJsonAtomic(this.metaPath(id2), meta); return full; }); } - async readEvents(id, afterSeq = 0, limit = 5e3) { - const rows = await readJsonl(this.timelinePath(id)); + async readEvents(id2, afterSeq = 0, limit = 5e3) { + const rows = await readJsonl(this.timelinePath(id2)); const out = rows.filter((e) => typeof e.seq === "number" && e.seq > afterSeq); return out.slice(-limit); } - async delete(id) { - const meta = await this.get(id); + async delete(id2) { + const meta = await this.get(id2); if (!meta) return; const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19); await mkdir6(this.trashDir, { recursive: true }); for (let attempt = 0; ; attempt++) { try { - await rename3(this.tdir(id), join14(this.trashDir, `${id}-${stamp2}`)); + await rename3(this.tdir(id2), join15(this.trashDir, `${id2}-${stamp2}`)); break; } catch (e) { const code = e?.code; @@ -6337,7 +6779,7 @@ var ThreadsStore = class { throw new ApiError("internal", "\u79FB\u5165\u56DE\u6536\u76EE\u5F55\u5931\u8D25\uFF1A" + String(e)); } } - this.metas.delete(id); + this.metas.delete(id2); } }; @@ -6544,6 +6986,8 @@ init_atomic(); init_registry(); // daemon/src/agents/manager.ts +init_launch(); +init_modes(); init_attachmentRefs(); init_registry(); init_catalog(); @@ -6585,7 +7029,7 @@ var Coalescer = class { this.flush(itemId); } dispose() { - for (const id of [...this.acc.keys()]) this.flush(id); + for (const id2 of [...this.acc.keys()]) this.flush(id2); } }; @@ -6595,6 +7039,7 @@ init_log(); init_i18n(); init_commands(); var SLASH_CACHE_TTL_MS = 10 * 60 * 1e3; +var MAX_WARM_IDLE = 3; var DELTA_TYPES = ["assistant_delta", "reasoning_delta", "tool_output_delta"]; var deltaKey = (type, itemId) => `${type}\0${itemId}`; var AgentManager = class { @@ -6673,6 +7118,16 @@ var AgentManager = class { } return false; } + /** Drop a queued message that hasn't been sent yet (the × on the composer's queue list) */ + removeQueued(threadId, queueId) { + const rt = this.runtimes.get(threadId); + if (!rt) return false; + const before = rt.queue.length; + rt.queue = rt.queue.filter((q) => q.id !== queueId); + if (rt.queue.length === before) return false; + this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue }); + return true; + } runtimeInfo(threadId) { const rt = this.runtimes.get(threadId); if (!rt) return null; @@ -6703,7 +7158,9 @@ var AgentManager = class { endedTurnIds: /* @__PURE__ */ new Set(), starting: false, commands: [], - sessionCreating: null + sessionCreating: null, + pendingText: /* @__PURE__ */ new Map(), + deltasOnly: false }; this.runtimes.set(threadId, r); } @@ -6752,17 +7209,18 @@ var AgentManager = class { steered: true, attachments: this.attachmentLabels(attachmentRefs) }); - return; + 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), 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 }; rt.queue.push(q); this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue }); - return; + return "queued"; } await this.startTurn(threadId, input.text, attachmentRefs); + return "started"; } async startTurn(threadId, text, attachmentRefs) { const rt = this.rt(threadId); @@ -6857,12 +7315,21 @@ var AgentManager = class { return; } if (ev.type === "assistant_delta" || ev.type === "reasoning_delta" || ev.type === "tool_output_delta") { + if (rt.deltasOnly && ev.type !== "tool_output_delta") { + const key = `${ev.type === "assistant_delta" ? "assistant" : "reasoning"}\0${ev.itemId}`; + const prior = rt.pendingText.get(key); + rt.pendingText.set(key, { type: ev.type === "assistant_delta" ? "assistant" : "reasoning", itemId: ev.itemId, text: (prior?.text ?? "") + ev.text }); + } rt.coalescer.push(deltaKey(ev.type, ev.itemId), ev.text); return; } const evItemId = ev.itemId; if (typeof evItemId === "string") this.flushDeltas(rt, evItemId); + if (rt.pendingText.size && ev.type !== "usage" && ev.type !== "assistant_message" && ev.type !== "reasoning") { + await this.persistPendingText(threadId, rt); + } if (ev.type === "assistant_message" || ev.type === "reasoning") { + rt.pendingText.delete(`${ev.type === "assistant_message" ? "assistant" : "reasoning"}\0${ev.itemId}`); await this.appendRaw(threadId, ev); return; } @@ -6919,6 +7386,8 @@ var AgentManager = class { if (ev.status === "failed" && rt.session && !this.alive(rt.session)) rt.session = null; await this.setStatus(threadId, "idle"); const next = rt.queue.shift(); + if (!next) void this.recycleIdle().catch(() => { + }); if (next) { this.gw.publish(`thread:${threadId}`, { type: "queue", queue: rt.queue }); await this.startTurn(threadId, next.text, next.attachments).catch((e) => { @@ -6929,6 +7398,15 @@ var AgentManager = class { } await this.appendRaw(threadId, ev); } + async persistPendingText(threadId, rt) { + const pending = [...rt.pendingText.values()]; + rt.pendingText.clear(); + for (const p of pending) { + if (!p.text) continue; + this.flushDeltas(rt, p.itemId); + await this.appendRaw(threadId, { type: p.type === "assistant" ? "assistant_message" : "reasoning", itemId: p.itemId, text: p.text }); + } + } alive(_s) { return true; } @@ -6936,10 +7414,10 @@ var AgentManager = class { async respond(threadId, requestId, answer) { const rt = this.rt(threadId); const pending = rt.pending.get(requestId); - if (!pending) throw new ApiError("not_found", "\u6388\u6743/\u63D0\u95EE\u4E0D\u5B58\u5728\u6216\u5DF2\u56DE\u5E94"); + if (!pending) throw new ApiError("not_found", tr("err.requestGone")); if (pending.kind === "permission" && answer.optionId) { const valid = pending.options.some((o) => o.id === answer.optionId); - if (!valid) throw new ApiError("bad_params", `optionId \u975E\u6CD5\uFF1A${answer.optionId}`); + if (!valid) throw new ApiError("bad_params", tr("err.badOption", { id: String(answer.optionId) })); } rt.pending.delete(requestId); if (pending.kind === "permission") { @@ -6967,8 +7445,8 @@ var AgentManager = class { async interrupt(threadId) { const rt = this.rt(threadId); if (!rt.session || rt.status !== "running") return; - for (const [id, p] of rt.pending) { - await this.appendRaw(threadId, { type: "permission_resolved", requestId: id, cancelled: true }); + for (const [id2, p] of rt.pending) { + await this.appendRaw(threadId, { type: "permission_resolved", requestId: id2, cancelled: true }); p.resolve({ cancelled: true }); } rt.pending.clear(); @@ -7006,10 +7484,10 @@ var AgentManager = class { if (rt.session) await rt.session.setModel(model); this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) }); } - async setMode(threadId, mode) { - await this.threads.patch(threadId, { mode }); + async setMode(threadId, mode2) { + await this.threads.patch(threadId, { mode: mode2 }); const rt = this.rt(threadId); - if (rt.session) await rt.session.setMode(mode); + if (rt.session) await rt.session.setMode(mode2); this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) }); } async setEffort(threadId, effort) { @@ -7028,7 +7506,7 @@ var AgentManager = class { } async setCursorOpts(threadId, patch) { const meta = await this.mustThread(threadId); - if (meta.provider !== "cursor") throw new ApiError("bad_params", "\u4EC5 Cursor \u5BF9\u8BDD\u652F\u6301\u8BE5\u9009\u9879"); + if (meta.provider !== "cursor") throw new ApiError("bad_params", tr("err.cursorOnly")); const next = await this.threads.patch(threadId, patch); const rt = this.rt(threadId); const sess = rt.session; @@ -7041,14 +7519,14 @@ var AgentManager = class { async setProvider(threadId, providerId) { await this.mustThread(threadId); const meta = await this.threads.get(threadId); - if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); + if (!meta) throw new ApiError("not_found", tr("err.threadMissing")); const rt = this.rt(threadId); if (rt.status === "running" || rt.status === "initializing" || rt.starting) { - throw new ApiError("busy", "\u5BF9\u8BDD\u8FD0\u884C\u4E2D\uFF0C\u4E0D\u80FD\u66F4\u6362 Agent"); + throw new ApiError("busy", tr("err.busySwitch")); } const events = await this.threads.readEvents(threadId, 0, 5e3); if (events.some((e) => e.type === "user_message")) { - throw new ApiError("bad_params", "\u5DF2\u6709\u6D88\u606F\uFF0C\u4E0D\u80FD\u66F4\u6362 Agent"); + throw new ApiError("bad_params", tr("err.hasMessages")); } const p = await this.assertProviderUsable(providerId); if (rt.session) { @@ -7063,7 +7541,7 @@ var AgentManager = class { await this.threads.patch(threadId, { provider: providerId, model: null, - mode: p.capabilities.modes.includes(meta.mode) ? meta.mode : p.capabilities.modes[0] ?? "default", + mode: clampMode(p.capabilities.modes, meta.mode), effort: null, providerSessionId: null, status: "idle" @@ -7166,7 +7644,7 @@ var AgentManager = class { if (rt.session) return rt.session; const provider = await this.assertProviderUsable(meta.provider, { allowDisabled: !!meta.providerSessionId }); const proj = await this.projects.get(meta.projectId); - if (!proj) throw new ApiError("not_found", "\u9879\u76EE\u4E0D\u5B58\u5728"); + if (!proj) throw new ApiError("not_found", tr("err.projectMissing")); let model = meta.model; if (meta.provider === "dsh" && model) { const available = await cachedModels(provider).catch(() => []); @@ -7182,13 +7660,13 @@ var AgentManager = class { } if (opts.updateStatus) await this.setStatus(threadId, "initializing"); const settings = await this.settings.get(); - const custom = settings.providerCommand?.[meta.provider]; - const launch = custom?.executable?.trim() ? { cmd: custom.executable.trim(), prefixArgs: custom.args ?? [] } : void 0; + const launch = launchFromSettings(settings, meta.provider); + rt.deltasOnly = !!provider.capabilities.deltasOnly; rt.session = await provider.createSession({ threadId, cwd: proj.path, model, - mode: meta.mode, + mode: clampMode(provider.capabilities.modes, meta.mode), effort: meta.effort, resumeId: meta.providerSessionId, cursorFast: meta.cursorFast, @@ -7206,7 +7684,7 @@ var AgentManager = class { // ---- internals ---- async mustThread(threadId) { const meta = await this.threads.get(threadId); - if (!meta) throw new ApiError("not_found", "\u5BF9\u8BDD\u4E0D\u5B58\u5728"); + if (!meta) throw new ApiError("not_found", tr("err.threadMissing")); return meta; } providerOf(meta) { @@ -7214,17 +7692,17 @@ var AgentManager = class { } async assertProviderUsable(providerId, opts = {}) { const p = getProvider(providerId); - if (!p) throw new ApiError("bad_params", `\u672A\u77E5 Agent\uFF1A${providerId}`); + if (!p) throw new ApiError("bad_params", tr("provider.unknown", { id: providerId })); const s = await this.settings.get(); if (!opts.allowDisabled && !isProviderEnabled(s, providerId)) { - throw new ApiError("bad_params", `${p.name} \u5DF2\u5728\u8BBE\u7F6E\u4E2D\u7981\u7528`); + throw new ApiError("bad_params", tr("provider.disabledNamed", { name: p.name })); } const entry = catalogById(providerId); if (entry && !providerCreatable(entry.status)) { - throw new ApiError("bad_params", `${p.name} \u5C1A\u672A\u63A5\u5165\uFF0C\u6682\u4E0D\u80FD\u65B0\u5EFA\u5BF9\u8BDD`); + throw new ApiError("bad_params", tr("provider.plannedNamed", { name: p.name })); } - const det = await cachedDetect(p); - if (!det.available) throw new ApiError("bad_params", det.reason ?? `${p.name} \u672A\u5B89\u88C5\u6216\u4E0D\u53EF\u7528`); + const det = await cachedDetect(p, launchFromSettings(s, providerId)); + if (!det.available) throw new ApiError("bad_params", det.reason ?? tr("provider.unavailable", { name: p.name })); return p; } async setStatus(threadId, status) { @@ -7246,23 +7724,41 @@ var AgentManager = class { const full = { ...ev, seq: -1, ts: Date.now(), threadId }; this.gw.publish(`thread:${threadId}`, { type: "event", event: full }); } + /** B17: idle Agent processes are closed after idleCloseMinutes, and at most MAX_WARM_IDLE of them stay warm + * (least recently used go first). A running turn, one starting, or one waiting on an approval is never touched. */ + recycling = false; async recycleIdle() { - const s = await this.settings.get(); - const limit = (s.idleCloseMinutes ?? 30) * 6e4; - for (const rt of this.runtimes.values()) { - if (rt.status === "idle" && rt.pending.size === 0 && Date.now() - rt.lastActivity > limit) { - log("info", `\u7A7A\u95F2\u56DE\u6536 thread ${rt.threadId}`); - await this.close(rt.threadId); + if (this.recycling) return; + this.recycling = true; + try { + const s = await this.settings.get(); + const minutes = Number(s.idleCloseMinutes); + const limit = (Number.isFinite(minutes) && minutes > 0 ? minutes : 30) * 6e4; + const idle = [...this.runtimes.values()].filter((rt) => rt.session && rt.status === "idle" && !rt.starting && !rt.sessionCreating && rt.pending.size === 0 && rt.queue.length === 0).sort((a, b) => b.lastActivity - a.lastActivity); + const now = Date.now(); + for (const [i, rt] of idle.entries()) { + const expired = now - rt.lastActivity > limit; + if (!expired && i < MAX_WARM_IDLE) continue; + log("info", `idle cleanup: closing thread ${rt.threadId} (${expired ? "idle timeout" : "over the warm limit"})`); + try { + await this.close(rt.threadId); + } catch (e) { + log("info", `idle cleanup: thread ${rt.threadId}: ${String(e?.message ?? e)}`); + this.runtimes.delete(rt.threadId); + } } + } finally { + this.recycling = false; } } }; // 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 readFile15, rename as rename4, rm, stat as stat9 } from "node:fs/promises"; -import { join as join15, normalize as normalize2, sep as sep2 } from "node:path"; +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"; var TIMEOUT2 = 15e3; var DIFF_LIMIT = 1024 * 1024; function runGit(cwd, args) { @@ -7270,13 +7766,13 @@ function runGit(cwd, args) { execFile4("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 ? "\u627E\u4E0D\u5230 git\uFF08\u8BF7\u5148\u5B89\u88C5 git \u5E76\u52A0\u5165 PATH\uFF09" : String(stderr || (e?.message ?? "")) }); + res({ code, out: String(stdout ?? ""), err: missing ? tr("git.missing") : String(stderr || (e?.message ?? "")) }); }); }); } function insidePath(projectPath, p) { const rel = normalize2(p).replace(/\\/g, "/"); - const abs = normalize2(join15(projectPath, rel)); + const abs = normalize2(join16(projectPath, rel)); const proj = normalize2(projectPath); if (abs !== proj && !abs.startsWith(proj + sep2)) return null; return rel.replace(/\\/g, "/"); @@ -7322,16 +7818,16 @@ var GitService = class { // Unified diff text; {tooLarge:true} when the diff is > 1MB async diff(projectPath, p) { const rel = insidePath(projectPath, p); - if (!rel) return { error: "\u8DEF\u5F84\u4E0D\u5141\u8BB8" }; + if (!rel) return { error: tr("fs.pathDenied") }; const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]); if (ls.code !== 0) { - const full = join15(projectPath, rel); - if (!existsSync10(full)) return { error: "\u6587\u4EF6\u4E0D\u5B58\u5728" }; + const full = join16(projectPath, rel); + if (!existsSync10(full)) return { error: tr("fs.fileMissing") }; const s = await stat9(full); - if (!s.isFile()) return { error: "\u4E0D\u662F\u6587\u4EF6" }; + if (!s.isFile()) return { error: tr("fs.notFile") }; if (s.size > DIFF_LIMIT) return { tooLarge: true }; - const text = await readFile15(full, "utf8").catch(() => null); - if (text === null) return { error: "\u4E8C\u8FDB\u5236\u6216\u65E0\u6CD5\u8BFB\u53D6" }; + const text = await readFile16(full, "utf8").catch(() => null); + if (text === null) return { error: tr("git.binary") }; const lines = text.split("\n").map((l) => "+" + l).join("\n"); return { untracked: true, diff: `--- /dev/null +++ b/${rel} @@ -7350,8 +7846,8 @@ ${lines}` }; // Tracked → git restore; untracked → move to trash/discarded// async discard(projectPath, p, dataDir) { const rel = insidePath(projectPath, p); - if (!rel) return { ok: false, error: "\u8DEF\u5F84\u4E0D\u5141\u8BB8" }; - if (rel === "." || rel === "" || rel === "./") return { ok: false, error: "\u8DEF\u5F84\u4E0D\u5141\u8BB8" }; + if (!rel) return { ok: false, error: tr("fs.pathDenied") }; + if (rel === "." || rel === "" || rel === "./") return { ok: false, error: tr("fs.pathDenied") }; const ls = await runGit(projectPath, ["ls-files", "--error-unmatch", "--", rel]); if (ls.code === 0) { let r = await runGit(projectPath, ["restore", "--staged", "--worktree", "--", rel]); @@ -7359,11 +7855,11 @@ ${lines}` }; if (r.code !== 0) return { ok: false, error: r.err.trim() || "\u653E\u5F03\u5931\u8D25" }; return { ok: true }; } - const full = join15(projectPath, rel); - if (!existsSync10(full)) return { ok: false, error: "\u6587\u4EF6\u4E0D\u5B58\u5728" }; + const full = join16(projectPath, rel); + if (!existsSync10(full)) return { ok: false, error: tr("fs.fileMissing") }; const stamp2 = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19); - const dest = join15(dataDir, "trash", "discarded", stamp2, rel); - await mkdir7(join15(dest, ".."), { recursive: true }); + const dest = join16(dataDir, "trash", "discarded", stamp2, rel); + await mkdir7(join16(dest, ".."), { recursive: true }); try { await moveAcrossDevices(full, dest); } catch (e) { @@ -7374,8 +7870,9 @@ ${lines}` }; }; // daemon/src/files/service.ts -import { readdir as readdir5, readFile as readFile16, stat as stat10 } from "node:fs/promises"; -import { join as join16, normalize as normalize3, sep as sep3, extname as extname3 } from "node:path"; +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 ignore from "ignore"; function decodeText(buf) { try { @@ -7438,7 +7935,7 @@ var LANG = { }; function insidePath2(projectPath, p) { const rel = normalize3(p || ".").replace(/\\/g, "/"); - const abs = normalize3(join16(projectPath, rel)); + const abs = normalize3(join17(projectPath, rel)); const proj = normalize3(projectPath); if (abs !== proj && !abs.startsWith(proj + sep3)) return null; return rel; @@ -7448,7 +7945,7 @@ var FileService = class { // Invalidate by .gitignore mtime: an edited .gitignore takes effect the next time a directory is expanded igCache = /* @__PURE__ */ new Map(); async igFor(projectPath) { - const gi = join16(projectPath, ".gitignore"); + const gi = join17(projectPath, ".gitignore"); const st = await stat10(gi).catch(() => null); const mtime = st?.isFile() ? st.mtimeMs : -1; const hit = this.igCache.get(projectPath); @@ -7456,7 +7953,7 @@ var FileService = class { let ig = null; if (mtime >= 0) { try { - ig = ignore().add(await readFile16(gi, "utf8")); + ig = ignore().add(await readFile17(gi, "utf8")); } catch { ig = null; } @@ -7466,13 +7963,13 @@ var FileService = class { } async tree(projectPath, dir) { const rel = insidePath2(projectPath, dir); - if (rel === null) return { error: "\u8DEF\u5F84\u4E0D\u5141\u8BB8" }; - const abs = join16(projectPath, rel); + if (rel === null) return { error: tr("fs.pathDenied") }; + const abs = join17(projectPath, rel); const s = await stat10(abs).catch(() => null); - if (!s?.isDirectory()) return { error: "\u76EE\u5F55\u4E0D\u5B58\u5728" }; + if (!s?.isDirectory()) return { error: tr("fs.dirMissing") }; const ig = await this.igFor(projectPath); const dirents = await readdir5(abs, { withFileTypes: true }).catch(() => null); - if (!dirents) return { error: "\u65E0\u6CD5\u8BFB\u53D6\u76EE\u5F55" }; + if (!dirents) return { error: tr("fs.dirUnreadable") }; const out = []; for (const d of dirents) { if (out.length >= MAX_PER_LEVEL) break; @@ -7481,7 +7978,7 @@ var FileService = class { const childRel = rel === "." ? name : `${rel}/${name}`; let isDir2 = d.isDirectory(); if (d.isSymbolicLink()) { - const st = await stat10(join16(projectPath, childRel)).catch(() => null); + const st = await stat10(join17(projectPath, childRel)).catch(() => null); if (!st) continue; isDir2 = st.isDirectory(); } else if (!d.isFile() && !isDir2) { @@ -7497,14 +7994,14 @@ var FileService = class { } async read(projectPath, p) { const rel = insidePath2(projectPath, p); - if (rel === null) return { error: "\u8DEF\u5F84\u4E0D\u5141\u8BB8" }; - const abs = join16(projectPath, rel); + if (rel === null) return { error: tr("fs.pathDenied") }; + const abs = join17(projectPath, rel); const s = await stat10(abs).catch(() => null); - if (!s) return { error: "\u6587\u4EF6\u4E0D\u5B58\u5728" }; - if (!s.isFile()) return { error: "\u4E0D\u662F\u6587\u4EF6" }; + if (!s) return { error: tr("fs.fileMissing") }; + if (!s.isFile()) return { error: tr("fs.notFile") }; if (s.size > MAX_READ) return { tooLarge: true }; - const buf = await readFile16(abs).catch(() => null); - if (!buf) return { error: "\u65E0\u6CD5\u8BFB\u53D6" }; + const buf = await readFile17(abs).catch(() => null); + if (!buf) return { error: tr("fs.unreadable") }; const head = buf.subarray(0, 8192); if (head.includes(0)) return { binary: true }; const { text, encoding } = decodeText(buf); @@ -7515,11 +8012,12 @@ var FileService = class { // daemon/src/terminal/service.ts 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 { createRequire as moduleRequire } from "node:module"; import { release } from "node:os"; -import { dirname as dirname6, join as join17 } from "node:path"; +import { dirname as dirname6, join as join18 } from "node:path"; import { StringDecoder } from "node:string_decoder"; var MAX_TERMS_PER_PROJECT = 8; var BUF_MAX = 2 * 1024 * 1024; @@ -7565,7 +8063,7 @@ function fixSpawnHelper() { const req = moduleRequire(import.meta.url); const root = dirname6(req.resolve("node-pty/package.json")); for (const sub of [`prebuilds/darwin-${process.arch}`, "build/Release"]) { - const f = join17(root, sub, "spawn-helper"); + const f = join18(root, sub, "spawn-helper"); if (existsSync11(f) && !isExecFile(f)) { chmodSync(f, 493); log("info", "\u5DF2\u4FEE\u590D node-pty spawn-helper \u7684\u53EF\u6267\u884C\u4F4D", { file: f }); @@ -7608,14 +8106,14 @@ var TerminalService = class { } async create(projectId, cwd, cols, rows) { const alive = [...this.terms.values()].filter((t) => t.projectId === projectId && t.alive); - if (alive.length >= MAX_TERMS_PER_PROJECT) return { error: `\u6BCF\u4E2A\u9879\u76EE\u6700\u591A ${MAX_TERMS_PER_PROJECT} \u4E2A\u7EC8\u7AEF` }; + if (alive.length >= MAX_TERMS_PER_PROJECT) return { error: tr("term.max", { n: MAX_TERMS_PER_PROJECT }) }; const shell = pickShell(); const term = { id: rid5(), index: nextIndex++, projectId, cwd, - title: `\u7EC8\u7AEF ${alive.length + 1}`, + title: tr("term.title", { n: alive.length + 1 }), alive: true, simple: false, pty: null, @@ -7663,25 +8161,25 @@ var TerminalService = class { this.byIndex.set(term.index, term); return { id: term.id, index: term.index, simple: term.simple }; } - attach(id) { - const t = this.terms.get(id); - if (!t) return { error: "\u7EC8\u7AEF\u4E0D\u5B58\u5728" }; + attach(id2) { + const t = this.terms.get(id2); + if (!t) return { error: tr("err.terminalMissing") }; const lines = t.buf.split("\n"); const snapshot = lines.length > SNAP_LINES ? lines.slice(-SNAP_LINES).join("\n") : t.buf; const windowsPty = process.platform === "win32" && t.pty ? conptyInfo() : void 0; return { index: t.index, snapshot, simple: t.simple, ...windowsPty ? { windowsPty } : {} }; } - indexOf(id) { - return this.terms.get(id)?.index ?? null; + indexOf(id2) { + return this.terms.get(id2)?.index ?? null; } - resize(id, cols, rows) { - const t = this.terms.get(id); + resize(id2, cols, rows) { + const t = this.terms.get(id2); if (!t || !t.alive) return { ok: false }; t.pty?.resize(Math.max(20, cols), Math.max(5, rows)); return { ok: true }; } - kill(id) { - const t = this.terms.get(id); + kill(id2) { + const t = this.terms.get(id2); if (!t) return { ok: false }; this.killTerm(t); return { ok: true }; @@ -7821,6 +8319,7 @@ if (nodeMajor < 20) { process.env.PATH = augmentPath(process.env, dirname7(process.execPath)); var cfg = parseConfig(process.argv.slice(2)); process.on("uncaughtException", (e) => { + if (e?.code === "EPIPE") return; log("error", "uncaughtException", { err: String(e?.stack ?? e) }); }); process.on("unhandledRejection", (e) => { @@ -7829,10 +8328,10 @@ process.on("unhandledRejection", (e) => { async function main() { initLog(cfg.dataDir); for (const d of ["threads", "attachments", "trash", "logs"]) { - mkdirSync2(join19(cfg.dataDir, d), { recursive: true }); + mkdirSync2(join20(cfg.dataDir, d), { recursive: true }); } - const appDir = join19(dirname7(fileURLToPath3(import.meta.url)), "..", "..", "app"); - const attachments = new AttachmentStore(join19(cfg.dataDir, "attachments")); + const appDir = join20(dirname7(fileURLToPath3(import.meta.url)), "..", "..", "app"); + const attachments = new AttachmentStore(join20(cfg.dataDir, "attachments")); const { bindAttachmentStore: bindAttachmentStore2 } = await Promise.resolve().then(() => (init_attachmentRefs(), attachmentRefs_exports)); bindAttachmentStore2(attachments); const settings = new SettingsStore(cfg.dataDir); @@ -7859,7 +8358,7 @@ async function main() { git: new GitService(), files: new FileService(), terminals, - runtime: (id) => manager.runtimeInfo(id) + runtime: (id2) => manager.runtimeInfo(id2) }); const server = createHttpServer(cfg, appDir, attachments, { onUpgrade: (req, socket, head) => gateway.handleUpgrade(req, socket, head) @@ -7891,7 +8390,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 = join19(cfg.dataDir, "daemon.json"); + const daemonJsonPath = join20(cfg.dataDir, "daemon.json"); await writeJsonAtomic(daemonJsonPath, { pid: process.pid, port: cfg.port, @@ -7902,7 +8401,9 @@ async function main() { }); chmodSync2(daemonJsonPath, 384); log("info", `daemon \u5DF2\u542F\u52A8 \u7AEF\u53E3 ${cfg.port} \u6570\u636E\u76EE\u5F55 ${cfg.dataDir} \u7248\u672C ${cfg.version} pid ${process.pid}`); - if (!cfg.parentPid) console.log(`[agent-console] \u6253\u5F00 http://127.0.0.1:${cfg.port}/#t=${cfg.token}`); + if (!cfg.parentPid) { + console.log(process.stdout.isTTY ? `[agent-console] open http://127.0.0.1:${cfg.port}/#t=${cfg.token}` : `[agent-console] listening on http://127.0.0.1:${cfg.port}/ (token not printed: stdout is not a terminal)`); + } let idleSince = Date.now(); setInterval(() => { const busy = gateway.connectionCount > 0 || manager.anyBusy() || terminals.count > 0; @@ -7939,9 +8440,16 @@ async function main() { } }, 2e3); parentWatch.unref(); - process.stdin.on("end", () => shutdown(0)); - process.stdin.on("close", () => shutdown(0)); - process.stdin.on("error", () => shutdown(0)); + let lifelineGone = false; + const lifelineClosed = () => { + if (lifelineGone) return; + lifelineGone = true; + log("info", "plugin host closed the lifeline (stdin); daemon exiting with it"); + shutdown(0); + }; + process.stdin.on("end", lifelineClosed); + process.stdin.on("close", lifelineClosed); + process.stdin.on("error", lifelineClosed); process.stdin.resume(); } } diff --git a/packages/agent-console/daemon/dist/main.js.map b/packages/agent-console/daemon/dist/main.js.map index 8d1a75d..845c420 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/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/i18n.ts","../src/util/attachmentRefs.ts","../src/util/attachmentKinds.ts","../src/providers/claude/content.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/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/ws/methods.ts","../src/util/atomic.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/settings.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\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 const fn = level === \"error\" ? console.error : level === \"warn\" ? console.warn : console.log;\n fn(`[agent-console] ${msg}`, extra !== undefined ? extra : \"\");\n}\n\nfunction safeJson(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\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 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: \"允许\", kind: \"allow_once\" },\n { id: \"acceptForSession\", label: \"本对话都允许\", kind: \"allow_always\" },\n { id: \"decline\", label: \"拒绝\", 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: \"拒绝\", 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\";\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: `PATH 里找不到 ${uniq.length > 1 ? uniq.join(\" 或 \") : 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: `PATH 里找不到 ${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\";\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\", `读取 ${relPath(file, cwd)}`, { path: file, offset: input.offset, limit: input.limit });\n case \"Edit\":\n return f(\"edit\", `编辑 ${relPath(file, cwd)}`, { path: file, old: input.old_string, new: input.new_string });\n case \"MultiEdit\":\n return f(\"edit\", `编辑 ${relPath(file, cwd)}(${((input.edits as unknown[]) || []).length} 处)`, { path: file, edits: input.edits ?? [] });\n case \"Write\":\n return f(\"write\", `${input._exists ? \"覆盖\" : \"新建\"} ${relPath(file, cwd)}`, { path: file, content: input.content });\n case \"NotebookEdit\":\n return f(\"edit\", `编辑笔记本 ${relPath(String(input.notebook_path || file), cwd)}`, { path: input.notebook_path ?? file });\n case \"Bash\":\n return f(\"bash\", `运行 ${trunc(String(input.command ?? \"\"))}`, { command: input.command, description: input.description });\n case \"BashOutput\":\n return f(\"bash\", `查看输出 ${String(input.bash_id ?? \"\")}`, { bashId: input.bash_id });\n case \"KillShell\":\n return f(\"bash\", `结束进程 ${String(input.shell_id ?? \"\")}`, { shellId: input.shell_id });\n case \"Grep\":\n return f(\"search\", `搜索 \"${trunc(String(input.pattern ?? \"\"), 40)}\"`, { pattern: input.pattern, path: input.path, glob: input.glob });\n case \"Glob\":\n case \"LS\":\n return f(\"glob\", `查找 ${trunc(String(input.pattern ?? input.path ?? \"\"), 40)}`, { pattern: input.pattern, path: input.path });\n case \"WebFetch\":\n return f(\"web\", `打开 ${hostOf(String(input.url ?? \"\"))}`, { url: input.url });\n case \"WebSearch\":\n return f(\"web\", `搜索网页 \"${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\", `更新待办(${done}/${items.length})`, { items });\n }\n case \"Task\":\n case \"Agent\":\n return f(\"task\", `子任务:${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 || \"工具\", {});\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\";\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\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: `API 重试中(第 ${r.attempt ?? \"?\"} 次)` });\n }\n if (r.subtype === \"compact_boundary\") {\n out.push({ type: \"notice\", level: \"info\", message: \"上下文已压缩\" });\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\" ? 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","/** 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 },\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 },\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","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","// 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 { 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};\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 = claudeArgs(o);\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 { 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 /** 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 },\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: \"允许\", kind: \"allow_once\" },\n { id: \"allow_always\", label: \"本对话都允许\", kind: \"allow_always\" },\n { id: \"deny\", label: \"拒绝\", 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: \"已取消\", 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: \"用户拒绝了此操作\", ...(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: \"Agent 提交了计划\",\n kind: \"plan\",\n detail: { plan: planText },\n options: [\n { id: \"implement\", label: \"实施\", kind: \"allow_once\" },\n { id: \"reject\", label: \"拒绝\", 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: \"用户拒绝了计划,请根据反馈修改\", ...(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: \"用户取消了提问\", 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\";\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 || \"(无标题)\",\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 } 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\";\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(): Provider {\n return {\n id: \"claude\",\n name: \"Claude Code\",\n capabilities: claudeCapabilities,\n async detect(): Promise {\n const bin = await resolveBin(\"claude\");\n if (!bin.ok) return { available: false, reason: bin.reason, installHint: INSTALL_HINT };\n try {\n const version = await runVersion(bin, [\"--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 = await resolveBin(\"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 });\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\";\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 || \"(无标题)\", 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: `(历史)调用 ${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: `(历史)调用 ${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\";\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};\n\nexport function newCodexMapState(): CodexMapState {\n return { currentTurnId: null, filesChanged: 0, diffText: \"\" };\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 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) out.push({ type: \"reasoning_delta\", itemId, text: delta });\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: `运行 ${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 out.push({\n type: \"tool_call\", itemId, kind: \"edit\",\n title: `修改 ${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: `搜索网页 \"${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 text = summary.filter((s): s is string => typeof s === \"string\").join(\"\\n\");\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: `运行 ${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 const istatus = str(item.status);\n st.filesChanged += changes.length;\n out.push({\n type: \"tool_call\", itemId, kind: \"edit\",\n title: `修改 ${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: `搜索网页 \"${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) ?? \"Codex 错误\";\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 { 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\";\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 },\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 [\"app-server\"],\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(\"会话已关闭\");\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(\"当前轮次还没开始,无法插话\");\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: `运行 ${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: \"允许\", kind: \"allow_once\" },\n { id: \"acceptForSession\", label: \"本对话都允许\", kind: \"allow_always\" },\n { id: \"decline\", label: \"拒绝\", 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 changes = Array.isArray(params.changes) ? params.changes : [];\n const requestId = \"perm_\" + rid();\n this.emit({\n type: \"permission_request\",\n requestId,\n title: \"修改文件\",\n kind: \"tool\",\n detail: { changes, approvalId: params.approvalId, itemId: params.itemId, reason: params.reason },\n options: [\n { id: \"accept\", label: \"允许\", kind: \"allow_once\" },\n { id: \"acceptForSession\", label: \"本对话都允许\", kind: \"allow_always\" },\n { id: \"decline\", label: \"拒绝\", 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","// Codex Provider (§7.3): detect + listModels (temporary app-server → model/list, cached 10 minutes) + createSession.\nimport type { Provider, ProviderSession, DetectResult, ModelInfo, Capabilities, HistoryItem } 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\";\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 modes: [\"plan\", \"default\", \"acceptEdits\", \"bypassPermissions\"],\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): Promise {\n const rpc = new CodexRpc(argvFor(r, [\"app-server\"]), { 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 function createCodexProvider(version: string): Provider {\n return {\n id: \"codex\",\n name: \"Codex\",\n capabilities: codexCapabilities,\n async detect(): Promise {\n const bin = 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, [\"--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(): Promise {\n if (modelCache && Date.now() - modelCache.at < MODEL_CACHE_MS) return modelCache.models;\n const bin = await resolveBin(\"codex\");\n if (!bin.ok) return [{ id: \"\", name: \"默认\" }];\n try {\n const models = await fetchModels(bin, process.cwd());\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: \"默认\" }];\n }\n },\n async createSession(o): Promise {\n const bin = await resolveBin(\"codex\");\n if (!bin.ok) throw new Error(`找不到 codex:${bin.reason}`);\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 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","/** 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: \"见 OpenAI Codex CLI 安装说明\", status: \"verified\" },\n { id: \"cursor\", name: \"Cursor\", bins: [\"cursor-agent\", \"cursor\"], installHint: \"安装 Cursor 并确保 CLI 在 PATH\", status: \"verified\" },\n { id: \"copilot\", name: \"Copilot\", bins: [\"copilot\"], installHint: \"GitHub Copilot CLI 安装说明\", status: \"verified\" },\n { id: \"opencode\", name: \"OpenCode\", bins: [\"opencode\"], installHint: \"npm i -g opencode / 见 OpenCode 文档\", status: \"verified\" },\n { id: \"pi\", name: \"Pi\", bins: [\"pi-acp\", \"pi\", \"pi-coding-agent\"], installHint: \"npm i -g pi-acp(或 Pi coding agent + ACP 适配器)\", status: \"verified\" },\n { id: \"devin\", name: \"Devin CLI\", bins: [\"devin\"], installHint: \"Devin 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\";\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 ?? \"需要授权\",\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\nexport type MapCtx = { itemPrefix: string; messageIds: Map };\n\nexport function newMapCtx(): MapCtx {\n return { itemPrefix: \"a\" + rid() + \"_\", messageIds: new Map() };\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 = mid ? ctx.messageIds.get(mid) ?? ctx.itemPrefix + mid : ctx.itemPrefix + \"msg\";\n if (mid) ctx.messageIds.set(mid, itemId);\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 = mid ? ctx.itemPrefix + \"t_\" + mid : ctx.itemPrefix + \"think\";\n out.push({ type: \"reasoning_delta\", itemId, text });\n break;\n }\n case \"tool_call\":\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 out.push({\n type: \"tool_call\",\n itemId: ctx.itemPrefix + update.toolCallId,\n kind: mapToolKind(update.kind),\n title: update.title ?? update.name ?? \"tool\",\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 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 { 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 { 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?: { cmd: string; prefixArgs: string[] };\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 ? ({\n ok: true as const,\n cmd: this.o.launch.cmd,\n prefixArgs: this.o.launch.prefixArgs,\n display: this.o.launch.cmd,\n via: \"custom\",\n binName: \"custom\",\n } satisfies ResolveResult & { ok: true; binName: string })\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, this.o.acpArgs, { 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: `${this.o.binName} 进程退出 (${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 } from \"../types.js\";\nimport { killTree, spawnBin, type ResolveResult } from \"../../util/bin.js\";\nimport { resolveFirstBin } from \"../../util/bin.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 }) => 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};\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(): Promise {\n const r = await resolveProviderBin(cfg);\n if (!r.ok) {\n return { available: false, reason: r.reason, installHint: cfg.installHint };\n }\n let version: string | undefined;\n try {\n if (cfg.id === \"cursor\") {\n version = (await runVersion(r, [\"--version\"])).split(/\\r?\\n/)[0]?.trim();\n } else if (cfg.id === \"devin\") {\n version = (await runVersion(r, [\"version\"])).split(/\\r?\\n/)[0]?.trim();\n } else if (cfg.id === \"opencode\") {\n version = (await runVersion(r, [\"--version\"])).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(): Promise {\n const r = await resolveProviderBin(cfg);\n if (!r.ok) return [{ id: \"default\", name: \"默认\", isDefault: true }];\n if (cfg.fetchModels) return cfg.fetchModels(r);\n return [{ id: \"default\", 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 }): Promise => {\n try {\n const { parsed, ext, promptCaps } = await probeAcpRaw(r, acpArgs, 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 }): Promise => {\n try {\n const first = await probeAcpRaw(r, DSH_ACP_ARGS, 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), 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 }): Promise => {\n try {\n return probeToModels(await probeAcp(r, acpArgs, 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 } from \"./types.js\";\nimport { withMagpie } from \"./magpieGateway.js\";\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\nexport async function cachedDetect(p: Provider): Promise {\n const hit = detects.get(p.id);\n if (fresh(hit, DETECT_MS)) return hit.value;\n let job = inflightDetect.get(p.id);\n if (!job) {\n job = withTimeout(\n p.detect().catch((e): DetectResult => ({ available: false, reason: String((e as Error)?.message ?? e) })),\n STEP_TIMEOUT_MS,\n { available: false, reason: \"检测超时\" },\n ).then((v) => {\n // Don't cache a timeout; try again next time\n if (v.reason !== \"检测超时\") detects.set(p.id, { at: Date.now(), value: v });\n return v;\n }).finally(() => inflightDetect.delete(p.id));\n inflightDetect.set(p.id, job);\n }\n return job;\n}\n\nexport async function cachedModels(p: Provider): Promise {\n const hit = models.get(p.id);\n if (fresh(hit, MODELS_MS)) return hit.value;\n let job = inflightModels.get(p.id);\n if (!job) {\n job = withTimeout(p.listModels().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(p.id)?.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(p.id, { at: Date.now(), value: list });\n return list;\n })\n .finally(() => inflightModels.delete(p.id));\n inflightModels.set(p.id, 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 === \"默认\") 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 detects.delete(id);\n models.delete(id);\n } else {\n detects.clear();\n models.clear();\n }\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 } 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\";\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;\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 };\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\", \"参数不对:\" + 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()) }), (p) =>\n svc.settings.set(p.patch)\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 // 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 ? \"已在设置中禁用\" : \"尚未接入\" }\n : await cachedDetect(p);\n const models = !skip && det.available ? await cachedModels(p) : [];\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 ? \"已在设置中禁用\" : 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\", \"项目不存在\");\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\", \"项目不存在\");\n if (!existsSync(proj.path)) throw new ApiError(\"bad_path\", \"目录不存在或不是文件夹\");\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\", \"项目不存在\");\n if (!existsSync(proj.path)) throw new ApiError(\"bad_path\", \"项目目录已不存在\");\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\", \"该 Agent 已在设置中禁用\");\n }\n const cat = catalogById(p.provider);\n if (!p.providerSessionId && cat && !providerCreatable(cat.status)) {\n throw new ApiError(\"bad_params\", `${cat.name} 尚未接入,暂不能新建对话`);\n }\n const meta = await svc.threads.create(p);\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\", \"对话不存在\");\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\", \"对话不存在\");\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\", \"对话不存在\");\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\", \"项目不存在\");\n if (!existsSync(proj.path)) throw new ApiError(\"bad_path\", \"项目目录已不存在\");\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\", \"项目不存在\");\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\", \"项目不存在\");\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 ?? \"终端不存在\");\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\", \"会话管理器未启动\");\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 await needManager().send(p.id, { text: p.text, attachments: p.attachments }, p.behavior ?? \"queue\");\n return { ok: true };\n }\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\", \"对话不存在\");\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 ?? \"默认\"} · ${meta.mode} · ${new Date(meta.createdAt).toLocaleString(\"zh-CN\")}`, \"\");\n for (const e of events) {\n switch (e.type) {\n case \"user_message\": L.push(`**我**${e.steered ? \"(插话)\" : \"\"}:\\n\\n${e.text}`, \"\"); break;\n case \"assistant_message\": L.push(e.text, \"\"); break;\n case \"reasoning\": L.push(`
思考\\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(\"### 计划\\n\\n\" + e.markdown, \"\"); break;\n case \"todo\": L.push(\"### 待办\\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 const dir = join(homedir(), \"Downloads\");\n await mkdir(dir, { recursive: true });\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","// 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 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 if (!cfg.parentPid) console.log(`[agent-console] 打开 http://127.0.0.1:${cfg.port}/#t=${cfg.token}`);\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 process.stdin.on(\"end\", () => shutdown(0));\n process.stdin.on(\"close\", () => shutdown(0));\n process.stdin.on(\"error\", () => shutdown(0));\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\";\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: \"服务内部错误\" } });\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: \"来源不允许\" } });\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: \"预检不允许\" } });\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: \"令牌无效\" } });\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: \"附件不存在\" } });\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