@chroxy/server 0.11.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +207 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const d of o)if(d.type==="childList")for(const h of d.addedNodes)h.tagName==="LINK"&&h.rel==="modulepreload"&&i(h)}).observe(document,{childList:!0,subtree:!0});function n(o){const d={};return o.integrity&&(d.integrity=o.integrity),o.referrerPolicy&&(d.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?d.credentials="include":o.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function i(o){if(o.ep)return;o.ep=!0;const d=n(o);fetch(o.href,d)}})();function Um(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function $C(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function i(){var o=!1;try{o=this instanceof i}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(i){var o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(n,i,o.get?o:{enumerable:!0,get:function(){return e[i]}})}),n}var up={exports:{}},hc={};var Cb;function zC(){if(Cb)return hc;Cb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(i,o,d){var h=null;if(d!==void 0&&(h=""+d),o.key!==void 0&&(h=""+o.key),"key"in o){d={};for(var l in o)l!=="key"&&(d[l]=o[l])}else d=o;return o=d.ref,{$$typeof:e,type:i,key:h,ref:o!==void 0?o:null,props:d}}return hc.Fragment=t,hc.jsx=n,hc.jsxs=n,hc}var Eb;function UC(){return Eb||(Eb=1,up.exports=zC()),up.exports}var r=UC(),dp={exports:{}},Xt={};var Nb;function qC(){if(Nb)return Xt;Nb=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),h=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),v=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),S=Symbol.iterator;function w(B){return B===null||typeof B!="object"?null:(B=S&&B[S]||B["@@iterator"],typeof B=="function"?B:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,m={};function y(B,K,le){this.props=B,this.context=K,this.refs=m,this.updater=le||E}y.prototype.isReactComponent={},y.prototype.setState=function(B,K){if(typeof B!="object"&&typeof B!="function"&&B!=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,B,K,"setState")},y.prototype.forceUpdate=function(B){this.updater.enqueueForceUpdate(this,B,"forceUpdate")};function b(){}b.prototype=y.prototype;function _(B,K,le){this.props=B,this.context=K,this.refs=m,this.updater=le||E}var k=_.prototype=new b;k.constructor=_,x(k,y.prototype),k.isPureReactComponent=!0;var j=Array.isArray;function T(){}var D={H:null,A:null,T:null,S:null},I=Object.prototype.hasOwnProperty;function L(B,K,le){var me=le.ref;return{$$typeof:e,type:B,key:K,ref:me!==void 0?me:null,props:le}}function q(B,K){return L(B.type,K,B.props)}function H(B){return typeof B=="object"&&B!==null&&B.$$typeof===e}function Q(B){var K={"=":"=0",":":"=2"};return"$"+B.replace(/[=:]/g,function(le){return K[le]})}var F=/\/+/g;function J(B,K){return typeof B=="object"&&B!==null&&B.key!=null?Q(""+B.key):K.toString(36)}function ie(B){switch(B.status){case"fulfilled":return B.value;case"rejected":throw B.reason;default:switch(typeof B.status=="string"?B.then(T,T):(B.status="pending",B.then(function(K){B.status==="pending"&&(B.status="fulfilled",B.value=K)},function(K){B.status==="pending"&&(B.status="rejected",B.reason=K)})),B.status){case"fulfilled":return B.value;case"rejected":throw B.reason}}throw B}function X(B,K,le,me,be){var Ee=typeof B;(Ee==="undefined"||Ee==="boolean")&&(B=null);var se=!1;if(B===null)se=!0;else switch(Ee){case"bigint":case"string":case"number":se=!0;break;case"object":switch(B.$$typeof){case e:case t:se=!0;break;case v:return se=B._init,X(se(B._payload),K,le,me,be)}}if(se)return be=be(B),se=me===""?"."+J(B,0):me,j(be)?(le="",se!=null&&(le=se.replace(F,"$&/")+"/"),X(be,K,le,"",function(De){return De})):be!=null&&(H(be)&&(be=q(be,le+(be.key==null||B&&B.key===be.key?"":(""+be.key).replace(F,"$&/")+"/")+se)),K.push(be)),1;se=0;var Z=me===""?".":me+":";if(j(B))for(var ge=0;ge<B.length;ge++)me=B[ge],Ee=Z+J(me,ge),se+=X(me,K,le,Ee,be);else if(ge=w(B),typeof ge=="function")for(B=ge.call(B),ge=0;!(me=B.next()).done;)me=me.value,Ee=Z+J(me,ge++),se+=X(me,K,le,Ee,be);else if(Ee==="object"){if(typeof B.then=="function")return X(ie(B),K,le,me,be);throw K=String(B),Error("Objects are not valid as a React child (found: "+(K==="[object Object]"?"object with keys {"+Object.keys(B).join(", ")+"}":K)+"). If you meant to render a collection of children, use an array instead.")}return se}function de(B,K,le){if(B==null)return B;var me=[],be=0;return X(B,me,"","",function(Ee){return K.call(le,Ee,be++)}),me}function fe(B){if(B._status===-1){var K=B._result;K=K(),K.then(function(le){(B._status===0||B._status===-1)&&(B._status=1,B._result=le)},function(le){(B._status===0||B._status===-1)&&(B._status=2,B._result=le)}),B._status===-1&&(B._status=0,B._result=K)}if(B._status===1)return B._result.default;throw B._result}var $=typeof reportError=="function"?reportError:function(B){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var K=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof B=="object"&&B!==null&&typeof B.message=="string"?String(B.message):String(B),error:B});if(!window.dispatchEvent(K))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",B);return}console.error(B)},P={map:de,forEach:function(B,K,le){de(B,function(){K.apply(this,arguments)},le)},count:function(B){var K=0;return de(B,function(){K++}),K},toArray:function(B){return de(B,function(K){return K})||[]},only:function(B){if(!H(B))throw Error("React.Children.only expected to receive a single React element child.");return B}};return Xt.Activity=g,Xt.Children=P,Xt.Component=y,Xt.Fragment=n,Xt.Profiler=o,Xt.PureComponent=_,Xt.StrictMode=i,Xt.Suspense=u,Xt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=D,Xt.__COMPILER_RUNTIME={__proto__:null,c:function(B){return D.H.useMemoCache(B)}},Xt.cache=function(B){return function(){return B.apply(null,arguments)}},Xt.cacheSignal=function(){return null},Xt.cloneElement=function(B,K,le){if(B==null)throw Error("The argument must be a React element, but you passed "+B+".");var me=x({},B.props),be=B.key;if(K!=null)for(Ee in K.key!==void 0&&(be=""+K.key),K)!I.call(K,Ee)||Ee==="key"||Ee==="__self"||Ee==="__source"||Ee==="ref"&&K.ref===void 0||(me[Ee]=K[Ee]);var Ee=arguments.length-2;if(Ee===1)me.children=le;else if(1<Ee){for(var se=Array(Ee),Z=0;Z<Ee;Z++)se[Z]=arguments[Z+2];me.children=se}return L(B.type,be,me)},Xt.createContext=function(B){return B={$$typeof:h,_currentValue:B,_currentValue2:B,_threadCount:0,Provider:null,Consumer:null},B.Provider=B,B.Consumer={$$typeof:d,_context:B},B},Xt.createElement=function(B,K,le){var me,be={},Ee=null;if(K!=null)for(me in K.key!==void 0&&(Ee=""+K.key),K)I.call(K,me)&&me!=="key"&&me!=="__self"&&me!=="__source"&&(be[me]=K[me]);var se=arguments.length-2;if(se===1)be.children=le;else if(1<se){for(var Z=Array(se),ge=0;ge<se;ge++)Z[ge]=arguments[ge+2];be.children=Z}if(B&&B.defaultProps)for(me in se=B.defaultProps,se)be[me]===void 0&&(be[me]=se[me]);return L(B,Ee,be)},Xt.createRef=function(){return{current:null}},Xt.forwardRef=function(B){return{$$typeof:l,render:B}},Xt.isValidElement=H,Xt.lazy=function(B){return{$$typeof:v,_payload:{_status:-1,_result:B},_init:fe}},Xt.memo=function(B,K){return{$$typeof:f,type:B,compare:K===void 0?null:K}},Xt.startTransition=function(B){var K=D.T,le={};D.T=le;try{var me=B(),be=D.S;be!==null&&be(le,me),typeof me=="object"&&me!==null&&typeof me.then=="function"&&me.then(T,$)}catch(Ee){$(Ee)}finally{K!==null&&le.types!==null&&(K.types=le.types),D.T=K}},Xt.unstable_useCacheRefresh=function(){return D.H.useCacheRefresh()},Xt.use=function(B){return D.H.use(B)},Xt.useActionState=function(B,K,le){return D.H.useActionState(B,K,le)},Xt.useCallback=function(B,K){return D.H.useCallback(B,K)},Xt.useContext=function(B){return D.H.useContext(B)},Xt.useDebugValue=function(){},Xt.useDeferredValue=function(B,K){return D.H.useDeferredValue(B,K)},Xt.useEffect=function(B,K){return D.H.useEffect(B,K)},Xt.useEffectEvent=function(B){return D.H.useEffectEvent(B)},Xt.useId=function(){return D.H.useId()},Xt.useImperativeHandle=function(B,K,le){return D.H.useImperativeHandle(B,K,le)},Xt.useInsertionEffect=function(B,K){return D.H.useInsertionEffect(B,K)},Xt.useLayoutEffect=function(B,K){return D.H.useLayoutEffect(B,K)},Xt.useMemo=function(B,K){return D.H.useMemo(B,K)},Xt.useOptimistic=function(B,K){return D.H.useOptimistic(B,K)},Xt.useReducer=function(B,K,le){return D.H.useReducer(B,K,le)},Xt.useRef=function(B){return D.H.useRef(B)},Xt.useState=function(B){return D.H.useState(B)},Xt.useSyncExternalStore=function(B,K,le){return D.H.useSyncExternalStore(B,K,le)},Xt.useTransition=function(){return D.H.useTransition()},Xt.version="19.2.5",Xt}var jb;function qm(){return jb||(jb=1,dp.exports=qC()),dp.exports}var N=qm();const Ac=Um(N);var fp={exports:{}},pc={},hp={exports:{}},pp={};var Ab;function HC(){return Ab||(Ab=1,(function(e){function t(X,de){var fe=X.length;X.push(de);e:for(;0<fe;){var $=fe-1>>>1,P=X[$];if(0<o(P,de))X[$]=de,X[fe]=P,fe=$;else break e}}function n(X){return X.length===0?null:X[0]}function i(X){if(X.length===0)return null;var de=X[0],fe=X.pop();if(fe!==de){X[0]=fe;e:for(var $=0,P=X.length,B=P>>>1;$<B;){var K=2*($+1)-1,le=X[K],me=K+1,be=X[me];if(0>o(le,fe))me<P&&0>o(be,le)?(X[$]=be,X[me]=fe,$=me):(X[$]=le,X[K]=fe,$=K);else if(me<P&&0>o(be,fe))X[$]=be,X[me]=fe,$=me;else break e}}return de}function o(X,de){var fe=X.sortIndex-de.sortIndex;return fe!==0?fe:X.id-de.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;e.unstable_now=function(){return d.now()}}else{var h=Date,l=h.now();e.unstable_now=function(){return h.now()-l}}var u=[],f=[],v=1,g=null,S=3,w=!1,E=!1,x=!1,m=!1,y=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;function k(X){for(var de=n(f);de!==null;){if(de.callback===null)i(f);else if(de.startTime<=X)i(f),de.sortIndex=de.expirationTime,t(u,de);else break;de=n(f)}}function j(X){if(x=!1,k(X),!E)if(n(u)!==null)E=!0,T||(T=!0,Q());else{var de=n(f);de!==null&&ie(j,de.startTime-X)}}var T=!1,D=-1,I=5,L=-1;function q(){return m?!0:!(e.unstable_now()-L<I)}function H(){if(m=!1,T){var X=e.unstable_now();L=X;var de=!0;try{e:{E=!1,x&&(x=!1,b(D),D=-1),w=!0;var fe=S;try{t:{for(k(X),g=n(u);g!==null&&!(g.expirationTime>X&&q());){var $=g.callback;if(typeof $=="function"){g.callback=null,S=g.priorityLevel;var P=$(g.expirationTime<=X);if(X=e.unstable_now(),typeof P=="function"){g.callback=P,k(X),de=!0;break t}g===n(u)&&i(u),k(X)}else i(u);g=n(u)}if(g!==null)de=!0;else{var B=n(f);B!==null&&ie(j,B.startTime-X),de=!1}}break e}finally{g=null,S=fe,w=!1}de=void 0}}finally{de?Q():T=!1}}}var Q;if(typeof _=="function")Q=function(){_(H)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,J=F.port2;F.port1.onmessage=H,Q=function(){J.postMessage(null)}}else Q=function(){y(H,0)};function ie(X,de){D=y(function(){X(e.unstable_now())},de)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(X){X.callback=null},e.unstable_forceFrameRate=function(X){0>X||125<X?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):I=0<X?Math.floor(1e3/X):5},e.unstable_getCurrentPriorityLevel=function(){return S},e.unstable_next=function(X){switch(S){case 1:case 2:case 3:var de=3;break;default:de=S}var fe=S;S=de;try{return X()}finally{S=fe}},e.unstable_requestPaint=function(){m=!0},e.unstable_runWithPriority=function(X,de){switch(X){case 1:case 2:case 3:case 4:case 5:break;default:X=3}var fe=S;S=X;try{return de()}finally{S=fe}},e.unstable_scheduleCallback=function(X,de,fe){var $=e.unstable_now();switch(typeof fe=="object"&&fe!==null?(fe=fe.delay,fe=typeof fe=="number"&&0<fe?$+fe:$):fe=$,X){case 1:var P=-1;break;case 2:P=250;break;case 5:P=1073741823;break;case 4:P=1e4;break;default:P=5e3}return P=fe+P,X={id:v++,callback:de,priorityLevel:X,startTime:fe,expirationTime:P,sortIndex:-1},fe>$?(X.sortIndex=fe,t(f,X),n(u)===null&&X===n(f)&&(x?(b(D),D=-1):x=!0,ie(j,fe-$))):(X.sortIndex=P,t(u,X),E||w||(E=!0,T||(T=!0,Q()))),X},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(X){var de=S;return function(){var fe=S;S=de;try{return X.apply(this,arguments)}finally{S=fe}}}})(pp)),pp}var Rb;function FC(){return Rb||(Rb=1,hp.exports=HC()),hp.exports}var mp={exports:{}},ks={};var Tb;function KC(){if(Tb)return ks;Tb=1;var e=qm();function t(u){var f="https://react.dev/errors/"+u;if(1<arguments.length){f+="?args[]="+encodeURIComponent(arguments[1]);for(var v=2;v<arguments.length;v++)f+="&args[]="+encodeURIComponent(arguments[v])}return"Minified React error #"+u+"; visit "+f+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var i={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},o=Symbol.for("react.portal");function d(u,f,v){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:g==null?null:""+g,children:u,containerInfo:f,implementation:v}}var h=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(u,f){if(u==="font")return"";if(typeof f=="string")return f==="use-credentials"?f:""}return ks.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,ks.createPortal=function(u,f){var v=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!f||f.nodeType!==1&&f.nodeType!==9&&f.nodeType!==11)throw Error(t(299));return d(u,f,null,v)},ks.flushSync=function(u){var f=h.T,v=i.p;try{if(h.T=null,i.p=2,u)return u()}finally{h.T=f,i.p=v,i.d.f()}},ks.preconnect=function(u,f){typeof u=="string"&&(f?(f=f.crossOrigin,f=typeof f=="string"?f==="use-credentials"?f:"":void 0):f=null,i.d.C(u,f))},ks.prefetchDNS=function(u){typeof u=="string"&&i.d.D(u)},ks.preinit=function(u,f){if(typeof u=="string"&&f&&typeof f.as=="string"){var v=f.as,g=l(v,f.crossOrigin),S=typeof f.integrity=="string"?f.integrity:void 0,w=typeof f.fetchPriority=="string"?f.fetchPriority:void 0;v==="style"?i.d.S(u,typeof f.precedence=="string"?f.precedence:void 0,{crossOrigin:g,integrity:S,fetchPriority:w}):v==="script"&&i.d.X(u,{crossOrigin:g,integrity:S,fetchPriority:w,nonce:typeof f.nonce=="string"?f.nonce:void 0})}},ks.preinitModule=function(u,f){if(typeof u=="string")if(typeof f=="object"&&f!==null){if(f.as==null||f.as==="script"){var v=l(f.as,f.crossOrigin);i.d.M(u,{crossOrigin:v,integrity:typeof f.integrity=="string"?f.integrity:void 0,nonce:typeof f.nonce=="string"?f.nonce:void 0})}}else f==null&&i.d.M(u)},ks.preload=function(u,f){if(typeof u=="string"&&typeof f=="object"&&f!==null&&typeof f.as=="string"){var v=f.as,g=l(v,f.crossOrigin);i.d.L(u,v,{crossOrigin:g,integrity:typeof f.integrity=="string"?f.integrity:void 0,nonce:typeof f.nonce=="string"?f.nonce:void 0,type:typeof f.type=="string"?f.type:void 0,fetchPriority:typeof f.fetchPriority=="string"?f.fetchPriority:void 0,referrerPolicy:typeof f.referrerPolicy=="string"?f.referrerPolicy:void 0,imageSrcSet:typeof f.imageSrcSet=="string"?f.imageSrcSet:void 0,imageSizes:typeof f.imageSizes=="string"?f.imageSizes:void 0,media:typeof f.media=="string"?f.media:void 0})}},ks.preloadModule=function(u,f){if(typeof u=="string")if(f){var v=l(f.as,f.crossOrigin);i.d.m(u,{as:typeof f.as=="string"&&f.as!=="script"?f.as:void 0,crossOrigin:v,integrity:typeof f.integrity=="string"?f.integrity:void 0})}else i.d.m(u)},ks.requestFormReset=function(u){i.d.r(u)},ks.unstable_batchedUpdates=function(u,f){return u(f)},ks.useFormState=function(u,f,v){return h.H.useFormState(u,f,v)},ks.useFormStatus=function(){return h.H.useHostTransitionStatus()},ks.version="19.2.5",ks}var Ib;function L0(){if(Ib)return mp.exports;Ib=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),mp.exports=KC(),mp.exports}var Mb;function WC(){if(Mb)return pc;Mb=1;var e=FC(),t=qm(),n=L0();function i(s){var a="https://react.dev/errors/"+s;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var c=2;c<arguments.length;c++)a+="&args[]="+encodeURIComponent(arguments[c])}return"Minified React error #"+s+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(s){return!(!s||s.nodeType!==1&&s.nodeType!==9&&s.nodeType!==11)}function d(s){var a=s,c=s;if(s.alternate)for(;a.return;)a=a.return;else{s=a;do a=s,(a.flags&4098)!==0&&(c=a.return),s=a.return;while(s)}return a.tag===3?c:null}function h(s){if(s.tag===13){var a=s.memoizedState;if(a===null&&(s=s.alternate,s!==null&&(a=s.memoizedState)),a!==null)return a.dehydrated}return null}function l(s){if(s.tag===31){var a=s.memoizedState;if(a===null&&(s=s.alternate,s!==null&&(a=s.memoizedState)),a!==null)return a.dehydrated}return null}function u(s){if(d(s)!==s)throw Error(i(188))}function f(s){var a=s.alternate;if(!a){if(a=d(s),a===null)throw Error(i(188));return a!==s?null:s}for(var c=s,p=a;;){var C=c.return;if(C===null)break;var A=C.alternate;if(A===null){if(p=C.return,p!==null){c=p;continue}break}if(C.child===A.child){for(A=C.child;A;){if(A===c)return u(C),s;if(A===p)return u(C),a;A=A.sibling}throw Error(i(188))}if(c.return!==p.return)c=C,p=A;else{for(var z=!1,ee=C.child;ee;){if(ee===c){z=!0,c=C,p=A;break}if(ee===p){z=!0,p=C,c=A;break}ee=ee.sibling}if(!z){for(ee=A.child;ee;){if(ee===c){z=!0,c=A,p=C;break}if(ee===p){z=!0,p=A,c=C;break}ee=ee.sibling}if(!z)throw Error(i(189))}}if(c.alternate!==p)throw Error(i(190))}if(c.tag!==3)throw Error(i(188));return c.stateNode.current===c?s:a}function v(s){var a=s.tag;if(a===5||a===26||a===27||a===6)return s;for(s=s.child;s!==null;){if(a=v(s),a!==null)return a;s=s.sibling}return null}var g=Object.assign,S=Symbol.for("react.element"),w=Symbol.for("react.transitional.element"),E=Symbol.for("react.portal"),x=Symbol.for("react.fragment"),m=Symbol.for("react.strict_mode"),y=Symbol.for("react.profiler"),b=Symbol.for("react.consumer"),_=Symbol.for("react.context"),k=Symbol.for("react.forward_ref"),j=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),D=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),L=Symbol.for("react.activity"),q=Symbol.for("react.memo_cache_sentinel"),H=Symbol.iterator;function Q(s){return s===null||typeof s!="object"?null:(s=H&&s[H]||s["@@iterator"],typeof s=="function"?s:null)}var F=Symbol.for("react.client.reference");function J(s){if(s==null)return null;if(typeof s=="function")return s.$$typeof===F?null:s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case x:return"Fragment";case y:return"Profiler";case m:return"StrictMode";case j:return"Suspense";case T:return"SuspenseList";case L:return"Activity"}if(typeof s=="object")switch(s.$$typeof){case E:return"Portal";case _:return s.displayName||"Context";case b:return(s._context.displayName||"Context")+".Consumer";case k:var a=s.render;return s=s.displayName,s||(s=a.displayName||a.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case D:return a=s.displayName||null,a!==null?a:J(s.type)||"Memo";case I:a=s._payload,s=s._init;try{return J(s(a))}catch{}}return null}var ie=Array.isArray,X=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,de=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,fe={pending:!1,data:null,method:null,action:null},$=[],P=-1;function B(s){return{current:s}}function K(s){0>P||(s.current=$[P],$[P]=null,P--)}function le(s,a){P++,$[P]=s.current,s.current=a}var me=B(null),be=B(null),Ee=B(null),se=B(null);function Z(s,a){switch(le(Ee,a),le(be,s),le(me,null),a.nodeType){case 9:case 11:s=(s=a.documentElement)&&(s=s.namespaceURI)?Vy(s):0;break;default:if(s=a.tagName,a=a.namespaceURI)a=Vy(a),s=Yy(a,s);else switch(s){case"svg":s=1;break;case"math":s=2;break;default:s=0}}K(me),le(me,s)}function ge(){K(me),K(be),K(Ee)}function De(s){s.memoizedState!==null&&le(se,s);var a=me.current,c=Yy(a,s.type);a!==c&&(le(be,s),le(me,c))}function Ge(s){be.current===s&&(K(me),K(be)),se.current===s&&(K(se),cc._currentValue=fe)}var Ve,St;function Nt(s){if(Ve===void 0)try{throw Error()}catch(c){var a=c.stack.trim().match(/\n( *(at )?)/);Ve=a&&a[1]||"",St=-1<c.stack.indexOf(`
|
|
2
|
-
at`)?" (<anonymous>)":-1<c.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
3
|
-
`+Ve+s+St}var kt=!1;function Tt(s,a){if(!s||kt)return"";kt=!0;var c=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var p={DetermineComponentFrameRoot:function(){try{if(a){var Fe=function(){throw Error()};if(Object.defineProperty(Fe.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Fe,[])}catch(Te){var Ce=Te}Reflect.construct(s,[],Fe)}else{try{Fe.call()}catch(Te){Ce=Te}s.call(Fe.prototype)}}else{try{throw Error()}catch(Te){Ce=Te}(Fe=s())&&typeof Fe.catch=="function"&&Fe.catch(function(){})}}catch(Te){if(Te&&Ce&&typeof Te.stack=="string")return[Te.stack,Ce.stack]}return[null,null]}};p.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var C=Object.getOwnPropertyDescriptor(p.DetermineComponentFrameRoot,"name");C&&C.configurable&&Object.defineProperty(p.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var A=p.DetermineComponentFrameRoot(),z=A[0],ee=A[1];if(z&&ee){var he=z.split(`
|
|
4
|
-
`),we=ee.split(`
|
|
5
|
-
`);for(C=p=0;p<he.length&&!he[p].includes("DetermineComponentFrameRoot");)p++;for(;C<we.length&&!we[C].includes("DetermineComponentFrameRoot");)C++;if(p===he.length||C===we.length)for(p=he.length-1,C=we.length-1;1<=p&&0<=C&&he[p]!==we[C];)C--;for(;1<=p&&0<=C;p--,C--)if(he[p]!==we[C]){if(p!==1||C!==1)do if(p--,C--,0>C||he[p]!==we[C]){var Pe=`
|
|
6
|
-
`+he[p].replace(" at new "," at ");return s.displayName&&Pe.includes("<anonymous>")&&(Pe=Pe.replace("<anonymous>",s.displayName)),Pe}while(1<=p&&0<=C);break}}}finally{kt=!1,Error.prepareStackTrace=c}return(c=s?s.displayName||s.name:"")?Nt(c):""}function at(s,a){switch(s.tag){case 26:case 27:case 5:return Nt(s.type);case 16:return Nt("Lazy");case 13:return s.child!==a&&a!==null?Nt("Suspense Fallback"):Nt("Suspense");case 19:return Nt("SuspenseList");case 0:case 15:return Tt(s.type,!1);case 11:return Tt(s.type.render,!1);case 1:return Tt(s.type,!0);case 31:return Nt("Activity");default:return""}}function en(s){try{var a="",c=null;do a+=at(s,c),c=s,s=s.return;while(s);return a}catch(p){return`
|
|
7
|
-
Error generating stack: `+p.message+`
|
|
8
|
-
`+p.stack}}var cn=Object.prototype.hasOwnProperty,Bt=e.unstable_scheduleCallback,hn=e.unstable_cancelCallback,sn=e.unstable_shouldYield,Ct=e.unstable_requestPaint,Ut=e.unstable_now,$t=e.unstable_getCurrentPriorityLevel,Lt=e.unstable_ImmediatePriority,Ht=e.unstable_UserBlockingPriority,zt=e.unstable_NormalPriority,rn=e.unstable_LowPriority,ze=e.unstable_IdlePriority,Je=e.log,tt=e.unstable_setDisableYieldValue,Pt=null,Vt=null;function Wt(s){if(typeof Je=="function"&&tt(s),Vt&&typeof Vt.setStrictMode=="function")try{Vt.setStrictMode(Pt,s)}catch{}}var Zt=Math.clz32?Math.clz32:Kn,Dn=Math.log,wn=Math.LN2;function Kn(s){return s>>>=0,s===0?32:31-(Dn(s)/wn|0)|0}var je=256,mt=262144,xt=4194304;function Mt(s){var a=s&42;if(a!==0)return a;switch(s&-s){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 s&261888;case 262144:case 524288:case 1048576:case 2097152:return s&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return s&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return s}}function un(s,a,c){var p=s.pendingLanes;if(p===0)return 0;var C=0,A=s.suspendedLanes,z=s.pingedLanes;s=s.warmLanes;var ee=p&134217727;return ee!==0?(p=ee&~A,p!==0?C=Mt(p):(z&=ee,z!==0?C=Mt(z):c||(c=ee&~s,c!==0&&(C=Mt(c))))):(ee=p&~A,ee!==0?C=Mt(ee):z!==0?C=Mt(z):c||(c=p&~s,c!==0&&(C=Mt(c)))),C===0?0:a!==0&&a!==C&&(a&A)===0&&(A=C&-C,c=a&-a,A>=c||A===32&&(c&4194048)!==0)?a:C}function _n(s,a){return(s.pendingLanes&~(s.suspendedLanes&~s.pingedLanes)&a)===0}function tn(s,a){switch(s){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function zn(){var s=xt;return xt<<=1,(xt&62914560)===0&&(xt=4194304),s}function ss(s){for(var a=[],c=0;31>c;c++)a.push(s);return a}function Ie(s,a){s.pendingLanes|=a,a!==268435456&&(s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0)}function ot(s,a,c,p,C,A){var z=s.pendingLanes;s.pendingLanes=c,s.suspendedLanes=0,s.pingedLanes=0,s.warmLanes=0,s.expiredLanes&=c,s.entangledLanes&=c,s.errorRecoveryDisabledLanes&=c,s.shellSuspendCounter=0;var ee=s.entanglements,he=s.expirationTimes,we=s.hiddenUpdates;for(c=z&~c;0<c;){var Pe=31-Zt(c),Fe=1<<Pe;ee[Pe]=0,he[Pe]=-1;var Ce=we[Pe];if(Ce!==null)for(we[Pe]=null,Pe=0;Pe<Ce.length;Pe++){var Te=Ce[Pe];Te!==null&&(Te.lane&=-536870913)}c&=~Fe}p!==0&&pt(s,p,0),A!==0&&C===0&&s.tag!==0&&(s.suspendedLanes|=A&~(z&~a))}function pt(s,a,c){s.pendingLanes|=a,s.suspendedLanes&=~a;var p=31-Zt(a);s.entangledLanes|=a,s.entanglements[p]=s.entanglements[p]|1073741824|c&261930}function At(s,a){var c=s.entangledLanes|=a;for(s=s.entanglements;c;){var p=31-Zt(c),C=1<<p;C&a|s[p]&a&&(s[p]|=a),c&=~C}}function O(s,a){var c=a&-a;return c=(c&42)!==0?1:W(c),(c&(s.suspendedLanes|a))!==0?0:c}function W(s){switch(s){case 2:s=1;break;case 8:s=4;break;case 32:s=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:s=128;break;case 268435456:s=134217728;break;default:s=0}return s}function G(s){return s&=-s,2<s?8<s?(s&134217727)!==0?32:268435456:8:2}function M(){var s=de.p;return s!==0?s:(s=window.event,s===void 0?32:yb(s.type))}function ne(s,a){var c=de.p;try{return de.p=s,a()}finally{de.p=c}}var te=Math.random().toString(36).slice(2),re="__reactFiber$"+te,ve="__reactProps$"+te,Me="__reactContainer$"+te,Ze="__reactEvents$"+te,Xe="__reactListeners$"+te,Dt="__reactHandles$"+te,nt="__reactResources$"+te,Oe="__reactMarker$"+te;function ce(s){delete s[re],delete s[ve],delete s[Ze],delete s[Xe],delete s[Dt]}function ke(s){var a=s[re];if(a)return a;for(var c=s.parentNode;c;){if(a=c[Me]||c[re]){if(c=a.alternate,a.child!==null||c!==null&&c.child!==null)for(s=nb(s);s!==null;){if(c=s[re])return c;s=nb(s)}return a}s=c,c=s.parentNode}return null}function Ue(s){if(s=s[re]||s[Me]){var a=s.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return s}return null}function rt(s){var a=s.tag;if(a===5||a===26||a===27||a===6)return s.stateNode;throw Error(i(33))}function ct(s){var a=s[nt];return a||(a=s[nt]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function et(s){s[Oe]=!0}var st=new Set,gt={};function it(s,a){ft(s,a),ft(s+"Capture",a)}function ft(s,a){for(gt[s]=a,s=0;s<a.length;s++)st.add(a[s])}var lt=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),ut={},Ne={};function Ae(s){return cn.call(Ne,s)?!0:cn.call(ut,s)?!1:lt.test(s)?Ne[s]=!0:(ut[s]=!0,!1)}function Ke(s,a,c){if(Ae(a))if(c===null)s.removeAttribute(a);else{switch(typeof c){case"undefined":case"function":case"symbol":s.removeAttribute(a);return;case"boolean":var p=a.toLowerCase().slice(0,5);if(p!=="data-"&&p!=="aria-"){s.removeAttribute(a);return}}s.setAttribute(a,""+c)}}function $e(s,a,c){if(c===null)s.removeAttribute(a);else{switch(typeof c){case"undefined":case"function":case"symbol":case"boolean":s.removeAttribute(a);return}s.setAttribute(a,""+c)}}function Le(s,a,c,p){if(p===null)s.removeAttribute(c);else{switch(typeof p){case"undefined":case"function":case"symbol":case"boolean":s.removeAttribute(c);return}s.setAttributeNS(a,c,""+p)}}function We(s){switch(typeof s){case"bigint":case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function Rt(s){var a=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function ae(s,a,c){var p=Object.getOwnPropertyDescriptor(s.constructor.prototype,a);if(!s.hasOwnProperty(a)&&typeof p<"u"&&typeof p.get=="function"&&typeof p.set=="function"){var C=p.get,A=p.set;return Object.defineProperty(s,a,{configurable:!0,get:function(){return C.call(this)},set:function(z){c=""+z,A.call(this,z)}}),Object.defineProperty(s,a,{enumerable:p.enumerable}),{getValue:function(){return c},setValue:function(z){c=""+z},stopTracking:function(){s._valueTracker=null,delete s[a]}}}}function vt(s){if(!s._valueTracker){var a=Rt(s)?"checked":"value";s._valueTracker=ae(s,a,""+s[a])}}function yt(s){if(!s)return!1;var a=s._valueTracker;if(!a)return!0;var c=a.getValue(),p="";return s&&(p=Rt(s)?s.checked?"true":"false":s.value),s=p,s!==c?(a.setValue(s),!0):!1}function ue(s){if(s=s||(typeof document<"u"?document:void 0),typeof s>"u")return null;try{return s.activeElement||s.body}catch{return s.body}}var Gt=/[\n"\\]/g;function bt(s){return s.replace(Gt,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Qt(s,a,c,p,C,A,z,ee){s.name="",z!=null&&typeof z!="function"&&typeof z!="symbol"&&typeof z!="boolean"?s.type=z:s.removeAttribute("type"),a!=null?z==="number"?(a===0&&s.value===""||s.value!=a)&&(s.value=""+We(a)):s.value!==""+We(a)&&(s.value=""+We(a)):z!=="submit"&&z!=="reset"||s.removeAttribute("value"),a!=null?Jt(s,z,We(a)):c!=null?Jt(s,z,We(c)):p!=null&&s.removeAttribute("value"),C==null&&A!=null&&(s.defaultChecked=!!A),C!=null&&(s.checked=C&&typeof C!="function"&&typeof C!="symbol"),ee!=null&&typeof ee!="function"&&typeof ee!="symbol"&&typeof ee!="boolean"?s.name=""+We(ee):s.removeAttribute("name")}function Kt(s,a,c,p,C,A,z,ee){if(A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"&&(s.type=A),a!=null||c!=null){if(!(A!=="submit"&&A!=="reset"||a!=null)){vt(s);return}c=c!=null?""+We(c):"",a=a!=null?""+We(a):c,ee||a===s.value||(s.value=a),s.defaultValue=a}p=p??C,p=typeof p!="function"&&typeof p!="symbol"&&!!p,s.checked=ee?s.checked:!!p,s.defaultChecked=!!p,z!=null&&typeof z!="function"&&typeof z!="symbol"&&typeof z!="boolean"&&(s.name=z),vt(s)}function Jt(s,a,c){a==="number"&&ue(s.ownerDocument)===s||s.defaultValue===""+c||(s.defaultValue=""+c)}function Yt(s,a,c,p){if(s=s.options,a){a={};for(var C=0;C<c.length;C++)a["$"+c[C]]=!0;for(c=0;c<s.length;c++)C=a.hasOwnProperty("$"+s[c].value),s[c].selected!==C&&(s[c].selected=C),C&&p&&(s[c].defaultSelected=!0)}else{for(c=""+We(c),a=null,C=0;C<s.length;C++){if(s[C].value===c){s[C].selected=!0,p&&(s[C].defaultSelected=!0);return}a!==null||s[C].disabled||(a=s[C])}a!==null&&(a.selected=!0)}}function An(s,a,c){if(a!=null&&(a=""+We(a),a!==s.value&&(s.value=a),c==null)){s.defaultValue!==a&&(s.defaultValue=a);return}s.defaultValue=c!=null?""+We(c):""}function bn(s,a,c,p){if(a==null){if(p!=null){if(c!=null)throw Error(i(92));if(ie(p)){if(1<p.length)throw Error(i(93));p=p[0]}c=p}c==null&&(c=""),a=c}c=We(a),s.defaultValue=c,p=s.textContent,p===c&&p!==""&&p!==null&&(s.value=p),vt(s)}function xn(s,a){if(a){var c=s.firstChild;if(c&&c===s.lastChild&&c.nodeType===3){c.nodeValue=a;return}}s.textContent=a}var Rn=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function En(s,a,c){var p=a.indexOf("--")===0;c==null||typeof c=="boolean"||c===""?p?s.setProperty(a,""):a==="float"?s.cssFloat="":s[a]="":p?s.setProperty(a,c):typeof c!="number"||c===0||Rn.has(a)?a==="float"?s.cssFloat=c:s[a]=(""+c).trim():s[a]=c+"px"}function Un(s,a,c){if(a!=null&&typeof a!="object")throw Error(i(62));if(s=s.style,c!=null){for(var p in c)!c.hasOwnProperty(p)||a!=null&&a.hasOwnProperty(p)||(p.indexOf("--")===0?s.setProperty(p,""):p==="float"?s.cssFloat="":s[p]="");for(var C in a)p=a[C],a.hasOwnProperty(C)&&c[C]!==p&&En(s,C,p)}else for(var A in a)a.hasOwnProperty(A)&&En(s,A,a[A])}function Vn(s){if(s.indexOf("-")===-1)return!1;switch(s){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Jn=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),is=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function ya(s){return is.test(""+s)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":s}function ki(){}var io=null;function hl(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Zi=null,Cr=null;function Zc(s){var a=Ue(s);if(a&&(s=a.stateNode)){var c=s[ve]||null;e:switch(s=a.stateNode,a.type){case"input":if(Qt(s,c.value,c.defaultValue,c.defaultValue,c.checked,c.defaultChecked,c.type,c.name),a=c.name,c.type==="radio"&&a!=null){for(c=s;c.parentNode;)c=c.parentNode;for(c=c.querySelectorAll('input[name="'+bt(""+a)+'"][type="radio"]'),a=0;a<c.length;a++){var p=c[a];if(p!==s&&p.form===s.form){var C=p[ve]||null;if(!C)throw Error(i(90));Qt(p,C.value,C.defaultValue,C.defaultValue,C.checked,C.defaultChecked,C.type,C.name)}}for(a=0;a<c.length;a++)p=c[a],p.form===s.form&&yt(p)}break e;case"textarea":An(s,c.value,c.defaultValue);break e;case"select":a=c.value,a!=null&&Yt(s,!!c.multiple,a,!1)}}}var Er=!1;function Xc(s,a,c){if(Er)return s(a,c);Er=!0;try{var p=s(a);return p}finally{if(Er=!1,(Zi!==null||Cr!==null)&&(td(),Zi&&(a=Zi,s=Cr,Cr=Zi=null,Zc(a),s)))for(a=0;a<s.length;a++)Zc(s[a])}}function ba(s,a){var c=s.stateNode;if(c===null)return null;var p=c[ve]||null;if(p===null)return null;c=p[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(p=!p.disabled)||(s=s.type,p=!(s==="button"||s==="input"||s==="select"||s==="textarea")),s=!p;break e;default:s=!1}if(s)return null;if(c&&typeof c!="function")throw Error(i(231,a,typeof c));return c}var Ci=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ro=!1;if(Ci)try{var Zs={};Object.defineProperty(Zs,"passive",{get:function(){ro=!0}}),window.addEventListener("test",Zs,Zs),window.removeEventListener("test",Zs,Zs)}catch{ro=!1}var Ls=null,pl=null,Ei=null;function ao(){if(Ei)return Ei;var s,a=pl,c=a.length,p,C="value"in Ls?Ls.value:Ls.textContent,A=C.length;for(s=0;s<c&&a[s]===C[s];s++);var z=c-s;for(p=1;p<=z&&a[c-p]===C[A-p];p++);return Ei=C.slice(s,1<p?1-p:void 0)}function Nr(s){var a=s.keyCode;return"charCode"in s?(s=s.charCode,s===0&&a===13&&(s=13)):s=a,s===10&&(s=13),32<=s||s===13?s:0}function Xi(){return!0}function oo(){return!1}function Ss(s){function a(c,p,C,A,z){this._reactName=c,this._targetInst=C,this.type=p,this.nativeEvent=A,this.target=z,this.currentTarget=null;for(var ee in s)s.hasOwnProperty(ee)&&(c=s[ee],this[ee]=c?c(A):A[ee]);return this.isDefaultPrevented=(A.defaultPrevented!=null?A.defaultPrevented:A.returnValue===!1)?Xi:oo,this.isPropagationStopped=oo,this}return g(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var c=this.nativeEvent;c&&(c.preventDefault?c.preventDefault():typeof c.returnValue!="unknown"&&(c.returnValue=!1),this.isDefaultPrevented=Xi)},stopPropagation:function(){var c=this.nativeEvent;c&&(c.stopPropagation?c.stopPropagation():typeof c.cancelBubble!="unknown"&&(c.cancelBubble=!0),this.isPropagationStopped=Xi)},persist:function(){},isPersistent:Xi}),a}var ui={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(s){return s.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},lo=Ss(ui),_a=g({},ui,{view:0,detail:0}),xf=Ss(_a),ml,jr,Ar,Rr=g({},_a,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Mr,button:0,buttons:0,relatedTarget:function(s){return s.relatedTarget===void 0?s.fromElement===s.srcElement?s.toElement:s.fromElement:s.relatedTarget},movementX:function(s){return"movementX"in s?s.movementX:(s!==Ar&&(Ar&&s.type==="mousemove"?(ml=s.screenX-Ar.screenX,jr=s.screenY-Ar.screenY):jr=ml=0,Ar=s),ml)},movementY:function(s){return"movementY"in s?s.movementY:jr}}),Qc=Ss(Rr),Jc=g({},Rr,{dataTransfer:0}),Tr=Ss(Jc),eu=g({},_a,{relatedTarget:0}),gl=Ss(eu),wf=g({},ui,{animationName:0,elapsedTime:0,pseudoElement:0}),kf=Ss(wf),tu=g({},ui,{clipboardData:function(s){return"clipboardData"in s?s.clipboardData:window.clipboardData}}),Cf=Ss(tu),nu=g({},ui,{data:0}),Ir=Ss(nu),co={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},su={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},vl={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Ef(s){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(s):(s=vl[s])?!!a[s]:!1}function Mr(){return Ef}var yl=g({},_a,{key:function(s){if(s.key){var a=co[s.key]||s.key;if(a!=="Unidentified")return a}return s.type==="keypress"?(s=Nr(s),s===13?"Enter":String.fromCharCode(s)):s.type==="keydown"||s.type==="keyup"?su[s.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Mr,charCode:function(s){return s.type==="keypress"?Nr(s):0},keyCode:function(s){return s.type==="keydown"||s.type==="keyup"?s.keyCode:0},which:function(s){return s.type==="keypress"?Nr(s):s.type==="keydown"||s.type==="keyup"?s.keyCode:0}}),uo=Ss(yl),Os=g({},Rr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),iu=Ss(Os),ru=g({},_a,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Mr}),Sa=Ss(ru),au=g({},ui,{propertyName:0,elapsedTime:0,pseudoElement:0}),ou=Ss(au),bl=g({},Rr,{deltaX:function(s){return"deltaX"in s?s.deltaX:"wheelDeltaX"in s?-s.wheelDeltaX:0},deltaY:function(s){return"deltaY"in s?s.deltaY:"wheelDeltaY"in s?-s.wheelDeltaY:"wheelDelta"in s?-s.wheelDelta:0},deltaZ:0,deltaMode:0}),lu=Ss(bl),_l=g({},ui,{newState:0,oldState:0}),cu=Ss(_l),Li=[9,13,27,32],fo=Ci&&"CompositionEvent"in window,Xs=null;Ci&&"documentMode"in document&&(Xs=document.documentMode);var ho=Ci&&"TextEvent"in window&&!Xs,xa=Ci&&(!fo||Xs&&8<Xs&&11>=Xs),uu=" ",du=!1;function fu(s,a){switch(s){case"keyup":return Li.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function hu(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var di=!1;function pu(s,a){switch(s){case"compositionend":return hu(a);case"keypress":return a.which!==32?null:(du=!0,uu);case"textInput":return s=a.data,s===uu&&du?null:s;default:return null}}function Nf(s,a){if(di)return s==="compositionend"||!fo&&fu(s,a)?(s=ao(),Ei=pl=Ls=null,di=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return xa&&a.locale!=="ko"?null:a.data;default:return null}}var mu={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function gu(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a==="input"?!!mu[s.type]:a==="textarea"}function vu(s,a,c,p){Zi?Cr?Cr.push(p):Cr=[p]:Zi=p,a=ld(a,"onChange"),0<a.length&&(c=new lo("onChange","change",null,c,p),s.push({event:c,listeners:a}))}var wa=null,ka=null;function Dr(s){qy(s,0)}function Ca(s){var a=rt(s);if(yt(a))return s}function yu(s,a){if(s==="change")return a}var Sl=!1;if(Ci){var xl;if(Ci){var po="oninput"in document;if(!po){var bu=document.createElement("div");bu.setAttribute("oninput","return;"),po=typeof bu.oninput=="function"}xl=po}else xl=!1;Sl=xl&&(!document.documentMode||9<document.documentMode)}function Ea(){wa&&(wa.detachEvent("onpropertychange",wl),ka=wa=null)}function wl(s){if(s.propertyName==="value"&&Ca(ka)){var a=[];vu(a,ka,s,hl(s)),Xc(Dr,a)}}function _u(s,a,c){s==="focusin"?(Ea(),wa=a,ka=c,wa.attachEvent("onpropertychange",wl)):s==="focusout"&&Ea()}function Su(s){if(s==="selectionchange"||s==="keyup"||s==="keydown")return Ca(ka)}function jf(s,a){if(s==="click")return Ca(a)}function Af(s,a){if(s==="input"||s==="change")return Ca(a)}function Rf(s,a){return s===a&&(s!==0||1/s===1/a)||s!==s&&a!==a}var es=typeof Object.is=="function"?Object.is:Rf;function Oi(s,a){if(es(s,a))return!0;if(typeof s!="object"||s===null||typeof a!="object"||a===null)return!1;var c=Object.keys(s),p=Object.keys(a);if(c.length!==p.length)return!1;for(p=0;p<c.length;p++){var C=c[p];if(!cn.call(a,C)||!es(s[C],a[C]))return!1}return!0}function kl(s){for(;s&&s.firstChild;)s=s.firstChild;return s}function Qi(s,a){var c=kl(s);s=0;for(var p;c;){if(c.nodeType===3){if(p=s+c.textContent.length,s<=a&&p>=a)return{node:c,offset:a-s};s=p}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=kl(c)}}function xu(s,a){return s&&a?s===a?!0:s&&s.nodeType===3?!1:a&&a.nodeType===3?xu(s,a.parentNode):"contains"in s?s.contains(a):s.compareDocumentPosition?!!(s.compareDocumentPosition(a)&16):!1:!1}function Cl(s){s=s!=null&&s.ownerDocument!=null&&s.ownerDocument.defaultView!=null?s.ownerDocument.defaultView:window;for(var a=ue(s.document);a instanceof s.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)s=a.contentWindow;else break;a=ue(s.document)}return a}function Pi(s){var a=s&&s.nodeName&&s.nodeName.toLowerCase();return a&&(a==="input"&&(s.type==="text"||s.type==="search"||s.type==="tel"||s.type==="url"||s.type==="password")||a==="textarea"||s.contentEditable==="true")}var Tf=Ci&&"documentMode"in document&&11>=document.documentMode,Lr=null,mo=null,Ni=null,go=!1;function Bi(s,a,c){var p=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;go||Lr==null||Lr!==ue(p)||(p=Lr,"selectionStart"in p&&Pi(p)?p={start:p.selectionStart,end:p.selectionEnd}:(p=(p.ownerDocument&&p.ownerDocument.defaultView||window).getSelection(),p={anchorNode:p.anchorNode,anchorOffset:p.anchorOffset,focusNode:p.focusNode,focusOffset:p.focusOffset}),Ni&&Oi(Ni,p)||(Ni=p,p=ld(mo,"onSelect"),0<p.length&&(a=new lo("onSelect","select",null,a,c),s.push({event:a,listeners:p}),a.target=Lr)))}function Ji(s,a){var c={};return c[s.toLowerCase()]=a.toLowerCase(),c["Webkit"+s]="webkit"+a,c["Moz"+s]="moz"+a,c}var fi={animationend:Ji("Animation","AnimationEnd"),animationiteration:Ji("Animation","AnimationIteration"),animationstart:Ji("Animation","AnimationStart"),transitionrun:Ji("Transition","TransitionRun"),transitionstart:Ji("Transition","TransitionStart"),transitioncancel:Ji("Transition","TransitionCancel"),transitionend:Ji("Transition","TransitionEnd")},El={},ji={};Ci&&(ji=document.createElement("div").style,"AnimationEvent"in window||(delete fi.animationend.animation,delete fi.animationiteration.animation,delete fi.animationstart.animation),"TransitionEvent"in window||delete fi.transitionend.transition);function hi(s){if(El[s])return El[s];if(!fi[s])return s;var a=fi[s],c;for(c in a)if(a.hasOwnProperty(c)&&c in ji)return El[s]=a[c];return s}var Nl=hi("animationend"),Na=hi("animationiteration"),vo=hi("animationstart"),ja=hi("transitionrun"),Or=hi("transitionstart"),If=hi("transitioncancel"),jl=hi("transitionend"),wu=new Map,Al="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");Al.push("scrollEnd");function Qs(s,a){wu.set(s,a),it(a,[s])}var er=typeof reportError=="function"?reportError:function(s){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof s=="object"&&s!==null&&typeof s.message=="string"?String(s.message):String(s),error:s});if(!window.dispatchEvent(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",s);return}console.error(s)},Ps=[],Pr=0,Rl=0;function yo(){for(var s=Pr,a=Rl=Pr=0;a<s;){var c=Ps[a];Ps[a++]=null;var p=Ps[a];Ps[a++]=null;var C=Ps[a];Ps[a++]=null;var A=Ps[a];if(Ps[a++]=null,p!==null&&C!==null){var z=p.pending;z===null?C.next=C:(C.next=z.next,z.next=C),p.pending=C}A!==0&&ku(c,C,A)}}function bo(s,a,c,p){Ps[Pr++]=s,Ps[Pr++]=a,Ps[Pr++]=c,Ps[Pr++]=p,Rl|=p,s.lanes|=p,s=s.alternate,s!==null&&(s.lanes|=p)}function Tl(s,a,c,p){return bo(s,a,c,p),_o(s)}function tr(s,a){return bo(s,null,null,a),_o(s)}function ku(s,a,c){s.lanes|=c;var p=s.alternate;p!==null&&(p.lanes|=c);for(var C=!1,A=s.return;A!==null;)A.childLanes|=c,p=A.alternate,p!==null&&(p.childLanes|=c),A.tag===22&&(s=A.stateNode,s===null||s._visibility&1||(C=!0)),s=A,A=A.return;return s.tag===3?(A=s.stateNode,C&&a!==null&&(C=31-Zt(c),s=A.hiddenUpdates,p=s[C],p===null?s[C]=[a]:p.push(a),a.lane=c|536870912),A):null}function _o(s){if(50<nc)throw nc=0,Dh=null,Error(i(185));for(var a=s.return;a!==null;)s=a,a=s.return;return s.tag===3?s.stateNode:null}var Br={};function Mf(s,a,c,p){this.tag=s,this.key=c,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=p,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Es(s,a,c,p){return new Mf(s,a,c,p)}function Il(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Ai(s,a){var c=s.alternate;return c===null?(c=Es(s.tag,a,s.key,s.mode),c.elementType=s.elementType,c.type=s.type,c.stateNode=s.stateNode,c.alternate=s,s.alternate=c):(c.pendingProps=a,c.type=s.type,c.flags=0,c.subtreeFlags=0,c.deletions=null),c.flags=s.flags&65011712,c.childLanes=s.childLanes,c.lanes=s.lanes,c.child=s.child,c.memoizedProps=s.memoizedProps,c.memoizedState=s.memoizedState,c.updateQueue=s.updateQueue,a=s.dependencies,c.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},c.sibling=s.sibling,c.index=s.index,c.ref=s.ref,c.refCleanup=s.refCleanup,c}function Cu(s,a){s.flags&=65011714;var c=s.alternate;return c===null?(s.childLanes=0,s.lanes=a,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=c.childLanes,s.lanes=c.lanes,s.child=c.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=c.memoizedProps,s.memoizedState=c.memoizedState,s.updateQueue=c.updateQueue,s.type=c.type,a=c.dependencies,s.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),s}function So(s,a,c,p,C,A){var z=0;if(p=s,typeof s=="function")Il(s)&&(z=1);else if(typeof s=="string")z=NC(s,c,me.current)?26:s==="html"||s==="head"||s==="body"?27:5;else e:switch(s){case L:return s=Es(31,c,a,C),s.elementType=L,s.lanes=A,s;case x:return nr(c.children,C,A,a);case m:z=8,C|=24;break;case y:return s=Es(12,c,a,C|2),s.elementType=y,s.lanes=A,s;case j:return s=Es(13,c,a,C),s.elementType=j,s.lanes=A,s;case T:return s=Es(19,c,a,C),s.elementType=T,s.lanes=A,s;default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case _:z=10;break e;case b:z=9;break e;case k:z=11;break e;case D:z=14;break e;case I:z=16,p=null;break e}z=29,c=Error(i(130,s===null?"null":typeof s,"")),p=null}return a=Es(z,c,a,C),a.elementType=s,a.type=p,a.lanes=A,a}function nr(s,a,c,p){return s=Es(7,s,p,a),s.lanes=c,s}function Ml(s,a,c){return s=Es(6,s,null,a),s.lanes=c,s}function Eu(s){var a=Es(18,null,null,0);return a.stateNode=s,a}function Dl(s,a,c){return a=Es(4,s.children!==null?s.children:[],s.key,a),a.lanes=c,a.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},a}var Aa=new WeakMap;function Bs(s,a){if(typeof s=="object"&&s!==null){var c=Aa.get(s);return c!==void 0?c:(a={value:s,source:a,stack:en(a)},Aa.set(s,a),a)}return{value:s,source:a,stack:en(a)}}var $r=[],Js=0,xo=null,Ra=0,$s=[],xs=0,pi=null,mi=1,zs="";function Ri(s,a){$r[Js++]=Ra,$r[Js++]=xo,xo=s,Ra=a}function zr(s,a,c){$s[xs++]=mi,$s[xs++]=zs,$s[xs++]=pi,pi=s;var p=mi;s=zs;var C=32-Zt(p)-1;p&=~(1<<C),c+=1;var A=32-Zt(a)+C;if(30<A){var z=C-C%5;A=(p&(1<<z)-1).toString(32),p>>=z,C-=z,mi=1<<32-Zt(a)+C|c<<C|p,zs=A+s}else mi=1<<A|c<<C|p,zs=s}function wo(s){s.return!==null&&(Ri(s,1),zr(s,1,0))}function Ll(s){for(;s===xo;)xo=$r[--Js],$r[Js]=null,Ra=$r[--Js],$r[Js]=null;for(;s===pi;)pi=$s[--xs],$s[xs]=null,zs=$s[--xs],$s[xs]=null,mi=$s[--xs],$s[xs]=null}function ws(s,a){$s[xs++]=mi,$s[xs++]=zs,$s[xs++]=pi,mi=a.id,zs=a.overflow,pi=s}var rs=null,Tn=null,pn=!1,ei=null,Ns=!1,Ol=Error(i(519));function gi(s){var a=Error(i(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw $i(Bs(a,s)),Ol}function U(s){var a=s.stateNode,c=s.type,p=s.memoizedProps;switch(a[re]=s,a[ve]=p,c){case"dialog":gn("cancel",a),gn("close",a);break;case"iframe":case"object":case"embed":gn("load",a);break;case"video":case"audio":for(c=0;c<ic.length;c++)gn(ic[c],a);break;case"source":gn("error",a);break;case"img":case"image":case"link":gn("error",a),gn("load",a);break;case"details":gn("toggle",a);break;case"input":gn("invalid",a),Kt(a,p.value,p.defaultValue,p.checked,p.defaultChecked,p.type,p.name,!0);break;case"select":gn("invalid",a);break;case"textarea":gn("invalid",a),bn(a,p.value,p.defaultValue,p.children)}c=p.children,typeof c!="string"&&typeof c!="number"&&typeof c!="bigint"||a.textContent===""+c||p.suppressHydrationWarning===!0||Wy(a.textContent,c)?(p.popover!=null&&(gn("beforetoggle",a),gn("toggle",a)),p.onScroll!=null&&gn("scroll",a),p.onScrollEnd!=null&&gn("scrollend",a),p.onClick!=null&&(a.onclick=ki),a=!0):a=!1,a||gi(s,!0)}function Re(s){for(rs=s.return;rs;)switch(rs.tag){case 5:case 31:case 13:Ns=!1;return;case 27:case 3:Ns=!0;return;default:rs=rs.return}}function Qe(s){if(s!==rs)return!1;if(!pn)return Re(s),pn=!0,!1;var a=s.tag,c;if((c=a!==3&&a!==27)&&((c=a===5)&&(c=s.type,c=!(c!=="form"&&c!=="button")||Yh(s.type,s.memoizedProps)),c=!c),c&&Tn&&gi(s),Re(s),a===13){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(i(317));Tn=tb(s)}else if(a===31){if(s=s.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(i(317));Tn=tb(s)}else a===27?(a=Tn,ea(s.type)?(s=ep,ep=null,Tn=s):Tn=a):Tn=rs?yi(s.stateNode.nextSibling):null;return!0}function jt(){Tn=rs=null,pn=!1}function Sn(){var s=ei;return s!==null&&(Fs===null?Fs=s:Fs.push.apply(Fs,s),ei=null),s}function $i(s){ei===null?ei=[s]:ei.push(s)}var Ur=B(null),sr=null,zi=null;function ti(s,a,c){le(Ur,a._currentValue),a._currentValue=c}function ir(s){s._currentValue=Ur.current,K(Ur)}function Df(s,a,c){for(;s!==null;){var p=s.alternate;if((s.childLanes&a)!==a?(s.childLanes|=a,p!==null&&(p.childLanes|=a)):p!==null&&(p.childLanes&a)!==a&&(p.childLanes|=a),s===c)break;s=s.return}}function Lf(s,a,c,p){var C=s.child;for(C!==null&&(C.return=s);C!==null;){var A=C.dependencies;if(A!==null){var z=C.child;A=A.firstContext;e:for(;A!==null;){var ee=A;A=C;for(var he=0;he<a.length;he++)if(ee.context===a[he]){A.lanes|=c,ee=A.alternate,ee!==null&&(ee.lanes|=c),Df(A.return,c,s),p||(z=null);break e}A=ee.next}}else if(C.tag===18){if(z=C.return,z===null)throw Error(i(341));z.lanes|=c,A=z.alternate,A!==null&&(A.lanes|=c),Df(z,c,s),z=null}else z=C.child;if(z!==null)z.return=C;else for(z=C;z!==null;){if(z===s){z=null;break}if(C=z.sibling,C!==null){C.return=z.return,z=C;break}z=z.return}C=z}}function ko(s,a,c,p){s=null;for(var C=a,A=!1;C!==null;){if(!A){if((C.flags&524288)!==0)A=!0;else if((C.flags&262144)!==0)break}if(C.tag===10){var z=C.alternate;if(z===null)throw Error(i(387));if(z=z.memoizedProps,z!==null){var ee=C.type;es(C.pendingProps.value,z.value)||(s!==null?s.push(ee):s=[ee])}}else if(C===se.current){if(z=C.alternate,z===null)throw Error(i(387));z.memoizedState.memoizedState!==C.memoizedState.memoizedState&&(s!==null?s.push(cc):s=[cc])}C=C.return}s!==null&&Lf(a,s,c,p),a.flags|=262144}function Nu(s){for(s=s.firstContext;s!==null;){if(!es(s.context._currentValue,s.memoizedValue))return!0;s=s.next}return!1}function Ta(s){sr=s,zi=null,s=s.dependencies,s!==null&&(s.firstContext=null)}function gs(s){return Tg(sr,s)}function ju(s,a){return sr===null&&Ta(s),Tg(s,a)}function Tg(s,a){var c=a._currentValue;if(a={context:a,memoizedValue:c,next:null},zi===null){if(s===null)throw Error(i(308));zi=a,s.dependencies={lanes:0,firstContext:a},s.flags|=524288}else zi=zi.next=a;return c}var wk=typeof AbortController<"u"?AbortController:function(){var s=[],a=this.signal={aborted:!1,addEventListener:function(c,p){s.push(p)}};this.abort=function(){a.aborted=!0,s.forEach(function(c){return c()})}},kk=e.unstable_scheduleCallback,Ck=e.unstable_NormalPriority,as={$$typeof:_,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Of(){return{controller:new wk,data:new Map,refCount:0}}function Pl(s){s.refCount--,s.refCount===0&&kk(Ck,function(){s.controller.abort()})}var Bl=null,Pf=0,Co=0,Eo=null;function Ek(s,a){if(Bl===null){var c=Bl=[];Pf=0,Co=zh(),Eo={status:"pending",value:void 0,then:function(p){c.push(p)}}}return Pf++,a.then(Ig,Ig),a}function Ig(){if(--Pf===0&&Bl!==null){Eo!==null&&(Eo.status="fulfilled");var s=Bl;Bl=null,Co=0,Eo=null;for(var a=0;a<s.length;a++)(0,s[a])()}}function Nk(s,a){var c=[],p={status:"pending",value:null,reason:null,then:function(C){c.push(C)}};return s.then(function(){p.status="fulfilled",p.value=a;for(var C=0;C<c.length;C++)(0,c[C])(a)},function(C){for(p.status="rejected",p.reason=C,C=0;C<c.length;C++)(0,c[C])(void 0)}),p}var Mg=X.S;X.S=function(s,a){gy=Ut(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&Ek(s,a),Mg!==null&&Mg(s,a)};var Ia=B(null);function Bf(){var s=Ia.current;return s!==null?s:$n.pooledCache}function Au(s,a){a===null?le(Ia,Ia.current):le(Ia,a.pool)}function Dg(){var s=Bf();return s===null?null:{parent:as._currentValue,pool:s}}var No=Error(i(460)),$f=Error(i(474)),Ru=Error(i(542)),Tu={then:function(){}};function Lg(s){return s=s.status,s==="fulfilled"||s==="rejected"}function Og(s,a,c){switch(c=s[c],c===void 0?s.push(a):c!==a&&(a.then(ki,ki),a=c),a.status){case"fulfilled":return a.value;case"rejected":throw s=a.reason,Bg(s),s;default:if(typeof a.status=="string")a.then(ki,ki);else{if(s=$n,s!==null&&100<s.shellSuspendCounter)throw Error(i(482));s=a,s.status="pending",s.then(function(p){if(a.status==="pending"){var C=a;C.status="fulfilled",C.value=p}},function(p){if(a.status==="pending"){var C=a;C.status="rejected",C.reason=p}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw s=a.reason,Bg(s),s}throw Da=a,No}}function Ma(s){try{var a=s._init;return a(s._payload)}catch(c){throw c!==null&&typeof c=="object"&&typeof c.then=="function"?(Da=c,No):c}}var Da=null;function Pg(){if(Da===null)throw Error(i(459));var s=Da;return Da=null,s}function Bg(s){if(s===No||s===Ru)throw Error(i(483))}var jo=null,$l=0;function Iu(s){var a=$l;return $l+=1,jo===null&&(jo=[]),Og(jo,s,a)}function zl(s,a){a=a.props.ref,s.ref=a!==void 0?a:null}function Mu(s,a){throw a.$$typeof===S?Error(i(525)):(s=Object.prototype.toString.call(a),Error(i(31,s==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":s)))}function $g(s){function a(_e,pe){if(s){var xe=_e.deletions;xe===null?(_e.deletions=[pe],_e.flags|=16):xe.push(pe)}}function c(_e,pe){if(!s)return null;for(;pe!==null;)a(_e,pe),pe=pe.sibling;return null}function p(_e){for(var pe=new Map;_e!==null;)_e.key!==null?pe.set(_e.key,_e):pe.set(_e.index,_e),_e=_e.sibling;return pe}function C(_e,pe){return _e=Ai(_e,pe),_e.index=0,_e.sibling=null,_e}function A(_e,pe,xe){return _e.index=xe,s?(xe=_e.alternate,xe!==null?(xe=xe.index,xe<pe?(_e.flags|=67108866,pe):xe):(_e.flags|=67108866,pe)):(_e.flags|=1048576,pe)}function z(_e){return s&&_e.alternate===null&&(_e.flags|=67108866),_e}function ee(_e,pe,xe,qe){return pe===null||pe.tag!==6?(pe=Ml(xe,_e.mode,qe),pe.return=_e,pe):(pe=C(pe,xe),pe.return=_e,pe)}function he(_e,pe,xe,qe){var Ot=xe.type;return Ot===x?Pe(_e,pe,xe.props.children,qe,xe.key):pe!==null&&(pe.elementType===Ot||typeof Ot=="object"&&Ot!==null&&Ot.$$typeof===I&&Ma(Ot)===pe.type)?(pe=C(pe,xe.props),zl(pe,xe),pe.return=_e,pe):(pe=So(xe.type,xe.key,xe.props,null,_e.mode,qe),zl(pe,xe),pe.return=_e,pe)}function we(_e,pe,xe,qe){return pe===null||pe.tag!==4||pe.stateNode.containerInfo!==xe.containerInfo||pe.stateNode.implementation!==xe.implementation?(pe=Dl(xe,_e.mode,qe),pe.return=_e,pe):(pe=C(pe,xe.children||[]),pe.return=_e,pe)}function Pe(_e,pe,xe,qe,Ot){return pe===null||pe.tag!==7?(pe=nr(xe,_e.mode,qe,Ot),pe.return=_e,pe):(pe=C(pe,xe),pe.return=_e,pe)}function Fe(_e,pe,xe){if(typeof pe=="string"&&pe!==""||typeof pe=="number"||typeof pe=="bigint")return pe=Ml(""+pe,_e.mode,xe),pe.return=_e,pe;if(typeof pe=="object"&&pe!==null){switch(pe.$$typeof){case w:return xe=So(pe.type,pe.key,pe.props,null,_e.mode,xe),zl(xe,pe),xe.return=_e,xe;case E:return pe=Dl(pe,_e.mode,xe),pe.return=_e,pe;case I:return pe=Ma(pe),Fe(_e,pe,xe)}if(ie(pe)||Q(pe))return pe=nr(pe,_e.mode,xe,null),pe.return=_e,pe;if(typeof pe.then=="function")return Fe(_e,Iu(pe),xe);if(pe.$$typeof===_)return Fe(_e,ju(_e,pe),xe);Mu(_e,pe)}return null}function Ce(_e,pe,xe,qe){var Ot=pe!==null?pe.key:null;if(typeof xe=="string"&&xe!==""||typeof xe=="number"||typeof xe=="bigint")return Ot!==null?null:ee(_e,pe,""+xe,qe);if(typeof xe=="object"&&xe!==null){switch(xe.$$typeof){case w:return xe.key===Ot?he(_e,pe,xe,qe):null;case E:return xe.key===Ot?we(_e,pe,xe,qe):null;case I:return xe=Ma(xe),Ce(_e,pe,xe,qe)}if(ie(xe)||Q(xe))return Ot!==null?null:Pe(_e,pe,xe,qe,null);if(typeof xe.then=="function")return Ce(_e,pe,Iu(xe),qe);if(xe.$$typeof===_)return Ce(_e,pe,ju(_e,xe),qe);Mu(_e,xe)}return null}function Te(_e,pe,xe,qe,Ot){if(typeof qe=="string"&&qe!==""||typeof qe=="number"||typeof qe=="bigint")return _e=_e.get(xe)||null,ee(pe,_e,""+qe,Ot);if(typeof qe=="object"&&qe!==null){switch(qe.$$typeof){case w:return _e=_e.get(qe.key===null?xe:qe.key)||null,he(pe,_e,qe,Ot);case E:return _e=_e.get(qe.key===null?xe:qe.key)||null,we(pe,_e,qe,Ot);case I:return qe=Ma(qe),Te(_e,pe,xe,qe,Ot)}if(ie(qe)||Q(qe))return _e=_e.get(xe)||null,Pe(pe,_e,qe,Ot,null);if(typeof qe.then=="function")return Te(_e,pe,xe,Iu(qe),Ot);if(qe.$$typeof===_)return Te(_e,pe,xe,ju(pe,qe),Ot);Mu(pe,qe)}return null}function _t(_e,pe,xe,qe){for(var Ot=null,kn=null,Et=pe,an=pe=0,yn=null;Et!==null&&an<xe.length;an++){Et.index>an?(yn=Et,Et=null):yn=Et.sibling;var Cn=Ce(_e,Et,xe[an],qe);if(Cn===null){Et===null&&(Et=yn);break}s&&Et&&Cn.alternate===null&&a(_e,Et),pe=A(Cn,pe,an),kn===null?Ot=Cn:kn.sibling=Cn,kn=Cn,Et=yn}if(an===xe.length)return c(_e,Et),pn&&Ri(_e,an),Ot;if(Et===null){for(;an<xe.length;an++)Et=Fe(_e,xe[an],qe),Et!==null&&(pe=A(Et,pe,an),kn===null?Ot=Et:kn.sibling=Et,kn=Et);return pn&&Ri(_e,an),Ot}for(Et=p(Et);an<xe.length;an++)yn=Te(Et,_e,an,xe[an],qe),yn!==null&&(s&&yn.alternate!==null&&Et.delete(yn.key===null?an:yn.key),pe=A(yn,pe,an),kn===null?Ot=yn:kn.sibling=yn,kn=yn);return s&&Et.forEach(function(ra){return a(_e,ra)}),pn&&Ri(_e,an),Ot}function qt(_e,pe,xe,qe){if(xe==null)throw Error(i(151));for(var Ot=null,kn=null,Et=pe,an=pe=0,yn=null,Cn=xe.next();Et!==null&&!Cn.done;an++,Cn=xe.next()){Et.index>an?(yn=Et,Et=null):yn=Et.sibling;var ra=Ce(_e,Et,Cn.value,qe);if(ra===null){Et===null&&(Et=yn);break}s&&Et&&ra.alternate===null&&a(_e,Et),pe=A(ra,pe,an),kn===null?Ot=ra:kn.sibling=ra,kn=ra,Et=yn}if(Cn.done)return c(_e,Et),pn&&Ri(_e,an),Ot;if(Et===null){for(;!Cn.done;an++,Cn=xe.next())Cn=Fe(_e,Cn.value,qe),Cn!==null&&(pe=A(Cn,pe,an),kn===null?Ot=Cn:kn.sibling=Cn,kn=Cn);return pn&&Ri(_e,an),Ot}for(Et=p(Et);!Cn.done;an++,Cn=xe.next())Cn=Te(Et,_e,an,Cn.value,qe),Cn!==null&&(s&&Cn.alternate!==null&&Et.delete(Cn.key===null?an:Cn.key),pe=A(Cn,pe,an),kn===null?Ot=Cn:kn.sibling=Cn,kn=Cn);return s&&Et.forEach(function(BC){return a(_e,BC)}),pn&&Ri(_e,an),Ot}function Pn(_e,pe,xe,qe){if(typeof xe=="object"&&xe!==null&&xe.type===x&&xe.key===null&&(xe=xe.props.children),typeof xe=="object"&&xe!==null){switch(xe.$$typeof){case w:e:{for(var Ot=xe.key;pe!==null;){if(pe.key===Ot){if(Ot=xe.type,Ot===x){if(pe.tag===7){c(_e,pe.sibling),qe=C(pe,xe.props.children),qe.return=_e,_e=qe;break e}}else if(pe.elementType===Ot||typeof Ot=="object"&&Ot!==null&&Ot.$$typeof===I&&Ma(Ot)===pe.type){c(_e,pe.sibling),qe=C(pe,xe.props),zl(qe,xe),qe.return=_e,_e=qe;break e}c(_e,pe);break}else a(_e,pe);pe=pe.sibling}xe.type===x?(qe=nr(xe.props.children,_e.mode,qe,xe.key),qe.return=_e,_e=qe):(qe=So(xe.type,xe.key,xe.props,null,_e.mode,qe),zl(qe,xe),qe.return=_e,_e=qe)}return z(_e);case E:e:{for(Ot=xe.key;pe!==null;){if(pe.key===Ot)if(pe.tag===4&&pe.stateNode.containerInfo===xe.containerInfo&&pe.stateNode.implementation===xe.implementation){c(_e,pe.sibling),qe=C(pe,xe.children||[]),qe.return=_e,_e=qe;break e}else{c(_e,pe);break}else a(_e,pe);pe=pe.sibling}qe=Dl(xe,_e.mode,qe),qe.return=_e,_e=qe}return z(_e);case I:return xe=Ma(xe),Pn(_e,pe,xe,qe)}if(ie(xe))return _t(_e,pe,xe,qe);if(Q(xe)){if(Ot=Q(xe),typeof Ot!="function")throw Error(i(150));return xe=Ot.call(xe),qt(_e,pe,xe,qe)}if(typeof xe.then=="function")return Pn(_e,pe,Iu(xe),qe);if(xe.$$typeof===_)return Pn(_e,pe,ju(_e,xe),qe);Mu(_e,xe)}return typeof xe=="string"&&xe!==""||typeof xe=="number"||typeof xe=="bigint"?(xe=""+xe,pe!==null&&pe.tag===6?(c(_e,pe.sibling),qe=C(pe,xe),qe.return=_e,_e=qe):(c(_e,pe),qe=Ml(xe,_e.mode,qe),qe.return=_e,_e=qe),z(_e)):c(_e,pe)}return function(_e,pe,xe,qe){try{$l=0;var Ot=Pn(_e,pe,xe,qe);return jo=null,Ot}catch(Et){if(Et===No||Et===Ru)throw Et;var kn=Es(29,Et,null,_e.mode);return kn.lanes=qe,kn.return=_e,kn}}}var La=$g(!0),zg=$g(!1),qr=!1;function zf(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Uf(s,a){s=s.updateQueue,a.updateQueue===s&&(a.updateQueue={baseState:s.baseState,firstBaseUpdate:s.firstBaseUpdate,lastBaseUpdate:s.lastBaseUpdate,shared:s.shared,callbacks:null})}function Hr(s){return{lane:s,tag:0,payload:null,callback:null,next:null}}function Fr(s,a,c){var p=s.updateQueue;if(p===null)return null;if(p=p.shared,(Nn&2)!==0){var C=p.pending;return C===null?a.next=a:(a.next=C.next,C.next=a),p.pending=a,a=_o(s),ku(s,null,c),a}return bo(s,p,a,c),_o(s)}function Ul(s,a,c){if(a=a.updateQueue,a!==null&&(a=a.shared,(c&4194048)!==0)){var p=a.lanes;p&=s.pendingLanes,c|=p,a.lanes=c,At(s,c)}}function qf(s,a){var c=s.updateQueue,p=s.alternate;if(p!==null&&(p=p.updateQueue,c===p)){var C=null,A=null;if(c=c.firstBaseUpdate,c!==null){do{var z={lane:c.lane,tag:c.tag,payload:c.payload,callback:null,next:null};A===null?C=A=z:A=A.next=z,c=c.next}while(c!==null);A===null?C=A=a:A=A.next=a}else C=A=a;c={baseState:p.baseState,firstBaseUpdate:C,lastBaseUpdate:A,shared:p.shared,callbacks:p.callbacks},s.updateQueue=c;return}s=c.lastBaseUpdate,s===null?c.firstBaseUpdate=a:s.next=a,c.lastBaseUpdate=a}var Hf=!1;function ql(){if(Hf){var s=Eo;if(s!==null)throw s}}function Hl(s,a,c,p){Hf=!1;var C=s.updateQueue;qr=!1;var A=C.firstBaseUpdate,z=C.lastBaseUpdate,ee=C.shared.pending;if(ee!==null){C.shared.pending=null;var he=ee,we=he.next;he.next=null,z===null?A=we:z.next=we,z=he;var Pe=s.alternate;Pe!==null&&(Pe=Pe.updateQueue,ee=Pe.lastBaseUpdate,ee!==z&&(ee===null?Pe.firstBaseUpdate=we:ee.next=we,Pe.lastBaseUpdate=he))}if(A!==null){var Fe=C.baseState;z=0,Pe=we=he=null,ee=A;do{var Ce=ee.lane&-536870913,Te=Ce!==ee.lane;if(Te?(vn&Ce)===Ce:(p&Ce)===Ce){Ce!==0&&Ce===Co&&(Hf=!0),Pe!==null&&(Pe=Pe.next={lane:0,tag:ee.tag,payload:ee.payload,callback:null,next:null});e:{var _t=s,qt=ee;Ce=a;var Pn=c;switch(qt.tag){case 1:if(_t=qt.payload,typeof _t=="function"){Fe=_t.call(Pn,Fe,Ce);break e}Fe=_t;break e;case 3:_t.flags=_t.flags&-65537|128;case 0:if(_t=qt.payload,Ce=typeof _t=="function"?_t.call(Pn,Fe,Ce):_t,Ce==null)break e;Fe=g({},Fe,Ce);break e;case 2:qr=!0}}Ce=ee.callback,Ce!==null&&(s.flags|=64,Te&&(s.flags|=8192),Te=C.callbacks,Te===null?C.callbacks=[Ce]:Te.push(Ce))}else Te={lane:Ce,tag:ee.tag,payload:ee.payload,callback:ee.callback,next:null},Pe===null?(we=Pe=Te,he=Fe):Pe=Pe.next=Te,z|=Ce;if(ee=ee.next,ee===null){if(ee=C.shared.pending,ee===null)break;Te=ee,ee=Te.next,Te.next=null,C.lastBaseUpdate=Te,C.shared.pending=null}}while(!0);Pe===null&&(he=Fe),C.baseState=he,C.firstBaseUpdate=we,C.lastBaseUpdate=Pe,A===null&&(C.shared.lanes=0),Yr|=z,s.lanes=z,s.memoizedState=Fe}}function Ug(s,a){if(typeof s!="function")throw Error(i(191,s));s.call(a)}function qg(s,a){var c=s.callbacks;if(c!==null)for(s.callbacks=null,s=0;s<c.length;s++)Ug(c[s],a)}var Ao=B(null),Du=B(0);function Hg(s,a){s=hr,le(Du,s),le(Ao,a),hr=s|a.baseLanes}function Ff(){le(Du,hr),le(Ao,Ao.current)}function Kf(){hr=Du.current,K(Ao),K(Du)}var ni=B(null),vi=null;function Kr(s){var a=s.alternate;le(ts,ts.current&1),le(ni,s),vi===null&&(a===null||Ao.current!==null||a.memoizedState!==null)&&(vi=s)}function Wf(s){le(ts,ts.current),le(ni,s),vi===null&&(vi=s)}function Fg(s){s.tag===22?(le(ts,ts.current),le(ni,s),vi===null&&(vi=s)):Wr()}function Wr(){le(ts,ts.current),le(ni,ni.current)}function si(s){K(ni),vi===s&&(vi=null),K(ts)}var ts=B(0);function Lu(s){for(var a=s;a!==null;){if(a.tag===13){var c=a.memoizedState;if(c!==null&&(c=c.dehydrated,c===null||Qh(c)||Jh(c)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===s)break;for(;a.sibling===null;){if(a.return===null||a.return===s)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var rr=0,nn=null,Ln=null,os=null,Ou=!1,Ro=!1,Oa=!1,Pu=0,Fl=0,To=null,jk=0;function Zn(){throw Error(i(321))}function Gf(s,a){if(a===null)return!1;for(var c=0;c<a.length&&c<s.length;c++)if(!es(s[c],a[c]))return!1;return!0}function Vf(s,a,c,p,C,A){return rr=A,nn=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,X.H=s===null||s.memoizedState===null?Nv:ch,Oa=!1,A=c(p,C),Oa=!1,Ro&&(A=Wg(a,c,p,C)),Kg(s),A}function Kg(s){X.H=Gl;var a=Ln!==null&&Ln.next!==null;if(rr=0,os=Ln=nn=null,Ou=!1,Fl=0,To=null,a)throw Error(i(300));s===null||ls||(s=s.dependencies,s!==null&&Nu(s)&&(ls=!0))}function Wg(s,a,c,p){nn=s;var C=0;do{if(Ro&&(To=null),Fl=0,Ro=!1,25<=C)throw Error(i(301));if(C+=1,os=Ln=null,s.updateQueue!=null){var A=s.updateQueue;A.lastEffect=null,A.events=null,A.stores=null,A.memoCache!=null&&(A.memoCache.index=0)}X.H=jv,A=a(c,p)}while(Ro);return A}function Ak(){var s=X.H,a=s.useState()[0];return a=typeof a.then=="function"?Kl(a):a,s=s.useState()[0],(Ln!==null?Ln.memoizedState:null)!==s&&(nn.flags|=1024),a}function Yf(){var s=Pu!==0;return Pu=0,s}function Zf(s,a,c){a.updateQueue=s.updateQueue,a.flags&=-2053,s.lanes&=~c}function Xf(s){if(Ou){for(s=s.memoizedState;s!==null;){var a=s.queue;a!==null&&(a.pending=null),s=s.next}Ou=!1}rr=0,os=Ln=nn=null,Ro=!1,Fl=Pu=0,To=null}function js(){var s={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return os===null?nn.memoizedState=os=s:os=os.next=s,os}function ns(){if(Ln===null){var s=nn.alternate;s=s!==null?s.memoizedState:null}else s=Ln.next;var a=os===null?nn.memoizedState:os.next;if(a!==null)os=a,Ln=s;else{if(s===null)throw nn.alternate===null?Error(i(467)):Error(i(310));Ln=s,s={memoizedState:Ln.memoizedState,baseState:Ln.baseState,baseQueue:Ln.baseQueue,queue:Ln.queue,next:null},os===null?nn.memoizedState=os=s:os=os.next=s}return os}function Bu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Kl(s){var a=Fl;return Fl+=1,To===null&&(To=[]),s=Og(To,s,a),a=nn,(os===null?a.memoizedState:os.next)===null&&(a=a.alternate,X.H=a===null||a.memoizedState===null?Nv:ch),s}function $u(s){if(s!==null&&typeof s=="object"){if(typeof s.then=="function")return Kl(s);if(s.$$typeof===_)return gs(s)}throw Error(i(438,String(s)))}function Qf(s){var a=null,c=nn.updateQueue;if(c!==null&&(a=c.memoCache),a==null){var p=nn.alternate;p!==null&&(p=p.updateQueue,p!==null&&(p=p.memoCache,p!=null&&(a={data:p.data.map(function(C){return C.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),c===null&&(c=Bu(),nn.updateQueue=c),c.memoCache=a,c=a.data[a.index],c===void 0)for(c=a.data[a.index]=Array(s),p=0;p<s;p++)c[p]=q;return a.index++,c}function ar(s,a){return typeof a=="function"?a(s):a}function zu(s){var a=ns();return Jf(a,Ln,s)}function Jf(s,a,c){var p=s.queue;if(p===null)throw Error(i(311));p.lastRenderedReducer=c;var C=s.baseQueue,A=p.pending;if(A!==null){if(C!==null){var z=C.next;C.next=A.next,A.next=z}a.baseQueue=C=A,p.pending=null}if(A=s.baseState,C===null)s.memoizedState=A;else{a=C.next;var ee=z=null,he=null,we=a,Pe=!1;do{var Fe=we.lane&-536870913;if(Fe!==we.lane?(vn&Fe)===Fe:(rr&Fe)===Fe){var Ce=we.revertLane;if(Ce===0)he!==null&&(he=he.next={lane:0,revertLane:0,gesture:null,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null}),Fe===Co&&(Pe=!0);else if((rr&Ce)===Ce){we=we.next,Ce===Co&&(Pe=!0);continue}else Fe={lane:0,revertLane:we.revertLane,gesture:null,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null},he===null?(ee=he=Fe,z=A):he=he.next=Fe,nn.lanes|=Ce,Yr|=Ce;Fe=we.action,Oa&&c(A,Fe),A=we.hasEagerState?we.eagerState:c(A,Fe)}else Ce={lane:Fe,revertLane:we.revertLane,gesture:we.gesture,action:we.action,hasEagerState:we.hasEagerState,eagerState:we.eagerState,next:null},he===null?(ee=he=Ce,z=A):he=he.next=Ce,nn.lanes|=Fe,Yr|=Fe;we=we.next}while(we!==null&&we!==a);if(he===null?z=A:he.next=ee,!es(A,s.memoizedState)&&(ls=!0,Pe&&(c=Eo,c!==null)))throw c;s.memoizedState=A,s.baseState=z,s.baseQueue=he,p.lastRenderedState=A}return C===null&&(p.lanes=0),[s.memoizedState,p.dispatch]}function eh(s){var a=ns(),c=a.queue;if(c===null)throw Error(i(311));c.lastRenderedReducer=s;var p=c.dispatch,C=c.pending,A=a.memoizedState;if(C!==null){c.pending=null;var z=C=C.next;do A=s(A,z.action),z=z.next;while(z!==C);es(A,a.memoizedState)||(ls=!0),a.memoizedState=A,a.baseQueue===null&&(a.baseState=A),c.lastRenderedState=A}return[A,p]}function Gg(s,a,c){var p=nn,C=ns(),A=pn;if(A){if(c===void 0)throw Error(i(407));c=c()}else c=a();var z=!es((Ln||C).memoizedState,c);if(z&&(C.memoizedState=c,ls=!0),C=C.queue,sh(Zg.bind(null,p,C,s),[s]),C.getSnapshot!==a||z||os!==null&&os.memoizedState.tag&1){if(p.flags|=2048,Io(9,{destroy:void 0},Yg.bind(null,p,C,c,a),null),$n===null)throw Error(i(349));A||(rr&127)!==0||Vg(p,a,c)}return c}function Vg(s,a,c){s.flags|=16384,s={getSnapshot:a,value:c},a=nn.updateQueue,a===null?(a=Bu(),nn.updateQueue=a,a.stores=[s]):(c=a.stores,c===null?a.stores=[s]:c.push(s))}function Yg(s,a,c,p){a.value=c,a.getSnapshot=p,Xg(a)&&Qg(s)}function Zg(s,a,c){return c(function(){Xg(a)&&Qg(s)})}function Xg(s){var a=s.getSnapshot;s=s.value;try{var c=a();return!es(s,c)}catch{return!0}}function Qg(s){var a=tr(s,2);a!==null&&Ks(a,s,2)}function th(s){var a=js();if(typeof s=="function"){var c=s;if(s=c(),Oa){Wt(!0);try{c()}finally{Wt(!1)}}}return a.memoizedState=a.baseState=s,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ar,lastRenderedState:s},a}function Jg(s,a,c,p){return s.baseState=c,Jf(s,Ln,typeof p=="function"?p:ar)}function Rk(s,a,c,p,C){if(Hu(s))throw Error(i(485));if(s=a.action,s!==null){var A={payload:C,action:s,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(z){A.listeners.push(z)}};X.T!==null?c(!0):A.isTransition=!1,p(A),c=a.pending,c===null?(A.next=a.pending=A,ev(a,A)):(A.next=c.next,a.pending=c.next=A)}}function ev(s,a){var c=a.action,p=a.payload,C=s.state;if(a.isTransition){var A=X.T,z={};X.T=z;try{var ee=c(C,p),he=X.S;he!==null&&he(z,ee),tv(s,a,ee)}catch(we){nh(s,a,we)}finally{A!==null&&z.types!==null&&(A.types=z.types),X.T=A}}else try{A=c(C,p),tv(s,a,A)}catch(we){nh(s,a,we)}}function tv(s,a,c){c!==null&&typeof c=="object"&&typeof c.then=="function"?c.then(function(p){nv(s,a,p)},function(p){return nh(s,a,p)}):nv(s,a,c)}function nv(s,a,c){a.status="fulfilled",a.value=c,sv(a),s.state=c,a=s.pending,a!==null&&(c=a.next,c===a?s.pending=null:(c=c.next,a.next=c,ev(s,c)))}function nh(s,a,c){var p=s.pending;if(s.pending=null,p!==null){p=p.next;do a.status="rejected",a.reason=c,sv(a),a=a.next;while(a!==p)}s.action=null}function sv(s){s=s.listeners;for(var a=0;a<s.length;a++)(0,s[a])()}function iv(s,a){return a}function rv(s,a){if(pn){var c=$n.formState;if(c!==null){e:{var p=nn;if(pn){if(Tn){t:{for(var C=Tn,A=Ns;C.nodeType!==8;){if(!A){C=null;break t}if(C=yi(C.nextSibling),C===null){C=null;break t}}A=C.data,C=A==="F!"||A==="F"?C:null}if(C){Tn=yi(C.nextSibling),p=C.data==="F!";break e}}gi(p)}p=!1}p&&(a=c[0])}}return c=js(),c.memoizedState=c.baseState=a,p={pending:null,lanes:0,dispatch:null,lastRenderedReducer:iv,lastRenderedState:a},c.queue=p,c=kv.bind(null,nn,p),p.dispatch=c,p=th(!1),A=lh.bind(null,nn,!1,p.queue),p=js(),C={state:a,dispatch:null,action:s,pending:null},p.queue=C,c=Rk.bind(null,nn,C,A,c),C.dispatch=c,p.memoizedState=s,[a,c,!1]}function av(s){var a=ns();return ov(a,Ln,s)}function ov(s,a,c){if(a=Jf(s,a,iv)[0],s=zu(ar)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var p=Kl(a)}catch(z){throw z===No?Ru:z}else p=a;a=ns();var C=a.queue,A=C.dispatch;return c!==a.memoizedState&&(nn.flags|=2048,Io(9,{destroy:void 0},Tk.bind(null,C,c),null)),[p,A,s]}function Tk(s,a){s.action=a}function lv(s){var a=ns(),c=Ln;if(c!==null)return ov(a,c,s);ns(),a=a.memoizedState,c=ns();var p=c.queue.dispatch;return c.memoizedState=s,[a,p,!1]}function Io(s,a,c,p){return s={tag:s,create:c,deps:p,inst:a,next:null},a=nn.updateQueue,a===null&&(a=Bu(),nn.updateQueue=a),c=a.lastEffect,c===null?a.lastEffect=s.next=s:(p=c.next,c.next=s,s.next=p,a.lastEffect=s),s}function cv(){return ns().memoizedState}function Uu(s,a,c,p){var C=js();nn.flags|=s,C.memoizedState=Io(1|a,{destroy:void 0},c,p===void 0?null:p)}function qu(s,a,c,p){var C=ns();p=p===void 0?null:p;var A=C.memoizedState.inst;Ln!==null&&p!==null&&Gf(p,Ln.memoizedState.deps)?C.memoizedState=Io(a,A,c,p):(nn.flags|=s,C.memoizedState=Io(1|a,A,c,p))}function uv(s,a){Uu(8390656,8,s,a)}function sh(s,a){qu(2048,8,s,a)}function Ik(s){nn.flags|=4;var a=nn.updateQueue;if(a===null)a=Bu(),nn.updateQueue=a,a.events=[s];else{var c=a.events;c===null?a.events=[s]:c.push(s)}}function dv(s){var a=ns().memoizedState;return Ik({ref:a,nextImpl:s}),function(){if((Nn&2)!==0)throw Error(i(440));return a.impl.apply(void 0,arguments)}}function fv(s,a){return qu(4,2,s,a)}function hv(s,a){return qu(4,4,s,a)}function pv(s,a){if(typeof a=="function"){s=s();var c=a(s);return function(){typeof c=="function"?c():a(null)}}if(a!=null)return s=s(),a.current=s,function(){a.current=null}}function mv(s,a,c){c=c!=null?c.concat([s]):null,qu(4,4,pv.bind(null,a,s),c)}function ih(){}function gv(s,a){var c=ns();a=a===void 0?null:a;var p=c.memoizedState;return a!==null&&Gf(a,p[1])?p[0]:(c.memoizedState=[s,a],s)}function vv(s,a){var c=ns();a=a===void 0?null:a;var p=c.memoizedState;if(a!==null&&Gf(a,p[1]))return p[0];if(p=s(),Oa){Wt(!0);try{s()}finally{Wt(!1)}}return c.memoizedState=[p,a],p}function rh(s,a,c){return c===void 0||(rr&1073741824)!==0&&(vn&261930)===0?s.memoizedState=a:(s.memoizedState=c,s=yy(),nn.lanes|=s,Yr|=s,c)}function yv(s,a,c,p){return es(c,a)?c:Ao.current!==null?(s=rh(s,c,p),es(s,a)||(ls=!0),s):(rr&42)===0||(rr&1073741824)!==0&&(vn&261930)===0?(ls=!0,s.memoizedState=c):(s=yy(),nn.lanes|=s,Yr|=s,a)}function bv(s,a,c,p,C){var A=de.p;de.p=A!==0&&8>A?A:8;var z=X.T,ee={};X.T=ee,lh(s,!1,a,c);try{var he=C(),we=X.S;if(we!==null&&we(ee,he),he!==null&&typeof he=="object"&&typeof he.then=="function"){var Pe=Nk(he,p);Wl(s,a,Pe,ai(s))}else Wl(s,a,p,ai(s))}catch(Fe){Wl(s,a,{then:function(){},status:"rejected",reason:Fe},ai())}finally{de.p=A,z!==null&&ee.types!==null&&(z.types=ee.types),X.T=z}}function Mk(){}function ah(s,a,c,p){if(s.tag!==5)throw Error(i(476));var C=_v(s).queue;bv(s,C,a,fe,c===null?Mk:function(){return Sv(s),c(p)})}function _v(s){var a=s.memoizedState;if(a!==null)return a;a={memoizedState:fe,baseState:fe,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ar,lastRenderedState:fe},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ar,lastRenderedState:c},next:null},s.memoizedState=a,s=s.alternate,s!==null&&(s.memoizedState=a),a}function Sv(s){var a=_v(s);a.next===null&&(a=s.alternate.memoizedState),Wl(s,a.next.queue,{},ai())}function oh(){return gs(cc)}function xv(){return ns().memoizedState}function wv(){return ns().memoizedState}function Dk(s){for(var a=s.return;a!==null;){switch(a.tag){case 24:case 3:var c=ai();s=Hr(c);var p=Fr(a,s,c);p!==null&&(Ks(p,a,c),Ul(p,a,c)),a={cache:Of()},s.payload=a;return}a=a.return}}function Lk(s,a,c){var p=ai();c={lane:p,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},Hu(s)?Cv(a,c):(c=Tl(s,a,c,p),c!==null&&(Ks(c,s,p),Ev(c,a,p)))}function kv(s,a,c){var p=ai();Wl(s,a,c,p)}function Wl(s,a,c,p){var C={lane:p,revertLane:0,gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hu(s))Cv(a,C);else{var A=s.alternate;if(s.lanes===0&&(A===null||A.lanes===0)&&(A=a.lastRenderedReducer,A!==null))try{var z=a.lastRenderedState,ee=A(z,c);if(C.hasEagerState=!0,C.eagerState=ee,es(ee,z))return bo(s,a,C,0),$n===null&&yo(),!1}catch{}if(c=Tl(s,a,C,p),c!==null)return Ks(c,s,p),Ev(c,a,p),!0}return!1}function lh(s,a,c,p){if(p={lane:2,revertLane:zh(),gesture:null,action:p,hasEagerState:!1,eagerState:null,next:null},Hu(s)){if(a)throw Error(i(479))}else a=Tl(s,c,p,2),a!==null&&Ks(a,s,2)}function Hu(s){var a=s.alternate;return s===nn||a!==null&&a===nn}function Cv(s,a){Ro=Ou=!0;var c=s.pending;c===null?a.next=a:(a.next=c.next,c.next=a),s.pending=a}function Ev(s,a,c){if((c&4194048)!==0){var p=a.lanes;p&=s.pendingLanes,c|=p,a.lanes=c,At(s,c)}}var Gl={readContext:gs,use:$u,useCallback:Zn,useContext:Zn,useEffect:Zn,useImperativeHandle:Zn,useLayoutEffect:Zn,useInsertionEffect:Zn,useMemo:Zn,useReducer:Zn,useRef:Zn,useState:Zn,useDebugValue:Zn,useDeferredValue:Zn,useTransition:Zn,useSyncExternalStore:Zn,useId:Zn,useHostTransitionStatus:Zn,useFormState:Zn,useActionState:Zn,useOptimistic:Zn,useMemoCache:Zn,useCacheRefresh:Zn};Gl.useEffectEvent=Zn;var Nv={readContext:gs,use:$u,useCallback:function(s,a){return js().memoizedState=[s,a===void 0?null:a],s},useContext:gs,useEffect:uv,useImperativeHandle:function(s,a,c){c=c!=null?c.concat([s]):null,Uu(4194308,4,pv.bind(null,a,s),c)},useLayoutEffect:function(s,a){return Uu(4194308,4,s,a)},useInsertionEffect:function(s,a){Uu(4,2,s,a)},useMemo:function(s,a){var c=js();a=a===void 0?null:a;var p=s();if(Oa){Wt(!0);try{s()}finally{Wt(!1)}}return c.memoizedState=[p,a],p},useReducer:function(s,a,c){var p=js();if(c!==void 0){var C=c(a);if(Oa){Wt(!0);try{c(a)}finally{Wt(!1)}}}else C=a;return p.memoizedState=p.baseState=C,s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:C},p.queue=s,s=s.dispatch=Lk.bind(null,nn,s),[p.memoizedState,s]},useRef:function(s){var a=js();return s={current:s},a.memoizedState=s},useState:function(s){s=th(s);var a=s.queue,c=kv.bind(null,nn,a);return a.dispatch=c,[s.memoizedState,c]},useDebugValue:ih,useDeferredValue:function(s,a){var c=js();return rh(c,s,a)},useTransition:function(){var s=th(!1);return s=bv.bind(null,nn,s.queue,!0,!1),js().memoizedState=s,[!1,s]},useSyncExternalStore:function(s,a,c){var p=nn,C=js();if(pn){if(c===void 0)throw Error(i(407));c=c()}else{if(c=a(),$n===null)throw Error(i(349));(vn&127)!==0||Vg(p,a,c)}C.memoizedState=c;var A={value:c,getSnapshot:a};return C.queue=A,uv(Zg.bind(null,p,A,s),[s]),p.flags|=2048,Io(9,{destroy:void 0},Yg.bind(null,p,A,c,a),null),c},useId:function(){var s=js(),a=$n.identifierPrefix;if(pn){var c=zs,p=mi;c=(p&~(1<<32-Zt(p)-1)).toString(32)+c,a="_"+a+"R_"+c,c=Pu++,0<c&&(a+="H"+c.toString(32)),a+="_"}else c=jk++,a="_"+a+"r_"+c.toString(32)+"_";return s.memoizedState=a},useHostTransitionStatus:oh,useFormState:rv,useActionState:rv,useOptimistic:function(s){var a=js();a.memoizedState=a.baseState=s;var c={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=c,a=lh.bind(null,nn,!0,c),c.dispatch=a,[s,a]},useMemoCache:Qf,useCacheRefresh:function(){return js().memoizedState=Dk.bind(null,nn)},useEffectEvent:function(s){var a=js(),c={impl:s};return a.memoizedState=c,function(){if((Nn&2)!==0)throw Error(i(440));return c.impl.apply(void 0,arguments)}}},ch={readContext:gs,use:$u,useCallback:gv,useContext:gs,useEffect:sh,useImperativeHandle:mv,useInsertionEffect:fv,useLayoutEffect:hv,useMemo:vv,useReducer:zu,useRef:cv,useState:function(){return zu(ar)},useDebugValue:ih,useDeferredValue:function(s,a){var c=ns();return yv(c,Ln.memoizedState,s,a)},useTransition:function(){var s=zu(ar)[0],a=ns().memoizedState;return[typeof s=="boolean"?s:Kl(s),a]},useSyncExternalStore:Gg,useId:xv,useHostTransitionStatus:oh,useFormState:av,useActionState:av,useOptimistic:function(s,a){var c=ns();return Jg(c,Ln,s,a)},useMemoCache:Qf,useCacheRefresh:wv};ch.useEffectEvent=dv;var jv={readContext:gs,use:$u,useCallback:gv,useContext:gs,useEffect:sh,useImperativeHandle:mv,useInsertionEffect:fv,useLayoutEffect:hv,useMemo:vv,useReducer:eh,useRef:cv,useState:function(){return eh(ar)},useDebugValue:ih,useDeferredValue:function(s,a){var c=ns();return Ln===null?rh(c,s,a):yv(c,Ln.memoizedState,s,a)},useTransition:function(){var s=eh(ar)[0],a=ns().memoizedState;return[typeof s=="boolean"?s:Kl(s),a]},useSyncExternalStore:Gg,useId:xv,useHostTransitionStatus:oh,useFormState:lv,useActionState:lv,useOptimistic:function(s,a){var c=ns();return Ln!==null?Jg(c,Ln,s,a):(c.baseState=s,[s,c.queue.dispatch])},useMemoCache:Qf,useCacheRefresh:wv};jv.useEffectEvent=dv;function uh(s,a,c,p){a=s.memoizedState,c=c(p,a),c=c==null?a:g({},a,c),s.memoizedState=c,s.lanes===0&&(s.updateQueue.baseState=c)}var dh={enqueueSetState:function(s,a,c){s=s._reactInternals;var p=ai(),C=Hr(p);C.payload=a,c!=null&&(C.callback=c),a=Fr(s,C,p),a!==null&&(Ks(a,s,p),Ul(a,s,p))},enqueueReplaceState:function(s,a,c){s=s._reactInternals;var p=ai(),C=Hr(p);C.tag=1,C.payload=a,c!=null&&(C.callback=c),a=Fr(s,C,p),a!==null&&(Ks(a,s,p),Ul(a,s,p))},enqueueForceUpdate:function(s,a){s=s._reactInternals;var c=ai(),p=Hr(c);p.tag=2,a!=null&&(p.callback=a),a=Fr(s,p,c),a!==null&&(Ks(a,s,c),Ul(a,s,c))}};function Av(s,a,c,p,C,A,z){return s=s.stateNode,typeof s.shouldComponentUpdate=="function"?s.shouldComponentUpdate(p,A,z):a.prototype&&a.prototype.isPureReactComponent?!Oi(c,p)||!Oi(C,A):!0}function Rv(s,a,c,p){s=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(c,p),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(c,p),a.state!==s&&dh.enqueueReplaceState(a,a.state,null)}function Pa(s,a){var c=a;if("ref"in a){c={};for(var p in a)p!=="ref"&&(c[p]=a[p])}if(s=s.defaultProps){c===a&&(c=g({},c));for(var C in s)c[C]===void 0&&(c[C]=s[C])}return c}function Tv(s){er(s)}function Iv(s){console.error(s)}function Mv(s){er(s)}function Fu(s,a){try{var c=s.onUncaughtError;c(a.value,{componentStack:a.stack})}catch(p){setTimeout(function(){throw p})}}function Dv(s,a,c){try{var p=s.onCaughtError;p(c.value,{componentStack:c.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(C){setTimeout(function(){throw C})}}function fh(s,a,c){return c=Hr(c),c.tag=3,c.payload={element:null},c.callback=function(){Fu(s,a)},c}function Lv(s){return s=Hr(s),s.tag=3,s}function Ov(s,a,c,p){var C=c.type.getDerivedStateFromError;if(typeof C=="function"){var A=p.value;s.payload=function(){return C(A)},s.callback=function(){Dv(a,c,p)}}var z=c.stateNode;z!==null&&typeof z.componentDidCatch=="function"&&(s.callback=function(){Dv(a,c,p),typeof C!="function"&&(Zr===null?Zr=new Set([this]):Zr.add(this));var ee=p.stack;this.componentDidCatch(p.value,{componentStack:ee!==null?ee:""})})}function Ok(s,a,c,p,C){if(c.flags|=32768,p!==null&&typeof p=="object"&&typeof p.then=="function"){if(a=c.alternate,a!==null&&ko(a,c,C,!0),c=ni.current,c!==null){switch(c.tag){case 31:case 13:return vi===null?nd():c.alternate===null&&Xn===0&&(Xn=3),c.flags&=-257,c.flags|=65536,c.lanes=C,p===Tu?c.flags|=16384:(a=c.updateQueue,a===null?c.updateQueue=new Set([p]):a.add(p),Ph(s,p,C)),!1;case 22:return c.flags|=65536,p===Tu?c.flags|=16384:(a=c.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([p])},c.updateQueue=a):(c=a.retryQueue,c===null?a.retryQueue=new Set([p]):c.add(p)),Ph(s,p,C)),!1}throw Error(i(435,c.tag))}return Ph(s,p,C),nd(),!1}if(pn)return a=ni.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=C,p!==Ol&&(s=Error(i(422),{cause:p}),$i(Bs(s,c)))):(p!==Ol&&(a=Error(i(423),{cause:p}),$i(Bs(a,c))),s=s.current.alternate,s.flags|=65536,C&=-C,s.lanes|=C,p=Bs(p,c),C=fh(s.stateNode,p,C),qf(s,C),Xn!==4&&(Xn=2)),!1;var A=Error(i(520),{cause:p});if(A=Bs(A,c),tc===null?tc=[A]:tc.push(A),Xn!==4&&(Xn=2),a===null)return!0;p=Bs(p,c),c=a;do{switch(c.tag){case 3:return c.flags|=65536,s=C&-C,c.lanes|=s,s=fh(c.stateNode,p,s),qf(c,s),!1;case 1:if(a=c.type,A=c.stateNode,(c.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||A!==null&&typeof A.componentDidCatch=="function"&&(Zr===null||!Zr.has(A))))return c.flags|=65536,C&=-C,c.lanes|=C,C=Lv(C),Ov(C,s,c,p),qf(c,C),!1}c=c.return}while(c!==null);return!1}var hh=Error(i(461)),ls=!1;function vs(s,a,c,p){a.child=s===null?zg(a,null,c,p):La(a,s.child,c,p)}function Pv(s,a,c,p,C){c=c.render;var A=a.ref;if("ref"in p){var z={};for(var ee in p)ee!=="ref"&&(z[ee]=p[ee])}else z=p;return Ta(a),p=Vf(s,a,c,z,A,C),ee=Yf(),s!==null&&!ls?(Zf(s,a,C),or(s,a,C)):(pn&&ee&&wo(a),a.flags|=1,vs(s,a,p,C),a.child)}function Bv(s,a,c,p,C){if(s===null){var A=c.type;return typeof A=="function"&&!Il(A)&&A.defaultProps===void 0&&c.compare===null?(a.tag=15,a.type=A,$v(s,a,A,p,C)):(s=So(c.type,null,p,a,a.mode,C),s.ref=a.ref,s.return=a,a.child=s)}if(A=s.child,!Sh(s,C)){var z=A.memoizedProps;if(c=c.compare,c=c!==null?c:Oi,c(z,p)&&s.ref===a.ref)return or(s,a,C)}return a.flags|=1,s=Ai(A,p),s.ref=a.ref,s.return=a,a.child=s}function $v(s,a,c,p,C){if(s!==null){var A=s.memoizedProps;if(Oi(A,p)&&s.ref===a.ref)if(ls=!1,a.pendingProps=p=A,Sh(s,C))(s.flags&131072)!==0&&(ls=!0);else return a.lanes=s.lanes,or(s,a,C)}return ph(s,a,c,p,C)}function zv(s,a,c,p){var C=p.children,A=s!==null?s.memoizedState:null;if(s===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),p.mode==="hidden"){if((a.flags&128)!==0){if(A=A!==null?A.baseLanes|c:c,s!==null){for(p=a.child=s.child,C=0;p!==null;)C=C|p.lanes|p.childLanes,p=p.sibling;p=C&~A}else p=0,a.child=null;return Uv(s,a,A,c,p)}if((c&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},s!==null&&Au(a,A!==null?A.cachePool:null),A!==null?Hg(a,A):Ff(),Fg(a);else return p=a.lanes=536870912,Uv(s,a,A!==null?A.baseLanes|c:c,c,p)}else A!==null?(Au(a,A.cachePool),Hg(a,A),Wr(),a.memoizedState=null):(s!==null&&Au(a,null),Ff(),Wr());return vs(s,a,C,c),a.child}function Vl(s,a){return s!==null&&s.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function Uv(s,a,c,p,C){var A=Bf();return A=A===null?null:{parent:as._currentValue,pool:A},a.memoizedState={baseLanes:c,cachePool:A},s!==null&&Au(a,null),Ff(),Fg(a),s!==null&&ko(s,a,p,!0),a.childLanes=C,null}function Ku(s,a){return a=Gu({mode:a.mode,children:a.children},s.mode),a.ref=s.ref,s.child=a,a.return=s,a}function qv(s,a,c){return La(a,s.child,null,c),s=Ku(a,a.pendingProps),s.flags|=2,si(a),a.memoizedState=null,s}function Pk(s,a,c){var p=a.pendingProps,C=(a.flags&128)!==0;if(a.flags&=-129,s===null){if(pn){if(p.mode==="hidden")return s=Ku(a,p),a.lanes=536870912,Vl(null,s);if(Wf(a),(s=Tn)?(s=eb(s,Ns),s=s!==null&&s.data==="&"?s:null,s!==null&&(a.memoizedState={dehydrated:s,treeContext:pi!==null?{id:mi,overflow:zs}:null,retryLane:536870912,hydrationErrors:null},c=Eu(s),c.return=a,a.child=c,rs=a,Tn=null)):s=null,s===null)throw gi(a);return a.lanes=536870912,null}return Ku(a,p)}var A=s.memoizedState;if(A!==null){var z=A.dehydrated;if(Wf(a),C)if(a.flags&256)a.flags&=-257,a=qv(s,a,c);else if(a.memoizedState!==null)a.child=s.child,a.flags|=128,a=null;else throw Error(i(558));else if(ls||ko(s,a,c,!1),C=(c&s.childLanes)!==0,ls||C){if(p=$n,p!==null&&(z=O(p,c),z!==0&&z!==A.retryLane))throw A.retryLane=z,tr(s,z),Ks(p,s,z),hh;nd(),a=qv(s,a,c)}else s=A.treeContext,Tn=yi(z.nextSibling),rs=a,pn=!0,ei=null,Ns=!1,s!==null&&ws(a,s),a=Ku(a,p),a.flags|=4096;return a}return s=Ai(s.child,{mode:p.mode,children:p.children}),s.ref=a.ref,a.child=s,s.return=a,s}function Wu(s,a){var c=a.ref;if(c===null)s!==null&&s.ref!==null&&(a.flags|=4194816);else{if(typeof c!="function"&&typeof c!="object")throw Error(i(284));(s===null||s.ref!==c)&&(a.flags|=4194816)}}function ph(s,a,c,p,C){return Ta(a),c=Vf(s,a,c,p,void 0,C),p=Yf(),s!==null&&!ls?(Zf(s,a,C),or(s,a,C)):(pn&&p&&wo(a),a.flags|=1,vs(s,a,c,C),a.child)}function Hv(s,a,c,p,C,A){return Ta(a),a.updateQueue=null,c=Wg(a,p,c,C),Kg(s),p=Yf(),s!==null&&!ls?(Zf(s,a,A),or(s,a,A)):(pn&&p&&wo(a),a.flags|=1,vs(s,a,c,A),a.child)}function Fv(s,a,c,p,C){if(Ta(a),a.stateNode===null){var A=Br,z=c.contextType;typeof z=="object"&&z!==null&&(A=gs(z)),A=new c(p,A),a.memoizedState=A.state!==null&&A.state!==void 0?A.state:null,A.updater=dh,a.stateNode=A,A._reactInternals=a,A=a.stateNode,A.props=p,A.state=a.memoizedState,A.refs={},zf(a),z=c.contextType,A.context=typeof z=="object"&&z!==null?gs(z):Br,A.state=a.memoizedState,z=c.getDerivedStateFromProps,typeof z=="function"&&(uh(a,c,z,p),A.state=a.memoizedState),typeof c.getDerivedStateFromProps=="function"||typeof A.getSnapshotBeforeUpdate=="function"||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(z=A.state,typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount(),z!==A.state&&dh.enqueueReplaceState(A,A.state,null),Hl(a,p,A,C),ql(),A.state=a.memoizedState),typeof A.componentDidMount=="function"&&(a.flags|=4194308),p=!0}else if(s===null){A=a.stateNode;var ee=a.memoizedProps,he=Pa(c,ee);A.props=he;var we=A.context,Pe=c.contextType;z=Br,typeof Pe=="object"&&Pe!==null&&(z=gs(Pe));var Fe=c.getDerivedStateFromProps;Pe=typeof Fe=="function"||typeof A.getSnapshotBeforeUpdate=="function",ee=a.pendingProps!==ee,Pe||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(ee||we!==z)&&Rv(a,A,p,z),qr=!1;var Ce=a.memoizedState;A.state=Ce,Hl(a,p,A,C),ql(),we=a.memoizedState,ee||Ce!==we||qr?(typeof Fe=="function"&&(uh(a,c,Fe,p),we=a.memoizedState),(he=qr||Av(a,c,he,p,Ce,we,z))?(Pe||typeof A.UNSAFE_componentWillMount!="function"&&typeof A.componentWillMount!="function"||(typeof A.componentWillMount=="function"&&A.componentWillMount(),typeof A.UNSAFE_componentWillMount=="function"&&A.UNSAFE_componentWillMount()),typeof A.componentDidMount=="function"&&(a.flags|=4194308)):(typeof A.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=p,a.memoizedState=we),A.props=p,A.state=we,A.context=z,p=he):(typeof A.componentDidMount=="function"&&(a.flags|=4194308),p=!1)}else{A=a.stateNode,Uf(s,a),z=a.memoizedProps,Pe=Pa(c,z),A.props=Pe,Fe=a.pendingProps,Ce=A.context,we=c.contextType,he=Br,typeof we=="object"&&we!==null&&(he=gs(we)),ee=c.getDerivedStateFromProps,(we=typeof ee=="function"||typeof A.getSnapshotBeforeUpdate=="function")||typeof A.UNSAFE_componentWillReceiveProps!="function"&&typeof A.componentWillReceiveProps!="function"||(z!==Fe||Ce!==he)&&Rv(a,A,p,he),qr=!1,Ce=a.memoizedState,A.state=Ce,Hl(a,p,A,C),ql();var Te=a.memoizedState;z!==Fe||Ce!==Te||qr||s!==null&&s.dependencies!==null&&Nu(s.dependencies)?(typeof ee=="function"&&(uh(a,c,ee,p),Te=a.memoizedState),(Pe=qr||Av(a,c,Pe,p,Ce,Te,he)||s!==null&&s.dependencies!==null&&Nu(s.dependencies))?(we||typeof A.UNSAFE_componentWillUpdate!="function"&&typeof A.componentWillUpdate!="function"||(typeof A.componentWillUpdate=="function"&&A.componentWillUpdate(p,Te,he),typeof A.UNSAFE_componentWillUpdate=="function"&&A.UNSAFE_componentWillUpdate(p,Te,he)),typeof A.componentDidUpdate=="function"&&(a.flags|=4),typeof A.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof A.componentDidUpdate!="function"||z===s.memoizedProps&&Ce===s.memoizedState||(a.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||z===s.memoizedProps&&Ce===s.memoizedState||(a.flags|=1024),a.memoizedProps=p,a.memoizedState=Te),A.props=p,A.state=Te,A.context=he,p=Pe):(typeof A.componentDidUpdate!="function"||z===s.memoizedProps&&Ce===s.memoizedState||(a.flags|=4),typeof A.getSnapshotBeforeUpdate!="function"||z===s.memoizedProps&&Ce===s.memoizedState||(a.flags|=1024),p=!1)}return A=p,Wu(s,a),p=(a.flags&128)!==0,A||p?(A=a.stateNode,c=p&&typeof c.getDerivedStateFromError!="function"?null:A.render(),a.flags|=1,s!==null&&p?(a.child=La(a,s.child,null,C),a.child=La(a,null,c,C)):vs(s,a,c,C),a.memoizedState=A.state,s=a.child):s=or(s,a,C),s}function Kv(s,a,c,p){return jt(),a.flags|=256,vs(s,a,c,p),a.child}var mh={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function gh(s){return{baseLanes:s,cachePool:Dg()}}function vh(s,a,c){return s=s!==null?s.childLanes&~c:0,a&&(s|=ri),s}function Wv(s,a,c){var p=a.pendingProps,C=!1,A=(a.flags&128)!==0,z;if((z=A)||(z=s!==null&&s.memoizedState===null?!1:(ts.current&2)!==0),z&&(C=!0,a.flags&=-129),z=(a.flags&32)!==0,a.flags&=-33,s===null){if(pn){if(C?Kr(a):Wr(),(s=Tn)?(s=eb(s,Ns),s=s!==null&&s.data!=="&"?s:null,s!==null&&(a.memoizedState={dehydrated:s,treeContext:pi!==null?{id:mi,overflow:zs}:null,retryLane:536870912,hydrationErrors:null},c=Eu(s),c.return=a,a.child=c,rs=a,Tn=null)):s=null,s===null)throw gi(a);return Jh(s)?a.lanes=32:a.lanes=536870912,null}var ee=p.children;return p=p.fallback,C?(Wr(),C=a.mode,ee=Gu({mode:"hidden",children:ee},C),p=nr(p,C,c,null),ee.return=a,p.return=a,ee.sibling=p,a.child=ee,p=a.child,p.memoizedState=gh(c),p.childLanes=vh(s,z,c),a.memoizedState=mh,Vl(null,p)):(Kr(a),yh(a,ee))}var he=s.memoizedState;if(he!==null&&(ee=he.dehydrated,ee!==null)){if(A)a.flags&256?(Kr(a),a.flags&=-257,a=bh(s,a,c)):a.memoizedState!==null?(Wr(),a.child=s.child,a.flags|=128,a=null):(Wr(),ee=p.fallback,C=a.mode,p=Gu({mode:"visible",children:p.children},C),ee=nr(ee,C,c,null),ee.flags|=2,p.return=a,ee.return=a,p.sibling=ee,a.child=p,La(a,s.child,null,c),p=a.child,p.memoizedState=gh(c),p.childLanes=vh(s,z,c),a.memoizedState=mh,a=Vl(null,p));else if(Kr(a),Jh(ee)){if(z=ee.nextSibling&&ee.nextSibling.dataset,z)var we=z.dgst;z=we,p=Error(i(419)),p.stack="",p.digest=z,$i({value:p,source:null,stack:null}),a=bh(s,a,c)}else if(ls||ko(s,a,c,!1),z=(c&s.childLanes)!==0,ls||z){if(z=$n,z!==null&&(p=O(z,c),p!==0&&p!==he.retryLane))throw he.retryLane=p,tr(s,p),Ks(z,s,p),hh;Qh(ee)||nd(),a=bh(s,a,c)}else Qh(ee)?(a.flags|=192,a.child=s.child,a=null):(s=he.treeContext,Tn=yi(ee.nextSibling),rs=a,pn=!0,ei=null,Ns=!1,s!==null&&ws(a,s),a=yh(a,p.children),a.flags|=4096);return a}return C?(Wr(),ee=p.fallback,C=a.mode,he=s.child,we=he.sibling,p=Ai(he,{mode:"hidden",children:p.children}),p.subtreeFlags=he.subtreeFlags&65011712,we!==null?ee=Ai(we,ee):(ee=nr(ee,C,c,null),ee.flags|=2),ee.return=a,p.return=a,p.sibling=ee,a.child=p,Vl(null,p),p=a.child,ee=s.child.memoizedState,ee===null?ee=gh(c):(C=ee.cachePool,C!==null?(he=as._currentValue,C=C.parent!==he?{parent:he,pool:he}:C):C=Dg(),ee={baseLanes:ee.baseLanes|c,cachePool:C}),p.memoizedState=ee,p.childLanes=vh(s,z,c),a.memoizedState=mh,Vl(s.child,p)):(Kr(a),c=s.child,s=c.sibling,c=Ai(c,{mode:"visible",children:p.children}),c.return=a,c.sibling=null,s!==null&&(z=a.deletions,z===null?(a.deletions=[s],a.flags|=16):z.push(s)),a.child=c,a.memoizedState=null,c)}function yh(s,a){return a=Gu({mode:"visible",children:a},s.mode),a.return=s,s.child=a}function Gu(s,a){return s=Es(22,s,null,a),s.lanes=0,s}function bh(s,a,c){return La(a,s.child,null,c),s=yh(a,a.pendingProps.children),s.flags|=2,a.memoizedState=null,s}function Gv(s,a,c){s.lanes|=a;var p=s.alternate;p!==null&&(p.lanes|=a),Df(s.return,a,c)}function _h(s,a,c,p,C,A){var z=s.memoizedState;z===null?s.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:p,tail:c,tailMode:C,treeForkCount:A}:(z.isBackwards=a,z.rendering=null,z.renderingStartTime=0,z.last=p,z.tail=c,z.tailMode=C,z.treeForkCount=A)}function Vv(s,a,c){var p=a.pendingProps,C=p.revealOrder,A=p.tail;p=p.children;var z=ts.current,ee=(z&2)!==0;if(ee?(z=z&1|2,a.flags|=128):z&=1,le(ts,z),vs(s,a,p,c),p=pn?Ra:0,!ee&&s!==null&&(s.flags&128)!==0)e:for(s=a.child;s!==null;){if(s.tag===13)s.memoizedState!==null&&Gv(s,c,a);else if(s.tag===19)Gv(s,c,a);else if(s.child!==null){s.child.return=s,s=s.child;continue}if(s===a)break e;for(;s.sibling===null;){if(s.return===null||s.return===a)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}switch(C){case"forwards":for(c=a.child,C=null;c!==null;)s=c.alternate,s!==null&&Lu(s)===null&&(C=c),c=c.sibling;c=C,c===null?(C=a.child,a.child=null):(C=c.sibling,c.sibling=null),_h(a,!1,C,c,A,p);break;case"backwards":case"unstable_legacy-backwards":for(c=null,C=a.child,a.child=null;C!==null;){if(s=C.alternate,s!==null&&Lu(s)===null){a.child=C;break}s=C.sibling,C.sibling=c,c=C,C=s}_h(a,!0,c,null,A,p);break;case"together":_h(a,!1,null,null,void 0,p);break;default:a.memoizedState=null}return a.child}function or(s,a,c){if(s!==null&&(a.dependencies=s.dependencies),Yr|=a.lanes,(c&a.childLanes)===0)if(s!==null){if(ko(s,a,c,!1),(c&a.childLanes)===0)return null}else return null;if(s!==null&&a.child!==s.child)throw Error(i(153));if(a.child!==null){for(s=a.child,c=Ai(s,s.pendingProps),a.child=c,c.return=a;s.sibling!==null;)s=s.sibling,c=c.sibling=Ai(s,s.pendingProps),c.return=a;c.sibling=null}return a.child}function Sh(s,a){return(s.lanes&a)!==0?!0:(s=s.dependencies,!!(s!==null&&Nu(s)))}function Bk(s,a,c){switch(a.tag){case 3:Z(a,a.stateNode.containerInfo),ti(a,as,s.memoizedState.cache),jt();break;case 27:case 5:De(a);break;case 4:Z(a,a.stateNode.containerInfo);break;case 10:ti(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,Wf(a),null;break;case 13:var p=a.memoizedState;if(p!==null)return p.dehydrated!==null?(Kr(a),a.flags|=128,null):(c&a.child.childLanes)!==0?Wv(s,a,c):(Kr(a),s=or(s,a,c),s!==null?s.sibling:null);Kr(a);break;case 19:var C=(s.flags&128)!==0;if(p=(c&a.childLanes)!==0,p||(ko(s,a,c,!1),p=(c&a.childLanes)!==0),C){if(p)return Vv(s,a,c);a.flags|=128}if(C=a.memoizedState,C!==null&&(C.rendering=null,C.tail=null,C.lastEffect=null),le(ts,ts.current),p)break;return null;case 22:return a.lanes=0,zv(s,a,c,a.pendingProps);case 24:ti(a,as,s.memoizedState.cache)}return or(s,a,c)}function Yv(s,a,c){if(s!==null)if(s.memoizedProps!==a.pendingProps)ls=!0;else{if(!Sh(s,c)&&(a.flags&128)===0)return ls=!1,Bk(s,a,c);ls=(s.flags&131072)!==0}else ls=!1,pn&&(a.flags&1048576)!==0&&zr(a,Ra,a.index);switch(a.lanes=0,a.tag){case 16:e:{var p=a.pendingProps;if(s=Ma(a.elementType),a.type=s,typeof s=="function")Il(s)?(p=Pa(s,p),a.tag=1,a=Fv(null,a,s,p,c)):(a.tag=0,a=ph(null,a,s,p,c));else{if(s!=null){var C=s.$$typeof;if(C===k){a.tag=11,a=Pv(null,a,s,p,c);break e}else if(C===D){a.tag=14,a=Bv(null,a,s,p,c);break e}}throw a=J(s)||s,Error(i(306,a,""))}}return a;case 0:return ph(s,a,a.type,a.pendingProps,c);case 1:return p=a.type,C=Pa(p,a.pendingProps),Fv(s,a,p,C,c);case 3:e:{if(Z(a,a.stateNode.containerInfo),s===null)throw Error(i(387));p=a.pendingProps;var A=a.memoizedState;C=A.element,Uf(s,a),Hl(a,p,null,c);var z=a.memoizedState;if(p=z.cache,ti(a,as,p),p!==A.cache&&Lf(a,[as],c,!0),ql(),p=z.element,A.isDehydrated)if(A={element:p,isDehydrated:!1,cache:z.cache},a.updateQueue.baseState=A,a.memoizedState=A,a.flags&256){a=Kv(s,a,p,c);break e}else if(p!==C){C=Bs(Error(i(424)),a),$i(C),a=Kv(s,a,p,c);break e}else for(s=a.stateNode.containerInfo,s.nodeType===9?s=s.body:s=s.nodeName==="HTML"?s.ownerDocument.body:s,Tn=yi(s.firstChild),rs=a,pn=!0,ei=null,Ns=!0,c=zg(a,null,p,c),a.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{if(jt(),p===C){a=or(s,a,c);break e}vs(s,a,p,c)}a=a.child}return a;case 26:return Wu(s,a),s===null?(c=ab(a.type,null,a.pendingProps,null))?a.memoizedState=c:pn||(c=a.type,s=a.pendingProps,p=cd(Ee.current).createElement(c),p[re]=a,p[ve]=s,ys(p,c,s),et(p),a.stateNode=p):a.memoizedState=ab(a.type,s.memoizedProps,a.pendingProps,s.memoizedState),null;case 27:return De(a),s===null&&pn&&(p=a.stateNode=sb(a.type,a.pendingProps,Ee.current),rs=a,Ns=!0,C=Tn,ea(a.type)?(ep=C,Tn=yi(p.firstChild)):Tn=C),vs(s,a,a.pendingProps.children,c),Wu(s,a),s===null&&(a.flags|=4194304),a.child;case 5:return s===null&&pn&&((C=p=Tn)&&(p=pC(p,a.type,a.pendingProps,Ns),p!==null?(a.stateNode=p,rs=a,Tn=yi(p.firstChild),Ns=!1,C=!0):C=!1),C||gi(a)),De(a),C=a.type,A=a.pendingProps,z=s!==null?s.memoizedProps:null,p=A.children,Yh(C,A)?p=null:z!==null&&Yh(C,z)&&(a.flags|=32),a.memoizedState!==null&&(C=Vf(s,a,Ak,null,null,c),cc._currentValue=C),Wu(s,a),vs(s,a,p,c),a.child;case 6:return s===null&&pn&&((s=c=Tn)&&(c=mC(c,a.pendingProps,Ns),c!==null?(a.stateNode=c,rs=a,Tn=null,s=!0):s=!1),s||gi(a)),null;case 13:return Wv(s,a,c);case 4:return Z(a,a.stateNode.containerInfo),p=a.pendingProps,s===null?a.child=La(a,null,p,c):vs(s,a,p,c),a.child;case 11:return Pv(s,a,a.type,a.pendingProps,c);case 7:return vs(s,a,a.pendingProps,c),a.child;case 8:return vs(s,a,a.pendingProps.children,c),a.child;case 12:return vs(s,a,a.pendingProps.children,c),a.child;case 10:return p=a.pendingProps,ti(a,a.type,p.value),vs(s,a,p.children,c),a.child;case 9:return C=a.type._context,p=a.pendingProps.children,Ta(a),C=gs(C),p=p(C),a.flags|=1,vs(s,a,p,c),a.child;case 14:return Bv(s,a,a.type,a.pendingProps,c);case 15:return $v(s,a,a.type,a.pendingProps,c);case 19:return Vv(s,a,c);case 31:return Pk(s,a,c);case 22:return zv(s,a,c,a.pendingProps);case 24:return Ta(a),p=gs(as),s===null?(C=Bf(),C===null&&(C=$n,A=Of(),C.pooledCache=A,A.refCount++,A!==null&&(C.pooledCacheLanes|=c),C=A),a.memoizedState={parent:p,cache:C},zf(a),ti(a,as,C)):((s.lanes&c)!==0&&(Uf(s,a),Hl(a,null,null,c),ql()),C=s.memoizedState,A=a.memoizedState,C.parent!==p?(C={parent:p,cache:p},a.memoizedState=C,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=C),ti(a,as,p)):(p=A.cache,ti(a,as,p),p!==C.cache&&Lf(a,[as],c,!0))),vs(s,a,a.pendingProps.children,c),a.child;case 29:throw a.pendingProps}throw Error(i(156,a.tag))}function lr(s){s.flags|=4}function xh(s,a,c,p,C){if((a=(s.mode&32)!==0)&&(a=!1),a){if(s.flags|=16777216,(C&335544128)===C)if(s.stateNode.complete)s.flags|=8192;else if(xy())s.flags|=8192;else throw Da=Tu,$f}else s.flags&=-16777217}function Zv(s,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)s.flags&=-16777217;else if(s.flags|=16777216,!db(a))if(xy())s.flags|=8192;else throw Da=Tu,$f}function Vu(s,a){a!==null&&(s.flags|=4),s.flags&16384&&(a=s.tag!==22?zn():536870912,s.lanes|=a,Oo|=a)}function Yl(s,a){if(!pn)switch(s.tailMode){case"hidden":a=s.tail;for(var c=null;a!==null;)a.alternate!==null&&(c=a),a=a.sibling;c===null?s.tail=null:c.sibling=null;break;case"collapsed":c=s.tail;for(var p=null;c!==null;)c.alternate!==null&&(p=c),c=c.sibling;p===null?a||s.tail===null?s.tail=null:s.tail.sibling=null:p.sibling=null}}function qn(s){var a=s.alternate!==null&&s.alternate.child===s.child,c=0,p=0;if(a)for(var C=s.child;C!==null;)c|=C.lanes|C.childLanes,p|=C.subtreeFlags&65011712,p|=C.flags&65011712,C.return=s,C=C.sibling;else for(C=s.child;C!==null;)c|=C.lanes|C.childLanes,p|=C.subtreeFlags,p|=C.flags,C.return=s,C=C.sibling;return s.subtreeFlags|=p,s.childLanes=c,a}function $k(s,a,c){var p=a.pendingProps;switch(Ll(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return qn(a),null;case 1:return qn(a),null;case 3:return c=a.stateNode,p=null,s!==null&&(p=s.memoizedState.cache),a.memoizedState.cache!==p&&(a.flags|=2048),ir(as),ge(),c.pendingContext&&(c.context=c.pendingContext,c.pendingContext=null),(s===null||s.child===null)&&(Qe(a)?lr(a):s===null||s.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Sn())),qn(a),null;case 26:var C=a.type,A=a.memoizedState;return s===null?(lr(a),A!==null?(qn(a),Zv(a,A)):(qn(a),xh(a,C,null,p,c))):A?A!==s.memoizedState?(lr(a),qn(a),Zv(a,A)):(qn(a),a.flags&=-16777217):(s=s.memoizedProps,s!==p&&lr(a),qn(a),xh(a,C,s,p,c)),null;case 27:if(Ge(a),c=Ee.current,C=a.type,s!==null&&a.stateNode!=null)s.memoizedProps!==p&&lr(a);else{if(!p){if(a.stateNode===null)throw Error(i(166));return qn(a),null}s=me.current,Qe(a)?U(a):(s=sb(C,p,c),a.stateNode=s,lr(a))}return qn(a),null;case 5:if(Ge(a),C=a.type,s!==null&&a.stateNode!=null)s.memoizedProps!==p&&lr(a);else{if(!p){if(a.stateNode===null)throw Error(i(166));return qn(a),null}if(A=me.current,Qe(a))U(a);else{var z=cd(Ee.current);switch(A){case 1:A=z.createElementNS("http://www.w3.org/2000/svg",C);break;case 2:A=z.createElementNS("http://www.w3.org/1998/Math/MathML",C);break;default:switch(C){case"svg":A=z.createElementNS("http://www.w3.org/2000/svg",C);break;case"math":A=z.createElementNS("http://www.w3.org/1998/Math/MathML",C);break;case"script":A=z.createElement("div"),A.innerHTML="<script><\/script>",A=A.removeChild(A.firstChild);break;case"select":A=typeof p.is=="string"?z.createElement("select",{is:p.is}):z.createElement("select"),p.multiple?A.multiple=!0:p.size&&(A.size=p.size);break;default:A=typeof p.is=="string"?z.createElement(C,{is:p.is}):z.createElement(C)}}A[re]=a,A[ve]=p;e:for(z=a.child;z!==null;){if(z.tag===5||z.tag===6)A.appendChild(z.stateNode);else if(z.tag!==4&&z.tag!==27&&z.child!==null){z.child.return=z,z=z.child;continue}if(z===a)break e;for(;z.sibling===null;){if(z.return===null||z.return===a)break e;z=z.return}z.sibling.return=z.return,z=z.sibling}a.stateNode=A;e:switch(ys(A,C,p),C){case"button":case"input":case"select":case"textarea":p=!!p.autoFocus;break e;case"img":p=!0;break e;default:p=!1}p&&lr(a)}}return qn(a),xh(a,a.type,s===null?null:s.memoizedProps,a.pendingProps,c),null;case 6:if(s&&a.stateNode!=null)s.memoizedProps!==p&&lr(a);else{if(typeof p!="string"&&a.stateNode===null)throw Error(i(166));if(s=Ee.current,Qe(a)){if(s=a.stateNode,c=a.memoizedProps,p=null,C=rs,C!==null)switch(C.tag){case 27:case 5:p=C.memoizedProps}s[re]=a,s=!!(s.nodeValue===c||p!==null&&p.suppressHydrationWarning===!0||Wy(s.nodeValue,c)),s||gi(a,!0)}else s=cd(s).createTextNode(p),s[re]=a,a.stateNode=s}return qn(a),null;case 31:if(c=a.memoizedState,s===null||s.memoizedState!==null){if(p=Qe(a),c!==null){if(s===null){if(!p)throw Error(i(318));if(s=a.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(i(557));s[re]=a}else jt(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;qn(a),s=!1}else c=Sn(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=c),s=!0;if(!s)return a.flags&256?(si(a),a):(si(a),null);if((a.flags&128)!==0)throw Error(i(558))}return qn(a),null;case 13:if(p=a.memoizedState,s===null||s.memoizedState!==null&&s.memoizedState.dehydrated!==null){if(C=Qe(a),p!==null&&p.dehydrated!==null){if(s===null){if(!C)throw Error(i(318));if(C=a.memoizedState,C=C!==null?C.dehydrated:null,!C)throw Error(i(317));C[re]=a}else jt(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;qn(a),C=!1}else C=Sn(),s!==null&&s.memoizedState!==null&&(s.memoizedState.hydrationErrors=C),C=!0;if(!C)return a.flags&256?(si(a),a):(si(a),null)}return si(a),(a.flags&128)!==0?(a.lanes=c,a):(c=p!==null,s=s!==null&&s.memoizedState!==null,c&&(p=a.child,C=null,p.alternate!==null&&p.alternate.memoizedState!==null&&p.alternate.memoizedState.cachePool!==null&&(C=p.alternate.memoizedState.cachePool.pool),A=null,p.memoizedState!==null&&p.memoizedState.cachePool!==null&&(A=p.memoizedState.cachePool.pool),A!==C&&(p.flags|=2048)),c!==s&&c&&(a.child.flags|=8192),Vu(a,a.updateQueue),qn(a),null);case 4:return ge(),s===null&&Fh(a.stateNode.containerInfo),qn(a),null;case 10:return ir(a.type),qn(a),null;case 19:if(K(ts),p=a.memoizedState,p===null)return qn(a),null;if(C=(a.flags&128)!==0,A=p.rendering,A===null)if(C)Yl(p,!1);else{if(Xn!==0||s!==null&&(s.flags&128)!==0)for(s=a.child;s!==null;){if(A=Lu(s),A!==null){for(a.flags|=128,Yl(p,!1),s=A.updateQueue,a.updateQueue=s,Vu(a,s),a.subtreeFlags=0,s=c,c=a.child;c!==null;)Cu(c,s),c=c.sibling;return le(ts,ts.current&1|2),pn&&Ri(a,p.treeForkCount),a.child}s=s.sibling}p.tail!==null&&Ut()>Ju&&(a.flags|=128,C=!0,Yl(p,!1),a.lanes=4194304)}else{if(!C)if(s=Lu(A),s!==null){if(a.flags|=128,C=!0,s=s.updateQueue,a.updateQueue=s,Vu(a,s),Yl(p,!0),p.tail===null&&p.tailMode==="hidden"&&!A.alternate&&!pn)return qn(a),null}else 2*Ut()-p.renderingStartTime>Ju&&c!==536870912&&(a.flags|=128,C=!0,Yl(p,!1),a.lanes=4194304);p.isBackwards?(A.sibling=a.child,a.child=A):(s=p.last,s!==null?s.sibling=A:a.child=A,p.last=A)}return p.tail!==null?(s=p.tail,p.rendering=s,p.tail=s.sibling,p.renderingStartTime=Ut(),s.sibling=null,c=ts.current,le(ts,C?c&1|2:c&1),pn&&Ri(a,p.treeForkCount),s):(qn(a),null);case 22:case 23:return si(a),Kf(),p=a.memoizedState!==null,s!==null?s.memoizedState!==null!==p&&(a.flags|=8192):p&&(a.flags|=8192),p?(c&536870912)!==0&&(a.flags&128)===0&&(qn(a),a.subtreeFlags&6&&(a.flags|=8192)):qn(a),c=a.updateQueue,c!==null&&Vu(a,c.retryQueue),c=null,s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),p=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(p=a.memoizedState.cachePool.pool),p!==c&&(a.flags|=2048),s!==null&&K(Ia),null;case 24:return c=null,s!==null&&(c=s.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),ir(as),qn(a),null;case 25:return null;case 30:return null}throw Error(i(156,a.tag))}function zk(s,a){switch(Ll(a),a.tag){case 1:return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 3:return ir(as),ge(),s=a.flags,(s&65536)!==0&&(s&128)===0?(a.flags=s&-65537|128,a):null;case 26:case 27:case 5:return Ge(a),null;case 31:if(a.memoizedState!==null){if(si(a),a.alternate===null)throw Error(i(340));jt()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 13:if(si(a),s=a.memoizedState,s!==null&&s.dehydrated!==null){if(a.alternate===null)throw Error(i(340));jt()}return s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 19:return K(ts),null;case 4:return ge(),null;case 10:return ir(a.type),null;case 22:case 23:return si(a),Kf(),s!==null&&K(Ia),s=a.flags,s&65536?(a.flags=s&-65537|128,a):null;case 24:return ir(as),null;case 25:return null;default:return null}}function Xv(s,a){switch(Ll(a),a.tag){case 3:ir(as),ge();break;case 26:case 27:case 5:Ge(a);break;case 4:ge();break;case 31:a.memoizedState!==null&&si(a);break;case 13:si(a);break;case 19:K(ts);break;case 10:ir(a.type);break;case 22:case 23:si(a),Kf(),s!==null&&K(Ia);break;case 24:ir(as)}}function Zl(s,a){try{var c=a.updateQueue,p=c!==null?c.lastEffect:null;if(p!==null){var C=p.next;c=C;do{if((c.tag&s)===s){p=void 0;var A=c.create,z=c.inst;p=A(),z.destroy=p}c=c.next}while(c!==C)}}catch(ee){Mn(a,a.return,ee)}}function Gr(s,a,c){try{var p=a.updateQueue,C=p!==null?p.lastEffect:null;if(C!==null){var A=C.next;p=A;do{if((p.tag&s)===s){var z=p.inst,ee=z.destroy;if(ee!==void 0){z.destroy=void 0,C=a;var he=c,we=ee;try{we()}catch(Pe){Mn(C,he,Pe)}}}p=p.next}while(p!==A)}}catch(Pe){Mn(a,a.return,Pe)}}function Qv(s){var a=s.updateQueue;if(a!==null){var c=s.stateNode;try{qg(a,c)}catch(p){Mn(s,s.return,p)}}}function Jv(s,a,c){c.props=Pa(s.type,s.memoizedProps),c.state=s.memoizedState;try{c.componentWillUnmount()}catch(p){Mn(s,a,p)}}function Xl(s,a){try{var c=s.ref;if(c!==null){switch(s.tag){case 26:case 27:case 5:var p=s.stateNode;break;case 30:p=s.stateNode;break;default:p=s.stateNode}typeof c=="function"?s.refCleanup=c(p):c.current=p}}catch(C){Mn(s,a,C)}}function Ui(s,a){var c=s.ref,p=s.refCleanup;if(c!==null)if(typeof p=="function")try{p()}catch(C){Mn(s,a,C)}finally{s.refCleanup=null,s=s.alternate,s!=null&&(s.refCleanup=null)}else if(typeof c=="function")try{c(null)}catch(C){Mn(s,a,C)}else c.current=null}function ey(s){var a=s.type,c=s.memoizedProps,p=s.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":c.autoFocus&&p.focus();break e;case"img":c.src?p.src=c.src:c.srcSet&&(p.srcset=c.srcSet)}}catch(C){Mn(s,s.return,C)}}function wh(s,a,c){try{var p=s.stateNode;lC(p,s.type,c,a),p[ve]=a}catch(C){Mn(s,s.return,C)}}function ty(s){return s.tag===5||s.tag===3||s.tag===26||s.tag===27&&ea(s.type)||s.tag===4}function kh(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||ty(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.tag===27&&ea(s.type)||s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function Ch(s,a,c){var p=s.tag;if(p===5||p===6)s=s.stateNode,a?(c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c).insertBefore(s,a):(a=c.nodeType===9?c.body:c.nodeName==="HTML"?c.ownerDocument.body:c,a.appendChild(s),c=c._reactRootContainer,c!=null||a.onclick!==null||(a.onclick=ki));else if(p!==4&&(p===27&&ea(s.type)&&(c=s.stateNode,a=null),s=s.child,s!==null))for(Ch(s,a,c),s=s.sibling;s!==null;)Ch(s,a,c),s=s.sibling}function Yu(s,a,c){var p=s.tag;if(p===5||p===6)s=s.stateNode,a?c.insertBefore(s,a):c.appendChild(s);else if(p!==4&&(p===27&&ea(s.type)&&(c=s.stateNode),s=s.child,s!==null))for(Yu(s,a,c),s=s.sibling;s!==null;)Yu(s,a,c),s=s.sibling}function ny(s){var a=s.stateNode,c=s.memoizedProps;try{for(var p=s.type,C=a.attributes;C.length;)a.removeAttributeNode(C[0]);ys(a,p,c),a[re]=s,a[ve]=c}catch(A){Mn(s,s.return,A)}}var cr=!1,cs=!1,Eh=!1,sy=typeof WeakSet=="function"?WeakSet:Set,ps=null;function Uk(s,a){if(s=s.containerInfo,Gh=gd,s=Cl(s),Pi(s)){if("selectionStart"in s)var c={start:s.selectionStart,end:s.selectionEnd};else e:{c=(c=s.ownerDocument)&&c.defaultView||window;var p=c.getSelection&&c.getSelection();if(p&&p.rangeCount!==0){c=p.anchorNode;var C=p.anchorOffset,A=p.focusNode;p=p.focusOffset;try{c.nodeType,A.nodeType}catch{c=null;break e}var z=0,ee=-1,he=-1,we=0,Pe=0,Fe=s,Ce=null;t:for(;;){for(var Te;Fe!==c||C!==0&&Fe.nodeType!==3||(ee=z+C),Fe!==A||p!==0&&Fe.nodeType!==3||(he=z+p),Fe.nodeType===3&&(z+=Fe.nodeValue.length),(Te=Fe.firstChild)!==null;)Ce=Fe,Fe=Te;for(;;){if(Fe===s)break t;if(Ce===c&&++we===C&&(ee=z),Ce===A&&++Pe===p&&(he=z),(Te=Fe.nextSibling)!==null)break;Fe=Ce,Ce=Fe.parentNode}Fe=Te}c=ee===-1||he===-1?null:{start:ee,end:he}}else c=null}c=c||{start:0,end:0}}else c=null;for(Vh={focusedElem:s,selectionRange:c},gd=!1,ps=a;ps!==null;)if(a=ps,s=a.child,(a.subtreeFlags&1028)!==0&&s!==null)s.return=a,ps=s;else for(;ps!==null;){switch(a=ps,A=a.alternate,s=a.flags,a.tag){case 0:if((s&4)!==0&&(s=a.updateQueue,s=s!==null?s.events:null,s!==null))for(c=0;c<s.length;c++)C=s[c],C.ref.impl=C.nextImpl;break;case 11:case 15:break;case 1:if((s&1024)!==0&&A!==null){s=void 0,c=a,C=A.memoizedProps,A=A.memoizedState,p=c.stateNode;try{var _t=Pa(c.type,C);s=p.getSnapshotBeforeUpdate(_t,A),p.__reactInternalSnapshotBeforeUpdate=s}catch(qt){Mn(c,c.return,qt)}}break;case 3:if((s&1024)!==0){if(s=a.stateNode.containerInfo,c=s.nodeType,c===9)Xh(s);else if(c===1)switch(s.nodeName){case"HEAD":case"HTML":case"BODY":Xh(s);break;default:s.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((s&1024)!==0)throw Error(i(163))}if(s=a.sibling,s!==null){s.return=a.return,ps=s;break}ps=a.return}}function iy(s,a,c){var p=c.flags;switch(c.tag){case 0:case 11:case 15:dr(s,c),p&4&&Zl(5,c);break;case 1:if(dr(s,c),p&4)if(s=c.stateNode,a===null)try{s.componentDidMount()}catch(z){Mn(c,c.return,z)}else{var C=Pa(c.type,a.memoizedProps);a=a.memoizedState;try{s.componentDidUpdate(C,a,s.__reactInternalSnapshotBeforeUpdate)}catch(z){Mn(c,c.return,z)}}p&64&&Qv(c),p&512&&Xl(c,c.return);break;case 3:if(dr(s,c),p&64&&(s=c.updateQueue,s!==null)){if(a=null,c.child!==null)switch(c.child.tag){case 27:case 5:a=c.child.stateNode;break;case 1:a=c.child.stateNode}try{qg(s,a)}catch(z){Mn(c,c.return,z)}}break;case 27:a===null&&p&4&&ny(c);case 26:case 5:dr(s,c),a===null&&p&4&&ey(c),p&512&&Xl(c,c.return);break;case 12:dr(s,c);break;case 31:dr(s,c),p&4&&oy(s,c);break;case 13:dr(s,c),p&4&&ly(s,c),p&64&&(s=c.memoizedState,s!==null&&(s=s.dehydrated,s!==null&&(c=Zk.bind(null,c),gC(s,c))));break;case 22:if(p=c.memoizedState!==null||cr,!p){a=a!==null&&a.memoizedState!==null||cs,C=cr;var A=cs;cr=p,(cs=a)&&!A?fr(s,c,(c.subtreeFlags&8772)!==0):dr(s,c),cr=C,cs=A}break;case 30:break;default:dr(s,c)}}function ry(s){var a=s.alternate;a!==null&&(s.alternate=null,ry(a)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(a=s.stateNode,a!==null&&ce(a)),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}var Wn=null,Us=!1;function ur(s,a,c){for(c=c.child;c!==null;)ay(s,a,c),c=c.sibling}function ay(s,a,c){if(Vt&&typeof Vt.onCommitFiberUnmount=="function")try{Vt.onCommitFiberUnmount(Pt,c)}catch{}switch(c.tag){case 26:cs||Ui(c,a),ur(s,a,c),c.memoizedState?c.memoizedState.count--:c.stateNode&&(c=c.stateNode,c.parentNode.removeChild(c));break;case 27:cs||Ui(c,a);var p=Wn,C=Us;ea(c.type)&&(Wn=c.stateNode,Us=!1),ur(s,a,c),ac(c.stateNode),Wn=p,Us=C;break;case 5:cs||Ui(c,a);case 6:if(p=Wn,C=Us,Wn=null,ur(s,a,c),Wn=p,Us=C,Wn!==null)if(Us)try{(Wn.nodeType===9?Wn.body:Wn.nodeName==="HTML"?Wn.ownerDocument.body:Wn).removeChild(c.stateNode)}catch(A){Mn(c,a,A)}else try{Wn.removeChild(c.stateNode)}catch(A){Mn(c,a,A)}break;case 18:Wn!==null&&(Us?(s=Wn,Qy(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,c.stateNode),Fo(s)):Qy(Wn,c.stateNode));break;case 4:p=Wn,C=Us,Wn=c.stateNode.containerInfo,Us=!0,ur(s,a,c),Wn=p,Us=C;break;case 0:case 11:case 14:case 15:Gr(2,c,a),cs||Gr(4,c,a),ur(s,a,c);break;case 1:cs||(Ui(c,a),p=c.stateNode,typeof p.componentWillUnmount=="function"&&Jv(c,a,p)),ur(s,a,c);break;case 21:ur(s,a,c);break;case 22:cs=(p=cs)||c.memoizedState!==null,ur(s,a,c),cs=p;break;default:ur(s,a,c)}}function oy(s,a){if(a.memoizedState===null&&(s=a.alternate,s!==null&&(s=s.memoizedState,s!==null))){s=s.dehydrated;try{Fo(s)}catch(c){Mn(a,a.return,c)}}}function ly(s,a){if(a.memoizedState===null&&(s=a.alternate,s!==null&&(s=s.memoizedState,s!==null&&(s=s.dehydrated,s!==null))))try{Fo(s)}catch(c){Mn(a,a.return,c)}}function qk(s){switch(s.tag){case 31:case 13:case 19:var a=s.stateNode;return a===null&&(a=s.stateNode=new sy),a;case 22:return s=s.stateNode,a=s._retryCache,a===null&&(a=s._retryCache=new sy),a;default:throw Error(i(435,s.tag))}}function Zu(s,a){var c=qk(s);a.forEach(function(p){if(!c.has(p)){c.add(p);var C=Xk.bind(null,s,p);p.then(C,C)}})}function qs(s,a){var c=a.deletions;if(c!==null)for(var p=0;p<c.length;p++){var C=c[p],A=s,z=a,ee=z;e:for(;ee!==null;){switch(ee.tag){case 27:if(ea(ee.type)){Wn=ee.stateNode,Us=!1;break e}break;case 5:Wn=ee.stateNode,Us=!1;break e;case 3:case 4:Wn=ee.stateNode.containerInfo,Us=!0;break e}ee=ee.return}if(Wn===null)throw Error(i(160));ay(A,z,C),Wn=null,Us=!1,A=C.alternate,A!==null&&(A.return=null),C.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)cy(a,s),a=a.sibling}var Ti=null;function cy(s,a){var c=s.alternate,p=s.flags;switch(s.tag){case 0:case 11:case 14:case 15:qs(a,s),Hs(s),p&4&&(Gr(3,s,s.return),Zl(3,s),Gr(5,s,s.return));break;case 1:qs(a,s),Hs(s),p&512&&(cs||c===null||Ui(c,c.return)),p&64&&cr&&(s=s.updateQueue,s!==null&&(p=s.callbacks,p!==null&&(c=s.shared.hiddenCallbacks,s.shared.hiddenCallbacks=c===null?p:c.concat(p))));break;case 26:var C=Ti;if(qs(a,s),Hs(s),p&512&&(cs||c===null||Ui(c,c.return)),p&4){var A=c!==null?c.memoizedState:null;if(p=s.memoizedState,c===null)if(p===null)if(s.stateNode===null){e:{p=s.type,c=s.memoizedProps,C=C.ownerDocument||C;t:switch(p){case"title":A=C.getElementsByTagName("title")[0],(!A||A[Oe]||A[re]||A.namespaceURI==="http://www.w3.org/2000/svg"||A.hasAttribute("itemprop"))&&(A=C.createElement(p),C.head.insertBefore(A,C.querySelector("head > title"))),ys(A,p,c),A[re]=s,et(A),p=A;break e;case"link":var z=cb("link","href",C).get(p+(c.href||""));if(z){for(var ee=0;ee<z.length;ee++)if(A=z[ee],A.getAttribute("href")===(c.href==null||c.href===""?null:c.href)&&A.getAttribute("rel")===(c.rel==null?null:c.rel)&&A.getAttribute("title")===(c.title==null?null:c.title)&&A.getAttribute("crossorigin")===(c.crossOrigin==null?null:c.crossOrigin)){z.splice(ee,1);break t}}A=C.createElement(p),ys(A,p,c),C.head.appendChild(A);break;case"meta":if(z=cb("meta","content",C).get(p+(c.content||""))){for(ee=0;ee<z.length;ee++)if(A=z[ee],A.getAttribute("content")===(c.content==null?null:""+c.content)&&A.getAttribute("name")===(c.name==null?null:c.name)&&A.getAttribute("property")===(c.property==null?null:c.property)&&A.getAttribute("http-equiv")===(c.httpEquiv==null?null:c.httpEquiv)&&A.getAttribute("charset")===(c.charSet==null?null:c.charSet)){z.splice(ee,1);break t}}A=C.createElement(p),ys(A,p,c),C.head.appendChild(A);break;default:throw Error(i(468,p))}A[re]=s,et(A),p=A}s.stateNode=p}else ub(C,s.type,s.stateNode);else s.stateNode=lb(C,p,s.memoizedProps);else A!==p?(A===null?c.stateNode!==null&&(c=c.stateNode,c.parentNode.removeChild(c)):A.count--,p===null?ub(C,s.type,s.stateNode):lb(C,p,s.memoizedProps)):p===null&&s.stateNode!==null&&wh(s,s.memoizedProps,c.memoizedProps)}break;case 27:qs(a,s),Hs(s),p&512&&(cs||c===null||Ui(c,c.return)),c!==null&&p&4&&wh(s,s.memoizedProps,c.memoizedProps);break;case 5:if(qs(a,s),Hs(s),p&512&&(cs||c===null||Ui(c,c.return)),s.flags&32){C=s.stateNode;try{xn(C,"")}catch(_t){Mn(s,s.return,_t)}}p&4&&s.stateNode!=null&&(C=s.memoizedProps,wh(s,C,c!==null?c.memoizedProps:C)),p&1024&&(Eh=!0);break;case 6:if(qs(a,s),Hs(s),p&4){if(s.stateNode===null)throw Error(i(162));p=s.memoizedProps,c=s.stateNode;try{c.nodeValue=p}catch(_t){Mn(s,s.return,_t)}}break;case 3:if(fd=null,C=Ti,Ti=ud(a.containerInfo),qs(a,s),Ti=C,Hs(s),p&4&&c!==null&&c.memoizedState.isDehydrated)try{Fo(a.containerInfo)}catch(_t){Mn(s,s.return,_t)}Eh&&(Eh=!1,uy(s));break;case 4:p=Ti,Ti=ud(s.stateNode.containerInfo),qs(a,s),Hs(s),Ti=p;break;case 12:qs(a,s),Hs(s);break;case 31:qs(a,s),Hs(s),p&4&&(p=s.updateQueue,p!==null&&(s.updateQueue=null,Zu(s,p)));break;case 13:qs(a,s),Hs(s),s.child.flags&8192&&s.memoizedState!==null!=(c!==null&&c.memoizedState!==null)&&(Qu=Ut()),p&4&&(p=s.updateQueue,p!==null&&(s.updateQueue=null,Zu(s,p)));break;case 22:C=s.memoizedState!==null;var he=c!==null&&c.memoizedState!==null,we=cr,Pe=cs;if(cr=we||C,cs=Pe||he,qs(a,s),cs=Pe,cr=we,Hs(s),p&8192)e:for(a=s.stateNode,a._visibility=C?a._visibility&-2:a._visibility|1,C&&(c===null||he||cr||cs||Ba(s)),c=null,a=s;;){if(a.tag===5||a.tag===26){if(c===null){he=c=a;try{if(A=he.stateNode,C)z=A.style,typeof z.setProperty=="function"?z.setProperty("display","none","important"):z.display="none";else{ee=he.stateNode;var Fe=he.memoizedProps.style,Ce=Fe!=null&&Fe.hasOwnProperty("display")?Fe.display:null;ee.style.display=Ce==null||typeof Ce=="boolean"?"":(""+Ce).trim()}}catch(_t){Mn(he,he.return,_t)}}}else if(a.tag===6){if(c===null){he=a;try{he.stateNode.nodeValue=C?"":he.memoizedProps}catch(_t){Mn(he,he.return,_t)}}}else if(a.tag===18){if(c===null){he=a;try{var Te=he.stateNode;C?Jy(Te,!0):Jy(he.stateNode,!1)}catch(_t){Mn(he,he.return,_t)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===s)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===s)break e;for(;a.sibling===null;){if(a.return===null||a.return===s)break e;c===a&&(c=null),a=a.return}c===a&&(c=null),a.sibling.return=a.return,a=a.sibling}p&4&&(p=s.updateQueue,p!==null&&(c=p.retryQueue,c!==null&&(p.retryQueue=null,Zu(s,c))));break;case 19:qs(a,s),Hs(s),p&4&&(p=s.updateQueue,p!==null&&(s.updateQueue=null,Zu(s,p)));break;case 30:break;case 21:break;default:qs(a,s),Hs(s)}}function Hs(s){var a=s.flags;if(a&2){try{for(var c,p=s.return;p!==null;){if(ty(p)){c=p;break}p=p.return}if(c==null)throw Error(i(160));switch(c.tag){case 27:var C=c.stateNode,A=kh(s);Yu(s,A,C);break;case 5:var z=c.stateNode;c.flags&32&&(xn(z,""),c.flags&=-33);var ee=kh(s);Yu(s,ee,z);break;case 3:case 4:var he=c.stateNode.containerInfo,we=kh(s);Ch(s,we,he);break;default:throw Error(i(161))}}catch(Pe){Mn(s,s.return,Pe)}s.flags&=-3}a&4096&&(s.flags&=-4097)}function uy(s){if(s.subtreeFlags&1024)for(s=s.child;s!==null;){var a=s;uy(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),s=s.sibling}}function dr(s,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)iy(s,a.alternate,a),a=a.sibling}function Ba(s){for(s=s.child;s!==null;){var a=s;switch(a.tag){case 0:case 11:case 14:case 15:Gr(4,a,a.return),Ba(a);break;case 1:Ui(a,a.return);var c=a.stateNode;typeof c.componentWillUnmount=="function"&&Jv(a,a.return,c),Ba(a);break;case 27:ac(a.stateNode);case 26:case 5:Ui(a,a.return),Ba(a);break;case 22:a.memoizedState===null&&Ba(a);break;case 30:Ba(a);break;default:Ba(a)}s=s.sibling}}function fr(s,a,c){for(c=c&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var p=a.alternate,C=s,A=a,z=A.flags;switch(A.tag){case 0:case 11:case 15:fr(C,A,c),Zl(4,A);break;case 1:if(fr(C,A,c),p=A,C=p.stateNode,typeof C.componentDidMount=="function")try{C.componentDidMount()}catch(we){Mn(p,p.return,we)}if(p=A,C=p.updateQueue,C!==null){var ee=p.stateNode;try{var he=C.shared.hiddenCallbacks;if(he!==null)for(C.shared.hiddenCallbacks=null,C=0;C<he.length;C++)Ug(he[C],ee)}catch(we){Mn(p,p.return,we)}}c&&z&64&&Qv(A),Xl(A,A.return);break;case 27:ny(A);case 26:case 5:fr(C,A,c),c&&p===null&&z&4&&ey(A),Xl(A,A.return);break;case 12:fr(C,A,c);break;case 31:fr(C,A,c),c&&z&4&&oy(C,A);break;case 13:fr(C,A,c),c&&z&4&&ly(C,A);break;case 22:A.memoizedState===null&&fr(C,A,c),Xl(A,A.return);break;case 30:break;default:fr(C,A,c)}a=a.sibling}}function Nh(s,a){var c=null;s!==null&&s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),s=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(s=a.memoizedState.cachePool.pool),s!==c&&(s!=null&&s.refCount++,c!=null&&Pl(c))}function jh(s,a){s=null,a.alternate!==null&&(s=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==s&&(a.refCount++,s!=null&&Pl(s))}function Ii(s,a,c,p){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)dy(s,a,c,p),a=a.sibling}function dy(s,a,c,p){var C=a.flags;switch(a.tag){case 0:case 11:case 15:Ii(s,a,c,p),C&2048&&Zl(9,a);break;case 1:Ii(s,a,c,p);break;case 3:Ii(s,a,c,p),C&2048&&(s=null,a.alternate!==null&&(s=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==s&&(a.refCount++,s!=null&&Pl(s)));break;case 12:if(C&2048){Ii(s,a,c,p),s=a.stateNode;try{var A=a.memoizedProps,z=A.id,ee=A.onPostCommit;typeof ee=="function"&&ee(z,a.alternate===null?"mount":"update",s.passiveEffectDuration,-0)}catch(he){Mn(a,a.return,he)}}else Ii(s,a,c,p);break;case 31:Ii(s,a,c,p);break;case 13:Ii(s,a,c,p);break;case 23:break;case 22:A=a.stateNode,z=a.alternate,a.memoizedState!==null?A._visibility&2?Ii(s,a,c,p):Ql(s,a):A._visibility&2?Ii(s,a,c,p):(A._visibility|=2,Mo(s,a,c,p,(a.subtreeFlags&10256)!==0||!1)),C&2048&&Nh(z,a);break;case 24:Ii(s,a,c,p),C&2048&&jh(a.alternate,a);break;default:Ii(s,a,c,p)}}function Mo(s,a,c,p,C){for(C=C&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var A=s,z=a,ee=c,he=p,we=z.flags;switch(z.tag){case 0:case 11:case 15:Mo(A,z,ee,he,C),Zl(8,z);break;case 23:break;case 22:var Pe=z.stateNode;z.memoizedState!==null?Pe._visibility&2?Mo(A,z,ee,he,C):Ql(A,z):(Pe._visibility|=2,Mo(A,z,ee,he,C)),C&&we&2048&&Nh(z.alternate,z);break;case 24:Mo(A,z,ee,he,C),C&&we&2048&&jh(z.alternate,z);break;default:Mo(A,z,ee,he,C)}a=a.sibling}}function Ql(s,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var c=s,p=a,C=p.flags;switch(p.tag){case 22:Ql(c,p),C&2048&&Nh(p.alternate,p);break;case 24:Ql(c,p),C&2048&&jh(p.alternate,p);break;default:Ql(c,p)}a=a.sibling}}var Jl=8192;function Do(s,a,c){if(s.subtreeFlags&Jl)for(s=s.child;s!==null;)fy(s,a,c),s=s.sibling}function fy(s,a,c){switch(s.tag){case 26:Do(s,a,c),s.flags&Jl&&s.memoizedState!==null&&jC(c,Ti,s.memoizedState,s.memoizedProps);break;case 5:Do(s,a,c);break;case 3:case 4:var p=Ti;Ti=ud(s.stateNode.containerInfo),Do(s,a,c),Ti=p;break;case 22:s.memoizedState===null&&(p=s.alternate,p!==null&&p.memoizedState!==null?(p=Jl,Jl=16777216,Do(s,a,c),Jl=p):Do(s,a,c));break;default:Do(s,a,c)}}function hy(s){var a=s.alternate;if(a!==null&&(s=a.child,s!==null)){a.child=null;do a=s.sibling,s.sibling=null,s=a;while(s!==null)}}function ec(s){var a=s.deletions;if((s.flags&16)!==0){if(a!==null)for(var c=0;c<a.length;c++){var p=a[c];ps=p,my(p,s)}hy(s)}if(s.subtreeFlags&10256)for(s=s.child;s!==null;)py(s),s=s.sibling}function py(s){switch(s.tag){case 0:case 11:case 15:ec(s),s.flags&2048&&Gr(9,s,s.return);break;case 3:ec(s);break;case 12:ec(s);break;case 22:var a=s.stateNode;s.memoizedState!==null&&a._visibility&2&&(s.return===null||s.return.tag!==13)?(a._visibility&=-3,Xu(s)):ec(s);break;default:ec(s)}}function Xu(s){var a=s.deletions;if((s.flags&16)!==0){if(a!==null)for(var c=0;c<a.length;c++){var p=a[c];ps=p,my(p,s)}hy(s)}for(s=s.child;s!==null;){switch(a=s,a.tag){case 0:case 11:case 15:Gr(8,a,a.return),Xu(a);break;case 22:c=a.stateNode,c._visibility&2&&(c._visibility&=-3,Xu(a));break;default:Xu(a)}s=s.sibling}}function my(s,a){for(;ps!==null;){var c=ps;switch(c.tag){case 0:case 11:case 15:Gr(8,c,a);break;case 23:case 22:if(c.memoizedState!==null&&c.memoizedState.cachePool!==null){var p=c.memoizedState.cachePool.pool;p!=null&&p.refCount++}break;case 24:Pl(c.memoizedState.cache)}if(p=c.child,p!==null)p.return=c,ps=p;else e:for(c=s;ps!==null;){p=ps;var C=p.sibling,A=p.return;if(ry(p),p===c){ps=null;break e}if(C!==null){C.return=A,ps=C;break e}ps=A}}}var Hk={getCacheForType:function(s){var a=gs(as),c=a.data.get(s);return c===void 0&&(c=s(),a.data.set(s,c)),c},cacheSignal:function(){return gs(as).controller.signal}},Fk=typeof WeakMap=="function"?WeakMap:Map,Nn=0,$n=null,mn=null,vn=0,In=0,ii=null,Vr=!1,Lo=!1,Ah=!1,hr=0,Xn=0,Yr=0,$a=0,Rh=0,ri=0,Oo=0,tc=null,Fs=null,Th=!1,Qu=0,gy=0,Ju=1/0,ed=null,Zr=null,fs=0,Xr=null,Po=null,pr=0,Ih=0,Mh=null,vy=null,nc=0,Dh=null;function ai(){return(Nn&2)!==0&&vn!==0?vn&-vn:X.T!==null?zh():M()}function yy(){if(ri===0)if((vn&536870912)===0||pn){var s=mt;mt<<=1,(mt&3932160)===0&&(mt=262144),ri=s}else ri=536870912;return s=ni.current,s!==null&&(s.flags|=32),ri}function Ks(s,a,c){(s===$n&&(In===2||In===9)||s.cancelPendingCommit!==null)&&(Bo(s,0),Qr(s,vn,ri,!1)),Ie(s,c),((Nn&2)===0||s!==$n)&&(s===$n&&((Nn&2)===0&&($a|=c),Xn===4&&Qr(s,vn,ri,!1)),qi(s))}function by(s,a,c){if((Nn&6)!==0)throw Error(i(327));var p=!c&&(a&127)===0&&(a&s.expiredLanes)===0||_n(s,a),C=p?Gk(s,a):Oh(s,a,!0),A=p;do{if(C===0){Lo&&!p&&Qr(s,a,0,!1);break}else{if(c=s.current.alternate,A&&!Kk(c)){C=Oh(s,a,!1),A=!1;continue}if(C===2){if(A=a,s.errorRecoveryDisabledLanes&A)var z=0;else z=s.pendingLanes&-536870913,z=z!==0?z:z&536870912?536870912:0;if(z!==0){a=z;e:{var ee=s;C=tc;var he=ee.current.memoizedState.isDehydrated;if(he&&(Bo(ee,z).flags|=256),z=Oh(ee,z,!1),z!==2){if(Ah&&!he){ee.errorRecoveryDisabledLanes|=A,$a|=A,C=4;break e}A=Fs,Fs=C,A!==null&&(Fs===null?Fs=A:Fs.push.apply(Fs,A))}C=z}if(A=!1,C!==2)continue}}if(C===1){Bo(s,0),Qr(s,a,0,!0);break}e:{switch(p=s,A=C,A){case 0:case 1:throw Error(i(345));case 4:if((a&4194048)!==a)break;case 6:Qr(p,a,ri,!Vr);break e;case 2:Fs=null;break;case 3:case 5:break;default:throw Error(i(329))}if((a&62914560)===a&&(C=Qu+300-Ut(),10<C)){if(Qr(p,a,ri,!Vr),un(p,0,!0)!==0)break e;pr=a,p.timeoutHandle=Zy(_y.bind(null,p,c,Fs,ed,Th,a,ri,$a,Oo,Vr,A,"Throttled",-0,0),C);break e}_y(p,c,Fs,ed,Th,a,ri,$a,Oo,Vr,A,null,-0,0)}}break}while(!0);qi(s)}function _y(s,a,c,p,C,A,z,ee,he,we,Pe,Fe,Ce,Te){if(s.timeoutHandle=-1,Fe=a.subtreeFlags,Fe&8192||(Fe&16785408)===16785408){Fe={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:ki},fy(a,A,Fe);var _t=(A&62914560)===A?Qu-Ut():(A&4194048)===A?gy-Ut():0;if(_t=AC(Fe,_t),_t!==null){pr=A,s.cancelPendingCommit=_t(jy.bind(null,s,a,A,c,p,C,z,ee,he,Pe,Fe,null,Ce,Te)),Qr(s,A,z,!we);return}}jy(s,a,A,c,p,C,z,ee,he)}function Kk(s){for(var a=s;;){var c=a.tag;if((c===0||c===11||c===15)&&a.flags&16384&&(c=a.updateQueue,c!==null&&(c=c.stores,c!==null)))for(var p=0;p<c.length;p++){var C=c[p],A=C.getSnapshot;C=C.value;try{if(!es(A(),C))return!1}catch{return!1}}if(c=a.child,a.subtreeFlags&16384&&c!==null)c.return=a,a=c;else{if(a===s)break;for(;a.sibling===null;){if(a.return===null||a.return===s)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Qr(s,a,c,p){a&=~Rh,a&=~$a,s.suspendedLanes|=a,s.pingedLanes&=~a,p&&(s.warmLanes|=a),p=s.expirationTimes;for(var C=a;0<C;){var A=31-Zt(C),z=1<<A;p[A]=-1,C&=~z}c!==0&&pt(s,c,a)}function td(){return(Nn&6)===0?(sc(0),!1):!0}function Lh(){if(mn!==null){if(In===0)var s=mn.return;else s=mn,zi=sr=null,Xf(s),jo=null,$l=0,s=mn;for(;s!==null;)Xv(s.alternate,s),s=s.return;mn=null}}function Bo(s,a){var c=s.timeoutHandle;c!==-1&&(s.timeoutHandle=-1,dC(c)),c=s.cancelPendingCommit,c!==null&&(s.cancelPendingCommit=null,c()),pr=0,Lh(),$n=s,mn=c=Ai(s.current,null),vn=a,In=0,ii=null,Vr=!1,Lo=_n(s,a),Ah=!1,Oo=ri=Rh=$a=Yr=Xn=0,Fs=tc=null,Th=!1,(a&8)!==0&&(a|=a&32);var p=s.entangledLanes;if(p!==0)for(s=s.entanglements,p&=a;0<p;){var C=31-Zt(p),A=1<<C;a|=s[C],p&=~A}return hr=a,yo(),c}function Sy(s,a){nn=null,X.H=Gl,a===No||a===Ru?(a=Pg(),In=3):a===$f?(a=Pg(),In=4):In=a===hh?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,ii=a,mn===null&&(Xn=1,Fu(s,Bs(a,s.current)))}function xy(){var s=ni.current;return s===null?!0:(vn&4194048)===vn?vi===null:(vn&62914560)===vn||(vn&536870912)!==0?s===vi:!1}function wy(){var s=X.H;return X.H=Gl,s===null?Gl:s}function ky(){var s=X.A;return X.A=Hk,s}function nd(){Xn=4,Vr||(vn&4194048)!==vn&&ni.current!==null||(Lo=!0),(Yr&134217727)===0&&($a&134217727)===0||$n===null||Qr($n,vn,ri,!1)}function Oh(s,a,c){var p=Nn;Nn|=2;var C=wy(),A=ky();($n!==s||vn!==a)&&(ed=null,Bo(s,a)),a=!1;var z=Xn;e:do try{if(In!==0&&mn!==null){var ee=mn,he=ii;switch(In){case 8:Lh(),z=6;break e;case 3:case 2:case 9:case 6:ni.current===null&&(a=!0);var we=In;if(In=0,ii=null,$o(s,ee,he,we),c&&Lo){z=0;break e}break;default:we=In,In=0,ii=null,$o(s,ee,he,we)}}Wk(),z=Xn;break}catch(Pe){Sy(s,Pe)}while(!0);return a&&s.shellSuspendCounter++,zi=sr=null,Nn=p,X.H=C,X.A=A,mn===null&&($n=null,vn=0,yo()),z}function Wk(){for(;mn!==null;)Cy(mn)}function Gk(s,a){var c=Nn;Nn|=2;var p=wy(),C=ky();$n!==s||vn!==a?(ed=null,Ju=Ut()+500,Bo(s,a)):Lo=_n(s,a);e:do try{if(In!==0&&mn!==null){a=mn;var A=ii;t:switch(In){case 1:In=0,ii=null,$o(s,a,A,1);break;case 2:case 9:if(Lg(A)){In=0,ii=null,Ey(a);break}a=function(){In!==2&&In!==9||$n!==s||(In=7),qi(s)},A.then(a,a);break e;case 3:In=7;break e;case 4:In=5;break e;case 7:Lg(A)?(In=0,ii=null,Ey(a)):(In=0,ii=null,$o(s,a,A,7));break;case 5:var z=null;switch(mn.tag){case 26:z=mn.memoizedState;case 5:case 27:var ee=mn;if(z?db(z):ee.stateNode.complete){In=0,ii=null;var he=ee.sibling;if(he!==null)mn=he;else{var we=ee.return;we!==null?(mn=we,sd(we)):mn=null}break t}}In=0,ii=null,$o(s,a,A,5);break;case 6:In=0,ii=null,$o(s,a,A,6);break;case 8:Lh(),Xn=6;break e;default:throw Error(i(462))}}Vk();break}catch(Pe){Sy(s,Pe)}while(!0);return zi=sr=null,X.H=p,X.A=C,Nn=c,mn!==null?0:($n=null,vn=0,yo(),Xn)}function Vk(){for(;mn!==null&&!sn();)Cy(mn)}function Cy(s){var a=Yv(s.alternate,s,hr);s.memoizedProps=s.pendingProps,a===null?sd(s):mn=a}function Ey(s){var a=s,c=a.alternate;switch(a.tag){case 15:case 0:a=Hv(c,a,a.pendingProps,a.type,void 0,vn);break;case 11:a=Hv(c,a,a.pendingProps,a.type.render,a.ref,vn);break;case 5:Xf(a);default:Xv(c,a),a=mn=Cu(a,hr),a=Yv(c,a,hr)}s.memoizedProps=s.pendingProps,a===null?sd(s):mn=a}function $o(s,a,c,p){zi=sr=null,Xf(a),jo=null,$l=0;var C=a.return;try{if(Ok(s,C,a,c,vn)){Xn=1,Fu(s,Bs(c,s.current)),mn=null;return}}catch(A){if(C!==null)throw mn=C,A;Xn=1,Fu(s,Bs(c,s.current)),mn=null;return}a.flags&32768?(pn||p===1?s=!0:Lo||(vn&536870912)!==0?s=!1:(Vr=s=!0,(p===2||p===9||p===3||p===6)&&(p=ni.current,p!==null&&p.tag===13&&(p.flags|=16384))),Ny(a,s)):sd(a)}function sd(s){var a=s;do{if((a.flags&32768)!==0){Ny(a,Vr);return}s=a.return;var c=$k(a.alternate,a,hr);if(c!==null){mn=c;return}if(a=a.sibling,a!==null){mn=a;return}mn=a=s}while(a!==null);Xn===0&&(Xn=5)}function Ny(s,a){do{var c=zk(s.alternate,s);if(c!==null){c.flags&=32767,mn=c;return}if(c=s.return,c!==null&&(c.flags|=32768,c.subtreeFlags=0,c.deletions=null),!a&&(s=s.sibling,s!==null)){mn=s;return}mn=s=c}while(s!==null);Xn=6,mn=null}function jy(s,a,c,p,C,A,z,ee,he){s.cancelPendingCommit=null;do id();while(fs!==0);if((Nn&6)!==0)throw Error(i(327));if(a!==null){if(a===s.current)throw Error(i(177));if(A=a.lanes|a.childLanes,A|=Rl,ot(s,c,A,z,ee,he),s===$n&&(mn=$n=null,vn=0),Po=a,Xr=s,pr=c,Ih=A,Mh=C,vy=p,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(s.callbackNode=null,s.callbackPriority=0,Qk(zt,function(){return My(),null})):(s.callbackNode=null,s.callbackPriority=0),p=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||p){p=X.T,X.T=null,C=de.p,de.p=2,z=Nn,Nn|=4;try{Uk(s,a,c)}finally{Nn=z,de.p=C,X.T=p}}fs=1,Ay(),Ry(),Ty()}}function Ay(){if(fs===1){fs=0;var s=Xr,a=Po,c=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||c){c=X.T,X.T=null;var p=de.p;de.p=2;var C=Nn;Nn|=4;try{cy(a,s);var A=Vh,z=Cl(s.containerInfo),ee=A.focusedElem,he=A.selectionRange;if(z!==ee&&ee&&ee.ownerDocument&&xu(ee.ownerDocument.documentElement,ee)){if(he!==null&&Pi(ee)){var we=he.start,Pe=he.end;if(Pe===void 0&&(Pe=we),"selectionStart"in ee)ee.selectionStart=we,ee.selectionEnd=Math.min(Pe,ee.value.length);else{var Fe=ee.ownerDocument||document,Ce=Fe&&Fe.defaultView||window;if(Ce.getSelection){var Te=Ce.getSelection(),_t=ee.textContent.length,qt=Math.min(he.start,_t),Pn=he.end===void 0?qt:Math.min(he.end,_t);!Te.extend&&qt>Pn&&(z=Pn,Pn=qt,qt=z);var _e=Qi(ee,qt),pe=Qi(ee,Pn);if(_e&&pe&&(Te.rangeCount!==1||Te.anchorNode!==_e.node||Te.anchorOffset!==_e.offset||Te.focusNode!==pe.node||Te.focusOffset!==pe.offset)){var xe=Fe.createRange();xe.setStart(_e.node,_e.offset),Te.removeAllRanges(),qt>Pn?(Te.addRange(xe),Te.extend(pe.node,pe.offset)):(xe.setEnd(pe.node,pe.offset),Te.addRange(xe))}}}}for(Fe=[],Te=ee;Te=Te.parentNode;)Te.nodeType===1&&Fe.push({element:Te,left:Te.scrollLeft,top:Te.scrollTop});for(typeof ee.focus=="function"&&ee.focus(),ee=0;ee<Fe.length;ee++){var qe=Fe[ee];qe.element.scrollLeft=qe.left,qe.element.scrollTop=qe.top}}gd=!!Gh,Vh=Gh=null}finally{Nn=C,de.p=p,X.T=c}}s.current=a,fs=2}}function Ry(){if(fs===2){fs=0;var s=Xr,a=Po,c=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||c){c=X.T,X.T=null;var p=de.p;de.p=2;var C=Nn;Nn|=4;try{iy(s,a.alternate,a)}finally{Nn=C,de.p=p,X.T=c}}fs=3}}function Ty(){if(fs===4||fs===3){fs=0,Ct();var s=Xr,a=Po,c=pr,p=vy;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?fs=5:(fs=0,Po=Xr=null,Iy(s,s.pendingLanes));var C=s.pendingLanes;if(C===0&&(Zr=null),G(c),a=a.stateNode,Vt&&typeof Vt.onCommitFiberRoot=="function")try{Vt.onCommitFiberRoot(Pt,a,void 0,(a.current.flags&128)===128)}catch{}if(p!==null){a=X.T,C=de.p,de.p=2,X.T=null;try{for(var A=s.onRecoverableError,z=0;z<p.length;z++){var ee=p[z];A(ee.value,{componentStack:ee.stack})}}finally{X.T=a,de.p=C}}(pr&3)!==0&&id(),qi(s),C=s.pendingLanes,(c&261930)!==0&&(C&42)!==0?s===Dh?nc++:(nc=0,Dh=s):nc=0,sc(0)}}function Iy(s,a){(s.pooledCacheLanes&=a)===0&&(a=s.pooledCache,a!=null&&(s.pooledCache=null,Pl(a)))}function id(){return Ay(),Ry(),Ty(),My()}function My(){if(fs!==5)return!1;var s=Xr,a=Ih;Ih=0;var c=G(pr),p=X.T,C=de.p;try{de.p=32>c?32:c,X.T=null,c=Mh,Mh=null;var A=Xr,z=pr;if(fs=0,Po=Xr=null,pr=0,(Nn&6)!==0)throw Error(i(331));var ee=Nn;if(Nn|=4,py(A.current),dy(A,A.current,z,c),Nn=ee,sc(0,!1),Vt&&typeof Vt.onPostCommitFiberRoot=="function")try{Vt.onPostCommitFiberRoot(Pt,A)}catch{}return!0}finally{de.p=C,X.T=p,Iy(s,a)}}function Dy(s,a,c){a=Bs(c,a),a=fh(s.stateNode,a,2),s=Fr(s,a,2),s!==null&&(Ie(s,2),qi(s))}function Mn(s,a,c){if(s.tag===3)Dy(s,s,c);else for(;a!==null;){if(a.tag===3){Dy(a,s,c);break}else if(a.tag===1){var p=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof p.componentDidCatch=="function"&&(Zr===null||!Zr.has(p))){s=Bs(c,s),c=Lv(2),p=Fr(a,c,2),p!==null&&(Ov(c,p,a,s),Ie(p,2),qi(p));break}}a=a.return}}function Ph(s,a,c){var p=s.pingCache;if(p===null){p=s.pingCache=new Fk;var C=new Set;p.set(a,C)}else C=p.get(a),C===void 0&&(C=new Set,p.set(a,C));C.has(c)||(Ah=!0,C.add(c),s=Yk.bind(null,s,a,c),a.then(s,s))}function Yk(s,a,c){var p=s.pingCache;p!==null&&p.delete(a),s.pingedLanes|=s.suspendedLanes&c,s.warmLanes&=~c,$n===s&&(vn&c)===c&&(Xn===4||Xn===3&&(vn&62914560)===vn&&300>Ut()-Qu?(Nn&2)===0&&Bo(s,0):Rh|=c,Oo===vn&&(Oo=0)),qi(s)}function Ly(s,a){a===0&&(a=zn()),s=tr(s,a),s!==null&&(Ie(s,a),qi(s))}function Zk(s){var a=s.memoizedState,c=0;a!==null&&(c=a.retryLane),Ly(s,c)}function Xk(s,a){var c=0;switch(s.tag){case 31:case 13:var p=s.stateNode,C=s.memoizedState;C!==null&&(c=C.retryLane);break;case 19:p=s.stateNode;break;case 22:p=s.stateNode._retryCache;break;default:throw Error(i(314))}p!==null&&p.delete(a),Ly(s,c)}function Qk(s,a){return Bt(s,a)}var rd=null,zo=null,Bh=!1,ad=!1,$h=!1,Jr=0;function qi(s){s!==zo&&s.next===null&&(zo===null?rd=zo=s:zo=zo.next=s),ad=!0,Bh||(Bh=!0,eC())}function sc(s,a){if(!$h&&ad){$h=!0;do for(var c=!1,p=rd;p!==null;){if(s!==0){var C=p.pendingLanes;if(C===0)var A=0;else{var z=p.suspendedLanes,ee=p.pingedLanes;A=(1<<31-Zt(42|s)+1)-1,A&=C&~(z&~ee),A=A&201326741?A&201326741|1:A?A|2:0}A!==0&&(c=!0,$y(p,A))}else A=vn,A=un(p,p===$n?A:0,p.cancelPendingCommit!==null||p.timeoutHandle!==-1),(A&3)===0||_n(p,A)||(c=!0,$y(p,A));p=p.next}while(c);$h=!1}}function Jk(){Oy()}function Oy(){ad=Bh=!1;var s=0;Jr!==0&&uC()&&(s=Jr);for(var a=Ut(),c=null,p=rd;p!==null;){var C=p.next,A=Py(p,a);A===0?(p.next=null,c===null?rd=C:c.next=C,C===null&&(zo=c)):(c=p,(s!==0||(A&3)!==0)&&(ad=!0)),p=C}fs!==0&&fs!==5||sc(s),Jr!==0&&(Jr=0)}function Py(s,a){for(var c=s.suspendedLanes,p=s.pingedLanes,C=s.expirationTimes,A=s.pendingLanes&-62914561;0<A;){var z=31-Zt(A),ee=1<<z,he=C[z];he===-1?((ee&c)===0||(ee&p)!==0)&&(C[z]=tn(ee,a)):he<=a&&(s.expiredLanes|=ee),A&=~ee}if(a=$n,c=vn,c=un(s,s===a?c:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),p=s.callbackNode,c===0||s===a&&(In===2||In===9)||s.cancelPendingCommit!==null)return p!==null&&p!==null&&hn(p),s.callbackNode=null,s.callbackPriority=0;if((c&3)===0||_n(s,c)){if(a=c&-c,a===s.callbackPriority)return a;switch(p!==null&&hn(p),G(c)){case 2:case 8:c=Ht;break;case 32:c=zt;break;case 268435456:c=ze;break;default:c=zt}return p=By.bind(null,s),c=Bt(c,p),s.callbackPriority=a,s.callbackNode=c,a}return p!==null&&p!==null&&hn(p),s.callbackPriority=2,s.callbackNode=null,2}function By(s,a){if(fs!==0&&fs!==5)return s.callbackNode=null,s.callbackPriority=0,null;var c=s.callbackNode;if(id()&&s.callbackNode!==c)return null;var p=vn;return p=un(s,s===$n?p:0,s.cancelPendingCommit!==null||s.timeoutHandle!==-1),p===0?null:(by(s,p,a),Py(s,Ut()),s.callbackNode!=null&&s.callbackNode===c?By.bind(null,s):null)}function $y(s,a){if(id())return null;by(s,a,!0)}function eC(){fC(function(){(Nn&6)!==0?Bt(Lt,Jk):Oy()})}function zh(){if(Jr===0){var s=Co;s===0&&(s=je,je<<=1,(je&261888)===0&&(je=256)),Jr=s}return Jr}function zy(s){return s==null||typeof s=="symbol"||typeof s=="boolean"?null:typeof s=="function"?s:ya(""+s)}function Uy(s,a){var c=a.ownerDocument.createElement("input");return c.name=a.name,c.value=a.value,s.id&&c.setAttribute("form",s.id),a.parentNode.insertBefore(c,a),s=new FormData(s),c.parentNode.removeChild(c),s}function tC(s,a,c,p,C){if(a==="submit"&&c&&c.stateNode===C){var A=zy((C[ve]||null).action),z=p.submitter;z&&(a=(a=z[ve]||null)?zy(a.formAction):z.getAttribute("formAction"),a!==null&&(A=a,z=null));var ee=new lo("action","action",null,p,C);s.push({event:ee,listeners:[{instance:null,listener:function(){if(p.defaultPrevented){if(Jr!==0){var he=z?Uy(C,z):new FormData(C);ah(c,{pending:!0,data:he,method:C.method,action:A},null,he)}}else typeof A=="function"&&(ee.preventDefault(),he=z?Uy(C,z):new FormData(C),ah(c,{pending:!0,data:he,method:C.method,action:A},A,he))},currentTarget:C}]})}}for(var Uh=0;Uh<Al.length;Uh++){var qh=Al[Uh],nC=qh.toLowerCase(),sC=qh[0].toUpperCase()+qh.slice(1);Qs(nC,"on"+sC)}Qs(Nl,"onAnimationEnd"),Qs(Na,"onAnimationIteration"),Qs(vo,"onAnimationStart"),Qs("dblclick","onDoubleClick"),Qs("focusin","onFocus"),Qs("focusout","onBlur"),Qs(ja,"onTransitionRun"),Qs(Or,"onTransitionStart"),Qs(If,"onTransitionCancel"),Qs(jl,"onTransitionEnd"),ft("onMouseEnter",["mouseout","mouseover"]),ft("onMouseLeave",["mouseout","mouseover"]),ft("onPointerEnter",["pointerout","pointerover"]),ft("onPointerLeave",["pointerout","pointerover"]),it("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),it("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),it("onBeforeInput",["compositionend","keypress","textInput","paste"]),it("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),it("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),it("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var ic="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),iC=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(ic));function qy(s,a){a=(a&4)!==0;for(var c=0;c<s.length;c++){var p=s[c],C=p.event;p=p.listeners;e:{var A=void 0;if(a)for(var z=p.length-1;0<=z;z--){var ee=p[z],he=ee.instance,we=ee.currentTarget;if(ee=ee.listener,he!==A&&C.isPropagationStopped())break e;A=ee,C.currentTarget=we;try{A(C)}catch(Pe){er(Pe)}C.currentTarget=null,A=he}else for(z=0;z<p.length;z++){if(ee=p[z],he=ee.instance,we=ee.currentTarget,ee=ee.listener,he!==A&&C.isPropagationStopped())break e;A=ee,C.currentTarget=we;try{A(C)}catch(Pe){er(Pe)}C.currentTarget=null,A=he}}}}function gn(s,a){var c=a[Ze];c===void 0&&(c=a[Ze]=new Set);var p=s+"__bubble";c.has(p)||(Hy(a,s,2,!1),c.add(p))}function Hh(s,a,c){var p=0;a&&(p|=4),Hy(c,s,p,a)}var od="_reactListening"+Math.random().toString(36).slice(2);function Fh(s){if(!s[od]){s[od]=!0,st.forEach(function(c){c!=="selectionchange"&&(iC.has(c)||Hh(c,!1,s),Hh(c,!0,s))});var a=s.nodeType===9?s:s.ownerDocument;a===null||a[od]||(a[od]=!0,Hh("selectionchange",!1,a))}}function Hy(s,a,c,p){switch(yb(a)){case 2:var C=IC;break;case 8:C=MC;break;default:C=rp}c=C.bind(null,a,c,s),C=void 0,!ro||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(C=!0),p?C!==void 0?s.addEventListener(a,c,{capture:!0,passive:C}):s.addEventListener(a,c,!0):C!==void 0?s.addEventListener(a,c,{passive:C}):s.addEventListener(a,c,!1)}function Kh(s,a,c,p,C){var A=p;if((a&1)===0&&(a&2)===0&&p!==null)e:for(;;){if(p===null)return;var z=p.tag;if(z===3||z===4){var ee=p.stateNode.containerInfo;if(ee===C)break;if(z===4)for(z=p.return;z!==null;){var he=z.tag;if((he===3||he===4)&&z.stateNode.containerInfo===C)return;z=z.return}for(;ee!==null;){if(z=ke(ee),z===null)return;if(he=z.tag,he===5||he===6||he===26||he===27){p=A=z;continue e}ee=ee.parentNode}}p=p.return}Xc(function(){var we=A,Pe=hl(c),Fe=[];e:{var Ce=wu.get(s);if(Ce!==void 0){var Te=lo,_t=s;switch(s){case"keypress":if(Nr(c)===0)break e;case"keydown":case"keyup":Te=uo;break;case"focusin":_t="focus",Te=gl;break;case"focusout":_t="blur",Te=gl;break;case"beforeblur":case"afterblur":Te=gl;break;case"click":if(c.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":Te=Qc;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":Te=Tr;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":Te=Sa;break;case Nl:case Na:case vo:Te=kf;break;case jl:Te=ou;break;case"scroll":case"scrollend":Te=xf;break;case"wheel":Te=lu;break;case"copy":case"cut":case"paste":Te=Cf;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":Te=iu;break;case"toggle":case"beforetoggle":Te=cu}var qt=(a&4)!==0,Pn=!qt&&(s==="scroll"||s==="scrollend"),_e=qt?Ce!==null?Ce+"Capture":null:Ce;qt=[];for(var pe=we,xe;pe!==null;){var qe=pe;if(xe=qe.stateNode,qe=qe.tag,qe!==5&&qe!==26&&qe!==27||xe===null||_e===null||(qe=ba(pe,_e),qe!=null&&qt.push(rc(pe,qe,xe))),Pn)break;pe=pe.return}0<qt.length&&(Ce=new Te(Ce,_t,null,c,Pe),Fe.push({event:Ce,listeners:qt}))}}if((a&7)===0){e:{if(Ce=s==="mouseover"||s==="pointerover",Te=s==="mouseout"||s==="pointerout",Ce&&c!==io&&(_t=c.relatedTarget||c.fromElement)&&(ke(_t)||_t[Me]))break e;if((Te||Ce)&&(Ce=Pe.window===Pe?Pe:(Ce=Pe.ownerDocument)?Ce.defaultView||Ce.parentWindow:window,Te?(_t=c.relatedTarget||c.toElement,Te=we,_t=_t?ke(_t):null,_t!==null&&(Pn=d(_t),qt=_t.tag,_t!==Pn||qt!==5&&qt!==27&&qt!==6)&&(_t=null)):(Te=null,_t=we),Te!==_t)){if(qt=Qc,qe="onMouseLeave",_e="onMouseEnter",pe="mouse",(s==="pointerout"||s==="pointerover")&&(qt=iu,qe="onPointerLeave",_e="onPointerEnter",pe="pointer"),Pn=Te==null?Ce:rt(Te),xe=_t==null?Ce:rt(_t),Ce=new qt(qe,pe+"leave",Te,c,Pe),Ce.target=Pn,Ce.relatedTarget=xe,qe=null,ke(Pe)===we&&(qt=new qt(_e,pe+"enter",_t,c,Pe),qt.target=xe,qt.relatedTarget=Pn,qe=qt),Pn=qe,Te&&_t)t:{for(qt=rC,_e=Te,pe=_t,xe=0,qe=_e;qe;qe=qt(qe))xe++;qe=0;for(var Ot=pe;Ot;Ot=qt(Ot))qe++;for(;0<xe-qe;)_e=qt(_e),xe--;for(;0<qe-xe;)pe=qt(pe),qe--;for(;xe--;){if(_e===pe||pe!==null&&_e===pe.alternate){qt=_e;break t}_e=qt(_e),pe=qt(pe)}qt=null}else qt=null;Te!==null&&Fy(Fe,Ce,Te,qt,!1),_t!==null&&Pn!==null&&Fy(Fe,Pn,_t,qt,!0)}}e:{if(Ce=we?rt(we):window,Te=Ce.nodeName&&Ce.nodeName.toLowerCase(),Te==="select"||Te==="input"&&Ce.type==="file")var kn=yu;else if(gu(Ce))if(Sl)kn=Af;else{kn=Su;var Et=_u}else Te=Ce.nodeName,!Te||Te.toLowerCase()!=="input"||Ce.type!=="checkbox"&&Ce.type!=="radio"?we&&Vn(we.elementType)&&(kn=yu):kn=jf;if(kn&&(kn=kn(s,we))){vu(Fe,kn,c,Pe);break e}Et&&Et(s,Ce,we),s==="focusout"&&we&&Ce.type==="number"&&we.memoizedProps.value!=null&&Jt(Ce,"number",Ce.value)}switch(Et=we?rt(we):window,s){case"focusin":(gu(Et)||Et.contentEditable==="true")&&(Lr=Et,mo=we,Ni=null);break;case"focusout":Ni=mo=Lr=null;break;case"mousedown":go=!0;break;case"contextmenu":case"mouseup":case"dragend":go=!1,Bi(Fe,c,Pe);break;case"selectionchange":if(Tf)break;case"keydown":case"keyup":Bi(Fe,c,Pe)}var an;if(fo)e:{switch(s){case"compositionstart":var yn="onCompositionStart";break e;case"compositionend":yn="onCompositionEnd";break e;case"compositionupdate":yn="onCompositionUpdate";break e}yn=void 0}else di?fu(s,c)&&(yn="onCompositionEnd"):s==="keydown"&&c.keyCode===229&&(yn="onCompositionStart");yn&&(xa&&c.locale!=="ko"&&(di||yn!=="onCompositionStart"?yn==="onCompositionEnd"&&di&&(an=ao()):(Ls=Pe,pl="value"in Ls?Ls.value:Ls.textContent,di=!0)),Et=ld(we,yn),0<Et.length&&(yn=new Ir(yn,s,null,c,Pe),Fe.push({event:yn,listeners:Et}),an?yn.data=an:(an=hu(c),an!==null&&(yn.data=an)))),(an=ho?pu(s,c):Nf(s,c))&&(yn=ld(we,"onBeforeInput"),0<yn.length&&(Et=new Ir("onBeforeInput","beforeinput",null,c,Pe),Fe.push({event:Et,listeners:yn}),Et.data=an)),tC(Fe,s,we,c,Pe)}qy(Fe,a)})}function rc(s,a,c){return{instance:s,listener:a,currentTarget:c}}function ld(s,a){for(var c=a+"Capture",p=[];s!==null;){var C=s,A=C.stateNode;if(C=C.tag,C!==5&&C!==26&&C!==27||A===null||(C=ba(s,c),C!=null&&p.unshift(rc(s,C,A)),C=ba(s,a),C!=null&&p.push(rc(s,C,A))),s.tag===3)return p;s=s.return}return[]}function rC(s){if(s===null)return null;do s=s.return;while(s&&s.tag!==5&&s.tag!==27);return s||null}function Fy(s,a,c,p,C){for(var A=a._reactName,z=[];c!==null&&c!==p;){var ee=c,he=ee.alternate,we=ee.stateNode;if(ee=ee.tag,he!==null&&he===p)break;ee!==5&&ee!==26&&ee!==27||we===null||(he=we,C?(we=ba(c,A),we!=null&&z.unshift(rc(c,we,he))):C||(we=ba(c,A),we!=null&&z.push(rc(c,we,he)))),c=c.return}z.length!==0&&s.push({event:a,listeners:z})}var aC=/\r\n?/g,oC=/\u0000|\uFFFD/g;function Ky(s){return(typeof s=="string"?s:""+s).replace(aC,`
|
|
9
|
-
`).replace(oC,"")}function Wy(s,a){return a=Ky(a),Ky(s)===a}function On(s,a,c,p,C,A){switch(c){case"children":typeof p=="string"?a==="body"||a==="textarea"&&p===""||xn(s,p):(typeof p=="number"||typeof p=="bigint")&&a!=="body"&&xn(s,""+p);break;case"className":$e(s,"class",p);break;case"tabIndex":$e(s,"tabindex",p);break;case"dir":case"role":case"viewBox":case"width":case"height":$e(s,c,p);break;case"style":Un(s,p,A);break;case"data":if(a!=="object"){$e(s,"data",p);break}case"src":case"href":if(p===""&&(a!=="a"||c!=="href")){s.removeAttribute(c);break}if(p==null||typeof p=="function"||typeof p=="symbol"||typeof p=="boolean"){s.removeAttribute(c);break}p=ya(""+p),s.setAttribute(c,p);break;case"action":case"formAction":if(typeof p=="function"){s.setAttribute(c,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof A=="function"&&(c==="formAction"?(a!=="input"&&On(s,a,"name",C.name,C,null),On(s,a,"formEncType",C.formEncType,C,null),On(s,a,"formMethod",C.formMethod,C,null),On(s,a,"formTarget",C.formTarget,C,null)):(On(s,a,"encType",C.encType,C,null),On(s,a,"method",C.method,C,null),On(s,a,"target",C.target,C,null)));if(p==null||typeof p=="symbol"||typeof p=="boolean"){s.removeAttribute(c);break}p=ya(""+p),s.setAttribute(c,p);break;case"onClick":p!=null&&(s.onclick=ki);break;case"onScroll":p!=null&&gn("scroll",s);break;case"onScrollEnd":p!=null&&gn("scrollend",s);break;case"dangerouslySetInnerHTML":if(p!=null){if(typeof p!="object"||!("__html"in p))throw Error(i(61));if(c=p.__html,c!=null){if(C.children!=null)throw Error(i(60));s.innerHTML=c}}break;case"multiple":s.multiple=p&&typeof p!="function"&&typeof p!="symbol";break;case"muted":s.muted=p&&typeof p!="function"&&typeof p!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(p==null||typeof p=="function"||typeof p=="boolean"||typeof p=="symbol"){s.removeAttribute("xlink:href");break}c=ya(""+p),s.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",c);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":p!=null&&typeof p!="function"&&typeof p!="symbol"?s.setAttribute(c,""+p):s.removeAttribute(c);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":p&&typeof p!="function"&&typeof p!="symbol"?s.setAttribute(c,""):s.removeAttribute(c);break;case"capture":case"download":p===!0?s.setAttribute(c,""):p!==!1&&p!=null&&typeof p!="function"&&typeof p!="symbol"?s.setAttribute(c,p):s.removeAttribute(c);break;case"cols":case"rows":case"size":case"span":p!=null&&typeof p!="function"&&typeof p!="symbol"&&!isNaN(p)&&1<=p?s.setAttribute(c,p):s.removeAttribute(c);break;case"rowSpan":case"start":p==null||typeof p=="function"||typeof p=="symbol"||isNaN(p)?s.removeAttribute(c):s.setAttribute(c,p);break;case"popover":gn("beforetoggle",s),gn("toggle",s),Ke(s,"popover",p);break;case"xlinkActuate":Le(s,"http://www.w3.org/1999/xlink","xlink:actuate",p);break;case"xlinkArcrole":Le(s,"http://www.w3.org/1999/xlink","xlink:arcrole",p);break;case"xlinkRole":Le(s,"http://www.w3.org/1999/xlink","xlink:role",p);break;case"xlinkShow":Le(s,"http://www.w3.org/1999/xlink","xlink:show",p);break;case"xlinkTitle":Le(s,"http://www.w3.org/1999/xlink","xlink:title",p);break;case"xlinkType":Le(s,"http://www.w3.org/1999/xlink","xlink:type",p);break;case"xmlBase":Le(s,"http://www.w3.org/XML/1998/namespace","xml:base",p);break;case"xmlLang":Le(s,"http://www.w3.org/XML/1998/namespace","xml:lang",p);break;case"xmlSpace":Le(s,"http://www.w3.org/XML/1998/namespace","xml:space",p);break;case"is":Ke(s,"is",p);break;case"innerText":case"textContent":break;default:(!(2<c.length)||c[0]!=="o"&&c[0]!=="O"||c[1]!=="n"&&c[1]!=="N")&&(c=Jn.get(c)||c,Ke(s,c,p))}}function Wh(s,a,c,p,C,A){switch(c){case"style":Un(s,p,A);break;case"dangerouslySetInnerHTML":if(p!=null){if(typeof p!="object"||!("__html"in p))throw Error(i(61));if(c=p.__html,c!=null){if(C.children!=null)throw Error(i(60));s.innerHTML=c}}break;case"children":typeof p=="string"?xn(s,p):(typeof p=="number"||typeof p=="bigint")&&xn(s,""+p);break;case"onScroll":p!=null&&gn("scroll",s);break;case"onScrollEnd":p!=null&&gn("scrollend",s);break;case"onClick":p!=null&&(s.onclick=ki);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!gt.hasOwnProperty(c))e:{if(c[0]==="o"&&c[1]==="n"&&(C=c.endsWith("Capture"),a=c.slice(2,C?c.length-7:void 0),A=s[ve]||null,A=A!=null?A[c]:null,typeof A=="function"&&s.removeEventListener(a,A,C),typeof p=="function")){typeof A!="function"&&A!==null&&(c in s?s[c]=null:s.hasAttribute(c)&&s.removeAttribute(c)),s.addEventListener(a,p,C);break e}c in s?s[c]=p:p===!0?s.setAttribute(c,""):Ke(s,c,p)}}}function ys(s,a,c){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":gn("error",s),gn("load",s);var p=!1,C=!1,A;for(A in c)if(c.hasOwnProperty(A)){var z=c[A];if(z!=null)switch(A){case"src":p=!0;break;case"srcSet":C=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(i(137,a));default:On(s,a,A,z,c,null)}}C&&On(s,a,"srcSet",c.srcSet,c,null),p&&On(s,a,"src",c.src,c,null);return;case"input":gn("invalid",s);var ee=A=z=C=null,he=null,we=null;for(p in c)if(c.hasOwnProperty(p)){var Pe=c[p];if(Pe!=null)switch(p){case"name":C=Pe;break;case"type":z=Pe;break;case"checked":he=Pe;break;case"defaultChecked":we=Pe;break;case"value":A=Pe;break;case"defaultValue":ee=Pe;break;case"children":case"dangerouslySetInnerHTML":if(Pe!=null)throw Error(i(137,a));break;default:On(s,a,p,Pe,c,null)}}Kt(s,A,ee,he,we,z,C,!1);return;case"select":gn("invalid",s),p=z=A=null;for(C in c)if(c.hasOwnProperty(C)&&(ee=c[C],ee!=null))switch(C){case"value":A=ee;break;case"defaultValue":z=ee;break;case"multiple":p=ee;default:On(s,a,C,ee,c,null)}a=A,c=z,s.multiple=!!p,a!=null?Yt(s,!!p,a,!1):c!=null&&Yt(s,!!p,c,!0);return;case"textarea":gn("invalid",s),A=C=p=null;for(z in c)if(c.hasOwnProperty(z)&&(ee=c[z],ee!=null))switch(z){case"value":p=ee;break;case"defaultValue":C=ee;break;case"children":A=ee;break;case"dangerouslySetInnerHTML":if(ee!=null)throw Error(i(91));break;default:On(s,a,z,ee,c,null)}bn(s,p,C,A);return;case"option":for(he in c)c.hasOwnProperty(he)&&(p=c[he],p!=null)&&(he==="selected"?s.selected=p&&typeof p!="function"&&typeof p!="symbol":On(s,a,he,p,c,null));return;case"dialog":gn("beforetoggle",s),gn("toggle",s),gn("cancel",s),gn("close",s);break;case"iframe":case"object":gn("load",s);break;case"video":case"audio":for(p=0;p<ic.length;p++)gn(ic[p],s);break;case"image":gn("error",s),gn("load",s);break;case"details":gn("toggle",s);break;case"embed":case"source":case"link":gn("error",s),gn("load",s);case"area":case"base":case"br":case"col":case"hr":case"keygen":case"meta":case"param":case"track":case"wbr":case"menuitem":for(we in c)if(c.hasOwnProperty(we)&&(p=c[we],p!=null))switch(we){case"children":case"dangerouslySetInnerHTML":throw Error(i(137,a));default:On(s,a,we,p,c,null)}return;default:if(Vn(a)){for(Pe in c)c.hasOwnProperty(Pe)&&(p=c[Pe],p!==void 0&&Wh(s,a,Pe,p,c,void 0));return}}for(ee in c)c.hasOwnProperty(ee)&&(p=c[ee],p!=null&&On(s,a,ee,p,c,null))}function lC(s,a,c,p){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var C=null,A=null,z=null,ee=null,he=null,we=null,Pe=null;for(Te in c){var Fe=c[Te];if(c.hasOwnProperty(Te)&&Fe!=null)switch(Te){case"checked":break;case"value":break;case"defaultValue":he=Fe;default:p.hasOwnProperty(Te)||On(s,a,Te,null,p,Fe)}}for(var Ce in p){var Te=p[Ce];if(Fe=c[Ce],p.hasOwnProperty(Ce)&&(Te!=null||Fe!=null))switch(Ce){case"type":A=Te;break;case"name":C=Te;break;case"checked":we=Te;break;case"defaultChecked":Pe=Te;break;case"value":z=Te;break;case"defaultValue":ee=Te;break;case"children":case"dangerouslySetInnerHTML":if(Te!=null)throw Error(i(137,a));break;default:Te!==Fe&&On(s,a,Ce,Te,p,Fe)}}Qt(s,z,ee,he,we,Pe,A,C);return;case"select":Te=z=ee=Ce=null;for(A in c)if(he=c[A],c.hasOwnProperty(A)&&he!=null)switch(A){case"value":break;case"multiple":Te=he;default:p.hasOwnProperty(A)||On(s,a,A,null,p,he)}for(C in p)if(A=p[C],he=c[C],p.hasOwnProperty(C)&&(A!=null||he!=null))switch(C){case"value":Ce=A;break;case"defaultValue":ee=A;break;case"multiple":z=A;default:A!==he&&On(s,a,C,A,p,he)}a=ee,c=z,p=Te,Ce!=null?Yt(s,!!c,Ce,!1):!!p!=!!c&&(a!=null?Yt(s,!!c,a,!0):Yt(s,!!c,c?[]:"",!1));return;case"textarea":Te=Ce=null;for(ee in c)if(C=c[ee],c.hasOwnProperty(ee)&&C!=null&&!p.hasOwnProperty(ee))switch(ee){case"value":break;case"children":break;default:On(s,a,ee,null,p,C)}for(z in p)if(C=p[z],A=c[z],p.hasOwnProperty(z)&&(C!=null||A!=null))switch(z){case"value":Ce=C;break;case"defaultValue":Te=C;break;case"children":break;case"dangerouslySetInnerHTML":if(C!=null)throw Error(i(91));break;default:C!==A&&On(s,a,z,C,p,A)}An(s,Ce,Te);return;case"option":for(var _t in c)Ce=c[_t],c.hasOwnProperty(_t)&&Ce!=null&&!p.hasOwnProperty(_t)&&(_t==="selected"?s.selected=!1:On(s,a,_t,null,p,Ce));for(he in p)Ce=p[he],Te=c[he],p.hasOwnProperty(he)&&Ce!==Te&&(Ce!=null||Te!=null)&&(he==="selected"?s.selected=Ce&&typeof Ce!="function"&&typeof Ce!="symbol":On(s,a,he,Ce,p,Te));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var qt in c)Ce=c[qt],c.hasOwnProperty(qt)&&Ce!=null&&!p.hasOwnProperty(qt)&&On(s,a,qt,null,p,Ce);for(we in p)if(Ce=p[we],Te=c[we],p.hasOwnProperty(we)&&Ce!==Te&&(Ce!=null||Te!=null))switch(we){case"children":case"dangerouslySetInnerHTML":if(Ce!=null)throw Error(i(137,a));break;default:On(s,a,we,Ce,p,Te)}return;default:if(Vn(a)){for(var Pn in c)Ce=c[Pn],c.hasOwnProperty(Pn)&&Ce!==void 0&&!p.hasOwnProperty(Pn)&&Wh(s,a,Pn,void 0,p,Ce);for(Pe in p)Ce=p[Pe],Te=c[Pe],!p.hasOwnProperty(Pe)||Ce===Te||Ce===void 0&&Te===void 0||Wh(s,a,Pe,Ce,p,Te);return}}for(var _e in c)Ce=c[_e],c.hasOwnProperty(_e)&&Ce!=null&&!p.hasOwnProperty(_e)&&On(s,a,_e,null,p,Ce);for(Fe in p)Ce=p[Fe],Te=c[Fe],!p.hasOwnProperty(Fe)||Ce===Te||Ce==null&&Te==null||On(s,a,Fe,Ce,p,Te)}function Gy(s){switch(s){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function cC(){if(typeof performance.getEntriesByType=="function"){for(var s=0,a=0,c=performance.getEntriesByType("resource"),p=0;p<c.length;p++){var C=c[p],A=C.transferSize,z=C.initiatorType,ee=C.duration;if(A&&ee&&Gy(z)){for(z=0,ee=C.responseEnd,p+=1;p<c.length;p++){var he=c[p],we=he.startTime;if(we>ee)break;var Pe=he.transferSize,Fe=he.initiatorType;Pe&&Gy(Fe)&&(he=he.responseEnd,z+=Pe*(he<ee?1:(ee-we)/(he-we)))}if(--p,a+=8*(A+z)/(C.duration/1e3),s++,10<s)break}}if(0<s)return a/s/1e6}return navigator.connection&&(s=navigator.connection.downlink,typeof s=="number")?s:5}var Gh=null,Vh=null;function cd(s){return s.nodeType===9?s:s.ownerDocument}function Vy(s){switch(s){case"http://www.w3.org/2000/svg":return 1;case"http://www.w3.org/1998/Math/MathML":return 2;default:return 0}}function Yy(s,a){if(s===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return s===1&&a==="foreignObject"?0:s}function Yh(s,a){return s==="textarea"||s==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var Zh=null;function uC(){var s=window.event;return s&&s.type==="popstate"?s===Zh?!1:(Zh=s,!0):(Zh=null,!1)}var Zy=typeof setTimeout=="function"?setTimeout:void 0,dC=typeof clearTimeout=="function"?clearTimeout:void 0,Xy=typeof Promise=="function"?Promise:void 0,fC=typeof queueMicrotask=="function"?queueMicrotask:typeof Xy<"u"?function(s){return Xy.resolve(null).then(s).catch(hC)}:Zy;function hC(s){setTimeout(function(){throw s})}function ea(s){return s==="head"}function Qy(s,a){var c=a,p=0;do{var C=c.nextSibling;if(s.removeChild(c),C&&C.nodeType===8)if(c=C.data,c==="/$"||c==="/&"){if(p===0){s.removeChild(C),Fo(a);return}p--}else if(c==="$"||c==="$?"||c==="$~"||c==="$!"||c==="&")p++;else if(c==="html")ac(s.ownerDocument.documentElement);else if(c==="head"){c=s.ownerDocument.head,ac(c);for(var A=c.firstChild;A;){var z=A.nextSibling,ee=A.nodeName;A[Oe]||ee==="SCRIPT"||ee==="STYLE"||ee==="LINK"&&A.rel.toLowerCase()==="stylesheet"||c.removeChild(A),A=z}}else c==="body"&&ac(s.ownerDocument.body);c=C}while(c);Fo(a)}function Jy(s,a){var c=s;s=0;do{var p=c.nextSibling;if(c.nodeType===1?a?(c._stashedDisplay=c.style.display,c.style.display="none"):(c.style.display=c._stashedDisplay||"",c.getAttribute("style")===""&&c.removeAttribute("style")):c.nodeType===3&&(a?(c._stashedText=c.nodeValue,c.nodeValue=""):c.nodeValue=c._stashedText||""),p&&p.nodeType===8)if(c=p.data,c==="/$"){if(s===0)break;s--}else c!=="$"&&c!=="$?"&&c!=="$~"&&c!=="$!"||s++;c=p}while(c)}function Xh(s){var a=s.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var c=a;switch(a=a.nextSibling,c.nodeName){case"HTML":case"HEAD":case"BODY":Xh(c),ce(c);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(c.rel.toLowerCase()==="stylesheet")continue}s.removeChild(c)}}function pC(s,a,c,p){for(;s.nodeType===1;){var C=c;if(s.nodeName.toLowerCase()!==a.toLowerCase()){if(!p&&(s.nodeName!=="INPUT"||s.type!=="hidden"))break}else if(p){if(!s[Oe])switch(a){case"meta":if(!s.hasAttribute("itemprop"))break;return s;case"link":if(A=s.getAttribute("rel"),A==="stylesheet"&&s.hasAttribute("data-precedence"))break;if(A!==C.rel||s.getAttribute("href")!==(C.href==null||C.href===""?null:C.href)||s.getAttribute("crossorigin")!==(C.crossOrigin==null?null:C.crossOrigin)||s.getAttribute("title")!==(C.title==null?null:C.title))break;return s;case"style":if(s.hasAttribute("data-precedence"))break;return s;case"script":if(A=s.getAttribute("src"),(A!==(C.src==null?null:C.src)||s.getAttribute("type")!==(C.type==null?null:C.type)||s.getAttribute("crossorigin")!==(C.crossOrigin==null?null:C.crossOrigin))&&A&&s.hasAttribute("async")&&!s.hasAttribute("itemprop"))break;return s;default:return s}}else if(a==="input"&&s.type==="hidden"){var A=C.name==null?null:""+C.name;if(C.type==="hidden"&&s.getAttribute("name")===A)return s}else return s;if(s=yi(s.nextSibling),s===null)break}return null}function mC(s,a,c){if(a==="")return null;for(;s.nodeType!==3;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!c||(s=yi(s.nextSibling),s===null))return null;return s}function eb(s,a){for(;s.nodeType!==8;)if((s.nodeType!==1||s.nodeName!=="INPUT"||s.type!=="hidden")&&!a||(s=yi(s.nextSibling),s===null))return null;return s}function Qh(s){return s.data==="$?"||s.data==="$~"}function Jh(s){return s.data==="$!"||s.data==="$?"&&s.ownerDocument.readyState!=="loading"}function gC(s,a){var c=s.ownerDocument;if(s.data==="$~")s._reactRetry=a;else if(s.data!=="$?"||c.readyState!=="loading")a();else{var p=function(){a(),c.removeEventListener("DOMContentLoaded",p)};c.addEventListener("DOMContentLoaded",p),s._reactRetry=p}}function yi(s){for(;s!=null;s=s.nextSibling){var a=s.nodeType;if(a===1||a===3)break;if(a===8){if(a=s.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return s}var ep=null;function tb(s){s=s.nextSibling;for(var a=0;s;){if(s.nodeType===8){var c=s.data;if(c==="/$"||c==="/&"){if(a===0)return yi(s.nextSibling);a--}else c!=="$"&&c!=="$!"&&c!=="$?"&&c!=="$~"&&c!=="&"||a++}s=s.nextSibling}return null}function nb(s){s=s.previousSibling;for(var a=0;s;){if(s.nodeType===8){var c=s.data;if(c==="$"||c==="$!"||c==="$?"||c==="$~"||c==="&"){if(a===0)return s;a--}else c!=="/$"&&c!=="/&"||a++}s=s.previousSibling}return null}function sb(s,a,c){switch(a=cd(c),s){case"html":if(s=a.documentElement,!s)throw Error(i(452));return s;case"head":if(s=a.head,!s)throw Error(i(453));return s;case"body":if(s=a.body,!s)throw Error(i(454));return s;default:throw Error(i(451))}}function ac(s){for(var a=s.attributes;a.length;)s.removeAttributeNode(a[0]);ce(s)}var bi=new Map,ib=new Set;function ud(s){return typeof s.getRootNode=="function"?s.getRootNode():s.nodeType===9?s:s.ownerDocument}var mr=de.d;de.d={f:vC,r:yC,D:bC,C:_C,L:SC,m:xC,X:kC,S:wC,M:CC};function vC(){var s=mr.f(),a=td();return s||a}function yC(s){var a=Ue(s);a!==null&&a.tag===5&&a.type==="form"?Sv(a):mr.r(s)}var Uo=typeof document>"u"?null:document;function rb(s,a,c){var p=Uo;if(p&&typeof a=="string"&&a){var C=bt(a);C='link[rel="'+s+'"][href="'+C+'"]',typeof c=="string"&&(C+='[crossorigin="'+c+'"]'),ib.has(C)||(ib.add(C),s={rel:s,crossOrigin:c,href:a},p.querySelector(C)===null&&(a=p.createElement("link"),ys(a,"link",s),et(a),p.head.appendChild(a)))}}function bC(s){mr.D(s),rb("dns-prefetch",s,null)}function _C(s,a){mr.C(s,a),rb("preconnect",s,a)}function SC(s,a,c){mr.L(s,a,c);var p=Uo;if(p&&s&&a){var C='link[rel="preload"][as="'+bt(a)+'"]';a==="image"&&c&&c.imageSrcSet?(C+='[imagesrcset="'+bt(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(C+='[imagesizes="'+bt(c.imageSizes)+'"]')):C+='[href="'+bt(s)+'"]';var A=C;switch(a){case"style":A=qo(s);break;case"script":A=Ho(s)}bi.has(A)||(s=g({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:s,as:a},c),bi.set(A,s),p.querySelector(C)!==null||a==="style"&&p.querySelector(oc(A))||a==="script"&&p.querySelector(lc(A))||(a=p.createElement("link"),ys(a,"link",s),et(a),p.head.appendChild(a)))}}function xC(s,a){mr.m(s,a);var c=Uo;if(c&&s){var p=a&&typeof a.as=="string"?a.as:"script",C='link[rel="modulepreload"][as="'+bt(p)+'"][href="'+bt(s)+'"]',A=C;switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":A=Ho(s)}if(!bi.has(A)&&(s=g({rel:"modulepreload",href:s},a),bi.set(A,s),c.querySelector(C)===null)){switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(lc(A)))return}p=c.createElement("link"),ys(p,"link",s),et(p),c.head.appendChild(p)}}}function wC(s,a,c){mr.S(s,a,c);var p=Uo;if(p&&s){var C=ct(p).hoistableStyles,A=qo(s);a=a||"default";var z=C.get(A);if(!z){var ee={loading:0,preload:null};if(z=p.querySelector(oc(A)))ee.loading=5;else{s=g({rel:"stylesheet",href:s,"data-precedence":a},c),(c=bi.get(A))&&tp(s,c);var he=z=p.createElement("link");et(he),ys(he,"link",s),he._p=new Promise(function(we,Pe){he.onload=we,he.onerror=Pe}),he.addEventListener("load",function(){ee.loading|=1}),he.addEventListener("error",function(){ee.loading|=2}),ee.loading|=4,dd(z,a,p)}z={type:"stylesheet",instance:z,count:1,state:ee},C.set(A,z)}}}function kC(s,a){mr.X(s,a);var c=Uo;if(c&&s){var p=ct(c).hoistableScripts,C=Ho(s),A=p.get(C);A||(A=c.querySelector(lc(C)),A||(s=g({src:s,async:!0},a),(a=bi.get(C))&&np(s,a),A=c.createElement("script"),et(A),ys(A,"link",s),c.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},p.set(C,A))}}function CC(s,a){mr.M(s,a);var c=Uo;if(c&&s){var p=ct(c).hoistableScripts,C=Ho(s),A=p.get(C);A||(A=c.querySelector(lc(C)),A||(s=g({src:s,async:!0,type:"module"},a),(a=bi.get(C))&&np(s,a),A=c.createElement("script"),et(A),ys(A,"link",s),c.head.appendChild(A)),A={type:"script",instance:A,count:1,state:null},p.set(C,A))}}function ab(s,a,c,p){var C=(C=Ee.current)?ud(C):null;if(!C)throw Error(i(446));switch(s){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=qo(c.href),c=ct(C).hoistableStyles,p=c.get(a),p||(p={type:"style",instance:null,count:0,state:null},c.set(a,p)),p):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){s=qo(c.href);var A=ct(C).hoistableStyles,z=A.get(s);if(z||(C=C.ownerDocument||C,z={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},A.set(s,z),(A=C.querySelector(oc(s)))&&!A._p&&(z.instance=A,z.state.loading=5),bi.has(s)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},bi.set(s,c),A||EC(C,s,c,z.state))),a&&p===null)throw Error(i(528,""));return z}if(a&&p!==null)throw Error(i(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=Ho(c),c=ct(C).hoistableScripts,p=c.get(a),p||(p={type:"script",instance:null,count:0,state:null},c.set(a,p)),p):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,s))}}function qo(s){return'href="'+bt(s)+'"'}function oc(s){return'link[rel="stylesheet"]['+s+"]"}function ob(s){return g({},s,{"data-precedence":s.precedence,precedence:null})}function EC(s,a,c,p){s.querySelector('link[rel="preload"][as="style"]['+a+"]")?p.loading=1:(a=s.createElement("link"),p.preload=a,a.addEventListener("load",function(){return p.loading|=1}),a.addEventListener("error",function(){return p.loading|=2}),ys(a,"link",c),et(a),s.head.appendChild(a))}function Ho(s){return'[src="'+bt(s)+'"]'}function lc(s){return"script[async]"+s}function lb(s,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var p=s.querySelector('style[data-href~="'+bt(c.href)+'"]');if(p)return a.instance=p,et(p),p;var C=g({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return p=(s.ownerDocument||s).createElement("style"),et(p),ys(p,"style",C),dd(p,c.precedence,s),a.instance=p;case"stylesheet":C=qo(c.href);var A=s.querySelector(oc(C));if(A)return a.state.loading|=4,a.instance=A,et(A),A;p=ob(c),(C=bi.get(C))&&tp(p,C),A=(s.ownerDocument||s).createElement("link"),et(A);var z=A;return z._p=new Promise(function(ee,he){z.onload=ee,z.onerror=he}),ys(A,"link",p),a.state.loading|=4,dd(A,c.precedence,s),a.instance=A;case"script":return A=Ho(c.src),(C=s.querySelector(lc(A)))?(a.instance=C,et(C),C):(p=c,(C=bi.get(A))&&(p=g({},c),np(p,C)),s=s.ownerDocument||s,C=s.createElement("script"),et(C),ys(C,"link",p),s.head.appendChild(C),a.instance=C);case"void":return null;default:throw Error(i(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(p=a.instance,a.state.loading|=4,dd(p,c.precedence,s));return a.instance}function dd(s,a,c){for(var p=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),C=p.length?p[p.length-1]:null,A=C,z=0;z<p.length;z++){var ee=p[z];if(ee.dataset.precedence===a)A=ee;else if(A!==C)break}A?A.parentNode.insertBefore(s,A.nextSibling):(a=c.nodeType===9?c.head:c,a.insertBefore(s,a.firstChild))}function tp(s,a){s.crossOrigin==null&&(s.crossOrigin=a.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=a.referrerPolicy),s.title==null&&(s.title=a.title)}function np(s,a){s.crossOrigin==null&&(s.crossOrigin=a.crossOrigin),s.referrerPolicy==null&&(s.referrerPolicy=a.referrerPolicy),s.integrity==null&&(s.integrity=a.integrity)}var fd=null;function cb(s,a,c){if(fd===null){var p=new Map,C=fd=new Map;C.set(c,p)}else C=fd,p=C.get(c),p||(p=new Map,C.set(c,p));if(p.has(s))return p;for(p.set(s,null),c=c.getElementsByTagName(s),C=0;C<c.length;C++){var A=c[C];if(!(A[Oe]||A[re]||s==="link"&&A.getAttribute("rel")==="stylesheet")&&A.namespaceURI!=="http://www.w3.org/2000/svg"){var z=A.getAttribute(a)||"";z=s+z;var ee=p.get(z);ee?ee.push(A):p.set(z,[A])}}return p}function ub(s,a,c){s=s.ownerDocument||s,s.head.insertBefore(c,a==="title"?s.querySelector("head > title"):null)}function NC(s,a,c){if(c===1||a.itemProp!=null)return!1;switch(s){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(s=a.disabled,typeof a.precedence=="string"&&s==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function db(s){return!(s.type==="stylesheet"&&(s.state.loading&3)===0)}function jC(s,a,c,p){if(c.type==="stylesheet"&&(typeof p.media!="string"||matchMedia(p.media).matches!==!1)&&(c.state.loading&4)===0){if(c.instance===null){var C=qo(p.href),A=a.querySelector(oc(C));if(A){a=A._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(s.count++,s=hd.bind(s),a.then(s,s)),c.state.loading|=4,c.instance=A,et(A);return}A=a.ownerDocument||a,p=ob(p),(C=bi.get(C))&&tp(p,C),A=A.createElement("link"),et(A);var z=A;z._p=new Promise(function(ee,he){z.onload=ee,z.onerror=he}),ys(A,"link",p),c.instance=A}s.stylesheets===null&&(s.stylesheets=new Map),s.stylesheets.set(c,a),(a=c.state.preload)&&(c.state.loading&3)===0&&(s.count++,c=hd.bind(s),a.addEventListener("load",c),a.addEventListener("error",c))}}var sp=0;function AC(s,a){return s.stylesheets&&s.count===0&&md(s,s.stylesheets),0<s.count||0<s.imgCount?function(c){var p=setTimeout(function(){if(s.stylesheets&&md(s,s.stylesheets),s.unsuspend){var A=s.unsuspend;s.unsuspend=null,A()}},6e4+a);0<s.imgBytes&&sp===0&&(sp=62500*cC());var C=setTimeout(function(){if(s.waitingForImages=!1,s.count===0&&(s.stylesheets&&md(s,s.stylesheets),s.unsuspend)){var A=s.unsuspend;s.unsuspend=null,A()}},(s.imgBytes>sp?50:800)+a);return s.unsuspend=c,function(){s.unsuspend=null,clearTimeout(p),clearTimeout(C)}}:null}function hd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)md(this,this.stylesheets);else if(this.unsuspend){var s=this.unsuspend;this.unsuspend=null,s()}}}var pd=null;function md(s,a){s.stylesheets=null,s.unsuspend!==null&&(s.count++,pd=new Map,a.forEach(RC,s),pd=null,hd.call(s))}function RC(s,a){if(!(a.state.loading&4)){var c=pd.get(s);if(c)var p=c.get(null);else{c=new Map,pd.set(s,c);for(var C=s.querySelectorAll("link[data-precedence],style[data-precedence]"),A=0;A<C.length;A++){var z=C[A];(z.nodeName==="LINK"||z.getAttribute("media")!=="not all")&&(c.set(z.dataset.precedence,z),p=z)}p&&c.set(null,p)}C=a.instance,z=C.getAttribute("data-precedence"),A=c.get(z)||p,A===p&&c.set(null,C),c.set(z,C),this.count++,p=hd.bind(this),C.addEventListener("load",p),C.addEventListener("error",p),A?A.parentNode.insertBefore(C,A.nextSibling):(s=s.nodeType===9?s.head:s,s.insertBefore(C,s.firstChild)),a.state.loading|=4}}var cc={$$typeof:_,Provider:null,Consumer:null,_currentValue:fe,_currentValue2:fe,_threadCount:0};function TC(s,a,c,p,C,A,z,ee,he){this.tag=1,this.containerInfo=s,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ss(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ss(0),this.hiddenUpdates=ss(null),this.identifierPrefix=p,this.onUncaughtError=C,this.onCaughtError=A,this.onRecoverableError=z,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=he,this.incompleteTransitions=new Map}function fb(s,a,c,p,C,A,z,ee,he,we,Pe,Fe){return s=new TC(s,a,c,z,he,we,Pe,Fe,ee),a=1,A===!0&&(a|=24),A=Es(3,null,null,a),s.current=A,A.stateNode=s,a=Of(),a.refCount++,s.pooledCache=a,a.refCount++,A.memoizedState={element:p,isDehydrated:c,cache:a},zf(A),s}function hb(s){return s?(s=Br,s):Br}function pb(s,a,c,p,C,A){C=hb(C),p.context===null?p.context=C:p.pendingContext=C,p=Hr(a),p.payload={element:c},A=A===void 0?null:A,A!==null&&(p.callback=A),c=Fr(s,p,a),c!==null&&(Ks(c,s,a),Ul(c,s,a))}function mb(s,a){if(s=s.memoizedState,s!==null&&s.dehydrated!==null){var c=s.retryLane;s.retryLane=c!==0&&c<a?c:a}}function ip(s,a){mb(s,a),(s=s.alternate)&&mb(s,a)}function gb(s){if(s.tag===13||s.tag===31){var a=tr(s,67108864);a!==null&&Ks(a,s,67108864),ip(s,67108864)}}function vb(s){if(s.tag===13||s.tag===31){var a=ai();a=W(a);var c=tr(s,a);c!==null&&Ks(c,s,a),ip(s,a)}}var gd=!0;function IC(s,a,c,p){var C=X.T;X.T=null;var A=de.p;try{de.p=2,rp(s,a,c,p)}finally{de.p=A,X.T=C}}function MC(s,a,c,p){var C=X.T;X.T=null;var A=de.p;try{de.p=8,rp(s,a,c,p)}finally{de.p=A,X.T=C}}function rp(s,a,c,p){if(gd){var C=ap(p);if(C===null)Kh(s,a,p,vd,c),bb(s,p);else if(LC(C,s,a,c,p))p.stopPropagation();else if(bb(s,p),a&4&&-1<DC.indexOf(s)){for(;C!==null;){var A=Ue(C);if(A!==null)switch(A.tag){case 3:if(A=A.stateNode,A.current.memoizedState.isDehydrated){var z=Mt(A.pendingLanes);if(z!==0){var ee=A;for(ee.pendingLanes|=2,ee.entangledLanes|=2;z;){var he=1<<31-Zt(z);ee.entanglements[1]|=he,z&=~he}qi(A),(Nn&6)===0&&(Ju=Ut()+500,sc(0))}}break;case 31:case 13:ee=tr(A,2),ee!==null&&Ks(ee,A,2),td(),ip(A,2)}if(A=ap(p),A===null&&Kh(s,a,p,vd,c),A===C)break;C=A}C!==null&&p.stopPropagation()}else Kh(s,a,p,null,c)}}function ap(s){return s=hl(s),op(s)}var vd=null;function op(s){if(vd=null,s=ke(s),s!==null){var a=d(s);if(a===null)s=null;else{var c=a.tag;if(c===13){if(s=h(a),s!==null)return s;s=null}else if(c===31){if(s=l(a),s!==null)return s;s=null}else if(c===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;s=null}else a!==s&&(s=null)}}return vd=s,null}function yb(s){switch(s){case"beforetoggle":case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"toggle":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 2;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 8;case"message":switch($t()){case Lt:return 2;case Ht:return 8;case zt:case rn:return 32;case ze:return 268435456;default:return 32}default:return 32}}var lp=!1,ta=null,na=null,sa=null,uc=new Map,dc=new Map,ia=[],DC="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(" ");function bb(s,a){switch(s){case"focusin":case"focusout":ta=null;break;case"dragenter":case"dragleave":na=null;break;case"mouseover":case"mouseout":sa=null;break;case"pointerover":case"pointerout":uc.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":dc.delete(a.pointerId)}}function fc(s,a,c,p,C,A){return s===null||s.nativeEvent!==A?(s={blockedOn:a,domEventName:c,eventSystemFlags:p,nativeEvent:A,targetContainers:[C]},a!==null&&(a=Ue(a),a!==null&&gb(a)),s):(s.eventSystemFlags|=p,a=s.targetContainers,C!==null&&a.indexOf(C)===-1&&a.push(C),s)}function LC(s,a,c,p,C){switch(a){case"focusin":return ta=fc(ta,s,a,c,p,C),!0;case"dragenter":return na=fc(na,s,a,c,p,C),!0;case"mouseover":return sa=fc(sa,s,a,c,p,C),!0;case"pointerover":var A=C.pointerId;return uc.set(A,fc(uc.get(A)||null,s,a,c,p,C)),!0;case"gotpointercapture":return A=C.pointerId,dc.set(A,fc(dc.get(A)||null,s,a,c,p,C)),!0}return!1}function _b(s){var a=ke(s.target);if(a!==null){var c=d(a);if(c!==null){if(a=c.tag,a===13){if(a=h(c),a!==null){s.blockedOn=a,ne(s.priority,function(){vb(c)});return}}else if(a===31){if(a=l(c),a!==null){s.blockedOn=a,ne(s.priority,function(){vb(c)});return}}else if(a===3&&c.stateNode.current.memoizedState.isDehydrated){s.blockedOn=c.tag===3?c.stateNode.containerInfo:null;return}}}s.blockedOn=null}function yd(s){if(s.blockedOn!==null)return!1;for(var a=s.targetContainers;0<a.length;){var c=ap(s.nativeEvent);if(c===null){c=s.nativeEvent;var p=new c.constructor(c.type,c);io=p,c.target.dispatchEvent(p),io=null}else return a=Ue(c),a!==null&&gb(a),s.blockedOn=c,!1;a.shift()}return!0}function Sb(s,a,c){yd(s)&&c.delete(a)}function OC(){lp=!1,ta!==null&&yd(ta)&&(ta=null),na!==null&&yd(na)&&(na=null),sa!==null&&yd(sa)&&(sa=null),uc.forEach(Sb),dc.forEach(Sb)}function bd(s,a){s.blockedOn===a&&(s.blockedOn=null,lp||(lp=!0,e.unstable_scheduleCallback(e.unstable_NormalPriority,OC)))}var _d=null;function xb(s){_d!==s&&(_d=s,e.unstable_scheduleCallback(e.unstable_NormalPriority,function(){_d===s&&(_d=null);for(var a=0;a<s.length;a+=3){var c=s[a],p=s[a+1],C=s[a+2];if(typeof p!="function"){if(op(p||c)===null)continue;break}var A=Ue(c);A!==null&&(s.splice(a,3),a-=3,ah(A,{pending:!0,data:C,method:c.method,action:p},p,C))}}))}function Fo(s){function a(he){return bd(he,s)}ta!==null&&bd(ta,s),na!==null&&bd(na,s),sa!==null&&bd(sa,s),uc.forEach(a),dc.forEach(a);for(var c=0;c<ia.length;c++){var p=ia[c];p.blockedOn===s&&(p.blockedOn=null)}for(;0<ia.length&&(c=ia[0],c.blockedOn===null);)_b(c),c.blockedOn===null&&ia.shift();if(c=(s.ownerDocument||s).$$reactFormReplay,c!=null)for(p=0;p<c.length;p+=3){var C=c[p],A=c[p+1],z=C[ve]||null;if(typeof A=="function")z||xb(c);else if(z){var ee=null;if(A&&A.hasAttribute("formAction")){if(C=A,z=A[ve]||null)ee=z.formAction;else if(op(C)!==null)continue}else ee=z.action;typeof ee=="function"?c[p+1]=ee:(c.splice(p,3),p-=3),xb(c)}}}function wb(){function s(A){A.canIntercept&&A.info==="react-transition"&&A.intercept({handler:function(){return new Promise(function(z){return C=z})},focusReset:"manual",scroll:"manual"})}function a(){C!==null&&(C(),C=null),p||setTimeout(c,20)}function c(){if(!p&&!navigation.transition){var A=navigation.currentEntry;A&&A.url!=null&&navigation.navigate(A.url,{state:A.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var p=!1,C=null;return navigation.addEventListener("navigate",s),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(c,100),function(){p=!0,navigation.removeEventListener("navigate",s),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),C!==null&&(C(),C=null)}}}function cp(s){this._internalRoot=s}Sd.prototype.render=cp.prototype.render=function(s){var a=this._internalRoot;if(a===null)throw Error(i(409));var c=a.current,p=ai();pb(c,p,s,a,null,null)},Sd.prototype.unmount=cp.prototype.unmount=function(){var s=this._internalRoot;if(s!==null){this._internalRoot=null;var a=s.containerInfo;pb(s.current,2,null,s,null,null),td(),a[Me]=null}};function Sd(s){this._internalRoot=s}Sd.prototype.unstable_scheduleHydration=function(s){if(s){var a=M();s={blockedOn:null,target:s,priority:a};for(var c=0;c<ia.length&&a!==0&&a<ia[c].priority;c++);ia.splice(c,0,s),c===0&&_b(s)}};var kb=t.version;if(kb!=="19.2.5")throw Error(i(527,kb,"19.2.5"));de.findDOMNode=function(s){var a=s._reactInternals;if(a===void 0)throw typeof s.render=="function"?Error(i(188)):(s=Object.keys(s).join(","),Error(i(268,s)));return s=f(a),s=s!==null?v(s):null,s=s===null?null:s.stateNode,s};var PC={bundleType:0,version:"19.2.5",rendererPackageName:"react-dom",currentDispatcherRef:X,reconcilerVersion:"19.2.5"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var xd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!xd.isDisabled&&xd.supportsFiber)try{Pt=xd.inject(PC),Vt=xd}catch{}}return pc.createRoot=function(s,a){if(!o(s))throw Error(i(299));var c=!1,p="",C=Tv,A=Iv,z=Mv;return a!=null&&(a.unstable_strictMode===!0&&(c=!0),a.identifierPrefix!==void 0&&(p=a.identifierPrefix),a.onUncaughtError!==void 0&&(C=a.onUncaughtError),a.onCaughtError!==void 0&&(A=a.onCaughtError),a.onRecoverableError!==void 0&&(z=a.onRecoverableError)),a=fb(s,1,!1,null,null,c,p,null,C,A,z,wb),s[Me]=a.current,Fh(s),new cp(a)},pc.hydrateRoot=function(s,a,c){if(!o(s))throw Error(i(299));var p=!1,C="",A=Tv,z=Iv,ee=Mv,he=null;return c!=null&&(c.unstable_strictMode===!0&&(p=!0),c.identifierPrefix!==void 0&&(C=c.identifierPrefix),c.onUncaughtError!==void 0&&(A=c.onUncaughtError),c.onCaughtError!==void 0&&(z=c.onCaughtError),c.onRecoverableError!==void 0&&(ee=c.onRecoverableError),c.formState!==void 0&&(he=c.formState)),a=fb(s,1,!0,a,c??null,p,C,he,A,z,ee,wb),a.context=hb(null),c=a.current,p=ai(),p=W(p),C=Hr(p),C.callback=null,Fr(c,C,p),c=p,a.current.lanes=c,Ie(a,c),qi(a),s[Me]=a.current,Fh(s),new Sd(a)},pc.version="19.2.5",pc}var Db;function GC(){if(Db)return fp.exports;Db=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),fp.exports=WC(),fp.exports}var VC=GC();const Lb=e=>Symbol.iterator in e,Ob=e=>"entries"in e,Pb=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),i=t instanceof Map?t:new Map(t.entries());if(n.size!==i.size)return!1;for(const[o,d]of n)if(!i.has(o)||!Object.is(d,i.get(o)))return!1;return!0},YC=(e,t)=>{const n=e[Symbol.iterator](),i=t[Symbol.iterator]();let o=n.next(),d=i.next();for(;!o.done&&!d.done;){if(!Object.is(o.value,d.value))return!1;o=n.next(),d=i.next()}return!!o.done&&!!d.done};function ZC(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Lb(e)&&Lb(t)?Ob(e)&&Ob(t)?Pb(e,t):YC(e,t):Pb({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Mc(e){const t=Ac.useRef(void 0);return n=>{const i=e(n);return ZC(t.current,i)?t.current:t.current=i}}const XC={continuous:!0,"auto-pause":!0};function O0(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(XC,e)}const QC=2e5,JC=new Set(["docker","docker-cli","docker-sdk","docker-byok"]);function eE(e){return e==null||e==="claude"||e.startsWith("claude-")?!0:JC.has(e)}function tE(e,t){const n=e?.contextWindow;return typeof n=="number"&&Number.isFinite(n)&&n>0?n:eE(t)?QC:null}function nE(e){if(typeof e!="object"||e===null||Array.isArray(e)||Object.keys(e).length!==2||!Object.prototype.hasOwnProperty.call(e,"otherLabel")||!Object.prototype.hasOwnProperty.call(e,"freeformText"))return!1;const n=e;return typeof n.otherLabel=="string"&&typeof n.freeformText=="string"}const sE=[["planMode","plan mode"],["streaming","streaming"],["modelSwitch","model switching"]];function iE(e){if(!e)return null;const t=sE.filter(([i])=>e[i]===!1).map(([,i])=>i);return t.length===0?null:`This provider doesn't support ${t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}.`}const la=new Map,aa=new Map,rE=64;function P0(e={}){la.clear(),e.clearCursors&&aa.clear()}function Hm(e,t){if(!e||typeof t!="number"||!Number.isFinite(t)||t<0)return;const n=aa.get(e);if(!(n!==void 0&&t<=n))for(aa.delete(e),aa.set(e,t);aa.size>rE;){const i=aa.keys().next().value;if(i===void 0)break;aa.delete(i)}}function aE(){const e={};for(const[t,n]of aa)e[t]=n;return e}function oE(e,t,n,i){return e?t?(la.set(e,Math.max(0,n|0)),{rebuildInProgress:!0}):(la.delete(e),{rebuildInProgress:!1}):{rebuildInProgress:!1}}function B0(e,t){if(e&&la.has(e)){const n=la.get(e);return t.slice(n)}return t}function Bb(e,t,n){if(e&&typeof n=="number"&&Number.isFinite(n)&&Hm(e,n),!e||!la.has(e))return{swappedMessages:null};const i=la.get(e);return la.delete(e),{swappedMessages:t.slice(i)}}const lE={alert(e,t){console.warn(`[chroxy] ${e}: ${t}`)}},gp="chroxy_last_url",vp="chroxy_last_token";function cE(e){return{saveConnection(t,n){try{e.setItem(gp,t),e.setItem(vp,n)}catch{}},loadConnection(){try{const t=e.getItem(gp),n=e.getItem(vp);return t&&n?{url:t,token:n}:null}catch{return null}},clearSavedCredentials(){try{e.removeItem(gp),e.removeItem(vp)}catch{}}}}function uE(e,t,n){const i=typeof e.clientId=="string"?e.clientId:void 0;if(i&&i===t)return null;const o=(typeof e.sessionId=="string"?e.sessionId:null)||n;return o?{sessionId:o,type:"user_input",content:typeof e.text=="string"?e.text:"",timestamp:typeof e.timestamp=="number"?e.timestamp:Date.now()}:null}function dE(e,t){const{messageType:n,messageId:i}=t;if(i&&n==="response")return e.some(l=>l.id===i&&l.type==="response"||l.id===`${i}-response`);if(i&&n==="user_input")return e.some(l=>l.id===i);const o=t.timestamp??null,d=t.tool??null,h=JSON.stringify(t.options??null);return e.some(l=>l.type!==n||l.content!==t.content||(l.timestamp??null)!==o||(l.tool??null)!==d?!1:JSON.stringify(l.options??null)===h)}const $b={keyword:"#c4a5ff",string:"#4eca6a",comment:"#7a7a7a",number:"#ff9a52",function:"#4a9eff",operator:"#e0e0e0",punctuation:"#888888",type:"#4a9eff",property:"#4eca6a",plain:"#a0d0ff",diff_add:"#4eca6a",diff_remove:"#ff5b5b"};function Se(e){const t=e.flags.includes("y")?e.flags:e.flags+"y";return new RegExp(e.source,t)}const zb=[{pattern:Se(/\/\/[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'`])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\b(?:abstract|as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/),type:"keyword"},{pattern:Se(/\b(?:true|false|null|undefined|NaN|Infinity)\b/),type:"keyword"},{pattern:Se(/\b(?:Array|Boolean|Date|Error|Function|JSON|Map|Math|Number|Object|Promise|Proxy|RegExp|Set|String|Symbol|WeakMap|WeakSet|console|window|document|global|globalThis|process)\b/),type:"type"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F_]*\b/),type:"number"},{pattern:Se(/\b0[oO][0-7][0-7_]*\b/),type:"number"},{pattern:Se(/\b0[bB][01][01_]*\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?\b/),type:"number"},{pattern:Se(/[a-zA-Z_$][\w$]*(?=\s*\()/),type:"function"},{pattern:Se(/=>|[+\-*/%=!<>&|^~?:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.]/),type:"punctuation"}],Ub=[{pattern:Se(/\/\/[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'`])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\b(?:abstract|as|async|await|break|case|catch|class|const|continue|debugger|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|infer|instanceof|interface|is|keyof|let|module|namespace|never|new|of|override|package|private|protected|public|readonly|return|satisfies|set|static|super|switch|this|throw|try|type|typeof|var|void|while|with|yield)\b/),type:"keyword"},{pattern:Se(/\b(?:true|false|null|undefined|NaN|Infinity)\b/),type:"keyword"},{pattern:Se(/\b(?:any|bigint|boolean|number|object|string|symbol|unknown|void|never)\b/),type:"type"},{pattern:Se(/\b(?:Array|Boolean|Date|Error|Function|JSON|Map|Math|Number|Object|Promise|Proxy|Record|Partial|Required|Readonly|Pick|Omit|Exclude|Extract|NonNullable|ReturnType|Parameters|RegExp|Set|String|Symbol|WeakMap|WeakSet|console)\b/),type:"type"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F_]*\b/),type:"number"},{pattern:Se(/\b0[oO][0-7][0-7_]*\b/),type:"number"},{pattern:Se(/\b0[bB][01][01_]*\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?\b/),type:"number"},{pattern:Se(/[a-zA-Z_$][\w$]*(?=\s*[<(])/),type:"function"},{pattern:Se(/=>|[+\-*/%=!<>&|^~?:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.]/),type:"punctuation"}],fE=[{pattern:Se(/#[^\n]*/),type:"comment"},{pattern:Se(/"""[\s\S]*?"""/),type:"string"},{pattern:Se(/'''[\s\S]*?'''/),type:"string"},{pattern:Se(/[fFrRbBuU]?(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|raise|return|try|while|with|yield)\b/),type:"keyword"},{pattern:Se(/\b(?:True|False|None)\b/),type:"keyword"},{pattern:Se(/\b(?:int|float|str|bool|list|dict|tuple|set|frozenset|bytes|bytearray|type|object|range|complex|memoryview|Exception|TypeError|ValueError|KeyError|IndexError|AttributeError|RuntimeError|StopIteration)\b/),type:"type"},{pattern:Se(/\b(?:print|len|range|enumerate|zip|map|filter|sorted|reversed|isinstance|issubclass|hasattr|getattr|setattr|super|property|staticmethod|classmethod|open|input)\b(?=\s*\()/),type:"function"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F_]*\b/),type:"number"},{pattern:Se(/\b0[oO][0-7][0-7_]*\b/),type:"number"},{pattern:Se(/\b0[bB][01][01_]*\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?\b/),type:"number"},{pattern:Se(/[a-zA-Z_]\w*(?=\s*\()/),type:"function"},{pattern:Se(/[-+*/%=!<>&|^~@:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.]/),type:"punctuation"}],hE=[{pattern:Se(/#[^\n]*/),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\$\{[^}]*\}/),type:"string"},{pattern:Se(/\$[a-zA-Z_]\w*/),type:"string"},{pattern:Se(/\b(?:if|then|else|elif|fi|for|while|do|done|case|esac|in|function|return|local|export|source|alias|unalias|declare|typeset|readonly|shift|break|continue|exit|eval|exec|trap|set|unset)\b/),type:"keyword"},{pattern:Se(/\b(?:echo|printf|cd|ls|cat|grep|sed|awk|find|xargs|sort|uniq|wc|head|tail|cut|tr|tee|mkdir|rmdir|rm|cp|mv|ln|chmod|chown|chgrp|touch|test|read|write|kill|ps|bg|fg|jobs|wait|nohup|true|false)\b/),type:"function"},{pattern:Se(/\b\d+\b/),type:"number"},{pattern:Se(/[|&;><!=]+/),type:"operator"},{pattern:Se(/[{}()\[\]]/),type:"punctuation"}],pE=[{pattern:Se(/"(?:[^"\\]|\\.)*"\s*(?=:)/),type:"property"},{pattern:Se(/"(?:[^"\\]|\\.)*"/),type:"string"},{pattern:Se(/\b(?:true|false|null)\b/),type:"keyword"},{pattern:Se(/-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b/),type:"number"},{pattern:Se(/:/),type:"operator"},{pattern:Se(/[{}()\[\],]/),type:"punctuation"}],mE=[{pattern:Se(/^\+\+\+[^\n]*/m),type:"keyword"},{pattern:Se(/^---[^\n]*/m),type:"keyword"},{pattern:Se(/^@@[^\n]*@@[^\n]*/m),type:"keyword"},{pattern:Se(/^\+[^\n]*/m),type:"diff_add"},{pattern:Se(/^-[^\n]*/m),type:"diff_remove"}],qb=[{pattern:Se(/<!--[\s\S]*?-->/),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/<\/?[a-zA-Z][\w-]*/),type:"keyword"},{pattern:Se(/\/?>/),type:"keyword"},{pattern:Se(/[a-zA-Z][\w-]*(?=\s*=)/),type:"property"},{pattern:Se(/[=]/),type:"operator"}],gE=[{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/@[a-zA-Z][\w-]*/),type:"keyword"},{pattern:Se(/\b(?:important|inherit|initial|unset|revert)\b/),type:"keyword"},{pattern:Se(/#[0-9a-fA-F]{3,8}\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:px|em|rem|%|vh|vw|vmin|vmax|ch|ex|cm|mm|in|pt|pc|deg|rad|grad|turn|s|ms|Hz|kHz|fr)?\b/),type:"number"},{pattern:Se(/[a-zA-Z][\w-]*(?=\s*\()/),type:"function"},{pattern:Se(/[a-zA-Z-]+(?=\s*:)/),type:"property"},{pattern:Se(/[.#][a-zA-Z][\w-]*/),type:"type"},{pattern:Se(/[:;{}(),>+~*=]/),type:"punctuation"}],vE=[{pattern:Se(/#[^\n]*/),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/[a-zA-Z_][\w.-]*(?=\s*:)/),type:"property"},{pattern:Se(/\b(?:true|false|null|yes|no|on|off)\b/i),type:"keyword"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?\b/),type:"number"},{pattern:Se(/[:\-|>]/),type:"operator"}],yE=[{pattern:Se(/\/\/[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'`])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\b(?: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)\b/),type:"keyword"},{pattern:Se(/\b(?:true|false|nil|iota)\b/),type:"keyword"},{pattern:Se(/\b(?:bool|byte|complex64|complex128|error|float32|float64|int|int8|int16|int32|int64|rune|string|uint|uint8|uint16|uint32|uint64|uintptr)\b/),type:"type"},{pattern:Se(/\b(?:append|cap|close|copy|delete|len|make|new|panic|print|println|recover)\b(?=\s*\()/),type:"function"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F_]*\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?\b/),type:"number"},{pattern:Se(/[a-zA-Z_]\w*(?=\s*\()/),type:"function"},{pattern:Se(/:=|[+\-*/%=!<>&|^~]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.]/),type:"punctuation"}],bE=[{pattern:Se(/\/\/[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\b(?:as|async|await|break|const|continue|crate|dyn|else|enum|extern|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|type|unsafe|use|where|while|yield)\b/),type:"keyword"},{pattern:Se(/\b(?:true|false)\b/),type:"keyword"},{pattern:Se(/\b(?:i8|i16|i32|i64|i128|isize|u8|u16|u32|u64|u128|usize|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Cell|RefCell|HashMap|HashSet|BTreeMap|BTreeSet)\b/),type:"type"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F_]*\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?\b/),type:"number"},{pattern:Se(/[a-zA-Z_]\w*(?=\s*[!(<])/),type:"function"},{pattern:Se(/=>|->|[+\-*/%=!<>&|^~?:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.#]/),type:"punctuation"}],_E=[{pattern:Se(/\/\/[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\b(?:abstract|assert|break|case|catch|class|const|continue|default|do|else|enum|extends|final|finally|for|goto|if|implements|import|instanceof|interface|native|new|package|private|protected|public|return|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|void|volatile|while)\b/),type:"keyword"},{pattern:Se(/\b(?:true|false|null)\b/),type:"keyword"},{pattern:Se(/\b(?:boolean|byte|char|double|float|int|long|short|var|String|Integer|Long|Double|Float|Boolean|Character|Object|Class|System|List|Map|Set|ArrayList|HashMap|HashSet|Optional|Stream)\b/),type:"type"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F_]*[lL]?\b/),type:"number"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?(?:[eE][+-]?\d[\d_]*)?[lLfFdD]?\b/),type:"number"},{pattern:Se(/[a-zA-Z_]\w*(?=\s*\()/),type:"function"},{pattern:Se(/[+\-*/%=!<>&|^~?:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.@]/),type:"punctuation"}],SE=[{pattern:Se(/#[^\n]*/),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/\bdefined\?/),type:"keyword"},{pattern:Se(/\b(?:alias|and|begin|break|case|class|def|do|else|elsif|end|ensure|for|if|in|module|next|nil|not|or|redo|require|rescue|retry|return|self|super|then|undef|unless|until|when|while|yield)\b/),type:"keyword"},{pattern:Se(/\b(?:true|false|nil)\b/),type:"keyword"},{pattern:Se(/:[a-zA-Z_]\w*/),type:"string"},{pattern:Se(/\b\d[\d_]*(?:\.[\d_]*)?\b/),type:"number"},{pattern:Se(/[a-zA-Z_]\w*(?=\s*[({])/),type:"function"},{pattern:Se(/[+\-*/%=!<>&|^~?:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.@]/),type:"punctuation"}],Hb=[{pattern:Se(/\/\/[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/(["'])(?:(?!\1|\\).|\\.)*\1/),type:"string"},{pattern:Se(/#\s*(?:include|define|ifdef|ifndef|endif|if|else|elif|undef|pragma|error|warning)[^\n]*/),type:"keyword"},{pattern:Se(/\b(?:auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|restrict|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while|_Bool|_Complex|_Imaginary)\b/),type:"keyword"},{pattern:Se(/\b(?:NULL|true|false)\b/),type:"keyword"},{pattern:Se(/\b(?:size_t|ptrdiff_t|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|FILE|bool)\b/),type:"type"},{pattern:Se(/\b0[xX][0-9a-fA-F][0-9a-fA-F]*[uUlL]*\b/),type:"number"},{pattern:Se(/\b\d[\d]*(?:\.[\d]*)?(?:[eE][+-]?\d+)?[uUlLfF]*\b/),type:"number"},{pattern:Se(/[a-zA-Z_]\w*(?=\s*\()/),type:"function"},{pattern:Se(/->|[+\-*/%=!<>&|^~?:]+/),type:"operator"},{pattern:Se(/[{}()\[\];,.]/),type:"punctuation"}],xE=[{pattern:Se(/--[^\n]*/),type:"comment"},{pattern:Se(/\/\*[\s\S]*?\*\//),type:"comment"},{pattern:Se(/'(?:[^'\\]|\\.)*'/),type:"string"},{pattern:Se(/\b(?:SELECT|FROM|WHERE|INSERT|INTO|VALUES|UPDATE|SET|DELETE|CREATE|ALTER|DROP|TABLE|INDEX|VIEW|DATABASE|SCHEMA|JOIN|INNER|LEFT|RIGHT|OUTER|CROSS|ON|AND|OR|NOT|IN|IS|NULL|AS|ORDER|BY|GROUP|HAVING|LIMIT|OFFSET|UNION|ALL|DISTINCT|CASE|WHEN|THEN|ELSE|END|EXISTS|BETWEEN|LIKE|PRIMARY|KEY|FOREIGN|REFERENCES|UNIQUE|CHECK|DEFAULT|CONSTRAINT|BEGIN|COMMIT|ROLLBACK|TRANSACTION|GRANT|REVOKE|WITH|RECURSIVE|RETURNING|CONFLICT|REPLACE|EXPLAIN|ANALYZE|VACUUM|PRAGMA|IF|TRIGGER|FUNCTION|PROCEDURE|DECLARE|CURSOR|FETCH|CLOSE|OPEN|ASC|DESC)\b/i),type:"keyword"},{pattern:Se(/\b(?:INT|INTEGER|BIGINT|SMALLINT|TINYINT|FLOAT|DOUBLE|DECIMAL|NUMERIC|REAL|CHAR|VARCHAR|TEXT|BLOB|BOOLEAN|BOOL|DATE|TIME|TIMESTAMP|DATETIME|SERIAL|UUID|JSON|JSONB|ARRAY|BYTEA)\b/i),type:"type"},{pattern:Se(/\b(?:COUNT|SUM|AVG|MIN|MAX|COALESCE|NULLIF|CAST|CONVERT|TRIM|UPPER|LOWER|LENGTH|SUBSTR|SUBSTRING|REPLACE|CONCAT|NOW|CURRENT_TIMESTAMP|CURRENT_DATE|CURRENT_TIME|ROW_NUMBER|RANK|DENSE_RANK|LAG|LEAD|FIRST_VALUE|LAST_VALUE|OVER|PARTITION)\b(?=\s*\()/i),type:"function"},{pattern:Se(/\b\d+(?:\.\d+)?\b/),type:"number"},{pattern:Se(/[=<>!]+|[+\-*/%]/),type:"operator"},{pattern:Se(/[();,.]/),type:"punctuation"}],wE=[{pattern:Se(/^ {0,3}#{1,6}(?=\s|$)[^\n]*/m),type:"keyword"},{pattern:Se(/^ {0,3}(?:```|~~~)[^\n]*/m),type:"string"},{pattern:Se(/^ {0,3}(?:-{3,}|\*{3,}|_{3,})[ \t]*$/m),type:"comment"},{pattern:Se(/^ {0,3}>+ ?/m),type:"comment"},{pattern:Se(/^ {0,3}(?:[-*+]|\d{1,9}[.)]) +/m),type:"operator"},{pattern:Se(/`[^`\n]+`/),type:"string"},{pattern:Se(/!\[[^\]\n]*\]\([^)\n]*\)/),type:"function"},{pattern:Se(/\[[^\]\n]+\]\([^)\n]*\)/),type:"function"},{pattern:Se(/https?:\/\/[^\s)]+/),type:"function"},{pattern:Se(/\*\*[^\n]+?\*\*/),type:"number"},{pattern:Se(/~~[^\n]+?~~/),type:"number"},{pattern:Se(/\*[^*\n]+?\*/),type:"number"}],Fb={javascript:zb,typescript:Ub,jsx:zb,tsx:Ub,python:fE,bash:hE,json:pE,diff:mE,html:qb,xml:qb,css:gE,yaml:vE,go:yE,rust:bE,java:_E,ruby:SE,c:Hb,cpp:Hb,sql:xE,markdown:wE},kE={js:"javascript",ts:"typescript",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",py:"python",sh:"bash",shell:"bash",zsh:"bash",yml:"yaml",htm:"html",rb:"ruby",rs:"rust","c++":"cpp","objective-c":"c",objc:"c",h:"c",hpp:"cpp",cc:"cpp",cxx:"cpp",patch:"diff",mysql:"sql",postgresql:"sql",postgres:"sql",sqlite:"sql",plsql:"sql",kt:"java",kotlin:"java",scala:"java",groovy:"java",cs:"java",csharp:"java",swift:"c",jsonc:"json",json5:"json",toml:"yaml",md:"markdown",mdx:"markdown"},CE=5e3;function EE(e){const t=e.toLowerCase();return Fb[t]??Fb[kE[t]??""]}function yp(e,t,n){const i=e[e.length-1];i&&i.type===n?i.text+=t:e.push({text:t,type:n})}function $0(e,t){if(!t||e.length>CE)return[{text:e,type:"plain"}];const n=EE(t);if(!n)return[{text:e,type:"plain"}];const i=[];let o=0,d=0;for(;o<e.length;){let h=!1;for(const l of n){l.pattern.lastIndex=o;const u=l.pattern.exec(e);if(u){o>d&&yp(i,e.slice(d,o),"plain"),yp(i,u[0],l.type),o+=u[0].length,d=o,h=!0;break}}h||o++}return o>d&&yp(i,e.slice(d,o),"plain"),i}function NE(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function jE(e,t){const n=$0(e,t);let i="";for(const o of n){const d=$b[o.type]??$b.plain;i+=`<span style="color:${d}">${NE(o.text)}</span>`}return i}function AE(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var bp={exports:{}};const RE={},TE=Object.freeze(Object.defineProperty({__proto__:null,default:RE},Symbol.toStringTag,{value:"Module"})),IE=$C(TE);var Kb;function ME(){return Kb||(Kb=1,(function(e){(function(t){var n=function(O){var W,G=new Float64Array(16);if(O)for(W=0;W<O.length;W++)G[W]=O[W];return G},i=function(){throw new Error("no PRNG")},o=new Uint8Array(16),d=new Uint8Array(32);d[0]=9;var h=n(),l=n([1]),u=n([56129,1]),f=n([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),v=n([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),g=n([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),S=n([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),w=n([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function E(O,W,G,M){O[W]=G>>24&255,O[W+1]=G>>16&255,O[W+2]=G>>8&255,O[W+3]=G&255,O[W+4]=M>>24&255,O[W+5]=M>>16&255,O[W+6]=M>>8&255,O[W+7]=M&255}function x(O,W,G,M,ne){var te,re=0;for(te=0;te<ne;te++)re|=O[W+te]^G[M+te];return(1&re-1>>>8)-1}function m(O,W,G,M){return x(O,W,G,M,16)}function y(O,W,G,M){return x(O,W,G,M,32)}function b(O,W,G,M){for(var ne=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,te=G[0]&255|(G[1]&255)<<8|(G[2]&255)<<16|(G[3]&255)<<24,re=G[4]&255|(G[5]&255)<<8|(G[6]&255)<<16|(G[7]&255)<<24,ve=G[8]&255|(G[9]&255)<<8|(G[10]&255)<<16|(G[11]&255)<<24,Me=G[12]&255|(G[13]&255)<<8|(G[14]&255)<<16|(G[15]&255)<<24,Ze=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,Xe=W[0]&255|(W[1]&255)<<8|(W[2]&255)<<16|(W[3]&255)<<24,Dt=W[4]&255|(W[5]&255)<<8|(W[6]&255)<<16|(W[7]&255)<<24,nt=W[8]&255|(W[9]&255)<<8|(W[10]&255)<<16|(W[11]&255)<<24,Oe=W[12]&255|(W[13]&255)<<8|(W[14]&255)<<16|(W[15]&255)<<24,ce=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,ke=G[16]&255|(G[17]&255)<<8|(G[18]&255)<<16|(G[19]&255)<<24,Ue=G[20]&255|(G[21]&255)<<8|(G[22]&255)<<16|(G[23]&255)<<24,rt=G[24]&255|(G[25]&255)<<8|(G[26]&255)<<16|(G[27]&255)<<24,ct=G[28]&255|(G[29]&255)<<8|(G[30]&255)<<16|(G[31]&255)<<24,et=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,st=ne,gt=te,it=re,ft=ve,lt=Me,ut=Ze,Ne=Xe,Ae=Dt,Ke=nt,$e=Oe,Le=ce,We=ke,Rt=Ue,ae=rt,vt=ct,yt=et,ue,Gt=0;Gt<20;Gt+=2)ue=st+Rt|0,lt^=ue<<7|ue>>>25,ue=lt+st|0,Ke^=ue<<9|ue>>>23,ue=Ke+lt|0,Rt^=ue<<13|ue>>>19,ue=Rt+Ke|0,st^=ue<<18|ue>>>14,ue=ut+gt|0,$e^=ue<<7|ue>>>25,ue=$e+ut|0,ae^=ue<<9|ue>>>23,ue=ae+$e|0,gt^=ue<<13|ue>>>19,ue=gt+ae|0,ut^=ue<<18|ue>>>14,ue=Le+Ne|0,vt^=ue<<7|ue>>>25,ue=vt+Le|0,it^=ue<<9|ue>>>23,ue=it+vt|0,Ne^=ue<<13|ue>>>19,ue=Ne+it|0,Le^=ue<<18|ue>>>14,ue=yt+We|0,ft^=ue<<7|ue>>>25,ue=ft+yt|0,Ae^=ue<<9|ue>>>23,ue=Ae+ft|0,We^=ue<<13|ue>>>19,ue=We+Ae|0,yt^=ue<<18|ue>>>14,ue=st+ft|0,gt^=ue<<7|ue>>>25,ue=gt+st|0,it^=ue<<9|ue>>>23,ue=it+gt|0,ft^=ue<<13|ue>>>19,ue=ft+it|0,st^=ue<<18|ue>>>14,ue=ut+lt|0,Ne^=ue<<7|ue>>>25,ue=Ne+ut|0,Ae^=ue<<9|ue>>>23,ue=Ae+Ne|0,lt^=ue<<13|ue>>>19,ue=lt+Ae|0,ut^=ue<<18|ue>>>14,ue=Le+$e|0,We^=ue<<7|ue>>>25,ue=We+Le|0,Ke^=ue<<9|ue>>>23,ue=Ke+We|0,$e^=ue<<13|ue>>>19,ue=$e+Ke|0,Le^=ue<<18|ue>>>14,ue=yt+vt|0,Rt^=ue<<7|ue>>>25,ue=Rt+yt|0,ae^=ue<<9|ue>>>23,ue=ae+Rt|0,vt^=ue<<13|ue>>>19,ue=vt+ae|0,yt^=ue<<18|ue>>>14;st=st+ne|0,gt=gt+te|0,it=it+re|0,ft=ft+ve|0,lt=lt+Me|0,ut=ut+Ze|0,Ne=Ne+Xe|0,Ae=Ae+Dt|0,Ke=Ke+nt|0,$e=$e+Oe|0,Le=Le+ce|0,We=We+ke|0,Rt=Rt+Ue|0,ae=ae+rt|0,vt=vt+ct|0,yt=yt+et|0,O[0]=st>>>0&255,O[1]=st>>>8&255,O[2]=st>>>16&255,O[3]=st>>>24&255,O[4]=gt>>>0&255,O[5]=gt>>>8&255,O[6]=gt>>>16&255,O[7]=gt>>>24&255,O[8]=it>>>0&255,O[9]=it>>>8&255,O[10]=it>>>16&255,O[11]=it>>>24&255,O[12]=ft>>>0&255,O[13]=ft>>>8&255,O[14]=ft>>>16&255,O[15]=ft>>>24&255,O[16]=lt>>>0&255,O[17]=lt>>>8&255,O[18]=lt>>>16&255,O[19]=lt>>>24&255,O[20]=ut>>>0&255,O[21]=ut>>>8&255,O[22]=ut>>>16&255,O[23]=ut>>>24&255,O[24]=Ne>>>0&255,O[25]=Ne>>>8&255,O[26]=Ne>>>16&255,O[27]=Ne>>>24&255,O[28]=Ae>>>0&255,O[29]=Ae>>>8&255,O[30]=Ae>>>16&255,O[31]=Ae>>>24&255,O[32]=Ke>>>0&255,O[33]=Ke>>>8&255,O[34]=Ke>>>16&255,O[35]=Ke>>>24&255,O[36]=$e>>>0&255,O[37]=$e>>>8&255,O[38]=$e>>>16&255,O[39]=$e>>>24&255,O[40]=Le>>>0&255,O[41]=Le>>>8&255,O[42]=Le>>>16&255,O[43]=Le>>>24&255,O[44]=We>>>0&255,O[45]=We>>>8&255,O[46]=We>>>16&255,O[47]=We>>>24&255,O[48]=Rt>>>0&255,O[49]=Rt>>>8&255,O[50]=Rt>>>16&255,O[51]=Rt>>>24&255,O[52]=ae>>>0&255,O[53]=ae>>>8&255,O[54]=ae>>>16&255,O[55]=ae>>>24&255,O[56]=vt>>>0&255,O[57]=vt>>>8&255,O[58]=vt>>>16&255,O[59]=vt>>>24&255,O[60]=yt>>>0&255,O[61]=yt>>>8&255,O[62]=yt>>>16&255,O[63]=yt>>>24&255}function _(O,W,G,M){for(var ne=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,te=G[0]&255|(G[1]&255)<<8|(G[2]&255)<<16|(G[3]&255)<<24,re=G[4]&255|(G[5]&255)<<8|(G[6]&255)<<16|(G[7]&255)<<24,ve=G[8]&255|(G[9]&255)<<8|(G[10]&255)<<16|(G[11]&255)<<24,Me=G[12]&255|(G[13]&255)<<8|(G[14]&255)<<16|(G[15]&255)<<24,Ze=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,Xe=W[0]&255|(W[1]&255)<<8|(W[2]&255)<<16|(W[3]&255)<<24,Dt=W[4]&255|(W[5]&255)<<8|(W[6]&255)<<16|(W[7]&255)<<24,nt=W[8]&255|(W[9]&255)<<8|(W[10]&255)<<16|(W[11]&255)<<24,Oe=W[12]&255|(W[13]&255)<<8|(W[14]&255)<<16|(W[15]&255)<<24,ce=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,ke=G[16]&255|(G[17]&255)<<8|(G[18]&255)<<16|(G[19]&255)<<24,Ue=G[20]&255|(G[21]&255)<<8|(G[22]&255)<<16|(G[23]&255)<<24,rt=G[24]&255|(G[25]&255)<<8|(G[26]&255)<<16|(G[27]&255)<<24,ct=G[28]&255|(G[29]&255)<<8|(G[30]&255)<<16|(G[31]&255)<<24,et=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,st=ne,gt=te,it=re,ft=ve,lt=Me,ut=Ze,Ne=Xe,Ae=Dt,Ke=nt,$e=Oe,Le=ce,We=ke,Rt=Ue,ae=rt,vt=ct,yt=et,ue,Gt=0;Gt<20;Gt+=2)ue=st+Rt|0,lt^=ue<<7|ue>>>25,ue=lt+st|0,Ke^=ue<<9|ue>>>23,ue=Ke+lt|0,Rt^=ue<<13|ue>>>19,ue=Rt+Ke|0,st^=ue<<18|ue>>>14,ue=ut+gt|0,$e^=ue<<7|ue>>>25,ue=$e+ut|0,ae^=ue<<9|ue>>>23,ue=ae+$e|0,gt^=ue<<13|ue>>>19,ue=gt+ae|0,ut^=ue<<18|ue>>>14,ue=Le+Ne|0,vt^=ue<<7|ue>>>25,ue=vt+Le|0,it^=ue<<9|ue>>>23,ue=it+vt|0,Ne^=ue<<13|ue>>>19,ue=Ne+it|0,Le^=ue<<18|ue>>>14,ue=yt+We|0,ft^=ue<<7|ue>>>25,ue=ft+yt|0,Ae^=ue<<9|ue>>>23,ue=Ae+ft|0,We^=ue<<13|ue>>>19,ue=We+Ae|0,yt^=ue<<18|ue>>>14,ue=st+ft|0,gt^=ue<<7|ue>>>25,ue=gt+st|0,it^=ue<<9|ue>>>23,ue=it+gt|0,ft^=ue<<13|ue>>>19,ue=ft+it|0,st^=ue<<18|ue>>>14,ue=ut+lt|0,Ne^=ue<<7|ue>>>25,ue=Ne+ut|0,Ae^=ue<<9|ue>>>23,ue=Ae+Ne|0,lt^=ue<<13|ue>>>19,ue=lt+Ae|0,ut^=ue<<18|ue>>>14,ue=Le+$e|0,We^=ue<<7|ue>>>25,ue=We+Le|0,Ke^=ue<<9|ue>>>23,ue=Ke+We|0,$e^=ue<<13|ue>>>19,ue=$e+Ke|0,Le^=ue<<18|ue>>>14,ue=yt+vt|0,Rt^=ue<<7|ue>>>25,ue=Rt+yt|0,ae^=ue<<9|ue>>>23,ue=ae+Rt|0,vt^=ue<<13|ue>>>19,ue=vt+ae|0,yt^=ue<<18|ue>>>14;O[0]=st>>>0&255,O[1]=st>>>8&255,O[2]=st>>>16&255,O[3]=st>>>24&255,O[4]=ut>>>0&255,O[5]=ut>>>8&255,O[6]=ut>>>16&255,O[7]=ut>>>24&255,O[8]=Le>>>0&255,O[9]=Le>>>8&255,O[10]=Le>>>16&255,O[11]=Le>>>24&255,O[12]=yt>>>0&255,O[13]=yt>>>8&255,O[14]=yt>>>16&255,O[15]=yt>>>24&255,O[16]=Ne>>>0&255,O[17]=Ne>>>8&255,O[18]=Ne>>>16&255,O[19]=Ne>>>24&255,O[20]=Ae>>>0&255,O[21]=Ae>>>8&255,O[22]=Ae>>>16&255,O[23]=Ae>>>24&255,O[24]=Ke>>>0&255,O[25]=Ke>>>8&255,O[26]=Ke>>>16&255,O[27]=Ke>>>24&255,O[28]=$e>>>0&255,O[29]=$e>>>8&255,O[30]=$e>>>16&255,O[31]=$e>>>24&255}function k(O,W,G,M){b(O,W,G,M)}function j(O,W,G,M){_(O,W,G,M)}var T=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function D(O,W,G,M,ne,te,re){var ve=new Uint8Array(16),Me=new Uint8Array(64),Ze,Xe;for(Xe=0;Xe<16;Xe++)ve[Xe]=0;for(Xe=0;Xe<8;Xe++)ve[Xe]=te[Xe];for(;ne>=64;){for(k(Me,ve,re,T),Xe=0;Xe<64;Xe++)O[W+Xe]=G[M+Xe]^Me[Xe];for(Ze=1,Xe=8;Xe<16;Xe++)Ze=Ze+(ve[Xe]&255)|0,ve[Xe]=Ze&255,Ze>>>=8;ne-=64,W+=64,M+=64}if(ne>0)for(k(Me,ve,re,T),Xe=0;Xe<ne;Xe++)O[W+Xe]=G[M+Xe]^Me[Xe];return 0}function I(O,W,G,M,ne){var te=new Uint8Array(16),re=new Uint8Array(64),ve,Me;for(Me=0;Me<16;Me++)te[Me]=0;for(Me=0;Me<8;Me++)te[Me]=M[Me];for(;G>=64;){for(k(re,te,ne,T),Me=0;Me<64;Me++)O[W+Me]=re[Me];for(ve=1,Me=8;Me<16;Me++)ve=ve+(te[Me]&255)|0,te[Me]=ve&255,ve>>>=8;G-=64,W+=64}if(G>0)for(k(re,te,ne,T),Me=0;Me<G;Me++)O[W+Me]=re[Me];return 0}function L(O,W,G,M,ne){var te=new Uint8Array(32);j(te,M,ne,T);for(var re=new Uint8Array(8),ve=0;ve<8;ve++)re[ve]=M[ve+16];return I(O,W,G,re,te)}function q(O,W,G,M,ne,te,re){var ve=new Uint8Array(32);j(ve,te,re,T);for(var Me=new Uint8Array(8),Ze=0;Ze<8;Ze++)Me[Ze]=te[Ze+16];return D(O,W,G,M,ne,Me,ve)}var H=function(O){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var W,G,M,ne,te,re,ve,Me;W=O[0]&255|(O[1]&255)<<8,this.r[0]=W&8191,G=O[2]&255|(O[3]&255)<<8,this.r[1]=(W>>>13|G<<3)&8191,M=O[4]&255|(O[5]&255)<<8,this.r[2]=(G>>>10|M<<6)&7939,ne=O[6]&255|(O[7]&255)<<8,this.r[3]=(M>>>7|ne<<9)&8191,te=O[8]&255|(O[9]&255)<<8,this.r[4]=(ne>>>4|te<<12)&255,this.r[5]=te>>>1&8190,re=O[10]&255|(O[11]&255)<<8,this.r[6]=(te>>>14|re<<2)&8191,ve=O[12]&255|(O[13]&255)<<8,this.r[7]=(re>>>11|ve<<5)&8065,Me=O[14]&255|(O[15]&255)<<8,this.r[8]=(ve>>>8|Me<<8)&8191,this.r[9]=Me>>>5&127,this.pad[0]=O[16]&255|(O[17]&255)<<8,this.pad[1]=O[18]&255|(O[19]&255)<<8,this.pad[2]=O[20]&255|(O[21]&255)<<8,this.pad[3]=O[22]&255|(O[23]&255)<<8,this.pad[4]=O[24]&255|(O[25]&255)<<8,this.pad[5]=O[26]&255|(O[27]&255)<<8,this.pad[6]=O[28]&255|(O[29]&255)<<8,this.pad[7]=O[30]&255|(O[31]&255)<<8};H.prototype.blocks=function(O,W,G){for(var M=this.fin?0:2048,ne,te,re,ve,Me,Ze,Xe,Dt,nt,Oe,ce,ke,Ue,rt,ct,et,st,gt,it,ft=this.h[0],lt=this.h[1],ut=this.h[2],Ne=this.h[3],Ae=this.h[4],Ke=this.h[5],$e=this.h[6],Le=this.h[7],We=this.h[8],Rt=this.h[9],ae=this.r[0],vt=this.r[1],yt=this.r[2],ue=this.r[3],Gt=this.r[4],bt=this.r[5],Qt=this.r[6],Kt=this.r[7],Jt=this.r[8],Yt=this.r[9];G>=16;)ne=O[W+0]&255|(O[W+1]&255)<<8,ft+=ne&8191,te=O[W+2]&255|(O[W+3]&255)<<8,lt+=(ne>>>13|te<<3)&8191,re=O[W+4]&255|(O[W+5]&255)<<8,ut+=(te>>>10|re<<6)&8191,ve=O[W+6]&255|(O[W+7]&255)<<8,Ne+=(re>>>7|ve<<9)&8191,Me=O[W+8]&255|(O[W+9]&255)<<8,Ae+=(ve>>>4|Me<<12)&8191,Ke+=Me>>>1&8191,Ze=O[W+10]&255|(O[W+11]&255)<<8,$e+=(Me>>>14|Ze<<2)&8191,Xe=O[W+12]&255|(O[W+13]&255)<<8,Le+=(Ze>>>11|Xe<<5)&8191,Dt=O[W+14]&255|(O[W+15]&255)<<8,We+=(Xe>>>8|Dt<<8)&8191,Rt+=Dt>>>5|M,nt=0,Oe=nt,Oe+=ft*ae,Oe+=lt*(5*Yt),Oe+=ut*(5*Jt),Oe+=Ne*(5*Kt),Oe+=Ae*(5*Qt),nt=Oe>>>13,Oe&=8191,Oe+=Ke*(5*bt),Oe+=$e*(5*Gt),Oe+=Le*(5*ue),Oe+=We*(5*yt),Oe+=Rt*(5*vt),nt+=Oe>>>13,Oe&=8191,ce=nt,ce+=ft*vt,ce+=lt*ae,ce+=ut*(5*Yt),ce+=Ne*(5*Jt),ce+=Ae*(5*Kt),nt=ce>>>13,ce&=8191,ce+=Ke*(5*Qt),ce+=$e*(5*bt),ce+=Le*(5*Gt),ce+=We*(5*ue),ce+=Rt*(5*yt),nt+=ce>>>13,ce&=8191,ke=nt,ke+=ft*yt,ke+=lt*vt,ke+=ut*ae,ke+=Ne*(5*Yt),ke+=Ae*(5*Jt),nt=ke>>>13,ke&=8191,ke+=Ke*(5*Kt),ke+=$e*(5*Qt),ke+=Le*(5*bt),ke+=We*(5*Gt),ke+=Rt*(5*ue),nt+=ke>>>13,ke&=8191,Ue=nt,Ue+=ft*ue,Ue+=lt*yt,Ue+=ut*vt,Ue+=Ne*ae,Ue+=Ae*(5*Yt),nt=Ue>>>13,Ue&=8191,Ue+=Ke*(5*Jt),Ue+=$e*(5*Kt),Ue+=Le*(5*Qt),Ue+=We*(5*bt),Ue+=Rt*(5*Gt),nt+=Ue>>>13,Ue&=8191,rt=nt,rt+=ft*Gt,rt+=lt*ue,rt+=ut*yt,rt+=Ne*vt,rt+=Ae*ae,nt=rt>>>13,rt&=8191,rt+=Ke*(5*Yt),rt+=$e*(5*Jt),rt+=Le*(5*Kt),rt+=We*(5*Qt),rt+=Rt*(5*bt),nt+=rt>>>13,rt&=8191,ct=nt,ct+=ft*bt,ct+=lt*Gt,ct+=ut*ue,ct+=Ne*yt,ct+=Ae*vt,nt=ct>>>13,ct&=8191,ct+=Ke*ae,ct+=$e*(5*Yt),ct+=Le*(5*Jt),ct+=We*(5*Kt),ct+=Rt*(5*Qt),nt+=ct>>>13,ct&=8191,et=nt,et+=ft*Qt,et+=lt*bt,et+=ut*Gt,et+=Ne*ue,et+=Ae*yt,nt=et>>>13,et&=8191,et+=Ke*vt,et+=$e*ae,et+=Le*(5*Yt),et+=We*(5*Jt),et+=Rt*(5*Kt),nt+=et>>>13,et&=8191,st=nt,st+=ft*Kt,st+=lt*Qt,st+=ut*bt,st+=Ne*Gt,st+=Ae*ue,nt=st>>>13,st&=8191,st+=Ke*yt,st+=$e*vt,st+=Le*ae,st+=We*(5*Yt),st+=Rt*(5*Jt),nt+=st>>>13,st&=8191,gt=nt,gt+=ft*Jt,gt+=lt*Kt,gt+=ut*Qt,gt+=Ne*bt,gt+=Ae*Gt,nt=gt>>>13,gt&=8191,gt+=Ke*ue,gt+=$e*yt,gt+=Le*vt,gt+=We*ae,gt+=Rt*(5*Yt),nt+=gt>>>13,gt&=8191,it=nt,it+=ft*Yt,it+=lt*Jt,it+=ut*Kt,it+=Ne*Qt,it+=Ae*bt,nt=it>>>13,it&=8191,it+=Ke*Gt,it+=$e*ue,it+=Le*yt,it+=We*vt,it+=Rt*ae,nt+=it>>>13,it&=8191,nt=(nt<<2)+nt|0,nt=nt+Oe|0,Oe=nt&8191,nt=nt>>>13,ce+=nt,ft=Oe,lt=ce,ut=ke,Ne=Ue,Ae=rt,Ke=ct,$e=et,Le=st,We=gt,Rt=it,W+=16,G-=16;this.h[0]=ft,this.h[1]=lt,this.h[2]=ut,this.h[3]=Ne,this.h[4]=Ae,this.h[5]=Ke,this.h[6]=$e,this.h[7]=Le,this.h[8]=We,this.h[9]=Rt},H.prototype.finish=function(O,W){var G=new Uint16Array(10),M,ne,te,re;if(this.leftover){for(re=this.leftover,this.buffer[re++]=1;re<16;re++)this.buffer[re]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(M=this.h[1]>>>13,this.h[1]&=8191,re=2;re<10;re++)this.h[re]+=M,M=this.h[re]>>>13,this.h[re]&=8191;for(this.h[0]+=M*5,M=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=M,M=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=M,G[0]=this.h[0]+5,M=G[0]>>>13,G[0]&=8191,re=1;re<10;re++)G[re]=this.h[re]+M,M=G[re]>>>13,G[re]&=8191;for(G[9]-=8192,ne=(M^1)-1,re=0;re<10;re++)G[re]&=ne;for(ne=~ne,re=0;re<10;re++)this.h[re]=this.h[re]&ne|G[re];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,te=this.h[0]+this.pad[0],this.h[0]=te&65535,re=1;re<8;re++)te=(this.h[re]+this.pad[re]|0)+(te>>>16)|0,this.h[re]=te&65535;O[W+0]=this.h[0]>>>0&255,O[W+1]=this.h[0]>>>8&255,O[W+2]=this.h[1]>>>0&255,O[W+3]=this.h[1]>>>8&255,O[W+4]=this.h[2]>>>0&255,O[W+5]=this.h[2]>>>8&255,O[W+6]=this.h[3]>>>0&255,O[W+7]=this.h[3]>>>8&255,O[W+8]=this.h[4]>>>0&255,O[W+9]=this.h[4]>>>8&255,O[W+10]=this.h[5]>>>0&255,O[W+11]=this.h[5]>>>8&255,O[W+12]=this.h[6]>>>0&255,O[W+13]=this.h[6]>>>8&255,O[W+14]=this.h[7]>>>0&255,O[W+15]=this.h[7]>>>8&255},H.prototype.update=function(O,W,G){var M,ne;if(this.leftover){for(ne=16-this.leftover,ne>G&&(ne=G),M=0;M<ne;M++)this.buffer[this.leftover+M]=O[W+M];if(G-=ne,W+=ne,this.leftover+=ne,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(G>=16&&(ne=G-G%16,this.blocks(O,W,ne),W+=ne,G-=ne),G){for(M=0;M<G;M++)this.buffer[this.leftover+M]=O[W+M];this.leftover+=G}};function Q(O,W,G,M,ne,te){var re=new H(te);return re.update(G,M,ne),re.finish(O,W),0}function F(O,W,G,M,ne,te){var re=new Uint8Array(16);return Q(re,0,G,M,ne,te),m(O,W,re,0)}function J(O,W,G,M,ne){var te;if(G<32)return-1;for(q(O,0,W,0,G,M,ne),Q(O,16,O,32,G-32,O),te=0;te<16;te++)O[te]=0;return 0}function ie(O,W,G,M,ne){var te,re=new Uint8Array(32);if(G<32||(L(re,0,32,M,ne),F(W,16,W,32,G-32,re)!==0))return-1;for(q(O,0,W,0,G,M,ne),te=0;te<32;te++)O[te]=0;return 0}function X(O,W){var G;for(G=0;G<16;G++)O[G]=W[G]|0}function de(O){var W,G,M=1;for(W=0;W<16;W++)G=O[W]+M+65535,M=Math.floor(G/65536),O[W]=G-M*65536;O[0]+=M-1+37*(M-1)}function fe(O,W,G){for(var M,ne=~(G-1),te=0;te<16;te++)M=ne&(O[te]^W[te]),O[te]^=M,W[te]^=M}function $(O,W){var G,M,ne,te=n(),re=n();for(G=0;G<16;G++)re[G]=W[G];for(de(re),de(re),de(re),M=0;M<2;M++){for(te[0]=re[0]-65517,G=1;G<15;G++)te[G]=re[G]-65535-(te[G-1]>>16&1),te[G-1]&=65535;te[15]=re[15]-32767-(te[14]>>16&1),ne=te[15]>>16&1,te[14]&=65535,fe(re,te,1-ne)}for(G=0;G<16;G++)O[2*G]=re[G]&255,O[2*G+1]=re[G]>>8}function P(O,W){var G=new Uint8Array(32),M=new Uint8Array(32);return $(G,O),$(M,W),y(G,0,M,0)}function B(O){var W=new Uint8Array(32);return $(W,O),W[0]&1}function K(O,W){var G;for(G=0;G<16;G++)O[G]=W[2*G]+(W[2*G+1]<<8);O[15]&=32767}function le(O,W,G){for(var M=0;M<16;M++)O[M]=W[M]+G[M]}function me(O,W,G){for(var M=0;M<16;M++)O[M]=W[M]-G[M]}function be(O,W,G){var M,ne,te=0,re=0,ve=0,Me=0,Ze=0,Xe=0,Dt=0,nt=0,Oe=0,ce=0,ke=0,Ue=0,rt=0,ct=0,et=0,st=0,gt=0,it=0,ft=0,lt=0,ut=0,Ne=0,Ae=0,Ke=0,$e=0,Le=0,We=0,Rt=0,ae=0,vt=0,yt=0,ue=G[0],Gt=G[1],bt=G[2],Qt=G[3],Kt=G[4],Jt=G[5],Yt=G[6],An=G[7],bn=G[8],xn=G[9],Rn=G[10],En=G[11],Un=G[12],Vn=G[13],Jn=G[14],is=G[15];M=W[0],te+=M*ue,re+=M*Gt,ve+=M*bt,Me+=M*Qt,Ze+=M*Kt,Xe+=M*Jt,Dt+=M*Yt,nt+=M*An,Oe+=M*bn,ce+=M*xn,ke+=M*Rn,Ue+=M*En,rt+=M*Un,ct+=M*Vn,et+=M*Jn,st+=M*is,M=W[1],re+=M*ue,ve+=M*Gt,Me+=M*bt,Ze+=M*Qt,Xe+=M*Kt,Dt+=M*Jt,nt+=M*Yt,Oe+=M*An,ce+=M*bn,ke+=M*xn,Ue+=M*Rn,rt+=M*En,ct+=M*Un,et+=M*Vn,st+=M*Jn,gt+=M*is,M=W[2],ve+=M*ue,Me+=M*Gt,Ze+=M*bt,Xe+=M*Qt,Dt+=M*Kt,nt+=M*Jt,Oe+=M*Yt,ce+=M*An,ke+=M*bn,Ue+=M*xn,rt+=M*Rn,ct+=M*En,et+=M*Un,st+=M*Vn,gt+=M*Jn,it+=M*is,M=W[3],Me+=M*ue,Ze+=M*Gt,Xe+=M*bt,Dt+=M*Qt,nt+=M*Kt,Oe+=M*Jt,ce+=M*Yt,ke+=M*An,Ue+=M*bn,rt+=M*xn,ct+=M*Rn,et+=M*En,st+=M*Un,gt+=M*Vn,it+=M*Jn,ft+=M*is,M=W[4],Ze+=M*ue,Xe+=M*Gt,Dt+=M*bt,nt+=M*Qt,Oe+=M*Kt,ce+=M*Jt,ke+=M*Yt,Ue+=M*An,rt+=M*bn,ct+=M*xn,et+=M*Rn,st+=M*En,gt+=M*Un,it+=M*Vn,ft+=M*Jn,lt+=M*is,M=W[5],Xe+=M*ue,Dt+=M*Gt,nt+=M*bt,Oe+=M*Qt,ce+=M*Kt,ke+=M*Jt,Ue+=M*Yt,rt+=M*An,ct+=M*bn,et+=M*xn,st+=M*Rn,gt+=M*En,it+=M*Un,ft+=M*Vn,lt+=M*Jn,ut+=M*is,M=W[6],Dt+=M*ue,nt+=M*Gt,Oe+=M*bt,ce+=M*Qt,ke+=M*Kt,Ue+=M*Jt,rt+=M*Yt,ct+=M*An,et+=M*bn,st+=M*xn,gt+=M*Rn,it+=M*En,ft+=M*Un,lt+=M*Vn,ut+=M*Jn,Ne+=M*is,M=W[7],nt+=M*ue,Oe+=M*Gt,ce+=M*bt,ke+=M*Qt,Ue+=M*Kt,rt+=M*Jt,ct+=M*Yt,et+=M*An,st+=M*bn,gt+=M*xn,it+=M*Rn,ft+=M*En,lt+=M*Un,ut+=M*Vn,Ne+=M*Jn,Ae+=M*is,M=W[8],Oe+=M*ue,ce+=M*Gt,ke+=M*bt,Ue+=M*Qt,rt+=M*Kt,ct+=M*Jt,et+=M*Yt,st+=M*An,gt+=M*bn,it+=M*xn,ft+=M*Rn,lt+=M*En,ut+=M*Un,Ne+=M*Vn,Ae+=M*Jn,Ke+=M*is,M=W[9],ce+=M*ue,ke+=M*Gt,Ue+=M*bt,rt+=M*Qt,ct+=M*Kt,et+=M*Jt,st+=M*Yt,gt+=M*An,it+=M*bn,ft+=M*xn,lt+=M*Rn,ut+=M*En,Ne+=M*Un,Ae+=M*Vn,Ke+=M*Jn,$e+=M*is,M=W[10],ke+=M*ue,Ue+=M*Gt,rt+=M*bt,ct+=M*Qt,et+=M*Kt,st+=M*Jt,gt+=M*Yt,it+=M*An,ft+=M*bn,lt+=M*xn,ut+=M*Rn,Ne+=M*En,Ae+=M*Un,Ke+=M*Vn,$e+=M*Jn,Le+=M*is,M=W[11],Ue+=M*ue,rt+=M*Gt,ct+=M*bt,et+=M*Qt,st+=M*Kt,gt+=M*Jt,it+=M*Yt,ft+=M*An,lt+=M*bn,ut+=M*xn,Ne+=M*Rn,Ae+=M*En,Ke+=M*Un,$e+=M*Vn,Le+=M*Jn,We+=M*is,M=W[12],rt+=M*ue,ct+=M*Gt,et+=M*bt,st+=M*Qt,gt+=M*Kt,it+=M*Jt,ft+=M*Yt,lt+=M*An,ut+=M*bn,Ne+=M*xn,Ae+=M*Rn,Ke+=M*En,$e+=M*Un,Le+=M*Vn,We+=M*Jn,Rt+=M*is,M=W[13],ct+=M*ue,et+=M*Gt,st+=M*bt,gt+=M*Qt,it+=M*Kt,ft+=M*Jt,lt+=M*Yt,ut+=M*An,Ne+=M*bn,Ae+=M*xn,Ke+=M*Rn,$e+=M*En,Le+=M*Un,We+=M*Vn,Rt+=M*Jn,ae+=M*is,M=W[14],et+=M*ue,st+=M*Gt,gt+=M*bt,it+=M*Qt,ft+=M*Kt,lt+=M*Jt,ut+=M*Yt,Ne+=M*An,Ae+=M*bn,Ke+=M*xn,$e+=M*Rn,Le+=M*En,We+=M*Un,Rt+=M*Vn,ae+=M*Jn,vt+=M*is,M=W[15],st+=M*ue,gt+=M*Gt,it+=M*bt,ft+=M*Qt,lt+=M*Kt,ut+=M*Jt,Ne+=M*Yt,Ae+=M*An,Ke+=M*bn,$e+=M*xn,Le+=M*Rn,We+=M*En,Rt+=M*Un,ae+=M*Vn,vt+=M*Jn,yt+=M*is,te+=38*gt,re+=38*it,ve+=38*ft,Me+=38*lt,Ze+=38*ut,Xe+=38*Ne,Dt+=38*Ae,nt+=38*Ke,Oe+=38*$e,ce+=38*Le,ke+=38*We,Ue+=38*Rt,rt+=38*ae,ct+=38*vt,et+=38*yt,ne=1,M=te+ne+65535,ne=Math.floor(M/65536),te=M-ne*65536,M=re+ne+65535,ne=Math.floor(M/65536),re=M-ne*65536,M=ve+ne+65535,ne=Math.floor(M/65536),ve=M-ne*65536,M=Me+ne+65535,ne=Math.floor(M/65536),Me=M-ne*65536,M=Ze+ne+65535,ne=Math.floor(M/65536),Ze=M-ne*65536,M=Xe+ne+65535,ne=Math.floor(M/65536),Xe=M-ne*65536,M=Dt+ne+65535,ne=Math.floor(M/65536),Dt=M-ne*65536,M=nt+ne+65535,ne=Math.floor(M/65536),nt=M-ne*65536,M=Oe+ne+65535,ne=Math.floor(M/65536),Oe=M-ne*65536,M=ce+ne+65535,ne=Math.floor(M/65536),ce=M-ne*65536,M=ke+ne+65535,ne=Math.floor(M/65536),ke=M-ne*65536,M=Ue+ne+65535,ne=Math.floor(M/65536),Ue=M-ne*65536,M=rt+ne+65535,ne=Math.floor(M/65536),rt=M-ne*65536,M=ct+ne+65535,ne=Math.floor(M/65536),ct=M-ne*65536,M=et+ne+65535,ne=Math.floor(M/65536),et=M-ne*65536,M=st+ne+65535,ne=Math.floor(M/65536),st=M-ne*65536,te+=ne-1+37*(ne-1),ne=1,M=te+ne+65535,ne=Math.floor(M/65536),te=M-ne*65536,M=re+ne+65535,ne=Math.floor(M/65536),re=M-ne*65536,M=ve+ne+65535,ne=Math.floor(M/65536),ve=M-ne*65536,M=Me+ne+65535,ne=Math.floor(M/65536),Me=M-ne*65536,M=Ze+ne+65535,ne=Math.floor(M/65536),Ze=M-ne*65536,M=Xe+ne+65535,ne=Math.floor(M/65536),Xe=M-ne*65536,M=Dt+ne+65535,ne=Math.floor(M/65536),Dt=M-ne*65536,M=nt+ne+65535,ne=Math.floor(M/65536),nt=M-ne*65536,M=Oe+ne+65535,ne=Math.floor(M/65536),Oe=M-ne*65536,M=ce+ne+65535,ne=Math.floor(M/65536),ce=M-ne*65536,M=ke+ne+65535,ne=Math.floor(M/65536),ke=M-ne*65536,M=Ue+ne+65535,ne=Math.floor(M/65536),Ue=M-ne*65536,M=rt+ne+65535,ne=Math.floor(M/65536),rt=M-ne*65536,M=ct+ne+65535,ne=Math.floor(M/65536),ct=M-ne*65536,M=et+ne+65535,ne=Math.floor(M/65536),et=M-ne*65536,M=st+ne+65535,ne=Math.floor(M/65536),st=M-ne*65536,te+=ne-1+37*(ne-1),O[0]=te,O[1]=re,O[2]=ve,O[3]=Me,O[4]=Ze,O[5]=Xe,O[6]=Dt,O[7]=nt,O[8]=Oe,O[9]=ce,O[10]=ke,O[11]=Ue,O[12]=rt,O[13]=ct,O[14]=et,O[15]=st}function Ee(O,W){be(O,W,W)}function se(O,W){var G=n(),M;for(M=0;M<16;M++)G[M]=W[M];for(M=253;M>=0;M--)Ee(G,G),M!==2&&M!==4&&be(G,G,W);for(M=0;M<16;M++)O[M]=G[M]}function Z(O,W){var G=n(),M;for(M=0;M<16;M++)G[M]=W[M];for(M=250;M>=0;M--)Ee(G,G),M!==1&&be(G,G,W);for(M=0;M<16;M++)O[M]=G[M]}function ge(O,W,G){var M=new Uint8Array(32),ne=new Float64Array(80),te,re,ve=n(),Me=n(),Ze=n(),Xe=n(),Dt=n(),nt=n();for(re=0;re<31;re++)M[re]=W[re];for(M[31]=W[31]&127|64,M[0]&=248,K(ne,G),re=0;re<16;re++)Me[re]=ne[re],Xe[re]=ve[re]=Ze[re]=0;for(ve[0]=Xe[0]=1,re=254;re>=0;--re)te=M[re>>>3]>>>(re&7)&1,fe(ve,Me,te),fe(Ze,Xe,te),le(Dt,ve,Ze),me(ve,ve,Ze),le(Ze,Me,Xe),me(Me,Me,Xe),Ee(Xe,Dt),Ee(nt,ve),be(ve,Ze,ve),be(Ze,Me,Dt),le(Dt,ve,Ze),me(ve,ve,Ze),Ee(Me,ve),me(Ze,Xe,nt),be(ve,Ze,u),le(ve,ve,Xe),be(Ze,Ze,ve),be(ve,Xe,nt),be(Xe,Me,ne),Ee(Me,Dt),fe(ve,Me,te),fe(Ze,Xe,te);for(re=0;re<16;re++)ne[re+16]=ve[re],ne[re+32]=Ze[re],ne[re+48]=Me[re],ne[re+64]=Xe[re];var Oe=ne.subarray(32),ce=ne.subarray(16);return se(Oe,Oe),be(ce,ce,Oe),$(O,ce),0}function De(O,W){return ge(O,W,d)}function Ge(O,W){return i(W,32),De(O,W)}function Ve(O,W,G){var M=new Uint8Array(32);return ge(M,G,W),j(O,o,M,T)}var St=J,Nt=ie;function kt(O,W,G,M,ne,te){var re=new Uint8Array(32);return Ve(re,ne,te),St(O,W,G,M,re)}function Tt(O,W,G,M,ne,te){var re=new Uint8Array(32);return Ve(re,ne,te),Nt(O,W,G,M,re)}var at=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function en(O,W,G,M){for(var ne=new Int32Array(16),te=new Int32Array(16),re,ve,Me,Ze,Xe,Dt,nt,Oe,ce,ke,Ue,rt,ct,et,st,gt,it,ft,lt,ut,Ne,Ae,Ke,$e,Le,We,Rt=O[0],ae=O[1],vt=O[2],yt=O[3],ue=O[4],Gt=O[5],bt=O[6],Qt=O[7],Kt=W[0],Jt=W[1],Yt=W[2],An=W[3],bn=W[4],xn=W[5],Rn=W[6],En=W[7],Un=0;M>=128;){for(lt=0;lt<16;lt++)ut=8*lt+Un,ne[lt]=G[ut+0]<<24|G[ut+1]<<16|G[ut+2]<<8|G[ut+3],te[lt]=G[ut+4]<<24|G[ut+5]<<16|G[ut+6]<<8|G[ut+7];for(lt=0;lt<80;lt++)if(re=Rt,ve=ae,Me=vt,Ze=yt,Xe=ue,Dt=Gt,nt=bt,Oe=Qt,ce=Kt,ke=Jt,Ue=Yt,rt=An,ct=bn,et=xn,st=Rn,gt=En,Ne=Qt,Ae=En,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=(ue>>>14|bn<<18)^(ue>>>18|bn<<14)^(bn>>>9|ue<<23),Ae=(bn>>>14|ue<<18)^(bn>>>18|ue<<14)^(ue>>>9|bn<<23),Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,Ne=ue&Gt^~ue&bt,Ae=bn&xn^~bn&Rn,Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,Ne=at[lt*2],Ae=at[lt*2+1],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,Ne=ne[lt%16],Ae=te[lt%16],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,it=Le&65535|We<<16,ft=Ke&65535|$e<<16,Ne=it,Ae=ft,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=(Rt>>>28|Kt<<4)^(Kt>>>2|Rt<<30)^(Kt>>>7|Rt<<25),Ae=(Kt>>>28|Rt<<4)^(Rt>>>2|Kt<<30)^(Rt>>>7|Kt<<25),Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,Ne=Rt&ae^Rt&vt^ae&vt,Ae=Kt&Jt^Kt&Yt^Jt&Yt,Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,Oe=Le&65535|We<<16,gt=Ke&65535|$e<<16,Ne=Ze,Ae=rt,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=it,Ae=ft,Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,Ze=Le&65535|We<<16,rt=Ke&65535|$e<<16,ae=re,vt=ve,yt=Me,ue=Ze,Gt=Xe,bt=Dt,Qt=nt,Rt=Oe,Jt=ce,Yt=ke,An=Ue,bn=rt,xn=ct,Rn=et,En=st,Kt=gt,lt%16===15)for(ut=0;ut<16;ut++)Ne=ne[ut],Ae=te[ut],Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=ne[(ut+9)%16],Ae=te[(ut+9)%16],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,it=ne[(ut+1)%16],ft=te[(ut+1)%16],Ne=(it>>>1|ft<<31)^(it>>>8|ft<<24)^it>>>7,Ae=(ft>>>1|it<<31)^(ft>>>8|it<<24)^(ft>>>7|it<<25),Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,it=ne[(ut+14)%16],ft=te[(ut+14)%16],Ne=(it>>>19|ft<<13)^(ft>>>29|it<<3)^it>>>6,Ae=(ft>>>19|it<<13)^(it>>>29|ft<<3)^(ft>>>6|it<<26),Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,ne[ut]=Le&65535|We<<16,te[ut]=Ke&65535|$e<<16;Ne=Rt,Ae=Kt,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[0],Ae=W[0],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[0]=Rt=Le&65535|We<<16,W[0]=Kt=Ke&65535|$e<<16,Ne=ae,Ae=Jt,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[1],Ae=W[1],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[1]=ae=Le&65535|We<<16,W[1]=Jt=Ke&65535|$e<<16,Ne=vt,Ae=Yt,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[2],Ae=W[2],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[2]=vt=Le&65535|We<<16,W[2]=Yt=Ke&65535|$e<<16,Ne=yt,Ae=An,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[3],Ae=W[3],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[3]=yt=Le&65535|We<<16,W[3]=An=Ke&65535|$e<<16,Ne=ue,Ae=bn,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[4],Ae=W[4],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[4]=ue=Le&65535|We<<16,W[4]=bn=Ke&65535|$e<<16,Ne=Gt,Ae=xn,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[5],Ae=W[5],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[5]=Gt=Le&65535|We<<16,W[5]=xn=Ke&65535|$e<<16,Ne=bt,Ae=Rn,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[6],Ae=W[6],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[6]=bt=Le&65535|We<<16,W[6]=Rn=Ke&65535|$e<<16,Ne=Qt,Ae=En,Ke=Ae&65535,$e=Ae>>>16,Le=Ne&65535,We=Ne>>>16,Ne=O[7],Ae=W[7],Ke+=Ae&65535,$e+=Ae>>>16,Le+=Ne&65535,We+=Ne>>>16,$e+=Ke>>>16,Le+=$e>>>16,We+=Le>>>16,O[7]=Qt=Le&65535|We<<16,W[7]=En=Ke&65535|$e<<16,Un+=128,M-=128}return M}function cn(O,W,G){var M=new Int32Array(8),ne=new Int32Array(8),te=new Uint8Array(256),re,ve=G;for(M[0]=1779033703,M[1]=3144134277,M[2]=1013904242,M[3]=2773480762,M[4]=1359893119,M[5]=2600822924,M[6]=528734635,M[7]=1541459225,ne[0]=4089235720,ne[1]=2227873595,ne[2]=4271175723,ne[3]=1595750129,ne[4]=2917565137,ne[5]=725511199,ne[6]=4215389547,ne[7]=327033209,en(M,ne,W,G),G%=128,re=0;re<G;re++)te[re]=W[ve-G+re];for(te[G]=128,G=256-128*(G<112?1:0),te[G-9]=0,E(te,G-8,ve/536870912|0,ve<<3),en(M,ne,te,G),re=0;re<8;re++)E(O,8*re,M[re],ne[re]);return 0}function Bt(O,W){var G=n(),M=n(),ne=n(),te=n(),re=n(),ve=n(),Me=n(),Ze=n(),Xe=n();me(G,O[1],O[0]),me(Xe,W[1],W[0]),be(G,G,Xe),le(M,O[0],O[1]),le(Xe,W[0],W[1]),be(M,M,Xe),be(ne,O[3],W[3]),be(ne,ne,v),be(te,O[2],W[2]),le(te,te,te),me(re,M,G),me(ve,te,ne),le(Me,te,ne),le(Ze,M,G),be(O[0],re,ve),be(O[1],Ze,Me),be(O[2],Me,ve),be(O[3],re,Ze)}function hn(O,W,G){var M;for(M=0;M<4;M++)fe(O[M],W[M],G)}function sn(O,W){var G=n(),M=n(),ne=n();se(ne,W[2]),be(G,W[0],ne),be(M,W[1],ne),$(O,M),O[31]^=B(G)<<7}function Ct(O,W,G){var M,ne;for(X(O[0],h),X(O[1],l),X(O[2],l),X(O[3],h),ne=255;ne>=0;--ne)M=G[ne/8|0]>>(ne&7)&1,hn(O,W,M),Bt(W,O),Bt(O,O),hn(O,W,M)}function Ut(O,W){var G=[n(),n(),n(),n()];X(G[0],g),X(G[1],S),X(G[2],l),be(G[3],g,S),Ct(O,G,W)}function $t(O,W,G){var M=new Uint8Array(64),ne=[n(),n(),n(),n()],te;for(G||i(W,32),cn(M,W,32),M[0]&=248,M[31]&=127,M[31]|=64,Ut(ne,M),sn(O,ne),te=0;te<32;te++)W[te+32]=O[te];return 0}var Lt=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Ht(O,W){var G,M,ne,te;for(M=63;M>=32;--M){for(G=0,ne=M-32,te=M-12;ne<te;++ne)W[ne]+=G-16*W[M]*Lt[ne-(M-32)],G=Math.floor((W[ne]+128)/256),W[ne]-=G*256;W[ne]+=G,W[M]=0}for(G=0,ne=0;ne<32;ne++)W[ne]+=G-(W[31]>>4)*Lt[ne],G=W[ne]>>8,W[ne]&=255;for(ne=0;ne<32;ne++)W[ne]-=G*Lt[ne];for(M=0;M<32;M++)W[M+1]+=W[M]>>8,O[M]=W[M]&255}function zt(O){var W=new Float64Array(64),G;for(G=0;G<64;G++)W[G]=O[G];for(G=0;G<64;G++)O[G]=0;Ht(O,W)}function rn(O,W,G,M){var ne=new Uint8Array(64),te=new Uint8Array(64),re=new Uint8Array(64),ve,Me,Ze=new Float64Array(64),Xe=[n(),n(),n(),n()];cn(ne,M,32),ne[0]&=248,ne[31]&=127,ne[31]|=64;var Dt=G+64;for(ve=0;ve<G;ve++)O[64+ve]=W[ve];for(ve=0;ve<32;ve++)O[32+ve]=ne[32+ve];for(cn(re,O.subarray(32),G+32),zt(re),Ut(Xe,re),sn(O,Xe),ve=32;ve<64;ve++)O[ve]=M[ve];for(cn(te,O,G+64),zt(te),ve=0;ve<64;ve++)Ze[ve]=0;for(ve=0;ve<32;ve++)Ze[ve]=re[ve];for(ve=0;ve<32;ve++)for(Me=0;Me<32;Me++)Ze[ve+Me]+=te[ve]*ne[Me];return Ht(O.subarray(32),Ze),Dt}function ze(O,W){var G=n(),M=n(),ne=n(),te=n(),re=n(),ve=n(),Me=n();return X(O[2],l),K(O[1],W),Ee(ne,O[1]),be(te,ne,f),me(ne,ne,O[2]),le(te,O[2],te),Ee(re,te),Ee(ve,re),be(Me,ve,re),be(G,Me,ne),be(G,G,te),Z(G,G),be(G,G,ne),be(G,G,te),be(G,G,te),be(O[0],G,te),Ee(M,O[0]),be(M,M,te),P(M,ne)&&be(O[0],O[0],w),Ee(M,O[0]),be(M,M,te),P(M,ne)?-1:(B(O[0])===W[31]>>7&&me(O[0],h,O[0]),be(O[3],O[0],O[1]),0)}function Je(O,W,G,M){var ne,te=new Uint8Array(32),re=new Uint8Array(64),ve=[n(),n(),n(),n()],Me=[n(),n(),n(),n()];if(G<64||ze(Me,M))return-1;for(ne=0;ne<G;ne++)O[ne]=W[ne];for(ne=0;ne<32;ne++)O[ne+32]=M[ne];if(cn(re,O,G),zt(re),Ct(ve,Me,re),Ut(Me,W.subarray(32)),Bt(ve,Me),sn(te,ve),G-=64,y(W,0,te,0)){for(ne=0;ne<G;ne++)O[ne]=0;return-1}for(ne=0;ne<G;ne++)O[ne]=W[ne+64];return G}var tt=32,Pt=24,Vt=32,Wt=16,Zt=32,Dn=32,wn=32,Kn=32,je=32,mt=Pt,xt=Vt,Mt=Wt,un=64,_n=32,tn=64,zn=32,ss=64;t.lowlevel={crypto_core_hsalsa20:j,crypto_stream_xor:q,crypto_stream:L,crypto_stream_salsa20_xor:D,crypto_stream_salsa20:I,crypto_onetimeauth:Q,crypto_onetimeauth_verify:F,crypto_verify_16:m,crypto_verify_32:y,crypto_secretbox:J,crypto_secretbox_open:ie,crypto_scalarmult:ge,crypto_scalarmult_base:De,crypto_box_beforenm:Ve,crypto_box_afternm:St,crypto_box:kt,crypto_box_open:Tt,crypto_box_keypair:Ge,crypto_hash:cn,crypto_sign:rn,crypto_sign_keypair:$t,crypto_sign_open:Je,crypto_secretbox_KEYBYTES:tt,crypto_secretbox_NONCEBYTES:Pt,crypto_secretbox_ZEROBYTES:Vt,crypto_secretbox_BOXZEROBYTES:Wt,crypto_scalarmult_BYTES:Zt,crypto_scalarmult_SCALARBYTES:Dn,crypto_box_PUBLICKEYBYTES:wn,crypto_box_SECRETKEYBYTES:Kn,crypto_box_BEFORENMBYTES:je,crypto_box_NONCEBYTES:mt,crypto_box_ZEROBYTES:xt,crypto_box_BOXZEROBYTES:Mt,crypto_sign_BYTES:un,crypto_sign_PUBLICKEYBYTES:_n,crypto_sign_SECRETKEYBYTES:tn,crypto_sign_SEEDBYTES:zn,crypto_hash_BYTES:ss,gf:n,D:f,L:Lt,pack25519:$,unpack25519:K,M:be,A:le,S:Ee,Z:me,pow2523:Z,add:Bt,set25519:X,modL:Ht,scalarmult:Ct,scalarbase:Ut};function Ie(O,W){if(O.length!==tt)throw new Error("bad key size");if(W.length!==Pt)throw new Error("bad nonce size")}function ot(O,W){if(O.length!==wn)throw new Error("bad public key size");if(W.length!==Kn)throw new Error("bad secret key size")}function pt(){for(var O=0;O<arguments.length;O++)if(!(arguments[O]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function At(O){for(var W=0;W<O.length;W++)O[W]=0}t.randomBytes=function(O){var W=new Uint8Array(O);return i(W,O),W},t.secretbox=function(O,W,G){pt(O,W,G),Ie(G,W);for(var M=new Uint8Array(Vt+O.length),ne=new Uint8Array(M.length),te=0;te<O.length;te++)M[te+Vt]=O[te];return J(ne,M,M.length,W,G),ne.subarray(Wt)},t.secretbox.open=function(O,W,G){pt(O,W,G),Ie(G,W);for(var M=new Uint8Array(Wt+O.length),ne=new Uint8Array(M.length),te=0;te<O.length;te++)M[te+Wt]=O[te];return M.length<32||ie(ne,M,M.length,W,G)!==0?null:ne.subarray(Vt)},t.secretbox.keyLength=tt,t.secretbox.nonceLength=Pt,t.secretbox.overheadLength=Wt,t.scalarMult=function(O,W){if(pt(O,W),O.length!==Dn)throw new Error("bad n size");if(W.length!==Zt)throw new Error("bad p size");var G=new Uint8Array(Zt);return ge(G,O,W),G},t.scalarMult.base=function(O){if(pt(O),O.length!==Dn)throw new Error("bad n size");var W=new Uint8Array(Zt);return De(W,O),W},t.scalarMult.scalarLength=Dn,t.scalarMult.groupElementLength=Zt,t.box=function(O,W,G,M){var ne=t.box.before(G,M);return t.secretbox(O,W,ne)},t.box.before=function(O,W){pt(O,W),ot(O,W);var G=new Uint8Array(je);return Ve(G,O,W),G},t.box.after=t.secretbox,t.box.open=function(O,W,G,M){var ne=t.box.before(G,M);return t.secretbox.open(O,W,ne)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var O=new Uint8Array(wn),W=new Uint8Array(Kn);return Ge(O,W),{publicKey:O,secretKey:W}},t.box.keyPair.fromSecretKey=function(O){if(pt(O),O.length!==Kn)throw new Error("bad secret key size");var W=new Uint8Array(wn);return De(W,O),{publicKey:W,secretKey:new Uint8Array(O)}},t.box.publicKeyLength=wn,t.box.secretKeyLength=Kn,t.box.sharedKeyLength=je,t.box.nonceLength=mt,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(O,W){if(pt(O,W),W.length!==tn)throw new Error("bad secret key size");var G=new Uint8Array(un+O.length);return rn(G,O,O.length,W),G},t.sign.open=function(O,W){if(pt(O,W),W.length!==_n)throw new Error("bad public key size");var G=new Uint8Array(O.length),M=Je(G,O,O.length,W);if(M<0)return null;for(var ne=new Uint8Array(M),te=0;te<ne.length;te++)ne[te]=G[te];return ne},t.sign.detached=function(O,W){for(var G=t.sign(O,W),M=new Uint8Array(un),ne=0;ne<M.length;ne++)M[ne]=G[ne];return M},t.sign.detached.verify=function(O,W,G){if(pt(O,W,G),W.length!==un)throw new Error("bad signature size");if(G.length!==_n)throw new Error("bad public key size");var M=new Uint8Array(un+O.length),ne=new Uint8Array(un+O.length),te;for(te=0;te<un;te++)M[te]=W[te];for(te=0;te<O.length;te++)M[te+un]=O[te];return Je(ne,M,M.length,G)>=0},t.sign.keyPair=function(){var O=new Uint8Array(_n),W=new Uint8Array(tn);return $t(O,W),{publicKey:O,secretKey:W}},t.sign.keyPair.fromSecretKey=function(O){if(pt(O),O.length!==tn)throw new Error("bad secret key size");for(var W=new Uint8Array(_n),G=0;G<W.length;G++)W[G]=O[32+G];return{publicKey:W,secretKey:new Uint8Array(O)}},t.sign.keyPair.fromSeed=function(O){if(pt(O),O.length!==zn)throw new Error("bad seed size");for(var W=new Uint8Array(_n),G=new Uint8Array(tn),M=0;M<32;M++)G[M]=O[M];return $t(W,G,!0),{publicKey:W,secretKey:G}},t.sign.publicKeyLength=_n,t.sign.secretKeyLength=tn,t.sign.seedLength=zn,t.sign.signatureLength=un,t.hash=function(O){pt(O);var W=new Uint8Array(ss);return cn(W,O,O.length),W},t.hash.hashLength=ss,t.verify=function(O,W){return pt(O,W),O.length===0||W.length===0||O.length!==W.length?!1:x(O,0,W,0,O.length)===0},t.setPRNG=function(O){i=O},(function(){var O=typeof self<"u"?self.crypto||self.msCrypto:null;if(O&&O.getRandomValues){var W=65536;t.setPRNG(function(G,M){var ne,te=new Uint8Array(M);for(ne=0;ne<M;ne+=W)O.getRandomValues(te.subarray(ne,ne+Math.min(M-ne,W)));for(ne=0;ne<M;ne++)G[ne]=te[ne];At(te)})}else typeof AE<"u"&&(O=IE,O&&O.randomBytes&&t.setPRNG(function(G,M){var ne,te=O.randomBytes(M);for(ne=0;ne<M;ne++)G[ne]=te[ne];At(te)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})(bp)),bp.exports}var DE=ME();const us=Um(DE);var Od={exports:{}},LE=Od.exports,Wb;function OE(){return Wb||(Wb=1,(function(e){(function(t,n){e.exports?e.exports=n():(t.nacl||(t.nacl={}),t.nacl.util=n())})(LE,function(){var t={};function n(i){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(i))throw new TypeError("invalid encoding")}return t.decodeUTF8=function(i){if(typeof i!="string")throw new TypeError("expected string");var o,d=unescape(encodeURIComponent(i)),h=new Uint8Array(d.length);for(o=0;o<d.length;o++)h[o]=d.charCodeAt(o);return h},t.encodeUTF8=function(i){var o,d=[];for(o=0;o<i.length;o++)d.push(String.fromCharCode(i[o]));return decodeURIComponent(escape(d.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(t.encodeBase64=function(i){return Buffer.from(i).toString("base64")},t.decodeBase64=function(i){return n(i),new Uint8Array(Array.prototype.slice.call(Buffer.from(i,"base64"),0))}):(t.encodeBase64=function(i){return new Buffer(i).toString("base64")},t.decodeBase64=function(i){return n(i),new Uint8Array(Array.prototype.slice.call(new Buffer(i,"base64"),0))}):(t.encodeBase64=function(i){var o,d=[],h=i.length;for(o=0;o<h;o++)d.push(String.fromCharCode(i[o]));return btoa(d.join(""))},t.decodeBase64=function(i){n(i);var o,d=atob(i),h=new Uint8Array(d.length);for(o=0;o<d.length;o++)h[o]=d.charCodeAt(o);return h}),t})})(Od)),Od.exports}var PE=OE();const BE=Um(PE),{encodeBase64:Fm,decodeBase64:br}=BE,$E=24,zE=2**48,um=32,UE=0,qE=1;function z0(){const e=us.box.keyPair();return{publicKey:Fm(e.publicKey),secretKey:e.secretKey}}const HE="chroxy-exchange-key-v1:";function FE(e,t){const n=new TextEncoder().encode(HE),i=new Uint8Array(n.length+e.length);return i.set(n,0),i.set(e,n.length),i}function Km(e,t,n){try{if(typeof e!="string"||e.length===0||typeof t!="string"||t.length===0||typeof n!="string"||n.length===0)return!1;const i=new Uint8Array(br(e)),o=new Uint8Array(br(t)),d=new Uint8Array(br(n));return i.length!==us.box.publicKeyLength||o.length!==us.sign.signatureLength||d.length!==us.sign.publicKeyLength?!1:us.sign.detached.verify(i,o,d)||us.sign.detached.verify(FE(i,!0),o,d)}catch{return!1}}const KE="chroxy-identity-rotation-v1:";function WE(e){const t=new TextEncoder().encode(KE),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function GE(e,t,n){try{if(typeof e!="string"||e.length===0||typeof t!="string"||t.length===0||typeof n!="string"||n.length===0)return!1;const i=new Uint8Array(br(e)),o=new Uint8Array(br(t)),d=new Uint8Array(br(n));return i.length!==us.sign.publicKeyLength||o.length!==us.sign.signatureLength||d.length!==us.sign.publicKeyLength?!1:us.sign.detached.verify(WE(i),o,d)}catch{return!1}}function Gb(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error("Invalid peer public key: expected a non-empty base64 string");let n;try{n=br(e)}catch{throw new Error("Invalid peer public key: not valid base64")}if(n.length!==us.box.publicKeyLength)throw new Error(`Invalid peer public key: expected length ${us.box.publicKeyLength}, got ${n.length}`);return new Uint8Array(us.box.before(n,t))}function U0(e,t){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new RangeError("Nonce counter must be a non-negative integer");if(e>zE)throw new Error("Nonce counter exhausted — reconnect required for new key exchange");const n=new Uint8Array($E);n[0]=t;let i=e;for(let o=1;o<=8;o++)n[o]=i&255,i=Math.floor(i/256);return n}function VE(e,t,n,i){const o=U0(n,i),d=new Uint8Array(new TextEncoder().encode(e)),h=us.secretbox(new Uint8Array(d),new Uint8Array(o),new Uint8Array(t));return{type:"encrypted",d:Fm(h),n}}function YE(e,t,n,i){if(typeof e.d!="string")throw new TypeError("decrypt: envelope.d must be a base64 string");if(typeof e.n!="number")throw new TypeError("decrypt: envelope.n must be a number");if(e.n!==n)throw new Error(`Unexpected nonce: got ${e.n}, expected ${n}`);const o=U0(e.n,i),d=new Uint8Array(br(e.d)),h=us.secretbox.open(d,new Uint8Array(o),new Uint8Array(t));if(!h)throw new Error("Decryption failed: message tampered or wrong key");try{return JSON.parse(new TextDecoder().decode(h))}catch(l){throw Object.assign(new Error("Decryption failed: plaintext is not valid JSON"),{cause:l})}}function q0(){return Fm(us.randomBytes(um))}function Vb(e,t){if(!(e instanceof Uint8Array)||e.length!==us.secretbox.keyLength)throw new Error(`Invalid shared key: expected ${us.secretbox.keyLength}-byte Uint8Array, got ${e instanceof Uint8Array?e.length:typeof e}`);if(typeof t!="string"||t.trim().length===0)throw new Error("Invalid connection salt: expected a non-empty base64 string");let n;try{n=br(t)}catch{throw new Error("Invalid connection salt: not valid base64")}if(n.length!==um)throw new Error(`Invalid connection salt: expected ${um} bytes, got ${n.length}`);const i=new Uint8Array(e.length+n.length);return i.set(e,0),i.set(n,e.length),us.hash(i).slice(0,us.secretbox.keyLength)}const Yd="Server identity changed — refused to connect. The daemon's encryption key doesn't match the one you paired with. This can happen if the server was reinstalled or its identity key rotated — or it could be a network impersonation attempt. Re-pair (scan a fresh QR / enter a new pairing code) to trust the new identity.",ZE="Refused to connect — this server you paired with did not negotiate encryption. A paired (pinned) connection must be end-to-end encrypted; an unencrypted handshake here means the server lost its identity key, or a network attacker is trying to downgrade you to plaintext to bypass identity verification. Re-pair (scan a fresh QR / enter a new pairing code) if the server was genuinely reinstalled.";function XE(e){return!!(e.pinnedIdentityKey||e.pairingIdentityKey)&&e.encryptionMode!=="required"?{action:"refuse",reason:"pinned-but-unencrypted",message:ZE}:{action:"connect",reason:"verified"}}function QE(e){const{pinnedIdentityKey:t,exchangePublicKey:n,serverKeySig:i}=e;if(!t)return i&&n?{action:"connect",reason:"unpinned-no-identity"}:{action:"connect",reason:"unpinned-no-identity"};if(!i)return{action:"refuse",reason:"pinned-but-unsigned",message:Yd};if(Km(n,i,t))return{action:"connect",reason:"verified"};const d=JE({pinnedIdentityKey:t,exchangePublicKey:n,serverKeySig:i,input:e});return d||{action:"refuse",reason:"signature-mismatch",message:Yd}}function JE(e){const{pinnedIdentityKey:t,exchangePublicKey:n,serverKeySig:i,input:o}=e,d=o.newIdentityKey,h=o.rotationCert;return!d||!h||!GE(d,h,t)||!Km(n,i,d)?null:{action:"rotate-pin",reason:"identity-rotated",identityKey:d}}function eN(e){const{pinnedIdentityKey:t,pairingIdentityKey:n,exchangePublicKey:i,serverKeySig:o}=e;return t?QE({pinnedIdentityKey:t,exchangePublicKey:i,serverKeySig:o,newIdentityKey:e.newIdentityKey,rotationCert:e.rotationCert}):n?o?Km(i,o,n)?{action:"pin-and-connect",reason:"pin-on-first-use",identityKey:n}:{action:"refuse",reason:"signature-mismatch",message:Yd}:{action:"refuse",reason:"pinned-but-unsigned",message:Yd}:{action:"connect",reason:"unpinned-no-identity"}}function Fc(e){return e.replace(/\x1b\[[0-9;?]*[A-Za-z~]|\x1b\][^\x07]*\x07?|\x1b[()#][A-Z0-2]|\x1b[A-Za-z]|\x9b[0-9;?]*[A-Za-z~]/g,"")}let tN=0;function fn(e="msg"){return`${e}-${++tN}-${Date.now()}`}function vr(e){return e.filter(t=>t.id!=="thinking")}function nN(){return{messages:[],streamingMessageId:null,pendingClientMessageId:null,claudeReady:!1,activeModel:null,permissionMode:null,contextUsage:null,lastResultCost:null,lastResultDuration:null,sessionCost:null,cumulativeUsage:null,costThresholdWarning:null,isIdle:!0,lastClientActivityAt:null,health:"healthy",stoppedAt:null,stoppedCode:null,activeAgents:[],activeTools:[],pendingBackgroundShells:[],transcriptBackgroundTasks:[],scheduledWakeup:null,isPlanPending:!1,planAllowedPrompts:[],primaryClientId:null,sessionRole:null,conversationId:null,sessionContext:null,mcpServers:[],devPreviews:[],inactivityWarning:null,interventions:[],queuedMessages:[]}}const Yb=50,sN=new Set(["stream_start","stream_delta","stream_end","tool_start","tool_input_delta","tool_result","message","result","user_question","permission_request"]);function iN(e){return typeof e=="string"&&sN.has(e)}function rN(e){if(Array.isArray(e))return e.map(n=>String(n)).join(", ");if(!e.startsWith("["))return e;let t;try{t=JSON.parse(e)}catch{return e}return Array.isArray(t)?t.map(n=>String(n)).join(", "):e}function H0(e){return typeof e=="string"?e:!Array.isArray(e)&&Object.keys(e).length===2&&"freeformText"in e&&"otherLabel"in e&&typeof e.freeformText=="string"&&typeof e.otherLabel=="string"?e.freeformText:Object.entries(e).map(([t,n])=>`${t}: ${rN(n)}`).join(" | ")}function gr(e){return!Number.isFinite(e)||e<=0?"$0":e>=1?`$${e.toFixed(2)}`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(3)}`}function aN(e){const t=gr(e.costUsd),n=e.inputTokens,i=e.outputTokens;return n<=0&&i<=0?`This turn cost ${t}`:`This turn cost ${t} (${oa(n)} in · ${oa(i)} out)`}function oa(e){return!Number.isFinite(e)||e<=0?"0":(e=Math.round(e),e<1e3?String(e):e<999500?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(2)}M`)}function Ga(e){if(!Number.isFinite(e)||e<=0)return"0";if(e=Math.round(e),e<1e3)return String(e);if(e<999500)return`${(e/1e3).toFixed(1)}k`;const n=(e/1e6).toFixed(1);return n.endsWith(".0")?`${n.slice(0,-2)}M`:`${n}M`}function oN(e){const t=n=>n.toLocaleString();return[`Total cost: $${e.costUsd.toFixed(4)}`,`Turns billed: ${t(e.turnsBilled)}`,`Input tokens: ${t(e.inputTokens)}`,`Output tokens: ${t(e.outputTokens)}`,`Cache read: ${t(e.cacheReadTokens)}`,`Cache write: ${t(e.cacheCreationTokens)}`].join(`
|
|
10
|
-
`)}function _p(e){const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;const n=Math.floor(t/60),i=t%60;return n<60?i===0?`${n}m`:`${n}m ${i}s`:`${Math.floor(n/60)}h ${n%60}m`}function lN(e){if(!Number.isFinite(e))return"1 second";const t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t} ${t===1?"second":"seconds"}`;const n=Math.round(t/60);if(n<60)return`${n} ${n===1?"minute":"minutes"}`;const i=Math.round(n/60);return`${i} ${i===1?"hour":"hours"}`}function F0(e){if(e<1e3)return"just now";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),i=t%60;return n<60?i===0?`${n}m`:`${n}m ${i}s`:`${Math.floor(n/60)}h ${n%60}m`}function cN(e){const t=F0(e);return t==="just now"?t:`${t} ago`}const uN=3600*1e3;function dN(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function fN(e){if(e.isBusy===!0||!!e.streamingMessageId||e.isIdle===!1||(e.activeAgentCount??0)>0)return"working";const n=e.staleAfterMs??uN,i=e.now??Date.now(),o=e.lastActivityAt;return n>0&&dN(o)&&i-o>=n?"stale":"idle"}function hN(e,t){if(!e)return{resolvedId:t};if(e.type==="response")return{resolvedId:t};const n=`${t}-response`;return{resolvedId:n,remap:{from:t,to:n}}}function Zb(e,t,n,i){for(const[o,d]of t){if(n.has(o))continue;const h=e.some(f=>f.id===o&&f.type!=="response"),l=h?`${o}-response`:o,u=e.findIndex(f=>f.id===l);if(u!==-1){const f=e[u];e[u]={...f,content:f.content+d}}else{const f={id:l,type:"response",content:d,timestamp:Date.now()};e.push(f)}h&&i.set(o,l)}}function da(){return Object.create(null)}function Wm(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const K0=50,pN=Object.freeze({byId:Object.freeze(da()),order:Object.freeze([])});function Pd(){return{bySession:da()}}function dm(e){return e.status==="done"||e.status==="failed"}function mN(e,t){if(e===void 0)return!0;const n=dm(e),i=dm(t);if(n&&!i)return!1;if(n&&i){const o=e.endedAt??0;return(t.endedAt??0)>=o}return!0}function gN(e,t,n){const i=e.byId[t.id];if(!mN(i,t))return e;const o=da();Object.assign(o,e.byId),o[t.id]=t;const d=i===void 0?[...e.order,t.id]:e.order;return W0({byId:o,order:d},n)}function W0(e,t){if(!Number.isFinite(t)||t<0)return e;const n=[];for(const f of e.order){const v=e.byId[f];v!==void 0&&dm(v)&&n.push(f)}if(n.length<=t)return e;const i=new Map(e.order.map((f,v)=>[f,v])),o=[...n].sort((f,v)=>{const g=e.byId[f].endedAt??0,S=e.byId[v].endedAt??0;return g!==S?g-S:(i.get(f)??0)-(i.get(v)??0)}),d=n.length-t,h=new Set(o.slice(0,d)),l=da();for(const f of e.order)h.has(f)||(l[f]=e.byId[f]);const u=e.order.filter(f=>!h.has(f));return{byId:l,order:u}}function vN(e,t,n=K0){const i=da(),o=[];for(const l of t.entries)Wm(i,l.id)||o.push(l.id),i[l.id]=l;const d=W0({byId:i,order:o},n),h=da();return Object.assign(h,e.bySession),h[t.sessionId]=d,{bySession:h}}function yN(e,t,n=K0){const i=e.bySession[t.sessionId]??pN,o=gN(i,t.entry,n);if(o===i)return e;const d=da();return Object.assign(d,e.bySession),d[t.sessionId]=o,{bySession:d}}function bN(e,t){if(!Wm(e.bySession,t))return e;const n=da();return Object.assign(n,e.bySession),delete n[t],{bySession:n}}function _N(e,t){const n=e.bySession[t];return n===void 0?[]:n.order.map(i=>n.byId[i]).filter(i=>i!==void 0)}function SN(e,t){const n=e.bySession[t];if(n===void 0)return[];const i=new Map,o=[];for(const u of n.order){const f=n.byId[u];if(f===void 0)continue;const v=f.parentId;if(v!==void 0&&v!==f.id&&Wm(n.byId,v)){const g=i.get(v);g===void 0?i.set(v,[f]):g.push(f)}else o.push(f)}const d=new Set;function h(u){d.add(u.id);const f=[{entry:u,kids:i.get(u.id)??[],i:0,children:[]}];for(;;){const v=f[f.length-1];if(v.i>=v.kids.length){f.pop();const S={entry:v.entry,children:v.children},w=f[f.length-1];if(w===void 0)return S;w.children.push(S);continue}const g=v.kids[v.i];v.i+=1,!d.has(g.id)&&(d.add(g.id),f.push({entry:g,kids:i.get(g.id)??[],i:0,children:[]}))}}const l=o.map(u=>h(u));for(const u of n.order){if(d.has(u))continue;const f=n.byId[u];f!==void 0&&l.push(h(f))}return l}function xN(e){let t=!1,n=!1;for(const i of e){if(i.status==="blocked")return"blocked";i.status==="running"?t=!0:i.status==="failed"&&(n=!0)}return t?"running":n?"failed":"idle"}function wN(e){const t=e.split(/[/\\]/).filter(Boolean);return t.length>0?t[t.length-1]:e}const Xb=()=>({running:0,blocked:0,failed:0,idle:0});function G0(e,t){const n=new Map,i=Xb(),o=new Set;for(const l of t){if(o.has(l.sessionId))continue;o.add(l.sessionId);const u=xN(_N(e,l.sessionId)),f=typeof l.cwd=="string"&&l.cwd.trim()!==""?l.cwd:"";let v=n.get(f);v===void 0&&(v={worktree:!1,sessions:[],rollup:Xb()},n.set(f,v)),v.sessions.push({sessionId:l.sessionId,name:l.name??l.sessionId,status:u}),l.worktree===!0&&(v.worktree=!0),v.rollup[u]+=1,i[u]+=1}return{groups:[...n.keys()].sort((l,u)=>l===u?0:l===""?1:u===""||l<u?-1:1).map(l=>{const u=n.get(l);return{key:l,label:l===""?"Ungrouped":wN(l),worktree:u.worktree,sessions:u.sessions,rollup:u.rollup}}),total:i}}function kN(e,t){let n="idle";e.hasError?n="error":e.pendingPermission||e.isPlanPending?n="waiting":e.streamingMessageId?n="thinking":e.isIdle||(n="busy");const i=Date.now();return{state:n,startedAt:i}}function Gm(e){if(!e)return;const t=e.trimEnd();if(t.length===0)return;const n=t.charCodeAt(t.length-1);if(!(n!==125&&n!==93))try{return JSON.parse(e)}catch{return}}function CN(e){const t=[];let n=[];const i=()=>{const o=n[0];o&&(t.push({type:"activity",messages:[...n],isActive:!1,key:`activity-${o.id}`}),n=[])};for(const o of e)o.type==="tool_use"||o.type==="thinking"?n.push(o):(i(),t.push({type:"single",message:o}));return i(),t}function EN(e,t,n){if(!n||e.length===0)return e;const i=e[e.length-1];if(!i||i.type!=="activity")return e;const o=i.messages[i.messages.length-1],d=t[t.length-1];if(!o||!d||o!==d)return e;const h=e.slice(0,-1);return h.push({type:"activity",messages:i.messages,isActive:!0,key:i.key}),h}function NN(e){const t=new Map;for(const n of e){if(n.type!=="tool_use")continue;const i=fa(n.tool??"Tool",n.serverName);t.set(i,(t.get(i)??0)+1)}return Array.from(t.entries()).map(([n,i])=>({name:n,count:i})).sort((n,i)=>i.count-n.count||n.name.localeCompare(i.name))}function jN(e){return e.map(({name:t,count:n})=>`${n} ${t}`).join(", ")}function fa(e,t){const n="mcp__";if(e.startsWith(n)){const o=e.slice(n.length),d=o.indexOf("__");if(d>0){const h=o.slice(0,d).split("_").filter(Boolean).map(Sp).join(" "),l=o.slice(d+2).split("_").filter(Boolean).map(Sp).join(" ");return l?`${h}: ${l}`:h}}const i=e.split("_").filter(Boolean).map(Sp).join(" ");return t?`${t} ${i}`:i}function Sp(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const AN=new Set(["ASK_USER_QUESTION_STALL","ASK_USER_QUESTION_MULTISELECT_UNSUPPORTED","ASK_USER_QUESTION_MULTISELECT_UNAVAILABLE","ASK_USER_QUESTION_MULTISELECT_EMPTY","ASK_USER_QUESTION_MULTISELECT_BUSY","ASK_USER_QUESTION_MULTI_QUESTION_UNSUPPORTED"]);function Vm(e){return e!=null&&AN.has(e)}function fm(e){return{id:e.id,type:e.type==="prompt"?"response":e.type,content:e.content,timestamp:e.timestamp,...e.code?{code:e.code}:{}}}function RN(e,t){const n=e.filter(g=>g.type!=="system"),i=CN(n),o=EN(i,n,t??null),d=new Map;for(const g of o)g.type==="activity"&&g.messages.length>=2&&d.set(g.key,{messages:g.messages,isActive:g.isActive});const h=o.map(g=>{if(g.type==="single")return fm(g.message);if(g.messages.length<2)return fm(g.messages[0]);const S=g.messages[g.messages.length-1];return{id:g.key,type:"tool_group",content:"",timestamp:S?.timestamp??0}}),l=h.length>0?h[h.length-1].id:null,u=new Map(e.map(g=>[g.id,g])),f=new Set;let v=-1;for(let g=e.length-1;g>=0;g-=1){const S=e[g];if(S.type==="error"&&Vm(S.code)){v=g;break}}if(v>=0)for(let g=0;g<v;g+=1){const S=e[g];S.type==="prompt"&&!S.answered&&f.add(S.id)}return{chatMessages:h,displayGroups:o,chatToolGroupPayloads:d,chatTailMessageId:l,storeMsgMap:u,stalledPromptIds:f}}const Zd=["command","file_path","filePath","path","description"],qa=100;function V0(e){const t=Object.keys(e);if(t.length===0)return null;const n=[];let i=0;for(const o of t){const d=e[o],h=`${o}: ${TN(d)}`,l=n.length===0?h.length:h.length+2;if(i+l>qa)break;n.push(h),i+=l}if(n.length===0){const o=`${t.length} key${t.length===1?"":"s"}: `,d=[];let h=o.length;for(const l of t){const u=d.length===0?l.length:l.length+2;h+u>qa||(d.push(l),h+=u)}return`${o}${d.join(", ")}`}return n.join(", ")}function TN(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e.length>40?`${JSON.stringify(e.slice(0,37)).slice(0,-1)}..."`:JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length}]`:typeof e=="object"?"{...}":String(e)}function IN(e){for(const t of Zd){const n=e[t];if(typeof n=="string"&&n.length>0)return n}for(const t of Object.values(e))if(!(!t||typeof t!="object"||Array.isArray(t)))for(const n of Zd){const i=t[n];if(typeof i=="string"&&i.length>0)return i}return null}function Y0(e){const t=Gm(e);if(!t||typeof t!="object"||Array.isArray(t))return null;const n=IN(t);return n?n.slice(0,qa):V0(t)}function Ym(e){if(!e)return"";if(typeof e=="string")return e.slice(0,qa);const t=e;for(const i of Zd){const o=t[i];if(o)return typeof o=="string"?o.slice(0,qa):JSON.stringify(o).slice(0,qa)}for(const i of Object.values(t))if(!(!i||typeof i!="object"||Array.isArray(i)))for(const o of Zd){const d=i[o];if(typeof d=="string"&&d.length>0)return d.slice(0,qa)}return V0(t)??""}const MN=new Set(["AskUserQuestion"]);function Z0(e){return!!e&&MN.has(e)}const DN={read:{icon:"file-text",colorToken:"accent-cyan"},edit:{icon:"pencil",colorToken:"accent-orange"},write:{icon:"file-plus",colorToken:"accent-green"},exec:{icon:"terminal",colorToken:"accent-purple"},search:{icon:"search",colorToken:"accent-cyan"},web:{icon:"world",colorToken:"accent-cyan"},task:{icon:"subtask",colorToken:"accent-purple"},todo:{icon:"checklist",colorToken:"accent-green"},question:{icon:"help",colorToken:"accent-orange"},other:{icon:"tool",colorToken:"text-muted"}},LN={read:"read",readfile:"read",notebookread:"read",ls:"read",cat:"read",edit:"edit",multiedit:"edit",notebookedit:"edit",applypatch:"edit",update:"edit",write:"write",writefile:"write",createfile:"write",bash:"exec",bashoutput:"exec",shell:"exec",execute:"exec",killbash:"exec",killshell:"exec",grep:"search",glob:"search",search:"search",find:"search",websearch:"web",webfetch:"web",fetch:"web",task:"task",agent:"task",todowrite:"todo",todoread:"todo",askuserquestion:"question"},ON="mcp__";function PN(e){if(!e||e.startsWith(ON))return"other";const t=e.toLowerCase().replace(/[_-]/g,"");return LN[t]??"other"}function BN(e,t){const n=PN(e),i=DN[n];return{kind:n,icon:i.icon,colorToken:i.colorToken,label:fa(e??"",t)}}const $N={stream_stall:{kind:"stall",role:"status",headline:"Stream stalled — retry?"},resume_unknown:{kind:"resume",role:"status",headline:"Previous conversation could not be resumed — starting fresh"},resume_unknown_exhausted:{kind:"resume",role:"alert",headline:"Auto-recovery exhausted — start a new session manually to continue"}},zN={kind:"question",role:"status",headline:"Question delivery failed — retry?"},Qb={kind:"generic",role:"alert",headline:"Something went wrong"};function Zm(e){return e?Vm(e)?zN:$N[e]??Qb:Qb}const UN=16,Jb=12,qN=1500,HN=20;function FN(e){if(!e)return!1;if(e.length>=qN)return!0;let t=1;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)===10&&t++,t>=HN)return!0;return!1}function KN(e,t){let n=1;for(let i=0;i<t.length;i++)t.charCodeAt(i)===10&&n++;return n>1?`[Pasted text #${e} +${n} lines]`:`[Pasted text #${e} +${t.length} chars]`}const X0=/\[Pasted text #(\d+) \+(\d+) (lines|chars)\]/g;function WN(e,t){const n=t instanceof Map?i=>t.get(i):i=>t[i];return e.replace(X0,(i,o)=>{const d=Number.parseInt(o,10),h=n(d);return h??i})}function GN(e){const t=new Set,n=new RegExp(X0.source,"g");let i;for(;(i=n.exec(e))!=null;){const o=Number.parseInt(i[1],10);Number.isFinite(o)&&t.add(o)}return t}const Xd={"claude-sdk":{short:"SDK",label:"Claude Code (SDK)",tooltip:"Anthropic API — billed per token via ANTHROPIC_API_KEY",type:"sdk"},"claude-cli":{short:"CLI",label:"Claude Code (CLI)",tooltip:"Claude Code CLI — uses your claude.ai subscription",type:"cli"},"claude-tui":{short:"TUI",label:"Claude Code (TUI)",tooltip:"Interactive Claude Code TUI under PTY — uses your claude.ai subscription, bypasses programmatic credit metering",type:"cli"},"claude-byok":{short:"BYOK",label:"Claude (API key — BYOK)",tooltip:"Direct Anthropic API via @anthropic-ai/sdk — per-token billing with your own ANTHROPIC_API_KEY. No claude binary required.",type:"sdk"},"docker-byok":{short:"Docker BYOK",label:"Claude (BYOK — Docker container)",tooltip:"BYOK agent loop on the host, tool execution (Read/Write/Edit/Bash/Glob/Grep) inside an isolated Docker container. Per-token billing with your own ANTHROPIC_API_KEY.",type:"sdk"},"docker-cli":{short:"Docker CLI",label:"Claude Code (Docker CLI)",tooltip:"Docker-isolated CLI — forwards your ANTHROPIC_API_KEY into the container (per-token billing, no OAuth fallback)",type:"cli"},"docker-sdk":{short:"Docker SDK",label:"Claude Code (Docker SDK)",tooltip:"Docker-isolated SDK — billed per token via ANTHROPIC_API_KEY",type:"sdk"},docker:{short:"Docker CLI",label:"Claude Code (Docker CLI)",tooltip:"Docker-isolated CLI — forwards your ANTHROPIC_API_KEY into the container (alias for docker-cli)",type:"cli"},gemini:{short:"Gemini",label:"Gemini (CLI)",tooltip:"Gemini CLI — uses Google API credits",type:"other"},codex:{short:"Codex",label:"Codex (CLI)",tooltip:"Codex CLI — uses OpenAI API credits",type:"other"}},VN={short:"API",tooltip:"External provider — check your billing dashboard",type:"other"},hm=Object.fromEntries(Object.entries(Xd).map(([e,t])=>[e,t.label]));function YN(e){return Xd[e]?.label??e}function Vi(e){if(Xd[e])return Xd[e];if(e.includes("sdk"))return{short:"SDK",label:e.replace(/^claude-/,""),tooltip:"SDK provider — billed per token",type:"sdk"};const t=e.replace(/^claude-/,"").toUpperCase();return{...VN,label:t,short:t}}function ZN(e){return e?Vi(e).type!=="cli":!1}function XN(e,t){return e?e==="claude-tui"?t?.multiSelectReinject===!0:Vi(e).type!=="cli":!1}const QN=["UTC","America/Los_Angeles","America/Denver","America/Chicago","America/New_York","America/Sao_Paulo","Europe/London","Europe/Berlin","Europe/Paris","Europe/Moscow","Asia/Dubai","Asia/Kolkata","Asia/Shanghai","Asia/Tokyo","Asia/Singapore","Australia/Sydney","Pacific/Auckland"];function JN(e){const t=[...QN];return e&&!t.includes(e)&&t.unshift(e),t}function Vs(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function ht(e,t){const n=e[t];return typeof n=="string"?n:null}function ms(e,t){const n=e[t];return Array.isArray(n)?n:[]}function e_(e,t,n=0){const i=e[t];return typeof i=="number"&&Number.isFinite(i)?i:n}function Q0(e,t,n){const i=e[t];return typeof i=="string"&&n.includes(i)?i:null}function on(e,t){return Vs(e,"sessionId")||t}function ej(e,t){const n=e.sessionId,i=e.name;return!n||!i?null:t.map(o=>o.sessionId===n?{...o,name:i}:o)}function tj(e){return`This device is paired to session "${e}" and can only talk to that session. Disconnect and scan a fresh QR code to create new sessions.`}function nj(e,t){const n=ht(e,"category"),i=ht(e,"code"),o=typeof e.boundSessionName=="string"&&e.boundSessionName.length>0?e.boundSessionName:null,d=Vs(e,"attemptedSessionId");if(n==="crash")return{category:n,code:i,boundSessionName:o,message:null,sessionPatch:{sessionId:on(e,t),patch:{health:"crashed"}},attemptedSessionId:d};let h;return i==="SESSION_TOKEN_MISMATCH"&&o?h=tj(o):h=Vs(e,"message")??"Unknown error",{category:n,code:i,boundSessionName:o,message:h,sessionPatch:null,attemptedSessionId:d}}function sj(e,t,n=Date.now){const i=typeof e.code=="number"&&Number.isInteger(e.code)?e.code:null;return{sessionId:on(e,t),patch:{stoppedAt:n(),stoppedCode:i}}}const ij=new Set(["debug","info","warn","error","audit"]);function rj(e){const t=typeof e.component=="string"?e.component:"unknown",n=ij.has(e.level)?e.level:"info",i=typeof e.message=="string"?Fc(e.message):"",o=typeof e.timestamp=="number"?e.timestamp:Date.now(),d=typeof e.sessionId=="string"?e.sessionId:void 0;return{entry:{id:fn("log"),component:t,level:n,message:i,timestamp:o,...d!==void 0?{sessionId:d}:{}}}}function aj(e){const t=typeof e.message=="string"?e.message:"Approaching cost budget limit";return{warningMessage:t,systemMessage:{id:fn("system"),type:"system",content:t,timestamp:Date.now()}}}function oj(e){const t=typeof e.message=="string"?e.message:"Cost budget exceeded";return{exceededMessage:t,systemMessage:{id:fn("system"),type:"system",content:`${t} — session paused`,timestamp:Date.now()}}}function lj(){return{systemMessage:{id:fn("system"),type:"system",content:"Cost budget override — session resumed",timestamp:Date.now()}}}function cj(e){return e.wasPaused===!0?{systemMessage:null}:{systemMessage:{id:fn("system"),type:"system",content:"Budget was not paused — nothing to resume",timestamp:Date.now()}}}function uj(e,t){return{sessionId:on(e,t),patch:{isPlanPending:!1,planAllowedPrompts:[]}}}function dj(e,t){const n=ms(e,"allowedPrompts");return{sessionId:on(e,t),patch:{isPlanPending:!0,planAllowedPrompts:n}}}const fj=1440*60*1e3;function hj(e,t){const n=e.idleMs,i=e.prefab;if(typeof n!="number"||!Number.isFinite(n))return null;const o=Math.floor(n);return o<=0||o>fj||typeof i!="string"||!i.trim()?null:{sessionId:on(e,t),patch:{inactivityWarning:{idleMs:o,prefab:i,receivedAt:Date.now()}}}}function pj(e,t){const n=e.toolUseId;if(typeof n!="string"||n.length===0)return null;const i=e.questionCount;if(typeof i!="number"||!Number.isFinite(i))return null;const o=Math.floor(i);if(o<2)return null;const d=e.timestamp,h=typeof d=="number"&&Number.isFinite(d)&&d>=0?Math.floor(d):Date.now();return{sessionId:on(e,t),isFirst:!1,applyTo:l=>{if(l.some(S=>S.toolUseId===n))return{interventions:l};const f={kind:"multi_question",toolUseId:n,count:o,timestamp:h},v=[...l,f];return{interventions:v.length>Yb?v.slice(-Yb):v}}}}function mj(e,t){const n=t.length===0,i=e.applyTo(t),o=i.interventions.length>t.length;return{interventions:i.interventions,isFirst:n&&o}}function J0(e,t){const n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function ex(e,t){const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Bd(e,t){if(typeof t!="number"||!Number.isFinite(t))return e;const n=Math.max(0,Math.floor(t)),i=e.reduce((d,h)=>h.status==="confirmed"?d+1:d,0);if(i<=n)return e;let o=i-n;return e.filter(d=>o>0&&d.status==="confirmed"?(o--,!1):!0)}function gj(e,t){return t.clientMessageId&&e.some(n=>n.clientMessageId===t.clientMessageId)?e:[...e,{clientMessageId:t.clientMessageId,text:t.text,queuedAt:t.queuedAt,status:"pending"}]}function tx(e,t){if(e.length===0)return e;if(t===void 0)return e.slice(1);const n=e.findIndex(i=>i.clientMessageId===t);return n===-1?e:[...e.slice(0,n),...e.slice(n+1)]}function vj(e,t){const n=e.text;if(typeof n!="string")return null;const i=J0(e,"clientMessageId"),o=ex(e,"queueLength");return{sessionId:on(e,t),reconcileFakedFreshTurn:({streamingMessageId:d,messages:h,pendingClientMessageId:l})=>{if(d!=="pending"||!i||i!==l)return null;const u={streamingMessageId:null,pendingClientMessageId:null},f=h.filter(v=>v.id!=="thinking");return f.length!==h.length&&(u.messages=f),u},applyTo:d=>{if(i){const l=d.findIndex(f=>f.clientMessageId===i),u=l===-1?void 0:d[l];if(u){if(u.status==="confirmed"&&u.text===n)return{queuedMessages:Bd(d,o)};const f=d.slice();return f[l]={...u,text:n,status:"confirmed"},{queuedMessages:Bd(f,o)}}}const h={clientMessageId:i,text:n,queuedAt:Date.now(),status:"confirmed"};return{queuedMessages:Bd([...d,h],o)}}}}function yj(e,t){const n=J0(e,"clientMessageId"),i=ex(e,"queueLength");return{sessionId:on(e,t),applyTo:o=>({queuedMessages:Bd(tx(o,n),i)})}}function bj(e,t){const n={port:e.port,url:e.url};return{sessionId:on(e,t),applyTo:i=>({devPreviews:[...i.filter(o=>o.port!==n.port),n]})}}function _j(e,t){const n=e.port;return{sessionId:on(e,t),applyTo:i=>({devPreviews:i.filter(o=>o.port!==n)})}}function Sj(e){const t=ht(e,"requestId"),n=ht(e,"tool"),i=ht(e,"description"),o=e.input&&typeof e.input=="object"&&!Array.isArray(e.input)?e.input:null,d=ht(e,"sessionId"),h=typeof e.remainingMs=="number"?e.remainingMs:null;return{requestId:t,tool:n,description:i,input:o,sessionId:d,remainingMs:h}}function xj(e){return{requestId:ht(e,"requestId"),decision:ht(e,"decision")}}function wj(e){return{requestId:ht(e,"requestId"),systemMessage:{id:fn("system"),type:"system",content:"(Expired — this permission was already handled or timed out)",timestamp:Date.now()}}}function kj(e){const t=ht(e,"requestId"),n=typeof e.tool=="string"?e.tool:"permission";return{requestId:t,tool:n,systemMessage:{id:fn("system"),type:"system",content:`Permission for "${n}" was auto-denied (timed out)`,timestamp:Date.now()}}}function Cj(e){const t=ht(e,"sessionId"),n=ms(e,"rules");return{sessionId:t,rules:n}}function Ej(e){return{mode:Vs(e,"mode")}}function nx(e){return Array.isArray(e.modes)?e.modes.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.label=="string").map(t=>{const n={id:t.id,label:t.label};return typeof t.description=="string"&&(n.description=t.description),n}):null}function Nj(e){const t=ht(e,"mode");if(!t)return null;const n=typeof e.warning=="string"?e.warning:"Are you sure?";return{mode:t,warning:n}}const sx=["cli"],jj={available:!1,remote:!1,teleport:!1};function t_(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Aj(e){const t=e.protocolVersion,n=typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=1?t:null,i=e.webFeatures,o=i&&typeof i=="object"&&!Array.isArray(i)?{available:!!i.available,remote:!!i.remote,teleport:!!i.teleport}:{...jj},d=e.capabilities,h={};if(d&&typeof d=="object"&&!Array.isArray(d))for(const[l,u]of Object.entries(d))l==="__proto__"||l==="constructor"||l==="prototype"||(h[l]=u===!0);return{serverMode:Q0(e,"serverMode",sx),sessionCwd:ht(e,"cwd"),defaultCwd:ht(e,"defaultCwd"),serverVersion:ht(e,"serverVersion"),latestVersion:ht(e,"latestVersion"),serverCommit:ht(e,"serverCommit"),protocolVersion:n,resultTimeoutMs:t_(e.resultTimeoutMs),streamStallTimeoutMs:t_(e.streamStallTimeoutMs),encryption:ht(e,"encryption"),sessionToken:ht(e,"sessionToken"),myClientId:ht(e,"clientId"),webFeatures:o,serverCapabilities:h,serverPublicKey:typeof e.serverPublicKey=="string"&&e.serverPublicKey?e.serverPublicKey:null,serverKeySig:typeof e.serverKeySig=="string"&&e.serverKeySig?e.serverKeySig:null,newIdentityKey:typeof e.newIdentityKey=="string"&&e.newIdentityKey?e.newIdentityKey:null,rotationCert:typeof e.rotationCert=="string"&&e.rotationCert?e.rotationCert:null,availablePermissionModes:Array.isArray(e.availablePermissionModes)?nx({modes:e.availablePermissionModes}):null}}function Rj(e){const t=e.reason;return{reason:typeof t=="string"&&t?t:"Invalid token"}}function Tj(e){const t=e.publicKey,n=e.serverKeySig;return{publicKey:typeof t=="string"&&t?t:null,serverKeySig:typeof n=="string"&&n?n:null,newIdentityKey:typeof e.newIdentityKey=="string"&&e.newIdentityKey?e.newIdentityKey:null,rotationCert:typeof e.rotationCert=="string"&&e.rotationCert?e.rotationCert:null}}function Ij(e){return{mode:Q0(e,"mode",sx)}}function Mj(e){const t=ms(e,"providers"),n=ms(e,"slashCommands"),i=ms(e,"agents"),o=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:null,d=pm(e.tunnelUrl);return{providers:t,slashCommands:n,agents:i,sessionId:o,tunnelUrl:d}}function pm(e){return typeof e=="string"&&/^wss:\/\//i.test(e)?e:null}function Dj(e){const t=pm(e.url);if(!t)return null;const n=pm(e.previousUrl);return{url:t,previousUrl:n}}function Lj(e){return{token:ht(e,"token")}}const Oj={expired:"This QR code has expired. Scan the latest QR code from your server.",already_used:"This QR code has already been used. Scan the latest QR code from your server.",invalid_pairing_id:"Invalid pairing code. Scan the latest QR code from your server.",rate_limited:"Too many attempts. Please wait a moment and try again."};function Pj(e,t){const n=typeof e.reason=="string"&&e.reason.length>0?e.reason:t;return{reason:n,alertMessage:Oj[n]??`Pairing failed: ${n}`}}function Bj(e,t,n){const i=on(e,n);if(!i||i!==n)return null;const o=e.checkpoint;return!o||typeof o!="object"?null:[...t,o]}function $j(e,t){const n=on(e,t);return!n||n!==t||!Array.isArray(e.checkpoints)?null:e.checkpoints}function zj(e){const t=e.newSessionId;if(typeof t!="string")return null;const n=t.trim();return n.length===0?null:{newSessionId:n}}const Uj="An unexpected server error occurred";function qj(e){const t=typeof e.code=="string"?e.code:"UNKNOWN",n=typeof e.message=="string"?Fc(e.message).trim():"",i=n.length>0?n:Uj,o=ht(e,"requestId"),d=typeof e.fatal=="boolean"?e.fatal:void 0,h=e.cost,l=typeof h=="number"&&Number.isFinite(h)&&h>=0?{costUsd:h,inputTokens:wd(e.usage,"input_tokens"),outputTokens:wd(e.usage,"output_tokens"),cacheReadTokens:wd(e.usage,"cache_read_input_tokens"),cacheCreationTokens:wd(e.usage,"cache_creation_input_tokens")}:null;return{code:t,message:i,requestId:o,fatal:d,partialCost:l}}function wd(e,t){if(e==null||typeof e!="object")return 0;const n=e[t];return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:0}const Hj=["tunnel","session","permission","general"];function Fj(e){const t=typeof e.category=="string"&&Hj.includes(e.category)?e.category:"general",n=typeof e.message=="string"&&e.message.trim().length>0?Fc(e.message):"Unknown server error",i=typeof e.recoverable=="boolean"?e.recoverable:!0,o=typeof e.sessionId=="string"?e.sessionId:void 0,d=Date.now(),h={id:fn("err"),category:t,message:n,recoverable:i,timestamp:d,...o?{sessionId:o}:{}},l={id:fn("err"),type:"error",content:n,timestamp:d};return{serverError:h,chatMessage:l}}function Kj(e){const t=e.reason==="restart"||e.reason==="shutdown"||e.reason==="crash"?e.reason:"shutdown",n=typeof e.restartEtaMs=="number"?e.restartEtaMs:0;return{shutdownReason:t,restartEtaMs:n,restartingSince:Date.now()}}function Wj(e){const t=typeof e.message=="string"&&e.message.trim().length>0?Fc(e.message):"Status update";return{chatMessage:{id:fn("status"),type:"system",content:t,timestamp:Date.now()}}}function Gj(e){const t=typeof e.message=="string"&&e.message.trim().length>0?e.message:"Rate limited. Please slow down.",n=typeof e.retryAfterMs=="number"?e.retryAfterMs:0,i=n>0?`${t} Retry in ${Math.max(1,Math.ceil(n/1e3))}s.`:t;return{chatMessage:{id:fn("rate-limit"),type:"system",content:i,timestamp:Date.now()}}}const ix=new Set(["phone","tablet","desktop","unknown"]);function Vj(e,t){const n=e.client;if(!n||typeof n!="object")return null;const i=n;if(typeof i.clientId!="string")return null;const o=ix.has(i.deviceType)?i.deviceType:"unknown",d={clientId:i.clientId,deviceName:typeof i.deviceName=="string"?i.deviceName:null,deviceType:o,platform:typeof i.platform=="string"?i.platform:"unknown",isSelf:!1},h=[...t.filter(l=>l.clientId!==d.clientId),d];return{client:d,roster:h}}function Yj(e,t){if(typeof e.clientId!="string")return null;const n=e.clientId,i=t.find(d=>d.clientId===n),o=t.filter(d=>d.clientId!==n);return{clientId:n,departingClient:i,roster:o}}function Zj(e){return{sessionId:ht(e,"sessionId"),primaryClientId:ht(e,"clientId")}}function Xj(e,t){const n=ht(e,"sessionId"),i=ht(e,"primaryClientId");let o;return i?t&&i===t?o="primary":o="observer":o="unclaimed",{sessionId:n,primaryClientId:i,role:o}}function Qj(e,t){return Array.isArray(e)?e.filter(n=>!!n&&typeof n=="object"&&typeof n.clientId=="string").map(n=>{const i=n,o=ix.has(i.deviceType)?i.deviceType:"unknown";return{clientId:n.clientId,deviceName:typeof i.deviceName=="string"?i.deviceName:null,deviceType:o,platform:typeof i.platform=="string"?i.platform:"unknown",isSelf:n.clientId===t}}):[]}function Jj(e){return Array.isArray(e.sessions)?e.sessions:null}const Rc=20;function eA(e,t){return!e||!t?!1:e.inputTokens===t.inputTokens&&e.outputTokens===t.outputTokens&&e.cacheReadTokens===t.cacheReadTokens&&e.cacheCreationTokens===t.cacheCreationTokens&&e.costUsd===t.costUsd&&e.turnsBilled===t.turnsBilled}function tA(e,t,n,i=Rc){const o=Jj(e);if(!o)return null;const d=new Set;for(const w of o)w&&typeof w.sessionId=="string"&&d.add(w.sessionId);const h=new Set(t),l=[];for(const w of t)d.has(w)||l.push(w);const u=[],f=new Map,v=new Map,g=new Map;for(const w of o){if(!w||typeof w.sessionId!="string")continue;const E=w.sessionId;h.has(E)||u.push(E),w.conversationId&&f.set(E,w.conversationId),w.cumulativeUsage&&v.set(E,w.cumulativeUsage),g.set(E,rx({sessionId:E,pending:w.pendingBackgroundShells??[]},n))}const S=nA(o,n,i);return{sessionList:o,removedIds:l,newSessionIds:u,conversationIdPatches:f,cumulativeUsagePatches:v,backgroundShellBuilders:g,subscribeChunks:S}}function nA(e,t,n=Rc){const i=typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):Rc,o=i>=1?i:Rc,d=Math.min(o,Rc),h=[];for(const u of e)!u||typeof u.sessionId!="string"||u.sessionId!==t&&h.push(u.sessionId);const l=[];for(let u=0;u<h.length;u+=d)l.push(h.slice(u,u+d));return l}function rx(e,t){const n=ms(e,"pending"),i=[];for(const o of n){if(!o||typeof o!="object")continue;const d=o,h=typeof d.shellId=="string"?d.shellId:null;if(!h)continue;const l=typeof d.command=="string"?d.command:"",u=typeof d.startedAt=="number"&&d.startedAt>=0?d.startedAt:Date.now();i.push({shellId:h,command:l,startedAt:u})}return{sessionId:on(e,t),applyTo:o=>{if(i.length===o.length){let d=!0;for(let h=0;h<i.length;h++){const l=i[h],u=o[h];if(!l||!u){d=!1;break}if(l.shellId!==u.shellId||l.startedAt!==u.startedAt||l.command!==u.command){d=!1;break}}if(d)return o}return i}}}function sA(e,t){return{sessionId:on(e,t),patch:{sessionContext:{gitBranch:ht(e,"gitBranch"),gitDirty:typeof e.gitDirty=="number"?e.gitDirty:0,gitAhead:typeof e.gitAhead=="number"?e.gitAhead:0,projectName:ht(e,"projectName")}}}}function iA(e){const t=Vs(e,"sessionId"),n=Vs(e,"name")??"Unknown";return{sessionId:t,name:n,systemMessage:{id:fn("system"),type:"system",content:`Session "${n}" was closed due to inactivity.`,timestamp:Date.now()}}}function rA(e){const t=ht(e,"sessionId"),n=ht(e,"name"),i=ht(e,"provider"),o=ht(e,"cwd"),d=ht(e,"model"),h=ht(e,"permissionMode"),l=ht(e,"errorCode"),u=ht(e,"errorMessage"),f=typeof e.historyLength=="number"?e.historyLength:null,v=n??t??"session",g=u??l??"unknown error";return{sessionId:t,name:n,provider:i,cwd:o,model:d,permissionMode:h,errorCode:l,errorMessage:u,historyLength:f,systemMessage:{id:fn("system"),type:"system",content:`Failed to restore ${v}: ${g}`,timestamp:Date.now()}}}function aA(e){const t=ht(e,"sessionId"),n=ht(e,"name"),i=n?`"${n}"`:t?`session ${t}`:"your session change";return{sessionId:t,name:n,message:`Couldn't save ${i} — the change may be lost on restart. Check the daemon's disk space and write permissions.`}}function oA(e){const t=Vs(e,"sessionId"),n=Vs(e,"name")??"Session",i=typeof e.remainingMs=="number"?e.remainingMs:12e4,o=Vs(e,"message")??"Session will timeout soon";return{sessionId:t,sessionName:n,remainingMs:i,message:o,systemMessage:{id:fn("warn"),type:"system",content:o,timestamp:Date.now()}}}function lA(e){const t=Vs(e,"sessionId");if(t===null)return null;const n=Vs(e,"conversationId");return{newSessionId:t,conversationId:n}}function cA(e){const t=ht(e,"clientId"),n=ht(e,"sessionId");return!t||!n?null:{clientId:t,sessionId:n}}function uA(e){return{sessionId:ht(e,"sessionId"),conversationId:ht(e,"conversationId")}}function dA(e){return{conversations:ms(e,"conversations")}}function fA(e,t){const n=ht(e,"sessionId");return{receivingHistoryReplay:!0,fullHistory:e.fullHistory===!0,sessionId:n||t,latestSeq:typeof e.latestSeq=="number"&&Number.isFinite(e.latestSeq)?e.latestSeq:null}}function ax(e){return{path:ht(e,"path"),parentPath:ht(e,"parentPath"),entries:ms(e,"entries"),error:ht(e,"error")}}function ox(e){return ax(e)}function lx(e){return ax(e)}function cx(e){return{path:ht(e,"path"),content:ht(e,"content"),language:ht(e,"language"),size:typeof e.size=="number"?e.size:null,truncated:e.truncated===!0,error:ht(e,"error"),requestId:ht(e,"requestId")}}function hA(e){return{path:ht(e,"path"),error:ht(e,"error")}}const pA=new Set(["modified","added","deleted","renamed","copied","unknown"]),mA=new Set(["modified","added","deleted","renamed","untracked"]),gA=new Set(["context","addition","deletion"]);function n_(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.path=="string"&&typeof t.status=="string"&&pA.has(t.status)}function vA(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.name=="string"&&typeof t.isCurrent=="boolean"&&typeof t.isRemote=="boolean"}function yA(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.type=="string"&&gA.has(t.type)&&typeof t.content=="string"}function bA(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.header!="string"||!Array.isArray(t.lines))return!1;for(const n of t.lines)if(!yA(n))return!1;return!0}function _A(e){if(typeof e!="object"||e===null)return!1;const t=e;if(typeof t.path!="string"||typeof t.status!="string"||!mA.has(t.status)||typeof t.additions!="number"||typeof t.deletions!="number"||!Array.isArray(t.hunks))return!1;for(const n of t.hunks)if(!bA(n))return!1;return!0}function Dc(e,t,n){const i=[];let o=0;for(let d=0;d<e.length;d++){const h=e[d];t(h)?i.push(h):o++}return o>0&&console.debug(`[${n}] dropped ${o}/${e.length} malformed elements`),i}function ux(e){const t=ms(e,"files");return{files:Dc(t,_A,"handleDiffResult.files"),error:ht(e,"error")}}function dx(e){const t=ms(e,"staged"),n=ms(e,"unstaged"),i=ms(e,"untracked");return{branch:ht(e,"branch"),staged:Dc(t,n_,"handleGitStatusResult.staged"),unstaged:Dc(n,n_,"handleGitStatusResult.unstaged"),untracked:Dc(i,o=>typeof o=="string","handleGitStatusResult.untracked"),error:ht(e,"error")}}function SA(e){const t=ms(e,"branches");return{branches:Dc(t,vA,"handleGitBranchesResult.branches"),currentBranch:ht(e,"currentBranch"),error:ht(e,"error")}}function s_(e){return{error:ht(e,"error")}}function xA(e){return{hash:ht(e,"hash"),message:ht(e,"message"),error:ht(e,"error")}}function wA(e,t){const n=ht(e,"toolUseId"),o=(typeof e.description=="string"?e.description:"")||"Background task",d=typeof e.startedAt=="number"?e.startedAt:0;return{sessionId:on(e,t),applyTo:h=>!n||h.some(l=>l.toolUseId===n)?h:[...h,{toolUseId:n,description:o,startedAt:d||Date.now()}]}}function kA(e,t){const n=ht(e,"toolUseId");return{sessionId:on(e,t),applyTo:i=>{if(!n)return i;const o=i.filter(d=>d.toolUseId!==n);return o.length===i.length?i:o}}}function CA(e,t){const n=ht(e,"parentToolUseId"),i=typeof e.eventType=="string"&&e.eventType?e.eventType:null,o=e.payload,d=o!==null&&typeof o=="object"&&!Array.isArray(o)?o:{};return{sessionId:on(e,t),applyTo:h=>{if(!n||!i)return h;let l=!1;const u=h.map(f=>{if(f.type!=="tool_use"||f.toolUseId!==n)return f;l=!0;const v=[...f.childAgentEvents||[],{type:i,payload:d}];return{...f,childAgentEvents:v}});return l?u:h}}}function EA(e){return{environments:ms(e,"environments")}}function NA(e){return{error:ht(e,"error")}}function jA(e,t){const n=typeof e.sessionCost=="number"?e.sessionCost:null;return{sessionId:ht(e,"sessionId")||t,patch:{sessionCost:n}}}function Ko(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function AA(e,t){const n=e.cumulativeUsage??{},i={inputTokens:Ko(n.inputTokens),outputTokens:Ko(n.outputTokens),cacheReadTokens:Ko(n.cacheReadTokens),cacheCreationTokens:Ko(n.cacheCreationTokens),costUsd:Ko(n.costUsd),turnsBilled:Ko(n.turnsBilled)};return{sessionId:ht(e,"sessionId")||t,patch:{cumulativeUsage:i}}}function RA(e){const t=e.task;if(!t||typeof t!="object")return{task:null};const n=t.taskId;return typeof n!="string"||n.length===0?{task:null}:{task:t}}function TA(e,t){return[...e.filter(i=>i.taskId!==t.taskId),t]}function IA(e){const t=typeof e.taskId=="string"&&e.taskId.length>0?e.taskId:null,n=typeof e.message=="string"&&e.message.length>0?e.message:null,i=n??"Unknown error",o=ht(e,"code"),d=typeof e.boundSessionName=="string"&&e.boundSessionName.length>0?e.boundSessionName:null;return{taskId:t,errorMessage:i,chatMessageContent:n??"Web task error",code:o,boundSessionName:d}}function MA(e){return{tasks:ms(e,"tasks")}}function DA(e){return{webFeatures:{available:!!e.available,remote:!!e.remote,teleport:!!e.teleport}}}function LA(e,t){const n=ms(e,"results"),i=ht(e,"query");return i!==null&&t&&i!==t?{results:n,shouldApply:!1}:{results:n,shouldApply:!0}}const mm="__chroxy_other__",xp="Other";function OA(e,t){const n=e.questions;if(!Array.isArray(n)||n.length===0)return null;const i=n[0];if(!i||typeof i!="object"||typeof i.question!="string")return null;const o=E=>{if(!E||typeof E!="object")return null;const x=E;if(typeof x.question!="string")return null;const m=Array.isArray(x.options)?x.options.filter(D=>!!D&&typeof D=="object"&&typeof D.label=="string").map(D=>({label:D.label,value:D.label})):[],y=m.filter(D=>D.label!==xp&&D.value!==mm),b=m.find(D=>D.label===xp),_=y.length>0||b!=null,k=x.multiSelect===!0,j=_?k?y:b?[...y,b]:[...y,{label:xp,value:mm}]:[],T={question:x.question,options:j};return k&&(T.multiSelect=!0),T},d=n.map(o).filter(E=>E!=null),[h]=d;if(h==null)return null;const l=h.question,u=h.options,f=typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)?e.timestamp:Date.now(),v={id:fn("question"),type:"prompt",content:l,options:u,questions:d,timestamp:f};typeof e.toolUseId=="string"&&(v.toolUseId=e.toolUseId);const S=(typeof e.sessionId=="string"&&e.sessionId.length>0?e.sessionId:null)??t,w=l.slice(0,60);return{sessionId:S,chatMessage:v,questionText:w}}function PA(e,t,n){const i=uE(e,t,n);if(!i)return null;const{sessionId:o,...d}=i,l={id:(typeof e.messageId=="string"?e.messageId:void 0)||fn("user_input"),...d};return{sessionId:o,chatMessage:l,content:i.content}}function Be(e,t,n){function i(l,u){if(l._zod||Object.defineProperty(l,"_zod",{value:{def:u,constr:h,traits:new Set},enumerable:!1}),l._zod.traits.has(e))return;l._zod.traits.add(e),t(l,u);const f=h.prototype,v=Object.keys(f);for(let g=0;g<v.length;g++){const S=v[g];S in l||(l[S]=f[S].bind(l))}}const o=n?.Parent??Object;class d extends o{}Object.defineProperty(d,"name",{value:e});function h(l){var u;const f=n?.Parent?new d:this;i(f,l),(u=f._zod).deferred??(u.deferred=[]);for(const v of f._zod.deferred)v();return f}return Object.defineProperty(h,"init",{value:i}),Object.defineProperty(h,Symbol.hasInstance,{value:l=>n?.Parent&&l instanceof n.Parent?!0:l?._zod?.traits?.has(e)}),Object.defineProperty(h,"name",{value:e}),h}class tl extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class fx extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const hx={};function ha(e){return hx}function px(e){const t=Object.values(e).filter(i=>typeof i=="number");return Object.entries(e).filter(([i,o])=>t.indexOf(+i)===-1).map(([i,o])=>o)}function gm(e,t){return typeof t=="bigint"?t.toString():t}function pf(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Xm(e){return e==null}function Qm(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function BA(e,t){const n=(e.toString().split(".")[1]||"").length,i=t.toString();let o=(i.split(".")[1]||"").length;if(o===0&&/\d?e-\d?/.test(i)){const u=i.match(/\d?e-(\d?)/);u?.[1]&&(o=Number.parseInt(u[1]))}const d=n>o?n:o,h=Number.parseInt(e.toFixed(d).replace(".","")),l=Number.parseInt(t.toFixed(d).replace(".",""));return h%l/10**d}const i_=Symbol("evaluating");function jn(e,t,n){let i;Object.defineProperty(e,t,{get(){if(i!==i_)return i===void 0&&(i=i_,i=n()),i},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Qa(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ga(...e){const t={};for(const n of e){const i=Object.getOwnPropertyDescriptors(n);Object.assign(t,i)}return Object.defineProperties({},t)}function r_(e){return JSON.stringify(e)}function $A(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const mx="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function $c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const zA=pf(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function ol(e){if($c(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!($c(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function gx(e){return ol(e)?{...e}:Array.isArray(e)?[...e]:e}const UA=new Set(["string","number","symbol"]);function ll(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function va(e,t,n){const i=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(i._zod.parent=e),i}function It(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function qA(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const HA={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function FA(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const d=ga(e._zod.def,{get shape(){const h={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(h[l]=n.shape[l])}return Qa(this,"shape",h),h},checks:[]});return va(e,d)}function KA(e,t){const n=e._zod.def,i=n.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const d=ga(e._zod.def,{get shape(){const h={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete h[l]}return Qa(this,"shape",h),h},checks:[]});return va(e,d)}function WA(e,t){if(!ol(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const d=e._zod.def.shape;for(const h in t)if(Object.getOwnPropertyDescriptor(d,h)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=ga(e._zod.def,{get shape(){const d={...e._zod.def.shape,...t};return Qa(this,"shape",d),d}});return va(e,o)}function GA(e,t){if(!ol(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ga(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Qa(this,"shape",i),i}});return va(e,n)}function VA(e,t){const n=ga(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t._zod.def.shape};return Qa(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return va(e,n)}function YA(e,t,n){const o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const h=ga(t._zod.def,{get shape(){const l=t._zod.def.shape,u={...l};if(n)for(const f in n){if(!(f in l))throw new Error(`Unrecognized key: "${f}"`);n[f]&&(u[f]=e?new e({type:"optional",innerType:l[f]}):l[f])}else for(const f in l)u[f]=e?new e({type:"optional",innerType:l[f]}):l[f];return Qa(this,"shape",u),u},checks:[]});return va(t,h)}function ZA(e,t,n){const i=ga(t._zod.def,{get shape(){const o=t._zod.def.shape,d={...o};if(n)for(const h in n){if(!(h in d))throw new Error(`Unrecognized key: "${h}"`);n[h]&&(d[h]=new e({type:"nonoptional",innerType:o[h]}))}else for(const h in o)d[h]=new e({type:"nonoptional",innerType:o[h]});return Qa(this,"shape",d),d}});return va(t,i)}function Yo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Zo(e,t){return t.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(e),n})}function kd(e){return typeof e=="string"?e:e?.message}function pa(e,t,n){const i={...e,path:e.path??[]};if(!e.message){const o=kd(e.inst?._zod.def?.error?.(e))??kd(t?.error?.(e))??kd(n.customError?.(e))??kd(n.localeError?.(e))??"Invalid input";i.message=o}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Jm(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function zc(...e){const[t,n,i]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:i}:{...t}}const vx=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,gm,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},yx=Be("$ZodError",vx),bx=Be("$ZodError",vx,{Parent:Error});function XA(e,t=n=>n.message){const n={},i=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):i.push(t(o));return{formErrors:i,fieldErrors:n}}function QA(e,t=n=>n.message){const n={_errors:[]},i=o=>{for(const d of o.issues)if(d.code==="invalid_union"&&d.errors.length)d.errors.map(h=>i({issues:h}));else if(d.code==="invalid_key")i({issues:d.issues});else if(d.code==="invalid_element")i({issues:d.issues});else if(d.path.length===0)n._errors.push(t(d));else{let h=n,l=0;for(;l<d.path.length;){const u=d.path[l];l===d.path.length-1?(h[u]=h[u]||{_errors:[]},h[u]._errors.push(t(d))):h[u]=h[u]||{_errors:[]},h=h[u],l++}}};return i(e),n}const eg=e=>(t,n,i,o)=>{const d=i?Object.assign(i,{async:!1}):{async:!1},h=t._zod.run({value:n,issues:[]},d);if(h instanceof Promise)throw new tl;if(h.issues.length){const l=new(o?.Err??e)(h.issues.map(u=>pa(u,d,ha())));throw mx(l,o?.callee),l}return h.value},tg=e=>async(t,n,i,o)=>{const d=i?Object.assign(i,{async:!0}):{async:!0};let h=t._zod.run({value:n,issues:[]},d);if(h instanceof Promise&&(h=await h),h.issues.length){const l=new(o?.Err??e)(h.issues.map(u=>pa(u,d,ha())));throw mx(l,o?.callee),l}return h.value},mf=e=>(t,n,i)=>{const o=i?{...i,async:!1}:{async:!1},d=t._zod.run({value:n,issues:[]},o);if(d instanceof Promise)throw new tl;return d.issues.length?{success:!1,error:new(e??yx)(d.issues.map(h=>pa(h,o,ha())))}:{success:!0,data:d.value}},JA=mf(bx),gf=e=>async(t,n,i)=>{const o=i?Object.assign(i,{async:!0}):{async:!0};let d=t._zod.run({value:n,issues:[]},o);return d instanceof Promise&&(d=await d),d.issues.length?{success:!1,error:new e(d.issues.map(h=>pa(h,o,ha())))}:{success:!0,data:d.value}},eR=gf(bx),tR=e=>(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return eg(e)(t,n,o)},nR=e=>(t,n,i)=>eg(e)(t,n,i),sR=e=>async(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return tg(e)(t,n,o)},iR=e=>async(t,n,i)=>tg(e)(t,n,i),rR=e=>(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return mf(e)(t,n,o)},aR=e=>(t,n,i)=>mf(e)(t,n,i),oR=e=>async(t,n,i)=>{const o=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return gf(e)(t,n,o)},lR=e=>async(t,n,i)=>gf(e)(t,n,i),cR=/^[cC][^\s-]{8,}$/,uR=/^[0-9a-z]+$/,dR=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,fR=/^[0-9a-vA-V]{20}$/,hR=/^[A-Za-z0-9]{27}$/,pR=/^[a-zA-Z0-9_-]{21}$/,mR=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,gR=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,a_=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,vR=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,yR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function bR(){return new RegExp(yR,"u")}const _R=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,SR=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,xR=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,wR=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kR=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_x=/^[A-Za-z0-9_-]*$/,CR=/^\+[1-9]\d{6,14}$/,Sx="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ER=new RegExp(`^${Sx}$`);function xx(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function NR(e){return new RegExp(`^${xx(e)}$`)}function jR(e){const t=xx({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${n.join("|")})`;return new RegExp(`^${Sx}T(?:${i})$`)}const AR=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},RR=/^-?\d+$/,wx=/^-?\d+(?:\.\d+)?$/,TR=/^(?:true|false)$/i,IR=/^null$/i,MR=/^[^A-Z]*$/,DR=/^[^a-z]*$/,Ys=Be("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),kx={number:"number",bigint:"bigint",object:"date"},Cx=Be("$ZodCheckLessThan",(e,t)=>{Ys.init(e,t);const n=kx[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,d=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<d&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ex=Be("$ZodCheckGreaterThan",(e,t)=>{Ys.init(e,t);const n=kx[typeof t.value];e._zod.onattach.push(i=>{const o=i._zod.bag,d=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>d&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:i.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),LR=Be("$ZodCheckMultipleOf",(e,t)=>{Ys.init(e,t),e._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):BA(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),OR=Be("$ZodCheckNumberFormat",(e,t)=>{Ys.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),i=n?"int":"number",[o,d]=HA[t.format];e._zod.onattach.push(h=>{const l=h._zod.bag;l.format=t.format,l.minimum=o,l.maximum=d,n&&(l.pattern=RR)}),e._zod.check=h=>{const l=h.value;if(n){if(!Number.isInteger(l)){h.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:l,inst:e});return}if(!Number.isSafeInteger(l)){l>0?h.issues.push({input:l,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort}):h.issues.push({input:l,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:i,inclusive:!0,continue:!t.abort});return}}l<o&&h.issues.push({origin:"number",input:l,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),l>d&&h.issues.push({origin:"number",input:l,code:"too_big",maximum:d,inclusive:!0,inst:e,continue:!t.abort})}}),PR=Be("$ZodCheckMaxLength",(e,t)=>{var n;Ys.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!Xm(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(i._zod.bag.maximum=t.maximum)}),e._zod.check=i=>{const o=i.value;if(o.length<=t.maximum)return;const h=Jm(o);i.issues.push({origin:h,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),BR=Be("$ZodCheckMinLength",(e,t)=>{var n;Ys.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!Xm(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(i._zod.bag.minimum=t.minimum)}),e._zod.check=i=>{const o=i.value;if(o.length>=t.minimum)return;const h=Jm(o);i.issues.push({origin:h,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),$R=Be("$ZodCheckLengthEquals",(e,t)=>{var n;Ys.init(e,t),(n=e._zod.def).when??(n.when=i=>{const o=i.value;return!Xm(o)&&o.length!==void 0}),e._zod.onattach.push(i=>{const o=i._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=i=>{const o=i.value,d=o.length;if(d===t.length)return;const h=Jm(o),l=d>t.length;i.issues.push({origin:h,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:e,continue:!t.abort})}}),vf=Be("$ZodCheckStringFormat",(e,t)=>{var n,i;Ys.init(e,t),e._zod.onattach.push(o=>{const d=o._zod.bag;d.format=t.format,t.pattern&&(d.patterns??(d.patterns=new Set),d.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(i=e._zod).check??(i.check=()=>{})}),zR=Be("$ZodCheckRegex",(e,t)=>{vf.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),UR=Be("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=MR),vf.init(e,t)}),qR=Be("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=DR),vf.init(e,t)}),HR=Be("$ZodCheckIncludes",(e,t)=>{Ys.init(e,t);const n=ll(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=i,e._zod.onattach.push(o=>{const d=o._zod.bag;d.patterns??(d.patterns=new Set),d.patterns.add(i)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),FR=Be("$ZodCheckStartsWith",(e,t)=>{Ys.init(e,t);const n=new RegExp(`^${ll(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:e,continue:!t.abort})}}),KR=Be("$ZodCheckEndsWith",(e,t)=>{Ys.init(e,t);const n=new RegExp(`.*${ll(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(i=>{const o=i._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),e._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:e,continue:!t.abort})}}),WR=Be("$ZodCheckOverwrite",(e,t)=>{Ys.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class GR{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(`
|
|
11
|
-
`).filter(h=>h),o=Math.min(...i.map(h=>h.length-h.trimStart().length)),d=i.map(h=>h.slice(o)).map(h=>" ".repeat(this.indent*2)+h);for(const h of d)this.content.push(h)}compile(){const t=Function,n=this?.args,o=[...(this?.content??[""]).map(d=>` ${d}`)];return new t(...n,o.join(`
|
|
12
|
-
`))}}const VR={major:4,minor:3,patch:6},Hn=Be("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=VR;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const o of i)for(const d of o._zod.onattach)d(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const o=(h,l,u)=>{let f=Yo(h),v;for(const g of l){if(g._zod.def.when){if(!g._zod.def.when(h))continue}else if(f)continue;const S=h.issues.length,w=g._zod.check(h);if(w instanceof Promise&&u?.async===!1)throw new tl;if(v||w instanceof Promise)v=(v??Promise.resolve()).then(async()=>{await w,h.issues.length!==S&&(f||(f=Yo(h,S)))});else{if(h.issues.length===S)continue;f||(f=Yo(h,S))}}return v?v.then(()=>h):h},d=(h,l,u)=>{if(Yo(h))return h.aborted=!0,h;const f=o(l,i,u);if(f instanceof Promise){if(u.async===!1)throw new tl;return f.then(v=>e._zod.parse(v,u))}return e._zod.parse(f,u)};e._zod.run=(h,l)=>{if(l.skipChecks)return e._zod.parse(h,l);if(l.direction==="backward"){const f=e._zod.parse({value:h.value,issues:[]},{...l,skipChecks:!0});return f instanceof Promise?f.then(v=>d(v,h,l)):d(f,h,l)}const u=e._zod.parse(h,l);if(u instanceof Promise){if(l.async===!1)throw new tl;return u.then(f=>o(f,i,l))}return o(u,i,l)}}jn(e,"~standard",()=>({validate:o=>{try{const d=JA(e,o);return d.success?{value:d.data}:{issues:d.error?.issues}}catch{return eR(e,o).then(h=>h.success?{value:h.data}:{issues:h.error?.issues})}},vendor:"zod",version:1}))}),ng=Be("$ZodString",(e,t)=>{Hn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??AR(e._zod.bag),e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Gn=Be("$ZodStringFormat",(e,t)=>{vf.init(e,t),ng.init(e,t)}),YR=Be("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=gR),Gn.init(e,t)}),ZR=Be("$ZodUUID",(e,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=a_(i))}else t.pattern??(t.pattern=a_());Gn.init(e,t)}),XR=Be("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=vR),Gn.init(e,t)}),QR=Be("$ZodURL",(e,t)=>{Gn.init(e,t),e._zod.check=n=>{try{const i=n.value.trim(),o=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),JR=Be("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=bR()),Gn.init(e,t)}),eT=Be("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=pR),Gn.init(e,t)}),tT=Be("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=cR),Gn.init(e,t)}),nT=Be("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=uR),Gn.init(e,t)}),sT=Be("$ZodULID",(e,t)=>{t.pattern??(t.pattern=dR),Gn.init(e,t)}),iT=Be("$ZodXID",(e,t)=>{t.pattern??(t.pattern=fR),Gn.init(e,t)}),rT=Be("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=hR),Gn.init(e,t)}),aT=Be("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=jR(t)),Gn.init(e,t)}),oT=Be("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ER),Gn.init(e,t)}),lT=Be("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=NR(t)),Gn.init(e,t)}),cT=Be("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=mR),Gn.init(e,t)}),uT=Be("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=_R),Gn.init(e,t),e._zod.bag.format="ipv4"}),dT=Be("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=SR),Gn.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),fT=Be("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=xR),Gn.init(e,t)}),hT=Be("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=wR),Gn.init(e,t),e._zod.check=n=>{const i=n.value.split("/");try{if(i.length!==2)throw new Error;const[o,d]=i;if(!d)throw new Error;const h=Number(d);if(`${h}`!==d)throw new Error;if(h<0||h>128)throw new Error;new URL(`http://[${o}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Nx(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const pT=Be("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=kR),Gn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Nx(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function mT(e){if(!_x.test(e))return!1;const t=e.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Nx(n)}const gT=Be("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=_x),Gn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{mT(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),vT=Be("$ZodE164",(e,t)=>{t.pattern??(t.pattern=CR),Gn.init(e,t)});function yT(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[i]=n;if(!i)return!1;const o=JSON.parse(atob(i));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}const bT=Be("$ZodJWT",(e,t)=>{Gn.init(e,t),e._zod.check=n=>{yT(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),jx=Be("$ZodNumber",(e,t)=>{Hn.init(e,t),e._zod.pattern=e._zod.bag.pattern??wx,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;const d=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...d?{received:d}:{}}),n}}),_T=Be("$ZodNumberFormat",(e,t)=>{OR.init(e,t),jx.init(e,t)}),ST=Be("$ZodBoolean",(e,t)=>{Hn.init(e,t),e._zod.pattern=TR,e._zod.parse=(n,i)=>{if(t.coerce)try{n.value=!!n.value}catch{}const o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),xT=Be("$ZodNull",(e,t)=>{Hn.init(e,t),e._zod.pattern=IR,e._zod.values=new Set([null]),e._zod.parse=(n,i)=>{const o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),wT=Be("$ZodAny",(e,t)=>{Hn.init(e,t),e._zod.parse=n=>n}),kT=Be("$ZodUnknown",(e,t)=>{Hn.init(e,t),e._zod.parse=n=>n}),CT=Be("$ZodNever",(e,t)=>{Hn.init(e,t),e._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function o_(e,t,n){e.issues.length&&t.issues.push(...Zo(n,e.issues)),t.value[n]=e.value}const ET=Be("$ZodArray",(e,t)=>{Hn.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const d=[];for(let h=0;h<o.length;h++){const l=o[h],u=t.element._zod.run({value:l,issues:[]},i);u instanceof Promise?d.push(u.then(f=>o_(f,n,h))):o_(u,n,h)}return d.length?Promise.all(d).then(()=>n):n}});function Qd(e,t,n,i,o){if(e.issues.length){if(o&&!(n in i))return;t.issues.push(...Zo(n,e.issues))}e.value===void 0?n in i&&(t.value[n]=void 0):t.value[n]=e.value}function Ax(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=qA(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Rx(e,t,n,i,o,d){const h=[],l=o.keySet,u=o.catchall._zod,f=u.def.type,v=u.optout==="optional";for(const g in t){if(l.has(g))continue;if(f==="never"){h.push(g);continue}const S=u.run({value:t[g],issues:[]},i);S instanceof Promise?e.push(S.then(w=>Qd(w,n,g,t,v))):Qd(S,n,g,t,v)}return h.length&&n.issues.push({code:"unrecognized_keys",keys:h,input:t,inst:d}),e.length?Promise.all(e).then(()=>n):n}const NT=Be("$ZodObject",(e,t)=>{if(Hn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...l};return Object.defineProperty(t,"shape",{value:u}),u}})}const i=pf(()=>Ax(t));jn(e._zod,"propValues",()=>{const l=t.shape,u={};for(const f in l){const v=l[f]._zod;if(v.values){u[f]??(u[f]=new Set);for(const g of v.values)u[f].add(g)}}return u});const o=$c,d=t.catchall;let h;e._zod.parse=(l,u)=>{h??(h=i.value);const f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),l;l.value={};const v=[],g=h.shape;for(const S of h.keys){const w=g[S],E=w._zod.optout==="optional",x=w._zod.run({value:f[S],issues:[]},u);x instanceof Promise?v.push(x.then(m=>Qd(m,l,S,f,E))):Qd(x,l,S,f,E)}return d?Rx(v,f,l,u,i.value,e):v.length?Promise.all(v).then(()=>l):l}}),jT=Be("$ZodObjectJIT",(e,t)=>{NT.init(e,t);const n=e._zod.parse,i=pf(()=>Ax(t)),o=S=>{const w=new GR(["shape","payload","ctx"]),E=i.value,x=_=>{const k=r_(_);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};w.write("const input = payload.value;");const m=Object.create(null);let y=0;for(const _ of E.keys)m[_]=`key_${y++}`;w.write("const newResult = {};");for(const _ of E.keys){const k=m[_],j=r_(_),D=S[_]?._zod?.optout==="optional";w.write(`const ${k} = ${x(_)};`),D?w.write(`
|
|
13
|
-
if (${k}.issues.length) {
|
|
14
|
-
if (${j} in input) {
|
|
15
|
-
payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
16
|
-
...iss,
|
|
17
|
-
path: iss.path ? [${j}, ...iss.path] : [${j}]
|
|
18
|
-
})));
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
if (${k}.value === undefined) {
|
|
23
|
-
if (${j} in input) {
|
|
24
|
-
newResult[${j}] = undefined;
|
|
25
|
-
}
|
|
26
|
-
} else {
|
|
27
|
-
newResult[${j}] = ${k}.value;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
`):w.write(`
|
|
31
|
-
if (${k}.issues.length) {
|
|
32
|
-
payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
|
|
33
|
-
...iss,
|
|
34
|
-
path: iss.path ? [${j}, ...iss.path] : [${j}]
|
|
35
|
-
})));
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
if (${k}.value === undefined) {
|
|
39
|
-
if (${j} in input) {
|
|
40
|
-
newResult[${j}] = undefined;
|
|
41
|
-
}
|
|
42
|
-
} else {
|
|
43
|
-
newResult[${j}] = ${k}.value;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
`)}w.write("payload.value = newResult;"),w.write("return payload;");const b=w.compile();return(_,k)=>b(S,_,k)};let d;const h=$c,l=!hx.jitless,f=l&&zA.value,v=t.catchall;let g;e._zod.parse=(S,w)=>{g??(g=i.value);const E=S.value;return h(E)?l&&f&&w?.async===!1&&w.jitless!==!0?(d||(d=o(t.shape)),S=d(S,w),v?Rx([],E,S,w,g,e):S):n(S,w):(S.issues.push({expected:"object",code:"invalid_type",input:E,inst:e}),S)}});function l_(e,t,n,i){for(const d of e)if(d.issues.length===0)return t.value=d.value,t;const o=e.filter(d=>!Yo(d));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(d=>d.issues.map(h=>pa(h,i,ha())))}),t)}const Tx=Be("$ZodUnion",(e,t)=>{Hn.init(e,t),jn(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),jn(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),jn(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),jn(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){const o=t.options.map(d=>d._zod.pattern);return new RegExp(`^(${o.map(d=>Qm(d.source)).join("|")})$`)}});const n=t.options.length===1,i=t.options[0]._zod.run;e._zod.parse=(o,d)=>{if(n)return i(o,d);let h=!1;const l=[];for(const u of t.options){const f=u._zod.run({value:o.value,issues:[]},d);if(f instanceof Promise)l.push(f),h=!0;else{if(f.issues.length===0)return f;l.push(f)}}return h?Promise.all(l).then(u=>l_(u,o,e,d)):l_(l,o,e,d)}}),AT=Be("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Tx.init(e,t);const n=e._zod.parse;jn(e._zod,"propValues",()=>{const o={};for(const d of t.options){const h=d._zod.propValues;if(!h||Object.keys(h).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(d)}"`);for(const[l,u]of Object.entries(h)){o[l]||(o[l]=new Set);for(const f of u)o[l].add(f)}}return o});const i=pf(()=>{const o=t.options,d=new Map;for(const h of o){const l=h._zod.propValues?.[t.discriminator];if(!l||l.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(h)}"`);for(const u of l){if(d.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);d.set(u,h)}}return d});e._zod.parse=(o,d)=>{const h=o.value;if(!$c(h))return o.issues.push({code:"invalid_type",expected:"object",input:h,inst:e}),o;const l=i.value.get(h?.[t.discriminator]);return l?l._zod.run(o,d):t.unionFallback?n(o,d):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:h,path:[t.discriminator],inst:e}),o)}}),RT=Be("$ZodIntersection",(e,t)=>{Hn.init(e,t),e._zod.parse=(n,i)=>{const o=n.value,d=t.left._zod.run({value:o,issues:[]},i),h=t.right._zod.run({value:o,issues:[]},i);return d instanceof Promise||h instanceof Promise?Promise.all([d,h]).then(([u,f])=>c_(n,u,f)):c_(n,d,h)}});function vm(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ol(e)&&ol(t)){const n=Object.keys(t),i=Object.keys(e).filter(d=>n.indexOf(d)!==-1),o={...e,...t};for(const d of i){const h=vm(e[d],t[d]);if(!h.valid)return{valid:!1,mergeErrorPath:[d,...h.mergeErrorPath]};o[d]=h.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let i=0;i<e.length;i++){const o=e[i],d=t[i],h=vm(o,d);if(!h.valid)return{valid:!1,mergeErrorPath:[i,...h.mergeErrorPath]};n.push(h.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function c_(e,t,n){const i=new Map;let o;for(const l of t.issues)if(l.code==="unrecognized_keys"){o??(o=l);for(const u of l.keys)i.has(u)||i.set(u,{}),i.get(u).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const u of l.keys)i.has(u)||i.set(u,{}),i.get(u).r=!0;else e.issues.push(l);const d=[...i].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(d.length&&o&&e.issues.push({...o,keys:d}),Yo(e))return e;const h=vm(t.value,n.value);if(!h.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(h.mergeErrorPath)}`);return e.value=h.data,e}const TT=Be("$ZodRecord",(e,t)=>{Hn.init(e,t),e._zod.parse=(n,i)=>{const o=n.value;if(!ol(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const d=[],h=t.keyType._zod.values;if(h){n.value={};const l=new Set;for(const f of h)if(typeof f=="string"||typeof f=="number"||typeof f=="symbol"){l.add(typeof f=="number"?f.toString():f);const v=t.valueType._zod.run({value:o[f],issues:[]},i);v instanceof Promise?d.push(v.then(g=>{g.issues.length&&n.issues.push(...Zo(f,g.issues)),n.value[f]=g.value})):(v.issues.length&&n.issues.push(...Zo(f,v.issues)),n.value[f]=v.value)}let u;for(const f in o)l.has(f)||(u=u??[],u.push(f));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(const l of Reflect.ownKeys(o)){if(l==="__proto__")continue;let u=t.keyType._zod.run({value:l,issues:[]},i);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&wx.test(l)&&u.issues.length){const g=t.keyType._zod.run({value:Number(l),issues:[]},i);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(u=g)}if(u.issues.length){t.mode==="loose"?n.value[l]=o[l]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(g=>pa(g,i,ha())),input:l,path:[l],inst:e});continue}const v=t.valueType._zod.run({value:o[l],issues:[]},i);v instanceof Promise?d.push(v.then(g=>{g.issues.length&&n.issues.push(...Zo(l,g.issues)),n.value[u.value]=g.value})):(v.issues.length&&n.issues.push(...Zo(l,v.issues)),n.value[u.value]=v.value)}}return d.length?Promise.all(d).then(()=>n):n}}),IT=Be("$ZodEnum",(e,t)=>{Hn.init(e,t);const n=px(t.entries),i=new Set(n);e._zod.values=i,e._zod.pattern=new RegExp(`^(${n.filter(o=>UA.has(typeof o)).map(o=>typeof o=="string"?ll(o):o.toString()).join("|")})$`),e._zod.parse=(o,d)=>{const h=o.value;return i.has(h)||o.issues.push({code:"invalid_value",values:n,input:h,inst:e}),o}}),MT=Be("$ZodLiteral",(e,t)=>{if(Hn.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(i=>typeof i=="string"?ll(i):i?ll(i.toString()):String(i)).join("|")})$`),e._zod.parse=(i,o)=>{const d=i.value;return n.has(d)||i.issues.push({code:"invalid_value",values:t.values,input:d,inst:e}),i}}),DT=Be("$ZodTransform",(e,t)=>{Hn.init(e,t),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new fx(e.constructor.name);const o=t.transform(n.value,n);if(i.async)return(o instanceof Promise?o:Promise.resolve(o)).then(h=>(n.value=h,n));if(o instanceof Promise)throw new tl;return n.value=o,n}});function u_(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Ix=Be("$ZodOptional",(e,t)=>{Hn.init(e,t),e._zod.optin="optional",e._zod.optout="optional",jn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),jn(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Qm(n.source)})?$`):void 0}),e._zod.parse=(n,i)=>{if(t.innerType._zod.optin==="optional"){const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(d=>u_(d,n.value)):u_(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,i)}}),LT=Be("$ZodExactOptional",(e,t)=>{Ix.init(e,t),jn(e._zod,"values",()=>t.innerType._zod.values),jn(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,i)=>t.innerType._zod.run(n,i)}),OT=Be("$ZodNullable",(e,t)=>{Hn.init(e,t),jn(e._zod,"optin",()=>t.innerType._zod.optin),jn(e._zod,"optout",()=>t.innerType._zod.optout),jn(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${Qm(n.source)}|null)$`):void 0}),jn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,i)=>n.value===null?n:t.innerType._zod.run(n,i)}),PT=Be("$ZodDefault",(e,t)=>{Hn.init(e,t),e._zod.optin="optional",jn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);if(n.value===void 0)return n.value=t.defaultValue,n;const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(d=>d_(d,t)):d_(o,t)}});function d_(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const BT=Be("$ZodPrefault",(e,t)=>{Hn.init(e,t),e._zod.optin="optional",jn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>(i.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,i))}),$T=Be("$ZodNonOptional",(e,t)=>{Hn.init(e,t),jn(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(n,i)=>{const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(d=>f_(d,e)):f_(o,e)}});function f_(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const zT=Be("$ZodCatch",(e,t)=>{Hn.init(e,t),jn(e._zod,"optin",()=>t.innerType._zod.optin),jn(e._zod,"optout",()=>t.innerType._zod.optout),jn(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(d=>(n.value=d.value,d.issues.length&&(n.value=t.catchValue({...n,error:{issues:d.issues.map(h=>pa(h,i,ha()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=t.catchValue({...n,error:{issues:o.issues.map(d=>pa(d,i,ha()))},input:n.value}),n.issues=[]),n)}}),UT=Be("$ZodPipe",(e,t)=>{Hn.init(e,t),jn(e._zod,"values",()=>t.in._zod.values),jn(e._zod,"optin",()=>t.in._zod.optin),jn(e._zod,"optout",()=>t.out._zod.optout),jn(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,i)=>{if(i.direction==="backward"){const d=t.out._zod.run(n,i);return d instanceof Promise?d.then(h=>Cd(h,t.in,i)):Cd(d,t.in,i)}const o=t.in._zod.run(n,i);return o instanceof Promise?o.then(d=>Cd(d,t.out,i)):Cd(o,t.out,i)}});function Cd(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const qT=Be("$ZodReadonly",(e,t)=>{Hn.init(e,t),jn(e._zod,"propValues",()=>t.innerType._zod.propValues),jn(e._zod,"values",()=>t.innerType._zod.values),jn(e._zod,"optin",()=>t.innerType?._zod?.optin),jn(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(n,i)=>{if(i.direction==="backward")return t.innerType._zod.run(n,i);const o=t.innerType._zod.run(n,i);return o instanceof Promise?o.then(h_):h_(o)}});function h_(e){return e.value=Object.freeze(e.value),e}const HT=Be("$ZodCustom",(e,t)=>{Ys.init(e,t),Hn.init(e,t),e._zod.parse=(n,i)=>n,e._zod.check=n=>{const i=n.value,o=t.fn(i);if(o instanceof Promise)return o.then(d=>p_(d,n,i,e));p_(o,n,i,e)}});function p_(e,t,n,i){if(!e){const o={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(o.params=i._zod.def.params),t.issues.push(zc(o))}}var m_;class FT{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const i=n[0];return this._map.set(t,i),i&&typeof i=="object"&&"id"in i&&this._idmap.set(i.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const i={...this.get(n)??{}};delete i.id;const o={...i,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function KT(){return new FT}(m_=globalThis).__zod_globalRegistry??(m_.__zod_globalRegistry=KT());const Tc=globalThis.__zod_globalRegistry;function WT(e,t){return new e({type:"string",...It(t)})}function GT(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...It(t)})}function g_(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...It(t)})}function VT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...It(t)})}function YT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...It(t)})}function ZT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...It(t)})}function XT(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...It(t)})}function QT(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...It(t)})}function JT(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...It(t)})}function e2(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...It(t)})}function t2(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...It(t)})}function n2(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...It(t)})}function s2(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...It(t)})}function i2(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...It(t)})}function r2(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...It(t)})}function a2(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...It(t)})}function o2(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...It(t)})}function l2(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...It(t)})}function c2(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...It(t)})}function u2(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...It(t)})}function d2(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...It(t)})}function f2(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...It(t)})}function h2(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...It(t)})}function p2(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...It(t)})}function m2(e,t){return new e({type:"string",format:"date",check:"string_format",...It(t)})}function g2(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...It(t)})}function v2(e,t){return new e({type:"string",format:"duration",check:"string_format",...It(t)})}function y2(e,t){return new e({type:"number",checks:[],...It(t)})}function b2(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...It(t)})}function _2(e,t){return new e({type:"boolean",...It(t)})}function S2(e,t){return new e({type:"null",...It(t)})}function x2(e){return new e({type:"any"})}function w2(e){return new e({type:"unknown"})}function k2(e,t){return new e({type:"never",...It(t)})}function v_(e,t){return new Cx({check:"less_than",...It(t),value:e,inclusive:!1})}function wp(e,t){return new Cx({check:"less_than",...It(t),value:e,inclusive:!0})}function y_(e,t){return new Ex({check:"greater_than",...It(t),value:e,inclusive:!1})}function kp(e,t){return new Ex({check:"greater_than",...It(t),value:e,inclusive:!0})}function b_(e,t){return new LR({check:"multiple_of",...It(t),value:e})}function Mx(e,t){return new PR({check:"max_length",...It(t),maximum:e})}function Jd(e,t){return new BR({check:"min_length",...It(t),minimum:e})}function Dx(e,t){return new $R({check:"length_equals",...It(t),length:e})}function C2(e,t){return new zR({check:"string_format",format:"regex",...It(t),pattern:e})}function E2(e){return new UR({check:"string_format",format:"lowercase",...It(e)})}function N2(e){return new qR({check:"string_format",format:"uppercase",...It(e)})}function j2(e,t){return new HR({check:"string_format",format:"includes",...It(t),includes:e})}function A2(e,t){return new FR({check:"string_format",format:"starts_with",...It(t),prefix:e})}function R2(e,t){return new KR({check:"string_format",format:"ends_with",...It(t),suffix:e})}function dl(e){return new WR({check:"overwrite",tx:e})}function T2(e){return dl(t=>t.normalize(e))}function I2(){return dl(e=>e.trim())}function M2(){return dl(e=>e.toLowerCase())}function D2(){return dl(e=>e.toUpperCase())}function L2(){return dl(e=>$A(e))}function O2(e,t,n){return new e({type:"array",element:t,...It(n)})}function P2(e,t,n){return new e({type:"custom",check:"custom",fn:t,...It(n)})}function B2(e){const t=$2(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(zc(i,n.value,t._zod.def));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),n.issues.push(zc(o))}},e(n.value,n)));return t}function $2(e,t){const n=new Ys({check:"custom",...It(t)});return n._zod.check=e,n}function Lx(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Tc,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ds(e,t,n={path:[],schemaPath:[]}){var i;const o=e._zod.def,d=t.seen.get(e);if(d)return d.count++,n.schemaPath.includes(e)&&(d.cycle=n.path),d.schema;const h={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,h);const l=e._zod.toJSONSchema?.();if(l)h.schema=l;else{const v={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,h.schema,v);else{const S=h.schema,w=t.processors[o.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);w(e,t,S,v)}const g=e._zod.parent;g&&(h.ref||(h.ref=g),ds(g,t,v),t.seen.get(g).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&Object.assign(h.schema,u),t.io==="input"&&Rs(e)&&(delete h.schema.examples,delete h.schema.default),t.io==="input"&&h.schema._prefault&&((i=h.schema).default??(i.default=h.schema._prefault)),delete h.schema._prefault,t.seen.get(e).schema}function Ox(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=new Map;for(const h of e.seen.entries()){const l=e.metadataRegistry.get(h[0])?.id;if(l){const u=i.get(l);if(u&&u!==h[0])throw new Error(`Duplicate schema id "${l}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(l,h[0])}}const o=h=>{const l=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(h[0])?.id,S=e.external.uri??(E=>E);if(g)return{ref:S(g)};const w=h[1].defId??h[1].schema.id??`schema${e.counter++}`;return h[1].defId=w,{defId:w,ref:`${S("__shared")}#/${l}/${w}`}}if(h[1]===n)return{ref:"#"};const f=`#/${l}/`,v=h[1].schema.id??`__schema${e.counter++}`;return{defId:v,ref:f+v}},d=h=>{if(h[1].schema.$ref)return;const l=h[1],{ref:u,defId:f}=o(h);l.def={...l.schema},f&&(l.defId=f);const v=l.schema;for(const g in v)delete v[g];v.$ref=u};if(e.cycles==="throw")for(const h of e.seen.entries()){const l=h[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
|
|
47
|
-
|
|
48
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const h of e.seen.entries()){const l=h[1];if(t===h[0]){d(h);continue}if(e.external){const f=e.external.registry.get(h[0])?.id;if(t!==h[0]&&f){d(h);continue}}if(e.metadataRegistry.get(h[0])?.id){d(h);continue}if(l.cycle){d(h);continue}if(l.count>1&&e.reused==="ref"){d(h);continue}}}function Px(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const i=h=>{const l=e.seen.get(h);if(l.ref===null)return;const u=l.def??l.schema,f={...u},v=l.ref;if(l.ref=null,v){i(v);const S=e.seen.get(v),w=S.schema;if(w.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(w)):Object.assign(u,w),Object.assign(u,f),h._zod.parent===v)for(const x in u)x==="$ref"||x==="allOf"||x in f||delete u[x];if(w.$ref&&S.def)for(const x in u)x==="$ref"||x==="allOf"||x in S.def&&JSON.stringify(u[x])===JSON.stringify(S.def[x])&&delete u[x]}const g=h._zod.parent;if(g&&g!==v){i(g);const S=e.seen.get(g);if(S?.schema.$ref&&(u.$ref=S.schema.$ref,S.def))for(const w in u)w==="$ref"||w==="allOf"||w in S.def&&JSON.stringify(u[w])===JSON.stringify(S.def[w])&&delete u[w]}e.override({zodSchema:h,jsonSchema:u,path:l.path??[]})};for(const h of[...e.seen.entries()].reverse())i(h[0]);const o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const h=e.external.registry.get(t)?.id;if(!h)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(h)}Object.assign(o,n.def??n.schema);const d=e.external?.defs??{};for(const h of e.seen.entries()){const l=h[1];l.def&&l.defId&&(d[l.defId]=l.def)}e.external||Object.keys(d).length>0&&(e.target==="draft-2020-12"?o.$defs=d:o.definitions=d);try{const h=JSON.parse(JSON.stringify(o));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:ef(t,"input",e.processors),output:ef(t,"output",e.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Rs(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const i=e._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Rs(i.element,n);if(i.type==="set")return Rs(i.valueType,n);if(i.type==="lazy")return Rs(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Rs(i.innerType,n);if(i.type==="intersection")return Rs(i.left,n)||Rs(i.right,n);if(i.type==="record"||i.type==="map")return Rs(i.keyType,n)||Rs(i.valueType,n);if(i.type==="pipe")return Rs(i.in,n)||Rs(i.out,n);if(i.type==="object"){for(const o in i.shape)if(Rs(i.shape[o],n))return!0;return!1}if(i.type==="union"){for(const o of i.options)if(Rs(o,n))return!0;return!1}if(i.type==="tuple"){for(const o of i.items)if(Rs(o,n))return!0;return!!(i.rest&&Rs(i.rest,n))}return!1}const z2=(e,t={})=>n=>{const i=Lx({...n,processors:t});return ds(e,i),Ox(i,e),Px(i,e)},ef=(e,t,n={})=>i=>{const{libraryOptions:o,target:d}=i??{},h=Lx({...o??{},target:d,io:t,processors:n});return ds(e,h),Ox(h,e),Px(h,e)},U2={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},q2=(e,t,n,i)=>{const o=n;o.type="string";const{minimum:d,maximum:h,format:l,patterns:u,contentEncoding:f}=e._zod.bag;if(typeof d=="number"&&(o.minLength=d),typeof h=="number"&&(o.maxLength=h),l&&(o.format=U2[l]??l,o.format===""&&delete o.format,l==="time"&&delete o.format),f&&(o.contentEncoding=f),u&&u.size>0){const v=[...u];v.length===1?o.pattern=v[0].source:v.length>1&&(o.allOf=[...v.map(g=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:g.source}))])}},H2=(e,t,n,i)=>{const o=n,{minimum:d,maximum:h,format:l,multipleOf:u,exclusiveMaximum:f,exclusiveMinimum:v}=e._zod.bag;typeof l=="string"&&l.includes("int")?o.type="integer":o.type="number",typeof v=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.minimum=v,o.exclusiveMinimum=!0):o.exclusiveMinimum=v),typeof d=="number"&&(o.minimum=d,typeof v=="number"&&t.target!=="draft-04"&&(v>=d?delete o.minimum:delete o.exclusiveMinimum)),typeof f=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(o.maximum=f,o.exclusiveMaximum=!0):o.exclusiveMaximum=f),typeof h=="number"&&(o.maximum=h,typeof f=="number"&&t.target!=="draft-04"&&(f<=h?delete o.maximum:delete o.exclusiveMaximum)),typeof u=="number"&&(o.multipleOf=u)},F2=(e,t,n,i)=>{n.type="boolean"},K2=(e,t,n,i)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},W2=(e,t,n,i)=>{n.not={}},G2=(e,t,n,i)=>{},V2=(e,t,n,i)=>{},Y2=(e,t,n,i)=>{const o=e._zod.def,d=px(o.entries);d.every(h=>typeof h=="number")&&(n.type="number"),d.every(h=>typeof h=="string")&&(n.type="string"),n.enum=d},Z2=(e,t,n,i)=>{const o=e._zod.def,d=[];for(const h of o.values)if(h===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof h=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");d.push(Number(h))}else d.push(h);if(d.length!==0)if(d.length===1){const h=d[0];n.type=h===null?"null":typeof h,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[h]:n.const=h}else d.every(h=>typeof h=="number")&&(n.type="number"),d.every(h=>typeof h=="string")&&(n.type="string"),d.every(h=>typeof h=="boolean")&&(n.type="boolean"),d.every(h=>h===null)&&(n.type="null"),n.enum=d},X2=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Q2=(e,t,n,i)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},J2=(e,t,n,i)=>{const o=n,d=e._zod.def,{minimum:h,maximum:l}=e._zod.bag;typeof h=="number"&&(o.minItems=h),typeof l=="number"&&(o.maxItems=l),o.type="array",o.items=ds(d.element,t,{...i,path:[...i.path,"items"]})},eI=(e,t,n,i)=>{const o=n,d=e._zod.def;o.type="object",o.properties={};const h=d.shape;for(const f in h)o.properties[f]=ds(h[f],t,{...i,path:[...i.path,"properties",f]});const l=new Set(Object.keys(h)),u=new Set([...l].filter(f=>{const v=d.shape[f]._zod;return t.io==="input"?v.optin===void 0:v.optout===void 0}));u.size>0&&(o.required=Array.from(u)),d.catchall?._zod.def.type==="never"?o.additionalProperties=!1:d.catchall?d.catchall&&(o.additionalProperties=ds(d.catchall,t,{...i,path:[...i.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},tI=(e,t,n,i)=>{const o=e._zod.def,d=o.inclusive===!1,h=o.options.map((l,u)=>ds(l,t,{...i,path:[...i.path,d?"oneOf":"anyOf",u]}));d?n.oneOf=h:n.anyOf=h},nI=(e,t,n,i)=>{const o=e._zod.def,d=ds(o.left,t,{...i,path:[...i.path,"allOf",0]}),h=ds(o.right,t,{...i,path:[...i.path,"allOf",1]}),l=f=>"allOf"in f&&Object.keys(f).length===1,u=[...l(d)?d.allOf:[d],...l(h)?h.allOf:[h]];n.allOf=u},sI=(e,t,n,i)=>{const o=n,d=e._zod.def;o.type="object";const h=d.keyType,u=h._zod.bag?.patterns;if(d.mode==="loose"&&u&&u.size>0){const v=ds(d.valueType,t,{...i,path:[...i.path,"patternProperties","*"]});o.patternProperties={};for(const g of u)o.patternProperties[g.source]=v}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(o.propertyNames=ds(d.keyType,t,{...i,path:[...i.path,"propertyNames"]})),o.additionalProperties=ds(d.valueType,t,{...i,path:[...i.path,"additionalProperties"]});const f=h._zod.values;if(f){const v=[...f].filter(g=>typeof g=="string"||typeof g=="number");v.length>0&&(o.required=v)}},iI=(e,t,n,i)=>{const o=e._zod.def,d=ds(o.innerType,t,i),h=t.seen.get(e);t.target==="openapi-3.0"?(h.ref=o.innerType,n.nullable=!0):n.anyOf=[d,{type:"null"}]},rI=(e,t,n,i)=>{const o=e._zod.def;ds(o.innerType,t,i);const d=t.seen.get(e);d.ref=o.innerType},aI=(e,t,n,i)=>{const o=e._zod.def;ds(o.innerType,t,i);const d=t.seen.get(e);d.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},oI=(e,t,n,i)=>{const o=e._zod.def;ds(o.innerType,t,i);const d=t.seen.get(e);d.ref=o.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},lI=(e,t,n,i)=>{const o=e._zod.def;ds(o.innerType,t,i);const d=t.seen.get(e);d.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=h},cI=(e,t,n,i)=>{const o=e._zod.def,d=t.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;ds(d,t,i);const h=t.seen.get(e);h.ref=d},uI=(e,t,n,i)=>{const o=e._zod.def;ds(o.innerType,t,i);const d=t.seen.get(e);d.ref=o.innerType,n.readOnly=!0},Bx=(e,t,n,i)=>{const o=e._zod.def;ds(o.innerType,t,i);const d=t.seen.get(e);d.ref=o.innerType},dI=Be("ZodISODateTime",(e,t)=>{aT.init(e,t),Yn.init(e,t)});function fI(e){return p2(dI,e)}const hI=Be("ZodISODate",(e,t)=>{oT.init(e,t),Yn.init(e,t)});function pI(e){return m2(hI,e)}const mI=Be("ZodISOTime",(e,t)=>{lT.init(e,t),Yn.init(e,t)});function gI(e){return g2(mI,e)}const vI=Be("ZodISODuration",(e,t)=>{cT.init(e,t),Yn.init(e,t)});function yI(e){return v2(vI,e)}const bI=(e,t)=>{yx.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>QA(e,n)},flatten:{value:n=>XA(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,gm,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,gm,2)}},isEmpty:{get(){return e.issues.length===0}}})},wi=Be("ZodError",bI,{Parent:Error}),_I=eg(wi),SI=tg(wi),xI=mf(wi),wI=gf(wi),kI=tR(wi),CI=nR(wi),EI=sR(wi),NI=iR(wi),jI=rR(wi),AI=aR(wi),RI=oR(wi),TI=lR(wi),Fn=Be("ZodType",(e,t)=>(Hn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ef(e,"input"),output:ef(e,"output")}}),e.toJSONSchema=z2(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(ga(t,{checks:[...t.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0}),e.with=e.check,e.clone=(n,i)=>va(e,n,i),e.brand=()=>e,e.register=((n,i)=>(n.add(e,i),e)),e.parse=(n,i)=>_I(e,n,i,{callee:e.parse}),e.safeParse=(n,i)=>xI(e,n,i),e.parseAsync=async(n,i)=>SI(e,n,i,{callee:e.parseAsync}),e.safeParseAsync=async(n,i)=>wI(e,n,i),e.spa=e.safeParseAsync,e.encode=(n,i)=>kI(e,n,i),e.decode=(n,i)=>CI(e,n,i),e.encodeAsync=async(n,i)=>EI(e,n,i),e.decodeAsync=async(n,i)=>NI(e,n,i),e.safeEncode=(n,i)=>jI(e,n,i),e.safeDecode=(n,i)=>AI(e,n,i),e.safeEncodeAsync=async(n,i)=>RI(e,n,i),e.safeDecodeAsync=async(n,i)=>TI(e,n,i),e.refine=(n,i)=>e.check(CM(n,i)),e.superRefine=n=>e.check(EM(n)),e.overwrite=n=>e.check(dl(n)),e.optional=()=>x_(e),e.exactOptional=()=>fM(e),e.nullable=()=>w_(e),e.nullish=()=>x_(w_(e)),e.nonoptional=n=>yM(e,n),e.array=()=>dt(e),e.or=n=>Di([e,n]),e.and=n=>aM(e,n),e.transform=n=>k_(e,uM(n)),e.default=n=>mM(e,n),e.prefault=n=>vM(e,n),e.catch=n=>_M(e,n),e.pipe=n=>k_(e,n),e.readonly=()=>wM(e),e.describe=n=>{const i=e.clone();return Tc.add(i,{description:n}),i},Object.defineProperty(e,"description",{get(){return Tc.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Tc.get(e);const i=e.clone();return Tc.add(i,n[0]),i},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),$x=Be("_ZodString",(e,t)=>{ng.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(i,o,d)=>q2(e,i,o);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...i)=>e.check(C2(...i)),e.includes=(...i)=>e.check(j2(...i)),e.startsWith=(...i)=>e.check(A2(...i)),e.endsWith=(...i)=>e.check(R2(...i)),e.min=(...i)=>e.check(Jd(...i)),e.max=(...i)=>e.check(Mx(...i)),e.length=(...i)=>e.check(Dx(...i)),e.nonempty=(...i)=>e.check(Jd(1,...i)),e.lowercase=i=>e.check(E2(i)),e.uppercase=i=>e.check(N2(i)),e.trim=()=>e.check(I2()),e.normalize=(...i)=>e.check(T2(...i)),e.toLowerCase=()=>e.check(M2()),e.toUpperCase=()=>e.check(D2()),e.slugify=()=>e.check(L2())}),II=Be("ZodString",(e,t)=>{ng.init(e,t),$x.init(e,t),e.email=n=>e.check(GT(MI,n)),e.url=n=>e.check(QT(DI,n)),e.jwt=n=>e.check(h2(YI,n)),e.emoji=n=>e.check(JT(LI,n)),e.guid=n=>e.check(g_(__,n)),e.uuid=n=>e.check(VT(Ed,n)),e.uuidv4=n=>e.check(YT(Ed,n)),e.uuidv6=n=>e.check(ZT(Ed,n)),e.uuidv7=n=>e.check(XT(Ed,n)),e.nanoid=n=>e.check(e2(OI,n)),e.guid=n=>e.check(g_(__,n)),e.cuid=n=>e.check(t2(PI,n)),e.cuid2=n=>e.check(n2(BI,n)),e.ulid=n=>e.check(s2($I,n)),e.base64=n=>e.check(u2(WI,n)),e.base64url=n=>e.check(d2(GI,n)),e.xid=n=>e.check(i2(zI,n)),e.ksuid=n=>e.check(r2(UI,n)),e.ipv4=n=>e.check(a2(qI,n)),e.ipv6=n=>e.check(o2(HI,n)),e.cidrv4=n=>e.check(l2(FI,n)),e.cidrv6=n=>e.check(c2(KI,n)),e.e164=n=>e.check(f2(VI,n)),e.datetime=n=>e.check(fI(n)),e.date=n=>e.check(pI(n)),e.time=n=>e.check(gI(n)),e.duration=n=>e.check(yI(n))});function R(e){return WT(II,e)}const Yn=Be("ZodStringFormat",(e,t)=>{Gn.init(e,t),$x.init(e,t)}),MI=Be("ZodEmail",(e,t)=>{XR.init(e,t),Yn.init(e,t)}),__=Be("ZodGUID",(e,t)=>{YR.init(e,t),Yn.init(e,t)}),Ed=Be("ZodUUID",(e,t)=>{ZR.init(e,t),Yn.init(e,t)}),DI=Be("ZodURL",(e,t)=>{QR.init(e,t),Yn.init(e,t)}),LI=Be("ZodEmoji",(e,t)=>{JR.init(e,t),Yn.init(e,t)}),OI=Be("ZodNanoID",(e,t)=>{eT.init(e,t),Yn.init(e,t)}),PI=Be("ZodCUID",(e,t)=>{tT.init(e,t),Yn.init(e,t)}),BI=Be("ZodCUID2",(e,t)=>{nT.init(e,t),Yn.init(e,t)}),$I=Be("ZodULID",(e,t)=>{sT.init(e,t),Yn.init(e,t)}),zI=Be("ZodXID",(e,t)=>{iT.init(e,t),Yn.init(e,t)}),UI=Be("ZodKSUID",(e,t)=>{rT.init(e,t),Yn.init(e,t)}),qI=Be("ZodIPv4",(e,t)=>{uT.init(e,t),Yn.init(e,t)}),HI=Be("ZodIPv6",(e,t)=>{dT.init(e,t),Yn.init(e,t)}),FI=Be("ZodCIDRv4",(e,t)=>{fT.init(e,t),Yn.init(e,t)}),KI=Be("ZodCIDRv6",(e,t)=>{hT.init(e,t),Yn.init(e,t)}),WI=Be("ZodBase64",(e,t)=>{pT.init(e,t),Yn.init(e,t)}),GI=Be("ZodBase64URL",(e,t)=>{gT.init(e,t),Yn.init(e,t)}),VI=Be("ZodE164",(e,t)=>{vT.init(e,t),Yn.init(e,t)}),YI=Be("ZodJWT",(e,t)=>{bT.init(e,t),Yn.init(e,t)}),zx=Be("ZodNumber",(e,t)=>{jx.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(i,o,d)=>H2(e,i,o),e.gt=(i,o)=>e.check(y_(i,o)),e.gte=(i,o)=>e.check(kp(i,o)),e.min=(i,o)=>e.check(kp(i,o)),e.lt=(i,o)=>e.check(v_(i,o)),e.lte=(i,o)=>e.check(wp(i,o)),e.max=(i,o)=>e.check(wp(i,o)),e.int=i=>e.check(S_(i)),e.safe=i=>e.check(S_(i)),e.positive=i=>e.check(y_(0,i)),e.nonnegative=i=>e.check(kp(0,i)),e.negative=i=>e.check(v_(0,i)),e.nonpositive=i=>e.check(wp(0,i)),e.multipleOf=(i,o)=>e.check(b_(i,o)),e.step=(i,o)=>e.check(b_(i,o)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function ye(e){return y2(zx,e)}const ZI=Be("ZodNumberFormat",(e,t)=>{_T.init(e,t),zx.init(e,t)});function S_(e){return b2(ZI,e)}const XI=Be("ZodBoolean",(e,t)=>{ST.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>F2(e,n,i)});function Ye(e){return _2(XI,e)}const QI=Be("ZodNull",(e,t)=>{xT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>K2(e,n,i)});function Ja(e){return S2(QI,e)}const JI=Be("ZodAny",(e,t)=>{wT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>G2()});function eo(){return x2(JI)}const eM=Be("ZodUnknown",(e,t)=>{kT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>V2()});function Yi(){return w2(eM)}const tM=Be("ZodNever",(e,t)=>{CT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>W2(e,n,i)});function Xo(e){return k2(tM,e)}const nM=Be("ZodArray",(e,t)=>{ET.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>J2(e,n,i,o),e.element=t.element,e.min=(n,i)=>e.check(Jd(n,i)),e.nonempty=n=>e.check(Jd(1,n)),e.max=(n,i)=>e.check(Mx(n,i)),e.length=(n,i)=>e.check(Dx(n,i)),e.unwrap=()=>e.element});function dt(e,t){return O2(nM,e,t)}const sM=Be("ZodObject",(e,t)=>{jT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>eI(e,n,i,o),jn(e,"shape",()=>t.shape),e.keyof=()=>wt(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Yi()}),e.loose=()=>e.clone({...e._zod.def,catchall:Yi()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xo()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>WA(e,n),e.safeExtend=n=>GA(e,n),e.merge=n=>VA(e,n),e.pick=n=>FA(e,n),e.omit=n=>KA(e,n),e.partial=(...n)=>YA(Hx,e,n[0]),e.required=(...n)=>ZA(Fx,e,n[0])});function Y(e,t){const n={type:"object",shape:e??{},...It(t)};return new sM(n)}const Ux=Be("ZodUnion",(e,t)=>{Tx.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>tI(e,n,i,o),e.options=t.options});function Di(e,t){return new Ux({type:"union",options:e,...It(t)})}const iM=Be("ZodDiscriminatedUnion",(e,t)=>{Ux.init(e,t),AT.init(e,t)});function qx(e,t,n){return new iM({type:"union",options:t,discriminator:e,...It(n)})}const rM=Be("ZodIntersection",(e,t)=>{RT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>nI(e,n,i,o)});function aM(e,t){return new rM({type:"intersection",left:e,right:t})}const oM=Be("ZodRecord",(e,t)=>{TT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>sI(e,n,i,o),e.keyType=t.keyType,e.valueType=t.valueType});function Ds(e,t,n){return new oM({type:"record",keyType:e,valueType:t,...It(n)})}const ym=Be("ZodEnum",(e,t)=>{IT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(i,o,d)=>Y2(e,i,o),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(i,o)=>{const d={};for(const h of i)if(n.has(h))d[h]=t.entries[h];else throw new Error(`Key ${h} not found in enum`);return new ym({...t,checks:[],...It(o),entries:d})},e.exclude=(i,o)=>{const d={...t.entries};for(const h of i)if(n.has(h))delete d[h];else throw new Error(`Key ${h} not found in enum`);return new ym({...t,checks:[],...It(o),entries:d})}});function wt(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(i=>[i,i])):e;return new ym({type:"enum",entries:n,...It(t)})}const lM=Be("ZodLiteral",(e,t)=>{MT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Z2(e,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function oe(e,t){return new lM({type:"literal",values:Array.isArray(e)?e:[e],...It(t)})}const cM=Be("ZodTransform",(e,t)=>{DT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Q2(e,n),e._zod.parse=(n,i)=>{if(i.direction==="backward")throw new fx(e.constructor.name);n.addIssue=d=>{if(typeof d=="string")n.issues.push(zc(d,n.value,t));else{const h=d;h.fatal&&(h.continue=!1),h.code??(h.code="custom"),h.input??(h.input=n.value),h.inst??(h.inst=e),n.issues.push(zc(h))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(d=>(n.value=d,n)):(n.value=o,n)}});function uM(e){return new cM({type:"transform",transform:e})}const Hx=Be("ZodOptional",(e,t)=>{Ix.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Bx(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function x_(e){return new Hx({type:"optional",innerType:e})}const dM=Be("ZodExactOptional",(e,t)=>{LT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>Bx(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function fM(e){return new dM({type:"optional",innerType:e})}const hM=Be("ZodNullable",(e,t)=>{OT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>iI(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function w_(e){return new hM({type:"nullable",innerType:e})}const pM=Be("ZodDefault",(e,t)=>{PT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>aI(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function mM(e,t){return new pM({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():gx(t)}})}const gM=Be("ZodPrefault",(e,t)=>{BT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>oI(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function vM(e,t){return new gM({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():gx(t)}})}const Fx=Be("ZodNonOptional",(e,t)=>{$T.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>rI(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function yM(e,t){return new Fx({type:"nonoptional",innerType:e,...It(t)})}const bM=Be("ZodCatch",(e,t)=>{zT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>lI(e,n,i,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _M(e,t){return new bM({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const SM=Be("ZodPipe",(e,t)=>{UT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>cI(e,n,i,o),e.in=t.in,e.out=t.out});function k_(e,t){return new SM({type:"pipe",in:e,out:t})}const xM=Be("ZodReadonly",(e,t)=>{qT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>uI(e,n,i,o),e.unwrap=()=>e._zod.def.innerType});function wM(e){return new xM({type:"readonly",innerType:e})}const kM=Be("ZodCustom",(e,t)=>{HT.init(e,t),Fn.init(e,t),e._zod.processJSONSchema=(n,i,o)=>X2(e,n)});function CM(e,t={}){return P2(kM,e,t)}function EM(e){return B2(e)}const NM=Y({type:wt(["image","document"]),mediaType:R().max(256),data:R().max(1e7),name:R().max(256)}),jM=Y({type:oe("file_ref"),path:R().max(4096),name:R().max(256).optional()}),AM=Di([NM,jM]),Kx=Y({deviceId:R().max(256).optional(),deviceName:R().max(256).optional(),deviceType:wt(["phone","tablet","desktop","unknown"]).optional(),platform:R().max(256).optional()}).passthrough();Y({type:oe("auth"),token:R().max(512),protocolVersion:ye().int().min(0).optional(),deviceInfo:Kx.optional(),capabilities:dt(R().max(256)).max(64).optional().catch([]).default([]),eagerPublicKey:R().max(512).optional(),eagerSalt:R().max(512).optional(),historyCursors:Ds(R().max(256),ye().int().nonnegative()).refine(e=>Object.keys(e).length<=256,{message:"too many history cursors (max 256)"}).optional()}).passthrough();Y({type:oe("pair"),pairingId:R().min(1).max(256),protocolVersion:ye().int().min(0).optional(),deviceInfo:Kx.optional(),capabilities:dt(R().max(256)).max(64).optional().catch([]).default([])}).passthrough();Y({type:oe("pair_request"),deviceName:R().max(64).optional(),requestId:R().min(1).max(128),protocolVersion:ye().int().min(0).optional()}).passthrough();const RM=Y({type:oe("pair_approve"),requestId:R().min(1).max(128)}).passthrough(),TM=Y({type:oe("pair_deny"),requestId:R().min(1).max(128)}).passthrough(),IM=Y({type:oe("input"),data:R().max(1e5).optional(),attachments:dt(AM).optional(),isVoice:Ye().optional()}).passthrough(),MM=Y({type:oe("interrupt")}).passthrough(),DM=Y({type:oe("cancel_activity"),activityId:R().min(1).max(512),sessionId:R().max(256).optional(),requestId:R().max(128).optional()}).passthrough(),LM=Y({type:oe("cancel_queued"),clientMessageId:R().min(1).max(128),sessionId:R().max(256).optional()}).passthrough(),OM=Y({type:oe("set_model"),model:R().max(256)}).passthrough(),PM=Y({type:oe("set_permission_mode"),mode:wt(["approve","auto","plan","acceptEdits"]),confirmed:Ye().optional()}).passthrough(),BM=Y({type:oe("set_thinking_level"),level:wt(["default","high","max"]),sessionId:R().max(256).optional()}).passthrough(),$M=Y({tool:R().min(1).max(256),decision:wt(["allow","deny"])}),zM=Y({type:oe("byok_get_credentials_status"),requestId:R().max(128).optional()}).passthrough(),UM=Y({type:oe("byok_set_credentials"),requestId:R().max(128).optional(),anthropicApiKey:R().min(1)}).passthrough(),qM=Y({type:oe("byok_clear_credentials"),requestId:R().max(128).optional()}).passthrough(),HM=Y({type:oe("get_credentials_status"),requestId:R().max(128).optional()}).passthrough(),FM=Y({type:oe("set_credential"),requestId:R().max(128).optional(),key:R().min(1).max(128),value:R().min(1)}).passthrough(),KM=Y({type:oe("delete_credential"),requestId:R().max(128).optional(),key:R().min(1).max(128)}).passthrough(),WM=Y({type:oe("test_credential"),requestId:R().max(128).optional(),key:R().min(1).max(128)}).passthrough(),GM=Y({type:oe("set_permission_rules"),rules:dt($M).max(1e3),sessionId:R().max(256).optional()}),VM=Y({type:oe("set_prompt_evaluator"),value:Ye(),sessionId:R().max(256).optional()}),YM=Y({type:oe("set_prompt_evaluator_skip_pattern"),value:Di([R().max(1024),Ja()]),sessionId:R().max(256).optional()}),ZM=Y({type:oe("set_chroxy_context_hint"),value:Ye(),sessionId:R().max(256).optional()}),XM=Y({type:oe("set_session_preamble"),value:R().max(4096),sessionId:R().max(256).optional()}),QM=Y({type:oe("skill_activate"),skillName:R().min(1).max(256),sessionId:R().max(256).optional()}),JM=Y({type:oe("skill_deactivate"),skillName:R().min(1).max(256),sessionId:R().max(256).optional()}),eD=Y({type:oe("skill_trust_accept"),skillName:R().min(1).max(256),sessionId:R().max(256).optional(),requestId:R().max(256).optional()}),tD=Y({type:oe("skill_trust_grant"),skillName:R().min(1).max(256),author:R().min(1).max(256),scope:R().max(64).optional(),sessionId:R().max(256).optional(),requestId:R().max(256).optional()}),nD=Y({type:oe("permission_response"),requestId:R().min(1).max(256),decision:wt(["allow","allowAlways","deny"]),editedInput:Ds(R(),Yi()).optional()}),sD=Y({type:oe("get_permission_input"),requestId:R().min(1).max(256)}),iD=Y({type:oe("query_permission_audit"),sessionId:R().max(256).optional(),auditType:wt(["mode_change","decision"]).optional(),since:ye().optional(),limit:ye().int().min(1).max(1e4).optional()}),rD=Y({type:oe("list_sessions")}),aD=Y({type:oe("switch_session"),sessionId:R().max(256)}),oD=Y({network:Y({allowedDomains:dt(R().max(256)).max(256).optional()}).passthrough().optional(),filesystem:Y({allowedPaths:dt(R().max(4096)).max(256).optional(),deniedPaths:dt(R().max(4096)).max(256).optional()}).passthrough().optional(),bash:Y({allowedCommands:dt(R().max(256)).max(256).optional()}).passthrough().optional(),autoAllowBashIfSandboxed:Ye().optional()}).passthrough(),lD=Y({type:oe("create_session"),name:R().max(200).optional(),cwd:R().max(4096).optional(),provider:R().max(256).optional(),model:R().max(256).optional(),permissionMode:wt(["approve","acceptEdits","auto","plan"]).optional(),worktree:Ye().optional(),sandbox:oD.optional(),isolation:wt(["none","worktree","sandbox","container"]).optional(),environmentId:R().max(256).optional(),skipPermissions:Ye().optional(),agentCommId:R().max(200).optional()}),cD=Y({type:oe("destroy_session"),sessionId:R().max(256),force:Ye().optional()}),uD=Y({type:oe("rename_session"),sessionId:R().max(256),name:R().max(200)}),dD=Y({type:oe("register_push_token"),token:R().min(1).max(512)}),Wx=Ds(R().min(1).max(64),Ye()),Gx=Di([Ja(),Y({start:R().regex(/^\d{2}:\d{2}$/),end:R().regex(/^\d{2}:\d{2}$/),timezone:R().min(1).max(64)})]),Vx=dt(R().min(1).max(64)).max(64),fD=Y({categories:Wx.optional(),quietHours:Gx.optional(),bypassCategories:Vx.optional(),lastSeenAt:ye().int().positive().optional(),platform:R().min(1).max(32).optional()}).passthrough(),hD=Y({categories:Wx.optional(),devices:Ds(R().min(1).max(512),Di([fD,Ja()])).refine(e=>Object.keys(e).length<=1e3,{message:"Too many device entries (max 1000)"}).optional(),quietHours:Gx.optional(),bypassCategories:Vx.optional()}),pD=Y({type:oe("notification_prefs_get"),requestId:R().max(128).optional()}).passthrough(),mD=Y({type:oe("notification_prefs_set"),requestId:R().max(128).optional(),prefs:hD}).passthrough(),gD=Di([R().max(1e5),dt(R().max(1e4)).max(100)]),vD=Y({type:oe("user_question_response"),answer:R().max(1e5),answers:Ds(R(),gD).refine(e=>Object.keys(e).length<=100,{message:"Too many answers (max 100)"}).optional(),toolUseId:R().max(256).optional(),freeformText:R().max(1e5).optional()}),yD=Y({type:oe("list_directory"),path:R().max(4096).optional()}),bD=Y({type:oe("browse_files"),path:R().max(4096).nullable().optional()}).passthrough(),_D=Y({type:oe("read_file"),path:R().max(4096),requestId:R().max(200).optional()}).passthrough(),SD=Y({type:oe("write_file"),path:R().max(4096),content:R().max(1e7)}).passthrough(),xD=Y({type:oe("list_files"),query:R().max(1e3).optional()}).passthrough(),wD=Y({type:oe("list_symbols"),path:R().max(4096).optional(),sessionId:R().max(256).optional()}).passthrough(),kD=Y({type:oe("resolve_symbol"),symbol:R().min(1).max(256),file:R().max(4096).optional(),sessionId:R().max(256).optional()}).passthrough(),CD=Y({type:oe("search_content"),query:R().min(1).max(1024),path:R().max(4096).optional(),sessionId:R().max(256).optional()}).passthrough(),ED=Y({type:oe("find_references"),symbol:R().min(1).max(256),file:R().max(4096).optional(),sessionId:R().max(256).optional()}).passthrough(),ND=Y({type:oe("list_slash_commands")}).passthrough(),jD=Y({type:oe("list_agents")}).passthrough(),AD=Y({type:oe("request_full_history"),sessionId:R().max(256).optional()});Y({type:oe("key_exchange"),publicKey:R().max(512),salt:R().max(512)});Y({type:oe("ping")});const RD=Y({type:oe("request_session_context"),sessionId:R().max(256).optional()}),TD=Y({type:oe("get_diff")}).passthrough(),ID=Y({type:oe("git_status")}).passthrough(),MD=Y({type:oe("git_branches")}).passthrough(),DD=Y({type:oe("git_stage"),files:dt(R().max(4096)).min(1)}).passthrough(),LD=Y({type:oe("git_unstage"),files:dt(R().max(4096)).min(1)}).passthrough(),OD=Y({type:oe("git_commit"),message:R().min(1).max(1e4)}).passthrough(),PD=Y({type:oe("resume_budget"),sessionId:R().max(256).optional(),requestId:R().max(128).optional()}).passthrough(),BD=Y({type:oe("list_checkpoints")}),$D=Y({type:oe("restore_checkpoint"),checkpointId:R().max(256)}),zD=Y({type:oe("create_checkpoint"),name:R().max(256).optional(),description:R().max(1e3).optional()}),UD=Y({type:oe("delete_checkpoint"),checkpointId:R().max(256)}),qD=Y({type:oe("close_dev_preview"),port:ye().int(),sessionId:R().max(256).optional()}),HD=Y({type:oe("launch_web_task"),prompt:R().min(1).max(1e4),cwd:R().max(4096).optional()}),FD=Y({type:oe("list_web_tasks")}),KD=Y({type:oe("teleport_web_task"),taskId:R().min(1).max(256)}),WD=Y({type:oe("list_conversations")}),GD=Y({type:oe("resume_conversation"),conversationId:R().max(256),cwd:R().max(4096).optional(),name:R().max(200).optional()}),VD=Y({type:oe("search_conversations"),query:R().trim().min(1).max(500),maxResults:ye().int().min(1).max(100).optional()}),YD=Y({type:oe("request_cost_summary")}),ZD=Y({type:oe("subscribe_sessions"),sessionIds:dt(R().max(256)).min(1).max(20)}),XD=Y({type:oe("unsubscribe_sessions"),sessionIds:dt(R().max(256)).min(1).max(20)}),QD=Y({type:oe("terminal_subscribe"),sessionId:R().max(256)}),JD=Y({type:oe("terminal_unsubscribe"),sessionId:R().max(256)}),e3=Y({type:oe("terminal_resize"),sessionId:R().max(256),cols:ye().int().min(1).max(1e3),rows:ye().int().min(1).max(1e3)}),t3=Y({type:oe("terminal_input"),sessionId:R().max(256),data:R().max(1e5)}),n3=Y({type:oe("terminal_resync"),sessionId:R().max(256)}),s3=Y({type:oe("client_visible"),visible:Ye()}),i3=Y({type:oe("claim_primary"),sessionId:R().max(256),force:Ye().optional()}),r3=Y({type:oe("list_providers")}),a3=Y({type:oe("list_skills")}),o3=Y({type:oe("list_repos")}),l3=Y({type:oe("add_repo"),path:R().min(1).max(4096),name:R().max(256).optional()}),c3=Y({type:oe("remove_repo"),path:R().min(1).max(4096)}),u3=Y({type:oe("session_preset_get"),cwd:R().min(1).max(4096),requestId:R().max(128).optional()}),d3=Y({type:oe("session_preset_set"),cwd:R().min(1).max(4096),preset:Y({preamble:R().max(8192).optional(),seed:R().max(16384).optional(),enabled:Ye().optional()}).nullable(),requestId:R().max(128).optional()}),f3=Y({type:oe("session_preset_approve"),cwd:R().min(1).max(4096),requestId:R().max(128).optional()}),h3=Y({type:oe("session_preset_revoke"),cwd:R().min(1).max(4096),requestId:R().max(128).optional()}),p3=Y({type:oe("revoke_token"),requestId:R().max(128).optional()}),m3=Y({type:oe("extension_message"),provider:R().min(1).max(256),subtype:R().min(1).max(256),data:Yi(),sessionId:R().max(256).optional()}),g3=Y({type:oe("create_environment"),name:R().max(200),cwd:R().max(4096),image:R().max(256).optional(),memoryLimit:R().max(64).optional(),cpuLimit:R().max(64).optional()}),v3=Y({type:oe("list_environments")}),y3=Y({type:oe("destroy_environment"),environmentId:R().max(256)}),b3=Y({type:oe("get_environment"),environmentId:R().max(256)}),_3=Y({type:oe("evaluate_draft"),draft:R().min(1).max(5e4),sessionId:R().optional(),requestId:R().max(128).optional()}),S3=Y({type:oe("host_status_request"),requestId:R().max(128).optional()}),x3=Y({type:oe("mailbox_status_request"),requestId:R().max(128).optional()}),w3=Y({type:oe("external_sessions_request"),requestId:R().max(128).optional()}),k3=Y({type:oe("repo_events_request"),requestId:R().max(128).optional()}),C3=Y({type:oe("runner_status_request"),requestId:R().max(128).optional()}),E3=Y({type:oe("containers_status_request"),requestId:R().max(128).optional()}),N3=Y({type:oe("repo_runtime_config_request"),requestId:R().max(128).optional()}),j3=Y({type:oe("byok_pool_status_request"),requestId:R().max(128).optional()}),A3=Y({type:oe("host_prune_status_request"),requestId:R().max(128).optional()}),R3=Y({type:oe("simulator_status_request"),requestId:R().max(128).optional()}),T3=Y({type:oe("emulator_status_request"),requestId:R().max(128).optional()}),I3=Y({type:oe("wsl_status_request"),requestId:R().max(128).optional()}),M3=Y({type:oe("integration_status_request"),requestId:R().max(128).optional()}),D3=Y({type:oe("skills_inventory_request"),requestId:R().max(128).optional()}),L3=Y({type:oe("integration_action"),action:wt(["repo_memory_reindex","repo_relay_rerun"]),repoPath:R().min(1).max(4096),runId:ye().int().nonnegative().finite().optional(),requestId:R().max(128).optional()}).passthrough(),O3=Y({type:oe("containers_action"),action:wt(["stop","restart","destroy"]),environmentId:R().min(1).max(256),requestId:R().max(128).optional()}).passthrough(),P3=Y({type:oe("byok_pool_action"),action:wt(["drain","recycle","resize"]),key:R().min(1).max(1024).optional(),maxPerKey:ye().int().positive().max(1024).optional(),maxTotal:ye().int().positive().max(4096).optional(),requestId:R().max(128).optional()}).passthrough(),B3=Y({type:oe("host_prune_action"),kind:wt(["containers","images","all"]),requestId:R().max(128).optional()}).passthrough(),$3=Y({type:oe("simulator_action"),action:wt(["boot","shutdown"]),udid:R().min(1).max(128),requestId:R().max(128).optional()}).passthrough(),z3=Y({type:oe("emulator_action"),action:wt(["boot","kill"]),avd:R().min(1).max(256).optional(),serial:R().min(1).max(128).optional(),headless:Ye().optional(),requestId:R().max(128).optional()}).passthrough(),U3=Y({type:oe("wsl_action"),action:wt(["start","terminate"]),distro:R().min(1).max(256),requestId:R().max(128).optional()}).passthrough(),q3=Y({type:oe("summarize_session"),sessionId:R().min(1).max(256),requestId:R().max(128).optional()});Y({type:oe("encrypted"),d:R().max(1e7),n:ye().int().nonnegative()});qx("type",[IM,MM,DM,LM,OM,PM,BM,GM,VM,YM,ZM,XM,QM,JM,eD,tD,nD,sD,rD,aD,lD,cD,uD,dD,pD,mD,vD,yD,bD,_D,SD,xD,wD,kD,CD,ED,ND,jD,AD,RD,TD,ID,MD,DD,LD,OD,PD,BD,$D,zD,UD,qD,HD,FD,KD,WD,GD,VD,YD,ZD,XD,QD,JD,e3,t3,n3,s3,i3,r3,zM,UM,qM,HM,FM,KM,WM,a3,o3,l3,c3,u3,d3,f3,h3,p3,iD,m3,g3,v3,y3,b3,_3,S3,C3,E3,N3,j3,A3,R3,T3,I3,M3,D3,x3,w3,k3,L3,O3,P3,B3,$3,z3,U3,q3,RM,TM]);const nl=1440*60*1e3,H3=Y({clientId:R(),deviceName:R().nullable(),deviceType:wt(["phone","tablet","desktop","unknown"]),platform:R()}),F3=Y({code:R(),message:R(),provider:R().optional(),sessionId:R().optional(),costUsd:ye().finite().optional()}),tf=Y({eraStarted:Ye(),defaultProvider:R(),defaultBillingClass:R(),warnings:dt(F3)});Y({type:oe("auth_ok"),clientId:R(),serverMode:oe("cli"),serverVersion:R(),latestVersion:R().nullable(),serverCommit:R(),cwd:R().nullable(),connectedClients:dt(H3),encryption:wt(["required","disabled"]),protocolVersion:ye().int().min(1),minProtocolVersion:ye().int().min(1),maxProtocolVersion:ye().int().min(1),capabilities:Ds(R(),Ye()).optional(),resultTimeoutMs:ye().int().positive().finite().max(nl).optional(),hardTimeoutMs:ye().int().positive().finite().max(nl).optional(),streamStallTimeoutMs:ye().int().nonnegative().finite().max(nl).optional(),exposure:Y({lanBind:Ye(),bindHost:R().nullable(),quickTunnel:Ye()}).optional(),billingCanary:tf.optional(),serverPublicKey:R().max(512).optional(),serverKeySig:R().max(512).optional(),newIdentityKey:R().max(512).optional(),rotationCert:R().max(512).optional(),availablePermissionModes:dt(Y({id:R(),label:R(),description:R().optional()})).optional()}).passthrough();Y({type:oe("auth_fail"),reason:R()});Y({type:oe("pair_fail"),reason:R()});Y({type:oe("pair_request_pending"),requestId:R(),verifyCode:R().regex(/^\d{6}$/)});const K3=Y({type:oe("pair_pending"),requestId:R(),deviceName:R().max(64),verifyCode:R().regex(/^\d{6}$/),expiresAt:ye().int().nonnegative().finite()});Y({type:oe("pair_result"),requestId:R(),ok:Ye(),token:R().optional(),reason:R().optional()});const W3=Y({type:oe("pair_resolved"),requestId:R(),reason:R()}),G3=Y({toolUseId:R(),kind:wt(["bash","agent","monitor"]),description:R(),startedAt:ye().int().nonnegative().finite()});Y({type:oe("claude_ready"),backgroundTasks:dt(G3).optional(),scheduledWakeup:Y({at:ye().int().nonnegative().finite(),reason:R()}).optional()});Y({type:oe("client_joined"),client:Y({clientId:R(),deviceName:R().nullable(),deviceType:wt(["phone","tablet","desktop","unknown"]),platform:R()})});Y({type:oe("client_left"),clientId:R()});Y({type:oe("key_exchange_ok"),publicKey:R(),serverKeySig:R().optional(),newIdentityKey:R().optional(),rotationCert:R().optional()});Y({type:oe("rate_limited"),retryAfterMs:ye(),message:R()});const sg=ye().int().nonnegative().finite().optional();Y({type:oe("stream_start"),messageId:R(),serverTs:sg});Y({type:oe("stream_delta"),messageId:R(),delta:R(),serverTs:sg});Y({type:oe("stream_end"),messageId:R(),serverTs:sg});Y({type:oe("message"),messageType:R(),content:R(),tool:R().nullable().optional(),options:eo().optional(),timestamp:ye(),code:R().max(64).optional(),attemptedResumeId:R().max(256).optional(),stdout:R().max(8192).optional(),stderr:R().max(8192).optional()});Y({type:oe("tool_start"),messageId:R(),toolUseId:R(),tool:R(),input:eo(),serverName:R().optional()});Y({type:oe("tool_result"),toolUseId:R(),result:eo(),truncated:Ye().optional()});Y({type:oe("tool_input_delta"),messageId:R(),toolUseId:R(),partialJson:R()});Y({type:oe("result"),cost:ye().nullable().optional(),duration:ye().optional(),usage:eo().optional(),sessionId:R().nullable().optional()});Y({type:oe("model_changed"),model:R().nullable()});Y({type:oe("prompt_evaluator_changed"),sessionId:R(),value:Ye()});Y({type:oe("prompt_evaluator_skip_pattern_changed"),sessionId:R(),value:Di([R(),Ja()])});Y({type:oe("chroxy_context_hint_changed"),sessionId:R(),value:Ye()});Y({type:oe("session_preamble_changed"),sessionId:R(),value:R()});const V3=Y({id:R(),label:R(),fullId:R(),contextWindow:Yi().optional()});Y({type:oe("available_models"),models:dt(Yi()).optional(),defaultModel:R().optional(),provider:R().nullable().optional()});Y({type:oe("permission_mode_changed"),mode:R()});Y({type:oe("permission_request"),requestId:R(),tool:R(),description:R().optional(),input:eo(),remainingMs:ye().int().nonnegative().finite().max(nl).optional(),sessionId:R().optional()});const Y3=qx("found",[Y({type:oe("permission_input"),requestId:R(),found:oe(!0),tool:R().optional(),input:Ds(R(),Yi())}),Y({type:oe("permission_input"),requestId:R(),found:oe(!1),error:Y({code:R(),message:R()})})]);Y({type:oe("user_question"),toolUseId:R(),questions:dt(eo())});Y({type:oe("agent_busy")});Y({type:oe("agent_idle")});Y({type:oe("agent_spawned"),toolUseId:R(),description:R().optional(),startedAt:ye().optional()});Y({type:oe("agent_completed"),toolUseId:R()});Y({type:oe("agent_event"),parentToolUseId:R(),eventType:R(),payload:Ds(R(),Yi())});const Yx=Y({shellId:R(),command:R(),startedAt:ye().int().nonnegative()});Y({type:oe("background_work_changed"),sessionId:R(),pending:dt(Yx)});Y({type:oe("shell_pending_approval"),approvalId:R(),hint:R().optional()});Y({type:oe("terminal_output"),sessionId:R(),data:R()});Y({type:oe("terminal_size"),sessionId:R(),cols:ye().int(),rows:ye().int()});const Z3=wt(["agent","shell","tool"]),X3=wt(["running","blocked","done","failed"]),Q3=Y({kind:R().min(1),id:R().min(1)}),Zx=Y({id:R().min(1),kind:Z3,label:R(),status:X3,startedAt:ye().int().nonnegative().finite(),endedAt:ye().int().nonnegative().finite().optional(),parentId:R().min(1).optional(),outputRef:Q3.optional()}).superRefine((e,t)=>{const n=e.status==="done"||e.status==="failed";n&&e.endedAt===void 0&&t.addIssue({code:"custom",path:["endedAt"],message:'endedAt is required when status is "done" or "failed"'}),!n&&e.endedAt!==void 0&&t.addIssue({code:"custom",path:["endedAt"],message:'endedAt must be absent while status is "running" or "blocked"'}),e.endedAt!==void 0&&e.endedAt<e.startedAt&&t.addIssue({code:"custom",path:["endedAt"],message:"endedAt must be >= startedAt"})}),J3=Y({type:oe("activity_snapshot"),sessionId:R(),schemaVersion:ye().int().positive(),entries:dt(Zx)}),e6=Y({type:oe("activity_delta"),sessionId:R(),schemaVersion:ye().int().positive(),op:wt(["started","updated","ended"]),entry:Zx}).superRefine((e,t)=>{e.op==="ended"&&(e.entry.status==="done"||e.entry.status==="failed"||t.addIssue({code:"custom",path:["entry","status"],message:'an "ended" delta must carry a terminal entry status ("done" or "failed")'}))}),t6=Y({type:oe("cancel_activity_ack"),activityId:R(),sessionId:R().optional(),requestId:R().max(128).optional()}).passthrough();Y({type:oe("message_queued"),sessionId:R(),clientMessageId:R().optional(),text:R(),queueLength:ye().int().nonnegative()}).passthrough();Y({type:oe("message_dequeued"),sessionId:R(),clientMessageId:R().optional(),queueLength:ye().int().nonnegative(),reason:wt(["flush","interrupted","cancelled"])}).passthrough();const n6=wt(["live","investigate","abandoned","recent","onboarded"]),s6=Y({state:wt(["clean","dirty"]),untracked:ye().int().nonnegative().finite(),modified:ye().int().nonnegative().finite(),staged:ye().int().nonnegative().finite()}),i6=Y({name:R(),path:R(),branch:R(),verdict:n6,live:Ye(),tree:s6,worktrees:ye().int().nonnegative().finite(),ahead:ye().int().nonnegative().finite().nullable(),behind:ye().int().nonnegative().finite().nullable(),openPRs:ye().int().nonnegative().finite().nullable(),prChecks:Y({failing:ye().int().nonnegative().finite(),pending:ye().int().nonnegative().finite(),approved:ye().int().nonnegative().finite(),changesRequested:ye().int().nonnegative().finite()}).nullable(),prsUrl:R().regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pulls$/,"must be a GitHub pull-requests URL").nullable(),attribution:Ye().nullable(),onboarding:R(),lastTouched:R().datetime(),note:R().optional()}),r6=Y({live:ye().int().nonnegative().finite(),onboarded:ye().int().nonnegative().finite(),abandoned:ye().int().nonnegative().finite(),investigate:ye().int().nonnegative().finite(),recent:ye().int().nonnegative().finite()}),a6=Y({type:oe("host_status_snapshot"),generatedAt:R().datetime(),root:R(),summary:r6,repos:dt(i6),error:Y({code:R(),message:R()}).optional()}),o6=Y({agentCommId:R(),sessionId:R(),sessionName:R().nullable(),isBusy:Ye(),isTui:Ye()}),l6=Y({at:ye(),to:R(),from:R(),unreadCount:ye().int().nonnegative().nullable(),outcome:wt(["injected","busy","not-tui","no-session","pty-dead"])}),c6=Y({type:oe("mailbox_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),registrations:dt(o6),recentEvents:dt(l6),error:Y({code:R(),message:R()}).optional()}),u6=Y({source:R(),sessionId:R(),name:R(),project:R().nullable(),cwd:R().nullable(),status:wt(["running","idle"]),subagents:ye().int().nonnegative(),lastActivityTs:ye()}).passthrough(),d6=Y({type:oe("external_sessions_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),sessions:dt(u6),error:Y({code:R(),message:R()}).optional()}).passthrough();Y({source:wt(["daemon","repo"]),active:Ye(),trustState:wt(["trusted","pending"]),enabled:Ye(),seed:R(),preambleLength:ye().int().nonnegative(),seedLength:ye().int().nonnegative(),capped:Ye(),repoPath:R().nullable()});const f6=Y({source:wt(["daemon","repo"]),active:Ye(),trustState:wt(["trusted","pending"]),enabled:Ye(),preamble:R(),seed:R(),preambleLength:ye().int().nonnegative(),seedLength:ye().int().nonnegative(),capped:Ye(),repoPath:R().nullable()}),h6=Y({type:oe("session_preset_snapshot"),cwd:R().nullable(),preset:f6.nullable(),requestId:R().max(128).optional()}),Xx=Y({kind:wt(["push","pull_request","issues","ping"]),repo:R().nullable(),actor:R().nullable(),at:R().datetime(),branch:R().nullable().optional(),action:R().nullable().optional(),number:ye().int().nullable().optional(),title:R().nullable().optional(),url:R().nullable().optional(),summary:R()}).passthrough(),p6=Y({type:oe("repo_events_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),events:dt(Xx),error:Y({code:R(),message:R()}).optional()}),m6=Y({type:oe("repo_events_delta"),generatedAt:R().datetime(),event:Xx}),g6=wt(["busy","idle","offline","stopped","unregistered"]),v6=Y({manager:wt(["launchd","systemd","none"]),label:R().nullable(),running:Ye(),pid:ye().int().nonnegative().finite().nullable(),lastExitCode:ye().int().finite().nullable()}),y6=Y({name:R(),dir:R(),verdict:g6,service:v6,githubStatus:wt(["online","offline"]).nullable(),busy:Ye().nullable(),os:R().nullable(),labels:dt(R())}),b6=Y({name:R(),owner:R().nullable(),repo:R().nullable(),githubUrl:R(),runnersUrl:R().regex(/^https:\/\/github\.com\/(?:[^/]+\/[^/]+\/settings\/actions\/runners|organizations\/[^/]+\/settings\/actions\/runners)$/,"must be a GitHub runner-settings URL").nullable(),runners:dt(y6)}),_6=Y({total:ye().int().nonnegative().finite(),busy:ye().int().nonnegative().finite(),idle:ye().int().nonnegative().finite(),offline:ye().int().nonnegative().finite(),stopped:ye().int().nonnegative().finite(),unregistered:ye().int().nonnegative().finite()}),S6=Y({type:oe("runner_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),root:R(),summary:_6,repos:dt(b6),error:Y({code:R(),message:R()}).optional()}),x6=Y({cpuPercent:ye().nonnegative().finite().nullable(),memBytes:ye().nonnegative().finite().nullable(),memPercent:ye().nonnegative().finite().nullable()}),w6=Y({id:R(),name:R(),cwd:R(),image:R().nullable(),status:R(),backend:R(),containerId:R().nullable(),composeProject:R().nullable(),sessionCount:ye().int().nonnegative().finite(),createdAt:R().nullable(),uptimeMs:ye().int().nonnegative().finite().nullable(),stats:x6.nullable()}),k6=Y({total:ye().int().nonnegative().finite(),running:ye().int().nonnegative().finite(),stopped:ye().int().nonnegative().finite(),other:ye().int().nonnegative().finite()}),C6=Y({type:oe("containers_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),summary:k6,containers:dt(w6),dockerStatsNote:R().nullable().optional(),error:Y({code:R(),message:R()}).optional()}),E6=Y({present:Ye(),path:R().nullable()}),N6=Y({present:Ye(),files:dt(R())}),j6=Y({name:R(),path:R(),devcontainer:E6,compose:N6,image:R().nullable(),imageSource:wt(["devcontainer","default"]).nullable(),imageAllowed:Ye().nullable(),error:R().nullable()}),A6=Y({total:ye().int().nonnegative().finite(),withDevcontainer:ye().int().nonnegative().finite(),withCompose:ye().int().nonnegative().finite(),imagesDenied:ye().int().nonnegative().finite(),errored:ye().int().nonnegative().finite()}),R6=Y({type:oe("repo_runtime_config_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),backend:R(),backendSource:wt(["config","default"]),isolation:R(),allowlist:Y({source:wt(["config","default"]),patterns:dt(R())}),repos:dt(j6),summary:A6,error:Y({code:R(),message:R()}).optional()}),Qx=Y({idleTimeoutMs:ye().nonnegative().finite(),maxPerKey:ye().int().nonnegative().finite(),maxTotal:ye().int().nonnegative().finite(),maxAgeMs:ye().nonnegative().finite().nullable()}),T6=Y({key:R(),size:ye().int().nonnegative().finite(),oldestIdleMs:ye().nonnegative().finite()}),I6=Y({key:R(),containerId:R().nullable(),reason:R(),timestamp:ye().finite()}),M6=Y({hits:ye().int().nonnegative().finite(),misses:ye().int().nonnegative().finite(),releases:ye().int().nonnegative().finite(),shutdowns:ye().int().nonnegative().finite(),hitRate:ye().finite(),totalSize:ye().int().nonnegative().finite(),buckets:dt(T6),evictionsByReason:Ds(R(),ye().int().nonnegative().finite()),recentEvictions:dt(I6)}),D6=Y({type:oe("byok_pool_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),enabled:Ye(),note:R().nullable(),limits:Qx.nullable(),stats:M6.nullable(),error:Y({code:R(),message:R()}).optional()}),L6=Y({present:Ye(),sizeBytes:ye().int().nonnegative().finite(),lastModified:R().datetime().nullable()}),O6=Y({totalEvents:ye().int().nonnegative().finite(),cacheHits:ye().int().nonnegative().finite(),cacheMisses:ye().int().nonnegative().finite(),cacheHitRatio:ye().min(0).max(1),estimatedTokensSaved:ye().nonnegative().finite(),cacheEntryCount:ye().int().nonnegative().finite().nullable(),staleEntryCount:ye().int().nonnegative().finite().nullable(),lastActivity:R().datetime().nullable(),topMissedQueries:dt(Y({query:R(),count:ye().int().nonnegative().finite()})).default([])}),P6=Y({configured:Ye(),summarizer:R().nullable(),toolGroups:dt(R()),cache:L6.nullable(),report:O6.nullable(),reason:R().nullable()}),B6=Y({databaseId:ye().int().nonnegative().finite(),status:R().nullable(),conclusion:R().nullable(),event:R().nullable(),createdAt:R().datetime().nullable()}),$6=wt(["ok","failing","drifted","not_installed","unknown"]),z6=Y({installed:Ye(),pinnedVersion:R().nullable(),pinnedSha:R().nullable(),latestVersion:R().nullable(),runs:dt(B6),failureStreak:ye().int().nonnegative().finite(),verdict:$6,driftUnknown:Ye(),workflowUrl:R().nullable(),reason:R().nullable()}),U6=Y({name:R(),path:R(),repoMemory:P6.nullable(),repoRelay:z6.nullable().optional()}),q6=Y({total:ye().int().nonnegative().finite(),configured:ye().int().nonnegative().finite(),notConfigured:ye().int().nonnegative().finite(),degraded:ye().int().nonnegative().finite(),relayInstalled:ye().int().nonnegative().finite().optional(),relayFailing:ye().int().nonnegative().finite().optional(),relayDrifted:ye().int().nonnegative().finite().optional()}),C_=Y({found:Ye(),path:R().nullable(),note:R().nullable()}),H6=Y({type:oe("integration_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),root:R(),summary:q6,repos:dt(U6),repoMemoryCli:C_.optional(),ghCli:C_.optional(),error:Y({code:R(),message:R()}).optional()}),F6=Y({scanned:ye().int().nonnegative().finite(),summarized:ye().int().nonnegative().finite(),fresh:ye().int().nonnegative().finite(),skipped:ye().int().nonnegative().finite()}),K6=Y({type:oe("integration_action_ack"),action:R(),repoPath:R(),requestId:R().max(128).nullable().optional(),runId:ye().int().nonnegative().finite().nullable().optional(),counts:F6.nullable()}).passthrough(),W6=Y({type:oe("containers_action_ack"),action:R(),environmentId:R(),requestId:R().max(128).nullable().optional(),status:R().nullable().optional()}).passthrough(),G6=Y({type:oe("byok_pool_action_ack"),action:R(),requestId:R().max(128).nullable().optional(),key:R().nullable().optional(),drained:ye().int().nonnegative().finite().nullable().optional(),evicted:ye().int().nonnegative().finite().nullable().optional(),limits:Qx.nullable().optional(),configured:Y({maxPerKey:ye().int().nonnegative().finite(),maxTotal:ye().int().nonnegative().finite()}).nullable().optional()}).passthrough(),V6=Y({id:R(),name:R(),state:R(),sizeBytes:ye().nonnegative().finite().nullable()}),Y6=Y({id:R(),ref:R(),repository:R(),sizeBytes:ye().nonnegative().finite().nullable()}),Z6=Y({type:oe("host_prune_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),dockerAvailable:Ye(),note:R().nullable(),containers:dt(V6),images:dt(Y6),summary:Y({containerCount:ye().int().nonnegative().finite(),imageCount:ye().int().nonnegative().finite(),reclaimableBytes:ye().nonnegative().finite()}),error:Y({code:R(),message:R()}).optional()}).passthrough(),X6=Y({type:oe("host_prune_action_ack"),kind:R(),requestId:R().max(128).nullable().optional(),dockerAvailable:Ye(),removedContainers:ye().int().nonnegative().finite(),removedImages:ye().int().nonnegative().finite(),reclaimedBytes:ye().nonnegative().finite(),failures:dt(Y({ref:R(),error:R()}))}).passthrough(),Q6=Y({udid:R(),name:R(),state:R(),runtime:R(),deviceType:R().nullable(),isAvailable:Ye()}),J6=Y({ready:Ye(),bootedSimulator:R().nullable(),metroReachable:Ye(),mockServerReachable:Ye(),reasons:dt(R())}),eL=Y({type:oe("simulator_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),available:Ye(),note:R().nullable(),devices:dt(Q6),readyForMaestro:J6,error:Y({code:R(),message:R()}).optional()}).passthrough(),tL=Y({type:oe("simulator_action_ack"),action:R(),udid:R(),requestId:R().max(128).nullable().optional(),status:R().nullable()}).passthrough(),nL=Y({avd:R().nullable(),serial:R().nullable(),state:R()}),sL=Y({ready:Ye(),runningDevice:R().nullable(),metroReachable:Ye(),mockServerReachable:Ye(),reasons:dt(R())}),iL=Y({type:oe("emulator_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),available:Ye(),note:R().nullable(),devices:dt(nL),readyForMaestro:sL,error:Y({code:R(),message:R()}).optional()}).passthrough(),rL=Y({type:oe("emulator_action_ack"),action:R(),avd:R().nullable().optional(),serial:R().nullable().optional(),requestId:R().max(128).nullable().optional(),status:R().nullable()}).passthrough(),aL=Y({name:R(),state:R(),version:ye().nullable(),isDefault:Ye()}),oL=Y({type:oe("wsl_status_snapshot"),requestId:R().nullable().optional(),generatedAt:R().datetime(),available:Ye(),note:R().nullable(),defaultDistro:R().nullable(),distros:dt(aL),error:Y({code:R(),message:R()}).optional()}).passthrough(),lL=Y({type:oe("wsl_action_ack"),action:R(),distro:R(),requestId:R().max(128).nullable().optional(),status:R().nullable()}).passthrough(),Jx=Y({name:R(),description:R(),source:wt(["global","repo"]),activation:wt(["auto","manual"]),active:Ye(),providers:dt(R()),version:R().nullable(),trustState:wt(["trusted","pending"]).nullable(),communityAuthor:R().nullable(),hash:R().nullable(),installed:R().nullable(),overridesGlobal:Ye().optional(),lastUsed:R().datetime().nullable(),useCount:ye().int().nonnegative().finite(),usedRepos:dt(R())}),cL=Y({name:R(),path:R(),skills:dt(Jx),error:R().nullable()}),uL=Y({type:oe("skills_inventory_snapshot"),requestId:R().max(128).nullable().optional(),generatedAt:R().datetime(),root:R(),global:dt(Jx),globalError:R().nullable().optional(),repos:dt(cL),error:Y({code:R(),message:R()}).optional()}),dL=Y({type:oe("summarize_session_result"),sessionId:R(),summary:R(),truncated:Ye().optional(),requestId:R().max(128).nullable().optional()}).passthrough();Y({type:oe("client_focus_changed"),clientId:R(),sessionId:R(),timestamp:ye()});Y({type:oe("inactivity_warning"),messageId:R(),idleMs:ye().int().positive().finite().max(nl),prefab:R()});Y({type:oe("multi_question_intervention"),toolUseId:R(),questionCount:ye().int().min(2).finite(),reason:oe("multi_question"),timestamp:ye().int().min(0).finite()});Y({type:oe("mcp_servers"),servers:dt(Y({name:R(),status:R()}))});Y({type:oe("plan_started")});Y({type:oe("plan_ready"),allowedPrompts:dt(eo()).optional()});const ew=Y({inputTokens:ye().int().nonnegative(),outputTokens:ye().int().nonnegative(),cacheReadTokens:ye().int().nonnegative(),cacheCreationTokens:ye().int().nonnegative(),costUsd:ye().finite(),turnsBilled:ye().int().nonnegative()}),fL=Y({sessionId:R(),name:R(),cwd:R().optional(),model:R().nullable().optional(),permissionMode:R().optional(),isBusy:Ye().optional(),createdAt:ye().optional(),lastActivityAt:ye().optional(),conversationId:R().nullable().optional(),provider:R().optional(),billingClass:wt(["api-key","subscription","programmatic-credit"]).optional(),capabilities:Ds(R(),Yi()).optional(),worktree:Ye().optional(),repoCwd:R().nullable().optional(),isolation:R().optional(),promptEvaluator:Ye().optional(),promptEvaluatorSkipPattern:Di([R(),Ja()]).optional(),chroxyContextHint:Ye().optional(),sessionPreamble:R().optional(),stdinForwardingDisabled:Ye().optional(),stdinDroppedBytes:ye().int().nonnegative().optional(),stdinDroppedCount:ye().int().nonnegative().optional(),cumulativeUsage:ew.optional(),pendingBackgroundShells:dt(Yx).optional()}).passthrough();Y({type:oe("session_list"),sessions:dt(fL)});Y({type:oe("session_restore_failed"),sessionId:R(),name:R(),provider:R(),cwd:R().optional(),model:R().nullable().optional(),permissionMode:R().nullable().optional(),errorCode:R(),errorMessage:R(),originalHistoryPreserved:Ye(),historyLength:ye().optional()});Y({type:oe("session_persist_failed"),sessionId:R(),name:R().nullable()});Y({type:oe("session_stopped"),sessionId:R().optional(),code:ye().int().optional()});const tw=Y({ready:Ye(),source:wt(["env","oauth","none"]),envVar:R().nullable(),envVars:dt(R()),hint:R(),detail:R(),billingClass:wt(["api-key","subscription","programmatic-credit"]).optional()});Y({type:oe("provider_list"),providers:dt(Y({name:R(),capabilities:Ds(R(),Ye()).optional(),auth:tw.optional()}))});Y({type:oe("auth_bootstrap"),providers:dt(Y({name:R(),capabilities:Ds(R(),Ye()).optional(),auth:tw.optional()})).default([]),slashCommands:dt(Y({name:R(),description:R().optional(),source:R().optional()})).default([]),agents:dt(Y({name:R(),description:R().optional(),source:R().optional()})).default([]),sessionId:R().optional(),tunnelUrl:R().optional()}).passthrough();Y({type:oe("tunnel_url_changed"),url:R(),previousUrl:R().optional()}).passthrough();Y({type:oe("skills_list"),skills:dt(Y({name:R(),description:R().optional(),source:wt(["global","repo"]).optional(),activation:wt(["auto","manual"]).optional(),active:Ye().optional(),version:R().optional(),hashPrefix:R().length(8).regex(/^[0-9a-f]{8}$/).optional(),firstSeen:R().datetime().optional(),lastVerified:R().datetime().optional()}))});Y({type:oe("skill_changed"),skillName:R(),sessionId:R().nullable(),oldHashPrefix:R().length(8).regex(/^[0-9a-f]{8}$/),newHashPrefix:R().length(8).regex(/^[0-9a-f]{8}$/),mode:wt(["warn","block"])});Y({type:oe("skill_activated"),sessionId:R(),skillName:R()});Y({type:oe("skill_deactivated"),sessionId:R(),skillName:R()});Y({type:oe("skill_trust_accepted"),sessionId:R(),skillName:R()});Y({type:oe("skill_trust_request"),skillName:R(),author:R(),source:R(),description:R(),path:R(),sessionId:R().nullable()});Y({type:oe("skill_trust_granted"),sessionId:R(),skillName:R(),author:R()});Y({type:oe("skill_trust_grant_ok"),requestId:R().nullable(),sessionId:R(),skillName:R(),author:R()});Y({type:oe("error"),requestId:R().nullable(),code:oe("INVALID_AUTHOR"),message:R(),actualAuthor:R()});Y({type:oe("session_activity"),sessionId:R(),isBusy:Ye(),lastCost:ye().finite().nullable()});Y({type:oe("session_error"),message:R(),code:R().optional(),category:R().optional(),sessionId:R().optional(),recoverable:Ye().optional(),reason:R().optional(),requestId:R().nullable().optional(),boundSessionId:R().nullable().optional(),boundSessionName:R().nullable().optional(),primaryClientId:R().nullable().optional()}).passthrough();Y({type:oe("session_updated"),sessionId:R(),name:R()});const nw=Y({id:R(),name:R(),description:R(),messageCount:ye(),createdAt:ye(),hasGitSnapshot:Ye()});Y({type:oe("checkpoint_created"),sessionId:R(),checkpoint:nw});Y({type:oe("checkpoint_list"),sessionId:R().nullable(),checkpoints:dt(nw)});Y({type:oe("checkpoint_restored"),checkpointId:R(),newSessionId:R(),name:R()});Y({type:oe("session_warning"),sessionId:R(),name:R(),reason:oe("idle_timeout"),message:R(),remainingMs:ye()});Y({type:oe("session_timeout"),sessionId:R(),name:R(),idleMs:ye()});Y({type:oe("error"),requestId:R().nullable().optional(),code:R().optional(),message:R(),fatal:Ye().optional(),correlationId:R().optional(),details:R().optional()}).passthrough();const hL=Y({type:oe("byok_credentials_status"),requestId:R().nullable().optional(),status:wt(["set","missing"]),source:wt(["env","file","none"]),masked:R().optional(),reason:R().optional(),fileExists:Ye().optional()}).passthrough(),pL=Y({key:R(),provider:R(),label:R(),kind:wt(["api-key","oauth-token"]),status:wt(["set","missing"]),source:wt(["env","store","oauth","none"]),masked:R().optional(),oauth:Ye()}).passthrough(),mL=Y({type:oe("credentials_status"),requestId:R().nullable().optional(),credentials:dt(pL),fileExists:Ye().optional(),fileError:R().nullable().optional()}).passthrough(),gL=Y({type:oe("credential_test_result"),requestId:R().nullable().optional(),key:R(),ok:Ye(),error:R().optional(),model:R().optional(),latencyMs:ye().optional()}).passthrough();Y({type:oe("stdin_dropped_totals"),sessionId:R().nullable(),bytes:ye().int().nonnegative(),count:ye().int().nonnegative(),reason:R(),escalated:Ye()});Y({type:oe("server_error"),category:R().optional(),message:R(),recoverable:Ye()});Y({type:oe("push_token_error"),message:R()});const sw=Ds(R().min(1).max(64),Ye()),iw=Di([Ja(),Y({start:R().regex(/^\d{2}:\d{2}$/),end:R().regex(/^\d{2}:\d{2}$/),timezone:R().min(1).max(64)})]),rw=dt(R().min(1).max(64)).max(64),vL=Ds(R().min(1).max(512),Y({categories:sw.optional(),quietHours:iw.optional(),bypassCategories:rw.optional()}).passthrough()),yL=Y({type:oe("notification_prefs"),requestId:R().nullable().optional(),prefs:Y({categories:sw,devices:vL,quietHours:iw,bypassCategories:rw.optional()}).passthrough()}).passthrough();Y({type:oe("server_shutdown"),reason:wt(["restart","shutdown","crash"]),restartEtaMs:ye().int().nonnegative().finite().max(nl)});Y({type:oe("pong"),serverTs:ye().int().nonnegative().finite().optional()});Y({type:oe("cost_update"),sessionCost:ye().nullable().optional(),totalCost:ye().nullable().optional(),budget:ye().nullable().optional()});Y({type:oe("session_usage"),sessionId:R().optional(),cumulativeUsage:ew});Y({type:oe("session_cost_threshold_crossed"),sessionId:R().optional(),costUsd:ye().finite(),thresholdUsd:ye().finite().nonnegative()});Y({type:oe("budget_warning"),sessionCost:ye(),budget:ye(),percent:ye(),message:R()});Y({type:oe("budget_exceeded"),sessionCost:ye(),budget:ye(),percent:ye(),message:R()});const bL=tf.extend({type:oe("billing_canary")});Y({type:oe("budget_resume_ack"),sessionId:R().optional(),wasPaused:Ye(),requestId:R().max(128).optional()}).passthrough();Y({type:oe("monthly_budget"),month:R(),spentUsd:ye().finite().nonnegative(),turnsBilled:ye().int().nonnegative(),budgetUsd:ye().finite().nonnegative().nullable(),warningPercent:ye().finite(),percent:ye().finite().nullable(),warning:Ye(),exceeded:Ye(),justWarned:Ye().optional(),justExceeded:Ye().optional()});const ig=Y({taskId:R(),prompt:R(),status:wt(["pending","running","completed","failed"]),createdAt:ye(),updatedAt:ye(),result:R().nullable(),error:R().nullable(),cwd:R().optional()});Y({type:oe("web_feature_status"),available:Ye(),remote:Ye(),teleport:Ye()});Y({type:oe("web_task_created"),task:ig});Y({type:oe("web_task_updated"),task:ig});Y({type:oe("web_task_error"),taskId:R().nullable().optional(),message:R(),code:R().max(64).optional(),boundSessionId:R().nullable().optional(),boundSessionName:R().nullable().optional()});Y({type:oe("web_task_list"),tasks:dt(ig)});Y({type:oe("extension_message"),provider:R().min(1),subtype:R().min(1),data:Yi(),sessionId:R().optional()});const _L=Y({type:oe("evaluate_draft_result"),requestId:R().nullable(),verdict:wt(["forward","rewrite","clarify"]),rewritten:R().nullable().optional(),clarification:R().nullable().optional(),reasoning:R(),error:Xo().optional()}),SL=Y({type:oe("evaluate_draft_result"),requestId:R().nullable(),error:Y({code:R(),message:R(),status:ye().int().optional()}),verdict:Xo().optional(),rewritten:Xo().optional(),clarification:Xo().optional(),reasoning:Xo().optional()});Di([_L,SL]);Y({type:oe("evaluator_rewrite"),sessionId:R(),originalDraft:R(),rewritten:R(),reasoning:R(),evaluatorIterationId:R()});Y({type:oe("evaluator_clarify"),sessionId:R(),originalDraft:R(),clarification:R(),reasoning:R(),evaluatorIterationId:R(),evaluatorIteration:ye().int().min(1).max(10)});const E_=Y({path:R(),status:wt(["modified","added","deleted","renamed","copied","unknown"])});Y({type:oe("git_status_result"),branch:R().nullable(),staged:dt(E_),unstaged:dt(E_),untracked:dt(R()),error:R().nullable()});Y({type:oe("git_branches_result"),branches:dt(Y({name:R(),isCurrent:Ye(),isRemote:Ye()})),currentBranch:R().nullable(),error:R().nullable()});Y({type:oe("diff_result"),files:dt(Y({path:R(),status:wt(["modified","added","deleted","renamed","untracked"]),additions:ye(),deletions:ye(),hunks:dt(Y({header:R(),lines:dt(Y({type:wt(["context","addition","deletion"]),content:R()}))}))})),error:R().nullable()});Y({type:oe("file_content"),path:R().nullable(),content:R().nullable(),language:R().nullable(),size:ye().nullable(),truncated:Ye(),error:R().nullable(),requestId:R().max(200).optional()});Y({type:oe("directory_listing"),path:R().nullable(),parentPath:R().nullable(),entries:dt(Y({name:R(),isDirectory:Ye()})),error:R().nullable()});Y({type:oe("write_file_result"),path:R().nullable(),error:R().nullable()});const xL=Y({name:R(),kind:R(),file:R(),line:ye(),exported:Ye()}),wL=Y({type:oe("symbols_snapshot"),path:R().nullable(),symbols:dt(xL),truncated:Ye(),error:R().nullable()}),kL=Y({type:oe("symbol_location"),symbol:R(),file:R().nullable(),line:ye().nullable(),error:R().nullable()}),aw=Y({file:R(),line:ye(),column:ye(),text:R()}),CL=Y({type:oe("code_search_results"),query:R(),results:dt(aw),truncated:Ye(),error:R().nullable()}),EL=Y({type:oe("references_result"),symbol:R(),results:dt(aw),truncated:Ye(),error:R().nullable()}),ow=wt(["running","stopped","error"]),lw=Y({id:R(),name:R(),cwd:R(),image:R(),containerId:R(),containerUser:R(),containerCliPath:R(),status:ow,sessions:dt(R()),createdAt:R(),memoryLimit:R().nullable(),cpuLimit:R().nullable(),compose:R().nullable(),composeProject:R().nullable(),primaryService:R().nullable().optional(),services:dt(Y({name:R(),status:R(),primary:Ye()})).optional(),snapshots:dt(Y({id:R(),name:R(),image:R(),createdAt:R()})).optional()});Y({type:oe("environment_created"),environmentId:R(),name:R(),status:ow});Y({type:oe("environment_destroyed"),environmentId:R()});Y({type:oe("environment_error"),error:R(),environmentId:R().optional(),code:R().optional()});Y({type:oe("environment_info"),environment:lw});Y({type:oe("environment_list"),environments:dt(lw)});const NL=["session_start","session_end","subagent_start","subagent_stop","notification","post_tool_use","user_prompt_submit","stop"],jL=15778368e5,AL=41024448e5,N_=32,RL=Di([R().max(4096),ye().finite(),Ye(),Ja()]),TL=Ds(R().min(1).max(128),RL).refine(e=>Object.keys(e).length<=N_,{message:`data must have at most ${N_} keys`});Y({source:R().min(1).max(64).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/,"source must be alphanumeric with ._- separators"),project:R().min(1).max(256).optional(),sessionId:R().min(1).max(256).optional(),type:wt(NL),data:TL.optional(),ts:ye().int().min(jL).max(AL)}).strict();const IL=["rate limit","usage limit","quota","overloaded"];function ML(e){if(typeof e!="string")return!1;const t=e.toLowerCase();for(const n of IL)if(t.includes(n))return!0;return!1}const cw=2,DL={desktop:["console","environment_panel","agent_monitor","diff_viewer","voice_input"]},yf="claude-tui",j_="user-shell",LL=Object.freeze({cols:120,rows:30});function OL(e,t,n,i){const o={shouldDispatch:!1},d=e.messageType??e.type;if(typeof d!="string"||d.length===0)return o;const h=d;if(typeof e.content!="string"||typeof e.timestamp!="number"||h==="user_input"&&!n)return o;const l=typeof e.messageId=="string"?e.messageId:void 0;if(n&&dE(i,{messageType:h,messageId:l,content:e.content,timestamp:e.timestamp,tool:typeof e.tool=="string"?e.tool:void 0,options:e.options}))return o;const u={id:l||fn(h),type:h,content:e.content,tool:typeof e.tool=="string"?e.tool:void 0,options:e.options,timestamp:e.timestamp,...typeof e.code=="string"?{code:e.code}:{},...h==="error"&&typeof e.code=="string"&&(e.code==="resume_unknown"||e.code==="resume_unknown_exhausted")&&typeof e.attemptedResumeId=="string"?(()=>{const g=e.attemptedResumeId.trim();return g.length===0?{}:{attemptedResumeId:g.length>256?g.slice(0,256):g}})():{}};let f=!1,v=null;return h==="error"&&ML(e.content)&&(f=!0,v=e.content),{shouldDispatch:!0,chatMessage:u,isRateLimitError:f,errorContent:v}}function PL(e,t,n,i){const d=ht(e,"sessionId")||t,h=typeof e.tool=="string"?e.tool:void 0,l=h||"tool",f=ht(e,"messageId")||fn("tool"),v=typeof e.toolUseId=="string"?e.toolUseId:void 0,g=typeof e.serverName=="string"?e.serverName:void 0,S=y=>y;if(n&&i.some(y=>y.id===f))return{shouldDispatch:!1,sessionId:d,chatMessage:null,toolName:l,activeTool:null,applyToActiveTools:S};const w=typeof e.timestamp=="number"&&Number.isFinite(e.timestamp)?e.timestamp:Date.now(),E={id:f,type:"tool_use",content:e.input?JSON.stringify(e.input):h||"",tool:h,toolUseId:v,serverName:g,timestamp:w},x=v?{toolUseId:v,tool:l,...g!==void 0?{serverName:g}:{},...e.input!==void 0?{input:e.input}:{},startedAt:E.timestamp}:null;return{shouldDispatch:!0,sessionId:d,chatMessage:E,toolName:l,activeTool:x,applyToActiveTools:y=>!x||y.some(b=>b.toolUseId===x.toolUseId)?y:[...y,x]}}function BL(e,t){if(typeof e.toolUseId!="string"||!e.toolUseId)return null;const n=e.toolUseId,o=ht(e,"sessionId")||t,d=typeof e.result=="string"?e.result:"",h=typeof e.truncated=="boolean"?e.truncated:!1,l=Array.isArray(e.images)?e.images:void 0,u={toolResult:d,toolResultTruncated:h};return l?.length&&(u.toolResultImages=l),{sessionId:o,toolUseId:n,patch:u,resultText:d,applyTo:f=>{const v=f.findIndex(S=>S.type==="tool_use"&&S.toolUseId===n);if(v===-1)return f;const g=[...f];return g[v]={...g[v],...u},g},applyToActiveTools:f=>{const v=f.filter(g=>g.toolUseId!==n);return v.length===f.length?f:v}}}const A_=1024*1024,$L="...[truncated]";function zL(e,t){if(typeof e.toolUseId!="string"||!e.toolUseId||typeof e.partialJson!="string")return null;const n=e.toolUseId,i=e.partialJson;return{sessionId:ht(e,"sessionId")||t,toolUseId:n,partialJson:i,applyTo:h=>{const l=h.findIndex(w=>w.type==="tool_use"&&w.toolUseId===n);if(l===-1)return h;const u=h[l],f=u.toolInputPartial||"";if(u.toolInputPartialTruncated||f.endsWith($L))return h;let v,g=!1;if(f.length+i.length>A_){const w=A_-f.length;v=f+i.slice(0,Math.max(0,w)),g=!0}else v=f+i;const S=[...h];return S[l]={...u,toolInputPartial:v,...g?{toolInputPartialTruncated:!0}:null},S}}}function R_(e,t,n){const i=typeof e.messageId=="string"?e.messageId:fn("msg"),o=typeof e.sessionId=="string"?e.sessionId:t,d=n.find(f=>f.id===i),{resolvedId:h,remap:l}=hN(d,i);if(d&&d.type==="response")return{sessionId:o,streamingMessageId:h,isNewMessage:!1,newMessage:null,remap:null};const u={id:h,type:"response",content:"",timestamp:Date.now()};return{sessionId:o,streamingMessageId:h,isNewMessage:!0,newMessage:u,remap:l??null}}function UL(e,t,n){if(t.postPermissionSplits.has(e)){const h=`${e}-post-${n()}`;return{kind:"permission-split",deltaId:e,newId:h}}if(t.deltaIdRemaps.has(e))return{kind:"remap",deltaId:t.deltaIdRemaps.get(e)};const{resolvedMessages:i,targetForSuffix:o}=t.resolveMessages(),d=i.find(h=>h.id===e);if(d&&d.type!=="response"){const h=`${e}-response`,l=!i.some(u=>u.id===h);return{kind:"suffix",deltaId:h,remapKey:e,suffixedId:h,targetForSuffix:o,needsAppend:l}}return{kind:"passthrough",deltaId:e}}function qL(e,t){if(typeof e.messageId!="string"||typeof e.delta!="string")return;const n=e.messageId;let i=n;const o=ht(e,"sessionId")||t.activeSessionId;e.delta.length>0&&t.appendTerminalDelta(e.delta),typeof i=="string"&&!t.postPermissionSplits.has(i)&&!t.deltaIdRemaps.has(i)&&!t.pendingDeltas.has(i)&&t.reorderEmptyResponseSlot(i,o);const d=()=>{const u=o?t.getSessionMessages(o):null,f=u||(t.activeSessionId?t.getSessionMessages(t.activeSessionId):null)||null,v=u?o:t.activeSessionId;return{sessionMessages:f,effectiveSessionId:v}},h=UL(i,{postPermissionSplits:t.postPermissionSplits,deltaIdRemaps:t.deltaIdRemaps,resolveMessages:()=>{const{sessionMessages:u,effectiveSessionId:f}=d();return{resolvedMessages:u??t.getFlatMessages(),targetForSuffix:u?f:null}}},Date.now);if(h.kind==="permission-split"){t.postPermissionSplits.delete(h.deltaId),t.deltaIdRemaps.set(h.deltaId,h.newId);const u={id:h.newId,type:"response",content:"",timestamp:Date.now()};t.appendResponseSlot(o,u),i=h.newId}else h.kind==="remap"?i=h.deltaId:h.kind==="suffix"&&(t.deltaIdRemaps.set(h.remapKey,h.suffixedId),h.needsAppend&&t.appendResponseSlot(h.targetForSuffix,{id:h.suffixedId,type:"response",content:"",timestamp:Date.now()},{onlyIfAbsent:!0}),i=h.deltaId);{const{sessionMessages:u,effectiveSessionId:f}=d();if(!(f?t.replayingSessions.has(f):!1)){const g=u??t.getFlatMessages(),S=u?f:null,w=g.findIndex(E=>E.id===i);if(w>=0){const E=g[w],x=t.pendingDeltas.get(i)?.delta||"",m=E.type==="response"&&(E.content.length>0||x.length>0);let y=!1;if(m){for(let b=w+1;b<g.length;b++)if(g[b].type==="tool_use"){y=!0;break}}if(y){const b=E.type==="response"?E.content+x:"",k=b.replace(/\s+$/,"").replace(/[)\]}"'’”»›」』)]+$/,""),j=k.charAt(k.length-1),T=j==="."||j==="!"||j==="?"||j==="."||j==="!"||j==="?"||j==="。",D=/\n\s*$/.test(b);!T&&!D&&(y=!1)}if(y){const b=E.type==="response"?E.content+x:"",_=e.delta,j=/^[A-Za-z0-9_]/.test(_)?b.match(/[A-Za-z0-9_]+$/):null;let T="";if(j&&j[0].length>0){T=j[0];let L=T.length;if(x.length>0){const q=Math.min(L,x.length),H=x.slice(0,x.length-q);H.length>0?t.pendingDeltas.set(i,{sessionId:o,delta:H}):t.pendingDeltas.delete(i),L-=q}L>0&&E.type==="response"&&E.content.length>0&&t.peelSlotContent(S,i,L)}const D=`${i}-cont-${Date.now()}`;t.deltaIdRemaps.set(n,D);const I={id:D,type:"response",content:"",timestamp:Date.now()};t.appendResponseSlot(S,I),i=D,T.length>0&&t.pendingDeltas.set(D,{sessionId:o,delta:T})}}}}const l=t.pendingDeltas.get(i);t.pendingDeltas.set(i,{sessionId:o,delta:(l?.delta||"")+e.delta}),t.scheduleFlush()}function HL(e,t){const n=typeof e.sessionId=="string"?e.sessionId:t,i=ht(e,"messageId");return{sessionId:n,messageId:i}}function FL(e,t){const n=e.usage,i=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null,o=f=>typeof f=="number"&&Number.isFinite(f)?f:0,d=i?{inputTokens:o(i.input_tokens),outputTokens:o(i.output_tokens),cacheCreation:o(i.cache_creation_input_tokens),cacheRead:o(i.cache_read_input_tokens)}:null,h=typeof e.cost=="number"?e.cost:null,l=typeof e.duration=="number"?e.duration:null;return{sessionId:ht(e,"sessionId")||t,contextUsage:d,lastResultCost:h,lastResultDuration:l}}function uw(e){return{data:typeof e.data=="string"?e.data:""}}function KL(e){return{model:Vs(e,"model")}}function WL(e,t){return{sessionId:on(e,t),patch:{activeModel:KL(e).model}}}function GL(e){const t={claudeReady:!0,stoppedAt:null,stoppedCode:null};if(Array.isArray(e?.backgroundTasks)){t.transcriptBackgroundTasks=e.backgroundTasks.filter(i=>!!i&&typeof i=="object"&&typeof i.toolUseId=="string"&&["bash","agent","monitor"].includes(i.kind)&&typeof i.description=="string"&&Number.isFinite(i.startedAt));const n=e.scheduledWakeup;t.scheduledWakeup=n&&typeof n.at=="number"&&typeof n.reason=="string"?{at:n.at,reason:n.reason}:null}return t}function VL(){return{isIdle:!0,streamingMessageId:null,activeTools:[]}}function YL(){return{isIdle:!1}}const ZL=new Set(["default","high","max"]);function XL(e){const t=Vs(e,"level")||"default";return{level:ZL.has(t)?t:"default"}}function dw(e,t){return!!e.sessionId&&!!t&&e.sessionId!==t}function QL(e,t){return dw(e,t)||!Array.isArray(e.commands)?null:{commands:e.commands}}function JL(e,t){return dw(e,t)||!Array.isArray(e.agents)?null:{agents:e.agents}}function eO(e){return Array.isArray(e.providers)?{providers:e.providers}:null}function tO(e){return{files:ms(e,"files")}}function nO(e){if(!Array.isArray(e.models))return{models:[],defaultModelId:null};const t=e.models.map(i=>{if(typeof i=="object"&&i!==null){const o=V3.safeParse(i);if(o.success){const{id:d,label:h,fullId:l,contextWindow:u}=o.data;if(d.trim()!==""&&h.trim()!==""&&l.trim()!==""){const f={id:d,label:h,fullId:l};return typeof u=="number"&&u>0&&(f.contextWindow=u),f}}}if(typeof i=="string"&&i.trim().length>0){const o=i.trim();return{id:o,label:o.charAt(0).toUpperCase()+o.slice(1),fullId:o}}return null}).filter(i=>i!==null),n=Vs(e,"defaultModel");return{models:t,defaultModelId:n}}function sO(e,t){const n=ms(e,"servers");return{sessionId:ht(e,"sessionId")||t,patch:{mcpServers:n}}}function iO(e){const t=ht(e,"sessionId"),n=e_(e,"costUsd",0),i=e_(e,"thresholdUsd",0);return{sessionId:t,patch:{costThresholdWarning:{costUsd:n,thresholdUsd:i,dismissedAt:null}}}}function rO(e){const t=yL.safeParse(e);if(!t.success)return{notificationPrefs:null,issues:t.error.issues};const n=t.data.prefs,i=n.bypassCategories;return{notificationPrefs:{categories:n.categories,devices:n.devices,quietHours:n.quietHours,...Array.isArray(i)?{bypassCategories:i}:{}},issues:null}}function aO(e,t){if(!e||e==="pending")return null;let n=e;for(const[i,o]of t)if(o===e){n=i;break}return{serverStreamId:n}}function oO(e){switch(e){case"ios":return"iOS";case"android":return"Android";case"web":return"Web";case"desktop":return"Desktop";default:return e}}function lO(e,t=Date.now()){const n=t-e;if(n<0)return"just now";const i=Math.floor(n/6e4);if(i<1)return"just now";if(i<60)return`${i} min ago`;const o=Math.floor(i/60);if(o<24)return`${o} hr ago`;const d=Math.floor(o/24);if(d<30)return`${d} day${d===1?"":"s"} ago`;const h=Math.floor(d/30);return h<12?`${h} mo ago`:`${Math.floor(h/12)} yr ago`}function cO(e){switch(e){case 1e3:return null;case 1006:return"Connection lost — check your network";case 1008:return"Encryption failed — check that your app is up to date";case 4008:return"Connection dropped — the server was overwhelmed, reconnecting";default:return"Connection failed — check your network and server status"}}function uO(e){return e.name==="AbortError"?"Server not responding — check your network":e.message?.startsWith("HTTP 4")?"Server rejected the connection — check your token":e.message?.startsWith("HTTP 5")?"Server error — the server may be restarting":e.message?.startsWith("HTTP ")?`Server unreachable (${e.message})`:"Could not reach server — check your network"}class fw{buf;capacity;head=0;size=0;constructor(t=200){this.capacity=Math.max(1,Math.floor(t)),this.buf=new Array(this.capacity)}get count(){return this.size}add(t){!Number.isFinite(t)||t<0||(this.buf[this.head]=t,this.head=(this.head+1)%this.capacity,this.size<this.capacity&&this.size++)}summary(){if(this.size===0)return{count:0,p50:null,p95:null};const t=this.buf.slice(0,this.size).sort((i,o)=>i-o),n=i=>t[Math.min(t.length-1,Math.max(0,Math.ceil(i*t.length)-1))];return{count:this.size,p50:n(.5),p95:n(.95)}}}function dO(e){const t=e.pongRecvAt-e.pingSentAt;if(!(t>0)||typeof e.serverTs!="number"||!Number.isFinite(e.serverTs))return{rttMs:Math.max(0,t),uplinkMs:null,downlinkMs:null};const i=Math.min(e.pongRecvAt,Math.max(e.pingSentAt,e.serverTs))-e.pingSentAt,o=t-i;return{rttMs:t,uplinkMs:i,downlinkMs:o}}const T_=new Map;function fO(e){const t=(T_.get(e)??0)+1;return T_.set(e,t),t}const hO=16,Cp=33,I_=100,Ep=60,M_=400;function pO(e){if(e==null||!Number.isFinite(e))return Cp;if(e<=Ep)return hO;if(e>=M_)return I_;const t=(e-Ep)/(M_-Ep);return Math.round(Cp+t*(I_-Cp))}const mO=.3;class gO{_value=null;_alpha;constructor(t=mO){this._alpha=t}get value(){return this._value}update(t){return this._value=this._value===null?t:this._alpha*t+(1-this._alpha)*this._value,this._value}reset(){this._value=null}}const vO={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function yO(e){const{getEwmaRtt:t,applyDeltas:n,scheduler:i=vO}=e,o=new Map;let d=null,h=null;function l(){return h??pO(t())}function u(){if(o.size===0)return;const w=new Map(o);o.clear(),n(w)}function f(){d!=null&&(i.clearTimeout(d),d=null),u()}function v(){d==null&&(d=i.setTimeout(()=>{d=null,u()},l()))}function g(){d!=null&&(i.clearTimeout(d),d=null),o.clear()}function S(w){h=w}return{pendingDeltas:o,schedule:v,flushNow:f,clear:g,setIntervalOverride:S,currentIntervalMs:l,dispose:g}}function bO(e,t){const n=nx(e);n&&t.setState({availablePermissionModes:n})}function _O(e,t){const n=ej(e,t.getSessions());n&&t.setState({sessions:n})}function SO(e,t){const n=on(e,t.getActiveSessionId());n&&t.hasSession(n)&&t.updateSession(n,()=>YL())}function xO(e,t){const n=on(e,t.getActiveSessionId()),i=VL();n&&t.hasSession(n)?t.updateSession(n,()=>i):t.applyNoSessionFallback?.(i)}function wO(e,t){const{mode:n}=Ej(e),i=on(e,t.getActiveSessionId());i&&t.hasSession(i)?t.updateSession(i,()=>({permissionMode:n})):t.applyNoSessionFallback?.({permissionMode:n}),i&&t.clearPendingPermissionModeRequests?.(i),t.setState({pendingPermissionConfirm:null})}function kO(e,t){const{systemMessage:n}=lj(),i=on(e,t.getActiveSessionId());i&&t.hasSession(i)?t.updateSession(i,o=>({messages:[...o.messages,n]})):t.addMessage(n)}function CO(e,t){const{warningMessage:n,systemMessage:i}=aj(e);t.alert("Budget Warning",n);const o=on(e,t.getActiveSessionId());o&&t.hasSession(o)?t.updateSession(o,d=>({messages:[...d.messages,i]})):t.addMessage(i)}function EO(e,t){const{chatMessage:n}=Gj(e),i=t.getActiveSessionId();i&&t.hasSession(i)?t.updateSession(i,o=>({messages:[...o.messages,n]})):t.addMessage(n)}function NO(e,t){const n=dj(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,()=>n.patch),n.sessionId&&t.notifyPlanReady?.(n.sessionId)}function jO(e,t){const n=Kj(e);t.setState(n),t.applyShutdownNotification?.(n)}function AO(e,t){const{conversations:n}=dA(e);t.setState({conversationHistory:n,conversationHistoryLoading:!1}),t.applyConversationsListExtras?.(n)}function RO(e,t){const n=zj(e);n&&t.switchToRestoredSession(n.newSessionId)}function TO(e,t){const{results:n,shouldApply:i}=LA(e,t.getSearchQuery());i&&(t.setState({searchResults:n,searchLoading:!1}),t.applySearchResultsExtras?.(n))}function IO(e,t){const{systemMessage:n}=cj(e);if(!n)return;const i=on(e,t.getActiveSessionId());i&&t.hasSession(i)?t.updateSession(i,o=>({messages:[...o.messages,n]})):t.addMessage(n)}function MO(e,t){const{sessionId:n,conversationId:i}=uA(e);n&&t.hasSession(n)&&t.updateSession(n,()=>({conversationId:i}))}function DO(e,t){const{sessionId:n,rules:i}=Cj(e),o=n||t.getActiveSessionId();o&&t.hasSession(o)&&t.updateSession(o,()=>({sessionRules:i}))}function LO(e,t){const n=Nj(e);n&&t.setState({pendingPermissionConfirm:n})}function OO(e,t){const n=wA(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,i=>{const o=n.applyTo(i.activeAgents??[]);return o===i.activeAgents?{}:{activeAgents:o}})}function PO(e,t){const n=kA(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,i=>{const o=n.applyTo(i.activeAgents??[]);return o===i.activeAgents?{}:{activeAgents:o}})}function BO(e,t){const n=CA(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,i=>{const o=n.applyTo(i.messages);return o===i.messages?{}:{messages:o}})}function $O(e,t){const n=rx(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,i=>{const o=n.applyTo(i.pendingBackgroundShells??[]);return o===i.pendingBackgroundShells?{}:{pendingBackgroundShells:o}})}function D_(e){return(t,n)=>{const i=e(t,n.getActiveSessionId());i&&i.sessionId&&n.hasSession(i.sessionId)&&n.updateSession(i.sessionId,o=>{const d=i.applyTo(o.queuedMessages??[]).queuedMessages,h=d===o.queuedMessages?{}:{queuedMessages:d},l=i.reconcileFakedFreshTurn?.({streamingMessageId:o.streamingMessageId??null,messages:o.messages,pendingClientMessageId:o.pendingClientMessageId??null});return l&&("streamingMessageId"in l&&(h.streamingMessageId=l.streamingMessageId),"pendingClientMessageId"in l&&(h.pendingClientMessageId=l.pendingClientMessageId),l.messages&&(h.messages=l.messages)),h})}}function mc(e){return(t,n)=>{const{sessionId:i,patch:o}=e(t,n.getActiveSessionId());i&&n.hasSession(i)&&n.updateSession(i,()=>o)}}function zO(e,t){const n=hj(e,t.getActiveSessionId());n&&n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,()=>n.patch)}function UO(e,t){const{sessionId:n,patch:i}=iO(e);n&&t.hasSession(n)&&t.updateSession(n,()=>i)}function qO(e,t){const n=bj(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,i=>n.applyTo(i.devPreviews??[]))}function HO(e,t){const n=_j(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,i=>n.applyTo(i.devPreviews??[]))}function FO(e,t){t.setState(DA(e))}function KO(e,t){const{tasks:n}=MA(e);t.setState({webTasks:n})}function WO(e,t){const n=QL(e,t.getActiveSessionId());n&&(t.setState({slashCommands:n.commands}),t.syncSecondaryInventory?.("slashCommands",n.commands))}function GO(e,t){const n=JL(e,t.getActiveSessionId());n&&(t.setState({customAgents:n.agents}),t.syncSecondaryInventory?.("customAgents",n.agents))}function VO(e,t){const n=eO(e);if(!n)return;const i=t.mapProviderList?t.mapProviderList(n.providers):n.providers;t.setState({availableProviders:i})}function YO(e,t){if(!t.addServerError)return!1;const n=rA(e);t.addServerError(n.systemMessage.content,{category:"session",recoverable:!0,...n.sessionId?{sessionId:n.sessionId}:{}}),console.warn("[session_restore_failed]",{sessionId:n.sessionId,name:n.name,provider:n.provider,cwd:n.cwd,model:n.model,permissionMode:n.permissionMode,errorCode:n.errorCode,errorMessage:n.errorMessage,historyLength:n.historyLength})}function ZO(e,t){if(!t.addServerError)return!1;const n=aA(e);t.addServerError(n.message,{category:"session",recoverable:!0,...n.sessionId?{sessionId:n.sessionId}:{}}),console.warn("[session_persist_failed]",{sessionId:n.sessionId,name:n.name})}function XO(e,t){const{sessionId:n,patch:i}=sj(e,t.getActiveSessionId());n&&t.hasSession(n)&&t.updateSession(n,()=>i);const o=i.stoppedCode,d=o!=null&&o!==0?`Session stopped. (exit ${o})`:"Session stopped.";t.addInfoNotification?.(d)}function QO(e,t){const{sessionId:n,primaryClientId:i}=Zj(e);t.setPrimaryClientId?.(i),n&&t.hasSession(n)?t.updateSession(n,()=>({primaryClientId:i})):(!n||n==="default")&&t.setState({primaryClientId:i})}function JO(e,t){if(!t.getMyClientId)return!1;const n=Xj(e,t.getMyClientId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,()=>({sessionRole:n.role,primaryClientId:n.primaryClientId}))}function e4(e,t){if(!t.getFollowMode||!t.getMyClientId||!t.switchSession)return!1;const n=cA(e);n&&t.getFollowMode()&&n.clientId!==t.getMyClientId()&&n.sessionId!==t.getActiveSessionId()&&t.hasSession(n.sessionId)&&t.switchSession(n.sessionId)}function t4(e,t){if(!Array.isArray(e.models))return;const{models:n,defaultModelId:i}=nO(e),o=t.extendModelsPatch?t.extendModelsPatch(e):{};t.setState({...o,availableModels:n,defaultModelId:i})}function n4(e,t){const n=jA(e,t.getActiveSessionId());n.sessionId&&t.hasSession(n.sessionId)&&t.updateSession(n.sessionId,()=>n.patch);const i=typeof e.totalCost=="number"?e.totalCost:null,o=typeof e.budget=="number"?e.budget:null;t.setCostUpdate?.(i,o)}function s4(e,t){if(!t.applyRotatedTunnelUrl)return!1;const n=Dj(e);n&&t.applyRotatedTunnelUrl(n.url,n.previousUrl)}function i4(e,t){const n=Mj(e);n.tunnelUrl&&t.applyRotatedTunnelUrl?.(n.tunnelUrl,null);const i=t.mapProviderList?t.mapProviderList(n.providers):n.providers;t.setState({availableProviders:i});const o=t.getActiveSessionId();n.sessionId&&o&&n.sessionId!==o||(t.setState({slashCommands:n.slashCommands}),t.syncSecondaryInventory?.("slashCommands",n.slashCommands),t.setState({customAgents:n.agents}),t.syncSecondaryInventory?.("customAgents",n.agents))}function r4(e,t){const{notificationPrefs:n,issues:i}=rO(e);if(!n){console.warn("notification_prefs: invalid payload from server",i);return}t.setState({notificationPrefs:n})}const hw=Symbol("dispatch-decline");function a4(e,t){return typeof e.getCallback!="function"?hw:e.getCallback(t)}function Hi(e,t){return(n,i)=>{const o=a4(i,e);if(o===hw)return!1;o&&o(t(n))}}function L_(e,t){const{task:n}=RA(e);n&&t.updateState(i=>{const o=i.webTasks??[];return{webTasks:TA(o,n)}})}function o4(e,t){const n=Bj(e,t.getCheckpoints(),t.getActiveSessionId());n&&(t.setState({checkpoints:n}),t.syncSecondaryCheckpoints?.({kind:"append",checkpoint:e.checkpoint}))}function l4(e,t){const n=$j(e,t.getActiveSessionId());n&&(t.setState({checkpoints:n}),t.syncSecondaryCheckpoints?.({kind:"replace",checkpoints:n}))}function c4(e,t){const n=OA(e,t.getActiveSessionId());if(!n)return;const{sessionId:i,chatMessage:o,questionText:d}=n;i&&t.hasSession(i)?t.updateSession(i,h=>({messages:[...h.messages,o]})):t.addMessage(o),i&&t.pushSessionNotification(i,"question",d)}function u4(e,t){const n=pj(e,t.getActiveSessionId());if(!n)return;const i=n.sessionId;!i||!t.hasSession(i)||t.updateSession(i,o=>{const d=o.interventions??[],{interventions:h,isFirst:l}=mj(n,d);return h===d?{}:l?{interventions:h,messages:[...o.messages,{id:fn("system"),type:"system",content:"chroxy intercepted a multi-question form and asked the agent to break it into single questions.",timestamp:Date.now()}]}:{interventions:h}})}function d4(e,t){t.appendTerminalData(uw(e).data)}function f4(e,t){t.appendTerminalData(uw(e).data)}function h4(e,t){const n=e;typeof n.data=="string"&&(typeof n.sessionId!="string"||n.sessionId!==t.getActiveSessionId()||t.appendTerminalData(n.data))}function p4(){return{available_permission_modes:bO,session_updated:_O,agent_busy:SO,agent_idle:xO,permission_mode_changed:wO,budget_warning:CO,plan_ready:NO,rate_limited:EO,server_shutdown:jO,conversations_list:AO,checkpoint_restored:RO,search_results:TO,budget_resumed:kO,budget_resume_ack:IO,conversation_id:MO,permission_rules_updated:DO,confirm_permission_mode:LO,agent_spawned:OO,agent_completed:PO,agent_event:BO,background_work_changed:$O,plan_started:mc(uj),inactivity_warning:zO,mcp_servers:mc(sO),slash_commands:WO,agent_list:GO,provider_list:VO,session_stopped:XO,session_restore_failed:YO,session_persist_failed:ZO,primary_changed:QO,session_role:JO,client_focus_changed:e4,available_models:t4,cost_update:n4,tunnel_url_changed:s4,auth_bootstrap:i4,session_usage:mc(AA),session_context:mc(sA),model_changed:mc(WL),session_cost_threshold_crossed:UO,dev_preview:qO,dev_preview_stopped:HO,web_feature_status:FO,web_task_list:KO,notification_prefs:r4,directory_listing:Hi("directoryListing",e=>ox(e)),file_listing:Hi("fileBrowser",e=>lx(e)),file_content:Hi("fileContent",e=>cx(e)),write_file_result:Hi("fileWrite",e=>hA(e)),diff_result:Hi("diff",e=>{const t=ux(e);return{files:t.files,error:t.error}}),git_status_result:Hi("gitStatus",e=>{const t=dx(e);return{branch:t.branch,staged:t.staged,unstaged:t.unstaged,untracked:t.untracked,error:t.error}}),git_branches_result:Hi("gitBranches",e=>{const t=SA(e);return{branches:t.branches,currentBranch:t.currentBranch,error:t.error}}),git_stage_result:Hi("gitStage",e=>s_(e)),git_unstage_result:Hi("gitStage",e=>s_(e)),git_commit_result:Hi("gitCommit",e=>xA(e)),web_task_created:L_,web_task_updated:L_,message_queued:D_(vj),message_dequeued:D_(yj),user_question:c4,multi_question_intervention:u4,checkpoint_created:o4,checkpoint_list:l4,raw:d4,raw_background:f4,terminal_output:h4}}function m4(e,t,n){const i=t.type;if(typeof i!="string"||!Object.prototype.hasOwnProperty.call(e,i))return!1;const o=e[i];return o(t,n)!==!1}const $d=5,g4=10,Uc=[1e3,2e3,3e3,5e3,8e3];function pw(e,t=Uc){const n=Math.min(Math.max(e,0),t.length-1);return t[n]??0}const v4={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function mw(e){return e+Math.floor(Math.random()*e*.5)}function y4(e){const{attempt:t,maxRetries:n=$d,retryDelays:i=Uc,resolveEndpoint:o,probe:d,isStale:h,openSocket:l,onRestarting:u,onProbeFailed:f,onRestartGaveUp:v,onProbeGaveUp:g,onTerminalDown:S,scheduleRetry:w,jitter:E=mw}=e,x=o(t);if(x===null)return Promise.resolve();function m(y){return E(pw(y,i))}return d(x).then(y=>{if(!h()){if(y.kind==="ok"){l(x);return}if(y.kind==="terminal_down"){if(S){S({reason:y.reason});return}f(y.reason),t<n?w(t+1,m(t)):g();return}if(y.kind==="restarting"){u({restartEtaMs:y.restartEtaMs}),t<n?w(t+1,m(t)):v();return}f(y.reason),t<n?w(t+1,m(t)):g()}},()=>{h()||(f("Could not reach server"),t<n?w(t+1,m(t)):g())})}function b4(e){const{nextRung:t,reconnect:n,isStale:i,retryDelays:o=Uc,scheduler:d=v4,jitter:h=mw,maxRung:l,onGaveUp:u}=e;let f=!1;function v(){if(f)return!1;const g=t();if(g>=l)return f=!0,u&&u(),!1;f=!0;const S=h(pw(g,o));return d.setTimeout(()=>{i()||n()},S),!0}return{schedule:v,get scheduled(){return f}}}const _4=15e3,S4=5e3,x4=1e4,w4=3e3,k4={setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function C4(e){return e<200?"good":e<500?"fair":"poor"}function E4(e){const{wsSend:t,rttSmoother:n,onPongQuality:i,openReadyState:o=1,now:d=()=>Date.now(),scheduler:h=k4,onLatencyLog:l}=e;let u=null,f=null,v=null,g=0;function S(){u&&(h.clearInterval(u),u=null),f&&(h.clearTimeout(f),f=null),g=0,n.reset()}function w(y){S(),u=h.setInterval(()=>{if(y.readyState!==o){S();return}try{g=d(),t(y,{type:"ping"})}catch{S();return}f=h.setTimeout(()=>{console.warn("[ws] Heartbeat pong timeout — closing dead connection"),S();try{y.close()}catch{}},S4)},_4)}function E(y){x(),v=h.setTimeout(()=>{v=null,y()},x4)}function x(){v&&(h.clearTimeout(v),v=null)}function m(y){if(f&&(h.clearTimeout(f),f=null),g>0){const b=d(),_=b-g,k=Math.round(n.update(_));if(i(k,C4(k)),l){const j=dO({pingSentAt:g,pongRecvAt:b,serverTs:y});j.uplinkMs!==null&&l(`[latency] rtt=${j.rttMs}ms split≈ up ${j.uplinkMs}ms / down ${j.downlinkMs}ms (approx, clock-skew)`,b)}g=0}}return{startHeartbeat:w,stopHeartbeat:S,armHandshakeTimer:E,clearHandshakeTimer:x,handlePong:m,get isHeartbeatRunning(){return u!==null},get isHandshakeArmed(){return v!==null}}}function N4(e,t,n){const i=e[t]??[],o=i.includes(n)?i.filter(d=>d!==n):[...i,n];return{...e,[t]:o}}function j4(e,t,n){return{...e,[t]:n}}function A4(e,t){const n={};return e.forEach((i,o)=>{if(i.multiSelect)n[i.question]=t.multiSelectByIdx[o]??[];else{const d=t.singleSelectByIdx[o];d!=null&&(n[i.question]=d)}}),n}function R4(e,t){return e.every((n,i)=>n.multiSelect?!0:t.singleSelectByIdx[i]!=null)}function T4(e){return Array.isArray(e)&&e.length===1&&e[0]?.multiSelect===!0}function I4(e){const t=typeof e.stdout=="string",n=typeof e.stderr=="string";if(!t&&!n)return null;const i=t&&e.stdout!==""?e.stdout:"",o=n&&e.stderr!==""?e.stderr:"";if(!i)return o;if(!o)return i;const d=i.endsWith(`
|
|
49
|
-
`)?"":`
|
|
50
|
-
`;return i+d+o}function M4(e){if(typeof e!="string")try{return String(e??"")}catch{return""}const t=e.trim();if(!t.startsWith("{"))return e;let n;try{n=JSON.parse(t)}catch{return e}if(n===null||typeof n!="object"||Array.isArray(n))return e;const i=I4(n);return i===null?e:i}function D4(e,t){return e.type==="prompt"&&!!e.requestId&&!!e.expiresAt&&e.expiresAt>t&&!e.answered}function L4(e,t){let n=0;for(const i of e)D4(i,t)&&n++;return n}function O4(e,t){const n={};for(const i in e){const o=L4(e[i].messages,t);o>0&&(n[i]=o)}return n}function P4(e){let t=0;for(const n in e)t+=e[n];return t}function B4(e,t,n){const i=l=>(t[l]??0)>0,o=e.length;if(o===0||!e.some(i))return null;const d=n?e.indexOf(n):-1,h=d<0?-1:d;for(let l=1;l<=o;l++){const u=e[(h+l+o)%o];if(i(u))return u}return null}const $4=3,z4=4e3;function bm(e){return e===""?[]:e.split(`
|
|
51
|
-
`)}function U4(e,t){const n=e.length,i=t.length,o=Array.from({length:n+1},()=>new Array(i+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=i-1;f>=0;f--)o[u][f]=e[u]===t[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const d=[];let h=0,l=0;for(;h<n&&l<i;)e[h]===t[l]?(d.push({op:"eq",oldIndex:h,newIndex:l,content:e[h]}),h++,l++):o[h+1][l]>=o[h][l+1]?(d.push({op:"del",oldIndex:h,newIndex:l,content:e[h]}),h++):(d.push({op:"ins",oldIndex:h,newIndex:l,content:t[l]}),l++);for(;h<n;)d.push({op:"del",oldIndex:h,newIndex:l,content:e[h]}),h++;for(;l<i;)d.push({op:"ins",oldIndex:h,newIndex:l,content:t[l]}),l++;return d}function q4(e,t){const n=[...e.map(d=>({type:"deletion",content:d})),...t.map(d=>({type:"addition",content:d}))],i=e.length===0?0:1,o=t.length===0?0:1;return{header:`@@ -${i},${e.length} +${o},${t.length} @@`,lines:n}}function H4(e,t,n=$4){if(e===t)return[];const i=bm(e),o=bm(t);if(i.length+o.length>z4)return[q4(i,o)];const d=U4(i,o),h=d.map(u=>u.op!=="eq"),l=[];for(let u=0;u<d.length;u++){if(!h[u])continue;const f=Math.max(0,u-n),v=Math.min(d.length,u+n+1),g=l[l.length-1];g&&f<=g[1]?g[1]=Math.max(g[1],v):l.push([f,v])}return l.map(([u,f])=>{const v=d.slice(u,f),g=v[0],S=v.filter(y=>y.op!=="ins").length,w=v.filter(y=>y.op!=="del").length,E=S===0?g.oldIndex:g.oldIndex+1,x=w===0?g.newIndex:g.newIndex+1,m=v.map(y=>({type:y.op==="eq"?"context":y.op==="del"?"deletion":"addition",content:y.content}));return{header:`@@ -${E},${S} +${x},${w} @@`,lines:m}})}function F4(e){const t=/^@@ -(\d+),(\d+) /.exec(e);if(!t)return null;const n=Number(t[1]),i=Number(t[2]);return{start:i===0?n:n-1,count:i}}function K4(e){return e.lines.filter(t=>t.type!=="deletion").map(t=>t.content)}function W4(e,t,n){const i=typeof n=="function"?n:(l=>u=>l.has(u))(n instanceof Set?n:new Set(n)),o=bm(e),d=[];let h=0;return t.forEach((l,u)=>{const f=F4(l.header);f&&(f.start>h&&d.push(...o.slice(h,f.start)),i(u)?d.push(...K4(l)):d.push(...o.slice(f.start,f.start+f.count)),h=f.start+f.count)}),h<o.length&&d.push(...o.slice(h)),d.join(`
|
|
52
|
-
`)}const O_=e=>{let t;const n=new Set,i=(f,v)=>{const g=typeof f=="function"?f(t):f;if(!Object.is(g,t)){const S=t;t=v??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(w=>w(t,S))}},o=()=>t,l={setState:i,getState:o,getInitialState:()=>u,subscribe:f=>(n.add(f),()=>n.delete(f))},u=t=e(i,o,l);return l},G4=(e=>e?O_(e):O_),V4=e=>e;function Y4(e,t=V4){const n=Ac.useSyncExternalStore(e.subscribe,Ac.useCallback(()=>t(e.getState()),[e,t]),Ac.useCallback(()=>t(e.getInitialState()),[e,t]));return Ac.useDebugValue(n),n}const P_=e=>{const t=G4(e),n=i=>Y4(t,i);return Object.assign(n,t),n},gw=(e=>e?P_(e):P_);function bf(){return{...nN(),terminalRawBuffer:"",selectedFilePath:null,thinkingLevel:"default",pendingEvaluatorClarify:null}}const Sr=new Map;function Z4(e,t){Sr.set(e,t)}function X4(e){const t=Sr.get(e);t&&(t.timeoutId!==void 0&&clearTimeout(t.timeoutId),Sr.delete(e))}function Q4(e,t){const n=Sr.get(e);n&&(n.timeoutId!==void 0&&clearTimeout(n.timeoutId),Sr.delete(e),n.resolve(t))}function J4(e,t){const n=Sr.get(e);n&&(n.timeoutId!==void 0&&clearTimeout(n.timeoutId),Sr.delete(e),n.reject(new Error(t)))}function Np(e){for(const[,t]of Sr)t.timeoutId!==void 0&&clearTimeout(t.timeoutId),t.reject(new Error(e));Sr.clear()}const eP={"claude-opus-4-8":{inputPer1k:.015,outputPer1k:.075,label:"Claude Opus 4.8"},"claude-sonnet-4-6":{inputPer1k:.003,outputPer1k:.015,label:"Claude Sonnet 4.6"},"claude-haiku-4-5":{inputPer1k:.001,outputPer1k:.005,label:"Claude Haiku 4.5"},"claude-sonnet-4-5":{inputPer1k:.003,outputPer1k:.015,label:"Claude Sonnet 4.5"},"claude-3-7-sonnet-20250219":{inputPer1k:.003,outputPer1k:.015,label:"Claude 3.7 Sonnet"},"claude-3-5-sonnet-20241022":{inputPer1k:.003,outputPer1k:.015,label:"Claude 3.5 Sonnet"},"claude-3-5-sonnet-20240620":{inputPer1k:.003,outputPer1k:.015,label:"Claude 3.5 Sonnet (Jun)"},"claude-3-5-haiku-20241022":{inputPer1k:8e-4,outputPer1k:.004,label:"Claude 3.5 Haiku"},"claude-3-opus-20240229":{inputPer1k:.015,outputPer1k:.075,label:"Claude 3 Opus"},"claude-3-haiku-20240307":{inputPer1k:25e-5,outputPer1k:.00125,label:"Claude 3 Haiku"}},tP={"gpt-5-codex":{inputPer1k:.01,outputPer1k:.03,label:"GPT-5 Codex"},"gpt-5":{inputPer1k:.01,outputPer1k:.03,label:"GPT-5"},"gpt-4.1":{inputPer1k:.002,outputPer1k:.008,label:"GPT-4.1"},"gpt-4.1-mini":{inputPer1k:4e-4,outputPer1k:.0016,label:"GPT-4.1 mini"},"gpt-4.1-nano":{inputPer1k:1e-4,outputPer1k:4e-4,label:"GPT-4.1 nano"},"gpt-4o":{inputPer1k:.0025,outputPer1k:.01,label:"GPT-4o"},"gpt-4o-mini":{inputPer1k:15e-5,outputPer1k:6e-4,label:"GPT-4o mini"},o1:{inputPer1k:.015,outputPer1k:.06,label:"o1"},"o1-mini":{inputPer1k:.003,outputPer1k:.012,label:"o1-mini"},"o1-pro":{inputPer1k:.15,outputPer1k:.6,label:"o1-pro"},o3:{inputPer1k:.01,outputPer1k:.04,label:"o3"},"o3-mini":{inputPer1k:.0011,outputPer1k:.0044,label:"o3-mini"},"o4-mini":{inputPer1k:.0011,outputPer1k:.0044,label:"o4-mini"}},nP={"gemini-2.5-pro":{inputPer1k:.00125,outputPer1k:.01,label:"Gemini 2.5 Pro"},"gemini-2.5-pro-preview-03-25":{inputPer1k:.00125,outputPer1k:.01,label:"Gemini 2.5 Pro Preview"},"gemini-2.5-pro-exp-03-25":{inputPer1k:.00125,outputPer1k:.01,label:"Gemini 2.5 Pro Exp"},"gemini-2.5-flash":{inputPer1k:3e-4,outputPer1k:.0025,label:"Gemini 2.5 Flash"},"gemini-2.5-flash-preview-04-17":{inputPer1k:3e-4,outputPer1k:.0025,label:"Gemini 2.5 Flash Preview"},"gemini-2.0-pro":{inputPer1k:.00125,outputPer1k:.01,label:"Gemini 2.0 Pro"},"gemini-2.0-flash":{inputPer1k:1e-4,outputPer1k:4e-4,label:"Gemini 2.0 Flash"},"gemini-2.0-flash-001":{inputPer1k:1e-4,outputPer1k:4e-4,label:"Gemini 2.0 Flash 001"},"gemini-2.0-flash-exp":{inputPer1k:1e-4,outputPer1k:4e-4,label:"Gemini 2.0 Flash Exp"},"gemini-2.0-flash-lite":{inputPer1k:75e-6,outputPer1k:3e-4,label:"Gemini 2.0 Flash-Lite"},"gemini-1.5-pro":{inputPer1k:.00125,outputPer1k:.005,label:"Gemini 1.5 Pro"},"gemini-1.5-pro-002":{inputPer1k:.00125,outputPer1k:.005,label:"Gemini 1.5 Pro 002"},"gemini-1.5-flash":{inputPer1k:75e-6,outputPer1k:3e-4,label:"Gemini 1.5 Flash"},"gemini-1.5-flash-002":{inputPer1k:75e-6,outputPer1k:3e-4,label:"Gemini 1.5 Flash 002"},"gemini-1.5-flash-8b":{inputPer1k:375e-7,outputPer1k:15e-5,label:"Gemini 1.5 Flash-8B"}},sP={...eP,...tP,...nP},B_=new Set;function iP(e,t,n){const i=sP[e];return i?t/1e3*i.inputPer1k+n/1e3*i.outputPer1k:(e&&!B_.has(e)&&(B_.add(e),console.warn(`[model-pricing] no pricing entry for "${e}" — its cost estimate will be blank. Add it to model-pricing.ts.`)),null)}const vw=new Set(["codex","gemini"]),Qn="chroxy_persist_",rg=`${Qn}view_mode`,yw=`${Qn}active_session_id`,ag=`${Qn}terminal_buffer`,bw=`${Qn}session_list`,og=`${Qn}sidebar_width`,nf=`${Qn}split_mode`,sf=`${Qn}active_server_id`,rP=`${Qn}theme`,_w=`${Qn}show_console_tab`,Sw=`${Qn}intervention_ping`,xw=`${Qn}sidebar_panel_height`,_m=`${Qn}sidebar_panel_view`,ww=`${Qn}sidebar_panel_collapsed`,kw=`${Qn}sidebar_repo_order`,Cw=`${Qn}sidebar_session_order`,Ew=`${Qn}session_tab_order`;let _r=null;function aP(){for(const e of Object.values(Ud))e.flush();Nw.flush(),jw.flush()}function zd(e){e!==_r&&aP(),_r=e}function kr(e){return _r?`${Qn}${_r}_${e.replace(Qn,"")}`:e}function cl(e){const t=kr(e),n=localStorage.getItem(t);if(n!==null||!_r)return n;const i=localStorage.getItem(e);return i!==null&&(localStorage.setItem(t,i),localStorage.removeItem(e)),i}const $_=5e4,oP=["chat","terminal","files","diff","system","console","snapshots","pool","pages"];function lg(e){return kr(`${Qn}messages_${e}`)}function cg(e){let t=null,n=null;return{schedule(i){n=i,!t&&(t=setTimeout(()=>{t=null;const o=n;if(n=null,o)try{o()}catch(d){console.warn("[persist] Debounced save failed:",d)}},e))},cancel(){t&&(clearTimeout(t),t=null),n=null},flush(){t&&(clearTimeout(t),t=null);const i=n;if(n=null,i)try{i()}catch{}}}}const Ud={},Nw=cg(1e3),jw=cg(500);function lP(e){return Ud[e]||(Ud[e]=cg(500)),Ud[e]}function z_(e,t){const n=lg(e);lP(e).schedule(()=>{const i=t.slice(-100).map(OP);try{localStorage.setItem(n,JSON.stringify(i))}catch{}})}function cP(e){try{localStorage.setItem(rg,e)}catch{}}function uP(e){try{const t=kr(yw);e?localStorage.setItem(t,e):localStorage.removeItem(t)}catch{}}function dP(e){const t=kr(ag);Nw.schedule(()=>{const n=e.length>$_?e.slice(-$_):e;try{localStorage.setItem(t,n)}catch{}})}function fP(e){try{localStorage.setItem(og,String(e))}catch{}}function hP(){try{const e=localStorage.getItem(og);if(!e)return null;const t=parseInt(e,10);return Number.isFinite(t)?t:null}catch{return null}}function pP(e){try{localStorage.setItem(xw,String(e))}catch{}}function mP(){try{const e=localStorage.getItem(xw);if(!e)return null;const t=parseInt(e,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function gP(e){try{e?localStorage.setItem(_m,e):localStorage.removeItem(_m)}catch{}}function vP(){try{return localStorage.getItem(_m)}catch{return null}}function yP(e){try{localStorage.setItem(ww,e?"1":"0")}catch{}}function bP(){try{return localStorage.getItem(ww)==="1"}catch{return!1}}function _P(e){try{const t=kr(kw);e.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(e))}catch{}}function U_(){try{const e=cl(kw);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function SP(e){try{const t=kr(Cw);Object.keys(e).length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(e))}catch{}}function q_(){try{const e=cl(Cw);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n={};for(const[i,o]of Object.entries(t))typeof i=="string"&&Array.isArray(o)&&(n[i]=o.filter(d=>typeof d=="string"));return n}catch{return{}}}function rf(e){try{e?localStorage.setItem(nf,e):localStorage.removeItem(nf)}catch{}}const xP=["horizontal","vertical"];function wP(){try{const e=localStorage.getItem(nf);return e&&xP.includes(e)?e:null}catch{return null}}function kP(e){try{e?localStorage.setItem(sf,e):localStorage.removeItem(sf)}catch{}}function CP(){try{return localStorage.getItem(sf)||null}catch{return null}}function H_(e){try{localStorage.setItem(_w,String(e))}catch{}}function EP(){try{return localStorage.getItem(_w)==="true"}catch{return!1}}function F_(e){try{localStorage.setItem(Sw,String(e))}catch{}}function NP(){try{return localStorage.getItem(Sw)!=="false"}catch{return!0}}function jP(e){try{const t=kr(Ew);e.length===0?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(e))}catch{}}function K_(){try{const e=cl(Ew);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function AP(e){const t=kr(bw);jw.schedule(()=>{try{localStorage.setItem(t,JSON.stringify(e))}catch{}})}function jp(){try{const e=localStorage.getItem(rg),t=cl(yw),n=cl(ag);return{viewMode:e&&oP.includes(e)?e:null,activeSessionId:t||null,terminalBuffer:n||null}}catch{return{viewMode:null,activeSessionId:null,terminalBuffer:null}}}function RP(e){try{const t=lg(e);let n=localStorage.getItem(t);if(n===null&&_r){const o=`${Qn}messages_${e}`;n=localStorage.getItem(o),n!==null&&(localStorage.setItem(t,n),localStorage.removeItem(o))}if(!n)return[];const i=JSON.parse(n);return Array.isArray(i)?i:[]}catch{return[]}}function TP(){try{const e=cl(bw);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function IP(e){const t={};for(const n of e)t[n]=RP(n);return t}function W_(e){try{localStorage.removeItem(lg(e))}catch{}}function MP(){try{localStorage.removeItem(kr(ag))}catch{}}function DP(){try{const e=[],t=_r?`${Qn}${_r}_`:Qn;for(let n=0;n<localStorage.length;n++){const i=localStorage.key(n);if(i&&i.startsWith(t)){if(!_r&&LP(i))continue;e.push(i)}}for(const n of e)localStorage.removeItem(n)}catch{}}function LP(e){return e===rg||e===og||e===nf||e===sf||e===rP}function OP(e){return!e.toolResultImages?.length&&!e.attachments?.length?e:{...e,toolResultImages:e.toolResultImages?.map(t=>({...t,data:t.data?"[image data stripped for storage]":t.data})),attachments:e.attachments?.map(t=>({...t,uri:t.uri.startsWith("data:")?"[data stripped]":t.uri}))}}const Sm=cw;let xm=null;function PP(e){xm=e}function ln(){if(!xm)throw new Error("Store not initialized — call setStore() first");return xm}const ca=new Map;function BP(e,t){ca.set(e,t)}function $P(e){const t=ca.get(e);t&&(window.clearTimeout(t.timeoutId),ca.delete(e))}function Ap(e){if(ca.size===0)return;const t=new Error(e);for(const n of ca.values())window.clearTimeout(n.timeoutId),n.reject(t);ca.clear()}const Ha=new Map,zP=32;function UP(e,t){if(Ha.size>=zP){const n=Ha.keys().next().value;n!==void 0&&Ha.delete(n)}Ha.set(e,{...t})}function Aw(e){const t=Ha.get(e);return t?(Ha.delete(e),t):null}function Rp(){Ha.clear()}const Fa=new Map,qP=16;function HP(e,t){if(Fa.size>=qP){const n=Fa.keys().next().value;n!==void 0&&Fa.delete(n)}Fa.set(e,{...t})}function FP(e){const t=Fa.get(e);return t?(Fa.delete(e),t):null}function Tp(){Fa.clear()}const Ka=new Map,KP=16;function WP(e,t){if(Ka.size>=KP){const n=Ka.keys().next().value;n!==void 0&&Ka.delete(n)}Ka.set(e,{...t})}function GP(e){const t=Ka.get(e);return t?(Ka.delete(e),t):null}function Ip(){Ka.clear()}const Wa=new Map,VP=16;function YP(e,t){if(Wa.size>=VP){const n=Wa.keys().next().value;n!==void 0&&Wa.delete(n)}Wa.set(e,{...t})}function ZP(e){const t=Wa.get(e);return t?(Wa.delete(e),t):null}function Mp(){Wa.clear()}let Mi=null,bs=null,Ws=null,Dp=!1;function He(e,t){const n=JSON.stringify(Mi?VE(JSON.stringify(t),Mi.sharedKey,Mi.sendNonce,qE):t);try{e.send(n)}catch(i){return console.warn("[wsSend] socket.send threw — frame not delivered:",i),!1}return Mi&&Mi.sendNonce++,!0}let wm=!0;function Lp(){wm=!0}function qd(e,t){!e||e.readyState!==WebSocket.OPEN||wm!==t&&(bs!==null&&Mi===null||(wm=t,He(e,{type:"client_visible",visible:t})))}const ug=cE(localStorage),Si={alert:lE};let Rw=null;function XP(e){Rw=e}function QP(){return Mi}function Op(e){Mi=e}function G_(e){bs=e}let Tw=null;function dg(e){Tw=e}function Iw(){return Tw}function JP(){return bs=z0(),Ws=q0(),{publicKey:bs.publicKey,salt:Ws}}let _i=0,Hd=-1,fg=null,Mw=0;function V_(){return++_i}function e5(){return Mw++}function Dw(){Mw=0}function t5(e){Hd=e}function Pp(e){fg=e}const Wi=new Set;function n5(){Wi.clear()}const Kc=new Set,xr=new Map;function Y_(){Kc.clear(),xr.clear()}let Lc="",sl=null;function s5(){if(sl=null,Lc.length===0)return;const e=Lc;Lc="";const t=ln().getState()._terminalWriteCallback;t&&t(e)}function i5(e){Lc+=e,sl||(sl=setTimeout(s5,50))}function Z_(){sl&&(clearTimeout(sl),sl=null),Lc=""}const Lw=new gO,qc=new Map,X_=new fw(200),Q_=new fw(200);let af=0;const Wc=E4({wsSend:He,rttSmoother:Lw,onPongQuality:(e,t)=>{ln().setState({latencyMs:e,connectionQuality:t})},openReadyState:WebSocket.OPEN,onLatencyLog:(e,t)=>{t-af>=Ow&&(af=t,console.log(e))}}),Ow=w4;function J_(){Wc.stopHeartbeat()}function r5(e){Wc.startHeartbeat(e)}function a5(e){Wc.armHandshakeTimer(e)}function Qo(){Wc.clearHandshakeTimer()}function o5(e){Wc.handlePong(e)}const fl=yO({getEwmaRtt:()=>Lw.value,applyDeltas:c5}),l5=fl.pendingDeltas;function c5(e){const t=ln().getState(),n=new Map;for(const[d,{sessionId:h,delta:l}]of e)n.has(h)||n.set(h,new Map),n.get(h).set(d,l);let i={...t.sessionStates},o=!1;for(const[d,h]of n)if(d&&i[d]){const l=i[d],u=new Set,v=l.messages.map(g=>{const S=h.get(g.id);return S&&g.type==="response"?(u.add(g.id),{...g,content:g.content+S}):g});Zb(v,h,u,xr),i={...i,[d]:{...l,messages:v}},d===t.activeSessionId&&(ln().setState({sessionStates:i,messages:v}),o=!0)}else ln().setState(l=>{const u=new Set,f=l.messages.map(v=>{const g=h.get(v.id);return g&&v.type==="response"?(u.add(v.id),{...v,content:v.content+g}):v});return Zb(f,h,u,xr),{messages:f}}),o=!0;o||ln().setState({sessionStates:i}),u5(e.keys())}function u5(e){const t=Date.now();let n=!1;for(const d of e){const h=qc.get(d);h&&(qc.delete(d),X_.add(t-h.serverTs),Q_.add(t-h.recvAt),n=!0)}if(!n||t-af<Ow)return;af=t;const i=X_.summary(),o=Q_.summary();console.log(`[latency] token→render(~approx, wall-clock) n=${i.count} p50=${i.p50}ms p95=${i.p95}ms | client-render n=${o.count} p50=${o.p50}ms p95=${o.p95}ms`)}function d5(){fl.clear(),qc.clear()}const f5={input:6e4,interrupt:5e3,permission_response:3e5,user_question_response:6e4},eS=10,h5=new Set(["set_model","set_permission_mode","mode","resize"]),p5=new Set(["MAX_TOOL_ROUNDS_REACHED"]),Va=[];function gc(e,t){if(h5.has(e))return!1;const n=f5[e];return!n||Va.length>=eS?!1:(Va.push({type:e,payload:t,queuedAt:Date.now(),maxAge:n}),console.log(`[queue] Queued ${e} (${Va.length}/${eS})`),"queued")}function m5(e){if(Va.length===0)return;const t=Date.now(),n=Va.filter(i=>t-i.queuedAt<i.maxAge);if(Va.length=0,n.length!==0){console.log(`[queue] Draining ${n.length} queued message(s)`);for(const i of n)try{He(e,i.payload)}catch(o){console.warn(`[queue] Failed to send queued ${i.type}:`,o)}}}function tS(){Va.length=0}function Ft(e,t){const n=ln().getState();if(!n.sessionStates[e])return;const i=n.sessionStates[e],o=t(i);if(Object.keys(o).length===0)return;const d={...i,...o},h={...n.sessionStates,[e]:d};if(e===n.activeSessionId){const l={sessionStates:h};"messages"in o&&(l.messages=o.messages),"streamingMessageId"in o&&(l.streamingMessageId=o.streamingMessageId),"claudeReady"in o&&(l.claudeReady=o.claudeReady),"activeModel"in o&&(l.activeModel=o.activeModel),"permissionMode"in o&&(l.permissionMode=o.permissionMode),"contextUsage"in o&&(l.contextUsage=o.contextUsage),"lastResultCost"in o&&(l.lastResultCost=o.lastResultCost),"lastResultDuration"in o&&(l.lastResultDuration=o.lastResultDuration),"isIdle"in o&&(l.isIdle=o.isIdle),ln().setState(l)}else ln().setState({sessionStates:h})}function Cs(e){const n=ln().getState().activeSessionId;n&&Ft(n,e)}const g5={getActiveSessionId:()=>ln().getState().activeSessionId,hasSession:e=>!!ln().getState().sessionStates[e],updateSession:(e,t)=>Ft(e,t),setState:e=>ln().setState(e),updateState:e=>ln().setState(t=>e(t)),addMessage:e=>ln().getState().addMessage(e),appendTerminalData:e=>ln().getState().appendTerminalData(e),alert:(e,t)=>Si.alert.alert(e,t),getSessions:()=>ln().getState().sessions,getCheckpoints:()=>ln().getState().checkpoints,switchToRestoredSession:e=>ln().getState().switchSession(e),getSearchQuery:()=>ln().getState().searchQuery,pushSessionNotification:(e,t,n)=>of(e,t,n),applyNoSessionFallback:e=>ln().setState(e),addServerError:e=>ln().getState().addServerError(e),addInfoNotification:e=>ln().getState().addInfoNotification(e),getMyClientId:()=>ln().getState().myClientId,getFollowMode:()=>ln().getState().followMode,switchSession:e=>ln().getState().switchSession(e),extendModelsPatch:e=>({availableModelsProvider:typeof e.provider=="string"?e.provider:null}),applyRotatedTunnelUrl:(e,t)=>{C5(ln().getState,e,t)}},v5=p4();function of(e,t,n,i){const o=ln().getState();if(e===o.activeSessionId)return;const h=o.sessions.find(u=>u.sessionId===e)?.name||e,l={id:`${e}-${t}-${Date.now()}`,sessionId:e,sessionName:h,eventType:t,message:n,timestamp:Date.now(),...i?{requestId:i}:{}};ln().setState(u=>({sessionNotifications:[...u.sessionNotifications.filter(v=>!(v.sessionId===e&&v.eventType===t)),l]}))}function y5(e,t){ug.saveConnection(e,t)}function b5(){return ug.loadConnection()}function _5(){ug.clearSavedCredentials()}function nS(e,t,n,i=null,o=null){const d=ln().getState(),h=d.activeServerId,u=(h?d.serverRegistry.find(v=>v.id===h):void 0)?.pinnedIdentityKey??null,f=eN({pinnedIdentityKey:u,pairingIdentityKey:Iw(),exchangePublicKey:t,serverKeySig:n,newIdentityKey:i,rotationCert:o});return f.action==="refuse"?(Pw(e,f.reason,f.message),!1):((f.action==="pin-and-connect"||f.action==="rotate-pin")&&h&&ln().getState().updateServer(h,{pinnedIdentityKey:f.identityKey}),dg(null),!0)}function Pw(e,t,n){console.error(`[crypto] Server identity verification failed (${t}) — refusing connection`);try{e.socket.close()}catch{}ln().setState({connectionPhase:"disconnected",socket:null,connectionError:n,userDisconnected:!0}),e.silent||Si.alert.alert("Server Identity Changed",n),dg(null)}function S5(e,t){const n=ln().getState(),i=n.activeServerId?n.serverRegistry.find(d=>d.id===n.activeServerId):void 0,o=XE({pinnedIdentityKey:i?.pinnedIdentityKey??null,pairingIdentityKey:Iw(),encryptionMode:t});return o.action==="refuse"?(Pw(e,o.reason,o.message),!1):!0}function x5(e,t,n,i){o5(typeof e.serverTs=="number"?e.serverTs:void 0)}function w5(e,t,n,i){typeof e.cols!="number"||typeof e.rows!="number"||!Number.isInteger(e.cols)||!Number.isInteger(e.rows)||e.cols<=0||e.rows<=0||typeof e.sessionId!="string"||e.sessionId!==t().activeSessionId||t().setTerminalSize(e.sessionId,e.cols,e.rows)}function k5(e,t,n,i){const{token:o}=Lj(e);if(o){console.log("[ws] Server token rotated — updating stored token");try{const d=new URL(window.location.href);d.searchParams.set("token",o),window.history.replaceState(null,"",d.toString())}catch{}}else console.log("[ws] Server token rotated — re-authentication required")}function C5(e,t,n){if(!t||!/^wss:\/\//i.test(t))return!1;const i=e(),o=i.activeServerId;if(!o)return!1;const d=i.serverRegistry.find(h=>h.id===o);if(!d||!/^wss:\/\//i.test(d.wsUrl)||d.wsUrl===t||n&&d.wsUrl!==n)return!1;try{return i.updateServer(o,{wsUrl:t}),!0}catch{return!1}}function E5(e,t,n,i){n(o=>({pairingRefreshedCount:(o.pairingRefreshedCount??0)+1}))}function N5(e,t,n,i){const{level:o}=XL(e),d=on(e,t().activeSessionId);d&&t().sessionStates[d]&&Ft(d,()=>({thinkingLevel:o}))}function j5(e,t,n,i){const o=typeof e.value=="boolean"?e.value:null;if(o===null)return;const d=on(e,t().activeSessionId);if(!d)return;const h=t().sessions.map(l=>l.sessionId===d?{...l,promptEvaluator:o}:l);n({sessions:h})}function A5(e,t,n,i){const o=typeof e.value=="boolean"?e.value:null;if(o===null)return;const d=on(e,t().activeSessionId);if(!d)return;const h=t().sessions.map(l=>l.sessionId===d?{...l,chroxyContextHint:o}:l);n({sessions:h})}function R5(e,t,n,i){const o=typeof e.value=="string"?e.value:null;if(o===null)return;const d=on(e,t().activeSessionId);if(!d)return;const h=t().sessions.map(l=>l.sessionId===d?{...l,sessionPreamble:o}:l);n({sessions:h})}function T5(e,t,n,i){if(!Array.isArray(e.skills))return;const o=on(e,t().activeSessionId);if(!o||!t().sessionStates[o])return;const d=e.skills.map(h=>{const l=h.source==="global"||h.source==="repo"?h.source:void 0,u=h.activation==="auto"||h.activation==="manual"?h.activation:void 0,f=h.trustState==="pending"||h.trustState==="trusted"?h.trustState:void 0;return{name:typeof h.name=="string"?h.name:"",description:typeof h.description=="string"?h.description:void 0,source:l,activation:u,active:typeof h.active=="boolean"?h.active:void 0,version:typeof h.version=="string"?h.version:void 0,hashPrefix:typeof h.hashPrefix=="string"?h.hashPrefix:void 0,firstSeen:typeof h.firstSeen=="string"?h.firstSeen:void 0,lastVerified:typeof h.lastVerified=="string"?h.lastVerified:void 0,trustState:f,communityAuthor:typeof h.communityAuthor=="string"?h.communityAuthor:void 0}}).filter(h=>h.name);Ft(o,()=>({skills:d}))}function I5(e,t,n,i){const o=typeof e.skillName=="string"?e.skillName:null;if(!o)return;const d=on(e,t().activeSessionId);!d||!t().sessionStates[d]||Ft(d,h=>{const l=Array.isArray(h.mismatchedSkillNames)?h.mismatchedSkillNames:[];return l.includes(o)?{}:{mismatchedSkillNames:[...l,o]}})}function M5(e,t,n,i){const o=typeof e.skillName=="string"?e.skillName:null;if(!o)return;const d=on(e,t().activeSessionId);!d||!t().sessionStates[d]||Ft(d,h=>({skills:(h.skills||[]).map(l=>l.name===o?{...l,active:!0}:l)}))}function D5(e,t,n,i){const o=typeof e.skillName=="string"?e.skillName:null;if(!o)return;const d=on(e,t().activeSessionId);!d||!t().sessionStates[d]||Ft(d,h=>({skills:(h.skills||[]).map(l=>l.name===o?{...l,active:!1}:l)}))}function L5(e,t,n,i){const o=typeof e.skillName=="string"?e.skillName:null;if(!o)return;const d=on(e,t().activeSessionId);!d||!t().sessionStates[d]||Ft(d,h=>{const l=Array.isArray(h.mismatchedSkillNames)?h.mismatchedSkillNames:[];return l.includes(o)?{mismatchedSkillNames:l.filter(u=>u!==o)}:{}})}function O5(e,t,n,i){const o=typeof e.evaluatorIterationId=="string"?e.evaluatorIterationId:null,d=typeof e.originalDraft=="string"?e.originalDraft:null,h=typeof e.rewritten=="string"?e.rewritten:null;if(!o||d===null||h===null)return;const l=typeof e.reasoning=="string"?e.reasoning:"",u=on(e,t().activeSessionId);if(!u||!t().sessionStates[u])return;const f={kind:"rewrite",evaluatorIterationId:o,originalDraft:d,rewritten:h,reasoning:l};Ft(u,v=>{if(v.messages.some(E=>E.type==="system"&&E.evaluator?.evaluatorIterationId===o))return v.pendingEvaluatorClarify?{pendingEvaluatorClarify:null}:{};const S={id:`evaluator-rewrite-${o}`,type:"system",content:"Your message was rewritten to be clearer — see why",timestamp:Date.now(),evaluator:f},w={messages:[...v.messages,S]};return v.pendingEvaluatorClarify&&(w.pendingEvaluatorClarify=null),w})}function P5(e,t,n,i){const o=typeof e.evaluatorIterationId=="string"?e.evaluatorIterationId:null,d=typeof e.evaluatorIteration=="number"&&Number.isInteger(e.evaluatorIteration)&&e.evaluatorIteration>=1?e.evaluatorIteration:null,h=typeof e.originalDraft=="string"?e.originalDraft:null,l=typeof e.clarification=="string"?e.clarification:null;if(!o||d===null||h===null||l===null)return;const u=typeof e.reasoning=="string"?e.reasoning:"",f=on(e,t().activeSessionId);if(!f||!t().sessionStates[f])return;const v={evaluatorIterationId:o,evaluatorIteration:d,originalDraft:h,clarification:l,reasoning:u};Ft(f,g=>g.pendingEvaluatorClarify?.evaluatorIterationId===o?{}:{pendingEvaluatorClarify:v})}function B5(e,t,n,i){const o=typeof e.skillName=="string"?e.skillName:null,d=typeof e.author=="string"?e.author:null;if(!o||!d)return;const h=typeof e.description=="string"&&e.description?e.description:void 0,l=typeof e.path=="string"&&e.path?e.path:void 0,u=on(e,t().activeSessionId);!u||!t().sessionStates[u]||Ft(u,f=>{const v=Array.isArray(f.pendingCommunitySkills)?f.pendingCommunitySkills:[];if(v.some(S=>S.name===o&&S.author===d))return{};const g={name:o,author:d};return h!==void 0&&(g.description=h),l!==void 0&&(g.path=l),{pendingCommunitySkills:[...v,g]}})}function $5(e,t,n,i){const o=typeof e.skillName=="string"?e.skillName:null,d=typeof e.author=="string"?e.author:null;if(!o||!d)return;const h=on(e,t().activeSessionId);!h||!t().sessionStates[h]||Ft(h,l=>({pendingCommunitySkills:(Array.isArray(l.pendingCommunitySkills)?l.pendingCommunitySkills:[]).filter(f=>!(f.name===o&&f.author===d))}))}function z5(e,t,n,i){const o=typeof e.requestId=="string"?e.requestId:null;if(!o)return;Aw(o);const d=on(e,t().activeSessionId);!d||!t().sessionStates[d]||Ft(d,h=>{const l=Array.isArray(h.pendingTrustGrants)?h.pendingTrustGrants:[],u=l.filter(f=>f.requestId!==o);return u.length===l.length?{}:{pendingTrustGrants:u}})}function U5(e,t){const n=t().sessionStates;let i=!1;for(const o of Object.keys(n)){const d=n[o];if(!d)continue;const h=Array.isArray(d.pendingTrustGrants)?d.pendingTrustGrants:[],l=h.filter(u=>u.requestId!==e);l.length!==h.length&&(i=!0,Ft(o,()=>({pendingTrustGrants:l})))}return i}function q5(e,t,n,i){const o=lA(e);if(!o)return;const{newSessionId:d,conversationId:h}=o,l=e.sessionPreset;if(l&&typeof l=="object"){const u=l.seed;typeof u=="string"&&u.length>0&&n({pendingServerSeed:{...t().pendingServerSeed,[d]:u}})}n(u=>{const f={...u.sessionStates};f[d]||(f[d]=bf()),h&&(f[d]={...f[d],conversationId:h});const v=f[d];return{activeSessionId:d,sessionStates:f,messages:v.messages,streamingMessageId:v.streamingMessageId,claudeReady:v.claudeReady,activeModel:v.activeModel,permissionMode:v.permissionMode,contextUsage:v.contextUsage,lastResultCost:v.lastResultCost,lastResultDuration:v.lastResultDuration,isIdle:v.isIdle}}),t().fetchSlashCommands(),t().fetchCustomAgents()}function H5(e,t,n,i){const o=GL(e),d=on(e,t().activeSessionId);d&&t().sessionStates[d]?Ft(d,()=>o):n(o);const h=t().socket;h&&h.readyState===WebSocket.OPEN&&m5(h)}function F5(e,t,n,i){const o=e.sessionId||t().activeSessionId;o&&t().sessionStates[o]?Ft(o,d=>{const h=R_(e,t().activeSessionId,d.messages);return h.remap&&xr.set(h.remap.from,h.remap.to),h.isNewMessage?{streamingMessageId:h.streamingMessageId,pendingClientMessageId:null,messages:[...vr(d.messages),h.newMessage]}:{streamingMessageId:h.streamingMessageId,pendingClientMessageId:null}}):n(d=>{const h=R_(e,t().activeSessionId,d.messages);return h.remap&&xr.set(h.remap.from,h.remap.to),h.isNewMessage?{streamingMessageId:h.streamingMessageId,messages:[...vr(d.messages),h.newMessage]}:{streamingMessageId:h.streamingMessageId}})}function K5(e,t,n,i){if(typeof e.messageId=="string"){const o=typeof e.serverTs=="number"?e.serverTs:null;o!==null&&!qc.has(e.messageId)&&qc.set(e.messageId,{serverTs:o,recvAt:Date.now()})}qL(e,{activeSessionId:t().activeSessionId,pendingDeltas:l5,deltaIdRemaps:xr,postPermissionSplits:Kc,replayingSessions:Wi,getSessionMessages:o=>o&&t().sessionStates[o]?t().sessionStates[o].messages:null,getFlatMessages:()=>t().messages,appendTerminalDelta:o=>{t().appendTerminalData(o)},reorderEmptyResponseSlot:(o,d)=>{const h=d&&t().sessionStates[d]?d:null;if(h){const l=t().sessionStates[h],u=l.messages.findIndex(f=>f.id===o);if(u>=0&&u<l.messages.length-1){const f=l.messages[u];f.type==="response"&&f.content===""&&Ft(h,v=>({messages:[...v.messages.slice(0,u),...v.messages.slice(u+1),f]}))}}else{const l=t().messages,u=l.findIndex(f=>f.id===o);if(u>=0&&u<l.length-1){const f=l[u];f.type==="response"&&f.content===""&&n(v=>({messages:[...v.messages.slice(0,u),...v.messages.slice(u+1),f]}))}}},appendResponseSlot:(o,d,h)=>{if(o&&t().sessionStates[o]){if(h?.onlyIfAbsent&&t().sessionStates[o].messages.some(l=>l.id===d.id))return;Ft(o,l=>({streamingMessageId:d.id,messages:[...l.messages,d]}))}else{if(h?.onlyIfAbsent&&t().messages.some(l=>l.id===d.id))return;n(l=>({streamingMessageId:d.id,messages:[...l.messages,d]}))}},peelSlotContent:(o,d,h)=>{const l=u=>({messages:u.messages.map(f=>f.id===d&&f.type==="response"?{...f,content:f.content.slice(0,f.content.length-h)}:f)});o&&t().sessionStates[o]?Ft(o,l):n(u=>({messages:l({messages:u.messages}).messages}))},scheduleFlush:()=>{fl.schedule()}})}function W5(e,t,n,i){fl.flushNow(),t().appendTerminalData(`\r
|
|
53
|
-
`);const o=HL(e,t().activeSessionId);o.messageId!==null&&(Kc.delete(o.messageId),xr.delete(o.messageId));const d=o.sessionId;d&&t().sessionStates[d]?Ft(d,h=>({streamingMessageId:null,messages:[...h.messages]})):n(h=>({streamingMessageId:null,messages:[...h.messages]}))}function G5(e,t,n,i){const o=typeof e.tool=="string"?e.tool:"tool";t().appendTerminalData(`\r
|
|
54
|
-
\x1B[36m⏺ ${o}\x1B[0m\r
|
|
55
|
-
`);const d=typeof e.sessionId=="string"?e.sessionId:t().activeSessionId,h=(()=>{const g=d?t().sessionStates[d]:null;return B0(d,g?g.messages:t().messages)})(),l=d?Wi.has(d):!1;l&&Hm(d,e.historySeq);const u=PL(e,t().activeSessionId,l,h);if(!u.shouldDispatch||!u.chatMessage)return;const f=u.chatMessage,v=u.sessionId;v&&t().sessionStates[v]?Ft(v,g=>{const S={messages:[...g.messages,f]};g.streamingMessageId==="pending"&&(S.streamingMessageId=f.id,S.pendingClientMessageId=null);const w=u.applyToActiveTools(g.activeTools);return w!==g.activeTools&&(S.activeTools=w),S}):(t().addMessage(f),ln().getState().streamingMessageId==="pending"&&ln().setState({streamingMessageId:f.id}))}function V5(e,t,n,i){const o=zL(e,t().activeSessionId);if(!o)return;const d=o.sessionId;if(d&&t().sessionStates[d])Ft(d,h=>{const l=o.applyTo(h.messages);return l===h.messages?{}:{messages:l}});else{const h=o.applyTo(t().messages);h!==t().messages&&n({messages:h})}}function Y5(e,t,n,i){const o=BL(e,t().activeSessionId);if(!o)return;if(o.resultText){const h=M4(o.resultText),l=h.length>500?h.slice(0,500)+"...":h;t().appendTerminalData(`\x1B[2m${l}\x1B[0m\r
|
|
56
|
-
`)}const d=o.sessionId;if(d&&t().sessionStates[d])Ft(d,h=>{const l=o.applyTo(h.messages),u=o.applyToActiveTools(h.activeTools),f={};return l!==h.messages&&(f.messages=l),u!==h.activeTools&&(f.activeTools=u),f});else{const h=o.applyTo(t().messages);h!==t().messages&&n({messages:h})}}function Z5(e,t,n,i){const o=Sj(e);if(!o.requestId)return;const d=o.sessionId;d&&!t().sessionStates[d]&&n(S=>({sessionStates:{...S.sessionStates,[d]:bf()}}));{const S=o.sessionId||t().activeSessionId,w=S&&t().sessionStates[S]?t().sessionStates[S].streamingMessageId:t().streamingMessageId,E=aO(w,xr);E&&(fl.flushNow(),Kc.add(E.serverStreamId),S&&t().sessionStates[S]?Ft(S,()=>({streamingMessageId:null})):n({streamingMessageId:null}))}const h=o.requestId,l=[{label:"Allow",value:"allow"},{label:"Deny",value:"deny"}],u=o.remainingMs!==null?Date.now()+o.remainingMs:void 0,f=o.sessionId||t().activeSessionId;if((f&&t().sessionStates[f]?t().sessionStates[f].messages:t().messages).findIndex(S=>S.requestId===h&&S.type==="prompt")!==-1){const S=w=>({messages:w.messages.map(E=>E.requestId===h&&E.type==="prompt"?{...E,answered:void 0,options:l,expiresAt:u}:E)});f&&t().sessionStates[f]?Ft(f,S):n({messages:S({messages:t().messages}).messages})}else{const S={id:fn("perm"),type:"prompt",content:o.tool?o.description?`${o.tool}: ${o.description}`:o.tool:o.description||"Permission required",tool:o.tool??void 0,requestId:h,toolInput:o.input??void 0,options:l,expiresAt:u,timestamp:Date.now(),originSessionId:o.sessionId??void 0};f&&t().sessionStates[f]?Ft(f,w=>({messages:[...w.messages,S]})):t().addMessage(S)}if(f){const S=o.tool??"Permission needed";of(f,"permission",S,h)}}function X5(e,t,n,i){const{requestId:o,decision:d}=xj(e);if(o){const h=v=>({messages:v.messages.map(g=>g.requestId===o&&g.type==="prompt"?{...g,answered:d??void 0,answeredAt:Date.now(),options:void 0}:g)}),l=t().sessionStates;let u=!1;for(const v of Object.keys(l))if(l[v]?.messages.some(g=>g.requestId===o)){Ft(v,h),u=!0;break}u||n({messages:h({messages:t().messages}).messages});const f=Date.now();n(v=>({sessionNotifications:(v.sessionNotifications??[]).map(g=>g.requestId===o&&g.readAt===void 0?{...g,readAt:f}:g)})),n(v=>{if(!v.permissionInputs||!Object.prototype.hasOwnProperty.call(v.permissionInputs,o))return{};const g={...v.permissionInputs};return delete g[o],{permissionInputs:g}})}}function Q5(e,t,n,i){const{exceededMessage:o,systemMessage:d}=oj(e),h=on(e,t().activeSessionId),l={...d,content:`${d.content}. Budget will auto-resume.`};h&&t().sessionStates[h]?Ft(h,f=>({messages:[...f.messages,l]})):t().addMessage(l),Si.alert.alert("Budget Exceeded",`${o}
|
|
57
|
-
|
|
58
|
-
New messages are paused.`);const u=t().socket;u&&h&&He(u,{type:"resume_budget",sessionId:h})}function J5(e,t,n,i){const{serverError:o,chatMessage:d}=Fj(e);n(l=>({serverErrors:[...l.serverErrors,o].slice(-10)}));const h=o.sessionId;if(h&&t().sessionStates[h])Ft(h,l=>({messages:vr([...l.messages,d]),streamingMessageId:null,pendingClientMessageId:null}));else{const l=t().activeSessionId;l&&t().sessionStates[l]?Cs(u=>({messages:vr([...u.messages,d]),streamingMessageId:null,pendingClientMessageId:null})):(n({streamingMessageId:null}),t().addMessage(d))}o.recoverable||Si.alert.alert("Server Error",o.message)}function eB(e,t,n,i){const o=J3.safeParse(e);if(!o.success)return;const d=t().activity,h=vN(d,o.data);h!==d&&n({activity:h})}function tB(e,t,n,i){const o=e6.safeParse(e);if(!o.success)return;const d=t().activity,h=yN(d,o.data);if(h===d)return;n({activity:h}),o.data.op==="ended"&&hg(t,n,o.data.sessionId,o.data.entry.id);const l=o.data.sessionId;t().sessionStates[l]&&!Wi.has(l)&&Ft(l,u=>{const f={lastClientActivityAt:Date.now()};return u.inactivityWarning&&(f.inactivityWarning=null),f})}function nB(e,t,n,i){const o=t6.safeParse(e);o.success&&hg(t,n,o.data.sessionId,o.data.activityId)}function sB(e,t){return!e||!t?null:`${e}:${t}`}function hg(e,t,n,i){const o=sB(n,i);if(!o)return;const d=e().cancellingActivityIds;if(!d||!d.has(o))return;const h=new Set(d);h.delete(o),t({cancellingActivityIds:h})}function iB(e,t,n){if(!n)return;const i=e().cancellingActivityIds;if(!i||i.size===0)return;const o=`${n}:`;let d=!1;const h=new Set;for(const l of i){if(l.startsWith(o)){d=!0;continue}h.add(l)}d&&t({cancellingActivityIds:h})}function rB(e,t,n,i){const o=a6.safeParse(e);o.success&&n({hostStatus:o.data,hostStatusLoading:!1})}function aB(e,t,n,i){const o=wL.safeParse(e);o.success&&(o.data.path===null?n({workspaceSymbols:o.data,workspaceSymbolsLoading:!1,symbolsLoading:!1}):n({symbols:o.data,symbolsLoading:!1,workspaceSymbolsLoading:!1}))}function oB(e,t,n,i){const o=kL.safeParse(e);if(!o.success)return;const{symbol:d,file:h,line:l,error:u}=o.data,f=t().symbolLocation;n({symbolLocation:{symbol:d,file:h,line:l,error:u,nonce:(f?.nonce??0)+1}})}function lB(e,t,n,i){const o=CL.safeParse(e);o.success&&n({codeSearchResults:o.data,codeSearchLoading:!1})}function cB(e,t,n,i){const o=EL.safeParse(e);o.success&&n({referencesResult:o.data,referencesLoading:!1})}function uB(e,t,n,i){const o=c6.safeParse(e);o.success&&n({mailboxStatus:o.data,mailboxStatusLoading:!1})}function dB(e,t,n,i){const o=d6.safeParse(e);o.success&&n({externalSessionsSnapshot:o.data,externalSessionsLoading:!1})}function fB(e,t,n,i){const o=p6.safeParse(e);o.success&&n({repoEventsSnapshot:o.data,repoEventsLoading:!1})}function hB(e,t,n,i){const o=m6.safeParse(e);if(!o.success)return;const d=t().repoEventsSnapshot;if(!d)return;const h=[...d.events,o.data.event].slice(-200);n({repoEventsSnapshot:{...d,events:h,generatedAt:o.data.generatedAt}})}function pB(e,t,n,i){const o=Y3.safeParse(e);o.success&&n({permissionInputs:{...t().permissionInputs,[o.data.requestId]:o.data}})}function mB(e,t,n,i){const o=h6.safeParse(e);if(!o.success)return;const{cwd:d,preset:h}=o.data;if(!d)return;const l={...t().sessionPresetSnapshots,[d]:h};n({sessionPresetSnapshots:l})}function gB(e,t,n,i){const o=K3.safeParse(e);if(!o.success)return;const h=t().pendingPairRequests.filter(l=>l.requestId!==o.data.requestId);h.push(o.data),n({pendingPairRequests:h})}function vB(e,t,n,i){const o=W3.safeParse(e);if(!o.success)return;const d=t().pendingPairRequests.filter(h=>h.requestId!==o.data.requestId);n({pendingPairRequests:d})}function yB(e,t,n,i){const o=S6.safeParse(e);o.success&&n({runnerStatus:o.data,runnerStatusLoading:!1})}function bB(e,t,n,i){const o=C6.safeParse(e);o.success&&n({containersStatus:o.data,containersStatusLoading:!1})}function _B(e,t,n,i){const o=R6.safeParse(e);o.success&&n({repoRuntimeConfig:o.data,repoRuntimeConfigLoading:!1})}function SB(e,t,n,i){const o=D6.safeParse(e);o.success&&n({byokPoolStatus:o.data,byokPoolStatusLoading:!1})}function xB(e,t,n,i){const o=Z6.safeParse(e);o.success&&n({hostPruneStatus:o.data,hostPruneStatusLoading:!1})}function wB(e,t,n,i){const o=eL.safeParse(e);o.success&&n({simulatorStatus:o.data,simulatorStatusLoading:!1})}function kB(e,t,n,i){const o=iL.safeParse(e);o.success&&n({emulatorStatus:o.data,emulatorStatusLoading:!1})}function CB(e,t,n,i){const o=oL.safeParse(e);o.success&&n({wslStatus:o.data,wslStatusLoading:!1})}function EB(e,t,n,i){const o=H6.safeParse(e);o.success&&n({integrationStatus:o.data,integrationStatusLoading:!1})}function NB(e,t,n,i){const o=uL.safeParse(e);o.success&&n({skillsInventory:o.data,skillsInventoryLoading:!1})}function Bw(e,t,n,i){const o=new Set(e().reindexingRepoPaths);o.delete(n),t({reindexingRepoPaths:o,reindexResults:{...e().reindexResults,[n]:{...i,at:Date.now()}}})}function $w(e,t,n,i){const o=new Set(e().relayRerunningRepoPaths);o.delete(n),t({relayRerunningRepoPaths:o,relayRerunResults:{...e().relayRerunResults,[n]:{...i,at:Date.now()}}})}function jB(e,t,n,i){const o=K6.safeParse(e);if(o.success){if(o.data.action==="repo_relay_rerun"){$w(t,n,o.data.repoPath,{error:null});return}o.data.action==="repo_memory_reindex"&&Bw(t,n,o.data.repoPath,{counts:o.data.counts,error:null})}}function zw(e,t,n,i){const o=new Set(e().containerActioningIds);o.delete(n),t({containerActioningIds:o,containerActionResults:{...e().containerActionResults,[n]:{...i,at:Date.now()}}})}function AB(e,t,n,i){const o=W6.safeParse(e);o.success&&zw(t,n,o.data.environmentId,{action:o.data.action,status:o.data.status??null,error:null})}function Uw(e,t){return e==="recycle"&&typeof t=="string"&&t.length>0?`recycle:${t}`:e}function qw(e,t,n,i){const o=new Set(e().byokPoolActioningIds);o.delete(n),t({byokPoolActioningIds:o,byokPoolActionResults:{...e().byokPoolActionResults,[n]:{...i,at:Date.now()}}})}function RB(e,t,n,i){const o=G6.safeParse(e);if(!o.success)return;const{action:d,key:h,drained:l,evicted:u,limits:f}=o.data;let v;if(d==="resize"){const g=f?` (caps now ${f.maxPerKey}/key, ${f.maxTotal} total)`:"";v=`Resized — evicted ${u??0}${g}`}else v=`${d==="recycle"?"Recycled":"Drained"} — evicted ${l??0}`;qw(t,n,Uw(d,h),{action:d,note:v,error:null})}function Hw(e,t,n,i){const o=new Set(e().hostPruneActioningIds);o.delete(n),t({hostPruneActioningIds:o,hostPruneActionResults:{...e().hostPruneActionResults,[n]:{kind:n,...i,at:Date.now()}}})}function TB(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,i=0;for(;n>=1024&&i<t.length-1;)n/=1024,i++;return`${n.toFixed(n<10?2:1)} ${t[i]}`}function IB(e,t,n,i){const o=X6.safeParse(e);if(!o.success)return;const{kind:d,removedContainers:h,removedImages:l,reclaimedBytes:u,failures:f}=o.data;let v=`Removed ${h} container${h===1?"":"s"}, ${l} image${l===1?"":"s"} (~${TB(u)})`;f.length>0&&(v+=` — ${f.length} failed`),Hw(t,n,d,{note:v,error:null})}function Fw(e,t,n,i){const o=new Set(e().simulatorActioningIds);o.delete(n),t({simulatorActioningIds:o,simulatorActionResults:{...e().simulatorActionResults,[n]:{...i,at:Date.now()}}})}function MB(e,t,n,i){const o=tL.safeParse(e);if(!o.success)return;const{action:d,udid:h,status:l}=o.data,u=d==="boot"?"Booted":"Shutdown",f=d==="boot"?"Booted":"Shut down",v=l&&l!==u?`${f} (${l})`:f;Fw(t,n,h,{action:d,note:v,error:null})}function Kw(e,t,n,i){const o=new Set(e().emulatorActioningIds);o.delete(n),t({emulatorActioningIds:o,emulatorActionResults:{...e().emulatorActionResults,[n]:{...i,at:Date.now()}}})}function DB(e,t,n,i){const o=rL.safeParse(e);if(!o.success)return;const{action:d,avd:h,serial:l,status:u}=o.data,f=d==="boot"?h:l;if(!f)return;const v=d==="boot"?`Starting${u?`… (${u})`:"…"}`:`Killed${u?` (${u})`:""}`;Kw(t,n,f,{action:d,note:v,error:null})}function Ww(e,t,n,i){const o=new Set(e().wslActioningIds);o.delete(n),t({wslActioningIds:o,wslActionResults:{...e().wslActionResults,[n]:{...i,at:Date.now()}}})}function LB(e,t,n,i){const o=lL.safeParse(e);if(!o.success)return;const{action:d,distro:h,status:l}=o.data;if(!h)return;const u=d==="start"?"running":"stopped",f=d==="start"?"Started":"Terminated",v=l&&l!==u?`${f} (${l})`:f;Ww(t,n,h,{action:d,note:v,error:null})}function OB(e){const t=dL.safeParse(e);if(!t.success)return;const n=t.data.requestId;typeof n!="string"||!n||Q4(n,{summary:t.data.summary,truncated:!!t.data.truncated})}function PB(e,t,n,i){const o=bL.safeParse(e);if(!o.success)return;const{eraStarted:d,defaultProvider:h,defaultBillingClass:l,warnings:u}=o.data,f={eraStarted:d,defaultProvider:h,defaultBillingClass:l,warnings:u},v=t().billingCanary,g=w=>w?w.warnings.map(E=>`${E.code}\0${E.sessionId??""}\0${E.costUsd??""}\0${E.message}`).sort().join(""):"",S=g(v)!==g(f);n(S?{billingCanary:f,billingBannerDismissed:!1}:{billingCanary:f})}const BB={billing_canary:PB,pong:x5,terminal_size:w5,token_rotated:k5,pairing_refreshed:E5,thinking_level_changed:N5,prompt_evaluator_changed:j5,chroxy_context_hint_changed:A5,session_preamble_changed:R5,evaluator_rewrite:O5,evaluator_clarify:P5,skills_list:T5,skill_changed:I5,skill_activated:M5,skill_trust_accepted:L5,skill_deactivated:D5,skill_trust_request:B5,skill_trust_granted:$5,skill_trust_grant_ok:z5,session_switched:q5,claude_ready:H5,stream_start:F5,stream_delta:K5,stream_end:W5,tool_start:G5,tool_input_delta:V5,tool_result:Y5,permission_request:Z5,permission_resolved:X5,budget_exceeded:Q5,server_error:J5,activity_snapshot:eB,activity_delta:tB,cancel_activity_ack:nB,pair_pending:gB,pair_resolved:vB,symbols_snapshot:aB,symbol_location:oB,code_search_results:lB,references_result:cB,host_status_snapshot:rB,mailbox_status_snapshot:uB,external_sessions_snapshot:dB,repo_events_snapshot:fB,repo_events_delta:hB,permission_input:pB,session_preset_snapshot:mB,runner_status_snapshot:yB,containers_status_snapshot:bB,repo_runtime_config_snapshot:_B,byok_pool_status_snapshot:SB,host_prune_status_snapshot:xB,simulator_status_snapshot:wB,emulator_status_snapshot:kB,wsl_status_snapshot:CB,integration_status_snapshot:EB,skills_inventory_snapshot:NB,integration_action_ack:jB,containers_action_ack:AB,byok_pool_action_ack:RB,host_prune_action_ack:IB,simulator_action_ack:MB,emulator_action_ack:DB,wsl_action_ack:LB,summarize_session_result:OB};function $B(e,t){const n=t??Rw;if(!n||!e||typeof e!="object"||Array.isArray(e))return;const i=e;if(typeof i.type!="string")return;const o=()=>ln().getState(),d=l=>ln().setState(l);if(iN(i.type)){const l=typeof i.sessionId=="string"&&i.sessionId||o().activeSessionId;l&&o().sessionStates[l]&&!Wi.has(l)&&Ft(l,u=>{const f={lastClientActivityAt:Date.now()};return u.inactivityWarning&&(f.inactivityWarning=null),f})}if(m4(v5,i,g5))return;const h=BB[i.type];if(h){h(i,o,d,n);return}switch(i.type){case"auth_ok":{Wi.clear(),P0(),Dw(),Qo(),fg=n.url;const l=Aj(i),u=Qj(i.connectedClients,l.myClientId),f=l.sessionToken??n.token,v=o().activeServerId;l.sessionToken&&v&&o().updateServer(v,{token:l.sessionToken});const g=i.exposure,S=g&&typeof g=="object"?{lanBind:g.lanBind===!0,quickTunnel:g.quickTunnel===!0}:null,w=i.billingCanary,E=w&&tf.safeParse(w).success?tf.parse(w):null,x={connectionPhase:"connected",viewingCachedSession:!1,wsUrl:n.url,apiToken:f,socket:n.socket,claudeReady:!1,serverMode:l.serverMode,sessionCwd:l.sessionCwd,defaultCwd:l.defaultCwd,serverVersion:l.serverVersion,latestVersion:l.latestVersion,serverCommit:l.serverCommit,serverProtocolVersion:l.protocolVersion,serverResultTimeoutMs:l.resultTimeoutMs,streamStallTimeoutMs:l.streamStallTimeoutMs,streamingMessageId:null,myClientId:l.myClientId,connectedClients:u,connectionError:null,connectionRetryCount:0,serverPhase:null,tunnelProgress:null,serverExposure:S,billingCanary:E,shutdownReason:null,restartEtaMs:null,restartingSince:null,webFeatures:l.webFeatures,serverCapabilities:l.serverCapabilities};n.isReconnect?d(x):d({...x,exposureBannerDismissed:!1,billingBannerDismissed:!1,messages:[],terminalBuffer:"",terminalRawBuffer:"",sessions:[],activeSessionId:null,sessionStates:{},customAgents:[]}),l.availablePermissionModes&&d({availablePermissionModes:l.availablePermissionModes}),Dp=l.serverCapabilities.authBootstrap===!0;const m=()=>{Dp||(He(n.socket,{type:"list_providers"}),He(n.socket,{type:"list_slash_commands"}),He(n.socket,{type:"list_agents"}))};if(r5(n.socket),!S5(n,l.encryption)){bs=null,Ws=null;break}if(l.encryption==="required"){let y=!1;if(l.serverPublicKey&&bs){if(!nS(n,l.serverPublicKey,l.serverKeySig,l.newIdentityKey,l.rotationCert)){bs=null,Ws=null;break}try{const b=Gb(l.serverPublicKey,bs.secretKey);Mi={sharedKey:Ws?Vb(b,Ws):b,sendNonce:0,recvNonce:0},bs=null,Ws=null,y=!0,console.log("[crypto] E2E encryption established (eager)"),m(),Lp(),typeof document<"u"&&qd(n.socket,document.visibilityState==="visible")}catch(b){console.warn("[crypto] Eager key derivation failed, falling back to discrete key_exchange",b),Mi=null}}y||(bs||(bs=z0(),Ws=q0()),n.socket.send(JSON.stringify({type:"key_exchange",publicKey:bs.publicKey,salt:Ws})))}else m(),Lp(),typeof document<"u"&&qd(n.socket,document.visibilityState==="visible");y5(n.url,f),d({savedConnection:{url:n.url,token:f}});break}case"key_exchange_ok":{if(bs){const{publicKey:l,serverKeySig:u,newIdentityKey:f,rotationCert:v}=Tj(i);if(!l){console.error("[crypto] Invalid publicKey in key_exchange_ok message",i.publicKey),n.socket.close(),d({connectionPhase:"disconnected",socket:null}),bs=null,Ws=null;break}if(!nS(n,l,u,f,v)){bs=null,Ws=null;break}const g=Gb(l,bs.secretKey);Mi={sharedKey:Ws?Vb(g,Ws):g,sendNonce:0,recvNonce:0},bs=null,Ws=null,Qo(),console.log("[crypto] E2E encryption established"),Dp||(He(n.socket,{type:"list_providers"}),He(n.socket,{type:"list_slash_commands"}),He(n.socket,{type:"list_agents"})),Lp(),typeof document<"u"&&qd(n.socket,document.visibilityState==="visible")}break}case"auth_fail":{if(n.socket.close(),d({connectionPhase:"disconnected",socket:null}),!n.silent){const{reason:l}=Rj(i);Si.alert.alert("Auth Failed",l)}break}case"pair_fail":{n.socket.close(),d({connectionPhase:"disconnected",socket:null});const{reason:l}=Pj(i,"unknown"),u=o().activeServerId,f=u?o().serverRegistry.find(v=>v.id===u):void 0;if(f&&!f.token&&o().removeServer(u),l==="requires_approval"&&f?.wsUrl){d({pendingApprovalPairHost:{name:f.name,wsUrl:f.wsUrl}});break}n.silent||Si.alert.alert("Pairing Failed",`Pairing failed: ${l}`);break}case"server_mode":{const{mode:l}=Ij(i);l?d({serverMode:l}):Si.alert.alert("Invalid Server Mode",`Ignoring invalid server_mode value: ${i.mode}`);break}case"session_list":{const l=o().activeSessionId,u=tA(i,Object.keys(o().sessionStates),l);if(!u)break;const{sessionList:f,removedIds:v,newSessionIds:g,conversationIdPatches:S,cumulativeUsagePatches:w,backgroundShellBuilders:E}=u;for(const m of v)W_(m);if(v.length>0){const m={},y={...o().sessionStates};for(const _ of v)delete y[_];m.sessionStates=y;let b=o().activity;for(const _ of v)b=bN(b,_);if(b!==o().activity&&(m.activity=b),l&&v.includes(l)){const _=Object.keys(y),k=_.length>0?_[0]:null;if(m.activeSessionId=k,k&&y[k]){const j=y[k];m.messages=j.messages,m.streamingMessageId=j.streamingMessageId,m.claudeReady=j.claudeReady,m.activeModel=j.activeModel,m.permissionMode=j.permissionMode,m.contextUsage=j.contextUsage,m.lastResultCost=j.lastResultCost,m.lastResultDuration=j.lastResultDuration,m.isIdle=j.isIdle}else m.messages=[],m.streamingMessageId=null,m.claudeReady=!1,m.activeModel=null,m.permissionMode=null,m.contextUsage=null,m.lastResultCost=null,m.lastResultDuration=null,m.isIdle=!0}d(m)}d({sessions:f});const x=o().activeSessionId;if(x){const m=f.find(y=>y.sessionId===x);if(m?.model){const y=m.model,_=o().availableModels.find(k=>k.fullId===y||k.id===y);d({activeModel:_?_.id:y})}}if(g.length>0){const y={...o().sessionStates},b=new Map(f.map(_=>[_.sessionId,_]));for(const _ of g)if(!y[_]){const k=bf(),j=b.get(_);j&&typeof j.isBusy=="boolean"&&(k.isIdle=!j.isBusy),y[_]=k}d({sessionStates:y})}for(const m of f){if(typeof m.isBusy!="boolean"||!o().sessionStates[m.sessionId])continue;const y=!m.isBusy;Ft(m.sessionId,b=>b.isIdle===y?{}:{isIdle:y})}for(const[m,y]of S)o().sessionStates[m]&&Ft(m,b=>b.conversationId!==y?{conversationId:y}:{});for(const[m,y]of w)o().sessionStates[m]&&Ft(m,b=>eA(b.cumulativeUsage,y)?{}:{cumulativeUsage:y});for(const[m,y]of E)o().sessionStates[m]&&Ft(m,b=>{const _=y.applyTo(b.pendingBackgroundShells);return _===b.pendingBackgroundShells?{}:{pendingBackgroundShells:_}});break}case"monthly_budget":{const l=typeof i.month=="string"?i.month:null;if(l){const u=E=>typeof E=="number"&&Number.isFinite(E)?E:0,f=E=>E===null?null:typeof E=="number"&&Number.isFinite(E)?E:null,v=u(i.spentUsd),g=f(i.budgetUsd);ln().setState({monthlyBudget:{month:l,spentUsd:v,turnsBilled:u(i.turnsBilled),budgetUsd:g,warningPercent:u(i.warningPercent),percent:f(i.percent),warning:i.warning===!0,exceeded:i.exceeded===!0}});const S=g!=null?`$${g.toFixed(2)}`:"",w=`$${v.toFixed(2)}`;if(i.justExceeded===!0)o().addInfoNotification(`Monthly programmatic-credit budget exceeded — ${w}${S?` of ${S}`:""} of your credit pool spent this month (chroxy-observed).`);else if(i.justWarned===!0){const E=f(i.percent);o().addInfoNotification(`Monthly credit budget at ${E!=null?`${Math.round(E)}%`:"the warning threshold"} — ${w}${S?` of ${S}`:""} spent this month (chroxy-observed).`)}}break}case"session_activity":{const l=typeof i.sessionId=="string"?i.sessionId:null,u=typeof i.isBusy=="boolean"?i.isBusy:null;if(l&&u!==null&&o().sessionStates[l]){const f=!u;Ft(l,v=>v.isIdle===f?{}:{isIdle:f})}break}case"evaluate_draft_result":{const l=typeof i.requestId=="string"?i.requestId:null;if(l){const u=ca.get(l);u&&(ca.delete(l),window.clearTimeout(u.timeoutId),u.resolve({verdict:i.verdict,rewritten:typeof i.rewritten=="string"?i.rewritten:null,clarification:typeof i.clarification=="string"?i.clarification:null,reasoning:typeof i.reasoning=="string"?i.reasoning:"",error:i.error}))}break}case"session_error":{const l=nj(i,o().activeSessionId);if(l.code==="CANCEL_ACTIVITY_FAILED"&&typeof i.sessionId=="string"&&typeof i.activityId=="string")hg(o,d,i.sessionId,i.activityId);else if(l.code==="SESSION_NOT_FOUND")iB(o,d,l.attemptedSessionId??void 0);else if(l.code==="SUMMARIZE_FAILED"&&typeof i.requestId=="string"){J4(i.requestId,l.message||"Could not summarize this session.");return}else if(l.code==="INTEGRATION_ACTION_FAILED"&&typeof i.repoPath=="string")i.action==="repo_relay_rerun"?$w(o,d,i.repoPath,{error:l.message||"Re-run failed."}):i.action==="repo_memory_reindex"&&Bw(o,d,i.repoPath,{counts:null,error:l.message||"Reindex failed."});else if(l.code==="CONTAINER_ACTION_FAILED"&&typeof i.environmentId=="string")zw(o,d,i.environmentId,{action:typeof i.action=="string"?i.action:"",status:null,error:l.message||"Container action failed."});else if(l.code==="BYOK_POOL_ACTION_FAILED"&&typeof i.action=="string")qw(o,d,Uw(i.action,typeof i.key=="string"?i.key:null),{action:i.action,note:null,error:l.message||"BYOK pool action failed."});else if(l.code==="HOST_PRUNE_ACTION_FAILED"&&typeof i.kind=="string")Hw(o,d,i.kind,{note:null,error:l.message||"Host prune failed."});else if(l.code==="SIMULATOR_ACTION_FAILED"&&typeof i.udid=="string")Fw(o,d,i.udid,{action:typeof i.action=="string"?i.action:"",note:null,error:l.message||"Simulator action failed."});else if(l.code==="EMULATOR_ACTION_FAILED"&&(typeof i.avd=="string"||typeof i.serial=="string")){const u=typeof i.action=="string"?i.action:"",f=u==="boot"?typeof i.avd=="string"?i.avd:"":typeof i.serial=="string"?i.serial:"";f&&Kw(o,d,f,{action:u,note:null,error:l.message||"Emulator action failed."})}else l.code==="WSL_ACTION_FAILED"&&typeof i.distro=="string"&&Ww(o,d,i.distro,{action:typeof i.action=="string"?i.action:"",note:null,error:l.message||"WSL action failed."});if(l.category==="crash"&&l.sessionPatch){const u=l.sessionPatch.sessionId;u&&o().sessionStates[u]&&(Ft(u,()=>({health:"crashed"})),of(u,"error","Session crashed"))}else if(l.code==="SESSION_NOT_FOUND")o().setSessionNotFoundError({attemptedSessionId:l.attemptedSessionId??null,message:l.message??"Session not found."}),d({activeSessionId:null}),l.message&&(Si.alert.alert("Session Restarted",l.message),o().addServerError(l.message));else if(l.category==="input_conflict"){const u=typeof i.sessionId=="string"?i.sessionId:o().activeSessionId,f=typeof i.clientMessageId=="string"&&i.clientMessageId.length>0?i.clientMessageId:null,v=g=>vr(g).filter(S=>!(f&&S.id===f&&S.type==="user_input"));u&&o().sessionStates[u]?Ft(u,g=>({messages:v(g.messages),streamingMessageId:g.streamingMessageId==="pending"?null:g.streamingMessageId,...g.streamingMessageId==="pending"?{pendingClientMessageId:null}:{}})):d(g=>({messages:v(g.messages),streamingMessageId:g.streamingMessageId==="pending"?null:g.streamingMessageId})),o().addInfoNotification(l.message||"Your message wasn’t sent — the session is busy. Wait for it to finish, or interrupt the current run.")}else l.message&&(Si.alert.alert("Session Error",l.message),o().addServerError(l.message));break}case"history_replay_start":{const{fullHistory:l,sessionId:u}=fA(i,o().activeSessionId);u&&Wi.add(u);{const f=u&&o().sessionStates[u]?.messages.length||0;oE(u,l,f)}Cs(f=>{const v={};return f.activeAgents.length>0&&(v.activeAgents=[]),f.isPlanPending&&(v.isPlanPending=!1,v.planAllowedPrompts=[]),Object.keys(v).length>0?v:{}});break}case"history_replay_end":{const l=typeof i.sessionId=="string"&&i.sessionId||o().activeSessionId;l&&Wi.delete(l);const u=typeof i.latestSeq=="number"&&Number.isFinite(i.latestSeq)?i.latestSeq:void 0;if(l&&o().sessionStates[l]){const{swappedMessages:f}=Bb(l,o().sessionStates[l].messages,u);f&&Ft(l,()=>({messages:f}))}else Bb(l,[],u)}Cs(l=>l.messages.some(f=>f.type==="prompt"&&!f.answered)?{messages:l.messages.map(f=>f.type==="prompt"&&!f.answered?{...f,answered:"(resolved)"}:f)}:{});break;case"user_input":{const l=PA(i,o().myClientId,o().activeSessionId);if(!l)break;l.content&&o().appendTerminalData(`\r
|
|
59
|
-
\x1B[33m> ${l.content}\x1B[0m\r
|
|
60
|
-
\r
|
|
61
|
-
`),Ft(l.sessionId,u=>{const f={messages:[...u.messages,l.chatMessage]};return u.pendingEvaluatorClarify&&(f.pendingEvaluatorClarify=null),f});break}case"message":{const l=on(i,o().activeSessionId),u=l?o().sessionStates[l]:null,f=B0(l,u?u.messages:o().messages),v=l?Wi.has(l):!1;v&&Hm(l,i.historySeq);const g=OL(i,o().activeSessionId,v,f);if(!g.shouldDispatch)break;const S=g.chatMessage;l&&o().sessionStates[l]?Ft(l,w=>({messages:[...w.messages.filter(E=>E.id!=="thinking"||S.id==="thinking"),S]})):o().addMessage(S),g.isRateLimitError&&g.errorContent&&Si.alert.alert("Usage Limit",g.errorContent);break}case"result":{fl.flushNow(),Kc.clear(),xr.clear();const l=FL(i,o().activeSessionId),u=l.sessionId;let f=l.lastResultCost;if(f===null&&l.contextUsage){const g=o().sessions.find(E=>E.sessionId===u),S=g?.model??null,w=g?.provider??null;S&&w&&vw.has(w)&&(f=iP(S,l.contextUsage.inputTokens,l.contextUsage.outputTokens))}const v={streamingMessageId:null,contextUsage:l.contextUsage,lastResultCost:f,lastResultDuration:l.lastResultDuration};u&&o().sessionStates[u]?.streamingMessageId&&of(u,"completed","Task completed"),u&&o().sessionStates[u]?Ft(u,g=>{const S={...v,messages:[...g.messages]};return g.activeTools.length>0&&!Wi.has(u)&&(S.activeTools=[]),S}):d(g=>({...v,messages:[...g.messages]}));break}case"permission_expired":{const{requestId:l,systemMessage:u}=wj(i);if(l){if(d(S=>{if(!S.permissionInputs||!Object.prototype.hasOwnProperty.call(S.permissionInputs,l))return{};const w={...S.permissionInputs};return delete w[l],{permissionInputs:w}}),!!o().resolvedPermissions?.[l]){const S=Date.now();d(w=>({sessionNotifications:w.sessionNotifications.map(E=>E.requestId===l&&E.readAt===void 0?{...E,readAt:S}:E)})),o().addInfoNotification("Already answered — your response was already recorded");break}console.warn(`[ws] Permission ${l} expired: ${i.message}`);const v=i.sessionId||o().activeSessionId;v&&o().sessionStates[v]&&Ft(v,S=>({messages:S.messages.map(w=>w.requestId===l&&w.type==="prompt"?{...w,content:`${w.content}
|
|
62
|
-
${u.content}`,options:void 0}:w)}));const g=Date.now();d(S=>({sessionNotifications:S.sessionNotifications.map(w=>w.requestId===l&&w.readAt===void 0?{...w,readAt:g}:w)}))}break}case"permission_timeout":{const{requestId:l,systemMessage:u}=kj(i);if(l){const f=w=>({messages:w.messages.map(E=>E.requestId===l&&E.type==="prompt"?{...E,content:`${E.content}
|
|
63
|
-
(Auto-denied — permission timed out)`,options:void 0}:E)}),v=o().sessionStates;let g=!1;for(const w of Object.keys(v))if(v[w]?.messages.some(E=>E.requestId===l)){Ft(w,f),g=!0;break}g||d({messages:f({messages:o().messages}).messages});const S=Date.now();d(w=>({sessionNotifications:w.sessionNotifications.map(E=>E.requestId===l&&E.readAt===void 0?{...E,readAt:S}:E)})),d(w=>{if(!w.permissionInputs||!Object.prototype.hasOwnProperty.call(w.permissionInputs,l))return{};const E={...w.permissionInputs};return delete E[l],{permissionInputs:E}})}o().addServerError(u.content);break}case"server_status":{const l=i.phase;if(l==="tunnel_warming"||l==="tunnel_verifying"){const v=typeof i.attempt=="number"?i.attempt:null,g=typeof i.maxAttempts=="number"?i.maxAttempts:null;d({serverPhase:"tunnel_warming",tunnelProgress:v!=null&&g!=null?{attempt:v,maxAttempts:g}:null});break}if(l==="ready"){const v={serverPhase:"ready",tunnelProgress:null};if(i.tunnelMode==="quick"){const g=o().serverExposure;v.serverExposure={lanBind:g?.lanBind??!1,quickTunnel:!0}}d(v);break}const{chatMessage:u}=Wj(i),f=o().activeSessionId;f&&o().sessionStates[f]?Cs(v=>({messages:[...v.messages,u]})):o().addMessage(u);break}case"client_joined":{const l=Vj(i,o().connectedClients);if(!l)break;d({connectedClients:l.roster});const u=l.client.deviceName||"A device",f={id:fn("client"),type:"system",content:`${u} connected`,timestamp:Date.now()};Object.keys(o().sessionStates).length>0?d(g=>{const S={};for(const x in g.sessionStates){const m=g.sessionStates[x];S[x]={...m,messages:[...m.messages,f]}}const w=g.activeSessionId,E={sessionStates:S};return w&&S[w]&&(E.messages=S[w].messages),E}):o().addMessage(f);break}case"client_left":{const l=Yj(i,o().connectedClients);if(!l)break;d({connectedClients:l.roster});const u=l.departingClient?.deviceName||"A device",f={id:fn("client"),type:"system",content:`${u} disconnected`,timestamp:Date.now()};Object.keys(o().sessionStates).length>0?d(g=>{const S={};for(const x in g.sessionStates){const m=g.sessionStates[x];S[x]={...m,messages:[...m.messages,f]}}const w=g.activeSessionId,E={sessionStates:S};return w&&S[w]&&(E.messages=S[w].messages),E}):o().addMessage(f);break}case"directory_listing":{const l=o()._directoryListingCallback;if(l){const u=ox(i);l({...u,entries:u.entries})}break}case"file_listing":{const l=o()._fileBrowserCallback;if(l){const u=lx(i);l({...u,entries:u.entries})}break}case"file_content":{const l=o()._fileContentCallback;l&&l(cx(i));break}case"diff_result":{const l=o()._diffCallback;if(l){const u=ux(i);l({files:u.files,error:u.error})}break}case"git_status_result":{const l=o()._gitStatusCallback;if(l){const u=dx(i);l({branch:u.branch,staged:u.staged,unstaged:u.unstaged,untracked:u.untracked,error:u.error})}break}case"file_list":{const l=tO(i);d({filePickerFiles:l.files});break}case"byok_credentials_status":{const l=hL.safeParse(i);if(!l.success){console.warn("byok_credentials_status: invalid payload from server",l.error.issues);break}const u=l.data;d({byokCredentialsStatus:{status:u.status,source:u.source,masked:u.masked,reason:u.reason,fileExists:u.fileExists}});break}case"credentials_status":{const l=mL.safeParse(i);if(!l.success){console.warn("credentials_status: invalid payload from server",l.error.issues);break}const u=l.data;d({credentialsStatus:{credentials:u.credentials.map(f=>({key:f.key,provider:f.provider,label:f.label,kind:f.kind,status:f.status,source:f.source,masked:f.masked,oauth:f.oauth})),fileExists:u.fileExists,fileError:u.fileError??null}});break}case"credential_test_result":{const l=gL.safeParse(i);if(!l.success){console.warn("credential_test_result: invalid payload from server",l.error.issues);break}const u=l.data;d(f=>({credentialTestResults:{...f.credentialTestResults,[u.key]:{ok:u.ok,error:u.error,model:u.model,latencyMs:u.latencyMs}}}));break}case"web_task_error":{const{taskId:l,errorMessage:u,chatMessageContent:f}=IA(i);l&&d(S=>({webTasks:S.webTasks.map(w=>w.taskId===l?{...w,status:"failed",error:u,updatedAt:Date.now()}:w)}));const v={id:fn("web"),type:"system",content:f,timestamp:Date.now()},g=o().activeSessionId;g&&o().sessionStates[g]?Cs(S=>({messages:[...S.messages,v]})):o().addMessage(v);break}case"log_entry":{const{entry:l}=rj(i);d(u=>({logEntries:[...u.logEntries,l].slice(-500)}));break}case"shell_pending_approval":{const l=typeof i.approvalId=="string"?i.approvalId:"";ln().getState().addInfoNotification(`Shell pending host approval — run \`chroxy shell approve ${l}\` on the host machine`);break}case"session_warning":{const{sessionId:l,message:u,systemMessage:f}=oA(i);if(l&&o().sessionStates[l]){const v=o().activeSessionId;d(g=>{const S=g.sessionStates[l];return{sessionStates:{...g.sessionStates,[l]:{...S,messages:[...S.messages,f]}}}}),v!==l&&Si.alert.alert("Session Warning",u)}else o().addMessage(f);break}case"session_timeout":{const{sessionId:l,name:u}=iA(i);if(Si.alert.alert("Session Closed",`Session "${u}" was closed due to inactivity.`),l){const{sessionStates:f,sessions:v}=o(),g={...f};delete g[l];const S=v.filter(E=>E.sessionId!==l),w={sessionStates:g,sessions:S};if(o().activeSessionId===l){const E=Object.keys(g),x=E.length>0?E[0]:null;if(w.activeSessionId=x,x&&g[x]){const m=g[x];w.messages=m.messages,w.streamingMessageId=m.streamingMessageId,w.claudeReady=m.claudeReady,w.activeModel=m.activeModel,w.permissionMode=m.permissionMode,w.contextUsage=m.contextUsage,w.lastResultCost=m.lastResultCost,w.lastResultDuration=m.lastResultDuration,w.isIdle=m.isIdle}else w.messages=[],w.streamingMessageId=null,w.claudeReady=!1,w.activeModel=null,w.permissionMode=null,w.contextUsage=null,w.lastResultCost=null,w.lastResultDuration=null,w.isIdle=!0}d(w),W_(l)}break}case"environment_list":{const{environments:l}=EA(i);d({environments:l});break}case"environment_created":case"environment_destroyed":case"environment_info":break;case"environment_error":{const{error:l}=NA(i);console.error("[ws] Environment error:",l);break}case"error":{const{code:l,message:u,fatal:f,partialCost:v}=qj(i),g=v?aN(v):void 0;console.error(`[ws] Server handler error [${l}]: ${u}`);const S=typeof i.requestId=="string"?i.requestId:null;if(S&&U5(S,o),l==="MODEL_NOT_APPLIED"&&S){const k=FP(S);k&&(k.sessionId&&o().sessionStates[k.sessionId]?Ft(k.sessionId,()=>({activeModel:k.previousModel})):d({activeModel:k.previousModel}))}if(l==="PERMISSION_MODE_NOT_APPLIED"&&S){const k=GP(S);k&&(k.sessionId&&o().sessionStates[k.sessionId]?Ft(k.sessionId,()=>({permissionMode:k.previousMode})):d({permissionMode:k.previousMode}),k.priorPreviousMode!==void 0&&o().previousPermissionMode===k.previousMode&&d({previousPermissionMode:k.priorPreviousMode}))}if(l==="THINKING_LEVEL_NOT_APPLIED"&&S){const k=ZP(S);k?.sessionId&&o().sessionStates[k.sessionId]&&Ft(k.sessionId,()=>({thinkingLevel:k.previousLevel??"default"}))}const w=typeof i.actualAuthor=="string"&&i.actualAuthor.length>0?i.actualAuthor:null,E=typeof i.requestId=="string"?i.requestId:null,x=E!==null?Aw(E):null;let m,y;if(l==="INVALID_AUTHOR"&&w!==null)if(x){const k=x.skillName;m=`Skill is owned by '${w}', not '${x.author}'. Try as ${w}?`,y={label:`Try as ${w}`,onClick:()=>{o().grantCommunitySkillTrust(k,w)}}}else m=`Skill is owned by '${w}'. Use the 'Trust ${w}' button on the pending entry instead.`;else m=u;const _=f===!1||p5.has(l)?"warning":"error";o().addServerError(m,y,_,g);break}default:{const l=ln().getState().serverProtocolVersion;l!=null&&l>Sm&&console.warn(`[ws] Unknown message type "${i.type}" (server protocol v${l}, client v${Sm})`);break}}}const Oc="obf:v1:",Gw="enc:v1:";function Vw(){const t=`chroxy-token-key:${typeof window<"u"?window.location.origin:"chroxy-dashboard"}`,n=[];for(let i=0;i<t.length;i++)n.push(t.charCodeAt(i));return n}function zB(e){if(!e)return e;const t=Vw(),n=[];for(let o=0;o<e.length;o++)n.push(e.charCodeAt(o)^t[o%t.length]);let i="";for(let o=0;o<n.length;o++)i+=String.fromCharCode(n[o]);return Oc+btoa(i)}function UB(e){if(!e||!e.startsWith(Oc)&&!e.startsWith(Gw))return e;if(e.startsWith(Oc))try{const t=e.slice(Oc.length),n=atob(t),i=Vw();let o="";for(let d=0;d<n.length;d++)o+=String.fromCharCode(n.charCodeAt(d)^i[d%i.length]);return o}catch{return e}return e}function Yw(e){return e.startsWith(Oc)||e.startsWith(Gw)}const Zw="chroxy_server_registry";function qB(){return`srv_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`}function HB(){try{const e=localStorage.getItem(Zw);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];let n=!1;const i=t.filter(o=>o!=null&&typeof o=="object"&&typeof o.id=="string").map(o=>typeof o.token=="string"&&Yw(o.token)?{...o,token:UB(o.token)}:(typeof o.token=="string"&&o.token&&(n=!0),o));return n&&Gc(i),i}catch{return[]}}function Gc(e){try{const t=e.map(n=>({...n,token:n.token&&!Yw(n.token)?zB(n.token):n.token}));localStorage.setItem(Zw,JSON.stringify(t))}catch{}}function Xw(e){const t=e.trim();if(!t)return"URL is required";if(!/^wss?:\/\//i.test(t))return"URL must start with ws:// or wss://";try{new URL(t)}catch{return"Invalid URL format"}return null}function FB(e,t,n,i){const o=Xw(n);if(o)throw new Error(o);const d={id:qB(),name:t.trim()||"Unnamed Server",wsUrl:n.trim(),token:i.trim(),lastConnectedAt:null},h=[...e,d];return Gc(h),[h,d]}function KB(e,t){const n=e.filter(i=>i.id!==t);return Gc(n),n}function WB(e,t,n){const i={};if(n.name!==void 0&&(i.name=n.name.trim()||"Unnamed Server"),n.wsUrl!==void 0){const d=Xw(n.wsUrl);if(d)throw new Error(d);i.wsUrl=n.wsUrl.trim()}n.token!==void 0&&(i.token=n.token.trim()),n.pinnedIdentityKey!==void 0&&(i.pinnedIdentityKey=n.pinnedIdentityKey);const o=e.map(d=>d.id===t?{...d,...i}:d);return Gc(o),o}function GB(e,t){const n=e.map(i=>i.id===t?{...i,lastConnectedAt:Date.now()}:i);return Gc(n),n}function li(){const t=new URLSearchParams(window.location.search).get("token");if(t)return t;const n=document.cookie.match(/(?:^|;\s*)chroxy_auth=([^;]*)/);if(!n||!n[1])return null;try{return decodeURIComponent(n[1])}catch{return null}}const VB=Object.freeze(Object.defineProperty({__proto__:null,getAuthToken:li},Symbol.toStringTag,{value:"Module"})),YB="Switch to Auto mode? Tools will run without asking for permission.",ZB=`Switch to Auto mode?
|
|
64
|
-
|
|
65
|
-
This session is mid-response. On this provider, switching to Auto will INTERRUPT the running turn and restart the session — the in-flight response will be dropped.
|
|
66
|
-
|
|
67
|
-
Tools will then run without asking for permission. Continue?`;function XB(e){return e.interruptsTurn&&e.isStreaming?ZB:YB}const lf="cost",Qw={"provider-model":!0,cost:!0,tokens:!0,"context-pct":!0,"session-type":!0},QB=Object.keys(Qw);function Jw(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(Qw,e)}const JB={"provider-model":"Provider / model",cost:"Cost ($)",tokens:"Token count","context-pct":"% of context used","session-type":"Session type"},vc=" ";function e$(e){const{mode:t=lf,cost:n,provider:i,model:o,inputTokens:d,outputTokens:h,contextPercent:l}=e;switch(t){case"cost":return n!=null&&Number.isFinite(n)?`$${n.toFixed(4)}`:vc;case"tokens":{const u=(d??0)+(h??0);return u>0?`${Ga(u)} tokens`:vc}case"context-pct":return l!=null&&Number.isFinite(l)?`${Math.round(l)}%`:vc;case"session-type":return i?Vi(i).short:vc;default:{if(!i)return o||vc;const u=Vi(i).label;return o?`${u} · ${o}`:u}}}const sS="chroxy_input_settings",t$=new Set(["auth_ok","key_exchange_ok"]),n$=new Set(["auth_fail","pair_fail"]),e1=new Set(["Read","Write","Edit","NotebookEdit","Glob","Grep"]);function cf(e){return e1.has(e)}function t1(e,t){return e?t.find(i=>i.name===e)?.capabilities?.sessionRules===!0:!1}const s$=1e3;function i$(e,t,n,i=s$){const o={...e};t in o&&delete o[t],o[t]=n;const d=Object.keys(o);if(d.length>i){const h=d.length-i;for(let l=0;l<h;l++)delete o[d[l]]}return o}function yc(e,t){try{return localStorage.getItem(e)??t}catch{return t}}const r$=[],a$=[],o$=[],l$=[],c$=[],u$=[],d$=[],f$=[],iS=[];function Bp(e){const t={};for(const n of Object.keys(e)){const i=e[n];i&&(Array.isArray(i.pendingTrustGrants)&&i.pendingTrustGrants.length>0?t[n]={...i,pendingTrustGrants:[]}:t[n]=i)}return t}let rS=0,aS,h$=0,$p=null;const oS="chroxy_device_id";let Nd=null;function n1(){if(Nd)return Nd;try{const t=localStorage.getItem(oS);if(t)return Nd=t,t}catch{}const e=`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;Nd=e;try{localStorage.setItem(oS,e)}catch{}return e}function p$(){return{deviceName:"Desktop Browser",deviceType:"desktop",platform:"web"}}function m$(){try{const e=n1();return e.length>0?e:null}catch{return null}}const km=CP();km&&zd(km);function lS(e){const t=e();return t.sessions.find(n=>n.sessionId===t.activeSessionId)?.provider===yf}const V=gw((e,t)=>({connectionPhase:"disconnected",wsUrl:null,apiToken:null,socket:null,serverRegistry:HB(),activeServerId:km,hasLocalServer:typeof window<"u"&&!!li(),serverMode:null,sessionCwd:null,defaultCwd:null,serverVersion:null,latestVersion:null,serverCommit:null,serverProtocolVersion:null,serverResultTimeoutMs:null,streamStallTimeoutMs:null,sessions:[],activeSessionId:null,sessionStates:{},activity:Pd(),cancellingActivityIds:new Set,pendingPairRequests:[],pendingApprovalPairHost:null,hostStatus:null,hostStatusLoading:!1,symbols:null,symbolsLoading:!1,mailboxStatus:null,mailboxStatusLoading:!1,externalSessionsSnapshot:null,externalSessionsLoading:!1,repoEventsSnapshot:null,repoEventsLoading:!1,sessionPresetSnapshots:{},pendingServerSeed:{},runnerStatus:null,runnerStatusLoading:!1,containersStatus:null,containersStatusLoading:!1,repoRuntimeConfig:null,repoRuntimeConfigLoading:!1,byokPoolStatus:null,byokPoolStatusLoading:!1,hostPruneStatus:null,hostPruneStatusLoading:!1,integrationStatus:null,integrationStatusLoading:!1,skillsInventory:null,skillsInventoryLoading:!1,reindexingRepoPaths:new Set,reindexResults:{},permissionInputs:{},relayRerunningRepoPaths:new Set,relayRerunResults:{},containerActioningIds:new Set,containerActionResults:{},byokPoolActioningIds:new Set,byokPoolActionResults:{},hostPruneActioningIds:new Set,hostPruneActionResults:{},simulatorStatus:null,simulatorStatusLoading:!1,simulatorActioningIds:new Set,simulatorActionResults:{},emulatorStatus:null,emulatorStatusLoading:!1,emulatorActioningIds:new Set,emulatorActionResults:{},wslStatus:null,wslStatusLoading:!1,wslActioningIds:new Set,wslActionResults:{},claudeReady:!1,streamingMessageId:null,activeModel:null,availableProviders:[],environments:[],pairingRefreshedCount:0,availableModels:[],availableModelsProvider:null,defaultModelId:null,permissionMode:null,previousPermissionMode:null,availablePermissionModes:[],myClientId:null,connectedClients:[],primaryClientId:null,followMode:!1,activeTheme:yc("chroxy_persist_theme","default"),defaultProvider:yc("chroxy_default_provider",yf),defaultModel:yc("chroxy_default_model",""),costBadgeMode:(()=>{const n=yc("chroxy_cost_badge_mode",lf);return Jw(n)?n:lf})(),confirmSessionClose:yc("chroxy_confirm_session_close","true")!=="false",byokCredentialsStatus:null,credentialsStatus:null,credentialTestResults:{},notificationPrefs:null,currentDeviceKey:m$(),connectionError:null,connectionRetryCount:0,serverStartupLogs:null,latencyMs:null,connectionQuality:null,logEntries:[],serverErrors:[],infoNotifications:[],sessionNotifications:[],monthlyBudget:null,sessionNotFoundError:null,resolvedPermissions:{},serverPhase:null,tunnelProgress:null,serverExposure:null,exposureBannerDismissed:!1,billingCanary:null,billingBannerDismissed:!1,shutdownReason:null,restartEtaMs:null,restartingSince:null,pendingPermissionConfirm:null,slashCommands:[],filePickerFiles:null,fileBrowserPendingOpen:null,workspaceSymbols:null,workspaceSymbolsLoading:!1,symbolLocation:null,codeSearchResults:null,codeSearchLoading:!1,referencesResult:null,referencesSymbol:"",referencesOpen:!1,referencesLoading:!1,customAgents:[],checkpoints:[],_directoryListingCallback:null,_fileBrowserCallback:null,_fileContentCallback:null,lastFileContentRequestId:null,_gitStatusCallback:null,_diffCallback:null,conversationHistory:[],conversationHistoryLoading:!1,searchResults:[],searchLoading:!1,searchQuery:"",contextUsage:null,lastResultCost:null,lastResultDuration:null,isIdle:!0,inputSettings:{chatEnterToSend:!0,terminalEnterToSend:!1,voiceInputMode:"continuous"},savedConnection:null,userDisconnected:!1,viewingCachedSession:!1,viewMode:"chat",messages:[],terminalBuffer:"",terminalRawBuffer:"",_terminalWriteCallback:null,closeDevPreview:n=>{const{socket:i,activeSessionId:o}=t();i&&i.readyState===WebSocket.OPEN&&He(i,{type:"close_dev_preview",port:n,sessionId:o})},subscribeTerminalMirror:n=>{const{socket:i}=t();n&&i&&i.readyState===WebSocket.OPEN&&(He(i,{type:"terminal_subscribe",sessionId:n}),He(i,{type:"terminal_resync",sessionId:n}))},requestTerminalResync:n=>{const{socket:i}=t();n&&i&&i.readyState===WebSocket.OPEN&&He(i,{type:"terminal_resync",sessionId:n})},unsubscribeTerminalMirror:n=>{const{socket:i}=t();n&&i&&i.readyState===WebSocket.OPEN&&He(i,{type:"terminal_unsubscribe",sessionId:n})},setTerminalSize:(n,i,o)=>{const d=t().sessionStates[n];if(!d)return;const h=d.terminalSize;h&&h.cols===i&&h.rows===o||e(l=>({sessionStates:{...l.sessionStates,[n]:{...d,terminalSize:{cols:i,rows:o}}}}))},requestTerminalResize:(n,i,o)=>{const{socket:d}=t();n&&i>0&&o>0&&d&&d.readyState===WebSocket.OPEN&&He(d,{type:"terminal_resize",sessionId:n,cols:i,rows:o})},sendTerminalInput:(n,i)=>{const{socket:o}=t();if(!n||!i||!o||o.readyState!==WebSocket.OPEN)return;const d=65536;if(i.length<=d){He(o,{type:"terminal_input",sessionId:n,data:i});return}let h=0;for(;h<i.length;){let l=Math.min(h+d,i.length);if(l<i.length){const u=i.charCodeAt(l-1);u>=55296&&u<=56319&&(l-=1)}He(o,{type:"terminal_input",sessionId:n,data:i.slice(h,l)}),h=l}},webFeatures:{available:!1,remote:!1,teleport:!1},webTasks:[],serverCapabilities:{},launchWebTask:(n,i)=>{const{socket:o}=t();if(o&&o.readyState===WebSocket.OPEN){const d={type:"launch_web_task",prompt:n};return i&&(d.cwd=i),He(o,d),"sent"}return!1},listWebTasks:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"list_web_tasks"})},teleportWebTask:n=>{const{socket:i}=t();i&&i.readyState===WebSocket.OPEN&&He(i,{type:"teleport_web_task",taskId:n})},viewCachedSession:()=>{const{activeSessionId:n,sessionStates:i}=t();n&&(i[n]?.messages.length??0)>0&&e({viewingCachedSession:!0})},exitCachedSession:()=>{e({viewingCachedSession:!1})},setFollowMode:n=>{e({followMode:n})},setTheme:n=>{e({activeTheme:n});try{localStorage.setItem("chroxy_persist_theme",n)}catch{}},setDefaultProvider:n=>{e({defaultProvider:n});try{localStorage.setItem("chroxy_default_provider",n)}catch{}},setDefaultModel:n=>{e({defaultModel:n});try{localStorage.setItem("chroxy_default_model",n)}catch{}},setCostBadgeMode:n=>{e({costBadgeMode:n});try{localStorage.setItem("chroxy_cost_badge_mode",n)}catch{}},setConfirmSessionClose:n=>{e({confirmSessionClose:n});try{localStorage.setItem("chroxy_confirm_session_close",n?"true":"false")}catch{}},refreshByokCredentialsStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(He(n,{type:"byok_get_credentials_status"}),!0):!1},setByokCredentials:n=>{const{socket:i}=t();return i&&i.readyState===WebSocket.OPEN?(He(i,{type:"byok_set_credentials",anthropicApiKey:n}),!0):!1},clearByokCredentials:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(He(n,{type:"byok_clear_credentials"}),!0):!1},refreshCredentialsStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(He(n,{type:"get_credentials_status"}),!0):!1},setCredential:(n,i)=>{const{socket:o}=t();return o&&o.readyState===WebSocket.OPEN?(He(o,{type:"set_credential",key:n,value:i}),!0):!1},deleteCredential:n=>{const{socket:i}=t();return i&&i.readyState===WebSocket.OPEN?(He(i,{type:"delete_credential",key:n}),!0):!1},testCredential:n=>{const{socket:i}=t();return i&&i.readyState===WebSocket.OPEN?(He(i,{type:"test_credential",key:n}),!0):!1},requestHostStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({hostStatusLoading:!0}),He(n,{type:"host_status_request"}),!0):!1},requestMailboxStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({mailboxStatusLoading:!0}),He(n,{type:"mailbox_status_request"}),!0):!1},requestExternalSessions:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({externalSessionsLoading:!0}),He(n,{type:"external_sessions_request"}),!0):!1},requestRepoEvents:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({repoEventsLoading:!0}),He(n,{type:"repo_events_request"}),!0):!1},requestPermissionInput:n=>{const{socket:i}=t();return i&&i.readyState===WebSocket.OPEN?(He(i,{type:"get_permission_input",requestId:n}),!0):!1},requestSessionPreset:n=>{const{socket:i}=t();return!n||!i||i.readyState!==WebSocket.OPEN?!1:(He(i,{type:"session_preset_get",cwd:n}),!0)},setSessionPresetOverride:(n,i)=>{const{socket:o}=t();return!n||!o||o.readyState!==WebSocket.OPEN?!1:(He(o,{type:"session_preset_set",cwd:n,preset:i}),!0)},approveSessionPreset:n=>{const{socket:i}=t();return!n||!i||i.readyState!==WebSocket.OPEN?!1:(He(i,{type:"session_preset_approve",cwd:n}),!0)},revokeSessionPreset:n=>{const{socket:i}=t();return!n||!i||i.readyState!==WebSocket.OPEN?!1:(He(i,{type:"session_preset_revoke",cwd:n}),!0)},takePendingServerSeed:n=>{const i=t().pendingServerSeed,o=i[n];if(typeof o!="string"||o.length===0)return null;const d={...i};return delete d[n],e({pendingServerSeed:d}),o},approvePairRequest:n=>{const{socket:i}=t();return!n||!i||i.readyState!==WebSocket.OPEN?!1:(He(i,{type:"pair_approve",requestId:n}),e(o=>({pendingPairRequests:o.pendingPairRequests.filter(d=>d.requestId!==n)})),!0)},denyPairRequest:n=>{const{socket:i}=t();return!n||!i||i.readyState!==WebSocket.OPEN?!1:(He(i,{type:"pair_deny",requestId:n}),e(o=>({pendingPairRequests:o.pendingPairRequests.filter(d=>d.requestId!==n)})),!0)},clearPendingApprovalPairHost:()=>{e({pendingApprovalPairHost:null})},requestRunnerStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({runnerStatusLoading:!0}),He(n,{type:"runner_status_request"}),!0):!1},requestContainersStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({containersStatusLoading:!0}),He(n,{type:"containers_status_request"}),!0):!1},requestRepoRuntimeConfig:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({repoRuntimeConfigLoading:!0}),He(n,{type:"repo_runtime_config_request"}),!0):!1},requestByokPoolStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({byokPoolStatusLoading:!0}),He(n,{type:"byok_pool_status_request"}),!0):!1},requestHostPruneStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({hostPruneStatusLoading:!0}),He(n,{type:"host_prune_status_request"}),!0):!1},requestSimulatorStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({simulatorStatusLoading:!0}),He(n,{type:"simulator_status_request"}),!0):!1},requestEmulatorStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({emulatorStatusLoading:!0}),He(n,{type:"emulator_status_request"}),!0):!1},requestWslStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({wslStatusLoading:!0}),He(n,{type:"wsl_status_request"}),!0):!1},requestIntegrationStatus:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({integrationStatusLoading:!0}),He(n,{type:"integration_status_request"}),!0):!1},requestSkillsInventory:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(e({skillsInventoryLoading:!0}),He(n,{type:"skills_inventory_request"}),!0):!1},sendRepoMemoryReindex:n=>{const{socket:i}=t();if(!n||!i||i.readyState!==WebSocket.OPEN)return!1;const o=`reindex-${fn()}`,d=new Set(t().reindexingRepoPaths);d.add(n);const h={...t().reindexResults};return delete h[n],e({reindexingRepoPaths:d,reindexResults:h}),He(i,{type:"integration_action",action:"repo_memory_reindex",repoPath:n,requestId:o}),!0},sendRepoRelayRerun:(n,i)=>{const{socket:o}=t();if(!n||!Number.isInteger(i)||i<0||!o||o.readyState!==WebSocket.OPEN)return!1;const d=`relay-rerun-${fn()}`,h=new Set(t().relayRerunningRepoPaths);h.add(n);const l={...t().relayRerunResults};return delete l[n],e({relayRerunningRepoPaths:h,relayRerunResults:l}),He(o,{type:"integration_action",action:"repo_relay_rerun",repoPath:n,runId:i,requestId:d}),!0},sendContainersAction:(n,i)=>{const{socket:o}=t();if(!n||i!=="stop"&&i!=="restart"&&i!=="destroy"||!o||o.readyState!==WebSocket.OPEN)return!1;const d=`container-action-${fn()}`,h=new Set(t().containerActioningIds);h.add(n);const l={...t().containerActionResults};return delete l[n],e({containerActioningIds:h,containerActionResults:l}),He(o,{type:"containers_action",action:i,environmentId:n,requestId:d}),!0},sendByokPoolAction:(n,i)=>{const{socket:o}=t();if(n!=="drain"&&n!=="recycle"&&n!=="resize"||n==="recycle"&&!i?.key||!o||o.readyState!==WebSocket.OPEN)return!1;const d=n==="recycle"?`recycle:${i.key}`:n,h=`byok-pool-action-${fn()}`,l=new Set(t().byokPoolActioningIds);l.add(d);const u={...t().byokPoolActionResults};delete u[d],e({byokPoolActioningIds:l,byokPoolActionResults:u});const f={type:"byok_pool_action",action:n,requestId:h};return n==="recycle"&&(f.key=i.key),n==="resize"&&(typeof i?.maxPerKey=="number"&&(f.maxPerKey=i.maxPerKey),typeof i?.maxTotal=="number"&&(f.maxTotal=i.maxTotal)),He(o,f),!0},sendHostPruneAction:n=>{const{socket:i}=t();if(n!=="containers"&&n!=="images"&&n!=="all"||!i||i.readyState!==WebSocket.OPEN)return!1;const o=`host-prune-action-${fn()}`,d=new Set(t().hostPruneActioningIds);d.add(n);const h={...t().hostPruneActionResults};return delete h[n],e({hostPruneActioningIds:d,hostPruneActionResults:h}),He(i,{type:"host_prune_action",kind:n,requestId:o}),!0},sendSimulatorAction:(n,i)=>{const{socket:o}=t();if(n!=="boot"&&n!=="shutdown"||!i||!o||o.readyState!==WebSocket.OPEN)return!1;const d=`simulator-action-${fn()}`,h=new Set(t().simulatorActioningIds);h.add(i);const l={...t().simulatorActionResults};return delete l[i],e({simulatorActioningIds:h,simulatorActionResults:l}),He(o,{type:"simulator_action",action:n,udid:i,requestId:d}),!0},sendEmulatorAction:(n,i)=>{const{socket:o}=t();if(n!=="boot"&&n!=="kill")return!1;const d=n==="boot"?i?.avd:i?.serial;if(!d||!o||o.readyState!==WebSocket.OPEN)return!1;const h=`emulator-action-${fn()}`,l=new Set(t().emulatorActioningIds);l.add(d);const u={...t().emulatorActionResults};delete u[d],e({emulatorActioningIds:l,emulatorActionResults:u});const f={type:"emulator_action",action:n,requestId:h};return n==="boot"?(f.avd=i.avd,i.headless&&(f.headless=!0)):f.serial=i.serial,He(o,f),!0},sendWslAction:(n,i)=>{const{socket:o}=t();if(n!=="start"&&n!=="terminate"||!i||!o||o.readyState!==WebSocket.OPEN)return!1;const d=`wsl-action-${fn()}`,h=new Set(t().wslActioningIds);h.add(i);const l={...t().wslActionResults};return delete l[i],e({wslActioningIds:h,wslActionResults:l}),He(o,{type:"wsl_action",action:n,distro:i,requestId:d}),!0},summarizeSession:n=>{const{socket:i}=t();if(!n||!i||i.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Not connected — cannot summarize this session."));const o=`summarize-${fn()}`;return new Promise((d,h)=>{const l=setTimeout(()=>{X4(o),h(new Error("Summary request timed out after 5 minutes."))},3e5);Z4(o,{resolve:d,reject:h,timeoutId:l}),He(i,{type:"summarize_session",sessionId:n,requestId:o})})},refreshNotificationPrefs:()=>{const{socket:n}=t();return n&&n.readyState===WebSocket.OPEN?(He(n,{type:"notification_prefs_get"}),!0):!1},setNotificationPrefsCategory:(n,i)=>{const{socket:o,notificationPrefs:d}=t();return o&&o.readyState===WebSocket.OPEN&&He(o,{type:"notification_prefs_set",prefs:{categories:{[n]:i}}})?(d&&e({notificationPrefs:{...d,categories:{...d.categories,[n]:i}}}),!0):!1},setNotificationPrefsDevice:(n,i,o)=>{if(!n)return!1;const{socket:d,notificationPrefs:h}=t();if(d&&d.readyState===WebSocket.OPEN){if(!He(d,{type:"notification_prefs_set",prefs:{devices:{[n]:{categories:{[i]:o}}}}}))return!1;if(h){const l=h.devices[n]??{},u=l.categories??{};e({notificationPrefs:{...h,devices:{...h.devices,[n]:{...l,categories:{...u,[i]:o}}}}})}return!0}return!1},deleteNotificationPrefsDevice:n=>{if(!n)return!1;const{socket:i,notificationPrefs:o}=t();if(i&&i.readyState===WebSocket.OPEN){if(!He(i,{type:"notification_prefs_set",prefs:{devices:{[n]:null}}}))return!1;if(o){const{[n]:d,...h}=o.devices;e({notificationPrefs:{...o,devices:h}})}return!0}return!1},setNotificationPrefsQuietHours:n=>{const{socket:i,notificationPrefs:o}=t();return i&&i.readyState===WebSocket.OPEN&&He(i,{type:"notification_prefs_set",prefs:{quietHours:n}})?(o&&e({notificationPrefs:{...o,quietHours:n}}),!0):!1},setNotificationPrefsBypassCategories:n=>{const{socket:i,notificationPrefs:o}=t();return i&&i.readyState===WebSocket.OPEN&&He(i,{type:"notification_prefs_set",prefs:{bypassCategories:n}})?(o&&e({notificationPrefs:{...o,bypassCategories:n}}),!0):!1},getActiveSessionState:()=>{const{activeSessionId:n,sessionStates:i}=t();return n&&i[n]?i[n]:{messages:t().messages,streamingMessageId:t().streamingMessageId,pendingClientMessageId:null,claudeReady:t().claudeReady,activeModel:t().activeModel,permissionMode:t().permissionMode,contextUsage:t().contextUsage,lastResultCost:t().lastResultCost,lastResultDuration:t().lastResultDuration,sessionCost:null,cumulativeUsage:null,costThresholdWarning:null,isIdle:!0,lastClientActivityAt:null,health:"healthy",stoppedAt:null,stoppedCode:null,terminalRawBuffer:t().terminalRawBuffer,activeAgents:r$,activeTools:c$,pendingBackgroundShells:u$,transcriptBackgroundTasks:d$,scheduledWakeup:null,isPlanPending:!1,planAllowedPrompts:a$,primaryClientId:null,sessionRole:null,conversationId:null,sessionContext:null,mcpServers:o$,devPreviews:l$,selectedFilePath:null,thinkingLevel:"default",pendingEvaluatorClarify:null,inactivityWarning:null,interventions:f$,queuedMessages:iS}},loadSavedConnection:()=>{const n=b5();n&&e({savedConnection:n});try{const i=localStorage.getItem(sS);if(i){const o=JSON.parse(i),d={};typeof o.chatEnterToSend=="boolean"&&(d.chatEnterToSend=o.chatEnterToSend),typeof o.terminalEnterToSend=="boolean"&&(d.terminalEnterToSend=o.terminalEnterToSend),O0(o.voiceInputMode)&&(d.voiceInputMode=o.voiceInputMode),Object.keys(d).length>0&&e(h=>({inputSettings:{...h.inputSettings,...d}}))}}catch{}try{const i=jp(),o=TP(),d={};i.viewMode&&(d.viewMode=i.viewMode),i.activeSessionId&&(d.activeSessionId=i.activeSessionId),i.terminalBuffer&&(d.terminalBuffer=i.terminalBuffer),o.length>0&&(d.sessions=o),Object.keys(d).length>0&&e(d);const h=o.map(l=>l.sessionId);if(i.activeSessionId&&!h.includes(i.activeSessionId)&&h.push(i.activeSessionId),h.length>0){const l=IP(h),u={};for(const[f,v]of Object.entries(l))v.length>0&&(u[f]={...bf(),messages:v});Object.keys(u).length>0&&e(f=>({sessionStates:{...f.sessionStates,...u}}))}}catch{}},clearSavedConnection:()=>{_5(),e({savedConnection:null})},connect:(n,i,o)=>{const d=o?._retryCount??0,h=o?.silent??!1,l=d===0?(()=>{const m=$p;return $p=null,m})():o?._pairingId??null,u=t().wsUrl;d===0&&u!==null&&u!==n&&(t().forgetSession(),tS());const f=fg===n;d===0&&V_();const v=_i,{socket:g}=t();g&&(g.onclose=null,g.onerror=null,g.onmessage=null,g.close());const S=f||d>0?"reconnecting":"connecting";e({socket:null,connectionPhase:S,connectionRetryCount:d,userDisconnected:!1,...d===0&&!f?{connectionError:null}:{}}),d>0&&console.log(`[ws] Connection attempt ${d+1}/${$d+1}...`);const E=(m,y)=>{const b=t().activeServerId;if(!b)return{url:m,token:y};const _=t().serverRegistry.find(k=>k.id===b);return _?{url:_.wsUrl,token:_.token||y}:{url:m,token:y}};y4({attempt:d,maxRetries:$d,retryDelays:Uc,resolveEndpoint:()=>v!==_i?null:E(n,i),isStale:()=>v!==_i,probe:async m=>{const y=m.url.replace(/^wss:/,"https:").replace(/^ws:/,"http:"),b=new URL("/",y).href,_=new AbortController,k=setTimeout(()=>_.abort(),5e3);try{const j=await fetch(b,{method:"GET",signal:_.signal});if(!j.ok)throw new Error(`HTTP ${j.status}`);try{const T=await j.json();if(console.log("[ws] Health check response:",T.status??"no status field"),T.status==="restarting")return{kind:"restarting",restartEtaMs:typeof T.restartEtaMs=="number"?T.restartEtaMs:null};if(T.status==="down")return{kind:"terminal_down",reason:typeof T.reason=="string"?T.reason:"supervisor_gave_up"}}catch(T){console.log("[ws] Health check body unreadable:",T instanceof Error?T.message:String(T))}return{kind:"ok"}}catch(j){return console.log(`[ws] Health check failed: ${j instanceof Error?j.message:String(j)}`),{kind:"failed",reason:uO(j)}}finally{clearTimeout(k)}},openSocket:()=>{console.log("[ws] Health check passed, connecting WebSocket..."),x()},onRestarting:({restartEtaMs:m})=>{const y=t();e({connectionPhase:"server_restarting",shutdownReason:y.shutdownReason??"restart",restartEtaMs:m,restartingSince:y.restartingSince||Date.now()}),console.log(`[ws] Server is restarting, will retry (attempt ${d+1}/${$d+1})`)},onProbeFailed:m=>{e({connectionError:m})},onTerminalDown:()=>{v===_i&&(e({connectionPhase:"server_down",connectionError:"Server appears to be down"}),console.warn("[chroxy] Server appears to be down (supervisor gave up). Reconnect manually when it is back."))},scheduleRetry:(m,y)=>{console.log(`[ws] Retrying in ${y}ms...`),setTimeout(()=>{if(v!==_i)return;const b=E(n,i);t().connect(b.url,b.token,{silent:h,_retryCount:m,...l?{_pairingId:l}:{}})},y)},onRestartGaveUp:()=>{e({connectionPhase:"disconnected",connectionError:"Server restart timed out"}),console.warn("[chroxy] Connection Failed: The server is still restarting. Try again later.")},onProbeGaveUp:()=>{e({connectionPhase:"disconnected",connectionError:"Could not reach server"}),console.warn("[chroxy] Connection Failed: Could not reach the Chroxy server. Make sure it's running."),t().clearSavedConnection()}});function x(){Op(null),G_(null),Qo();const m=new WebSocket(n),y=b4({nextRung:e5,reconnect:()=>{const k=E(n,i);t().connect(k.url,k.token)},isStale:()=>v!==_i,retryDelays:Uc,maxRung:g4,onGaveUp:()=>{v===_i&&(console.log("[ws] reconnect ladder exhausted — server appears down"),e({connectionPhase:"server_down",connectionError:"Server appears to be down"}))}}),b=(k,j)=>{y.scheduled||t().userDisconnected||Hd===v||!y.schedule()||(console.log(`[ws] ${k}, reconnecting...`),e({connectionPhase:"reconnecting",...j!==null?{connectionError:j}:{},connectionRetryCount:0}))};m.onopen=()=>{const k=p$(),j=n1();if(m.readyState===WebSocket.OPEN){const T={protocolVersion:Sm,deviceInfo:{deviceId:j,...k},capabilities:DL.desktop};if(l)m.send(JSON.stringify({type:"pair",pairingId:l,...T}));else{const D=JP(),I=aE();m.send(JSON.stringify({type:"auth",token:i,...T,eagerPublicKey:D.publicKey,eagerSalt:D.salt,...Object.keys(I).length>0?{historyCursors:I}:{}}))}a5(()=>{if(v===_i){m.onclose=null,m.onerror=null,m.onmessage=null;try{m.close()}catch{}b("Handshake timed out","Handshake failed — reconnecting")}})}};const _={url:n,token:i,isReconnect:f,silent:h,socket:m};XP(_),m.onmessage=k=>{let j;try{j=JSON.parse(k.data)}catch{return}const T=QP();if(j.type==="encrypted"&&T){if(typeof j.d!="string"||typeof j.n!="number"){console.error("[crypto] Invalid encrypted envelope structure:",j),m.close();return}try{j=YE(j,T.sharedKey,T.recvNonce,UE),Op({...T,recvNonce:T.recvNonce+1})}catch(D){console.error("[crypto] Decryption failed:",D),m.close();return}}else if(T&&t$.has(j.type)){console.error("[crypto] Dropped plaintext handshake frame after encryption established:",j.type);return}else if(T&&!n$.has(j.type)){console.error("[crypto] Rejected plaintext frame after encryption established:",j.type),m.close();return}$B(j,_)},m.onclose=k=>{if(J_(),v!==_i)return;Qo(),Ap("Connection closed before evaluator response arrived"),Np("Connection closed before the summary arrived"),Rp(),Tp(),Ip(),Mp();const j=Bp(t().sessionStates),T=t().connectionPhase==="connected";e({socket:null,sessionStates:j}),t().cancellingActivityIds.size>0&&e({cancellingActivityIds:new Set}),t().reindexingRepoPaths.size>0&&e({reindexingRepoPaths:new Set}),t().relayRerunningRepoPaths.size>0&&e({relayRerunningRepoPaths:new Set}),t().containerActioningIds.size>0&&e({containerActioningIds:new Set}),t().byokPoolActioningIds.size>0&&e({byokPoolActioningIds:new Set}),t().hostPruneActioningIds.size>0&&e({hostPruneActioningIds:new Set}),t().simulatorActioningIds.size>0&&e({simulatorActioningIds:new Set}),t().emulatorActioningIds.size>0&&e({emulatorActioningIds:new Set}),t().wslActioningIds.size>0&&e({wslActioningIds:new Set});const D=["hostStatusLoading","runnerStatusLoading","containersStatusLoading","repoRuntimeConfigLoading","byokPoolStatusLoading","hostPruneStatusLoading","simulatorStatusLoading","emulatorStatusLoading","wslStatusLoading","integrationStatusLoading","skillsInventoryLoading","mailboxStatusLoading","externalSessionsLoading","repoEventsLoading"],I={};for(const q of D)t()[q]&&(I[q]=!1);Object.keys(I).length>0&&e(I),Y_();const L=q=>{const H={};return q.streamingMessageId&&(H.streamingMessageId=null),q.isPlanPending&&(H.isPlanPending=!1,H.planAllowedPrompts=[]),q.pendingEvaluatorClarify&&(H.pendingEvaluatorClarify=null),q.inactivityWarning&&(H.inactivityWarning=null),q.sessionRole!==null&&(H.sessionRole=null),q.primaryClientId!==null&&(H.primaryClientId=null),Object.keys(H).length>0?H:{}};for(const q of Object.keys(t().sessionStates))Ft(q,L);if(T&&!t().userDisconnected&&Hd!==v){const q=k?.code,H=typeof q=="number"?cO(q):"Connection lost";b(typeof q=="number"?`Connection lost (code ${q})`:"Connection lost",H)}else Hd===v||t().userDisconnected?e({connectionPhase:"disconnected"}):t().connectionPhase!=="reconnecting"&&e({connectionPhase:"disconnected"})},m.onerror=()=>{if(v!==_i)return;Qo(),Ap("Connection errored before evaluator response arrived"),Np("Connection errored before the summary arrived"),Rp(),Tp(),Ip(),Mp();const k=Bp(t().sessionStates);e({socket:null,sessionStates:k}),b("WebSocket error","Connection error")}}},disconnect:()=>{V_(),t5(_i),Pp(null),J_(),Qo(),Ap("Disconnected before evaluator response arrived"),Np("Disconnected before the summary arrived"),Rp(),Tp(),Ip(),Mp();const{socket:n}=t();n&&(n.onclose=null,n.close()),n5(),P0({clearCursors:!0}),d5(),Y_(),Z_(),Op(null),G_(null),tS();const i=Bp(t().sessionStates);e({connectionPhase:"disconnected",sessionStates:i,socket:null,serverMode:null,sessionCwd:null,defaultCwd:null,serverVersion:null,latestVersion:null,serverCommit:null,serverProtocolVersion:null,serverResultTimeoutMs:null,streamStallTimeoutMs:null,claudeReady:!1,streamingMessageId:null,activeModel:null,availableProviders:[],environments:[],pairingRefreshedCount:0,availableModels:[],availableModelsProvider:null,defaultModelId:null,permissionMode:null,previousPermissionMode:null,availablePermissionModes:[],myClientId:null,connectedClients:[],primaryClientId:null,connectionError:null,connectionRetryCount:0,latencyMs:null,connectionQuality:null,logEntries:[],serverErrors:[],sessionNotifications:[],resolvedPermissions:{},permissionInputs:{},serverPhase:null,tunnelProgress:null,serverExposure:null,exposureBannerDismissed:!1,billingCanary:null,billingBannerDismissed:!1,shutdownReason:null,restartEtaMs:null,restartingSince:null,pendingPermissionConfirm:null,slashCommands:[],filePickerFiles:null,fileBrowserPendingOpen:null,workspaceSymbols:null,workspaceSymbolsLoading:!1,symbolLocation:null,codeSearchResults:null,codeSearchLoading:!1,referencesResult:null,referencesSymbol:"",referencesOpen:!1,referencesLoading:!1,customAgents:[],checkpoints:[],_directoryListingCallback:null,_terminalWriteCallback:null,contextUsage:null,lastResultCost:null,lastResultDuration:null,webFeatures:{available:!1,remote:!1,teleport:!1},webTasks:[],serverCapabilities:{},savedConnection:null,userDisconnected:!0,viewingCachedSession:!1,conversationHistory:[],conversationHistoryLoading:!1,searchResults:[],searchLoading:!1,searchQuery:""})},forgetSession:()=>{Pp(null),DP(),e({messages:[],terminalBuffer:"",terminalRawBuffer:"",sessions:[],activeSessionId:null,sessionStates:{},activity:Pd(),cancellingActivityIds:new Set,reindexingRepoPaths:new Set,reindexResults:{},relayRerunningRepoPaths:new Set,relayRerunResults:{},containerActioningIds:new Set,containerActionResults:{},byokPoolActioningIds:new Set,byokPoolActionResults:{},hostPruneActioningIds:new Set,hostPruneActionResults:{},simulatorActioningIds:new Set,simulatorActionResults:{},emulatorActioningIds:new Set,emulatorActionResults:{},wslActioningIds:new Set,wslActionResults:{},wsUrl:null,apiToken:null,serverMode:null,sessionCwd:null,defaultCwd:null,serverVersion:null,latestVersion:null,serverCommit:null,serverProtocolVersion:null,serverResultTimeoutMs:null,streamStallTimeoutMs:null,viewingCachedSession:!1})},_resetSessionMemory:()=>{Pp(null),e({messages:[],terminalBuffer:"",terminalRawBuffer:"",sessions:[],activeSessionId:null,sessionStates:{},activity:Pd(),cancellingActivityIds:new Set,reindexingRepoPaths:new Set,reindexResults:{},relayRerunningRepoPaths:new Set,relayRerunResults:{},containerActioningIds:new Set,containerActionResults:{},byokPoolActioningIds:new Set,byokPoolActionResults:{},hostPruneActioningIds:new Set,hostPruneActionResults:{},simulatorActioningIds:new Set,simulatorActionResults:{},emulatorActioningIds:new Set,emulatorActionResults:{},wslActioningIds:new Set,wslActionResults:{},wsUrl:null,apiToken:null,serverMode:null,sessionCwd:null,defaultCwd:null,serverVersion:null,latestVersion:null,serverCommit:null,serverProtocolVersion:null,serverResultTimeoutMs:null,streamStallTimeoutMs:null,viewingCachedSession:!1})},setViewMode:n=>{e({viewMode:n}),cP(n)},addMessage:n=>{e(i=>({messages:[...i.messages.filter(o=>o.id!=="thinking"||n.id==="thinking"),n]}))},addUserMessage:(n,i,o)=>{const d=o?.clientMessageId||fn("user"),h={id:d,type:"user_input",content:n,timestamp:Date.now(),...i?.length?{attachments:i}:void 0};if(o?.queued){const f=t().activeSessionId;f&&t().sessionStates[f]&&Cs(v=>({messages:[...v.messages,h],queuedMessages:gj(v.queuedMessages,{clientMessageId:d,text:n,queuedAt:Date.now()})}));return}const l={id:"thinking",type:"thinking",content:"",timestamp:Date.now()};n&&!lS(t)&&t().appendTerminalData(`\r
|
|
68
|
-
\x1B[33m> ${n}\x1B[0m\r
|
|
69
|
-
\r
|
|
70
|
-
`);const u=t().activeSessionId;u&&t().sessionStates[u]?Cs(f=>({messages:[...vr(f.messages),h,l],streamingMessageId:"pending",pendingClientMessageId:d})):e(f=>({messages:[...vr(f.messages),h,l],streamingMessageId:"pending"})),setTimeout(()=>{if(t().streamingMessageId!=="pending")return;const f=t().activeSessionId;f&&t().sessionStates[f]?Cs(v=>({messages:vr(v.messages),streamingMessageId:null,pendingClientMessageId:null})):e(v=>({messages:vr(v.messages),streamingMessageId:null}))},5e3)},appendTerminalData:n=>{const i=t().activeSessionId;e(d=>{const h={terminalBuffer:(d.terminalBuffer+Fc(n)).slice(-5e4),terminalRawBuffer:(d.terminalRawBuffer+n).slice(-1e5)};if(i&&d.sessionStates[i]){const l=d.sessionStates[i];h.sessionStates={...d.sessionStates,[i]:{...l,terminalRawBuffer:(l.terminalRawBuffer+n).slice(-1e5)}}}return h}),t()._terminalWriteCallback&&i5(n)},clearTerminalBuffer:()=>{const n=t().activeSessionId;e(i=>{const o={terminalBuffer:"",terminalRawBuffer:""};return n&&i.sessionStates[n]&&(o.sessionStates={...i.sessionStates,[n]:{...i.sessionStates[n],terminalRawBuffer:""}}),o}),Z_()},setTerminalWriteCallback:n=>{e({_terminalWriteCallback:n})},updateInputSettings:n=>{e(i=>{const o={...i.inputSettings,...n};try{localStorage.setItem(sS,JSON.stringify(o))}catch{}return{inputSettings:o}})},sendInput:(n,i,o)=>{const{socket:d,activeSessionId:h}=t(),l=fn("user"),u=t().getActiveSessionState(),f=u.streamingMessageId!==null||u.isIdle===!1;t().addUserMessage(n,void 0,{clientMessageId:l,queued:f});const v={type:"input",data:n,clientMessageId:l};h&&(v.sessionId=h),i?.length&&(v.attachments=i),o?.isVoice&&(v.isVoice=!0);let g;if(d&&d.readyState===WebSocket.OPEN?g=He(d,v)?"sent":gc("input",v):g=gc("input",v),(g==="sent"||g==="queued")&&h){const S=t().sessionStates[h];(S?.pendingEvaluatorClarify||S?.inactivityWarning)&&Cs(w=>{const E={};return w.pendingEvaluatorClarify&&(E.pendingEvaluatorClarify=null),w.inactivityWarning&&(E.inactivityWarning=null),E})}return g},sendInterrupt:n=>{const{socket:i,activeSessionId:o}=t(),d=n??o,h={type:"interrupt"};d&&(h.sessionId=d);const l=d?t().sessionStates[d]:void 0;if(d&&l){const u=l.queuedMessages??[];if(u.length>0){const f=new Set(u.map(v=>v.clientMessageId).filter(v=>!!v));Ft(d,v=>({queuedMessages:iS,messages:v.messages.filter(g=>!f.has(g.id))}))}}return i&&i.readyState===WebSocket.OPEN&&He(i,h)?"sent":gc("interrupt",h)},sendCancelActivity:(n,i)=>{const{socket:o,activeSessionId:d}=t(),h=i??d,l=`cancel-${fn()}`,u={type:"cancel_activity",activityId:n,requestId:l};if(h&&(u.sessionId=h),h&&o&&o.readyState===WebSocket.OPEN){if(!He(o,u))return!1;const f=new Set(t().cancellingActivityIds);return f.add(`${h}:${n}`),e({cancellingActivityIds:f}),"sent"}return gc("cancel_activity",u)},sendCancelQueued:(n,i)=>{const{socket:o,activeSessionId:d}=t(),h=i??d;if(!(o&&o.readyState===WebSocket.OPEN))return!1;const l={type:"cancel_queued",clientMessageId:n};return h&&(l.sessionId=h),He(o,l)?(h&&t().sessionStates[h]&&Ft(h,u=>({queuedMessages:tx(u.queuedMessages,n),messages:u.messages.filter(f=>f.id!==n)})),"sent"):!1},evaluateDraft:n=>{const{socket:i,activeSessionId:o}=t(),d=`eval-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return new Promise((h,l)=>{if(!i||i.readyState!==WebSocket.OPEN){l(new Error("Not connected to server"));return}const u=window.setTimeout(()=>{$P(d),l(new Error("Evaluator request timed out after 60s"))},6e4);BP(d,{resolve:h,reject:l,timeoutId:u});const f={type:"evaluate_draft",draft:n,requestId:d};o&&(f.sessionId=o),He(i,f)})},sendPermissionResponse:(n,i,o)=>{const{socket:d}=t();if(!d||d.readyState!==WebSocket.OPEN)return!1;const h=i==="allowSession"?"allow":i,l={type:"permission_response",requestId:n,decision:h,...o&&Object.keys(o).length>0&&h!=="deny"?{editedInput:o}:{}};if(!He(d,l))return!1;const u="sent";t().markPermissionResolved(n,i),t().markPromptAnsweredByRequestId(n,i);const{activeSessionId:f,sessionStates:v,sessionNotifications:g}=t(),w=g.find(E=>E.requestId===n)?.sessionId??Object.entries(v).find(([,E])=>E.messages.some(x=>x.requestId===n))?.[0];if(w&&w!==f&&t().switchSession(w),i==="allowSession"&&d&&d.readyState===WebSocket.OPEN){const E=w??f;if(E){const x=t().sessionStates[E],y=x?.messages.find(b=>b.requestId===n&&b.type==="prompt")?.tool;if(y&&e1.has(y)){const b=x?.sessionRules??[];He(d,{type:"set_permission_rules",sessionId:E,rules:[...b,{tool:y,decision:"allow"}]})}}}return u},markPermissionResolved:(n,i)=>{e(o=>({resolvedPermissions:i$(o.resolvedPermissions,n,i)}))},sendUserQuestionResponse:(n,i)=>{const{socket:o,activeSessionId:d,sessionStates:h}=t(),l=nE(n),u=!l&&typeof n!="string";let f;l?f=n.freeformText:f=H0(n);const v={type:"user_question_response",answer:l?n.otherLabel:f};return u&&(v.answers=n),l&&(v.freeformText=n.freeformText),i&&(v.toolUseId=i),f&&!lS(t)&&t().appendTerminalData(`\r
|
|
71
|
-
\x1B[36m> User answered: ${f}\x1B[0m\r
|
|
72
|
-
`),d&&h[d]&&Cs(g=>{const S={isIdle:!1,lastClientActivityAt:Date.now()};if(i){S.activeTools=g.activeTools.filter(x=>x.toolUseId!==i);let w=!1;const E=g.messages.map(x=>x.id===i&&x.type==="tool_use"&&x.toolResult===void 0?(w=!0,{...x,toolResult:"(resolved by user)"}):x);w&&(S.messages=E)}return S}),o&&o.readyState===WebSocket.OPEN&&He(o,v)?"sent":gc("user_question_response",v)},markPromptAnswered:(n,i)=>{const{activeSessionId:o,sessionStates:d}=t(),h=Date.now();o&&d[o]?Cs(l=>({messages:l.messages.map(u=>u.id===n?{...u,answered:i,answeredAt:h}:u)})):e(l=>({messages:l.messages.map(u=>u.id===n?{...u,answered:i,answeredAt:h}:u)}))},markPromptAnsweredByRequestId:(n,i)=>{const{sessionStates:o}=t(),d=Date.now();for(const[h,l]of Object.entries(o))if(l.messages.some(u=>u.requestId===n)){e(u=>({sessionStates:{...u.sessionStates,[h]:{...u.sessionStates[h],messages:u.sessionStates[h].messages.map(f=>f.requestId===n?{...f,answered:i,answeredAt:d}:f)}}}));return}e(h=>({messages:h.messages.map(l=>l.requestId===n?{...l,answered:i,answeredAt:d}:l)}))},setModel:n=>{const{socket:i,activeSessionId:o}=t(),d=o&&t().sessionStates[o]?t().sessionStates[o].activeModel??null:t().activeModel??null;if(i&&i.readyState===WebSocket.OPEN){const h=`set-model-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;HP(h,{sessionId:o,previousModel:d});const l={type:"set_model",model:n,requestId:h};o&&(l.sessionId=o),He(i,l)}o&&t().sessionStates[o]?Cs(()=>({activeModel:n})):e({activeModel:n})},setPermissionMode:n=>{const{socket:i,activeSessionId:o,permissionMode:d}=t();if(n==="auto"){const v=t(),S=(o?v.sessions.find(m=>m.sessionId===o):void 0)?.provider??null,w=v.availableProviders.find(m=>m.name===S)?.capabilities,E=!!t().getActiveSessionState().streamingMessageId;if(!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(XB({interruptsTurn:w?.interruptsTurnOnAutoSwitch,isStreaming:E})):!0))return}const h=t().previousPermissionMode??null,l=o&&t().sessionStates[o]?t().sessionStates[o].permissionMode??null:t().permissionMode??null,u=`set-perm-mode-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,f=n==="auto"?{type:"set_permission_mode",mode:n,confirmed:!0,requestId:u}:{type:"set_permission_mode",mode:n,requestId:u};if(o&&(f.sessionId=o),i&&i.readyState===WebSocket.OPEN){if(!He(i,f))return;WP(u,{sessionId:o,previousMode:l,priorPreviousMode:h})}d&&d!==n&&e({previousPermissionMode:d}),o&&t().sessionStates[o]?Cs(()=>({permissionMode:n})):e({permissionMode:n})},setThinkingLevel:n=>{const{socket:i,activeSessionId:o}=t(),d=o&&t().sessionStates[o]?t().sessionStates[o].thinkingLevel??"default":"default",h=`set-thinking-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(i&&i.readyState===WebSocket.OPEN){YP(h,{sessionId:o,previousLevel:d});const l={type:"set_thinking_level",level:n,requestId:h};o&&(l.sessionId=o),He(i,l)}o&&t().sessionStates[o]&&Cs(()=>({thinkingLevel:n}))},setPromptEvaluator:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d={type:"set_prompt_evaluator",value:n};o&&(d.sessionId=o),He(i,d)}},setChroxyContextHint:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d={type:"set_chroxy_context_hint",value:n};o&&(d.sessionId=o),He(i,d)}},setSessionPreamble:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d={type:"set_session_preamble",value:n};o&&(d.sessionId=o),He(i,d)}},requestListSkills:()=>{const{socket:n,activeSessionId:i}=t();if(n&&n.readyState===WebSocket.OPEN){const o={type:"list_skills"};i&&(o.sessionId=i),He(n,o)}},activateSkill:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d={type:"skill_activate",skillName:n};o&&(d.sessionId=o),He(i,d)}},deactivateSkill:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d={type:"skill_deactivate",skillName:n};o&&(d.sessionId=o),He(i,d)}},acceptSkillTrust:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d=`accept-trust-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,h={type:"skill_trust_accept",skillName:n,requestId:d};o&&(h.sessionId=o),He(i,h)}},grantCommunitySkillTrust:(n,i)=>{const{socket:o,activeSessionId:d}=t();if(o&&o.readyState===WebSocket.OPEN){const h=`trust-grant-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;UP(h,{skillName:n,author:i});const l={type:"skill_trust_grant",skillName:n,author:i,scope:"author",requestId:h};d&&(l.sessionId=d),He(o,l),d&&t().sessionStates[d]&&Cs(u=>({pendingTrustGrants:[...(Array.isArray(u.pendingTrustGrants)?u.pendingTrustGrants:[]).filter(g=>!(g.skillName===n&&g.author===i)),{requestId:h,skillName:n,author:i}]}))}},confirmPermissionMode:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){const d={type:"set_permission_mode",mode:n,confirmed:!0};o&&(d.sessionId=o),He(i,d)}e({pendingPermissionConfirm:null})},cancelPermissionConfirm:()=>{e({pendingPermissionConfirm:null})},resize:(n,i)=>{const{socket:o,activeSessionId:d}=t();if(o&&o.readyState===WebSocket.OPEN){const h={type:"resize",cols:n,rows:i};d&&(h.sessionId=d),He(o,h)}},setDirectoryListingCallback:n=>{e({_directoryListingCallback:n})},requestDirectoryListing:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"list_directory"};n&&(o.path=n),He(i,o)}},setFileBrowserCallback:n=>{e({_fileBrowserCallback:n})},setFileContentCallback:n=>{e({_fileContentCallback:n})},requestFileListing:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"browse_files"};n&&(o.path=n),He(i,o)}},requestFileContent:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o=String(++h$);e({lastFileContentRequestId:o}),He(i,{type:"read_file",path:n,requestId:o})}},requestSymbols:n=>{const{socket:i,activeSessionId:o}=t();if(i&&i.readyState===WebSocket.OPEN){e({symbolsLoading:!0});const d={type:"list_symbols"};n&&(d.path=n),o&&(d.sessionId=o),He(i,d)}},openFileInBrowser:(n,i)=>{const{activeSessionId:o,sessionStates:d,setViewMode:h}=t();o&&d[o]&&e({sessionStates:{...d,[o]:{...d[o],selectedFilePath:n}}}),e(l=>({fileBrowserPendingOpen:{path:n,line:i,nonce:(l.fileBrowserPendingOpen?.nonce??0)+1}})),h("files")},requestWorkspaceSymbols:()=>{const{socket:n,activeSessionId:i}=t();if(n&&n.readyState===WebSocket.OPEN){e({workspaceSymbolsLoading:!0});const o={type:"list_symbols"};i&&(o.sessionId=i),He(n,o)}},requestResolveSymbol:(n,i)=>{const o=typeof n=="string"?n.trim():"";if(!o)return;const{socket:d,activeSessionId:h}=t();if(d&&d.readyState===WebSocket.OPEN){const l={type:"resolve_symbol",symbol:o};i&&(l.file=i),h&&(l.sessionId=h),He(d,l)}},requestSearchContent:n=>{const i=typeof n=="string"?n.trim():"";if(i.length<2)return;const{socket:o,activeSessionId:d}=t();if(o&&o.readyState===WebSocket.OPEN){e({codeSearchLoading:!0});const h={type:"search_content",query:i};d&&(h.sessionId=d),He(o,h)}},requestFindReferences:(n,i)=>{const o=typeof n=="string"?n.trim():"";if(!o)return;const{socket:d,activeSessionId:h}=t();if(d&&d.readyState===WebSocket.OPEN){e({referencesSymbol:o,referencesOpen:!0,referencesLoading:!0,referencesResult:null});const l={type:"find_references",symbol:o};i&&(l.file=i),h&&(l.sessionId=h),He(d,l)}},setGitStatusCallback:n=>{e({_gitStatusCallback:n})},requestGitStatus:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"git_status"})},setDiffCallback:n=>{e({_diffCallback:n})},requestDiff:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"get_diff"};n&&(o.base=n),He(i,o)}},fetchProviders:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"list_providers"})},fetchSlashCommands:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"list_slash_commands"})},fetchFileList:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"list_files"};n&&(o.query=n),He(i,o)}},fetchCustomAgents:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"list_agents"})},claimPrimary:(n,i)=>{const{socket:o}=t();o&&o.readyState===WebSocket.OPEN&&He(o,{type:"claim_primary",sessionId:n,...i?.force?{force:!0}:{}})},switchSession:n=>{const{socket:i,activeSessionId:o,sessionStates:d}=t();if(n===o)return;t().sessionNotFoundError&&e({sessionNotFoundError:null});const h=d[n],l=Date.now(),u=t().sessionNotifications.map(f=>f.sessionId===n&&f.readAt===void 0?{...f,readAt:l}:f);if(h)e({activeSessionId:n,messages:h.messages,streamingMessageId:h.streamingMessageId,claudeReady:h.claudeReady,activeModel:h.activeModel,permissionMode:h.permissionMode,contextUsage:h.contextUsage,lastResultCost:h.lastResultCost,lastResultDuration:h.lastResultDuration,isIdle:h.isIdle,primaryClientId:h.primaryClientId,sessionNotifications:u});else{const f=t().sessions.find(g=>g.sessionId===n),v=typeof f?.isBusy=="boolean"?!f.isBusy:!0;e({activeSessionId:n,messages:[],streamingMessageId:null,claudeReady:!1,activeModel:null,permissionMode:null,contextUsage:null,lastResultCost:null,lastResultDuration:null,isIdle:v,primaryClientId:null,sessionNotifications:u})}i&&i.readyState===WebSocket.OPEN&&He(i,{type:"switch_session",sessionId:n})},createSession:({name:n,cwd:i,provider:o,model:d,permissionMode:h,worktree:l,environmentId:u,skipPermissions:f})=>{const{socket:v}=t();if(v&&v.readyState===WebSocket.OPEN){const g={type:"create_session"};return n&&(g.name=n),i&&(g.cwd=i),o&&(g.provider=o),d&&(g.model=d),h&&(g.permissionMode=h),l&&(g.worktree=!0),u&&(g.environmentId=u),typeof f=="boolean"&&(g.skipPermissions=f),He(v,g),!0}return console.warn("[chroxy] createSession: socket not open — create request not sent"),!1},revokeToken:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN?He(n,{type:"revoke_token"}):console.warn("[chroxy] revokeToken: socket not open — revoke request not sent")},destroySession:(n,i)=>{const{socket:o}=t();o&&o.readyState===WebSocket.OPEN&&He(o,i?{type:"destroy_session",sessionId:n,force:!0}:{type:"destroy_session",sessionId:n})},renameSession:(n,i)=>{const{socket:o}=t();o&&o.readyState===WebSocket.OPEN&&He(o,{type:"rename_session",sessionId:n,name:i})},requestEnvironments:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"list_environments"})},createEnvironment:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"create_environment",name:n.name,cwd:n.cwd};n.image&&(o.image=n.image),n.memoryLimit&&(o.memoryLimit=n.memoryLimit),n.cpuLimit&&(o.cpuLimit=n.cpuLimit),He(i,o)}},destroyEnvironment:n=>{const{socket:i}=t();i&&i.readyState===WebSocket.OPEN&&He(i,{type:"destroy_environment",environmentId:n})},fetchConversationHistory:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN?(e({conversationHistoryLoading:!0}),He(n,{type:"list_conversations"}),setTimeout(()=>{t().conversationHistoryLoading&&e({conversationHistoryLoading:!1})},1e4)):e({conversationHistoryLoading:!1})},resumeConversation:(n,i)=>{const{socket:o}=t();if(o&&o.readyState===WebSocket.OPEN){const d={type:"resume_conversation",conversationId:n};i&&(d.cwd=i),He(o,d)}},searchConversations:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o=++rS;e({searchLoading:!0,searchResults:[],searchQuery:n}),He(i,{type:"search_conversations",query:n}),clearTimeout(aS),aS=setTimeout(()=>{rS===o&&t().searchLoading&&e({searchLoading:!1})},15e3)}},clearSearchResults:()=>{e({searchResults:[],searchLoading:!1,searchQuery:""})},requestFullHistory:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"request_full_history"};n&&(o.sessionId=n),He(i,o)}},createCheckpoint:n=>{const{socket:i}=t();if(i&&i.readyState===WebSocket.OPEN){const o={type:"create_checkpoint"};n&&(o.name=n),He(i,o)}},listCheckpoints:()=>{const{socket:n}=t();n&&n.readyState===WebSocket.OPEN&&He(n,{type:"list_checkpoints"})},restoreCheckpoint:n=>{const{socket:i}=t();i&&i.readyState===WebSocket.OPEN&&He(i,{type:"restore_checkpoint",checkpointId:n})},deleteCheckpoint:n=>{const{socket:i}=t();i&&i.readyState===WebSocket.OPEN&&He(i,{type:"delete_checkpoint",checkpointId:n})},clearPlanState:()=>{Cs(()=>({isPlanPending:!1,planAllowedPrompts:[]}))},clearLogEntries:()=>{e({logEntries:[]})},addServerError:(n,i,o,d)=>{const h=Date.now(),l={id:fn("info"),category:"general",message:n,recoverable:!0,timestamp:h,...i?{action:i}:{},...o?{severity:o}:{},...d?{partialCostLine:d}:{}};e(u=>({serverErrors:[...u.serverErrors,l].slice(-10)}))},dismissServerError:n=>{e(i=>({serverErrors:i.serverErrors.filter(o=>o.id!==n)}))},dismissExposureBanner:()=>{e({exposureBannerDismissed:!0})},dismissBillingBanner:()=>{e({billingBannerDismissed:!0})},addInfoNotification:n=>{const i=Date.now(),o={id:fn("info-notif"),category:"general",message:n,recoverable:!0,timestamp:i};e(d=>({infoNotifications:[...d.infoNotifications,o].slice(-10)}))},dismissInfoNotification:n=>{const{infoNotifications:i}=t();i.some(o=>o.id===n)&&e({infoNotifications:i.filter(o=>o.id!==n)})},dismissSessionNotification:n=>{e(i=>({sessionNotifications:i.sessionNotifications.filter(o=>o.id!==n)}))},markSessionNotificationRead:n=>{e(i=>({sessionNotifications:i.sessionNotifications.map(o=>o.id===n&&o.readAt===void 0?{...o,readAt:Date.now()}:o)}))},markAllSessionNotificationsRead:()=>{const n=Date.now();e(i=>({sessionNotifications:i.sessionNotifications.map(o=>o.readAt===void 0?{...o,readAt:n}:o)}))},setSessionNotFoundError:n=>{e({sessionNotFoundError:n})},dismissSessionNotFoundError:()=>{e({sessionNotFoundError:null})},addServer:(n,i,o)=>{const[d,h]=FB(t().serverRegistry,n,i,o);return e({serverRegistry:d}),h},removeServer:n=>{const i=KB(t().serverRegistry,n);t().activeServerId===n&&(t().disconnect(),e({activeServerId:null})),e({serverRegistry:i})},updateServer:(n,i)=>{const o=WB(t().serverRegistry,n,i);e({serverRegistry:o})},switchServer:n=>{const i=t().serverRegistry.find(d=>d.id===n);if(!i||n===t().activeServerId&&t().connectionPhase==="connected")return;t().connectionPhase!=="disconnected"&&t().disconnect(),zd(n),t()._resetSessionMemory(),e({activeServerId:n,userDisconnected:!1});const o=jp();o.activeSessionId&&e({activeSessionId:o.activeSessionId}),t().connect(i.wsUrl,i.token)},connectToServer:n=>{const i=t().serverRegistry.find(o=>o.id===n);i&&(zd(n),e({activeServerId:n}),t().connect(i.wsUrl,i.token))},connectLocal:()=>{const n=li();if(!n)return;const o=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`;if(t().activeServerId===null&&t().connectionPhase==="connected")return;t().connectionPhase!=="disconnected"&&t().disconnect(),zd(null),t()._resetSessionMemory(),e({activeServerId:null,userDisconnected:!1});const d=jp();d.activeSessionId&&e({activeSessionId:d.activeSessionId}),t().connect(o,n)},retryConnection:()=>{Dw();const n=t().activeServerId;if(n){t().connectToServer(n);return}const i=li();if(!i)return;const d=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`;t().connect(d,i)},pairServer:(n,i,o,d)=>{const h=t().addServer(n,i,"");return $p=o,dg(d??null),t().switchServer(h.id),h}}));PP({getState:V.getState,setState:V.setState});let cS=null,uS=null;V.subscribe(e=>{const t=cS==="connected";if(cS=e.connectionPhase,e.connectionPhase==="connected"&&!t&&e.activeServerId){const n=GB(e.serverRegistry,e.activeServerId);V.setState({serverRegistry:n})}e.activeServerId!==uS&&(uS=e.activeServerId,kP(e.activeServerId))});let Wo=null;const zp={};let dS=0,fS=[];V.subscribe(e=>{if(e.activeSessionId!==Wo){if(Wo){const t=e.sessionStates[Wo];t&&(z_(Wo,t.messages),zp[Wo]=t.messages.length)}Wo=e.activeSessionId,uP(e.activeSessionId)}for(const[t,n]of Object.entries(e.sessionStates)){const i=zp[t]??0;n.messages.length!==i&&(zp[t]=n.messages.length,z_(t,n.messages))}e.sessions!==fS&&(fS=e.sessions,e.sessions.length>0&&AP(e.sessions)),e.terminalBuffer.length!==dS&&(dS=e.terminalBuffer.length,e.terminalBuffer?dP(e.terminalBuffer):MP())});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const e=V.getState(),{socket:t,connectionPhase:n,wsUrl:i,apiToken:o,activeSessionId:d,sessionStates:h}=e,l=document.visibilityState==="visible";if(qd(t,l),l){if(n==="server_down")console.log("[ws] Tab became visible while server_down — retrying"),e.retryConnection();else if(n==="connected"&&t&&t.readyState!==WebSocket.OPEN&&i&&o)console.log("[ws] Tab became visible, socket stale — reconnecting"),e.connect(i,o);else if(n==="connected"&&d&&h[d]){const u=h[d];V.setState({messages:[...u.messages]})}}});const g$=300;function v$({searchResults:e,searchLoading:t,searchQuery:n,searchConversations:i,clearSearchResults:o,onResumeSession:d}){const[h,l]=N.useState(""),u=N.useRef(null),f=N.useRef(null),v=N.useRef(null),g=N.useId(),S=N.useCallback(y=>{const b=y.target.value;l(b),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{const _=b.trim();_?i(_):o()},g$)},[i,o]);N.useEffect(()=>()=>{u.current&&clearTimeout(u.current)},[]);const w=N.useCallback(y=>{if(y.key==="ArrowDown"&&e.length>0){y.preventDefault();const b=v.current?.querySelectorAll('[role="option"]');b&&b.length>0&&b[0].focus()}},[e.length]),E=N.useCallback((y,b,_)=>{switch(y.key){case"ArrowDown":{y.preventDefault();const k=v.current?.querySelectorAll('[role="option"]');k&&b+1<k.length&&k[b+1].focus();break}case"ArrowUp":{if(y.preventDefault(),b===0)f.current?.focus();else{const k=v.current?.querySelectorAll('[role="option"]');k&&k[b-1].focus()}break}case"Enter":case" ":{y.preventDefault(),d(_.conversationId,_.cwd??"");break}}},[d]),m=n.length>0&&!t&&e.length===0;return r.jsxs("div",{className:"conversation-search",children:[r.jsx("input",{ref:f,type:"text",className:"conversation-search-input",placeholder:"Search conversations...",value:h,onChange:S,onKeyDown:w,role:"combobox","aria-expanded":e.length>0,"aria-controls":g,"aria-autocomplete":"list"}),t&&r.jsx("div",{className:"conversation-search-status",children:"Searching..."}),m&&r.jsx("div",{className:"conversation-search-status",children:"No results found"}),e.length>0&&r.jsx("ul",{className:"conversation-search-results",role:"listbox",id:g,ref:v,children:e.map((y,b)=>r.jsxs("li",{className:"conversation-search-result",role:"option",tabIndex:-1,"aria-selected":!1,onClick:()=>d(y.conversationId,y.cwd??""),onKeyDown:_=>E(_,b,y),children:[r.jsx("div",{className:"conversation-search-result-title",children:y.preview||"Untitled conversation"}),r.jsx("div",{className:"conversation-search-result-snippet",children:y.snippet}),r.jsxs("div",{className:"conversation-search-result-meta",children:[y.projectName," · ",y.matchCount," match",y.matchCount!==1?"es":""]})]},y.conversationId))})]})}function hs(){if(typeof window>"u")return!1;const e=window;return"__TAURI_INTERNALS__"in e||"__TAURI__"in e}function _s(){return hs()?window.__TAURI_INTERNALS__?.invoke??null:null}function pg(){return hs()?window.__TAURI__?.event?.listen??null:null}function y$(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.name=="string"&&typeof t.host=="string"&&typeof t.port=="number"&&Number.isFinite(t.port)&&typeof t.wsUrl=="string"&&(t.version==null||typeof t.version=="string")}async function b$(){const e=_s();if(!e)return[];const t=await e("discover_lan_servers");return Array.isArray(t)?t.filter(y$):[]}function Cm(e){const t=e.trim();let n,i;try{if(t.startsWith("chroxy://"))n=new URL(t.replace(/^chroxy:\/\//,"https://")),i=n.port?"ws":"wss";else if(t.startsWith("ws://")||t.startsWith("wss://"))n=new URL(t),i=t.startsWith("wss://")?"wss":"ws";else return null}catch{return null}const o=n.searchParams.get("pair")??void 0,d=n.searchParams.get("token")??void 0;if(!o&&!d)return null;const h=n.searchParams.get("idk")??void 0;return{wsUrl:`${i}://${n.host}/ws`,...o?{pairingId:o}:{},...d?{token:d}:{},...h?{identityKey:h}:{}}}function _$(e){return e.replace(/[\s-]+/g,"").toUpperCase()}function S$(e,t){const n=_$(t.trim());if(!n)return null;const i=e.trim();if(!i)return null;let o="chroxy",d=i;try{if(/^wss?:\/\//i.test(i)){const l=new URL(i);o=i.toLowerCase().startsWith("wss://")?"wss":"ws",d=l.host}else/^chroxy:\/\//i.test(i)?d=new URL(i.replace(/^chroxy:\/\//i,"https://")).host:d=i.replace(/^\/+/,"").split("/")[0]?.split("?")[0]??""}catch{return null}if(!d)return null;const h=`${o}://${d}?pair=${encodeURIComponent(n)}`;return Cm(h)}function x$(){try{return crypto.randomUUID()}catch{return`pr-${Date.now()}-${Math.random().toString(36).slice(2)}`}}function w$(e,t,n){const i=x$();let o=!1,d=null;const h={phase:"requesting",verifyCode:null,token:null,reason:null},l=()=>n({...h}),u=(f,v)=>{if(!o){o=!0,Object.assign(h,{phase:f},v),l();try{d?.close()}catch{}d=null}};try{d=new WebSocket(e)}catch{return u("error",{reason:"connect_failed"}),{cancel:()=>u("error",{reason:"cancelled"})}}return d.onopen=()=>{o||!d||(d.send(JSON.stringify({type:"pair_request",requestId:i,deviceName:t.slice(0,64),protocolVersion:cw})),l())},d.onmessage=f=>{if(o)return;let v;try{v=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}if(!(!v||typeof v!="object")&&!(typeof v.requestId=="string"&&v.requestId!==i)){if(v.type==="pair_request_pending"){typeof v.verifyCode=="string"&&(h.phase="code-shown",h.verifyCode=v.verifyCode,l());return}if(v.type==="pair_result"){if(v.ok===!0&&typeof v.token=="string"){u("approved",{token:v.token});return}const g=typeof v.reason=="string"?v.reason:"denied";g==="expired"?u("expired",{reason:g}):g==="denied"?u("denied",{reason:g}):u("error",{reason:g})}}},d.onerror=()=>{u("error",{reason:"transport_error"})},d.onclose=()=>{o||u("error",{reason:"connection_closed"})},{cancel:()=>u("error",{reason:"cancelled"})}}function s1(e,t){if(!t)return"server-dot disconnected";switch(e){case"connected":return"server-dot connected";case"connecting":case"reconnecting":return"server-dot connecting";case"server_restarting":return"server-dot restarting";case"server_down":return"server-dot down";default:return"server-dot disconnected"}}function uf(e,t){switch(e){case"connected":return"Connected";case"connecting":return"Connecting...";case"reconnecting":return"Reconnecting...";case"server_restarting":return"Restarting...";case"server_down":return"Server down";default:return"Disconnected"}}function k$(e){if(!e)return"Never connected";const t=Date.now()-e;return t<6e4?"Just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:new Date(e).toLocaleDateString()}function C$({onAdd:e,onCancel:t,error:n,initialName:i="",initialUrl:o="",onPair:d,onRequestPair:h}){const[l,u]=N.useState(i),[f,v]=N.useState(o),[g,S]=N.useState(""),w=Cm(f),E=!!w?.pairingId,x=!E&&!!w?.token,m=E||x,y=N.useCallback(b=>{b?.preventDefault();const _=Cm(f);let k=_?.wsUrl??"";try{_&&(k=new URL(_.wsUrl).host)}catch{}if(_?.pairingId){d(l.trim()||k,_.wsUrl,_.pairingId,_.identityKey);return}if(_?.token){e(l.trim()||k,_.wsUrl,_.token);return}!f.trim()||!g.trim()||e(l.trim()||f.trim(),f.trim(),g.trim())},[l,f,g,e,d]);return r.jsxs("form",{className:"server-add-form","data-testid":"server-add-form",onSubmit:y,children:[r.jsx("input",{type:"text",placeholder:"Server name (optional)",value:l,onChange:b=>u(b.target.value),className:"server-input","data-testid":"server-name-input"}),r.jsx("input",{type:"text",placeholder:"wss://your-server/ws or chroxy://…?pair=…",value:f,onChange:b=>v(b.target.value),className:`server-input${n?" server-input-error":""}`,"data-testid":"server-url-input"}),n&&r.jsx("span",{className:"server-form-error","data-testid":"server-url-error",role:"alert",children:n}),m?r.jsx("span",{className:"server-form-hint","data-testid":"server-pairing-hint",children:E?"Pairing URL detected — no token needed.":"Connection URL includes a token — no token needed."}):r.jsx("input",{type:"password",placeholder:"Auth token",value:g,onChange:b=>S(b.target.value),className:"server-input","data-testid":"server-token-input"}),r.jsxs("div",{className:"server-add-actions",children:[r.jsx("button",{type:"submit",className:"server-btn server-btn-primary",disabled:m?!1:!f.trim()||!g.trim(),"data-testid":"server-add-submit",children:E?"Pair":"Add"}),!m&&(()=>{const b=f.trim(),_=/^wss?:\/\//i.test(b);return r.jsx("button",{type:"button",className:"server-btn",disabled:!_,onClick:()=>h(l.trim()||b,b),"data-testid":"server-request-pair",title:"Request approval-gated pairing from the host (no token needed)",children:"Request to pair"})})(),r.jsx("button",{type:"button",className:"server-btn",onClick:t,"data-testid":"server-add-cancel",children:"Cancel"})]})]})}function E$({wsUrl:e,name:t,onApproved:n,onCancel:i}){const[o,d]=N.useState({phase:"requesting",verifyCode:null,token:null,reason:null}),h=N.useRef(null),l=N.useRef(n);l.current=n,N.useEffect(()=>{const f=w$(e,"Desktop Browser",v=>{d(v),v.phase==="approved"&&v.token&&l.current(t,e,v.token)});return h.current=f,()=>f.cancel()},[e,t]);const u=e.replace(/^wss?:\/\//,"").replace(/\/ws$/,"");return r.jsxs("div",{className:"server-pair-request","data-testid":"request-pair-panel",children:[r.jsx("div",{className:"server-pair-request-host",children:u}),(o.phase==="requesting"||o.phase==="code-shown")&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"server-pair-request-status","data-testid":"request-pair-status",children:o.phase==="requesting"?"Requesting pairing…":"Waiting for approval on the host"}),o.verifyCode&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"server-pair-request-compare",children:"Compare this code with the host:"}),r.jsx("div",{className:"server-pair-request-code","data-testid":"request-pair-code",children:o.verifyCode})]})]}),o.phase==="denied"&&r.jsx("div",{className:"server-pair-request-status server-pair-request-status--error","data-testid":"request-pair-denied",children:"Pairing denied by the host."}),o.phase==="expired"&&r.jsx("div",{className:"server-pair-request-status server-pair-request-status--error","data-testid":"request-pair-expired",children:"Request expired. Try again."}),o.phase==="error"&&r.jsxs("div",{className:"server-pair-request-status server-pair-request-status--error","data-testid":"request-pair-error",children:["Could not pair",o.reason?` (${o.reason})`:"","."]}),r.jsx("button",{type:"button",className:"server-btn",onClick:i,"data-testid":"request-pair-cancel",children:o.phase==="approved"?"Done":"Cancel"})]})}function N$({onPair:e,onCancel:t}){const[n,i]=N.useState(""),[o,d]=N.useState(""),[h,l]=N.useState(null),u=N.useCallback(f=>{f?.preventDefault();const v=S$(n,o);if(!v?.pairingId){l("Enter the host (e.g. my.tunnel.tld or 192.168.1.5:8765) and the code shown on it.");return}l(null);let g=v.wsUrl;try{g=new URL(v.wsUrl).host}catch{}e(g,v.wsUrl,v.pairingId,v.identityKey)},[n,o,e]);return r.jsxs("form",{className:"server-add-form","data-testid":"have-code-form",onSubmit:u,children:[r.jsx("input",{type:"text",placeholder:"Host (e.g. my.tunnel.tld or 192.168.1.5:8765)",value:n,onChange:f=>i(f.target.value),className:"server-input","data-testid":"have-code-host-input"}),r.jsx("input",{type:"text",placeholder:"Pairing code",value:o,onChange:f=>d(f.target.value),className:`server-input${h?" server-input-error":""}`,"data-testid":"have-code-code-input",autoCapitalize:"characters",autoCorrect:"off",spellCheck:!1}),h&&r.jsx("span",{className:"server-form-error","data-testid":"have-code-error",role:"alert",children:h}),r.jsxs("div",{className:"server-add-actions",children:[r.jsx("button",{type:"submit",className:"server-btn server-btn-primary",disabled:!n.trim()||!o.trim(),"data-testid":"have-code-submit",children:"Pair"}),r.jsx("button",{type:"button",className:"server-btn",onClick:t,"data-testid":"have-code-cancel",children:"Cancel"})]})]})}function j$({server:e,isActive:t,connectionPhase:n,onConnect:i,onRemove:o}){const[d,h]=N.useState(!1);return r.jsxs("div",{className:`server-item${t?" active":""}`,"data-testid":"server-item",children:[r.jsxs("button",{type:"button",className:"server-item-main",onClick:i,title:`Connect to ${e.name}`,"aria-describedby":`server-status-${e.id}`,children:[r.jsx("span",{className:s1(n,t),"aria-label":t?uf(n):"Idle"}),r.jsxs("div",{className:"server-item-info",children:[r.jsx("span",{className:"server-item-name",children:e.name}),r.jsx("span",{className:"server-item-url",children:e.wsUrl.replace(/^wss?:\/\//,"").replace(/\/ws$/,"")})]}),r.jsx("span",{className:"server-item-status",id:`server-status-${e.id}`,children:t?uf(n):k$(e.lastConnectedAt)})]}),d?r.jsxs("div",{className:"server-item-confirm",children:[r.jsx("button",{type:"button",className:"server-btn server-btn-danger",onClick:()=>{h(!1),o()},"data-testid":"server-remove-confirm",children:"Remove"}),r.jsx("button",{type:"button",className:"server-btn",onClick:()=>h(!1),children:"Cancel"})]}):r.jsx("button",{type:"button",className:"server-remove-btn",onClick:()=>h(!0),"aria-label":`Remove ${e.name}`,"data-testid":"server-remove-btn",children:r.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function A$(){const e=V(P=>P.serverRegistry),t=V(P=>P.activeServerId),n=V(P=>P.connectionPhase),i=V(P=>P.hasLocalServer),o=V(P=>P.addServer),d=V(P=>P.removeServer),h=V(P=>P.switchServer),l=V(P=>P.connectLocal),u=V(P=>P.pairServer),f=V(P=>P.pendingApprovalPairHost),v=V(P=>P.clearPendingApprovalPairHost),[g,S]=N.useState(!1),[w,E]=N.useState(!1),[x,m]=N.useState(null),[y,b]=N.useState(null),[_,k]=N.useState(null),[j,T]=N.useState([]),[D,I]=N.useState(!1),[L,q]=N.useState(null),H=hs(),Q=N.useCallback((P,B,K)=>{try{const le=o(P,B,K);m(null),S(!1),k(null),h(le.id)}catch(le){m(le instanceof Error?le.message:"Failed to add server")}},[o,h]),F=N.useCallback((P,B,K,le)=>{try{u(P,B,K,le),m(null),S(!1),E(!1),k(null)}catch(me){m(me instanceof Error?me.message:"Failed to pair")}},[u]),J=N.useCallback((P,B)=>{m(null),S(!1),k(null),b({name:P,wsUrl:B})},[]),ie=N.useCallback((P,B,K)=>{try{const le=o(P,B,K);h(le.id)}catch(le){m(le instanceof Error?le.message:"Failed to add paired server")}},[o,h]);N.useEffect(()=>{f&&(m(null),S(!1),E(!1),k(null),b({name:f.name,wsUrl:f.wsUrl}),v())},[f,v]);const X=N.useCallback(async()=>{I(!0),q(null);try{T(await b$())}catch(P){q(P instanceof Error?P.message:"Discovery failed"),T([])}finally{I(!1)}},[]),de=N.useCallback(P=>{k({name:P.name,url:P.wsUrl}),m(null),S(!0)},[]),fe=new Set(e.map(P=>P.wsUrl)),$=j.filter(P=>!fe.has(P.wsUrl));return r.jsxs("div",{className:"server-picker","data-testid":"server-picker",children:[r.jsxs("div",{className:"server-picker-header",children:[r.jsx("span",{className:"server-picker-title",children:"Servers"}),r.jsxs("div",{className:"server-picker-header-actions",children:[r.jsx("button",{type:"button",className:"server-btn server-have-code-btn",onClick:()=>{E(!0),S(!1),m(null)},"data-testid":"server-have-code-btn",children:"Have a code?"}),r.jsx("button",{type:"button",className:"server-btn server-btn-add",onClick:()=>{S(!0),E(!1)},"data-testid":"server-add-btn","aria-label":"Add server",children:r.jsx("span",{"aria-hidden":"true",children:"+"})})]})]}),w&&r.jsx(N$,{onPair:F,onCancel:()=>E(!1)}),g&&r.jsx(C$,{onAdd:Q,onPair:F,onRequestPair:J,onCancel:()=>{S(!1),m(null),k(null)},error:x,initialName:_?.name??"",initialUrl:_?.url??""},_?.url??"blank"),y&&r.jsx(E$,{wsUrl:y.wsUrl,name:y.name,onApproved:ie,onCancel:()=>b(null)},y.wsUrl),H&&r.jsxs("div",{className:"server-discover","data-testid":"server-discover",children:[r.jsx("button",{type:"button",className:"server-btn server-discover-btn",onClick:X,disabled:D,"data-testid":"server-discover-btn",children:D?"Scanning LAN…":"Discover on LAN"}),L&&r.jsx("span",{className:"server-form-error","data-testid":"server-discover-error",role:"alert",children:L}),!D&&!L&&j.length>0&&$.length===0&&r.jsx("span",{className:"server-discover-empty","data-testid":"server-discover-allknown",children:"All discovered servers are already added."}),$.map(P=>r.jsxs("div",{className:"server-discover-item","data-testid":`server-discover-row-${P.host}`,children:[r.jsxs("span",{className:"server-item-info",children:[r.jsx("span",{className:"server-item-name",children:P.name}),r.jsxs("span",{className:"server-item-url",children:[P.host,":",P.port,P.version?` • v${P.version}`:""]})]}),r.jsxs("div",{className:"server-discover-actions",children:[r.jsx("button",{type:"button",className:"server-btn server-btn-primary server-discover-pair",onClick:()=>J(P.name,P.wsUrl),"data-testid":`server-discover-pair-${P.host}`,title:`Request to pair with ${P.name} (no token needed)`,children:"Request to pair"}),r.jsx("button",{type:"button",className:"server-btn server-discover-add-btn",onClick:()=>de(P),"data-testid":`server-discover-item-${P.host}`,title:`Add ${P.name} with a token`,children:"Add with token"})]})]},P.wsUrl))]}),i&&r.jsx("div",{className:`server-item${t===null?" active":""}`,"data-testid":"server-item-local",children:r.jsxs("button",{type:"button",className:"server-item-main",onClick:()=>l(),title:"Connect to the daemon on this machine",children:[r.jsx("span",{className:s1(n,t===null),"aria-label":t===null?uf(n):"Idle"}),r.jsxs("div",{className:"server-item-info",children:[r.jsx("span",{className:"server-item-name",children:"This machine"}),r.jsx("span",{className:"server-item-url",children:"local daemon"})]}),r.jsx("span",{className:"server-item-status",children:t===null?uf(n):"Idle"})]})}),e.length===0&&!g&&!i&&r.jsx("div",{className:"server-empty","data-testid":"server-empty",children:"No servers configured."}),e.map(P=>r.jsx(j$,{server:P,isActive:P.id===t,connectionPhase:P.id===t?n:"disconnected",onConnect:()=>h(P.id),onRemove:()=>d(P.id)},P.id))]})}function R$(e){switch(e){case"phone":return"📱";case"tablet":return"📟";case"desktop":return"🖥";default:return"🌐"}}function hS(e){return e.deviceName?e.deviceName:e.platform?e.platform:e.deviceType!=="unknown"?e.deviceType:"Unknown device"}function T$(e,t,n){return e?t[e]?.primaryClientId??null:n}function I$({clients:e,primaryClientId:t,connected:n,sessionRole:i,onTakeOver:o}){const[d,h]=N.useState(!1),l=N.useRef(null),u=N.useRef(null),f=N.useId();if(N.useEffect(()=>{if(!d)return;const x=b=>{const _=b.target;u.current?.contains(_)||l.current?.contains(_)||h(!1)},m=b=>{b.key==="Escape"&&(b.stopPropagation(),h(!1),l.current?.focus())},y=()=>h(!1);return document.addEventListener("mousedown",x,!0),document.addEventListener("keydown",m),window.addEventListener("blur",y),()=>{document.removeEventListener("mousedown",x,!0),document.removeEventListener("keydown",m),window.removeEventListener("blur",y)}},[d]),!n)return null;const v=e.length;if(v===0)return null;const g=`${v} client${v===1?"":"s"}`,S=i==="observer";if(v===1)return r.jsx("span",{className:"sidebar-client-count","data-testid":"viewers-indicator-solo",children:g});const w=t?e.find(x=>x.clientId===t):null,E=w?hS(w):"another device";return r.jsxs("div",{className:`viewers-indicator sidebar-client-count${S?" observing":""}`,"data-testid":"viewers-indicator",children:[r.jsxs("button",{ref:l,type:"button",className:"viewers-trigger","data-testid":"viewers-indicator-trigger",onClick:()=>h(x=>!x),"aria-haspopup":"dialog","aria-expanded":d,"aria-controls":f,"aria-label":S?`Observing — ${E} is driving. ${g} sharing this session — show devices`:`${g} sharing this session — show devices`,title:S?`Observing — ${E} is driving`:`${g} sharing this session`,children:[r.jsx("span",{className:"viewers-trigger-glyph","aria-hidden":"true",children:"👥"}),r.jsx("span",{className:"viewers-trigger-count",children:v}),S&&r.jsx("span",{className:"viewers-observing-badge","data-testid":"viewers-observing-badge",children:"Observing"})]}),d&&r.jsxs("div",{ref:u,id:f,className:"viewers-popover","data-testid":"viewers-popover",role:"dialog","aria-modal":"false","aria-label":"Connected devices",children:[r.jsxs("div",{className:"viewers-popover-header",children:[r.jsx("strong",{children:"Shared session"}),r.jsx("p",{className:"viewers-popover-sub",children:"Everyone here sees the same output. The agent handles one request at a time — if it's busy, other devices wait."})]}),r.jsx("ul",{className:"viewers-list",children:e.map(x=>{const m=!!t&&x.clientId===t;return r.jsxs("li",{className:"viewers-client-row","data-testid":`viewers-client-${x.clientId}`,children:[r.jsx("span",{className:"viewers-client-glyph","aria-hidden":"true",children:R$(x.deviceType)}),r.jsx("span",{className:"viewers-client-name",children:hS(x)}),x.isSelf&&r.jsx("span",{className:"viewers-tag viewers-tag-self","data-testid":`viewers-self-${x.clientId}`,children:"This device"}),m&&r.jsx("span",{className:"viewers-tag viewers-tag-primary","data-testid":`viewers-primary-${x.clientId}`,children:"drove last"})]},x.clientId)})}),S&&r.jsxs("div",{className:"viewers-observing-footer","data-testid":"viewers-observing-footer",children:[r.jsxs("p",{className:"viewers-observing-note",children:[E," is driving. Your input is rejected while the agent is busy — take over to drive."]}),o&&r.jsx("button",{type:"button",className:"viewers-takeover-button","data-testid":"viewers-takeover-button",onClick:()=>{o(),h(!1)},children:"Take over"})]})]})]})}const M$=120,D$=600,L$=28;function O$({views:e,launchers:t,selectedViewId:n,onSelectView:i,collapsed:o,onCollapsedChange:d,height:h,onHeightChange:l,minHeight:u=M$,maxHeight:f=D$}){const v=e.find(j=>j.id===n)??e[0]??null,g=N.useRef(!1),S=N.useRef(0),w=N.useRef(h),E=N.useRef(null),x=N.useRef(null),m=N.useCallback(j=>{if(o)return;j.preventDefault(),g.current=!0,S.current=j.clientY,w.current=h;const T=I=>{if(!g.current)return;const L=S.current-I.clientY,q=Math.min(f,Math.max(u,w.current+L));l(q)},D=()=>{g.current=!1,document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",D),E.current=null,x.current=null};E.current=T,x.current=D,document.addEventListener("mousemove",T),document.addEventListener("mouseup",D)},[o,h,f,u,l]),y=N.useCallback(j=>{if(o)return;const T=16;j.key==="ArrowUp"?(j.preventDefault(),l(Math.min(f,h+T))):j.key==="ArrowDown"&&(j.preventDefault(),l(Math.max(u,h-T)))},[o,h,f,u,l]);N.useEffect(()=>()=>{g.current=!1,E.current&&(document.removeEventListener("mousemove",E.current),E.current=null),x.current&&(document.removeEventListener("mouseup",x.current),x.current=null)},[]);const b=N.useRef([]),_=N.useCallback((j,T)=>{if(e.length===0)return;let D=null;switch(j.key){case"ArrowLeft":D=(T-1+e.length)%e.length;break;case"ArrowRight":D=(T+1)%e.length;break;case"Home":D=0;break;case"End":D=e.length-1;break;default:return}j.preventDefault();const I=e[D];I&&(i(I.id),b.current[D]?.focus())},[i,e]);if(e.length===0)return null;const k=Math.min(f,Math.max(u,h));return r.jsxs("div",{className:"sidebar-panel-slot","data-testid":"sidebar-panel-slot","data-collapsed":o?"true":"false",children:[!o&&r.jsx("div",{className:"sidebar-panel-slot-resize-handle","data-testid":"sidebar-panel-slot-resize-handle",role:"separator","aria-orientation":"horizontal","aria-valuenow":k,"aria-valuemin":u,"aria-valuemax":f,"aria-label":"Resize sidebar panel",tabIndex:0,onMouseDown:m,onKeyDown:y}),r.jsxs("div",{className:"sidebar-panel-slot-header","data-testid":"sidebar-panel-slot-header",style:{height:L$},children:[r.jsx("div",{className:"sidebar-panel-slot-tabs",role:"tablist","aria-label":"Sidebar panel views",children:e.map((j,T)=>{const D=j.id===v?.id;return r.jsx("button",{ref:I=>{b.current[T]=I},type:"button",role:"tab","aria-selected":D,"aria-controls":`sidebar-panel-slot-view-${j.id}`,"data-testid":`sidebar-panel-slot-tab-${j.id}`,className:`sidebar-panel-slot-tab${D?" selected":""}`,onClick:()=>i(j.id),onKeyDown:I=>_(I,T),tabIndex:D?0:-1,children:j.label},j.id)})}),t&&t.length>0&&r.jsx("div",{className:"sidebar-panel-slot-launchers",children:t.map(j=>r.jsx("button",{type:"button",className:"sidebar-panel-slot-launcher","data-testid":`sidebar-panel-slot-launcher-${j.id}`,title:j.title??j.label,onClick:j.onClick,children:j.label},j.id))}),o&&v?.collapsedHeaderMetric&&r.jsx("div",{className:"sidebar-panel-slot-collapsed-metric","data-testid":"sidebar-panel-slot-collapsed-metric",children:v.collapsedHeaderMetric()}),r.jsx("button",{type:"button",className:"sidebar-panel-slot-collapse-toggle","data-testid":"sidebar-panel-slot-collapse-toggle","aria-label":o?"Expand sidebar panel":"Collapse sidebar panel","aria-expanded":!o,onClick:()=>d(!o),children:o?"▴":"▾"})]}),!o&&v&&r.jsx("div",{className:"sidebar-panel-slot-body","data-testid":"sidebar-panel-slot-body",id:`sidebar-panel-slot-view-${v.id}`,role:"tabpanel",style:{height:k},children:v.render()})]})}const i1=new Set(["claude-tui"]),P$={"api-key":"Cost (BYOK)","programmatic-credit":"Credit spend",subscription:"Included (subscription)"},B$={"api-key":"Billed per token against your own API key. Cost is computed from billed tokens, which include the full conversation context re-sent every call — so long agentic sessions bill far more input than the visible count suggests. Pricing follows the provider’s published rates.","programmatic-credit":"Drawn from Anthropic’s monthly programmatic-credit pool (metered credits, effective 2026-06-15). The dollar figure is the metered credit spend for these turns.",subscription:"Included in your flat Claude subscription — no per-turn dollar charge. Token counts are shown above; there is no metered cost to display."},$$=["api-key","programmatic-credit","subscription"],z$=new Set(["claude-tui","claude-channel"]),U$=new Set(["claude-byok","docker-byok","codex","gemini","deepseek","ollama"]);function r1(e){if(e.billingClass)return e.billingClass;const t=e.provider??"unknown";return z$.has(t)?"subscription":(U$.has(t),"api-key")}const Fd={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,turnsBilled:0};function pS(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheCreationTokens:e.cacheCreationTokens+t.cacheCreationTokens,costUsd:e.costUsd+t.costUsd,turnsBilled:e.turnsBilled+t.turnsBilled}}function q$(e){const t=e.inputTokens+e.cacheReadTokens+e.cacheCreationTokens;return t<=0?null:e.cacheReadTokens/t}function H$(e){return`${Math.round(e*100)}%`}function a1(e){const t=new Map,n=new Map;let i=Fd,o=0,d=!1;for(const u of e){o+=1;const f=u.provider??"unknown",v=i1.has(f);v&&(d=!0);const g=r1(u),S=u.cumulativeUsage??Fd;t.has(f)||t.set(f,{provider:f,untracked:v,totals:Fd,sessionCount:0,billingClass:g});const w=t.get(f);w.totals=pS(w.totals,S),w.sessionCount+=1,n.has(g)||n.set(g,{billingClass:g,costUsd:0,sessionCount:0});const E=n.get(g);E.costUsd+=S.costUsd,E.sessionCount+=1,v||(i=pS(i,S))}const h=Array.from(t.values()).sort((u,f)=>{if(u.untracked!==f.untracked)return u.untracked?1:-1;const v=u.totals.inputTokens+u.totals.outputTokens;return f.totals.inputTokens+f.totals.outputTokens-v}),l=$$.map(u=>n.get(u)).filter(u=>u!==void 0);return{totals:i,byProvider:h,byBillingClass:l,totalSessions:o,hasUntracked:d}}function Up({triggerText:e,ariaLabel:t,triggerClassName:n,testIdBase:i,children:o}){const[d,h]=N.useState(!1),l=N.useId(),u=N.useRef(null),f=N.useRef(null),v=N.useRef(!1),g=N.useRef("mouse");return N.useEffect(()=>{if(!d)return;function S(E){E.key==="Escape"&&(h(!1),f.current?.focus())}function w(E){const x=E.target;x&&(u.current&&u.current.contains(x)||h(!1))}return document.addEventListener("keydown",S),document.addEventListener("pointerdown",w),document.addEventListener("mousedown",w),()=>{document.removeEventListener("keydown",S),document.removeEventListener("pointerdown",w),document.removeEventListener("mousedown",w)}},[d]),r.jsxs("span",{className:"sidebar-token-view-disclosure",ref:u,children:[r.jsx("button",{type:"button",ref:f,className:n,"data-testid":i,"aria-label":t,"aria-expanded":d,"aria-controls":d?l:void 0,onPointerDown:S=>{g.current=S.pointerType||"mouse"},onClick:()=>{if(g.current==="touch"&&v.current){v.current=!1,h(!0);return}h(S=>!S),v.current=!1},onMouseEnter:()=>{v.current=!0,h(!0)},onMouseLeave:()=>{v.current&&(h(!1),v.current=!1)},children:e}),d&&r.jsx("span",{id:l,className:"sidebar-token-view-popover","data-testid":`${i}-popover`,role:"tooltip",children:o})]})}const F$="Token count not exposed by claude TUI (PTY-only interface)";function K$({sessions:e,activeSessionId:t=null,onSessionClick:n,monthlyBudget:i=null}){const o=N.useMemo(()=>a1(e),[e]),d=o.totals.inputTokens+o.totals.outputTokens,h=q$(o.totals),l=N.useMemo(()=>e.filter(u=>!i1.has(u.provider??"unknown")).map(u=>{const f=u.cumulativeUsage??Fd;return{session:u,tokens:f.inputTokens+f.outputTokens,costUsd:f.costUsd,billingClass:r1(u)}}).sort((u,f)=>{const v=u.session.sessionId===t,g=f.session.sessionId===t;return v!==g?v?-1:1:f.tokens-u.tokens}),[e,t]);return r.jsxs("div",{className:"sidebar-token-view","data-testid":"sidebar-token-view",children:[r.jsxs("div",{className:"sidebar-token-view-aggregate","data-testid":"sidebar-token-view-aggregate",children:[r.jsxs("div",{className:"sidebar-token-view-aggregate-row",children:[r.jsx("span",{className:"sidebar-token-view-label",children:"Today"}),r.jsxs("span",{className:"sidebar-token-view-value","data-testid":"sidebar-token-view-today-total",children:[oa(d)," tokens"]})]}),r.jsxs("div",{className:"sidebar-token-view-aggregate-row",children:[r.jsx("span",{className:"sidebar-token-view-label",children:"Input · Output"}),r.jsxs("span",{className:"sidebar-token-view-value-secondary",children:[oa(o.totals.inputTokens)," · ",oa(o.totals.outputTokens)]})]}),h!==null&&r.jsxs("div",{className:"sidebar-token-view-aggregate-row",children:[r.jsx("span",{className:"sidebar-token-view-label",children:"Cache hit"}),r.jsx("span",{className:"sidebar-token-view-value-secondary","data-testid":"sidebar-token-view-cache-hit",children:H$(h)})]}),o.byBillingClass.map(u=>{const f=u.billingClass==="subscription";if(!f&&u.costUsd<=0)return null;const v=P$[u.billingClass];return r.jsxs("div",{className:"sidebar-token-view-aggregate-row","data-testid":`sidebar-token-view-cost-${u.billingClass}`,children:[r.jsxs("span",{className:"sidebar-token-view-label",children:[v," ",r.jsx(Up,{triggerText:"ⓘ",ariaLabel:`What does "${v}" mean?`,triggerClassName:"sidebar-token-view-info",testIdBase:`sidebar-token-view-cost-info-${u.billingClass}`,children:B$[u.billingClass]})]}),f?r.jsx("span",{className:"sidebar-token-view-value-secondary sidebar-token-view-included-chip","data-testid":`sidebar-token-view-cost-value-${u.billingClass}`,children:"Included"}):r.jsx("span",{className:"sidebar-token-view-value-secondary","data-testid":`sidebar-token-view-cost-value-${u.billingClass}`,children:gr(u.costUsd)})]},u.billingClass)}),i&&(i.budgetUsd!=null||i.spentUsd>0)&&(()=>{const{spentUsd:u,budgetUsd:f,percent:v,warning:g,exceeded:S}=i,w=v==null?null:Math.min(100,Math.max(0,v)),E=S?"exceeded":g?"warning":"ok";return r.jsxs("div",{className:`sidebar-token-view-credit-meter sidebar-token-view-credit-meter-${E}`,"data-testid":"sidebar-token-view-credit-meter","data-meter-state":E,children:[r.jsxs("div",{className:"sidebar-token-view-aggregate-row",children:[r.jsxs("span",{className:"sidebar-token-view-label",children:["Credit spend"," ",r.jsx(Up,{triggerText:"ⓘ",ariaLabel:"What does the credit spend meter count?",triggerClassName:"sidebar-token-view-info",testIdBase:"sidebar-token-view-credit-meter-info",children:"Chroxy-observed programmatic-credit spend (claude -p / SDK) this UTC month — only sessions THIS daemon ran. Not your full Anthropic credit-pool balance; sessions on other machines or outside chroxy aren't counted."})]}),r.jsx("span",{className:"sidebar-token-view-value-secondary","data-testid":"sidebar-token-view-credit-meter-value",children:f!=null?`${gr(u)} / ${gr(f)}${w!=null?` · ${Math.round(w)}%`:""}`:`${gr(u)} this month`})]}),f!=null&&w!=null&&r.jsx("div",{className:"sidebar-token-view-credit-bar",role:"progressbar","aria-valuenow":Math.round(w),"aria-valuemin":0,"aria-valuemax":100,"aria-label":"Monthly credit spend",children:r.jsx("div",{className:"sidebar-token-view-credit-bar-fill","data-testid":"sidebar-token-view-credit-bar-fill",style:{width:`${w}%`}})})]})})()]}),r.jsxs("div",{className:"sidebar-token-view-section","data-testid":"sidebar-token-view-by-provider",children:[r.jsx("div",{className:"sidebar-token-view-section-header",children:"By provider"}),o.byProvider.length===0?r.jsx("div",{className:"sidebar-token-view-empty","data-testid":"sidebar-token-view-empty",children:"No sessions yet"}):r.jsx("ul",{className:"sidebar-token-view-provider-list",children:o.byProvider.map(u=>{const f=YN(u.provider),v=u.totals.inputTokens+u.totals.outputTokens,g=u.billingClass==="subscription";return r.jsxs("li",{className:"sidebar-token-view-provider-row","data-testid":`sidebar-token-view-provider-${u.provider}`,"data-billing-class":u.billingClass,children:[r.jsx("span",{className:"sidebar-token-view-provider-label",children:f}),u.untracked?r.jsx(Up,{triggerText:"—",ariaLabel:`Why does ${f} not show a token count?`,triggerClassName:"sidebar-token-view-provider-untracked",testIdBase:`sidebar-token-view-provider-${u.provider}-untracked`,children:F$}):r.jsxs("span",{className:"sidebar-token-view-provider-tokens",children:[oa(v),g?r.jsxs("span",{className:"sidebar-token-view-provider-cost sidebar-token-view-included-chip",children:[" ","(Included)"]}):u.totals.costUsd>0&&r.jsxs("span",{className:"sidebar-token-view-provider-cost",children:[" ","(",gr(u.totals.costUsd),")"]})]})]},u.provider)})})]}),l.length>0&&r.jsxs("div",{className:"sidebar-token-view-section","data-testid":"sidebar-token-view-by-session",children:[r.jsx("div",{className:"sidebar-token-view-section-header",children:"By session"}),r.jsx("ul",{className:"sidebar-token-view-session-list",children:l.map(({session:u,tokens:f,costUsd:v,billingClass:g})=>{const S=u.sessionId===t,w=g==="subscription",E=r.jsxs("span",{className:"sidebar-token-view-session-tokens","data-billing-class":g,children:[oa(f),w?r.jsxs("span",{className:"sidebar-token-view-provider-cost sidebar-token-view-included-chip",children:[" ","(Included)"]}):v>0&&r.jsxs("span",{className:"sidebar-token-view-provider-cost",children:[" ","(",gr(v),")"]})]}),x=`sidebar-token-view-session-row${S?" active":""}`,m=`sidebar-token-view-session-${u.sessionId}`;return n?r.jsx("li",{children:r.jsxs("button",{type:"button",className:x,"data-testid":m,"aria-current":S?"true":void 0,onClick:()=>n(u.sessionId),children:[r.jsx("span",{className:"sidebar-token-view-session-name",children:u.name}),E]})},u.sessionId):r.jsxs("li",{className:x,"data-testid":m,"aria-current":S?"true":void 0,children:[r.jsx("span",{className:"sidebar-token-view-session-name",children:u.name}),E]},u.sessionId)})})]})]})}function W$(e){const t=a1(e),n=t.totals.inputTokens+t.totals.outputTokens;return`${oa(n)} tokens`}function jd(e,t,n){if(e.length<=1)return e;const i=Math.max(0,Math.min(t,e.length-1)),o=Math.max(0,Math.min(n,e.length-1));if(i===o)return e;const d=e.slice(),[h]=d.splice(i,1);return d.splice(o,0,h),d}function mS(e,t,n){if(e.length===0)return[];if(t.length===0)return e.slice();const i=new Map;for(const h of e)i.set(n(h),h);const o=new Set,d=[];for(const h of t){const l=i.get(h);l&&!o.has(h)&&(d.push(l),o.add(h))}for(const h of e){const l=n(h);o.has(l)||(d.push(h),o.add(l))}return d}function gS(e,t){return e.map(t)}const Em="chroxy_persist_shortcut_overrides_v1",G$=new Set(["cmd","meta","ctrl","control"]),V$="shift",Y$=new Set(["alt","option","opt"]);function il(e){const t=e.trim().toLowerCase().split("+").map(l=>l.trim()).filter(Boolean);if(t.length===0)return"";let n=!1,i=!1,o=!1,d="";for(const l of t)G$.has(l)?n=!0:l===V$?i=!0:Y$.has(l)?o=!0:d=l;!d&&t.length>0&&(d=t[t.length-1]);const h=[];return n&&h.push("cmd"),i&&h.push("shift"),o&&h.push("alt"),h.push(d),h.join("+")}function Nm(e){const n=il(e).split("+");return{key:n[n.length-1]||"",meta:n.includes("cmd"),shift:n.includes("shift"),alt:n.includes("alt")}}const df={arrowup:"ArrowUp",arrowdown:"ArrowDown",arrowleft:"ArrowLeft",arrowright:"ArrowRight",pageup:"PageUp",pagedown:"PageDown",enter:"Enter",tab:"Tab",escape:"Escape",backspace:"Backspace",delete:"Delete",home:"Home",end:"End",space:"Space",insert:"Insert"};function vS(e){if(!e)return"";const t=e.split("+"),n=[];for(let i=0;i<t.length;i+=1){const o=t[i];o==="cmd"?n.push("Meta"):o==="ctrl"?n.push("Control"):o==="shift"?n.push("Shift"):o==="alt"?n.push("Alt"):i===t.length-1?/^[a-z]$/.test(o)?n.push(o.toUpperCase()):Object.prototype.hasOwnProperty.call(df,o)?n.push(df[o]):n.push(o):n.push(o)}return n.join("+")}function Jo(e,t){if(!e)return"";const n=e.split("+"),i=[];for(let o=0;o<n.length;o+=1){const d=n[o];d==="cmd"?i.push(t?"Cmd":"Ctrl"):d==="shift"?i.push("Shift"):d==="alt"?i.push(t?"Option":"Alt"):o===n.length-1?/^[a-z]$/.test(d)?i.push(d.toUpperCase()):Object.prototype.hasOwnProperty.call(df,d)?i.push(df[d]):/^[a-z]/.test(d)?i.push(d.charAt(0).toUpperCase()+d.slice(1)):i.push(d):i.push(d)}return i.join("+")}function Z$(e){if(!e||typeof e.tagName!="string")return!1;const t=e,n=t.tagName;return!!(n==="INPUT"||n==="TEXTAREA"||n==="SELECT"||t.isContentEditable)}function X$(){try{const e=localStorage.getItem(Em);if(!e)return{};const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))return{};const n={};for(const[i,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(n[i]=il(o));return n}catch{return{}}}function qp(e){try{Object.keys(e).length===0?localStorage.removeItem(Em):localStorage.setItem(Em,JSON.stringify(e))}catch{}}function Q$(e){const t=e.map(m=>({...m,defaultBinding:il(m.defaultBinding)}));let n=X$();const i=new Set,o=new Map;for(const m of t)o.set(m.id,m);function d(m){const y=n[m];return y||(o.get(m)?.defaultBinding??"")}function h(m){const y=o.get(m);if(!y)return null;const b=d(m);return{...y,binding:b,isCustomized:b!==y.defaultBinding}}function l(){return t.map(m=>{const y=d(m.id);return{...m,binding:y,isCustomized:y!==m.defaultBinding}})}function u(m,y){const b=o.get(m);if(!b)return null;const _=il(y);if(!_||b.enabled&&!b.enabled())return null;for(const k of t)if(k.id!==m&&k.scope===b.scope&&!(k.enabled&&!k.enabled())&&d(k.id)===_)return{...k,binding:_,isCustomized:d(k.id)!==k.defaultBinding};return null}function f(){for(const m of i)try{m()}catch{}}function v(m,y){const b=o.get(m);if(!b)throw new Error(`Unknown shortcut id: ${m}`);const _=il(y);if(!_)throw new Error("Empty binding");if(d(m)===_)return;const k=u(m,_);if(k)throw new Error(`Binding conflict: "${_}" is already used by "${k.description}" (${k.id})`);_===b.defaultBinding?delete n[m]:n[m]=_,qp(n),f()}function g(m){m in n&&(delete n[m],qp(n),f())}function S(){Object.keys(n).length!==0&&(n={},qp(n),f())}function w(m,y){const b=(m.key||"").toLowerCase(),_=m.metaKey||m.ctrlKey,k=Z$(m.target);for(const j of t){if(j.scope!==y)continue;const T=d(j.id),D=Nm(T);if(D.key===b&&D.meta===_&&D.shift===m.shiftKey&&D.alt===m.altKey){if(j.disabledInTextInput&&k||j.enabled&&!j.enabled())continue;return j.id}}return null}function E(m){return i.add(m),()=>{i.delete(m)}}function x(){return t}return{list:l,getBinding:d,get:h,setBinding:v,resetBinding:g,resetAll:S,findConflict:u,matchEvent:w,subscribe:E,definitions:x}}const J$=[1,2,3,4,5,6,7,8,9],e8=J$.map(e=>({id:`session.switch.${e}`,defaultBinding:`cmd+${e}`,description:`Switch to tab ${e}`,category:"session",scope:"global"})),t8=[{id:"palette.toggle",defaultBinding:"cmd+k",description:"Toggle command palette",category:"navigation",scope:"global"},{id:"file.openPalette",defaultBinding:"cmd+p",description:"Quick open file",category:"navigation",scope:"global"},{id:"symbol.search",defaultBinding:"cmd+shift+o",description:"Search symbols",category:"navigation",scope:"global"},{id:"search.inProject",defaultBinding:"cmd+shift+f",description:"Search in files",category:"navigation",scope:"global"},{id:"sidebar.toggle",defaultBinding:"cmd+b",description:"Toggle sidebar",category:"view",scope:"global"},{id:"settings.open",defaultBinding:"cmd+,",description:"Open settings",category:"navigation",scope:"global"},{id:"device.pairQr",defaultBinding:"cmd+shift+l",description:"Pair a device (show QR)",category:"navigation",scope:"global"},{id:"session.new",defaultBinding:"cmd+n",description:"New session",category:"session",scope:"global"},{id:"palette.toggle.vscode",defaultBinding:"cmd+shift+p",description:"Toggle command palette (VSCode alias)",category:"navigation",scope:"global"},{id:"view.toggleChatTerminal",defaultBinding:"cmd+shift+d",description:"Toggle chat / terminal view",category:"view",scope:"global"},{id:"view.cycleSplit",defaultBinding:"cmd+\\",description:"Cycle split view",category:"view",scope:"global"},{id:"session.copyTranscript",defaultBinding:"cmd+shift+t",description:"Copy chat transcript",category:"session",scope:"global"},{id:"session.interrupt",defaultBinding:"cmd+.",description:"Interrupt session",category:"session",scope:"global"},{id:"session.togglePlanMode",defaultBinding:"shift+tab",description:"Toggle plan mode",category:"session",scope:"global",disabledInTextInput:!0},{id:"help.toggle",defaultBinding:"?",description:"Show keyboard shortcuts",category:"other",scope:"global",disabledInTextInput:!0},{id:"session.prev",defaultBinding:"cmd+shift+[",description:"Previous tab",category:"session",scope:"global"},{id:"session.next",defaultBinding:"cmd+shift+]",description:"Next tab",category:"session",scope:"global"},{id:"session.close",defaultBinding:"cmd+w",description:"Close tab (desktop)",category:"session",scope:"global",enabled:()=>hs()},...e8,{id:"sidebar.reorder.up",defaultBinding:"alt+arrowup",description:"Move sidebar row up (when focused)",category:"sidebar",scope:"global"},{id:"sidebar.reorder.down",defaultBinding:"alt+arrowdown",description:"Move sidebar row down (when focused)",category:"sidebar",scope:"global"},{id:"session.reorder.lift",defaultBinding:"shift+space",description:"Lift session tab for keyboard reorder (Arrow Left/Right to move, Enter/Escape to commit/cancel)",category:"session",scope:"sessionbar"}];function n8(e){const t={registry:e,version:0,subscribers:new Set,notify:()=>{}};return t.notify=()=>{t.version+=1;for(const n of t.subscribers)n()},e.subscribe(t.notify),t}let bc=n8(Q$(t8));function mg(){return N.useSyncExternalStore(e=>(bc.subscribers.add(e),()=>{bc.subscribers.delete(e)}),()=>bc.version,()=>bc.version),bc.registry}function s8(e){try{return new URL(e).hostname}catch{return e}}function i8({repos:e,activeSessionId:t,isOpen:n,width:i,filter:o,serverStatus:d,chatActivityState:h,tunnelUrl:l,connectedClients:u,activePrimaryClientId:f,activeSessionRole:v,onTakeOverPrimary:g,onFilterChange:S,onSessionClick:w,onResumeSession:E,onNewSession:x,onToggle:m,onContextMenu:y,searchResults:b=[],searchLoading:_=!1,searchQuery:k="",searchConversations:j,clearSearchResults:T,onWidthChange:D,sessions:I=[],monthlyBudget:L=null,initialPanelHeight:q=200,initialPanelView:H=null,initialPanelCollapsed:Q=!1,onReorderRepos:F,onReorderSessions:J,onOpenControlRoom:ie}){const[X,de]=N.useState({}),[fe,$]=N.useState(0),P=N.useRef(null),B=mg(),K=B.getBinding("sidebar.reorder.up"),le=B.getBinding("sidebar.reorder.down"),me=`${vS(K)} ${vS(le)}`,[be,Ee]=N.useState(q),[se,Z]=N.useState(H??"tokens"),[ge,De]=N.useState(Q),Ge=N.useCallback(Ie=>{Ee(Ie),pP(Ie)},[]),Ve=N.useCallback(Ie=>{Z(Ie),gP(Ie)},[]),St=N.useCallback(Ie=>{De(Ie),yP(Ie)},[]),Nt=N.useMemo(()=>[{id:"tokens",label:"Tokens",render:()=>r.jsx(K$,{sessions:I,activeSessionId:t,onSessionClick:w,monthlyBudget:L}),collapsedHeaderMetric:()=>W$(I)}],[I,t,w,L]),kt=N.useMemo(()=>ie?[{id:"control-room",label:"Control Room",title:"Open the Control Room",onClick:ie}]:[],[ie]),Tt=N.useCallback(Ie=>{de(ot=>({...ot,[Ie]:!ot[Ie]}))},[]),at=o?e.map(Ie=>{const ot=o.toLowerCase(),pt=Ie.name.toLowerCase().includes(ot),At=Ie.activeSessions.filter(G=>G.name.toLowerCase().includes(ot)),O=Ie.resumableSessions.filter(G=>(G.preview??"").toLowerCase().includes(ot)),W=At.length>0||O.length>0;return!pt&&!W?null:{...Ie,activeSessions:pt?Ie.activeSessions:At,resumableSessions:pt?Ie.resumableSessions:O}}).filter(Ie=>Ie!==null):e,[en,cn]=N.useState(null),[Bt,hn]=N.useState(null),[sn,Ct]=N.useState(null),[Ut,$t]=N.useState(null),Lt=N.useCallback(Ie=>{const ot=Ie.currentTarget.getBoundingClientRect(),pt=ot.top+ot.height/2;return Ie.clientY<pt?"before":"after"},[]),Ht=N.useCallback(Ie=>ot=>{if(F){ot.dataTransfer.effectAllowed="move";try{ot.dataTransfer.setData("text/plain",Ie)}catch{}cn(Ie)}},[F]),zt=N.useCallback(Ie=>ot=>{if(!F||en===null)return;ot.preventDefault(),ot.dataTransfer.dropEffect="move";const pt=Lt(ot);hn(At=>At&&At.path===Ie&&At.position===pt?At:{path:Ie,position:pt})},[F,en,Lt]),rn=N.useCallback(Ie=>()=>{hn(ot=>ot&&ot.path===Ie?null:ot)},[]),ze=N.useCallback(Ie=>ot=>{if(!F||en===null)return;ot.preventDefault();const pt=Lt(ot);if(cn(null),hn(null),en===Ie)return;const At=at.map(ne=>ne.path),O=At.indexOf(en),W=At.indexOf(Ie);if(O<0||W<0)return;let G=pt==="before"?W:W+1;O<G&&(G-=1);const M=jd(At,O,G);F(M)},[F,en,Lt,at]),Je=N.useCallback(()=>{cn(null),hn(null)},[]),tt=N.useCallback((Ie,ot)=>pt=>{if(J){pt.dataTransfer.effectAllowed="move";try{pt.dataTransfer.setData("text/plain",ot)}catch{}pt.stopPropagation(),Ct({repoPath:Ie,sessionId:ot})}},[J]),Pt=N.useCallback((Ie,ot)=>pt=>{if(!J||sn===null||sn.repoPath!==Ie)return;pt.preventDefault(),pt.stopPropagation(),pt.dataTransfer.dropEffect="move";const At=Lt(pt);$t(O=>O&&O.sessionId===ot&&O.position===At&&O.repoPath===Ie?O:{repoPath:Ie,sessionId:ot,position:At})},[J,sn,Lt]),Vt=N.useCallback(Ie=>()=>{$t(ot=>ot&&ot.sessionId===Ie?null:ot)},[]),Wt=N.useCallback((Ie,ot)=>pt=>{if(!J||sn===null||sn.repoPath!==Ie)return;pt.preventDefault(),pt.stopPropagation();const At=Lt(pt),O=sn.sessionId;if(Ct(null),$t(null),O===ot)return;const W=at.find(ve=>ve.path===Ie);if(!W)return;const G=gS(W.activeSessions,ve=>ve.sessionId),M=G.indexOf(O),ne=G.indexOf(ot);if(M<0||ne<0)return;let te=At==="before"?ne:ne+1;M<te&&(te-=1);const re=jd(G,M,te);J(Ie,re)},[J,sn,Lt,at]),Zt=N.useCallback(()=>{Ct(null),$t(null)},[]),Dn=N.useCallback(Ie=>ot=>{if(!F||o)return!1;const pt=B.matchEvent(ot,"global"),At=pt==="sidebar.reorder.up"?-1:pt==="sidebar.reorder.down"?1:0;if(At===0)return!1;const O=at.map(ne=>ne.path),W=O.indexOf(Ie);if(W<0)return!1;const G=W+At;if(G<0||G>=O.length)return!0;const M=jd(O,W,G);return F(M),!0},[F,at,o,B]),wn=N.useCallback((Ie,ot)=>pt=>{if(!J||o)return!1;const At=B.matchEvent(pt,"global"),O=At==="sidebar.reorder.up"?-1:At==="sidebar.reorder.down"?1:0;if(O===0)return!1;const W=at.find(re=>re.path===Ie);if(!W)return!1;const G=gS(W.activeSessions,re=>re.sessionId),M=G.indexOf(ot);if(M<0)return!1;const ne=M+O;if(ne<0||ne>=G.length)return!0;const te=jd(G,M,ne);return J(Ie,te),!0},[J,at,o,B]),Kn=N.useRef(!1),je=N.useRef(0),mt=N.useRef(i),xt=N.useCallback(Ie=>{Ie.preventDefault(),Kn.current=!0,je.current=Ie.clientX,mt.current=i;const ot=At=>{if(!Kn.current)return;const O=At.clientX-je.current,W=Math.min(480,Math.max(160,mt.current+O));D?.(W)},pt=()=>{Kn.current=!1,document.removeEventListener("mousemove",ot),document.removeEventListener("mouseup",pt)};document.addEventListener("mousemove",ot),document.addEventListener("mouseup",pt)},[i,D]),Mt=N.useCallback(()=>P.current?Array.from(P.current.querySelectorAll('[role="treeitem"]')).filter(Ie=>{const ot=Ie.closest('[role="group"]');if(!ot)return!0;const pt=ot.closest('[role="treeitem"]');return!pt||pt.getAttribute("aria-expanded")!=="false"}):[],[]),un=N.useCallback((Ie,ot)=>{if(!(Ie.key==="ContextMenu"||Ie.key==="F10"&&Ie.shiftKey))return;Ie.preventDefault(),Ie.stopPropagation();const pt=Ie.currentTarget,At=pt.getBoundingClientRect(),O=At.right-10,W=At.top+At.height/2,G={clientX:O,clientY:W,currentTarget:pt,target:pt,preventDefault:()=>Ie.preventDefault(),stopPropagation:()=>Ie.stopPropagation(),nativeEvent:Ie.nativeEvent};y(ot,G)},[y]),_n=N.useCallback(Ie=>{const ot=Mt();if(ot.length===0)return;const pt=document.activeElement,At=ot.indexOf(pt);if(!(At<0))switch(Ie.key){case"ArrowDown":{Ie.preventDefault();const O=Math.min(At+1,ot.length-1);ot[O].focus(),$(O);break}case"ArrowUp":{Ie.preventDefault();const O=Math.max(At-1,0);ot[O].focus(),$(O);break}case"ArrowRight":{Ie.preventDefault();const O=ot[At];if(O.getAttribute("aria-expanded")==="false"){const W=O.querySelector('[data-testid^="repo-header-"]')?.getAttribute("data-testid")?.replace("repo-header-","");W&&de(G=>({...G,[W]:!1}))}break}case"ArrowLeft":{Ie.preventDefault();const O=ot[At];if(O.getAttribute("aria-expanded")==="true"){const W=O.querySelector('[data-testid^="repo-header-"]')?.getAttribute("data-testid")?.replace("repo-header-","");W&&de(G=>({...G,[W]:!0}))}break}case"Enter":case" ":{Ie.preventDefault(),pt.click();break}case"Home":{Ie.preventDefault(),ot[0].focus(),$(0);break}case"End":{Ie.preventDefault(),ot[ot.length-1].focus(),$(ot.length-1);break}}},[Mt,de]),zn=N.useCallback(()=>{const Ie=[];for(const ot of at)if(Ie.push(`repo:${ot.path}`),!(o?!1:X[ot.path]??!1)){for(const At of ot.activeSessions)Ie.push(`session:${At.sessionId}`);for(const At of ot.resumableSessions)Ie.push(`resumable:${At.conversationId}`)}return Ie},[at,X,o])(),ss=d==="connected"?"Running":d==="reconnecting"?"Reconnecting":"Stopped";return r.jsxs("aside",{className:`sidebar${n?"":" collapsed"}`,style:n?{width:i}:void 0,"data-testid":"sidebar",children:[r.jsx("button",{className:"sidebar-toggle","data-testid":"sidebar-toggle",onClick:m,"aria-label":n?"Collapse sidebar":"Expand sidebar",type:"button",children:n?"◀":"▶"}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"sidebar-filter",children:r.jsx("input",{type:"text",placeholder:"Filter...",value:o,onChange:Ie=>S(Ie.target.value),className:"sidebar-filter-input"})}),j&&T&&r.jsx(v$,{searchResults:b,searchLoading:_,searchQuery:k,searchConversations:j,clearSearchResults:T,onResumeSession:(Ie,ot)=>E(Ie,ot)}),r.jsxs("div",{className:"sidebar-projects-header","data-testid":"sidebar-projects-header",children:[r.jsx("span",{className:"sidebar-projects-title",children:"Projects"}),r.jsx("span",{className:`sidebar-status-dot ${d}`,"data-activity":d==="connected"?h:void 0,"data-testid":"sidebar-projects-status-dot","aria-hidden":"true",title:d==="connected"?"Server connected":d==="reconnecting"?"Reconnecting to server...":"Server disconnected"}),r.jsx("span",{className:"sidebar-projects-status-label",children:ss})]}),r.jsx("div",{className:"sidebar-tree",role:"tree","aria-label":"Repository sessions",ref:P,onKeyDown:_n,children:at.map(Ie=>{const ot=o?!1:X[Ie.path]??!1,pt=Bt?.path===Ie.path?Bt.position:null,At=`sidebar-repo${en===Ie.path?" dragging":""}${pt?` drop-${pt}`:""}`;return r.jsxs("div",{className:At,role:"treeitem","aria-expanded":!ot,draggable:!!F&&!o,"data-testid":`sidebar-repo-${Ie.path}`,"data-drop-position":pt??void 0,tabIndex:zn.indexOf(`repo:${Ie.path}`)===fe?0:-1,"aria-keyshortcuts":F&&!o?me:void 0,onContextMenu:O=>{O.preventDefault(),y({type:"repo",path:Ie.path},O)},onKeyDown:O=>{if(Dn(Ie.path)(O)){O.preventDefault(),O.stopPropagation();return}un(O,{type:"repo",path:Ie.path})},onDragStart:Ht(Ie.path),onDragOver:zt(Ie.path),onDragLeave:rn(Ie.path),onDrop:ze(Ie.path),onDragEnd:Je,children:[r.jsxs("div",{className:`sidebar-repo-header${Ie.exists?"":" missing"}`,"data-testid":`repo-header-${Ie.path}`,onClick:()=>Tt(Ie.path),children:[r.jsx("span",{className:"sidebar-chevron",children:ot?"▶":"▼"}),r.jsx("span",{className:"sidebar-repo-name",children:Ie.name}),Ie.source==="manual"&&r.jsx("span",{className:"sidebar-repo-badge",children:"pinned"}),r.jsx("button",{className:"sidebar-repo-new-session","data-testid":`sidebar-new-session-${Ie.path}`,onClick:O=>{O.stopPropagation(),x(Ie.path)},"aria-label":`New session in ${Ie.name}`,type:"button",children:"+"})]}),!ot&&r.jsxs("div",{className:"sidebar-repo-children",role:"group",children:[Ie.activeSessions.map(O=>{const W=O.status??(O.isBusy?"working":"idle"),G=W==="working"?"Session working — response, tool, or agent active":W==="stale"?"Session stale — idle for 1 hour or more":"Session idle — ready for input",M=sn?.sessionId===O.sessionId,ne=Ut?.sessionId===O.sessionId?Ut.position:null,te=`sidebar-session-item${t===O.sessionId?" active":""}${M?" dragging":""}${ne?` drop-${ne}`:""}`;return r.jsxs("div",{role:"treeitem","aria-selected":t===O.sessionId,tabIndex:zn.indexOf(`session:${O.sessionId}`)===fe?0:-1,className:te,"data-testid":`session-item-${O.sessionId}`,draggable:!!J&&!o,"data-drop-position":ne??void 0,"aria-keyshortcuts":J&&!o?me:void 0,onClick:()=>w(O.sessionId),onContextMenu:re=>{re.preventDefault(),re.stopPropagation(),y({type:"session",sessionId:O.sessionId},re)},onKeyDown:re=>{if(wn(Ie.path,O.sessionId)(re)){re.preventDefault(),re.stopPropagation();return}un(re,{type:"session",sessionId:O.sessionId})},onDragStart:tt(Ie.path,O.sessionId),onDragOver:Pt(Ie.path,O.sessionId),onDragLeave:Vt(O.sessionId),onDrop:Wt(Ie.path,O.sessionId),onDragEnd:Zt,children:[r.jsx("span",{className:`sidebar-session-dot status-${W}`,title:G}),r.jsx("span",{className:"sidebar-session-name",children:O.name}),O.worktree&&r.jsx("span",{className:"sidebar-worktree-badge",title:"Isolated git worktree",children:"W"}),O.provider&&O.provider!==yf&&r.jsx("span",{className:"sidebar-provider-badge",title:O.provider,children:O.provider.replace(/^claude-/,"").toUpperCase()}),O.stdinForwardingDisabled&&r.jsx("span",{className:"sidebar-stdin-disabled-badge","data-testid":`sidebar-stdin-disabled-${O.sessionId}`,role:"img",title:"Stdin forwarding lost — restart this session","aria-label":"Stdin forwarding disabled",children:"!"}),O.cumulativeUsage&&O.cumulativeUsage.costUsd>0&&r.jsx("span",{className:"sidebar-cost-badge","data-testid":`sidebar-cost-badge-${O.sessionId}`,title:oN(O.cumulativeUsage),"aria-label":`Session cost ${gr(O.cumulativeUsage.costUsd)}`,children:gr(O.cumulativeUsage.costUsd)})]},O.sessionId)}),Ie.resumableSessions.map(O=>r.jsxs("div",{role:"treeitem","aria-selected":!1,tabIndex:zn.indexOf(`resumable:${O.conversationId}`)===fe?0:-1,className:"sidebar-resumable-item","data-testid":`resumable-item-${O.conversationId}`,draggable:!1,onDragStart:W=>W.stopPropagation(),onClick:()=>E(O.conversationId),onContextMenu:W=>{W.preventDefault(),W.stopPropagation(),y({type:"resumable",conversationId:O.conversationId},W)},onKeyDown:W=>un(W,{type:"resumable",conversationId:O.conversationId}),children:[r.jsx("span",{className:"sidebar-resumable-dot",title:"Resumable conversation"}),r.jsx("span",{className:"sidebar-session-name",children:O.preview||"Untitled conversation"})]},O.conversationId))]})]},Ie.path)})}),r.jsx(O$,{views:Nt,launchers:kt,selectedViewId:se,onSelectView:Ve,collapsed:ge,onCollapsedChange:St,height:be,onHeightChange:Ge}),r.jsx(A$,{}),r.jsxs("div",{className:"sidebar-footer","data-testid":"sidebar-footer",children:[r.jsx("span",{className:`sidebar-status-dot ${d}`,"data-activity":d==="connected"?h:void 0,title:d==="connected"?"Server connected":d==="reconnecting"?"Reconnecting to server...":"Server disconnected"}),r.jsx("span",{className:"sidebar-status-label",children:ss}),l&&r.jsx("span",{className:"sidebar-tunnel",title:l,children:s8(l)}),r.jsx(I$,{clients:u,primaryClientId:f,connected:d==="connected",sessionRole:v??null,onTakeOver:g})]})]}),n&&r.jsx("div",{className:"sidebar-resize-handle",onMouseDown:xt})]})}function r8(e){const{target:t,sessions:n,conversationHistory:i,isTauri:o,createSession:d,resumeConversation:h,revealInFinder:l,onRevealError:u,copyToClipboard:f,openCreateSessionAt:v,copySessionTranscript:g,summarizeAndCreateSession:S,confirmCloseSession:w}=e,E=x=>{l(x).catch(m=>{u(`Failed to reveal in Finder: ${m instanceof Error?m.message:String(m)}`)})};if(t.type==="session"&&t.sessionId){const x=n.find(m=>m.sessionId===t.sessionId);return x?[{id:"duplicate",label:"Duplicate Session",onClick:()=>{d({name:x.name,cwd:x.cwd||void 0,provider:x.provider,model:x.model||void 0,permissionMode:x.permissionMode||void 0,worktree:x.worktree})}},{id:"copy-transcript",label:"Copy transcript",onClick:()=>g(x.sessionId)},{id:"summarize",label:"Summarize & start new session",onClick:()=>S(x.sessionId)},{id:"reveal",label:"Open in Finder",onClick:o&&x.cwd?()=>E(x.cwd):void 0},{id:"copy-path",label:"Copy path",onClick:x.cwd?()=>f(x.cwd):void 0},{id:"close",label:"Close Session",destructive:!0,separatorAbove:!0,onClick:()=>w(x.sessionId)}]:[]}if(t.type==="repo"&&t.path){const x=t.path,m=n.filter(_=>_.cwd===x).sort((_,k)=>(k.lastActivityAt??0)-(_.lastActivityAt??0)),y=m.length===1?m[0]:null,b=y?[{id:"summarize",label:"Summarize & start new session",onClick:()=>S(y.sessionId)}]:m.map((_,k)=>({id:`summarize-${_.sessionId}`,label:`Summarize "${_.name}" & start new session`,separatorAbove:k===0,onClick:()=>S(_.sessionId)}));return[{id:"new-session",label:"New Session Here",onClick:()=>v(x)},...b,{id:"reveal",label:"Open in Finder",separatorAbove:b.length>0,onClick:o?()=>E(x):void 0},{id:"copy-path",label:"Copy path",onClick:()=>f(x)}]}if(t.type==="resumable"&&t.conversationId){const x=t.conversationId,y=i.find(b=>b.conversationId===x)?.cwd??void 0;return[{id:"resume",label:"Resume Conversation",onClick:()=>h(x,y)},{id:"copy-id",label:"Copy Conversation ID",onClick:()=>f(x)},{id:"reveal",label:"Open in Finder",onClick:o&&y?()=>E(y):void 0}]}return[]}const o1="chroxy-mru-commands",l1=10;function a8(){try{const e=localStorage.getItem(o1);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string").slice(0,l1):[]}catch{return[]}}function o8(e){try{localStorage.setItem(o1,JSON.stringify(e))}catch{}}const c1=gw((e,t)=>({mruList:a8(),recordCommand:n=>{const i=t().mruList.filter(d=>d!==n);i.unshift(n);const o=i.slice(0,l1);o8(o),e({mruList:o})}}));function l8(){return[...c1.getState().mruList]}function c8(e){c1.getState().recordCommand(e)}function u8(e=!0){const t=V(o=>o.setViewMode),n=V(o=>o.sendInterrupt),i=V(o=>o.createSession);return N.useMemo(()=>{const o=[{id:"new-session",name:"New Session",category:"Session",shortcut:"Cmd+N",action:()=>i({name:"New Session"})},{id:"interrupt",name:"Interrupt",category:"Session",shortcut:"Cmd+.",action:()=>n()},{id:"toggle-view",name:"Toggle View",category:"View",shortcut:"Cmd+Shift+D",action:()=>{const d=V.getState().viewMode;t(d==="chat"?"terminal":"chat")}},{id:"toggle-sidebar",name:"Toggle Sidebar",category:"View",shortcut:"Cmd+B",action:()=>{}},{id:"switch-chat",name:"Switch to Chat",category:"View",action:()=>t("chat")},{id:"switch-terminal",name:"Switch to Terminal",category:"View",action:()=>t("terminal")},{id:"switch-files",name:"Switch to Files",category:"View",action:()=>t("files")}];return e?o:o.filter(d=>d.id!=="switch-terminal"&&d.id!=="toggle-view")},[t,n,i,e])}function d8(){return r.jsxs("div",{className:"thinking-dots","data-testid":"thinking-dots",children:[r.jsx("span",{className:"thinking-dot"}),r.jsx("span",{className:"thinking-dot"}),r.jsx("span",{className:"thinking-dot"})]})}const f8="Claude is working…";function h8({label:e}){return r.jsxs("div",{className:"working-indicator","data-testid":"working-indicator",role:"status","aria-live":"polite",children:[r.jsx(d8,{}),r.jsx("span",{className:"working-label","data-testid":"working-label",children:e&&e.length>0?e:f8})]})}const{entries:u1,setPrototypeOf:yS,isFrozen:p8,getPrototypeOf:m8,getOwnPropertyDescriptor:g8}=Object;let{freeze:Is,seal:xi,create:Kd}=Object,{apply:jm,construct:Am}=typeof Reflect<"u"&&Reflect;Is||(Is=function(t){return t});xi||(xi=function(t){return t});jm||(jm=function(t,n){for(var i=arguments.length,o=new Array(i>2?i-2:0),d=2;d<i;d++)o[d-2]=arguments[d];return t.apply(n,o)});Am||(Am=function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];return new t(...i)});const Ad=Ms(Array.prototype.forEach),v8=Ms(Array.prototype.lastIndexOf),bS=Ms(Array.prototype.pop),_c=Ms(Array.prototype.push),y8=Ms(Array.prototype.splice),Wd=Ms(String.prototype.toLowerCase),Hp=Ms(String.prototype.toString),Fp=Ms(String.prototype.match),Sc=Ms(String.prototype.replace),b8=Ms(String.prototype.indexOf),_8=Ms(String.prototype.trim),oi=Ms(Object.prototype.hasOwnProperty),As=Ms(RegExp.prototype.test),xc=S8(TypeError);function Ms(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];return jm(e,t,i)}}function S8(e){return function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Am(e,n)}}function dn(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Wd;yS&&yS(e,null);let i=t.length;for(;i--;){let o=t[i];if(typeof o=="string"){const d=n(o);d!==o&&(p8(t)||(t[i]=d),o=d)}e[o]=!0}return e}function x8(e){for(let t=0;t<e.length;t++)oi(e,t)||(e[t]=null);return e}function Fi(e){const t=Kd(null);for(const[n,i]of u1(e))oi(e,n)&&(Array.isArray(i)?t[n]=x8(i):i&&typeof i=="object"&&i.constructor===Object?t[n]=Fi(i):t[n]=i);return t}function wc(e,t){for(;e!==null;){const i=g8(e,t);if(i){if(i.get)return Ms(i.get);if(typeof i.value=="function")return Ms(i.value)}e=m8(e)}function n(){return null}return n}const _S=Is(["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"]),Kp=Is(["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"]),Wp=Is(["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"]),w8=Is(["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"]),Gp=Is(["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"]),k8=Is(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),SS=Is(["#text"]),xS=Is(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","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","slot"]),Vp=Is(["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","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","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-rendering","textlength","type","u1","u2","unicode","values","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"]),wS=Is(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","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"]),Rd=Is(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),C8=xi(/\{\{[\w\W]*|[\w\W]*\}\}/gm),E8=xi(/<%[\w\W]*|[\w\W]*%>/gm),N8=xi(/\$\{[\w\W]*/gm),j8=xi(/^data-[\-\w.\u00B7-\uFFFF]+$/),A8=xi(/^aria-[\-\w]+$/),d1=xi(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),R8=xi(/^(?:\w+script|data):/i),T8=xi(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),f1=xi(/^html$/i),I8=xi(/^[a-z][.\w]*(-[.\w]+)+$/i);var kS=Object.freeze({__proto__:null,ARIA_ATTR:A8,ATTR_WHITESPACE:T8,CUSTOM_ELEMENT:I8,DATA_ATTR:j8,DOCTYPE_NAME:f1,ERB_EXPR:E8,IS_ALLOWED_URI:d1,IS_SCRIPT_OR_DATA:R8,MUSTACHE_EXPR:C8,TMPLIT_EXPR:N8});const kc={element:1,text:3,progressingInstruction:7,comment:8,document:9},M8=function(){return typeof window>"u"?null:window},D8=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let i=null;const o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(i=n.getAttribute(o));const d="dompurify"+(i?"#"+i:"");try{return t.createPolicy(d,{createHTML(h){return h},createScriptURL(h){return h}})}catch{return console.warn("TrustedTypes policy "+d+" could not be created."),null}},CS=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function h1(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:M8();const t=Oe=>h1(Oe);if(t.version="3.3.3",t.removed=[],!e||!e.document||e.document.nodeType!==kc.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const i=n,o=i.currentScript,{DocumentFragment:d,HTMLTemplateElement:h,Node:l,Element:u,NodeFilter:f,NamedNodeMap:v=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:g,DOMParser:S,trustedTypes:w}=e,E=u.prototype,x=wc(E,"cloneNode"),m=wc(E,"remove"),y=wc(E,"nextSibling"),b=wc(E,"childNodes"),_=wc(E,"parentNode");if(typeof h=="function"){const Oe=n.createElement("template");Oe.content&&Oe.content.ownerDocument&&(n=Oe.content.ownerDocument)}let k,j="";const{implementation:T,createNodeIterator:D,createDocumentFragment:I,getElementsByTagName:L}=n,{importNode:q}=i;let H=CS();t.isSupported=typeof u1=="function"&&typeof _=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Q,ERB_EXPR:F,TMPLIT_EXPR:J,DATA_ATTR:ie,ARIA_ATTR:X,IS_SCRIPT_OR_DATA:de,ATTR_WHITESPACE:fe,CUSTOM_ELEMENT:$}=kS;let{IS_ALLOWED_URI:P}=kS,B=null;const K=dn({},[..._S,...Kp,...Wp,...Gp,...SS]);let le=null;const me=dn({},[...xS,...Vp,...wS,...Rd]);let be=Object.seal(Kd(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}})),Ee=null,se=null;const Z=Object.seal(Kd(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ge=!0,De=!0,Ge=!1,Ve=!0,St=!1,Nt=!0,kt=!1,Tt=!1,at=!1,en=!1,cn=!1,Bt=!1,hn=!0,sn=!1;const Ct="user-content-";let Ut=!0,$t=!1,Lt={},Ht=null;const zt=dn({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let rn=null;const ze=dn({},["audio","video","img","source","image","track"]);let Je=null;const tt=dn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Pt="http://www.w3.org/1998/Math/MathML",Vt="http://www.w3.org/2000/svg",Wt="http://www.w3.org/1999/xhtml";let Zt=Wt,Dn=!1,wn=null;const Kn=dn({},[Pt,Vt,Wt],Hp);let je=dn({},["mi","mo","mn","ms","mtext"]),mt=dn({},["annotation-xml"]);const xt=dn({},["title","style","font","a","script"]);let Mt=null;const un=["application/xhtml+xml","text/html"],_n="text/html";let tn=null,zn=null;const ss=n.createElement("form"),Ie=function(ce){return ce instanceof RegExp||ce instanceof Function},ot=function(){let ce=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(zn&&zn===ce)){if((!ce||typeof ce!="object")&&(ce={}),ce=Fi(ce),Mt=un.indexOf(ce.PARSER_MEDIA_TYPE)===-1?_n:ce.PARSER_MEDIA_TYPE,tn=Mt==="application/xhtml+xml"?Hp:Wd,B=oi(ce,"ALLOWED_TAGS")?dn({},ce.ALLOWED_TAGS,tn):K,le=oi(ce,"ALLOWED_ATTR")?dn({},ce.ALLOWED_ATTR,tn):me,wn=oi(ce,"ALLOWED_NAMESPACES")?dn({},ce.ALLOWED_NAMESPACES,Hp):Kn,Je=oi(ce,"ADD_URI_SAFE_ATTR")?dn(Fi(tt),ce.ADD_URI_SAFE_ATTR,tn):tt,rn=oi(ce,"ADD_DATA_URI_TAGS")?dn(Fi(ze),ce.ADD_DATA_URI_TAGS,tn):ze,Ht=oi(ce,"FORBID_CONTENTS")?dn({},ce.FORBID_CONTENTS,tn):zt,Ee=oi(ce,"FORBID_TAGS")?dn({},ce.FORBID_TAGS,tn):Fi({}),se=oi(ce,"FORBID_ATTR")?dn({},ce.FORBID_ATTR,tn):Fi({}),Lt=oi(ce,"USE_PROFILES")?ce.USE_PROFILES:!1,ge=ce.ALLOW_ARIA_ATTR!==!1,De=ce.ALLOW_DATA_ATTR!==!1,Ge=ce.ALLOW_UNKNOWN_PROTOCOLS||!1,Ve=ce.ALLOW_SELF_CLOSE_IN_ATTR!==!1,St=ce.SAFE_FOR_TEMPLATES||!1,Nt=ce.SAFE_FOR_XML!==!1,kt=ce.WHOLE_DOCUMENT||!1,en=ce.RETURN_DOM||!1,cn=ce.RETURN_DOM_FRAGMENT||!1,Bt=ce.RETURN_TRUSTED_TYPE||!1,at=ce.FORCE_BODY||!1,hn=ce.SANITIZE_DOM!==!1,sn=ce.SANITIZE_NAMED_PROPS||!1,Ut=ce.KEEP_CONTENT!==!1,$t=ce.IN_PLACE||!1,P=ce.ALLOWED_URI_REGEXP||d1,Zt=ce.NAMESPACE||Wt,je=ce.MATHML_TEXT_INTEGRATION_POINTS||je,mt=ce.HTML_INTEGRATION_POINTS||mt,be=ce.CUSTOM_ELEMENT_HANDLING||{},ce.CUSTOM_ELEMENT_HANDLING&&Ie(ce.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(be.tagNameCheck=ce.CUSTOM_ELEMENT_HANDLING.tagNameCheck),ce.CUSTOM_ELEMENT_HANDLING&&Ie(ce.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(be.attributeNameCheck=ce.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),ce.CUSTOM_ELEMENT_HANDLING&&typeof ce.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(be.allowCustomizedBuiltInElements=ce.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),St&&(De=!1),cn&&(en=!0),Lt&&(B=dn({},SS),le=Kd(null),Lt.html===!0&&(dn(B,_S),dn(le,xS)),Lt.svg===!0&&(dn(B,Kp),dn(le,Vp),dn(le,Rd)),Lt.svgFilters===!0&&(dn(B,Wp),dn(le,Vp),dn(le,Rd)),Lt.mathMl===!0&&(dn(B,Gp),dn(le,wS),dn(le,Rd))),oi(ce,"ADD_TAGS")||(Z.tagCheck=null),oi(ce,"ADD_ATTR")||(Z.attributeCheck=null),ce.ADD_TAGS&&(typeof ce.ADD_TAGS=="function"?Z.tagCheck=ce.ADD_TAGS:(B===K&&(B=Fi(B)),dn(B,ce.ADD_TAGS,tn))),ce.ADD_ATTR&&(typeof ce.ADD_ATTR=="function"?Z.attributeCheck=ce.ADD_ATTR:(le===me&&(le=Fi(le)),dn(le,ce.ADD_ATTR,tn))),ce.ADD_URI_SAFE_ATTR&&dn(Je,ce.ADD_URI_SAFE_ATTR,tn),ce.FORBID_CONTENTS&&(Ht===zt&&(Ht=Fi(Ht)),dn(Ht,ce.FORBID_CONTENTS,tn)),ce.ADD_FORBID_CONTENTS&&(Ht===zt&&(Ht=Fi(Ht)),dn(Ht,ce.ADD_FORBID_CONTENTS,tn)),Ut&&(B["#text"]=!0),kt&&dn(B,["html","head","body"]),B.table&&(dn(B,["tbody"]),delete Ee.tbody),ce.TRUSTED_TYPES_POLICY){if(typeof ce.TRUSTED_TYPES_POLICY.createHTML!="function")throw xc('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof ce.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw xc('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');k=ce.TRUSTED_TYPES_POLICY,j=k.createHTML("")}else k===void 0&&(k=D8(w,o)),k!==null&&typeof j=="string"&&(j=k.createHTML(""));Is&&Is(ce),zn=ce}},pt=dn({},[...Kp,...Wp,...w8]),At=dn({},[...Gp,...k8]),O=function(ce){let ke=_(ce);(!ke||!ke.tagName)&&(ke={namespaceURI:Zt,tagName:"template"});const Ue=Wd(ce.tagName),rt=Wd(ke.tagName);return wn[ce.namespaceURI]?ce.namespaceURI===Vt?ke.namespaceURI===Wt?Ue==="svg":ke.namespaceURI===Pt?Ue==="svg"&&(rt==="annotation-xml"||je[rt]):!!pt[Ue]:ce.namespaceURI===Pt?ke.namespaceURI===Wt?Ue==="math":ke.namespaceURI===Vt?Ue==="math"&&mt[rt]:!!At[Ue]:ce.namespaceURI===Wt?ke.namespaceURI===Vt&&!mt[rt]||ke.namespaceURI===Pt&&!je[rt]?!1:!At[Ue]&&(xt[Ue]||!pt[Ue]):!!(Mt==="application/xhtml+xml"&&wn[ce.namespaceURI]):!1},W=function(ce){_c(t.removed,{element:ce});try{_(ce).removeChild(ce)}catch{m(ce)}},G=function(ce,ke){try{_c(t.removed,{attribute:ke.getAttributeNode(ce),from:ke})}catch{_c(t.removed,{attribute:null,from:ke})}if(ke.removeAttribute(ce),ce==="is")if(en||cn)try{W(ke)}catch{}else try{ke.setAttribute(ce,"")}catch{}},M=function(ce){let ke=null,Ue=null;if(at)ce="<remove></remove>"+ce;else{const et=Fp(ce,/^[\r\n\t ]+/);Ue=et&&et[0]}Mt==="application/xhtml+xml"&&Zt===Wt&&(ce='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+ce+"</body></html>");const rt=k?k.createHTML(ce):ce;if(Zt===Wt)try{ke=new S().parseFromString(rt,Mt)}catch{}if(!ke||!ke.documentElement){ke=T.createDocument(Zt,"template",null);try{ke.documentElement.innerHTML=Dn?j:rt}catch{}}const ct=ke.body||ke.documentElement;return ce&&Ue&&ct.insertBefore(n.createTextNode(Ue),ct.childNodes[0]||null),Zt===Wt?L.call(ke,kt?"html":"body")[0]:kt?ke.documentElement:ct},ne=function(ce){return D.call(ce.ownerDocument||ce,ce,f.SHOW_ELEMENT|f.SHOW_COMMENT|f.SHOW_TEXT|f.SHOW_PROCESSING_INSTRUCTION|f.SHOW_CDATA_SECTION,null)},te=function(ce){return ce instanceof g&&(typeof ce.nodeName!="string"||typeof ce.textContent!="string"||typeof ce.removeChild!="function"||!(ce.attributes instanceof v)||typeof ce.removeAttribute!="function"||typeof ce.setAttribute!="function"||typeof ce.namespaceURI!="string"||typeof ce.insertBefore!="function"||typeof ce.hasChildNodes!="function")},re=function(ce){return typeof l=="function"&&ce instanceof l};function ve(Oe,ce,ke){Ad(Oe,Ue=>{Ue.call(t,ce,ke,zn)})}const Me=function(ce){let ke=null;if(ve(H.beforeSanitizeElements,ce,null),te(ce))return W(ce),!0;const Ue=tn(ce.nodeName);if(ve(H.uponSanitizeElement,ce,{tagName:Ue,allowedTags:B}),Nt&&ce.hasChildNodes()&&!re(ce.firstElementChild)&&As(/<[/\w!]/g,ce.innerHTML)&&As(/<[/\w!]/g,ce.textContent)||ce.nodeType===kc.progressingInstruction||Nt&&ce.nodeType===kc.comment&&As(/<[/\w]/g,ce.data))return W(ce),!0;if(!(Z.tagCheck instanceof Function&&Z.tagCheck(Ue))&&(!B[Ue]||Ee[Ue])){if(!Ee[Ue]&&Xe(Ue)&&(be.tagNameCheck instanceof RegExp&&As(be.tagNameCheck,Ue)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Ue)))return!1;if(Ut&&!Ht[Ue]){const rt=_(ce)||ce.parentNode,ct=b(ce)||ce.childNodes;if(ct&&rt){const et=ct.length;for(let st=et-1;st>=0;--st){const gt=x(ct[st],!0);gt.__removalCount=(ce.__removalCount||0)+1,rt.insertBefore(gt,y(ce))}}}return W(ce),!0}return ce instanceof u&&!O(ce)||(Ue==="noscript"||Ue==="noembed"||Ue==="noframes")&&As(/<\/no(script|embed|frames)/i,ce.innerHTML)?(W(ce),!0):(St&&ce.nodeType===kc.text&&(ke=ce.textContent,Ad([Q,F,J],rt=>{ke=Sc(ke,rt," ")}),ce.textContent!==ke&&(_c(t.removed,{element:ce.cloneNode()}),ce.textContent=ke)),ve(H.afterSanitizeElements,ce,null),!1)},Ze=function(ce,ke,Ue){if(se[ke]||hn&&(ke==="id"||ke==="name")&&(Ue in n||Ue in ss))return!1;if(!(De&&!se[ke]&&As(ie,ke))){if(!(ge&&As(X,ke))){if(!(Z.attributeCheck instanceof Function&&Z.attributeCheck(ke,ce))){if(!le[ke]||se[ke]){if(!(Xe(ce)&&(be.tagNameCheck instanceof RegExp&&As(be.tagNameCheck,ce)||be.tagNameCheck instanceof Function&&be.tagNameCheck(ce))&&(be.attributeNameCheck instanceof RegExp&&As(be.attributeNameCheck,ke)||be.attributeNameCheck instanceof Function&&be.attributeNameCheck(ke,ce))||ke==="is"&&be.allowCustomizedBuiltInElements&&(be.tagNameCheck instanceof RegExp&&As(be.tagNameCheck,Ue)||be.tagNameCheck instanceof Function&&be.tagNameCheck(Ue))))return!1}else if(!Je[ke]){if(!As(P,Sc(Ue,fe,""))){if(!((ke==="src"||ke==="xlink:href"||ke==="href")&&ce!=="script"&&b8(Ue,"data:")===0&&rn[ce])){if(!(Ge&&!As(de,Sc(Ue,fe,"")))){if(Ue)return!1}}}}}}}return!0},Xe=function(ce){return ce!=="annotation-xml"&&Fp(ce,$)},Dt=function(ce){ve(H.beforeSanitizeAttributes,ce,null);const{attributes:ke}=ce;if(!ke||te(ce))return;const Ue={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0};let rt=ke.length;for(;rt--;){const ct=ke[rt],{name:et,namespaceURI:st,value:gt}=ct,it=tn(et),ft=gt;let lt=et==="value"?ft:_8(ft);if(Ue.attrName=it,Ue.attrValue=lt,Ue.keepAttr=!0,Ue.forceKeepAttr=void 0,ve(H.uponSanitizeAttribute,ce,Ue),lt=Ue.attrValue,sn&&(it==="id"||it==="name")&&(G(et,ce),lt=Ct+lt),Nt&&As(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,lt)){G(et,ce);continue}if(it==="attributename"&&Fp(lt,"href")){G(et,ce);continue}if(Ue.forceKeepAttr)continue;if(!Ue.keepAttr){G(et,ce);continue}if(!Ve&&As(/\/>/i,lt)){G(et,ce);continue}St&&Ad([Q,F,J],Ne=>{lt=Sc(lt,Ne," ")});const ut=tn(ce.nodeName);if(!Ze(ut,it,lt)){G(et,ce);continue}if(k&&typeof w=="object"&&typeof w.getAttributeType=="function"&&!st)switch(w.getAttributeType(ut,it)){case"TrustedHTML":{lt=k.createHTML(lt);break}case"TrustedScriptURL":{lt=k.createScriptURL(lt);break}}if(lt!==ft)try{st?ce.setAttributeNS(st,et,lt):ce.setAttribute(et,lt),te(ce)?W(ce):bS(t.removed)}catch{G(et,ce)}}ve(H.afterSanitizeAttributes,ce,null)},nt=function Oe(ce){let ke=null;const Ue=ne(ce);for(ve(H.beforeSanitizeShadowDOM,ce,null);ke=Ue.nextNode();)ve(H.uponSanitizeShadowNode,ke,null),Me(ke),Dt(ke),ke.content instanceof d&&Oe(ke.content);ve(H.afterSanitizeShadowDOM,ce,null)};return t.sanitize=function(Oe){let ce=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ke=null,Ue=null,rt=null,ct=null;if(Dn=!Oe,Dn&&(Oe="<!-->"),typeof Oe!="string"&&!re(Oe))if(typeof Oe.toString=="function"){if(Oe=Oe.toString(),typeof Oe!="string")throw xc("dirty is not a string, aborting")}else throw xc("toString is not a function");if(!t.isSupported)return Oe;if(Tt||ot(ce),t.removed=[],typeof Oe=="string"&&($t=!1),$t){if(Oe.nodeName){const gt=tn(Oe.nodeName);if(!B[gt]||Ee[gt])throw xc("root node is forbidden and cannot be sanitized in-place")}}else if(Oe instanceof l)ke=M("<!---->"),Ue=ke.ownerDocument.importNode(Oe,!0),Ue.nodeType===kc.element&&Ue.nodeName==="BODY"||Ue.nodeName==="HTML"?ke=Ue:ke.appendChild(Ue);else{if(!en&&!St&&!kt&&Oe.indexOf("<")===-1)return k&&Bt?k.createHTML(Oe):Oe;if(ke=M(Oe),!ke)return en?null:Bt?j:""}ke&&at&&W(ke.firstChild);const et=ne($t?Oe:ke);for(;rt=et.nextNode();)Me(rt),Dt(rt),rt.content instanceof d&&nt(rt.content);if($t)return Oe;if(en){if(cn)for(ct=I.call(ke.ownerDocument);ke.firstChild;)ct.appendChild(ke.firstChild);else ct=ke;return(le.shadowroot||le.shadowrootmode)&&(ct=q.call(i,ct,!0)),ct}let st=kt?ke.outerHTML:ke.innerHTML;return kt&&B["!doctype"]&&ke.ownerDocument&&ke.ownerDocument.doctype&&ke.ownerDocument.doctype.name&&As(f1,ke.ownerDocument.doctype.name)&&(st="<!DOCTYPE "+ke.ownerDocument.doctype.name+`>
|
|
73
|
-
`+st),St&&Ad([Q,F,J],gt=>{st=Sc(st,gt," ")}),k&&Bt?k.createHTML(st):st},t.setConfig=function(){let Oe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ot(Oe),Tt=!0},t.clearConfig=function(){zn=null,Tt=!1},t.isValidAttribute=function(Oe,ce,ke){zn||ot({});const Ue=tn(Oe),rt=tn(ce);return Ze(Ue,rt,ke)},t.addHook=function(Oe,ce){typeof ce=="function"&&_c(H[Oe],ce)},t.removeHook=function(Oe,ce){if(ce!==void 0){const ke=v8(H[Oe],ce);return ke===-1?void 0:y8(H[Oe],ke,1)[0]}return bS(H[Oe])},t.removeHooks=function(Oe){H[Oe]=[]},t.removeAllHooks=function(){H=CS()},t}var _f=h1();function Yp(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function L8(e){if(!e)return"";const t=[];let n=e.replace(/```([^\n]*)?\n([\s\S]*?)```/g,(l,u,f)=>{const v="\0FB"+t.length+"\0",g=u?u.trim().split(/\s+/)[0]:"",S=g?` class="language-${g}"`:"",w=g?jE(f,g):Yp(f);return t.push(`<pre><code${S}>${w}</code></pre>`),v});n=n.replace(/`([^`\n]+)`/g,(l,u)=>{const f="\0CB"+t.length+"\0";return t.push(`<code>${Yp(u)}</code>`),f});let i=Yp(n);i=i.replace(/^### (.+)$/gm,"<h3>$1</h3>"),i=i.replace(/^## (.+)$/gm,"<h2>$1</h2>"),i=i.replace(/^# (.+)$/gm,"<h1>$1</h1>"),i=i.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(l,u,f)=>/^\s*(javascript|data|vbscript)\s*:/i.test(f)?u:`<a href="${f.replace(/"/g,""")}" target="_blank" rel="noopener">${u}</a>`);const o=[];i=i.replace(/<a [^>]*>[\s\S]*?<\/a>/g,l=>{const u="\0AN"+o.length+"\0";return o.push(l),u}),i=i.replace(/\bhttps?:\/\/(?:[^\s<&]+|&)*[^\s<&.,;:!?)\]]/g,l=>`<a href="${l.replace(/"/g,""")}" target="_blank" rel="noopener">${l}</a>`),i=i.replace(/\x00AN(\d+)\x00/g,(l,u)=>o[Number(u)]),i=i.replace(/^> (.+)$/gm,"<blockquote>$1</blockquote>"),i=i.replace(/^- (.+)$/gm,'<li class="md-ul">$1</li>'),i=i.replace(/(<li class="md-ul">.*<\/li>\n?)+/g,l=>`<ul>${l}</ul>`),i=i.replace(/^\d+\. (.+)$/gm,'<li class="md-ol">$1</li>'),i=i.replace(/(<li class="md-ol">.*<\/li>\n?)+/g,l=>`<ol>${l}</ol>`);const d=/^\|(.+)\|[ \t]*\n\|([-:|\s]+)\|[ \t]*\n((?:\|.*\|[ \t]*\n?)*)/gm;i=i.replace(d,(l,u,f,v)=>{const g=u.split("|").map(m=>m.trim()),S=f.split("|").map(m=>m.trim()).filter(m=>/^:?-+:?$/.test(m)).map(m=>m.startsWith(":")&&m.endsWith(":")?"center":m.endsWith(":")?"right":m.startsWith(":")?"left":""),w=m=>S[m]?` style="text-align:${S[m]}"`:"",E=g.map((m,y)=>`<th${w(y)}>${m}</th>`).join(""),x=v.trim().split(`
|
|
74
|
-
`).map(m=>`<tr>${m.replace(/^\s*\||\|\s*$/g,"").split("|").map(b=>b.trim()).map((b,_)=>`<td${w(_)}>${b}</td>`).join("")}</tr>`).filter(m=>m!=="<tr></tr>").join("");return`<table><thead><tr>${E}</tr></thead><tbody>${x}</tbody></table>
|
|
75
|
-
|
|
76
|
-
`});const h=/^(<(h[1-6]|pre|ul|ol|blockquote|table)|\x00FB\d+\x00$)/;return i=i.split(`
|
|
77
|
-
|
|
78
|
-
`).map(l=>{const u=l.trim();return u?h.test(u)?u:`<p>${u}</p>`:""}).filter(Boolean).join(""),i=i.replace(/\n/g,"<br>"),i=i.replace(/\x00(?:FB|CB)(\d+)\x00/g,(l,u)=>t[Number(u)]),_f.sanitize(i,{ADD_ATTR:["target","rel"]})}function O8({rowKey:e,measureRow:t,className:n,testId:i,children:o}){const d=N.useRef(null),h=N.useCallback(()=>{const l=d.current;l&&t(e,l.offsetHeight)},[e,t]);return N.useEffect(()=>{const l=d.current;if(!l||(h(),typeof ResizeObserver>"u"))return;const u=new ResizeObserver(()=>h());return u.observe(l),()=>u.disconnect()},[h]),r.jsx("div",{ref:d,className:n||void 0,"data-testid":i,"data-row-key":e,children:o})}const ES=N.memo(O8),P8={get:()=>{},set:()=>{}},gg=N.createContext(P8);function p1(e,t){const n=N.useContext(gg),i=n.get(e),o=N.useCallback(d=>n.set(e,d),[n,e]);return{initial:i??t,persist:o}}const B8=80,$8=6,z8=40;function U8({itemCount:e,scrollTop:t,viewportHeight:n,estimatedRowHeight:i=B8,overscan:o=$8,threshold:d=z8,rowGap:h=0,keyAt:l}){const u=N.useRef(new Map),[f,v]=N.useState(0),g=e>d,S=N.useCallback((x,m)=>{if(!g)return;const y=u.current,b=y.get(x);b!==void 0&&Math.abs(b-m)<1||(y.set(x,m),v(_=>_+1))},[g]),w=N.useCallback(x=>(u.current.get(l(x))??i)+h,[l,i,h]),E=N.useCallback(x=>{const m=Math.max(0,Math.min(x,e));let y=0;for(let b=0;b<m;b++)y+=w(b);return y},[w,e]);return N.useMemo(()=>{if(!g)return{startIndex:0,endIndex:e,topSpacer:0,bottomSpacer:0,virtualized:!1,measureRow:S,firstVisibleIndex:0,firstVisibleOffset:0,offsetAt:E};const x=Math.max(0,t),m=x+Math.max(0,n);let y=0,b=0,_=0;for(;_<e;_++){const q=w(_);if(y+q>x){b=_;break}y+=q}_===e&&(b=e-1);const k=y;let j=b;for(let q=b;q<e&&!(y>=m);q++)j=q,y+=w(q);const T=Math.max(0,b-o),D=Math.min(e,j+1+o);let I=0;for(let q=0;q<T;q++)I+=w(q);T>0&&(I-=h);let L=0;for(let q=D;q<e;q++)L+=w(q);return D<e&&(L-=h),{startIndex:T,endIndex:D,topSpacer:I,bottomSpacer:L,virtualized:!0,measureRow:S,firstVisibleIndex:b,firstVisibleOffset:k,offsetAt:E}},[e,t,n,g,o,h,w,E,S,f])}const vg={width:24,height:24,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:13,lineHeight:1};function q8(){return r.jsx("span",{className:"sender-icon sender-icon-assistant",style:{...vg,background:"var(--accent-blue-subtle, rgba(96, 165, 250, 0.15))",color:"var(--accent-blue, #60a5fa)"},"aria-hidden":"true",children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:r.jsx("path",{d:"M12 2L14.09 8.26L20 9.27L15.55 13.97L16.91 20L12 16.9L7.09 20L8.45 13.97L4 9.27L9.91 8.26L12 2Z"})})})}function H8(){return r.jsx("span",{className:"sender-icon sender-icon-user",style:{...vg,background:"var(--accent-green-subtle, rgba(74, 222, 128, 0.15))",color:"var(--accent-green, #4ade80)"},"aria-hidden":"true",children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:r.jsx("path",{d:"M12 12c2.7 0 4.8-2.1 4.8-4.8S14.7 2.4 12 2.4 7.2 4.5 7.2 7.2 9.3 12 12 12zm0 2.4c-3.2 0-9.6 1.6-9.6 4.8v2.4h19.2v-2.4c0-3.2-6.4-4.8-9.6-4.8z"})})})}function F8(){return r.jsx("span",{className:"sender-icon sender-icon-system",style:{...vg,background:"var(--bg-secondary, rgba(148, 163, 184, 0.15))",color:"var(--text-dim, #94a3b8)"},"aria-hidden":"true",children:r.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"currentColor",children:r.jsx("path",{d:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 00.12-.61l-1.92-3.32a.49.49 0 00-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.48.48 0 00-.48-.41h-3.84a.48.48 0 00-.48.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96a.49.49 0 00-.59.22L2.74 8.87a.48.48 0 00.12.61l2.03 1.58c-.05.3-.07.63-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 00-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.26.41.48.41h3.84c.24 0 .44-.17.48-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6A3.6 3.6 0 1112 8.4a3.6 3.6 0 010 7.2z"})})})}function m1(e){switch(e){case"response":return r.jsx(q8,{});case"user_input":return r.jsx(H8,{});case"system":return r.jsx(F8,{});default:return null}}const K8={response:"assistant",user_input:"user",system:"system",error:"error",thinking:"thinking",tool_use:"tool"},W8=100,Rm=12;function G8(e){if(!e||typeof getComputedStyle!="function")return Rm;const t=getComputedStyle(e).rowGap,n=parseFloat(t);return Number.isFinite(n)?n:Rm}function V8(e){const t=new Date(e);let n=t.getHours();const i=t.getMinutes().toString().padStart(2,"0"),o=n>=12?"PM":"AM";return n=n%12||12,`${n}:${i} ${o}`}const Y8=typeof import.meta<"u"&&!1;function Z8(e,t){return e==="user_input"?"msg-row msg-row-user":e==="system"?"msg-row msg-row-system":t?"msg-row":""}function X8({content:e,streaming:t}){const[n,i]=N.useState(!1);return r.jsxs("div",{className:"thinking-body",children:[r.jsxs("button",{type:"button",className:"thinking-toggle","data-testid":"thinking-toggle","aria-expanded":n,onClick:o=>{o.stopPropagation(),i(d=>!d)},children:[n?"▾":"▸"," ",t?"Thinking…":"Thought"]}),n&&r.jsx("div",{className:"thinking-full",children:e})]})}const Q8=N.memo(function({id:t,type:n,content:i,timestamp:o,isStreaming:d,queued:h,onCancelQueued:l,queuePosition:u}){Y8&&fO(`ChatMessageRow:${t}`);const f=m1(n),v=n==="response"||n==="tool_use"?r.jsx("div",{dangerouslySetInnerHTML:{__html:L8(i)}}):n==="thinking"?r.jsx(X8,{content:i,streaming:!!d}):i;return r.jsxs(r.Fragment,{children:[n!=="user_input"&&f,r.jsxs("div",{className:`msg ${K8[n]||"assistant"}${d?" streaming":""}${h?" queued":""}`,children:[v,h&&r.jsxs("span",{className:"msg-queued","data-testid":`msg-queued-${t}`,children:[r.jsx("span",{className:"msg-queued-label",children:"Queued"}),u!=null&&r.jsxs("span",{className:"msg-queued-position","data-testid":`msg-queued-position-${t}`,children:["#",u]}),l&&r.jsx("button",{type:"button",className:"msg-queued-cancel","aria-label":"Cancel queued message",title:"Cancel queued message","data-testid":`msg-queued-cancel-${t}`,onClick:()=>l(t),children:"✕"})]}),o>0&&r.jsx("span",{className:"msg-timestamp",children:V8(o)})]}),n==="user_input"&&f]})});function J8({messages:e,isStreaming:t,isBusy:n,chatActivityState:i,inFlightToolColor:o,renderMessage:d,scrollToBottomSignal:h,queuedIds:l,onCancelQueued:u,workingLabel:f}){const v=N.useRef(null),g=N.useMemo(()=>{if(!l||l.size<2)return null;const P=new Map;let B=0;for(const K of e)l.has(K.id)&&P.set(K.id,++B);return P},[e,l]),[S,w]=N.useState(!1),E=N.useRef(!1),x=N.useRef(!1),m=N.useRef(null),y=N.useRef(null),[b,_]=N.useState(0),[k,j]=N.useState(0),[T,D]=N.useState(Rm),I=N.useMemo(()=>{const P=new Set;return e.filter(B=>P.has(B.id)?!1:(P.add(B.id),!0))},[e]),L=N.useRef(new Map),q=N.useMemo(()=>({get:P=>L.current.get(P),set:(P,B)=>{B?L.current.set(P,!0):L.current.delete(P)}}),[]),H=N.useCallback(P=>I[P]?.id??`__row_${P}`,[I]),Q=U8({itemCount:I.length,scrollTop:b,viewportHeight:k,rowGap:T,keyAt:H}),F=N.useCallback(()=>{const P=v.current;if(!P)return;_(K=>K===P.scrollTop?K:P.scrollTop),j(K=>K===P.clientHeight?K:P.clientHeight);const B=G8(P);D(K=>K===B?K:B)},[]),J=N.useCallback(()=>{const P=v.current;if(!P)return;if(y.current!==null&&Math.abs(P.scrollTop-y.current)<1){y.current=null;return}y.current=null,_(P.scrollTop),j(P.clientHeight);const B=P.scrollHeight-P.scrollTop-P.clientHeight<W8;E.current&&B||w(!B)},[]),ie=N.useCallback(()=>{const P=v.current;P&&(E.current=!0,P.scrollTop=P.scrollHeight,requestAnimationFrame(()=>{E.current=!1}))},[]),X=N.useCallback(()=>{ie(),w(!1)},[ie]);N.useEffect(()=>{v.current&&(ie(),F())},[F,ie]),N.useEffect(()=>{x.current=S},[S]),N.useEffect(()=>{const P=v.current;if(!P||typeof ResizeObserver>"u")return;const B=new ResizeObserver(()=>{F(),x.current||ie()});return B.observe(P),()=>B.disconnect()},[F,ie]),N.useLayoutEffect(()=>{const P=v.current,B=m.current,K={index:Q.firstVisibleIndex,offset:Q.firstVisibleOffset};if(!P||!Q.virtualized){m.current=K;return}if(!S||E.current||!B){m.current=K;return}const le=Q.offsetAt(B.index),me=le-B.offset;if(me===0){m.current=K;return}const be=P.scrollTop+me;y.current=be,P.scrollTop=be,m.current={index:B.index,offset:le},_(be)},[Q,S]);const de=N.useRef(I.length);N.useEffect(()=>{const P=I.length!==de.current;de.current=I.length,P&&!S&&requestAnimationFrame(()=>{ie()})},[I.length,S,n,ie]);const fe=N.useRef(h);N.useEffect(()=>{h!==fe.current&&(fe.current=h,w(!1),requestAnimationFrame(()=>{ie()}))},[h,ie]),N.useEffect(()=>{if(!t||S)return;let P;const B=()=>{ie(),P=requestAnimationFrame(B)};return P=requestAnimationFrame(B),()=>cancelAnimationFrame(P)},[t,S,ie]);const $=I.slice(Q.startIndex,Q.endIndex);return r.jsxs("div",{className:"chat-view","data-testid":"chat-view",children:[r.jsx("div",{className:"presence-rail","data-activity-state":i??"idle",style:o?{"--rail-color":o}:void 0,"data-testid":"presence-rail","aria-hidden":"true"}),r.jsx(gg.Provider,{value:q,children:r.jsxs("div",{ref:v,className:"chat-messages","data-testid":"chat-messages",onScroll:J,children:[Q.topSpacer>0&&r.jsx("div",{"aria-hidden":"true","data-testid":"chat-window-top-spacer",style:{flex:"0 0 auto",height:Q.topSpacer}}),$.map(P=>{const B=m1(P.type),K=Z8(P.type,B!==null),le=d?.(P);return le!=null?r.jsxs(ES,{rowKey:P.id,measureRow:Q.measureRow,className:K,testId:`msg-${P.id}`,children:[P.type!=="user_input"&&B,r.jsx("div",{style:{display:"contents"},children:le}),P.type==="user_input"&&B]},P.id):r.jsx(ES,{rowKey:P.id,measureRow:Q.measureRow,className:K,testId:`msg-${P.id}`,children:r.jsx(Q8,{id:P.id,type:P.type,content:P.content,timestamp:P.timestamp,isStreaming:P.isStreaming,queued:l?.has(P.id)??!1,queuePosition:g?.get(P.id),onCancelQueued:u})},P.id)}),Q.bottomSpacer>0&&r.jsx("div",{"aria-hidden":"true","data-testid":"chat-window-bottom-spacer",style:{flex:"0 0 auto",height:Q.bottomSpacer}}),(t||n)&&r.jsx(h8,{label:f})]})}),S&&r.jsx("button",{className:"scroll-to-bottom","data-testid":"scroll-to-bottom",onClick:X,type:"button","aria-label":"Scroll to bottom",children:"↓"})]})}const Zp=N.memo(J8,(e,t)=>!!e.hidden&&!!t.hidden);var Xp={exports:{}},NS;function ez(){return NS||(NS=1,(function(e,t){(function(n,i){e.exports=i()})(globalThis,(()=>(()=>{var n={4567:function(h,l,u){var f=this&&this.__decorate||function(b,_,k,j){var T,D=arguments.length,I=D<3?_:j===null?j=Object.getOwnPropertyDescriptor(_,k):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(b,_,k,j);else for(var L=b.length-1;L>=0;L--)(T=b[L])&&(I=(D<3?T(I):D>3?T(_,k,I):T(_,k))||I);return D>3&&I&&Object.defineProperty(_,k,I),I},v=this&&this.__param||function(b,_){return function(k,j){_(k,j,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const g=u(9042),S=u(9924),w=u(844),E=u(4725),x=u(2585),m=u(3656);let y=l.AccessibilityManager=class extends w.Disposable{constructor(b,_,k,j){super(),this._terminal=b,this._coreBrowserService=k,this._renderService=j,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let T=0;T<this._terminal.rows;T++)this._rowElements[T]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[T]);if(this._topBoundaryFocusListener=T=>this._handleBoundaryFocus(T,0),this._bottomBoundaryFocusListener=T=>this._handleBoundaryFocus(T,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new S.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((T=>this._handleResize(T.rows)))),this.register(this._terminal.onRender((T=>this._refreshRows(T.start,T.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((T=>this._handleChar(T)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
79
|
-
`)))),this.register(this._terminal.onA11yTab((T=>this._handleTab(T)))),this.register(this._terminal.onKey((T=>this._handleKey(T.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,m.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,w.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(b){for(let _=0;_<b;_++)this._handleChar(" ")}_handleChar(b){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==b&&(this._charsToAnnounce+=b):this._charsToAnnounce+=b,b===`
|
|
80
|
-
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(b){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(b)||this._charsToConsume.push(b)}_refreshRows(b,_){this._liveRegionDebouncer.refresh(b,_,this._terminal.rows)}_renderRows(b,_){const k=this._terminal.buffer,j=k.lines.length.toString();for(let T=b;T<=_;T++){const D=k.lines.get(k.ydisp+T),I=[],L=D?.translateToString(!0,void 0,void 0,I)||"",q=(k.ydisp+T+1).toString(),H=this._rowElements[T];H&&(L.length===0?(H.innerText=" ",this._rowColumns.set(H,[0,1])):(H.textContent=L,this._rowColumns.set(H,I)),H.setAttribute("aria-posinset",q),H.setAttribute("aria-setsize",j))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(b,_){const k=b.target,j=this._rowElements[_===0?1:this._rowElements.length-2];if(k.getAttribute("aria-posinset")===(_===0?"1":`${this._terminal.buffer.lines.length}`)||b.relatedTarget!==j)return;let T,D;if(_===0?(T=k,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(T=this._rowElements.shift(),D=k,this._rowContainer.removeChild(T)),T.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),_===0){const I=this._createAccessibilityTreeNode();this._rowElements.unshift(I),this._rowContainer.insertAdjacentElement("afterbegin",I)}else{const I=this._createAccessibilityTreeNode();this._rowElements.push(I),this._rowContainer.appendChild(I)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(_===0?-1:1),this._rowElements[_===0?1:this._rowElements.length-2].focus(),b.preventDefault(),b.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;const b=document.getSelection();if(!b)return;if(b.isCollapsed)return void(this._rowContainer.contains(b.anchorNode)&&this._terminal.clearSelection());if(!b.anchorNode||!b.focusNode)return void console.error("anchorNode and/or focusNode are null");let _={node:b.anchorNode,offset:b.anchorOffset},k={node:b.focusNode,offset:b.focusOffset};if((_.node.compareDocumentPosition(k.node)&Node.DOCUMENT_POSITION_PRECEDING||_.node===k.node&&_.offset>k.offset)&&([_,k]=[k,_]),_.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(_={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(_.node))return;const j=this._rowElements.slice(-1)[0];if(k.node.compareDocumentPosition(j)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(k={node:j,offset:j.textContent?.length??0}),!this._rowContainer.contains(k.node))return;const T=({node:L,offset:q})=>{const H=L instanceof Text?L.parentNode:L;let Q=parseInt(H?.getAttribute("aria-posinset"),10)-1;if(isNaN(Q))return console.warn("row is invalid. Race condition?"),null;const F=this._rowColumns.get(H);if(!F)return console.warn("columns is null. Race condition?"),null;let J=q<F.length?F[q]:F.slice(-1)[0]+1;return J>=this._terminal.cols&&(++Q,J=0),{row:Q,column:J}},D=T(_),I=T(k);if(D&&I){if(D.row>I.row||D.row===I.row&&D.column>=I.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(I.row-D.row)*this._terminal.cols-D.column+I.column)}}_handleResize(b){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let _=this._rowContainer.children.length;_<this._terminal.rows;_++)this._rowElements[_]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[_]);for(;this._rowElements.length>b;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const b=this._coreBrowserService.mainDocument.createElement("div");return b.setAttribute("role","listitem"),b.tabIndex=-1,this._refreshRowDimensions(b),b}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let b=0;b<this._terminal.rows;b++)this._refreshRowDimensions(this._rowElements[b])}}_refreshRowDimensions(b){b.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=y=f([v(1,x.IInstantiationService),v(2,E.ICoreBrowserService),v(3,E.IRenderService)],y)},3614:(h,l)=>{function u(S){return S.replace(/\r?\n/g,"\r")}function f(S,w){return w?"\x1B[200~"+S+"\x1B[201~":S}function v(S,w,E,x){S=f(S=u(S),E.decPrivateModes.bracketedPasteMode&&x.rawOptions.ignoreBracketedPasteMode!==!0),E.triggerDataEvent(S,!0),w.value=""}function g(S,w,E){const x=E.getBoundingClientRect(),m=S.clientX-x.left-10,y=S.clientY-x.top-10;w.style.width="20px",w.style.height="20px",w.style.left=`${m}px`,w.style.top=`${y}px`,w.style.zIndex="1000",w.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=u,l.bracketTextForPaste=f,l.copyHandler=function(S,w){S.clipboardData&&S.clipboardData.setData("text/plain",w.selectionText),S.preventDefault()},l.handlePasteEvent=function(S,w,E,x){S.stopPropagation(),S.clipboardData&&v(S.clipboardData.getData("text/plain"),w,E,x)},l.paste=v,l.moveTextAreaUnderMouseCursor=g,l.rightClickHandler=function(S,w,E,x,m){g(S,w,E),m&&x.rightClickSelect(S),w.value=x.selectionText,w.select()}},7239:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const f=u(1505);l.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(v,g,S){this._css.set(v,g,S)}getCss(v,g){return this._css.get(v,g)}setColor(v,g,S){this._color.set(v,g,S)}getColor(v,g){return this._color.get(v,g)}clear(){this._color.clear(),this._css.clear()}}},3656:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(u,f,v,g){u.addEventListener(f,v,g);let S=!1;return{dispose:()=>{S||(S=!0,u.removeEventListener(f,v,g))}}}},3551:function(h,l,u){var f=this&&this.__decorate||function(y,b,_,k){var j,T=arguments.length,D=T<3?b:k===null?k=Object.getOwnPropertyDescriptor(b,_):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(y,b,_,k);else for(var I=y.length-1;I>=0;I--)(j=y[I])&&(D=(T<3?j(D):T>3?j(b,_,D):j(b,_))||D);return T>3&&D&&Object.defineProperty(b,_,D),D},v=this&&this.__param||function(y,b){return function(_,k){b(_,k,y)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const g=u(3656),S=u(8460),w=u(844),E=u(2585),x=u(4725);let m=l.Linkifier=class extends w.Disposable{get currentLink(){return this._currentLink}constructor(y,b,_,k,j){super(),this._element=y,this._mouseService=b,this._renderService=_,this._bufferService=k,this._linkProviderService=j,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new S.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new S.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,w.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,w.toDisposable)((()=>{this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,g.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,g.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(y){this._lastMouseEvent=y;const b=this._positionFromMouseEvent(y,this._element,this._mouseService);if(!b)return;this._isMouseOut=!1;const _=y.composedPath();for(let k=0;k<_.length;k++){const j=_[k];if(j.classList.contains("xterm"))break;if(j.classList.contains("xterm-hover"))return}this._lastBufferCell&&b.x===this._lastBufferCell.x&&b.y===this._lastBufferCell.y||(this._handleHover(b),this._lastBufferCell=b)}_handleHover(y){if(this._activeLine!==y.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(y,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,y)||(this._clearCurrentLink(),this._askForLink(y,!0))}_askForLink(y,b){this._activeProviderReplies&&b||(this._activeProviderReplies?.forEach((k=>{k?.forEach((j=>{j.link.dispose&&j.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=y.y);let _=!1;for(const[k,j]of this._linkProviderService.linkProviders.entries())b?this._activeProviderReplies?.get(k)&&(_=this._checkLinkProviderResult(k,y,_)):j.provideLinks(y.y,(T=>{if(this._isMouseOut)return;const D=T?.map((I=>({link:I})));this._activeProviderReplies?.set(k,D),_=this._checkLinkProviderResult(k,y,_),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(y.y,this._activeProviderReplies)}))}_removeIntersectingLinks(y,b){const _=new Set;for(let k=0;k<b.size;k++){const j=b.get(k);if(j)for(let T=0;T<j.length;T++){const D=j[T],I=D.link.range.start.y<y?0:D.link.range.start.x,L=D.link.range.end.y>y?this._bufferService.cols:D.link.range.end.x;for(let q=I;q<=L;q++){if(_.has(q)){j.splice(T--,1);break}_.add(q)}}}}_checkLinkProviderResult(y,b,_){if(!this._activeProviderReplies)return _;const k=this._activeProviderReplies.get(y);let j=!1;for(let T=0;T<y;T++)this._activeProviderReplies.has(T)&&!this._activeProviderReplies.get(T)||(j=!0);if(!j&&k){const T=k.find((D=>this._linkAtPosition(D.link,b)));T&&(_=!0,this._handleNewLink(T))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!_)for(let T=0;T<this._activeProviderReplies.size;T++){const D=this._activeProviderReplies.get(T)?.find((I=>this._linkAtPosition(I.link,b)));if(D){_=!0,this._handleNewLink(D);break}}return _}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(y){if(!this._currentLink)return;const b=this._positionFromMouseEvent(y,this._element,this._mouseService);b&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,b)&&this._currentLink.link.activate(y,this._currentLink.link.text)}_clearCurrentLink(y,b){this._currentLink&&this._lastMouseEvent&&(!y||!b||this._currentLink.link.range.start.y>=y&&this._currentLink.link.range.end.y<=b)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,w.disposeArray)(this._linkCacheDisposables))}_handleNewLink(y){if(!this._lastMouseEvent)return;const b=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);b&&this._linkAtPosition(y.link,b)&&(this._currentLink=y,this._currentLink.state={decorations:{underline:y.link.decorations===void 0||y.link.decorations.underline,pointerCursor:y.link.decorations===void 0||y.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,y.link,this._lastMouseEvent),y.link.decorations={},Object.defineProperties(y.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:_=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==_&&(this._currentLink.state.decorations.pointerCursor=_,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",_))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:_=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==_&&(this._currentLink.state.decorations.underline=_,this._currentLink.state.isHovered&&this._fireUnderlineEvent(y.link,_))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((_=>{if(!this._currentLink)return;const k=_.start===0?0:_.start+1+this._bufferService.buffer.ydisp,j=this._bufferService.buffer.ydisp+1+_.end;if(this._currentLink.link.range.start.y>=k&&this._currentLink.link.range.end.y<=j&&(this._clearCurrentLink(k,j),this._lastMouseEvent)){const T=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);T&&this._askForLink(T,!1)}}))))}_linkHover(y,b,_){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(b,!0),this._currentLink.state.decorations.pointerCursor&&y.classList.add("xterm-cursor-pointer")),b.hover&&b.hover(_,b.text)}_fireUnderlineEvent(y,b){const _=y.range,k=this._bufferService.buffer.ydisp,j=this._createLinkUnderlineEvent(_.start.x-1,_.start.y-k-1,_.end.x,_.end.y-k-1,void 0);(b?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(j)}_linkLeave(y,b,_){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(b,!1),this._currentLink.state.decorations.pointerCursor&&y.classList.remove("xterm-cursor-pointer")),b.leave&&b.leave(_,b.text)}_linkAtPosition(y,b){const _=y.range.start.y*this._bufferService.cols+y.range.start.x,k=y.range.end.y*this._bufferService.cols+y.range.end.x,j=b.y*this._bufferService.cols+b.x;return _<=j&&j<=k}_positionFromMouseEvent(y,b,_){const k=_.getCoords(y,b,this._bufferService.cols,this._bufferService.rows);if(k)return{x:k[0],y:k[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(y,b,_,k,j){return{x1:y,y1:b,x2:_,y2:k,cols:this._bufferService.cols,fg:j}}};l.Linkifier=m=f([v(1,x.IMouseService),v(2,x.IRenderService),v(3,E.IBufferService),v(4,x.ILinkProviderService)],m)},9042:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(h,l,u){var f=this&&this.__decorate||function(x,m,y,b){var _,k=arguments.length,j=k<3?m:b===null?b=Object.getOwnPropertyDescriptor(m,y):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(x,m,y,b);else for(var T=x.length-1;T>=0;T--)(_=x[T])&&(j=(k<3?_(j):k>3?_(m,y,j):_(m,y))||j);return k>3&&j&&Object.defineProperty(m,y,j),j},v=this&&this.__param||function(x,m){return function(y,b){m(y,b,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const g=u(511),S=u(2585);let w=l.OscLinkProvider=class{constructor(x,m,y){this._bufferService=x,this._optionsService=m,this._oscLinkService=y}provideLinks(x,m){const y=this._bufferService.buffer.lines.get(x-1);if(!y)return void m(void 0);const b=[],_=this._optionsService.rawOptions.linkHandler,k=new g.CellData,j=y.getTrimmedLength();let T=-1,D=-1,I=!1;for(let L=0;L<j;L++)if(D!==-1||y.hasContent(L)){if(y.loadCell(L,k),k.hasExtendedAttrs()&&k.extended.urlId){if(D===-1){D=L,T=k.extended.urlId;continue}I=k.extended.urlId!==T}else D!==-1&&(I=!0);if(I||D!==-1&&L===j-1){const q=this._oscLinkService.getLinkData(T)?.uri;if(q){const H={start:{x:D+1,y:x},end:{x:L+(I||L!==j-1?0:1),y:x}};let Q=!1;if(!_?.allowNonHttpProtocols)try{const F=new URL(q);["http:","https:"].includes(F.protocol)||(Q=!0)}catch{Q=!0}Q||b.push({text:q,range:H,activate:(F,J)=>_?_.activate(F,J,H):E(0,J),hover:(F,J)=>_?.hover?.(F,J,H),leave:(F,J)=>_?.leave?.(F,J,H)})}I=!1,k.hasExtendedAttrs()&&k.extended.urlId?(D=L,T=k.extended.urlId):(D=-1,T=-1)}}m(b)}};function E(x,m){if(confirm(`Do you want to navigate to ${m}?
|
|
81
|
-
|
|
82
|
-
WARNING: This link could potentially be dangerous`)){const y=window.open();if(y){try{y.opener=null}catch{}y.location.href=m}else console.warn("Opening link blocked as opener could not be cleared")}}l.OscLinkProvider=w=f([v(0,S.IBufferService),v(1,S.IOptionsService),v(2,S.IOscLinkService)],w)},6193:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.RenderDebouncer=void 0,l.RenderDebouncer=class{constructor(u,f){this._renderCallback=u,this._coreBrowserService=f,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(u){return this._refreshCallbacks.push(u),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(u,f,v){this._rowCount=v,u=u!==void 0?u:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f,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)return void this._runRefreshCallbacks();const u=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,f),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const u of this._refreshCallbacks)u(0);this._refreshCallbacks=[]}}},3236:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Terminal=void 0;const f=u(3614),v=u(3656),g=u(3551),S=u(9042),w=u(3730),E=u(1680),x=u(3107),m=u(5744),y=u(2950),b=u(1296),_=u(428),k=u(4269),j=u(5114),T=u(8934),D=u(3230),I=u(9312),L=u(4725),q=u(6731),H=u(8055),Q=u(8969),F=u(8460),J=u(844),ie=u(6114),X=u(8437),de=u(2584),fe=u(7399),$=u(5941),P=u(9074),B=u(2585),K=u(5435),le=u(4567),me=u(779);class be extends Q.CoreTerminal{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}constructor(se={}){super(se),this.browser=ie,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new J.MutableDisposable),this._onCursorMove=this.register(new F.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new F.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new F.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new F.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new F.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new F.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new F.EventEmitter),this._onBlur=this.register(new F.EventEmitter),this._onA11yCharEmitter=this.register(new F.EventEmitter),this._onA11yTabEmitter=this.register(new F.EventEmitter),this._onWillOpen=this.register(new F.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(P.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(me.LinkProviderService),this._instantiationService.setService(L.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(w.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((Z,ge)=>this.refresh(Z,ge)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((Z=>this._reportWindowsOptions(Z)))),this.register(this._inputHandler.onColor((Z=>this._handleColorEvent(Z)))),this.register((0,F.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,F.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,F.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,F.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((Z=>this._afterResize(Z.cols,Z.rows)))),this.register((0,J.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(se){if(this._themeService)for(const Z of se){let ge,De="";switch(Z.index){case 256:ge="foreground",De="10";break;case 257:ge="background",De="11";break;case 258:ge="cursor",De="12";break;default:ge="ansi",De="4;"+Z.index}switch(Z.type){case 0:const Ge=H.color.toColorRGB(ge==="ansi"?this._themeService.colors.ansi[Z.index]:this._themeService.colors[ge]);this.coreService.triggerDataEvent(`${de.C0.ESC}]${De};${(0,$.toRgbString)(Ge)}${de.C1_ESCAPED.ST}`);break;case 1:if(ge==="ansi")this._themeService.modifyColors((Ve=>Ve.ansi[Z.index]=H.channels.toColor(...Z.color)));else{const Ve=ge;this._themeService.modifyColors((St=>St[Ve]=H.channels.toColor(...Z.color)))}break;case 2:this._themeService.restoreColor(Z.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(se){se?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(le.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(se){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(de.C0.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(de.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const se=this.buffer.ybase+this.buffer.y,Z=this.buffer.lines.get(se);if(!Z)return;const ge=Math.min(this.buffer.x,this.cols-1),De=this._renderService.dimensions.css.cell.height,Ge=Z.getWidth(ge),Ve=this._renderService.dimensions.css.cell.width*Ge,St=this.buffer.y*this._renderService.dimensions.css.cell.height,Nt=ge*this._renderService.dimensions.css.cell.width;this.textarea.style.left=Nt+"px",this.textarea.style.top=St+"px",this.textarea.style.width=Ve+"px",this.textarea.style.height=De+"px",this.textarea.style.lineHeight=De+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,v.addDisposableDomListener)(this.element,"copy",(Z=>{this.hasSelection()&&(0,f.copyHandler)(Z,this._selectionService)})));const se=Z=>(0,f.handlePasteEvent)(Z,this.textarea,this.coreService,this.optionsService);this.register((0,v.addDisposableDomListener)(this.textarea,"paste",se)),this.register((0,v.addDisposableDomListener)(this.element,"paste",se)),ie.isFirefox?this.register((0,v.addDisposableDomListener)(this.element,"mousedown",(Z=>{Z.button===2&&(0,f.rightClickHandler)(Z,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this.register((0,v.addDisposableDomListener)(this.element,"contextmenu",(Z=>{(0,f.rightClickHandler)(Z,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),ie.isLinux&&this.register((0,v.addDisposableDomListener)(this.element,"auxclick",(Z=>{Z.button===1&&(0,f.moveTextAreaUnderMouseCursor)(Z,this.textarea,this.screenElement)})))}_bindKeys(){this.register((0,v.addDisposableDomListener)(this.textarea,"keyup",(se=>this._keyUp(se)),!0)),this.register((0,v.addDisposableDomListener)(this.textarea,"keydown",(se=>this._keyDown(se)),!0)),this.register((0,v.addDisposableDomListener)(this.textarea,"keypress",(se=>this._keyPress(se)),!0)),this.register((0,v.addDisposableDomListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this.register((0,v.addDisposableDomListener)(this.textarea,"compositionupdate",(se=>this._compositionHelper.compositionupdate(se)))),this.register((0,v.addDisposableDomListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this.register((0,v.addDisposableDomListener)(this.textarea,"input",(se=>this._inputEvent(se)),!0)),this.register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(se){if(!se)throw new Error("Terminal requires a parent element.");if(se.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=se.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"),se.appendChild(this.element);const Z=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),Z.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,v.addDisposableDomListener)(this.screenElement,"mousemove",(ge=>this.updateCursorStyle(ge)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),Z.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",S.promptLabel),ie.isChromeOS||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._coreBrowserService=this.register(this._instantiationService.createInstance(j.CoreBrowserService,this.textarea,se.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(L.ICoreBrowserService,this._coreBrowserService),this.register((0,v.addDisposableDomListener)(this.textarea,"focus",(ge=>this._handleTextAreaFocus(ge)))),this.register((0,v.addDisposableDomListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(_.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(L.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(q.ThemeService),this._instantiationService.setService(L.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(k.CharacterJoinerService),this._instantiationService.setService(L.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(D.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(L.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange((ge=>this._onRender.fire(ge)))),this.onResize((ge=>this._renderService.resize(ge.cols,ge.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(y.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(T.MouseService),this._instantiationService.setService(L.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(g.Linkifier,this.screenElement)),this.element.appendChild(Z);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(E.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines((ge=>this.scrollLines(ge.amount,ge.suppressScrollEvent,1))),this.register(this._inputHandler.onRequestSyncScrollBar((()=>this.viewport.syncScrollArea()))),this.register(this.viewport),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.register(this._renderService.onDimensionsChange((()=>this.viewport.syncScrollArea()))),this._selectionService=this.register(this._instantiationService.createInstance(I.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(L.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((ge=>this.scrollLines(ge.amount,ge.suppressScrollEvent)))),this.register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this.register(this._selectionService.onRequestRedraw((ge=>this._renderService.handleSelectionChanged(ge.start,ge.end,ge.columnSelectMode)))),this.register(this._selectionService.onLinuxMouseSelection((ge=>{this.textarea.value=ge,this.textarea.focus(),this.textarea.select()}))),this.register(this._onScroll.event((ge=>{this.viewport.syncScrollArea(),this._selectionService.refresh()}))),this.register((0,v.addDisposableDomListener)(this._viewportElement,"scroll",(()=>this._selectionService.refresh()))),this.register(this._instantiationService.createInstance(x.BufferDecorationRenderer,this.screenElement)),this.register((0,v.addDisposableDomListener)(this.element,"mousedown",(ge=>this._selectionService.handleMouseDown(ge)))),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(le.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",(ge=>this._handleScreenReaderModeOptionChange(ge)))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(m.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",(ge=>{!this._overviewRulerRenderer&&ge&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(m.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(b.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const se=this,Z=this.element;function ge(Ve){const St=se._mouseService.getMouseReportCoords(Ve,se.screenElement);if(!St)return!1;let Nt,kt;switch(Ve.overrideType||Ve.type){case"mousemove":kt=32,Ve.buttons===void 0?(Nt=3,Ve.button!==void 0&&(Nt=Ve.button<3?Ve.button:3)):Nt=1&Ve.buttons?0:4&Ve.buttons?1:2&Ve.buttons?2:3;break;case"mouseup":kt=0,Nt=Ve.button<3?Ve.button:3;break;case"mousedown":kt=1,Nt=Ve.button<3?Ve.button:3;break;case"wheel":if(se._customWheelEventHandler&&se._customWheelEventHandler(Ve)===!1||se.viewport.getLinesScrolled(Ve)===0)return!1;kt=Ve.deltaY<0?0:1,Nt=4;break;default:return!1}return!(kt===void 0||Nt===void 0||Nt>4)&&se.coreMouseService.triggerMouseEvent({col:St.col,row:St.row,x:St.x,y:St.y,button:Nt,action:kt,ctrl:Ve.ctrlKey,alt:Ve.altKey,shift:Ve.shiftKey})}const De={mouseup:null,wheel:null,mousedrag:null,mousemove:null},Ge={mouseup:Ve=>(ge(Ve),Ve.buttons||(this._document.removeEventListener("mouseup",De.mouseup),De.mousedrag&&this._document.removeEventListener("mousemove",De.mousedrag)),this.cancel(Ve)),wheel:Ve=>(ge(Ve),this.cancel(Ve,!0)),mousedrag:Ve=>{Ve.buttons&&ge(Ve)},mousemove:Ve=>{Ve.buttons||ge(Ve)}};this.register(this.coreMouseService.onProtocolChange((Ve=>{Ve?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(Ve)),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()),8&Ve?De.mousemove||(Z.addEventListener("mousemove",Ge.mousemove),De.mousemove=Ge.mousemove):(Z.removeEventListener("mousemove",De.mousemove),De.mousemove=null),16&Ve?De.wheel||(Z.addEventListener("wheel",Ge.wheel,{passive:!1}),De.wheel=Ge.wheel):(Z.removeEventListener("wheel",De.wheel),De.wheel=null),2&Ve?De.mouseup||(De.mouseup=Ge.mouseup):(this._document.removeEventListener("mouseup",De.mouseup),De.mouseup=null),4&Ve?De.mousedrag||(De.mousedrag=Ge.mousedrag):(this._document.removeEventListener("mousemove",De.mousedrag),De.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,v.addDisposableDomListener)(Z,"mousedown",(Ve=>{if(Ve.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(Ve))return ge(Ve),De.mouseup&&this._document.addEventListener("mouseup",De.mouseup),De.mousedrag&&this._document.addEventListener("mousemove",De.mousedrag),this.cancel(Ve)}))),this.register((0,v.addDisposableDomListener)(Z,"wheel",(Ve=>{if(!De.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(Ve)===!1)return!1;if(!this.buffer.hasScrollback){const St=this.viewport.getLinesScrolled(Ve);if(St===0)return;const Nt=de.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(Ve.deltaY<0?"A":"B");let kt="";for(let Tt=0;Tt<Math.abs(St);Tt++)kt+=Nt;return this.coreService.triggerDataEvent(kt,!0),this.cancel(Ve,!0)}return this.viewport.handleWheel(Ve)?this.cancel(Ve):void 0}}),{passive:!1})),this.register((0,v.addDisposableDomListener)(Z,"touchstart",(Ve=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(Ve),this.cancel(Ve)}),{passive:!0})),this.register((0,v.addDisposableDomListener)(Z,"touchmove",(Ve=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(Ve)?void 0:this.cancel(Ve)}),{passive:!1}))}refresh(se,Z){this._renderService?.refreshRows(se,Z)}updateCursorStyle(se){this._selectionService?.shouldColumnSelect(se)?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(se,Z,ge=0){ge===1?(super.scrollLines(se,Z,ge),this.refresh(0,this.rows-1)):this.viewport?.scrollLines(se)}paste(se){(0,f.paste)(se,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(se){this._customKeyEventHandler=se}attachCustomWheelEventHandler(se){this._customWheelEventHandler=se}registerLinkProvider(se){return this._linkProviderService.registerLinkProvider(se)}registerCharacterJoiner(se){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const Z=this._characterJoinerService.register(se);return this.refresh(0,this.rows-1),Z}deregisterCharacterJoiner(se){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(se)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(se){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+se)}registerDecoration(se){return this._decorationService.registerDecoration(se)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(se,Z,ge){this._selectionService.setSelection(se,Z,ge)}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(se,Z){this._selectionService?.selectLines(se,Z)}_keyDown(se){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(se)===!1)return!1;const Z=this.browser.isMac&&this.options.macOptionIsMeta&&se.altKey;if(!Z&&!this._compositionHelper.keydown(se))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;Z||se.key!=="Dead"&&se.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const ge=(0,fe.evaluateKeyboardEvent)(se,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(se),ge.type===3||ge.type===2){const De=this.rows-1;return this.scrollLines(ge.type===2?-De:De),this.cancel(se,!0)}return ge.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,se)||(ge.cancel&&this.cancel(se,!0),!ge.key||!!(se.key&&!se.ctrlKey&&!se.altKey&&!se.metaKey&&se.key.length===1&&se.key.charCodeAt(0)>=65&&se.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(ge.key!==de.C0.ETX&&ge.key!==de.C0.CR||(this.textarea.value=""),this._onKey.fire({key:ge.key,domEvent:se}),this._showCursor(),this.coreService.triggerDataEvent(ge.key,!0),!this.optionsService.rawOptions.screenReaderMode||se.altKey||se.ctrlKey?this.cancel(se,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(se,Z){const ge=se.isMac&&!this.options.macOptionIsMeta&&Z.altKey&&!Z.ctrlKey&&!Z.metaKey||se.isWindows&&Z.altKey&&Z.ctrlKey&&!Z.metaKey||se.isWindows&&Z.getModifierState("AltGraph");return Z.type==="keypress"?ge:ge&&(!Z.keyCode||Z.keyCode>47)}_keyUp(se){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(se)===!1||((function(Z){return Z.keyCode===16||Z.keyCode===17||Z.keyCode===18})(se)||this.focus(),this.updateCursorStyle(se),this._keyPressHandled=!1)}_keyPress(se){let Z;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(se)===!1)return!1;if(this.cancel(se),se.charCode)Z=se.charCode;else if(se.which===null||se.which===void 0)Z=se.keyCode;else{if(se.which===0||se.charCode===0)return!1;Z=se.which}return!(!Z||(se.altKey||se.ctrlKey||se.metaKey)&&!this._isThirdLevelShift(this.browser,se)||(Z=String.fromCharCode(Z),this._onKey.fire({key:Z,domEvent:se}),this._showCursor(),this.coreService.triggerDataEvent(Z,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(se){if(se.data&&se.inputType==="insertText"&&(!se.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const Z=se.data;return this.coreService.triggerDataEvent(Z,!0),this.cancel(se),!0}return!1}resize(se,Z){se!==this.cols||Z!==this.rows?super.resize(se,Z):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(se,Z){this._charSizeService?.measure(),this.viewport?.syncScrollArea(!0)}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 se=1;se<this.rows;se++)this.buffer.lines.push(this.buffer.getBlankLine(X.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),this.viewport?.reset(),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;const se=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this.viewport?.reset(),this._customKeyEventHandler=se,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(de.C0.ESC+"[I"):this.coreService.triggerDataEvent(de.C0.ESC+"[O")}_reportWindowsOptions(se){if(this._renderService)switch(se){case K.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const Z=this._renderService.dimensions.css.canvas.width.toFixed(0),ge=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${de.C0.ESC}[4;${ge};${Z}t`);break;case K.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const De=this._renderService.dimensions.css.cell.width.toFixed(0),Ge=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${de.C0.ESC}[6;${Ge};${De}t`)}}cancel(se,Z){if(this.options.cancelEvents||Z)return se.preventDefault(),se.stopPropagation(),!1}}l.Terminal=be},9924:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.TimeBasedDebouncer=void 0,l.TimeBasedDebouncer=class{constructor(u,f=1e3){this._renderCallback=u,this._debounceThresholdMS=f,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(u,f,v){this._rowCount=v,u=u!==void 0?u:0,f=f!==void 0?f:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,u):u,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,f):f;const g=Date.now();if(g-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=g,this._innerRefresh();else if(!this._additionalRefreshRequested){const S=g-this._lastRefreshMs,w=this._debounceThresholdMS-S;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),w)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const u=Math.max(this._rowStart,0),f=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(u,f)}}},1680:function(h,l,u){var f=this&&this.__decorate||function(y,b,_,k){var j,T=arguments.length,D=T<3?b:k===null?k=Object.getOwnPropertyDescriptor(b,_):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(y,b,_,k);else for(var I=y.length-1;I>=0;I--)(j=y[I])&&(D=(T<3?j(D):T>3?j(b,_,D):j(b,_))||D);return T>3&&D&&Object.defineProperty(b,_,D),D},v=this&&this.__param||function(y,b){return function(_,k){b(_,k,y)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Viewport=void 0;const g=u(3656),S=u(4725),w=u(8460),E=u(844),x=u(2585);let m=l.Viewport=class extends E.Disposable{constructor(y,b,_,k,j,T,D,I){super(),this._viewportElement=y,this._scrollArea=b,this._bufferService=_,this._optionsService=k,this._charSizeService=j,this._renderService=T,this._coreBrowserService=D,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new w.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,g.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((L=>this._activeBuffer=L.activeBuffer))),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange((L=>this._renderDimensions=L))),this._handleThemeChange(I.colors),this.register(I.onChangeColors((L=>this._handleThemeChange(L)))),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.syncScrollArea()))),setTimeout((()=>this.syncScrollArea()))}_handleThemeChange(y){this._viewportElement.style.backgroundColor=y.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame((()=>this.syncScrollArea()))}_refresh(y){if(y)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const b=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==b&&(this._lastRecordedBufferHeight=b,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const y=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==y&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=y),this._refreshAnimationFrame=null}syncScrollArea(y=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(y);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(y)}_handleScroll(y){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const b=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:b,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const y=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(y*(this._smoothScrollState.target-this._smoothScrollState.origin)),y<1?this._coreBrowserService.window.requestAnimationFrame((()=>this._smoothScroll())):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(y,b){const _=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(b<0&&this._viewportElement.scrollTop!==0||b>0&&_<this._lastRecordedBufferHeight)||(y.cancelable&&y.preventDefault(),!1)}handleWheel(y){const b=this._getPixelsScrolled(y);return b!==0&&(this._optionsService.rawOptions.smoothScrollDuration?(this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target===-1?this._smoothScrollState.target=this._viewportElement.scrollTop+b:this._smoothScrollState.target+=b,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=b,this._bubbleScroll(y,b))}scrollLines(y){if(y!==0)if(this._optionsService.rawOptions.smoothScrollDuration){const b=y*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+b,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()}else this._onRequestScrollLines.fire({amount:y,suppressScrollEvent:!1})}_getPixelsScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let b=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_LINE?b*=this._currentRowHeight:y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(b*=this._currentRowHeight*this._bufferService.rows),b}getBufferElements(y,b){let _,k="";const j=[],T=b??this._bufferService.buffer.lines.length,D=this._bufferService.buffer.lines;for(let I=y;I<T;I++){const L=D.get(I);if(!L)continue;const q=D.get(I+1)?.isWrapped;if(k+=L.translateToString(!q),!q||I===D.length-1){const H=document.createElement("div");H.textContent=k,j.push(H),k.length>0&&(_=H),k=""}}return{bufferElements:j,cursorElement:_}}getLinesScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let b=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(b/=this._currentRowHeight+0,this._wheelPartialScroll+=b,b=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(b*=this._bufferService.rows),b}_applyScrollModifier(y,b){const _=this._optionsService.rawOptions.fastScrollModifier;return _==="alt"&&b.altKey||_==="ctrl"&&b.ctrlKey||_==="shift"&&b.shiftKey?y*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:y*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(y){this._lastTouchY=y.touches[0].pageY}handleTouchMove(y){const b=this._lastTouchY-y.touches[0].pageY;return this._lastTouchY=y.touches[0].pageY,b!==0&&(this._viewportElement.scrollTop+=b,this._bubbleScroll(y,b))}};l.Viewport=m=f([v(2,x.IBufferService),v(3,x.IOptionsService),v(4,S.ICharSizeService),v(5,S.IRenderService),v(6,S.ICoreBrowserService),v(7,S.IThemeService)],m)},3107:function(h,l,u){var f=this&&this.__decorate||function(x,m,y,b){var _,k=arguments.length,j=k<3?m:b===null?b=Object.getOwnPropertyDescriptor(m,y):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(x,m,y,b);else for(var T=x.length-1;T>=0;T--)(_=x[T])&&(j=(k<3?_(j):k>3?_(m,y,j):_(m,y))||j);return k>3&&j&&Object.defineProperty(m,y,j),j},v=this&&this.__param||function(x,m){return function(y,b){m(y,b,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.BufferDecorationRenderer=void 0;const g=u(4725),S=u(844),w=u(2585);let E=l.BufferDecorationRenderer=class extends S.Disposable{constructor(x,m,y,b,_){super(),this._screenElement=x,this._bufferService=m,this._coreBrowserService=y,this._decorationService=b,this._renderService=_,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((k=>this._removeDecoration(k)))),this.register((0,S.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const x of this._decorationService.decorations)this._renderDecoration(x);this._dimensionsChanged=!1}_renderDecoration(x){this._refreshStyle(x),this._dimensionsChanged&&this._refreshXPosition(x)}_createElement(x){const m=this._coreBrowserService.mainDocument.createElement("div");m.classList.add("xterm-decoration"),m.classList.toggle("xterm-decoration-top-layer",x?.options?.layer==="top"),m.style.width=`${Math.round((x.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,m.style.height=(x.options.height||1)*this._renderService.dimensions.css.cell.height+"px",m.style.top=(x.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",m.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const y=x.options.x??0;return y&&y>this._bufferService.cols&&(m.style.display="none"),this._refreshXPosition(x,m),m}_refreshStyle(x){const m=x.marker.line-this._bufferService.buffers.active.ydisp;if(m<0||m>=this._bufferService.rows)x.element&&(x.element.style.display="none",x.onRenderEmitter.fire(x.element));else{let y=this._decorationElements.get(x);y||(y=this._createElement(x),x.element=y,this._decorationElements.set(x,y),this._container.appendChild(y),x.onDispose((()=>{this._decorationElements.delete(x),y.remove()}))),y.style.top=m*this._renderService.dimensions.css.cell.height+"px",y.style.display=this._altBufferIsActive?"none":"block",x.onRenderEmitter.fire(y)}}_refreshXPosition(x,m=x.element){if(!m)return;const y=x.options.x??0;(x.options.anchor||"left")==="right"?m.style.right=y?y*this._renderService.dimensions.css.cell.width+"px":"":m.style.left=y?y*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(x){this._decorationElements.get(x)?.remove(),this._decorationElements.delete(x),x.dispose()}};l.BufferDecorationRenderer=E=f([v(1,w.IBufferService),v(2,g.ICoreBrowserService),v(3,w.IDecorationService),v(4,g.IRenderService)],E)},5871:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorZoneStore=void 0,l.ColorZoneStore=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(u){if(u.options.overviewRulerOptions){for(const f of this._zones)if(f.color===u.options.overviewRulerOptions.color&&f.position===u.options.overviewRulerOptions.position){if(this._lineIntersectsZone(f,u.marker.line))return;if(this._lineAdjacentToZone(f,u.marker.line,u.options.overviewRulerOptions.position))return void this._addLineToZone(f,u.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=u.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=u.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=u.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=u.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:u.options.overviewRulerOptions.color,position:u.options.overviewRulerOptions.position,startBufferLine:u.marker.line,endBufferLine:u.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(u){this._linePadding=u}_lineIntersectsZone(u,f){return f>=u.startBufferLine&&f<=u.endBufferLine}_lineAdjacentToZone(u,f,v){return f>=u.startBufferLine-this._linePadding[v||"full"]&&f<=u.endBufferLine+this._linePadding[v||"full"]}_addLineToZone(u,f){u.startBufferLine=Math.min(u.startBufferLine,f),u.endBufferLine=Math.max(u.endBufferLine,f)}}},5744:function(h,l,u){var f=this&&this.__decorate||function(_,k,j,T){var D,I=arguments.length,L=I<3?k:T===null?T=Object.getOwnPropertyDescriptor(k,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(_,k,j,T);else for(var q=_.length-1;q>=0;q--)(D=_[q])&&(L=(I<3?D(L):I>3?D(k,j,L):D(k,j))||L);return I>3&&L&&Object.defineProperty(k,j,L),L},v=this&&this.__param||function(_,k){return function(j,T){k(j,T,_)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OverviewRulerRenderer=void 0;const g=u(5871),S=u(4725),w=u(844),E=u(2585),x={full:0,left:0,center:0,right:0},m={full:0,left:0,center:0,right:0},y={full:0,left:0,center:0,right:0};let b=l.OverviewRulerRenderer=class extends w.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(_,k,j,T,D,I,L){super(),this._viewportElement=_,this._screenElement=k,this._bufferService=j,this._decorationService=T,this._renderService=D,this._optionsService=I,this._coreBrowserService=L,this._colorZoneStore=new g.ColorZoneStore,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);const q=this._canvas.getContext("2d");if(!q)throw new Error("Ctx cannot be null");this._ctx=q,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,w.toDisposable)((()=>{this._canvas?.remove()})))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this.register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0))))}_registerBufferChangeListeners(){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())})))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",(()=>this._queueRefresh(!0)))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._queueRefresh(!0)}_refreshDrawConstants(){const _=Math.floor(this._canvas.width/3),k=Math.ceil(this._canvas.width/3);m.full=this._canvas.width,m.left=_,m.center=k,m.right=_,this._refreshDrawHeightConstants(),y.full=0,y.left=0,y.center=m.left,y.right=m.left+m.center}_refreshDrawHeightConstants(){x.full=Math.round(2*this._coreBrowserService.dpr);const _=this._canvas.height/this._bufferService.buffer.lines.length,k=Math.round(Math.max(Math.min(_,12),6)*this._coreBrowserService.dpr);x.left=k,x.center=k,x.right=k}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*x.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*x.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*x.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*x.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(const k of this._decorationService.decorations)this._colorZoneStore.addDecoration(k);this._ctx.lineWidth=1;const _=this._colorZoneStore.zones;for(const k of _)k.position!=="full"&&this._renderColorZone(k);for(const k of _)k.position==="full"&&this._renderColorZone(k);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(_){this._ctx.fillStyle=_.color,this._ctx.fillRect(y[_.position||"full"],Math.round((this._canvas.height-1)*(_.startBufferLine/this._bufferService.buffers.active.lines.length)-x[_.position||"full"]/2),m[_.position||"full"],Math.round((this._canvas.height-1)*((_.endBufferLine-_.startBufferLine)/this._bufferService.buffers.active.lines.length)+x[_.position||"full"]))}_queueRefresh(_,k){this._shouldUpdateDimensions=_||this._shouldUpdateDimensions,this._shouldUpdateAnchor=k||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};l.OverviewRulerRenderer=b=f([v(2,E.IBufferService),v(3,E.IDecorationService),v(4,S.IRenderService),v(5,E.IOptionsService),v(6,S.ICoreBrowserService)],b)},2950:function(h,l,u){var f=this&&this.__decorate||function(x,m,y,b){var _,k=arguments.length,j=k<3?m:b===null?b=Object.getOwnPropertyDescriptor(m,y):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(x,m,y,b);else for(var T=x.length-1;T>=0;T--)(_=x[T])&&(j=(k<3?_(j):k>3?_(m,y,j):_(m,y))||j);return k>3&&j&&Object.defineProperty(m,y,j),j},v=this&&this.__param||function(x,m){return function(y,b){m(y,b,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CompositionHelper=void 0;const g=u(4725),S=u(2585),w=u(2584);let E=l.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(x,m,y,b,_,k){this._textarea=x,this._compositionView=m,this._bufferService=y,this._optionsService=b,this._coreService=_,this._renderService=k,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(x){this._compositionView.textContent=x.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(x){if(this._isComposing||this._isSendingComposition){if(x.keyCode===229||x.keyCode===16||x.keyCode===17||x.keyCode===18)return!1;this._finalizeComposition(!1)}return x.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(x){if(this._compositionView.classList.remove("active"),this._isComposing=!1,x){const m={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let y;this._isSendingComposition=!1,m.start+=this._dataAlreadySent.length,y=this._isComposing?this._textarea.value.substring(m.start,m.end):this._textarea.value.substring(m.start),y.length>0&&this._coreService.triggerDataEvent(y,!0)}}),0)}else{this._isSendingComposition=!1;const m=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(m,!0)}}_handleAnyTextareaChanges(){const x=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const m=this._textarea.value,y=m.replace(x,"");this._dataAlreadySent=y,m.length>x.length?this._coreService.triggerDataEvent(y,!0):m.length<x.length?this._coreService.triggerDataEvent(`${w.C0.DEL}`,!0):m.length===x.length&&m!==x&&this._coreService.triggerDataEvent(m,!0)}}),0)}updateCompositionElements(x){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const m=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),y=this._renderService.dimensions.css.cell.height,b=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,_=m*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=_+"px",this._compositionView.style.top=b+"px",this._compositionView.style.height=y+"px",this._compositionView.style.lineHeight=y+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const k=this._compositionView.getBoundingClientRect();this._textarea.style.left=_+"px",this._textarea.style.top=b+"px",this._textarea.style.width=Math.max(k.width,1)+"px",this._textarea.style.height=Math.max(k.height,1)+"px",this._textarea.style.lineHeight=k.height+"px"}x||setTimeout((()=>this.updateCompositionElements(!0)),0)}}};l.CompositionHelper=E=f([v(2,S.IBufferService),v(3,S.IOptionsService),v(4,S.ICoreService),v(5,g.IRenderService)],E)},9806:(h,l)=>{function u(f,v,g){const S=g.getBoundingClientRect(),w=f.getComputedStyle(g),E=parseInt(w.getPropertyValue("padding-left")),x=parseInt(w.getPropertyValue("padding-top"));return[v.clientX-S.left-E,v.clientY-S.top-x]}Object.defineProperty(l,"__esModule",{value:!0}),l.getCoords=l.getCoordsRelativeToElement=void 0,l.getCoordsRelativeToElement=u,l.getCoords=function(f,v,g,S,w,E,x,m,y){if(!E)return;const b=u(f,v,g);return b?(b[0]=Math.ceil((b[0]+(y?x/2:0))/x),b[1]=Math.ceil(b[1]/m),b[0]=Math.min(Math.max(b[0],1),S+(y?1:0)),b[1]=Math.min(Math.max(b[1],1),w),b):void 0}},9504:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.moveToCellSequence=void 0;const f=u(2584);function v(m,y,b,_){const k=m-g(m,b),j=y-g(y,b),T=Math.abs(k-j)-(function(D,I,L){let q=0;const H=D-g(D,L),Q=I-g(I,L);for(let F=0;F<Math.abs(H-Q);F++){const J=S(D,I)==="A"?-1:1;L.buffer.lines.get(H+J*F)?.isWrapped&&q++}return q})(m,y,b);return x(T,E(S(m,y),_))}function g(m,y){let b=0,_=y.buffer.lines.get(m),k=_?.isWrapped;for(;k&&m>=0&&m<y.rows;)b++,_=y.buffer.lines.get(--m),k=_?.isWrapped;return b}function S(m,y){return m>y?"A":"B"}function w(m,y,b,_,k,j){let T=m,D=y,I="";for(;T!==b||D!==_;)T+=k?1:-1,k&&T>j.cols-1?(I+=j.buffer.translateBufferLineToString(D,!1,m,T),T=0,m=0,D++):!k&&T<0&&(I+=j.buffer.translateBufferLineToString(D,!1,0,m+1),T=j.cols-1,m=T,D--);return I+j.buffer.translateBufferLineToString(D,!1,m,T)}function E(m,y){const b=y?"O":"[";return f.C0.ESC+b+m}function x(m,y){m=Math.floor(m);let b="";for(let _=0;_<m;_++)b+=y;return b}l.moveToCellSequence=function(m,y,b,_){const k=b.buffer.x,j=b.buffer.y;if(!b.buffer.hasScrollback)return(function(I,L,q,H,Q,F){return v(L,H,Q,F).length===0?"":x(w(I,L,I,L-g(L,Q),!1,Q).length,E("D",F))})(k,j,0,y,b,_)+v(j,y,b,_)+(function(I,L,q,H,Q,F){let J;J=v(L,H,Q,F).length>0?H-g(H,Q):L;const ie=H,X=(function(de,fe,$,P,B,K){let le;return le=v($,P,B,K).length>0?P-g(P,B):fe,de<$&&le<=P||de>=$&&le<P?"C":"D"})(I,L,q,H,Q,F);return x(w(I,J,q,ie,X==="C",Q).length,E(X,F))})(k,j,m,y,b,_);let T;if(j===y)return T=k>m?"D":"C",x(Math.abs(k-m),E(T,_));T=j>y?"D":"C";const D=Math.abs(j-y);return x((function(I,L){return L.cols-I})(j>y?m:k,b)+(D-1)*b.cols+1+((j>y?k:m)-1),E(T,_))}},1296:function(h,l,u){var f=this&&this.__decorate||function(F,J,ie,X){var de,fe=arguments.length,$=fe<3?J:X===null?X=Object.getOwnPropertyDescriptor(J,ie):X;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(F,J,ie,X);else for(var P=F.length-1;P>=0;P--)(de=F[P])&&($=(fe<3?de($):fe>3?de(J,ie,$):de(J,ie))||$);return fe>3&&$&&Object.defineProperty(J,ie,$),$},v=this&&this.__param||function(F,J){return function(ie,X){J(ie,X,F)}};Object.defineProperty(l,"__esModule",{value:!0}),l.DomRenderer=void 0;const g=u(3787),S=u(2550),w=u(2223),E=u(6171),x=u(6052),m=u(4725),y=u(8055),b=u(8460),_=u(844),k=u(2585),j="xterm-dom-renderer-owner-",T="xterm-rows",D="xterm-fg-",I="xterm-bg-",L="xterm-focus",q="xterm-selection";let H=1,Q=l.DomRenderer=class extends _.Disposable{constructor(F,J,ie,X,de,fe,$,P,B,K,le,me,be){super(),this._terminal=F,this._document=J,this._element=ie,this._screenElement=X,this._viewportElement=de,this._helperContainer=fe,this._linkifier2=$,this._charSizeService=B,this._optionsService=K,this._bufferService=le,this._coreBrowserService=me,this._themeService=be,this._terminalClass=H++,this._rowElements=[],this._selectionRenderModel=(0,x.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new b.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(T),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(q),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,E.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._themeService.onChangeColors((Ee=>this._injectCss(Ee)))),this._injectCss(this._themeService.colors),this._rowFactory=P.createInstance(g.DomRendererRowFactory,document),this._element.classList.add(j+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline((Ee=>this._handleLinkHover(Ee)))),this.register(this._linkifier2.onHideLinkUnderline((Ee=>this._handleLinkLeave(Ee)))),this.register((0,_.toDisposable)((()=>{this._element.classList.remove(j+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new S.WidthCache(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(){const F=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*F,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*F),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/F),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/F),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(const ie of this._rowElements)ie.style.width=`${this.dimensions.css.canvas.width}px`,ie.style.height=`${this.dimensions.css.cell.height}px`,ie.style.lineHeight=`${this.dimensions.css.cell.height}px`,ie.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const J=`${this._terminalSelector} .${T} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=J,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(F){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let J=`${this._terminalSelector} .${T} { color: ${F.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;J+=`${this._terminalSelector} .${T} .xterm-dim { color: ${y.color.multiplyOpacity(F.foreground,.5).css};}`,J+=`${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;}`;const ie=`blink_underline_${this._terminalClass}`,X=`blink_bar_${this._terminalClass}`,de=`blink_block_${this._terminalClass}`;J+=`@keyframes ${ie} { 50% { border-bottom-style: hidden; }}`,J+=`@keyframes ${X} { 50% { box-shadow: none; }}`,J+=`@keyframes ${de} { 0% { background-color: ${F.cursor.css}; color: ${F.cursorAccent.css}; } 50% { background-color: inherit; color: ${F.cursor.css}; }}`,J+=`${this._terminalSelector} .${T}.${L} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${ie} 1s step-end infinite;}${this._terminalSelector} .${T}.${L} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${X} 1s step-end infinite;}${this._terminalSelector} .${T}.${L} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${de} 1s step-end infinite;}${this._terminalSelector} .${T} .xterm-cursor.xterm-cursor-block { background-color: ${F.cursor.css}; color: ${F.cursorAccent.css};}${this._terminalSelector} .${T} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${F.cursor.css} !important; color: ${F.cursorAccent.css} !important;}${this._terminalSelector} .${T} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${F.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${T} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${F.cursor.css} inset;}${this._terminalSelector} .${T} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${F.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,J+=`${this._terminalSelector} .${q} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${q} div { position: absolute; background-color: ${F.selectionBackgroundOpaque.css};}${this._terminalSelector} .${q} div { position: absolute; background-color: ${F.selectionInactiveBackgroundOpaque.css};}`;for(const[fe,$]of F.ansi.entries())J+=`${this._terminalSelector} .${D}${fe} { color: ${$.css}; }${this._terminalSelector} .${D}${fe}.xterm-dim { color: ${y.color.multiplyOpacity($,.5).css}; }${this._terminalSelector} .${I}${fe} { background-color: ${$.css}; }`;J+=`${this._terminalSelector} .${D}${w.INVERTED_DEFAULT_COLOR} { color: ${y.color.opaque(F.background).css}; }${this._terminalSelector} .${D}${w.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${y.color.multiplyOpacity(y.color.opaque(F.background),.5).css}; }${this._terminalSelector} .${I}${w.INVERTED_DEFAULT_COLOR} { background-color: ${F.foreground.css}; }`,this._themeStyleElement.textContent=J}_setDefaultSpacing(){const F=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${F}px`,this._rowFactory.defaultSpacing=F}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(F,J){for(let ie=this._rowElements.length;ie<=J;ie++){const X=this._document.createElement("div");this._rowContainer.appendChild(X),this._rowElements.push(X)}for(;this._rowElements.length>J;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(F,J){this._refreshRowElements(F,J),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(L),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(L),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(F,J,ie){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(F,J,ie),this.renderRows(0,this._bufferService.rows-1),!F||!J)return;this._selectionRenderModel.update(this._terminal,F,J,ie);const X=this._selectionRenderModel.viewportStartRow,de=this._selectionRenderModel.viewportEndRow,fe=this._selectionRenderModel.viewportCappedStartRow,$=this._selectionRenderModel.viewportCappedEndRow;if(fe>=this._bufferService.rows||$<0)return;const P=this._document.createDocumentFragment();if(ie){const B=F[0]>J[0];P.appendChild(this._createSelectionElement(fe,B?J[0]:F[0],B?F[0]:J[0],$-fe+1))}else{const B=X===fe?F[0]:0,K=fe===de?J[0]:this._bufferService.cols;P.appendChild(this._createSelectionElement(fe,B,K));const le=$-fe-1;if(P.appendChild(this._createSelectionElement(fe+1,0,this._bufferService.cols,le)),fe!==$){const me=de===$?J[0]:this._bufferService.cols;P.appendChild(this._createSelectionElement($,0,me))}}this._selectionContainer.appendChild(P)}_createSelectionElement(F,J,ie,X=1){const de=this._document.createElement("div"),fe=J*this.dimensions.css.cell.width;let $=this.dimensions.css.cell.width*(ie-J);return fe+$>this.dimensions.css.canvas.width&&($=this.dimensions.css.canvas.width-fe),de.style.height=X*this.dimensions.css.cell.height+"px",de.style.top=F*this.dimensions.css.cell.height+"px",de.style.left=`${fe}px`,de.style.width=`${$}px`,de}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(const F of this._rowElements)F.replaceChildren()}renderRows(F,J){const ie=this._bufferService.buffer,X=ie.ybase+ie.y,de=Math.min(ie.x,this._bufferService.cols-1),fe=this._optionsService.rawOptions.cursorBlink,$=this._optionsService.rawOptions.cursorStyle,P=this._optionsService.rawOptions.cursorInactiveStyle;for(let B=F;B<=J;B++){const K=B+ie.ydisp,le=this._rowElements[B],me=ie.lines.get(K);if(!le||!me)break;le.replaceChildren(...this._rowFactory.createRow(me,K,K===X,$,P,de,fe,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${j}${this._terminalClass}`}_handleLinkHover(F){this._setCellUnderline(F.x1,F.x2,F.y1,F.y2,F.cols,!0)}_handleLinkLeave(F){this._setCellUnderline(F.x1,F.x2,F.y1,F.y2,F.cols,!1)}_setCellUnderline(F,J,ie,X,de,fe){ie<0&&(F=0),X<0&&(J=0);const $=this._bufferService.rows-1;ie=Math.max(Math.min(ie,$),0),X=Math.max(Math.min(X,$),0),de=Math.min(de,this._bufferService.cols);const P=this._bufferService.buffer,B=P.ybase+P.y,K=Math.min(P.x,de-1),le=this._optionsService.rawOptions.cursorBlink,me=this._optionsService.rawOptions.cursorStyle,be=this._optionsService.rawOptions.cursorInactiveStyle;for(let Ee=ie;Ee<=X;++Ee){const se=Ee+P.ydisp,Z=this._rowElements[Ee],ge=P.lines.get(se);if(!Z||!ge)break;Z.replaceChildren(...this._rowFactory.createRow(ge,se,se===B,me,be,K,le,this.dimensions.css.cell.width,this._widthCache,fe?Ee===ie?F:0:-1,fe?(Ee===X?J:de)-1:-1))}}};l.DomRenderer=Q=f([v(7,k.IInstantiationService),v(8,m.ICharSizeService),v(9,k.IOptionsService),v(10,k.IBufferService),v(11,m.ICoreBrowserService),v(12,m.IThemeService)],Q)},3787:function(h,l,u){var f=this&&this.__decorate||function(T,D,I,L){var q,H=arguments.length,Q=H<3?D:L===null?L=Object.getOwnPropertyDescriptor(D,I):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")Q=Reflect.decorate(T,D,I,L);else for(var F=T.length-1;F>=0;F--)(q=T[F])&&(Q=(H<3?q(Q):H>3?q(D,I,Q):q(D,I))||Q);return H>3&&Q&&Object.defineProperty(D,I,Q),Q},v=this&&this.__param||function(T,D){return function(I,L){D(I,L,T)}};Object.defineProperty(l,"__esModule",{value:!0}),l.DomRendererRowFactory=void 0;const g=u(2223),S=u(643),w=u(511),E=u(2585),x=u(8055),m=u(4725),y=u(4269),b=u(6171),_=u(3734);let k=l.DomRendererRowFactory=class{constructor(T,D,I,L,q,H,Q){this._document=T,this._characterJoinerService=D,this._optionsService=I,this._coreBrowserService=L,this._coreService=q,this._decorationService=H,this._themeService=Q,this._workCell=new w.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(T,D,I){this._selectionStart=T,this._selectionEnd=D,this._columnSelectMode=I}createRow(T,D,I,L,q,H,Q,F,J,ie,X){const de=[],fe=this._characterJoinerService.getJoinedCharacters(D),$=this._themeService.colors;let P,B=T.getNoBgTrimmedLength();I&&B<H+1&&(B=H+1);let K=0,le="",me=0,be=0,Ee=0,se=!1,Z=0,ge=!1,De=0;const Ge=[],Ve=ie!==-1&&X!==-1;for(let St=0;St<B;St++){T.loadCell(St,this._workCell);let Nt=this._workCell.getWidth();if(Nt===0)continue;let kt=!1,Tt=St,at=this._workCell;if(fe.length>0&&St===fe[0][0]){kt=!0;const tt=fe.shift();at=new y.JoinedCellData(this._workCell,T.translateToString(!0,tt[0],tt[1]),tt[1]-tt[0]),Tt=tt[1]-1,Nt=at.getWidth()}const en=this._isCellInSelection(St,D),cn=I&&St===H,Bt=Ve&&St>=ie&&St<=X;let hn=!1;this._decorationService.forEachDecorationAtCell(St,D,void 0,(tt=>{hn=!0}));let sn=at.getChars()||S.WHITESPACE_CELL_CHAR;if(sn===" "&&(at.isUnderline()||at.isOverline())&&(sn=" "),De=Nt*F-J.get(sn,at.isBold(),at.isItalic()),P){if(K&&(en&&ge||!en&&!ge&&at.bg===me)&&(en&&ge&&$.selectionForeground||at.fg===be)&&at.extended.ext===Ee&&Bt===se&&De===Z&&!cn&&!kt&&!hn){at.isInvisible()?le+=S.WHITESPACE_CELL_CHAR:le+=sn,K++;continue}K&&(P.textContent=le),P=this._document.createElement("span"),K=0,le=""}else P=this._document.createElement("span");if(me=at.bg,be=at.fg,Ee=at.extended.ext,se=Bt,Z=De,ge=en,kt&&H>=St&&H<=Tt&&(H=St),!this._coreService.isCursorHidden&&cn&&this._coreService.isCursorInitialized){if(Ge.push("xterm-cursor"),this._coreBrowserService.isFocused)Q&&Ge.push("xterm-cursor-blink"),Ge.push(L==="bar"?"xterm-cursor-bar":L==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(q)switch(q){case"outline":Ge.push("xterm-cursor-outline");break;case"block":Ge.push("xterm-cursor-block");break;case"bar":Ge.push("xterm-cursor-bar");break;case"underline":Ge.push("xterm-cursor-underline")}}if(at.isBold()&&Ge.push("xterm-bold"),at.isItalic()&&Ge.push("xterm-italic"),at.isDim()&&Ge.push("xterm-dim"),le=at.isInvisible()?S.WHITESPACE_CELL_CHAR:at.getChars()||S.WHITESPACE_CELL_CHAR,at.isUnderline()&&(Ge.push(`xterm-underline-${at.extended.underlineStyle}`),le===" "&&(le=" "),!at.isUnderlineColorDefault()))if(at.isUnderlineColorRGB())P.style.textDecorationColor=`rgb(${_.AttributeData.toColorRGB(at.getUnderlineColor()).join(",")})`;else{let tt=at.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&at.isBold()&&tt<8&&(tt+=8),P.style.textDecorationColor=$.ansi[tt].css}at.isOverline()&&(Ge.push("xterm-overline"),le===" "&&(le=" ")),at.isStrikethrough()&&Ge.push("xterm-strikethrough"),Bt&&(P.style.textDecoration="underline");let Ct=at.getFgColor(),Ut=at.getFgColorMode(),$t=at.getBgColor(),Lt=at.getBgColorMode();const Ht=!!at.isInverse();if(Ht){const tt=Ct;Ct=$t,$t=tt;const Pt=Ut;Ut=Lt,Lt=Pt}let zt,rn,ze,Je=!1;switch(this._decorationService.forEachDecorationAtCell(St,D,void 0,(tt=>{tt.options.layer!=="top"&&Je||(tt.backgroundColorRGB&&(Lt=50331648,$t=tt.backgroundColorRGB.rgba>>8&16777215,zt=tt.backgroundColorRGB),tt.foregroundColorRGB&&(Ut=50331648,Ct=tt.foregroundColorRGB.rgba>>8&16777215,rn=tt.foregroundColorRGB),Je=tt.options.layer==="top")})),!Je&&en&&(zt=this._coreBrowserService.isFocused?$.selectionBackgroundOpaque:$.selectionInactiveBackgroundOpaque,$t=zt.rgba>>8&16777215,Lt=50331648,Je=!0,$.selectionForeground&&(Ut=50331648,Ct=$.selectionForeground.rgba>>8&16777215,rn=$.selectionForeground)),Je&&Ge.push("xterm-decoration-top"),Lt){case 16777216:case 33554432:ze=$.ansi[$t],Ge.push(`xterm-bg-${$t}`);break;case 50331648:ze=x.channels.toColor($t>>16,$t>>8&255,255&$t),this._addStyle(P,`background-color:#${j(($t>>>0).toString(16),"0",6)}`);break;default:Ht?(ze=$.foreground,Ge.push(`xterm-bg-${g.INVERTED_DEFAULT_COLOR}`)):ze=$.background}switch(zt||at.isDim()&&(zt=x.color.multiplyOpacity(ze,.5)),Ut){case 16777216:case 33554432:at.isBold()&&Ct<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Ct+=8),this._applyMinimumContrast(P,ze,$.ansi[Ct],at,zt,void 0)||Ge.push(`xterm-fg-${Ct}`);break;case 50331648:const tt=x.channels.toColor(Ct>>16&255,Ct>>8&255,255&Ct);this._applyMinimumContrast(P,ze,tt,at,zt,rn)||this._addStyle(P,`color:#${j(Ct.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(P,ze,$.foreground,at,zt,rn)||Ht&&Ge.push(`xterm-fg-${g.INVERTED_DEFAULT_COLOR}`)}Ge.length&&(P.className=Ge.join(" "),Ge.length=0),cn||kt||hn?P.textContent=le:K++,De!==this.defaultSpacing&&(P.style.letterSpacing=`${De}px`),de.push(P),St=Tt}return P&&K&&(P.textContent=le),de}_applyMinimumContrast(T,D,I,L,q,H){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,b.treatGlyphAsBackgroundColor)(L.getCode()))return!1;const Q=this._getContrastCache(L);let F;if(q||H||(F=Q.getColor(D.rgba,I.rgba)),F===void 0){const J=this._optionsService.rawOptions.minimumContrastRatio/(L.isDim()?2:1);F=x.color.ensureContrastRatio(q||D,H||I,J),Q.setColor((q||D).rgba,(H||I).rgba,F??null)}return!!F&&(this._addStyle(T,`color:${F.css}`),!0)}_getContrastCache(T){return T.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(T,D){T.setAttribute("style",`${T.getAttribute("style")||""}${D};`)}_isCellInSelection(T,D){const I=this._selectionStart,L=this._selectionEnd;return!(!I||!L)&&(this._columnSelectMode?I[0]<=L[0]?T>=I[0]&&D>=I[1]&&T<L[0]&&D<=L[1]:T<I[0]&&D>=I[1]&&T>=L[0]&&D<=L[1]:D>I[1]&&D<L[1]||I[1]===L[1]&&D===I[1]&&T>=I[0]&&T<L[0]||I[1]<L[1]&&D===L[1]&&T<L[0]||I[1]<L[1]&&D===I[1]&&T>=I[0])}};function j(T,D,I){for(;T.length<I;)T=D+T;return T}l.DomRendererRowFactory=k=f([v(1,m.ICharacterJoinerService),v(2,E.IOptionsService),v(3,m.ICoreBrowserService),v(4,E.ICoreService),v(5,E.IDecorationService),v(6,m.IThemeService)],k)},2550:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.WidthCache=void 0,l.WidthCache=class{constructor(u,f){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=u.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";const v=u.createElement("span");v.classList.add("xterm-char-measure-element");const g=u.createElement("span");g.classList.add("xterm-char-measure-element"),g.style.fontWeight="bold";const S=u.createElement("span");S.classList.add("xterm-char-measure-element"),S.style.fontStyle="italic";const w=u.createElement("span");w.classList.add("xterm-char-measure-element"),w.style.fontWeight="bold",w.style.fontStyle="italic",this._measureElements=[v,g,S,w],this._container.appendChild(v),this._container.appendChild(g),this._container.appendChild(S),this._container.appendChild(w),f.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(u,f,v,g){u===this._font&&f===this._fontSize&&v===this._weight&&g===this._weightBold||(this._font=u,this._fontSize=f,this._weight=v,this._weightBold=g,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${v}`,this._measureElements[1].style.fontWeight=`${g}`,this._measureElements[2].style.fontWeight=`${v}`,this._measureElements[3].style.fontWeight=`${g}`,this.clear())}get(u,f,v){let g=0;if(!f&&!v&&u.length===1&&(g=u.charCodeAt(0))<256){if(this._flat[g]!==-9999)return this._flat[g];const E=this._measure(u,0);return E>0&&(this._flat[g]=E),E}let S=u;f&&(S+="B"),v&&(S+="I");let w=this._holey.get(S);if(w===void 0){let E=0;f&&(E|=1),v&&(E|=2),w=this._measure(u,E),w>0&&this._holey.set(S,w)}return w}_measure(u,f){const v=this._measureElements[f];return v.textContent=u.repeat(32),v.offsetWidth/32}}},2223:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.TEXT_BASELINE=l.DIM_OPACITY=l.INVERTED_DEFAULT_COLOR=void 0;const f=u(6114);l.INVERTED_DEFAULT_COLOR=257,l.DIM_OPACITY=.5,l.TEXT_BASELINE=f.isFirefox||f.isLegacyEdge?"bottom":"ideographic"},6171:(h,l)=>{function u(v){return 57508<=v&&v<=57558}function f(v){return v>=128512&&v<=128591||v>=127744&&v<=128511||v>=128640&&v<=128767||v>=9728&&v<=9983||v>=9984&&v<=10175||v>=65024&&v<=65039||v>=129280&&v<=129535||v>=127462&&v<=127487}Object.defineProperty(l,"__esModule",{value:!0}),l.computeNextVariantOffset=l.createRenderDimensions=l.treatGlyphAsBackgroundColor=l.allowRescaling=l.isEmoji=l.isRestrictedPowerlineGlyph=l.isPowerlineGlyph=l.throwIfFalsy=void 0,l.throwIfFalsy=function(v){if(!v)throw new Error("value must not be falsy");return v},l.isPowerlineGlyph=u,l.isRestrictedPowerlineGlyph=function(v){return 57520<=v&&v<=57527},l.isEmoji=f,l.allowRescaling=function(v,g,S,w){return g===1&&S>Math.ceil(1.5*w)&&v!==void 0&&v>255&&!f(v)&&!u(v)&&!(function(E){return 57344<=E&&E<=63743})(v)},l.treatGlyphAsBackgroundColor=function(v){return u(v)||(function(g){return 9472<=g&&g<=9631})(v)},l.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},l.computeNextVariantOffset=function(v,g,S=0){return(v-(2*Math.round(g)-S))%(2*Math.round(g))}},6052:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.createSelectionRenderModel=void 0;class u{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(v,g,S,w=!1){if(this.selectionStart=g,this.selectionEnd=S,!g||!S||g[0]===S[0]&&g[1]===S[1])return void this.clear();const E=v.buffers.active.ydisp,x=g[1]-E,m=S[1]-E,y=Math.max(x,0),b=Math.min(m,v.rows-1);y>=v.rows||b<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=w,this.viewportStartRow=x,this.viewportEndRow=m,this.viewportCappedStartRow=y,this.viewportCappedEndRow=b,this.startCol=g[0],this.endCol=S[0])}isCellSelected(v,g,S){return!!this.hasSelection&&(S-=v.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?g>=this.startCol&&S>=this.viewportCappedStartRow&&g<this.endCol&&S<=this.viewportCappedEndRow:g<this.startCol&&S>=this.viewportCappedStartRow&&g>=this.endCol&&S<=this.viewportCappedEndRow:S>this.viewportStartRow&&S<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&S===this.viewportStartRow&&g>=this.startCol&&g<this.endCol||this.viewportStartRow<this.viewportEndRow&&S===this.viewportEndRow&&g<this.endCol||this.viewportStartRow<this.viewportEndRow&&S===this.viewportStartRow&&g>=this.startCol)}}l.createSelectionRenderModel=function(){return new u}},456:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.SelectionModel=void 0,l.SelectionModel=class{constructor(u){this._bufferService=u,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.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()){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?u%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)-1]:[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[u,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const u=this.selectionStart[0]+this.selectionStartLength;return u>this._bufferService.cols?[u%this._bufferService.cols,this.selectionStart[1]+Math.floor(u/this._bufferService.cols)]:[Math.max(u,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const u=this.selectionStart,f=this.selectionEnd;return!(!u||!f)&&(u[1]>f[1]||u[1]===f[1]&&u[0]>f[0])}handleTrim(u){return this.selectionStart&&(this.selectionStart[1]-=u),this.selectionEnd&&(this.selectionEnd[1]-=u),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(h,l,u){var f=this&&this.__decorate||function(b,_,k,j){var T,D=arguments.length,I=D<3?_:j===null?j=Object.getOwnPropertyDescriptor(_,k):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(b,_,k,j);else for(var L=b.length-1;L>=0;L--)(T=b[L])&&(I=(D<3?T(I):D>3?T(_,k,I):T(_,k))||I);return D>3&&I&&Object.defineProperty(_,k,I),I},v=this&&this.__param||function(b,_){return function(k,j){_(k,j,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CharSizeService=void 0;const g=u(2585),S=u(8460),w=u(844);let E=l.CharSizeService=class extends w.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(b,_,k){super(),this._optionsService=k,this.width=0,this.height=0,this._onCharSizeChange=this.register(new S.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new y(this._optionsService))}catch{this._measureStrategy=this.register(new m(b,_,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const b=this._measureStrategy.measure();b.width===this.width&&b.height===this.height||(this.width=b.width,this.height=b.height,this._onCharSizeChange.fire())}};l.CharSizeService=E=f([v(2,g.IOptionsService)],E);class x extends w.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(_,k){_!==void 0&&_>0&&k!==void 0&&k>0&&(this._result.width=_,this._result.height=k)}}class m extends x{constructor(_,k,j){super(),this._document=_,this._parentElement=k,this._optionsService=j,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}}class y extends x{constructor(_){super(),this._optionsService=_,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const k=this._ctx.measureText("W");if(!("width"in k&&"fontBoundingBoxAscent"in k&&"fontBoundingBoxDescent"in k))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const _=this._ctx.measureText("W");return this._validateAndSet(_.width,_.fontBoundingBoxAscent+_.fontBoundingBoxDescent),this._result}}},4269:function(h,l,u){var f=this&&this.__decorate||function(y,b,_,k){var j,T=arguments.length,D=T<3?b:k===null?k=Object.getOwnPropertyDescriptor(b,_):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(y,b,_,k);else for(var I=y.length-1;I>=0;I--)(j=y[I])&&(D=(T<3?j(D):T>3?j(b,_,D):j(b,_))||D);return T>3&&D&&Object.defineProperty(b,_,D),D},v=this&&this.__param||function(y,b){return function(_,k){b(_,k,y)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CharacterJoinerService=l.JoinedCellData=void 0;const g=u(3734),S=u(643),w=u(511),E=u(2585);class x extends g.AttributeData{constructor(b,_,k){super(),this.content=0,this.combinedData="",this.fg=b.fg,this.bg=b.bg,this.combinedData=_,this._width=k}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(b){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}l.JoinedCellData=x;let m=l.CharacterJoinerService=class g1{constructor(b){this._bufferService=b,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new w.CellData}register(b){const _={id:this._nextCharacterJoinerId++,handler:b};return this._characterJoiners.push(_),_.id}deregister(b){for(let _=0;_<this._characterJoiners.length;_++)if(this._characterJoiners[_].id===b)return this._characterJoiners.splice(_,1),!0;return!1}getJoinedCharacters(b){if(this._characterJoiners.length===0)return[];const _=this._bufferService.buffer.lines.get(b);if(!_||_.length===0)return[];const k=[],j=_.translateToString(!0);let T=0,D=0,I=0,L=_.getFg(0),q=_.getBg(0);for(let H=0;H<_.getTrimmedLength();H++)if(_.loadCell(H,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==L||this._workCell.bg!==q){if(H-T>1){const Q=this._getJoinedRanges(j,I,D,_,T);for(let F=0;F<Q.length;F++)k.push(Q[F])}T=H,I=D,L=this._workCell.fg,q=this._workCell.bg}D+=this._workCell.getChars().length||S.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-T>1){const H=this._getJoinedRanges(j,I,D,_,T);for(let Q=0;Q<H.length;Q++)k.push(H[Q])}return k}_getJoinedRanges(b,_,k,j,T){const D=b.substring(_,k);let I=[];try{I=this._characterJoiners[0].handler(D)}catch(L){console.error(L)}for(let L=1;L<this._characterJoiners.length;L++)try{const q=this._characterJoiners[L].handler(D);for(let H=0;H<q.length;H++)g1._mergeRanges(I,q[H])}catch(q){console.error(q)}return this._stringRangesToCellRanges(I,j,T),I}_stringRangesToCellRanges(b,_,k){let j=0,T=!1,D=0,I=b[j];if(I){for(let L=k;L<this._bufferService.cols;L++){const q=_.getWidth(L),H=_.getString(L).length||S.WHITESPACE_CELL_CHAR.length;if(q!==0){if(!T&&I[0]<=D&&(I[0]=L,T=!0),I[1]<=D){if(I[1]=L,I=b[++j],!I)break;I[0]<=D?(I[0]=L,T=!0):T=!1}D+=H}}I&&(I[1]=this._bufferService.cols)}}static _mergeRanges(b,_){let k=!1;for(let j=0;j<b.length;j++){const T=b[j];if(k){if(_[1]<=T[0])return b[j-1][1]=_[1],b;if(_[1]<=T[1])return b[j-1][1]=Math.max(_[1],T[1]),b.splice(j,1),b;b.splice(j,1),j--}else{if(_[1]<=T[0])return b.splice(j,0,_),b;if(_[1]<=T[1])return T[0]=Math.min(_[0],T[0]),b;_[0]<T[1]&&(T[0]=Math.min(_[0],T[0]),k=!0)}}return k?b[b.length-1][1]=_[1]:b.push(_),b}};l.CharacterJoinerService=m=f([v(0,E.IBufferService)],m)},5114:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CoreBrowserService=void 0;const f=u(844),v=u(8460),g=u(3656);class S extends f.Disposable{constructor(x,m,y){super(),this._textarea=x,this._window=m,this.mainDocument=y,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new w(this._window),this._onDprChange=this.register(new v.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new v.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange((b=>this._screenDprMonitor.setWindow(b)))),this.register((0,v.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",(()=>this._isFocused=!0)),this._textarea.addEventListener("blur",(()=>this._isFocused=!1))}get window(){return this._window}set window(x){this._window!==x&&(this._window=x,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}}l.CoreBrowserService=S;class w extends f.Disposable{constructor(x){super(),this._parentWindow=x,this._windowResizeListener=this.register(new f.MutableDisposable),this._onDprChange=this.register(new v.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,f.toDisposable)((()=>this.clearListener())))}setWindow(x){this._parentWindow=x,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,g.addDisposableDomListener)(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)}}},779:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.LinkProviderService=void 0;const f=u(844);class v extends f.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,f.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(S){return this.linkProviders.push(S),{dispose:()=>{const w=this.linkProviders.indexOf(S);w!==-1&&this.linkProviders.splice(w,1)}}}}l.LinkProviderService=v},8934:function(h,l,u){var f=this&&this.__decorate||function(E,x,m,y){var b,_=arguments.length,k=_<3?x:y===null?y=Object.getOwnPropertyDescriptor(x,m):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(E,x,m,y);else for(var j=E.length-1;j>=0;j--)(b=E[j])&&(k=(_<3?b(k):_>3?b(x,m,k):b(x,m))||k);return _>3&&k&&Object.defineProperty(x,m,k),k},v=this&&this.__param||function(E,x){return function(m,y){x(m,y,E)}};Object.defineProperty(l,"__esModule",{value:!0}),l.MouseService=void 0;const g=u(4725),S=u(9806);let w=l.MouseService=class{constructor(E,x){this._renderService=E,this._charSizeService=x}getCoords(E,x,m,y,b){return(0,S.getCoords)(window,E,x,m,y,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,b)}getMouseReportCoords(E,x){const m=(0,S.getCoordsRelativeToElement)(window,E,x);if(this._charSizeService.hasValidSize)return m[0]=Math.min(Math.max(m[0],0),this._renderService.dimensions.css.canvas.width-1),m[1]=Math.min(Math.max(m[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(m[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(m[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(m[0]),y:Math.floor(m[1])}}};l.MouseService=w=f([v(0,g.IRenderService),v(1,g.ICharSizeService)],w)},3230:function(h,l,u){var f=this&&this.__decorate||function(b,_,k,j){var T,D=arguments.length,I=D<3?_:j===null?j=Object.getOwnPropertyDescriptor(_,k):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(b,_,k,j);else for(var L=b.length-1;L>=0;L--)(T=b[L])&&(I=(D<3?T(I):D>3?T(_,k,I):T(_,k))||I);return D>3&&I&&Object.defineProperty(_,k,I),I},v=this&&this.__param||function(b,_){return function(k,j){_(k,j,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.RenderService=void 0;const g=u(6193),S=u(4725),w=u(8460),E=u(844),x=u(7226),m=u(2585);let y=l.RenderService=class extends E.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(b,_,k,j,T,D,I,L){super(),this._rowCount=b,this._charSizeService=j,this._renderer=this.register(new E.MutableDisposable),this._pausedResizeTask=new x.DebouncedIdleTask,this._observerDisposable=this.register(new E.MutableDisposable),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 w.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new w.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new w.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new w.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new g.RenderDebouncer(((q,H)=>this._renderRows(q,H)),I),this.register(this._renderDebouncer),this.register(I.onDprChange((()=>this.handleDevicePixelRatioChange()))),this.register(D.onResize((()=>this._fullRefresh()))),this.register(D.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this.register(k.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this.register(T.onDecorationRegistered((()=>this._fullRefresh()))),this.register(T.onDecorationRemoved((()=>this._fullRefresh()))),this.register(k.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(D.cols,D.rows),this._fullRefresh()}))),this.register(k.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(D.buffer.y,D.buffer.y,!0)))),this.register(L.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(I.window,_),this.register(I.onWindowChange((q=>this._registerIntersectionObserver(q,_))))}_registerIntersectionObserver(b,_){if("IntersectionObserver"in b){const k=new b.IntersectionObserver((j=>this._handleIntersectionChange(j[j.length-1])),{threshold:0});k.observe(_),this._observerDisposable.value=(0,E.toDisposable)((()=>k.disconnect()))}}_handleIntersectionChange(b){this._isPaused=b.isIntersecting===void 0?b.intersectionRatio===0:!b.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(b,_,k=!1){this._isPaused?this._needsFullRefresh=!0:(k||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(b,_,this._rowCount))}_renderRows(b,_){this._renderer.value&&(b=Math.min(b,this._rowCount-1),_=Math.min(_,this._rowCount-1),this._renderer.value.renderRows(b,_),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:b,end:_}),this._onRender.fire({start:b,end:_}),this._isNextRenderRedrawOnly=!0)}resize(b,_){this._rowCount=_,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(b){this._renderer.value=b,this._renderer.value&&(this._renderer.value.onRequestRedraw((_=>this.refreshRows(_.start,_.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(b){return this._renderDebouncer.addRefreshCallback(b)}_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(b,_){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(b,_))):this._renderer.value.handleResize(b,_),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(b,_,k){this._selectionState.start=b,this._selectionState.end=_,this._selectionState.columnSelectMode=k,this._renderer.value?.handleSelectionChanged(b,_,k)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};l.RenderService=y=f([v(2,m.IOptionsService),v(3,S.ICharSizeService),v(4,m.IDecorationService),v(5,m.IBufferService),v(6,S.ICoreBrowserService),v(7,S.IThemeService)],y)},9312:function(h,l,u){var f=this&&this.__decorate||function(I,L,q,H){var Q,F=arguments.length,J=F<3?L:H===null?H=Object.getOwnPropertyDescriptor(L,q):H;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")J=Reflect.decorate(I,L,q,H);else for(var ie=I.length-1;ie>=0;ie--)(Q=I[ie])&&(J=(F<3?Q(J):F>3?Q(L,q,J):Q(L,q))||J);return F>3&&J&&Object.defineProperty(L,q,J),J},v=this&&this.__param||function(I,L){return function(q,H){L(q,H,I)}};Object.defineProperty(l,"__esModule",{value:!0}),l.SelectionService=void 0;const g=u(9806),S=u(9504),w=u(456),E=u(4725),x=u(8460),m=u(844),y=u(6114),b=u(4841),_=u(511),k=u(2585),j=" ",T=new RegExp(j,"g");let D=l.SelectionService=class extends m.Disposable{constructor(I,L,q,H,Q,F,J,ie,X){super(),this._element=I,this._screenElement=L,this._linkifier=q,this._bufferService=H,this._coreService=Q,this._mouseService=F,this._optionsService=J,this._renderService=ie,this._coreBrowserService=X,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new _.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new x.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new x.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new x.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new x.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=de=>this._handleMouseMove(de),this._mouseUpListener=de=>this._handleMouseUp(de),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((de=>this._handleTrim(de))),this.register(this._bufferService.buffers.onBufferActivate((de=>this._handleBufferActivate(de)))),this.enable(),this._model=new w.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,m.toDisposable)((()=>{this._removeMouseDownListeners()})))}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(){const I=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!(!I||!L||I[0]===L[0]&&I[1]===L[1])}get selectionText(){const I=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;if(!I||!L)return"";const q=this._bufferService.buffer,H=[];if(this._activeSelectionMode===3){if(I[0]===L[0])return"";const Q=I[0]<L[0]?I[0]:L[0],F=I[0]<L[0]?L[0]:I[0];for(let J=I[1];J<=L[1];J++){const ie=q.translateBufferLineToString(J,!0,Q,F);H.push(ie)}}else{const Q=I[1]===L[1]?L[0]:void 0;H.push(q.translateBufferLineToString(I[1],!0,I[0],Q));for(let F=I[1]+1;F<=L[1]-1;F++){const J=q.lines.get(F),ie=q.translateBufferLineToString(F,!0);J?.isWrapped?H[H.length-1]+=ie:H.push(ie)}if(I[1]!==L[1]){const F=q.lines.get(L[1]),J=q.translateBufferLineToString(L[1],!0,0,L[0]);F&&F.isWrapped?H[H.length-1]+=J:H.push(J)}}return H.map((Q=>Q.replace(T," "))).join(y.isWindows?`\r
|
|
83
|
-
`:`
|
|
84
|
-
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(I){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),y.isLinux&&I&&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(I){const L=this._getMouseBufferCoords(I),q=this._model.finalSelectionStart,H=this._model.finalSelectionEnd;return!!(q&&H&&L)&&this._areCoordsInSelection(L,q,H)}isCellInSelection(I,L){const q=this._model.finalSelectionStart,H=this._model.finalSelectionEnd;return!(!q||!H)&&this._areCoordsInSelection([I,L],q,H)}_areCoordsInSelection(I,L,q){return I[1]>L[1]&&I[1]<q[1]||L[1]===q[1]&&I[1]===L[1]&&I[0]>=L[0]&&I[0]<q[0]||L[1]<q[1]&&I[1]===q[1]&&I[0]<q[0]||L[1]<q[1]&&I[1]===L[1]&&I[0]>=L[0]}_selectWordAtCursor(I,L){const q=this._linkifier.currentLink?.link?.range;if(q)return this._model.selectionStart=[q.start.x-1,q.start.y-1],this._model.selectionStartLength=(0,b.getRangeLength)(q,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const H=this._getMouseBufferCoords(I);return!!H&&(this._selectWordAt(H,L),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(I,L){this._model.clearSelection(),I=Math.max(I,0),L=Math.min(L,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,I],this._model.selectionEnd=[this._bufferService.cols,L],this.refresh(),this._onSelectionChange.fire()}_handleTrim(I){this._model.handleTrim(I)&&this.refresh()}_getMouseBufferCoords(I){const L=this._mouseService.getCoords(I,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(L)return L[0]--,L[1]--,L[1]+=this._bufferService.buffer.ydisp,L}_getMouseEventScrollAmount(I){let L=(0,g.getCoordsRelativeToElement)(this._coreBrowserService.window,I,this._screenElement)[1];const q=this._renderService.dimensions.css.canvas.height;return L>=0&&L<=q?0:(L>q&&(L-=q),L=Math.min(Math.max(L,-50),50),L/=50,L/Math.abs(L)+Math.round(14*L))}shouldForceSelection(I){return y.isMac?I.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:I.shiftKey}handleMouseDown(I){if(this._mouseDownTimeStamp=I.timeStamp,(I.button!==2||!this.hasSelection)&&I.button===0){if(!this._enabled){if(!this.shouldForceSelection(I))return;I.stopPropagation()}I.preventDefault(),this._dragScrollAmount=0,this._enabled&&I.shiftKey?this._handleIncrementalClick(I):I.detail===1?this._handleSingleClick(I):I.detail===2?this._handleDoubleClick(I):I.detail===3&&this._handleTripleClick(I),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()),50)}_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(I){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(I))}_handleSingleClick(I){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(I)?3:0,this._model.selectionStart=this._getMouseBufferCoords(I),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const L=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);L&&L.length!==this._model.selectionStart[0]&&L.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(I){this._selectWordAtCursor(I,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(I){const L=this._getMouseBufferCoords(I);L&&(this._activeSelectionMode=2,this._selectLineAt(L[1]))}shouldColumnSelect(I){return I.altKey&&!(y.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(I){if(I.stopImmediatePropagation(),!this._model.selectionStart)return;const L=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(I),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(I),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const q=this._bufferService.buffer;if(this._model.selectionEnd[1]<q.lines.length){const H=q.lines.get(this._model.selectionEnd[1]);H&&H.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}L&&L[0]===this._model.selectionEnd[0]&&L[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const I=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(I.ydisp+this._bufferService.rows,I.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=I.ydisp),this.refresh()}}_handleMouseUp(I){const L=I.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&L<500&&I.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const q=this._mouseService.getCoords(I,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(q&&q[0]!==void 0&&q[1]!==void 0){const H=(0,S.moveToCellSequence)(q[0]-1,q[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(H,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const I=this._model.finalSelectionStart,L=this._model.finalSelectionEnd,q=!(!I||!L||I[0]===L[0]&&I[1]===L[1]);q?I&&L&&(this._oldSelectionStart&&this._oldSelectionEnd&&I[0]===this._oldSelectionStart[0]&&I[1]===this._oldSelectionStart[1]&&L[0]===this._oldSelectionEnd[0]&&L[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(I,L,q)):this._oldHasSelection&&this._fireOnSelectionChange(I,L,q)}_fireOnSelectionChange(I,L,q){this._oldSelectionStart=I,this._oldSelectionEnd=L,this._oldHasSelection=q,this._onSelectionChange.fire()}_handleBufferActivate(I){this.clearSelection(),this._trimListener.dispose(),this._trimListener=I.activeBuffer.lines.onTrim((L=>this._handleTrim(L)))}_convertViewportColToCharacterIndex(I,L){let q=L;for(let H=0;L>=H;H++){const Q=I.loadCell(H,this._workCell).getChars().length;this._workCell.getWidth()===0?q--:Q>1&&L!==H&&(q+=Q-1)}return q}setSelection(I,L,q){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[I,L],this._model.selectionStartLength=q,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(I){this._isClickInSelection(I)||(this._selectWordAtCursor(I,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(I,L,q=!0,H=!0){if(I[0]>=this._bufferService.cols)return;const Q=this._bufferService.buffer,F=Q.lines.get(I[1]);if(!F)return;const J=Q.translateBufferLineToString(I[1],!1);let ie=this._convertViewportColToCharacterIndex(F,I[0]),X=ie;const de=I[0]-ie;let fe=0,$=0,P=0,B=0;if(J.charAt(ie)===" "){for(;ie>0&&J.charAt(ie-1)===" ";)ie--;for(;X<J.length&&J.charAt(X+1)===" ";)X++}else{let me=I[0],be=I[0];F.getWidth(me)===0&&(fe++,me--),F.getWidth(be)===2&&($++,be++);const Ee=F.getString(be).length;for(Ee>1&&(B+=Ee-1,X+=Ee-1);me>0&&ie>0&&!this._isCharWordSeparator(F.loadCell(me-1,this._workCell));){F.loadCell(me-1,this._workCell);const se=this._workCell.getChars().length;this._workCell.getWidth()===0?(fe++,me--):se>1&&(P+=se-1,ie-=se-1),ie--,me--}for(;be<F.length&&X+1<J.length&&!this._isCharWordSeparator(F.loadCell(be+1,this._workCell));){F.loadCell(be+1,this._workCell);const se=this._workCell.getChars().length;this._workCell.getWidth()===2?($++,be++):se>1&&(B+=se-1,X+=se-1),X++,be++}}X++;let K=ie+de-fe+P,le=Math.min(this._bufferService.cols,X-ie+fe+$-P-B);if(L||J.slice(ie,X).trim()!==""){if(q&&K===0&&F.getCodePoint(0)!==32){const me=Q.lines.get(I[1]-1);if(me&&F.isWrapped&&me.getCodePoint(this._bufferService.cols-1)!==32){const be=this._getWordAt([this._bufferService.cols-1,I[1]-1],!1,!0,!1);if(be){const Ee=this._bufferService.cols-be.start;K-=Ee,le+=Ee}}}if(H&&K+le===this._bufferService.cols&&F.getCodePoint(this._bufferService.cols-1)!==32){const me=Q.lines.get(I[1]+1);if(me?.isWrapped&&me.getCodePoint(0)!==32){const be=this._getWordAt([0,I[1]+1],!1,!1,!0);be&&(le+=be.length)}}return{start:K,length:le}}}_selectWordAt(I,L){const q=this._getWordAt(I,L);if(q){for(;q.start<0;)q.start+=this._bufferService.cols,I[1]--;this._model.selectionStart=[q.start,I[1]],this._model.selectionStartLength=q.length}}_selectToWordAt(I){const L=this._getWordAt(I,!0);if(L){let q=I[1];for(;L.start<0;)L.start+=this._bufferService.cols,q--;if(!this._model.areSelectionValuesReversed())for(;L.start+L.length>this._bufferService.cols;)L.length-=this._bufferService.cols,q++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?L.start:L.start+L.length,q]}}_isCharWordSeparator(I){return I.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(I.getChars())>=0}_selectLineAt(I){const L=this._bufferService.buffer.getWrappedRangeForLine(I),q={start:{x:0,y:L.first},end:{x:this._bufferService.cols-1,y:L.last}};this._model.selectionStart=[0,L.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,b.getRangeLength)(q,this._bufferService.cols)}};l.SelectionService=D=f([v(3,k.IBufferService),v(4,k.ICoreService),v(5,E.IMouseService),v(6,k.IOptionsService),v(7,E.IRenderService),v(8,E.ICoreBrowserService)],D)},4725:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ILinkProviderService=l.IThemeService=l.ICharacterJoinerService=l.ISelectionService=l.IRenderService=l.IMouseService=l.ICoreBrowserService=l.ICharSizeService=void 0;const f=u(8343);l.ICharSizeService=(0,f.createDecorator)("CharSizeService"),l.ICoreBrowserService=(0,f.createDecorator)("CoreBrowserService"),l.IMouseService=(0,f.createDecorator)("MouseService"),l.IRenderService=(0,f.createDecorator)("RenderService"),l.ISelectionService=(0,f.createDecorator)("SelectionService"),l.ICharacterJoinerService=(0,f.createDecorator)("CharacterJoinerService"),l.IThemeService=(0,f.createDecorator)("ThemeService"),l.ILinkProviderService=(0,f.createDecorator)("LinkProviderService")},6731:function(h,l,u){var f=this&&this.__decorate||function(D,I,L,q){var H,Q=arguments.length,F=Q<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,L):q;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")F=Reflect.decorate(D,I,L,q);else for(var J=D.length-1;J>=0;J--)(H=D[J])&&(F=(Q<3?H(F):Q>3?H(I,L,F):H(I,L))||F);return Q>3&&F&&Object.defineProperty(I,L,F),F},v=this&&this.__param||function(D,I){return function(L,q){I(L,q,D)}};Object.defineProperty(l,"__esModule",{value:!0}),l.ThemeService=l.DEFAULT_ANSI_COLORS=void 0;const g=u(7239),S=u(8055),w=u(8460),E=u(844),x=u(2585),m=S.css.toColor("#ffffff"),y=S.css.toColor("#000000"),b=S.css.toColor("#ffffff"),_=S.css.toColor("#000000"),k={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};l.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const D=[S.css.toColor("#2e3436"),S.css.toColor("#cc0000"),S.css.toColor("#4e9a06"),S.css.toColor("#c4a000"),S.css.toColor("#3465a4"),S.css.toColor("#75507b"),S.css.toColor("#06989a"),S.css.toColor("#d3d7cf"),S.css.toColor("#555753"),S.css.toColor("#ef2929"),S.css.toColor("#8ae234"),S.css.toColor("#fce94f"),S.css.toColor("#729fcf"),S.css.toColor("#ad7fa8"),S.css.toColor("#34e2e2"),S.css.toColor("#eeeeec")],I=[0,95,135,175,215,255];for(let L=0;L<216;L++){const q=I[L/36%6|0],H=I[L/6%6|0],Q=I[L%6];D.push({css:S.channels.toCss(q,H,Q),rgba:S.channels.toRgba(q,H,Q)})}for(let L=0;L<24;L++){const q=8+10*L;D.push({css:S.channels.toCss(q,q,q),rgba:S.channels.toRgba(q,q,q)})}return D})());let j=l.ThemeService=class extends E.Disposable{get colors(){return this._colors}constructor(D){super(),this._optionsService=D,this._contrastCache=new g.ColorContrastCache,this._halfContrastCache=new g.ColorContrastCache,this._onChangeColors=this.register(new w.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:m,background:y,cursor:b,cursorAccent:_,selectionForeground:void 0,selectionBackgroundTransparent:k,selectionBackgroundOpaque:S.color.blend(y,k),selectionInactiveBackgroundTransparent:k,selectionInactiveBackgroundOpaque:S.color.blend(y,k),ansi:l.DEFAULT_ANSI_COLORS.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))))}_setTheme(D={}){const I=this._colors;if(I.foreground=T(D.foreground,m),I.background=T(D.background,y),I.cursor=T(D.cursor,b),I.cursorAccent=T(D.cursorAccent,_),I.selectionBackgroundTransparent=T(D.selectionBackground,k),I.selectionBackgroundOpaque=S.color.blend(I.background,I.selectionBackgroundTransparent),I.selectionInactiveBackgroundTransparent=T(D.selectionInactiveBackground,I.selectionBackgroundTransparent),I.selectionInactiveBackgroundOpaque=S.color.blend(I.background,I.selectionInactiveBackgroundTransparent),I.selectionForeground=D.selectionForeground?T(D.selectionForeground,S.NULL_COLOR):void 0,I.selectionForeground===S.NULL_COLOR&&(I.selectionForeground=void 0),S.color.isOpaque(I.selectionBackgroundTransparent)&&(I.selectionBackgroundTransparent=S.color.opacity(I.selectionBackgroundTransparent,.3)),S.color.isOpaque(I.selectionInactiveBackgroundTransparent)&&(I.selectionInactiveBackgroundTransparent=S.color.opacity(I.selectionInactiveBackgroundTransparent,.3)),I.ansi=l.DEFAULT_ANSI_COLORS.slice(),I.ansi[0]=T(D.black,l.DEFAULT_ANSI_COLORS[0]),I.ansi[1]=T(D.red,l.DEFAULT_ANSI_COLORS[1]),I.ansi[2]=T(D.green,l.DEFAULT_ANSI_COLORS[2]),I.ansi[3]=T(D.yellow,l.DEFAULT_ANSI_COLORS[3]),I.ansi[4]=T(D.blue,l.DEFAULT_ANSI_COLORS[4]),I.ansi[5]=T(D.magenta,l.DEFAULT_ANSI_COLORS[5]),I.ansi[6]=T(D.cyan,l.DEFAULT_ANSI_COLORS[6]),I.ansi[7]=T(D.white,l.DEFAULT_ANSI_COLORS[7]),I.ansi[8]=T(D.brightBlack,l.DEFAULT_ANSI_COLORS[8]),I.ansi[9]=T(D.brightRed,l.DEFAULT_ANSI_COLORS[9]),I.ansi[10]=T(D.brightGreen,l.DEFAULT_ANSI_COLORS[10]),I.ansi[11]=T(D.brightYellow,l.DEFAULT_ANSI_COLORS[11]),I.ansi[12]=T(D.brightBlue,l.DEFAULT_ANSI_COLORS[12]),I.ansi[13]=T(D.brightMagenta,l.DEFAULT_ANSI_COLORS[13]),I.ansi[14]=T(D.brightCyan,l.DEFAULT_ANSI_COLORS[14]),I.ansi[15]=T(D.brightWhite,l.DEFAULT_ANSI_COLORS[15]),D.extendedAnsi){const L=Math.min(I.ansi.length-16,D.extendedAnsi.length);for(let q=0;q<L;q++)I.ansi[q+16]=T(D.extendedAnsi[q],l.DEFAULT_ANSI_COLORS[q+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(D){this._restoreColor(D),this._onChangeColors.fire(this.colors)}_restoreColor(D){if(D!==void 0)switch(D){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[D]=this._restoreColors.ansi[D]}else for(let I=0;I<this._restoreColors.ansi.length;++I)this._colors.ansi[I]=this._restoreColors.ansi[I]}modifyColors(D){D(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function T(D,I){if(D!==void 0)try{return S.css.toColor(D)}catch{}return I}l.ThemeService=j=f([v(0,x.IOptionsService)],j)},6349:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CircularList=void 0;const f=u(8460),v=u(844);class g extends v.Disposable{constructor(w){super(),this._maxLength=w,this.onDeleteEmitter=this.register(new f.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new f.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new f.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(w){if(this._maxLength===w)return;const E=new Array(w);for(let x=0;x<Math.min(w,this.length);x++)E[x]=this._array[this._getCyclicIndex(x)];this._array=E,this._maxLength=w,this._startIndex=0}get length(){return this._length}set length(w){if(w>this._length)for(let E=this._length;E<w;E++)this._array[E]=void 0;this._length=w}get(w){return this._array[this._getCyclicIndex(w)]}set(w,E){this._array[this._getCyclicIndex(w)]=E}push(w){this._array[this._getCyclicIndex(this._length)]=w,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(w,E,...x){if(E){for(let m=w;m<this._length-E;m++)this._array[this._getCyclicIndex(m)]=this._array[this._getCyclicIndex(m+E)];this._length-=E,this.onDeleteEmitter.fire({index:w,amount:E})}for(let m=this._length-1;m>=w;m--)this._array[this._getCyclicIndex(m+x.length)]=this._array[this._getCyclicIndex(m)];for(let m=0;m<x.length;m++)this._array[this._getCyclicIndex(w+m)]=x[m];if(x.length&&this.onInsertEmitter.fire({index:w,amount:x.length}),this._length+x.length>this._maxLength){const m=this._length+x.length-this._maxLength;this._startIndex+=m,this._length=this._maxLength,this.onTrimEmitter.fire(m)}else this._length+=x.length}trimStart(w){w>this._length&&(w=this._length),this._startIndex+=w,this._length-=w,this.onTrimEmitter.fire(w)}shiftElements(w,E,x){if(!(E<=0)){if(w<0||w>=this._length)throw new Error("start argument out of range");if(w+x<0)throw new Error("Cannot shift elements in list beyond index 0");if(x>0){for(let y=E-1;y>=0;y--)this.set(w+y+x,this.get(w+y));const m=w+E+x-this._length;if(m>0)for(this._length+=m;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let m=0;m<E;m++)this.set(w+m+x,this.get(w+m))}}_getCyclicIndex(w){return(this._startIndex+w)%this._maxLength}}l.CircularList=g},1439:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.clone=void 0,l.clone=function u(f,v=5){if(typeof f!="object")return f;const g=Array.isArray(f)?[]:{};for(const S in f)g[S]=v<=1?f[S]:f[S]&&u(f[S],v-1);return g}},8055:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.contrastRatio=l.toPaddedHex=l.rgba=l.rgb=l.css=l.color=l.channels=l.NULL_COLOR=void 0;let u=0,f=0,v=0,g=0;var S,w,E,x,m;function y(_){const k=_.toString(16);return k.length<2?"0"+k:k}function b(_,k){return _<k?(k+.05)/(_+.05):(_+.05)/(k+.05)}l.NULL_COLOR={css:"#00000000",rgba:0},(function(_){_.toCss=function(k,j,T,D){return D!==void 0?`#${y(k)}${y(j)}${y(T)}${y(D)}`:`#${y(k)}${y(j)}${y(T)}`},_.toRgba=function(k,j,T,D=255){return(k<<24|j<<16|T<<8|D)>>>0},_.toColor=function(k,j,T,D){return{css:_.toCss(k,j,T,D),rgba:_.toRgba(k,j,T,D)}}})(S||(l.channels=S={})),(function(_){function k(j,T){return g=Math.round(255*T),[u,f,v]=m.toChannels(j.rgba),{css:S.toCss(u,f,v,g),rgba:S.toRgba(u,f,v,g)}}_.blend=function(j,T){if(g=(255&T.rgba)/255,g===1)return{css:T.css,rgba:T.rgba};const D=T.rgba>>24&255,I=T.rgba>>16&255,L=T.rgba>>8&255,q=j.rgba>>24&255,H=j.rgba>>16&255,Q=j.rgba>>8&255;return u=q+Math.round((D-q)*g),f=H+Math.round((I-H)*g),v=Q+Math.round((L-Q)*g),{css:S.toCss(u,f,v),rgba:S.toRgba(u,f,v)}},_.isOpaque=function(j){return(255&j.rgba)==255},_.ensureContrastRatio=function(j,T,D){const I=m.ensureContrastRatio(j.rgba,T.rgba,D);if(I)return S.toColor(I>>24&255,I>>16&255,I>>8&255)},_.opaque=function(j){const T=(255|j.rgba)>>>0;return[u,f,v]=m.toChannels(T),{css:S.toCss(u,f,v),rgba:T}},_.opacity=k,_.multiplyOpacity=function(j,T){return g=255&j.rgba,k(j,g*T/255)},_.toColorRGB=function(j){return[j.rgba>>24&255,j.rgba>>16&255,j.rgba>>8&255]}})(w||(l.color=w={})),(function(_){let k,j;try{const T=document.createElement("canvas");T.width=1,T.height=1;const D=T.getContext("2d",{willReadFrequently:!0});D&&(k=D,k.globalCompositeOperation="copy",j=k.createLinearGradient(0,0,1,1))}catch{}_.toColor=function(T){if(T.match(/#[\da-f]{3,8}/i))switch(T.length){case 4:return u=parseInt(T.slice(1,2).repeat(2),16),f=parseInt(T.slice(2,3).repeat(2),16),v=parseInt(T.slice(3,4).repeat(2),16),S.toColor(u,f,v);case 5:return u=parseInt(T.slice(1,2).repeat(2),16),f=parseInt(T.slice(2,3).repeat(2),16),v=parseInt(T.slice(3,4).repeat(2),16),g=parseInt(T.slice(4,5).repeat(2),16),S.toColor(u,f,v,g);case 7:return{css:T,rgba:(parseInt(T.slice(1),16)<<8|255)>>>0};case 9:return{css:T,rgba:parseInt(T.slice(1),16)>>>0}}const D=T.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(D)return u=parseInt(D[1]),f=parseInt(D[2]),v=parseInt(D[3]),g=Math.round(255*(D[5]===void 0?1:parseFloat(D[5]))),S.toColor(u,f,v,g);if(!k||!j)throw new Error("css.toColor: Unsupported css format");if(k.fillStyle=j,k.fillStyle=T,typeof k.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(k.fillRect(0,0,1,1),[u,f,v,g]=k.getImageData(0,0,1,1).data,g!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:S.toRgba(u,f,v,g),css:T}}})(E||(l.css=E={})),(function(_){function k(j,T,D){const I=j/255,L=T/255,q=D/255;return .2126*(I<=.03928?I/12.92:Math.pow((I+.055)/1.055,2.4))+.7152*(L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4))+.0722*(q<=.03928?q/12.92:Math.pow((q+.055)/1.055,2.4))}_.relativeLuminance=function(j){return k(j>>16&255,j>>8&255,255&j)},_.relativeLuminance2=k})(x||(l.rgb=x={})),(function(_){function k(T,D,I){const L=T>>24&255,q=T>>16&255,H=T>>8&255;let Q=D>>24&255,F=D>>16&255,J=D>>8&255,ie=b(x.relativeLuminance2(Q,F,J),x.relativeLuminance2(L,q,H));for(;ie<I&&(Q>0||F>0||J>0);)Q-=Math.max(0,Math.ceil(.1*Q)),F-=Math.max(0,Math.ceil(.1*F)),J-=Math.max(0,Math.ceil(.1*J)),ie=b(x.relativeLuminance2(Q,F,J),x.relativeLuminance2(L,q,H));return(Q<<24|F<<16|J<<8|255)>>>0}function j(T,D,I){const L=T>>24&255,q=T>>16&255,H=T>>8&255;let Q=D>>24&255,F=D>>16&255,J=D>>8&255,ie=b(x.relativeLuminance2(Q,F,J),x.relativeLuminance2(L,q,H));for(;ie<I&&(Q<255||F<255||J<255);)Q=Math.min(255,Q+Math.ceil(.1*(255-Q))),F=Math.min(255,F+Math.ceil(.1*(255-F))),J=Math.min(255,J+Math.ceil(.1*(255-J))),ie=b(x.relativeLuminance2(Q,F,J),x.relativeLuminance2(L,q,H));return(Q<<24|F<<16|J<<8|255)>>>0}_.blend=function(T,D){if(g=(255&D)/255,g===1)return D;const I=D>>24&255,L=D>>16&255,q=D>>8&255,H=T>>24&255,Q=T>>16&255,F=T>>8&255;return u=H+Math.round((I-H)*g),f=Q+Math.round((L-Q)*g),v=F+Math.round((q-F)*g),S.toRgba(u,f,v)},_.ensureContrastRatio=function(T,D,I){const L=x.relativeLuminance(T>>8),q=x.relativeLuminance(D>>8);if(b(L,q)<I){if(q<L){const F=k(T,D,I),J=b(L,x.relativeLuminance(F>>8));if(J<I){const ie=j(T,D,I);return J>b(L,x.relativeLuminance(ie>>8))?F:ie}return F}const H=j(T,D,I),Q=b(L,x.relativeLuminance(H>>8));if(Q<I){const F=k(T,D,I);return Q>b(L,x.relativeLuminance(F>>8))?H:F}return H}},_.reduceLuminance=k,_.increaseLuminance=j,_.toChannels=function(T){return[T>>24&255,T>>16&255,T>>8&255,255&T]}})(m||(l.rgba=m={})),l.toPaddedHex=y,l.contrastRatio=b},8969:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CoreTerminal=void 0;const f=u(844),v=u(2585),g=u(4348),S=u(7866),w=u(744),E=u(7302),x=u(6975),m=u(8460),y=u(1753),b=u(1480),_=u(7994),k=u(9282),j=u(5435),T=u(5981),D=u(2660);let I=!1;class L extends f.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new m.EventEmitter),this._onScroll.event((H=>{this._onScrollApi?.fire(H.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(H){for(const Q in H)this.optionsService.options[Q]=H[Q]}constructor(H){super(),this._windowsWrappingHeuristics=this.register(new f.MutableDisposable),this._onBinary=this.register(new m.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new m.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new m.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new m.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new m.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new m.EventEmitter),this._instantiationService=new g.InstantiationService,this.optionsService=this.register(new E.OptionsService(H)),this._instantiationService.setService(v.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(w.BufferService)),this._instantiationService.setService(v.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(S.LogService)),this._instantiationService.setService(v.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(x.CoreService)),this._instantiationService.setService(v.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(y.CoreMouseService)),this._instantiationService.setService(v.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(b.UnicodeService)),this._instantiationService.setService(v.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(_.CharsetService),this._instantiationService.setService(v.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(D.OscLinkService),this._instantiationService.setService(v.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new j.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,m.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,m.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,m.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,m.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((Q=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((Q=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new T.WriteBuffer(((Q,F)=>this._inputHandler.parse(Q,F)))),this.register((0,m.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(H,Q){this._writeBuffer.write(H,Q)}writeSync(H,Q){this._logService.logLevel<=v.LogLevelEnum.WARN&&!I&&(this._logService.warn("writeSync is unreliable and will be removed soon."),I=!0),this._writeBuffer.writeSync(H,Q)}input(H,Q=!0){this.coreService.triggerDataEvent(H,Q)}resize(H,Q){isNaN(H)||isNaN(Q)||(H=Math.max(H,w.MINIMUM_COLS),Q=Math.max(Q,w.MINIMUM_ROWS),this._bufferService.resize(H,Q))}scroll(H,Q=!1){this._bufferService.scroll(H,Q)}scrollLines(H,Q,F){this._bufferService.scrollLines(H,Q,F)}scrollPages(H){this.scrollLines(H*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(H){const Q=H-this._bufferService.buffer.ydisp;Q!==0&&this.scrollLines(Q)}registerEscHandler(H,Q){return this._inputHandler.registerEscHandler(H,Q)}registerDcsHandler(H,Q){return this._inputHandler.registerDcsHandler(H,Q)}registerCsiHandler(H,Q){return this._inputHandler.registerCsiHandler(H,Q)}registerOscHandler(H,Q){return this._inputHandler.registerOscHandler(H,Q)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let H=!1;const Q=this.optionsService.rawOptions.windowsPty;Q&&Q.buildNumber!==void 0&&Q.buildNumber!==void 0?H=Q.backend==="conpty"&&Q.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(H=!0),H?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const H=[];H.push(this.onLineFeed(k.updateWindowsModeWrappedState.bind(null,this._bufferService))),H.push(this.registerCsiHandler({final:"H"},(()=>((0,k.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,f.toDisposable)((()=>{for(const Q of H)Q.dispose()}))}}}l.CoreTerminal=L},8460:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.runAndSubscribe=l.forwardEvent=l.EventEmitter=void 0,l.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=u=>(this._listeners.push(u),{dispose:()=>{if(!this._disposed){for(let f=0;f<this._listeners.length;f++)if(this._listeners[f]===u)return void this._listeners.splice(f,1)}}})),this._event}fire(u,f){const v=[];for(let g=0;g<this._listeners.length;g++)v.push(this._listeners[g]);for(let g=0;g<v.length;g++)v[g].call(void 0,u,f)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},l.forwardEvent=function(u,f){return u((v=>f.fire(v)))},l.runAndSubscribe=function(u,f){return f(void 0),u((v=>f(v)))}},5435:function(h,l,u){var f=this&&this.__decorate||function(fe,$,P,B){var K,le=arguments.length,me=le<3?$:B===null?B=Object.getOwnPropertyDescriptor($,P):B;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")me=Reflect.decorate(fe,$,P,B);else for(var be=fe.length-1;be>=0;be--)(K=fe[be])&&(me=(le<3?K(me):le>3?K($,P,me):K($,P))||me);return le>3&&me&&Object.defineProperty($,P,me),me},v=this&&this.__param||function(fe,$){return function(P,B){$(P,B,fe)}};Object.defineProperty(l,"__esModule",{value:!0}),l.InputHandler=l.WindowsOptionsReportType=void 0;const g=u(2584),S=u(7116),w=u(2015),E=u(844),x=u(482),m=u(8437),y=u(8460),b=u(643),_=u(511),k=u(3734),j=u(2585),T=u(1480),D=u(6242),I=u(6351),L=u(5941),q={"(":0,")":1,"*":2,"+":3,"-":1,".":2},H=131072;function Q(fe,$){if(fe>24)return $.setWinLines||!1;switch(fe){case 1:return!!$.restoreWin;case 2:return!!$.minimizeWin;case 3:return!!$.setWinPosition;case 4:return!!$.setWinSizePixels;case 5:return!!$.raiseWin;case 6:return!!$.lowerWin;case 7:return!!$.refreshWin;case 8:return!!$.setWinSizeChars;case 9:return!!$.maximizeWin;case 10:return!!$.fullscreenWin;case 11:return!!$.getWinState;case 13:return!!$.getWinPosition;case 14:return!!$.getWinSizePixels;case 15:return!!$.getScreenSizePixels;case 16:return!!$.getCellSizePixels;case 18:return!!$.getWinSizeChars;case 19:return!!$.getScreenSizeChars;case 20:return!!$.getIconTitle;case 21:return!!$.getWinTitle;case 22:return!!$.pushTitle;case 23:return!!$.popTitle;case 24:return!!$.setWinLines}return!1}var F;(function(fe){fe[fe.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",fe[fe.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(F||(l.WindowsOptionsReportType=F={}));let J=0;class ie extends E.Disposable{getAttrData(){return this._curAttrData}constructor($,P,B,K,le,me,be,Ee,se=new w.EscapeSequenceParser){super(),this._bufferService=$,this._charsetService=P,this._coreService=B,this._logService=K,this._optionsService=le,this._oscLinkService=me,this._coreMouseService=be,this._unicodeService=Ee,this._parser=se,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new x.StringToUtf32,this._utf8Decoder=new x.Utf8ToUtf32,this._workCell=new _.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=m.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=m.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new y.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new y.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new y.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new y.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new y.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new y.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new y.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new y.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new y.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new y.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new y.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new y.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new y.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new X(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((Z=>this._activeBuffer=Z.activeBuffer))),this._parser.setCsiHandlerFallback(((Z,ge)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(Z),params:ge.toArray()})})),this._parser.setEscHandlerFallback((Z=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(Z)})})),this._parser.setExecuteHandlerFallback((Z=>{this._logService.debug("Unknown EXECUTE code: ",{code:Z})})),this._parser.setOscHandlerFallback(((Z,ge,De)=>{this._logService.debug("Unknown OSC code: ",{identifier:Z,action:ge,data:De})})),this._parser.setDcsHandlerFallback(((Z,ge,De)=>{ge==="HOOK"&&(De=De.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(Z),action:ge,payload:De})})),this._parser.setPrintHandler(((Z,ge,De)=>this.print(Z,ge,De))),this._parser.registerCsiHandler({final:"@"},(Z=>this.insertChars(Z))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(Z=>this.scrollLeft(Z))),this._parser.registerCsiHandler({final:"A"},(Z=>this.cursorUp(Z))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(Z=>this.scrollRight(Z))),this._parser.registerCsiHandler({final:"B"},(Z=>this.cursorDown(Z))),this._parser.registerCsiHandler({final:"C"},(Z=>this.cursorForward(Z))),this._parser.registerCsiHandler({final:"D"},(Z=>this.cursorBackward(Z))),this._parser.registerCsiHandler({final:"E"},(Z=>this.cursorNextLine(Z))),this._parser.registerCsiHandler({final:"F"},(Z=>this.cursorPrecedingLine(Z))),this._parser.registerCsiHandler({final:"G"},(Z=>this.cursorCharAbsolute(Z))),this._parser.registerCsiHandler({final:"H"},(Z=>this.cursorPosition(Z))),this._parser.registerCsiHandler({final:"I"},(Z=>this.cursorForwardTab(Z))),this._parser.registerCsiHandler({final:"J"},(Z=>this.eraseInDisplay(Z,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(Z=>this.eraseInDisplay(Z,!0))),this._parser.registerCsiHandler({final:"K"},(Z=>this.eraseInLine(Z,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(Z=>this.eraseInLine(Z,!0))),this._parser.registerCsiHandler({final:"L"},(Z=>this.insertLines(Z))),this._parser.registerCsiHandler({final:"M"},(Z=>this.deleteLines(Z))),this._parser.registerCsiHandler({final:"P"},(Z=>this.deleteChars(Z))),this._parser.registerCsiHandler({final:"S"},(Z=>this.scrollUp(Z))),this._parser.registerCsiHandler({final:"T"},(Z=>this.scrollDown(Z))),this._parser.registerCsiHandler({final:"X"},(Z=>this.eraseChars(Z))),this._parser.registerCsiHandler({final:"Z"},(Z=>this.cursorBackwardTab(Z))),this._parser.registerCsiHandler({final:"`"},(Z=>this.charPosAbsolute(Z))),this._parser.registerCsiHandler({final:"a"},(Z=>this.hPositionRelative(Z))),this._parser.registerCsiHandler({final:"b"},(Z=>this.repeatPrecedingCharacter(Z))),this._parser.registerCsiHandler({final:"c"},(Z=>this.sendDeviceAttributesPrimary(Z))),this._parser.registerCsiHandler({prefix:">",final:"c"},(Z=>this.sendDeviceAttributesSecondary(Z))),this._parser.registerCsiHandler({final:"d"},(Z=>this.linePosAbsolute(Z))),this._parser.registerCsiHandler({final:"e"},(Z=>this.vPositionRelative(Z))),this._parser.registerCsiHandler({final:"f"},(Z=>this.hVPosition(Z))),this._parser.registerCsiHandler({final:"g"},(Z=>this.tabClear(Z))),this._parser.registerCsiHandler({final:"h"},(Z=>this.setMode(Z))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(Z=>this.setModePrivate(Z))),this._parser.registerCsiHandler({final:"l"},(Z=>this.resetMode(Z))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(Z=>this.resetModePrivate(Z))),this._parser.registerCsiHandler({final:"m"},(Z=>this.charAttributes(Z))),this._parser.registerCsiHandler({final:"n"},(Z=>this.deviceStatus(Z))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(Z=>this.deviceStatusPrivate(Z))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(Z=>this.softReset(Z))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(Z=>this.setCursorStyle(Z))),this._parser.registerCsiHandler({final:"r"},(Z=>this.setScrollRegion(Z))),this._parser.registerCsiHandler({final:"s"},(Z=>this.saveCursor(Z))),this._parser.registerCsiHandler({final:"t"},(Z=>this.windowOptions(Z))),this._parser.registerCsiHandler({final:"u"},(Z=>this.restoreCursor(Z))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(Z=>this.insertColumns(Z))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(Z=>this.deleteColumns(Z))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(Z=>this.selectProtected(Z))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(Z=>this.requestMode(Z,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(Z=>this.requestMode(Z,!1))),this._parser.setExecuteHandler(g.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(g.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(g.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(g.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(g.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(g.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(g.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(g.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(g.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(g.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(g.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(g.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new D.OscHandler((Z=>(this.setTitle(Z),this.setIconName(Z),!0)))),this._parser.registerOscHandler(1,new D.OscHandler((Z=>this.setIconName(Z)))),this._parser.registerOscHandler(2,new D.OscHandler((Z=>this.setTitle(Z)))),this._parser.registerOscHandler(4,new D.OscHandler((Z=>this.setOrReportIndexedColor(Z)))),this._parser.registerOscHandler(8,new D.OscHandler((Z=>this.setHyperlink(Z)))),this._parser.registerOscHandler(10,new D.OscHandler((Z=>this.setOrReportFgColor(Z)))),this._parser.registerOscHandler(11,new D.OscHandler((Z=>this.setOrReportBgColor(Z)))),this._parser.registerOscHandler(12,new D.OscHandler((Z=>this.setOrReportCursorColor(Z)))),this._parser.registerOscHandler(104,new D.OscHandler((Z=>this.restoreIndexedColor(Z)))),this._parser.registerOscHandler(110,new D.OscHandler((Z=>this.restoreFgColor(Z)))),this._parser.registerOscHandler(111,new D.OscHandler((Z=>this.restoreBgColor(Z)))),this._parser.registerOscHandler(112,new D.OscHandler((Z=>this.restoreCursorColor(Z)))),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(const Z in S.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:Z},(()=>this.selectCharset("("+Z))),this._parser.registerEscHandler({intermediates:")",final:Z},(()=>this.selectCharset(")"+Z))),this._parser.registerEscHandler({intermediates:"*",final:Z},(()=>this.selectCharset("*"+Z))),this._parser.registerEscHandler({intermediates:"+",final:Z},(()=>this.selectCharset("+"+Z))),this._parser.registerEscHandler({intermediates:"-",final:Z},(()=>this.selectCharset("-"+Z))),this._parser.registerEscHandler({intermediates:".",final:Z},(()=>this.selectCharset("."+Z))),this._parser.registerEscHandler({intermediates:"/",final:Z},(()=>this.selectCharset("/"+Z)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((Z=>(this._logService.error("Parsing error: ",Z),Z))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new I.DcsHandler(((Z,ge)=>this.requestStatusString(Z,ge))))}_preserveStack($,P,B,K){this._parseStack.paused=!0,this._parseStack.cursorStartX=$,this._parseStack.cursorStartY=P,this._parseStack.decodedLength=B,this._parseStack.position=K}_logSlowResolvingAsync($){this._logService.logLevel<=j.LogLevelEnum.WARN&&Promise.race([$,new Promise(((P,B)=>setTimeout((()=>B("#SLOW_TIMEOUT")),5e3)))]).catch((P=>{if(P!=="#SLOW_TIMEOUT")throw P;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse($,P){let B,K=this._activeBuffer.x,le=this._activeBuffer.y,me=0;const be=this._parseStack.paused;if(be){if(B=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,P))return this._logSlowResolvingAsync(B),B;K=this._parseStack.cursorStartX,le=this._parseStack.cursorStartY,this._parseStack.paused=!1,$.length>H&&(me=this._parseStack.position+H)}if(this._logService.logLevel<=j.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof $=="string"?` "${$}"`:` "${Array.prototype.map.call($,(Z=>String.fromCharCode(Z))).join("")}"`),typeof $=="string"?$.split("").map((Z=>Z.charCodeAt(0))):$),this._parseBuffer.length<$.length&&this._parseBuffer.length<H&&(this._parseBuffer=new Uint32Array(Math.min($.length,H))),be||this._dirtyRowTracker.clearRange(),$.length>H)for(let Z=me;Z<$.length;Z+=H){const ge=Z+H<$.length?Z+H:$.length,De=typeof $=="string"?this._stringDecoder.decode($.substring(Z,ge),this._parseBuffer):this._utf8Decoder.decode($.subarray(Z,ge),this._parseBuffer);if(B=this._parser.parse(this._parseBuffer,De))return this._preserveStack(K,le,De,Z),this._logSlowResolvingAsync(B),B}else if(!be){const Z=typeof $=="string"?this._stringDecoder.decode($,this._parseBuffer):this._utf8Decoder.decode($,this._parseBuffer);if(B=this._parser.parse(this._parseBuffer,Z))return this._preserveStack(K,le,Z,0),this._logSlowResolvingAsync(B),B}this._activeBuffer.x===K&&this._activeBuffer.y===le||this._onCursorMove.fire();const Ee=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),se=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);se<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(se,this._bufferService.rows-1),Math.min(Ee,this._bufferService.rows-1))}print($,P,B){let K,le;const me=this._charsetService.charset,be=this._optionsService.rawOptions.screenReaderMode,Ee=this._bufferService.cols,se=this._coreService.decPrivateModes.wraparound,Z=this._coreService.modes.insertMode,ge=this._curAttrData;let De=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&B-P>0&&De.getWidth(this._activeBuffer.x-1)===2&&De.setCellFromCodepoint(this._activeBuffer.x-1,0,1,ge);let Ge=this._parser.precedingJoinState;for(let Ve=P;Ve<B;++Ve){if(K=$[Ve],K<127&&me){const Tt=me[String.fromCharCode(K)];Tt&&(K=Tt.charCodeAt(0))}const St=this._unicodeService.charProperties(K,Ge);le=T.UnicodeService.extractWidth(St);const Nt=T.UnicodeService.extractShouldJoin(St),kt=Nt?T.UnicodeService.extractWidth(Ge):0;if(Ge=St,be&&this._onA11yChar.fire((0,x.stringFromCodePoint)(K)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+le-kt>Ee){if(se){const Tt=De;let at=this._activeBuffer.x-kt;for(this._activeBuffer.x=kt,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),De=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),kt>0&&De instanceof m.BufferLine&&De.copyCellsFrom(Tt,at,0,kt,!1);at<Ee;)Tt.setCellFromCodepoint(at++,0,1,ge)}else if(this._activeBuffer.x=Ee-1,le===2)continue}if(Nt&&this._activeBuffer.x){const Tt=De.getWidth(this._activeBuffer.x-1)?1:2;De.addCodepointToCell(this._activeBuffer.x-Tt,K,le);for(let at=le-kt;--at>=0;)De.setCellFromCodepoint(this._activeBuffer.x++,0,0,ge)}else if(Z&&(De.insertCells(this._activeBuffer.x,le-kt,this._activeBuffer.getNullCell(ge)),De.getWidth(Ee-1)===2&&De.setCellFromCodepoint(Ee-1,b.NULL_CELL_CODE,b.NULL_CELL_WIDTH,ge)),De.setCellFromCodepoint(this._activeBuffer.x++,K,le,ge),le>0)for(;--le;)De.setCellFromCodepoint(this._activeBuffer.x++,0,0,ge)}this._parser.precedingJoinState=Ge,this._activeBuffer.x<Ee&&B-P>0&&De.getWidth(this._activeBuffer.x)===0&&!De.hasContent(this._activeBuffer.x)&&De.setCellFromCodepoint(this._activeBuffer.x,0,1,ge),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler($,P){return $.final!=="t"||$.prefix||$.intermediates?this._parser.registerCsiHandler($,P):this._parser.registerCsiHandler($,(B=>!Q(B.params[0],this._optionsService.rawOptions.windowOptions)||P(B)))}registerDcsHandler($,P){return this._parser.registerDcsHandler($,new I.DcsHandler(P))}registerEscHandler($,P){return this._parser.registerEscHandler($,P)}registerOscHandler($,P){return this._parser.registerOscHandler($,new D.OscHandler(P))}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;const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);$.hasWidth(this._activeBuffer.x)&&!$.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const $=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-$),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor($=this._bufferService.cols-1){this._activeBuffer.x=Math.min($,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($,P){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=$,this._activeBuffer.y=this._activeBuffer.scrollTop+P):(this._activeBuffer.x=$,this._activeBuffer.y=P),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor($,P){this._restrictCursor(),this._setCursor(this._activeBuffer.x+$,this._activeBuffer.y+P)}cursorUp($){const P=this._activeBuffer.y-this._activeBuffer.scrollTop;return P>=0?this._moveCursor(0,-Math.min(P,$.params[0]||1)):this._moveCursor(0,-($.params[0]||1)),!0}cursorDown($){const P=this._activeBuffer.scrollBottom-this._activeBuffer.y;return P>=0?this._moveCursor(0,Math.min(P,$.params[0]||1)):this._moveCursor(0,$.params[0]||1),!0}cursorForward($){return this._moveCursor($.params[0]||1,0),!0}cursorBackward($){return this._moveCursor(-($.params[0]||1),0),!0}cursorNextLine($){return this.cursorDown($),this._activeBuffer.x=0,!0}cursorPrecedingLine($){return this.cursorUp($),this._activeBuffer.x=0,!0}cursorCharAbsolute($){return this._setCursor(($.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition($){return this._setCursor($.length>=2?($.params[1]||1)-1:0,($.params[0]||1)-1),!0}charPosAbsolute($){return this._setCursor(($.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative($){return this._moveCursor($.params[0]||1,0),!0}linePosAbsolute($){return this._setCursor(this._activeBuffer.x,($.params[0]||1)-1),!0}vPositionRelative($){return this._moveCursor(0,$.params[0]||1),!0}hVPosition($){return this.cursorPosition($),!0}tabClear($){const P=$.params[0];return P===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:P===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab($){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let P=$.params[0]||1;for(;P--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab($){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let P=$.params[0]||1;for(;P--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected($){const P=$.params[0];return P===1&&(this._curAttrData.bg|=536870912),P!==2&&P!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine($,P,B,K=!1,le=!1){const me=this._activeBuffer.lines.get(this._activeBuffer.ybase+$);me.replaceCells(P,B,this._activeBuffer.getNullCell(this._eraseAttrData()),le),K&&(me.isWrapped=!1)}_resetBufferLine($,P=!1){const B=this._activeBuffer.lines.get(this._activeBuffer.ybase+$);B&&(B.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),P),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+$),B.isWrapped=!1)}eraseInDisplay($,P=!1){let B;switch(this._restrictCursor(this._bufferService.cols),$.params[0]){case 0:for(B=this._activeBuffer.y,this._dirtyRowTracker.markDirty(B),this._eraseInBufferLine(B++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,P);B<this._bufferService.rows;B++)this._resetBufferLine(B,P);this._dirtyRowTracker.markDirty(B);break;case 1:for(B=this._activeBuffer.y,this._dirtyRowTracker.markDirty(B),this._eraseInBufferLine(B,0,this._activeBuffer.x+1,!0,P),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(B+1).isWrapped=!1);B--;)this._resetBufferLine(B,P);this._dirtyRowTracker.markDirty(0);break;case 2:for(B=this._bufferService.rows,this._dirtyRowTracker.markDirty(B-1);B--;)this._resetBufferLine(B,P);this._dirtyRowTracker.markDirty(0);break;case 3:const K=this._activeBuffer.lines.length-this._bufferService.rows;K>0&&(this._activeBuffer.lines.trimStart(K),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-K,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-K,0),this._onScroll.fire(0))}return!0}eraseInLine($,P=!1){switch(this._restrictCursor(this._bufferService.cols),$.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,P);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,P);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,P)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines($){this._restrictCursor();let P=$.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const B=this._activeBuffer.ybase+this._activeBuffer.y,K=this._bufferService.rows-1-this._activeBuffer.scrollBottom,le=this._bufferService.rows-1+this._activeBuffer.ybase-K+1;for(;P--;)this._activeBuffer.lines.splice(le-1,1),this._activeBuffer.lines.splice(B,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines($){this._restrictCursor();let P=$.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const B=this._activeBuffer.ybase+this._activeBuffer.y;let K;for(K=this._bufferService.rows-1-this._activeBuffer.scrollBottom,K=this._bufferService.rows-1+this._activeBuffer.ybase-K;P--;)this._activeBuffer.lines.splice(B,1),this._activeBuffer.lines.splice(K,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars($){this._restrictCursor();const P=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return P&&(P.insertCells(this._activeBuffer.x,$.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars($){this._restrictCursor();const P=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return P&&(P.deleteCells(this._activeBuffer.x,$.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp($){let P=$.params[0]||1;for(;P--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown($){let P=$.params[0]||1;for(;P--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(m.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft($){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const P=$.params[0]||1;for(let B=this._activeBuffer.scrollTop;B<=this._activeBuffer.scrollBottom;++B){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+B);K.deleteCells(0,P,this._activeBuffer.getNullCell(this._eraseAttrData())),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight($){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const P=$.params[0]||1;for(let B=this._activeBuffer.scrollTop;B<=this._activeBuffer.scrollBottom;++B){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+B);K.insertCells(0,P,this._activeBuffer.getNullCell(this._eraseAttrData())),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns($){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const P=$.params[0]||1;for(let B=this._activeBuffer.scrollTop;B<=this._activeBuffer.scrollBottom;++B){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+B);K.insertCells(this._activeBuffer.x,P,this._activeBuffer.getNullCell(this._eraseAttrData())),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns($){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const P=$.params[0]||1;for(let B=this._activeBuffer.scrollTop;B<=this._activeBuffer.scrollBottom;++B){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+B);K.deleteCells(this._activeBuffer.x,P,this._activeBuffer.getNullCell(this._eraseAttrData())),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars($){this._restrictCursor();const P=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return P&&(P.replaceCells(this._activeBuffer.x,this._activeBuffer.x+($.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter($){const P=this._parser.precedingJoinState;if(!P)return!0;const B=$.params[0]||1,K=T.UnicodeService.extractWidth(P),le=this._activeBuffer.x-K,me=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(le),be=new Uint32Array(me.length*B);let Ee=0;for(let Z=0;Z<me.length;){const ge=me.codePointAt(Z)||0;be[Ee++]=ge,Z+=ge>65535?2:1}let se=Ee;for(let Z=1;Z<B;++Z)be.copyWithin(se,0,Ee),se+=Ee;return this.print(be,0,se),!0}sendDeviceAttributesPrimary($){return $.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(g.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(g.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary($){return $.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(g.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(g.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent($.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(g.C0.ESC+"[>83;40003;0c")),!0}_is($){return(this._optionsService.rawOptions.termName+"").indexOf($)===0}setMode($){for(let P=0;P<$.length;P++)switch($.params[P]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate($){for(let P=0;P<$.length;P++)switch($.params[P]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,S.DEFAULT_CHARSET),this._charsetService.setgCharset(1,S.DEFAULT_CHARSET),this._charsetService.setgCharset(2,S.DEFAULT_CHARSET),this._charsetService.setgCharset(3,S.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode($){for(let P=0;P<$.length;P++)switch($.params[P]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate($){for(let P=0;P<$.length;P++)switch($.params[P]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),$.params[P]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode($,P){const B=this._coreService.decPrivateModes,{activeProtocol:K,activeEncoding:le}=this._coreMouseService,me=this._coreService,{buffers:be,cols:Ee}=this._bufferService,{active:se,alt:Z}=be,ge=this._optionsService.rawOptions,De=Nt=>Nt?1:2,Ge=$.params[0];return Ve=Ge,St=P?Ge===2?4:Ge===4?De(me.modes.insertMode):Ge===12?3:Ge===20?De(ge.convertEol):0:Ge===1?De(B.applicationCursorKeys):Ge===3?ge.windowOptions.setWinLines?Ee===80?2:Ee===132?1:0:0:Ge===6?De(B.origin):Ge===7?De(B.wraparound):Ge===8?3:Ge===9?De(K==="X10"):Ge===12?De(ge.cursorBlink):Ge===25?De(!me.isCursorHidden):Ge===45?De(B.reverseWraparound):Ge===66?De(B.applicationKeypad):Ge===67?4:Ge===1e3?De(K==="VT200"):Ge===1002?De(K==="DRAG"):Ge===1003?De(K==="ANY"):Ge===1004?De(B.sendFocus):Ge===1005?4:Ge===1006?De(le==="SGR"):Ge===1015?4:Ge===1016?De(le==="SGR_PIXELS"):Ge===1048?1:Ge===47||Ge===1047||Ge===1049?De(se===Z):Ge===2004?De(B.bracketedPasteMode):0,me.triggerDataEvent(`${g.C0.ESC}[${P?"":"?"}${Ve};${St}$y`),!0;var Ve,St}_updateAttrColor($,P,B,K,le){return P===2?($|=50331648,$&=-16777216,$|=k.AttributeData.fromColorRGB([B,K,le])):P===5&&($&=-50331904,$|=33554432|255&B),$}_extractColor($,P,B){const K=[0,0,-1,0,0,0];let le=0,me=0;do{if(K[me+le]=$.params[P+me],$.hasSubParams(P+me)){const be=$.getSubParams(P+me);let Ee=0;do K[1]===5&&(le=1),K[me+Ee+1+le]=be[Ee];while(++Ee<be.length&&Ee+me+1+le<K.length);break}if(K[1]===5&&me+le>=2||K[1]===2&&me+le>=5)break;K[1]&&(le=1)}while(++me+P<$.length&&me+le<K.length);for(let be=2;be<K.length;++be)K[be]===-1&&(K[be]=0);switch(K[0]){case 38:B.fg=this._updateAttrColor(B.fg,K[1],K[3],K[4],K[5]);break;case 48:B.bg=this._updateAttrColor(B.bg,K[1],K[3],K[4],K[5]);break;case 58:B.extended=B.extended.clone(),B.extended.underlineColor=this._updateAttrColor(B.extended.underlineColor,K[1],K[3],K[4],K[5])}return me}_processUnderline($,P){P.extended=P.extended.clone(),(!~$||$>5)&&($=1),P.extended.underlineStyle=$,P.fg|=268435456,$===0&&(P.fg&=-268435457),P.updateExtended()}_processSGR0($){$.fg=m.DEFAULT_ATTR_DATA.fg,$.bg=m.DEFAULT_ATTR_DATA.bg,$.extended=$.extended.clone(),$.extended.underlineStyle=0,$.extended.underlineColor&=-67108864,$.updateExtended()}charAttributes($){if($.length===1&&$.params[0]===0)return this._processSGR0(this._curAttrData),!0;const P=$.length;let B;const K=this._curAttrData;for(let le=0;le<P;le++)B=$.params[le],B>=30&&B<=37?(K.fg&=-50331904,K.fg|=16777216|B-30):B>=40&&B<=47?(K.bg&=-50331904,K.bg|=16777216|B-40):B>=90&&B<=97?(K.fg&=-50331904,K.fg|=16777224|B-90):B>=100&&B<=107?(K.bg&=-50331904,K.bg|=16777224|B-100):B===0?this._processSGR0(K):B===1?K.fg|=134217728:B===3?K.bg|=67108864:B===4?(K.fg|=268435456,this._processUnderline($.hasSubParams(le)?$.getSubParams(le)[0]:1,K)):B===5?K.fg|=536870912:B===7?K.fg|=67108864:B===8?K.fg|=1073741824:B===9?K.fg|=2147483648:B===2?K.bg|=134217728:B===21?this._processUnderline(2,K):B===22?(K.fg&=-134217729,K.bg&=-134217729):B===23?K.bg&=-67108865:B===24?(K.fg&=-268435457,this._processUnderline(0,K)):B===25?K.fg&=-536870913:B===27?K.fg&=-67108865:B===28?K.fg&=-1073741825:B===29?K.fg&=2147483647:B===39?(K.fg&=-67108864,K.fg|=16777215&m.DEFAULT_ATTR_DATA.fg):B===49?(K.bg&=-67108864,K.bg|=16777215&m.DEFAULT_ATTR_DATA.bg):B===38||B===48||B===58?le+=this._extractColor($,le,K):B===53?K.bg|=1073741824:B===55?K.bg&=-1073741825:B===59?(K.extended=K.extended.clone(),K.extended.underlineColor=-1,K.updateExtended()):B===100?(K.fg&=-67108864,K.fg|=16777215&m.DEFAULT_ATTR_DATA.fg,K.bg&=-67108864,K.bg|=16777215&m.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",B);return!0}deviceStatus($){switch($.params[0]){case 5:this._coreService.triggerDataEvent(`${g.C0.ESC}[0n`);break;case 6:const P=this._activeBuffer.y+1,B=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${g.C0.ESC}[${P};${B}R`)}return!0}deviceStatusPrivate($){if($.params[0]===6){const P=this._activeBuffer.y+1,B=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${g.C0.ESC}[?${P};${B}R`)}return!0}softReset($){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=m.DEFAULT_ATTR_DATA.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($){const P=$.params[0]||1;switch(P){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const B=P%2==1;return this._optionsService.options.cursorBlink=B,!0}setScrollRegion($){const P=$.params[0]||1;let B;return($.length<2||(B=$.params[1])>this._bufferService.rows||B===0)&&(B=this._bufferService.rows),B>P&&(this._activeBuffer.scrollTop=P-1,this._activeBuffer.scrollBottom=B-1,this._setCursor(0,0)),!0}windowOptions($){if(!Q($.params[0],this._optionsService.rawOptions.windowOptions))return!0;const P=$.length>1?$.params[1]:0;switch($.params[0]){case 14:P!==2&&this._onRequestWindowsOptionsReport.fire(F.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(F.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${g.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:P!==0&&P!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),P!==0&&P!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:P!==0&&P!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),P!==0&&P!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor($){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($){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($){return this._windowTitle=$,this._onTitleChange.fire($),!0}setIconName($){return this._iconName=$,!0}setOrReportIndexedColor($){const P=[],B=$.split(";");for(;B.length>1;){const K=B.shift(),le=B.shift();if(/^\d+$/.exec(K)){const me=parseInt(K);if(de(me))if(le==="?")P.push({type:0,index:me});else{const be=(0,L.parseColor)(le);be&&P.push({type:1,index:me,color:be})}}}return P.length&&this._onColor.fire(P),!0}setHyperlink($){const P=$.split(";");return!(P.length<2)&&(P[1]?this._createHyperlink(P[0],P[1]):!P[0]&&this._finishHyperlink())}_createHyperlink($,P){this._getCurrentLinkId()&&this._finishHyperlink();const B=$.split(":");let K;const le=B.findIndex((me=>me.startsWith("id=")));return le!==-1&&(K=B[le].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:K,uri:P}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor($,P){const B=$.split(";");for(let K=0;K<B.length&&!(P>=this._specialColors.length);++K,++P)if(B[K]==="?")this._onColor.fire([{type:0,index:this._specialColors[P]}]);else{const le=(0,L.parseColor)(B[K]);le&&this._onColor.fire([{type:1,index:this._specialColors[P],color:le}])}return!0}setOrReportFgColor($){return this._setOrReportSpecialColor($,0)}setOrReportBgColor($){return this._setOrReportSpecialColor($,1)}setOrReportCursorColor($){return this._setOrReportSpecialColor($,2)}restoreIndexedColor($){if(!$)return this._onColor.fire([{type:2}]),!0;const P=[],B=$.split(";");for(let K=0;K<B.length;++K)if(/^\d+$/.exec(B[K])){const le=parseInt(B[K]);de(le)&&P.push({type:2,index:le})}return P.length&&this._onColor.fire(P),!0}restoreFgColor($){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor($){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor($){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,S.DEFAULT_CHARSET),!0}selectCharset($){return $.length!==2?(this.selectDefaultCharset(),!0):($[0]==="/"||this._charsetService.setgCharset(q[$[0]],S.CHARSETS[$[1]]||S.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),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._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const $=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,$,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=m.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=m.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel($){return this._charsetService.setgLevel($),!0}screenAlignmentPattern(){const $=new _.CellData;$.content=4194373,$.fg=this._curAttrData.fg,$.bg=this._curAttrData.bg,this._setCursor(0,0);for(let P=0;P<this._bufferService.rows;++P){const B=this._activeBuffer.ybase+this._activeBuffer.y+P,K=this._activeBuffer.lines.get(B);K&&(K.fill($),K.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString($,P){const B=this._bufferService.buffer,K=this._optionsService.rawOptions;return(le=>(this._coreService.triggerDataEvent(`${g.C0.ESC}${le}${g.C0.ESC}\\`),!0))($==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:$==='"p'?'P1$r61;1"p':$==="r"?`P1$r${B.scrollTop+1};${B.scrollBottom+1}r`:$==="m"?"P1$r0m":$===" q"?`P1$r${{block:2,underline:4,bar:6}[K.cursorStyle]-(K.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty($,P){this._dirtyRowTracker.markRangeDirty($,P)}}l.InputHandler=ie;let X=class{constructor(fe){this._bufferService=fe,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(fe){fe<this.start?this.start=fe:fe>this.end&&(this.end=fe)}markRangeDirty(fe,$){fe>$&&(J=fe,fe=$,$=J),fe<this.start&&(this.start=fe),$>this.end&&(this.end=$)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function de(fe){return 0<=fe&&fe<256}X=f([v(0,j.IBufferService)],X)},844:(h,l)=>{function u(f){for(const v of f)v.dispose();f.length=0}Object.defineProperty(l,"__esModule",{value:!0}),l.getDisposeArrayDisposable=l.disposeArray=l.toDisposable=l.MutableDisposable=l.Disposable=void 0,l.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const f of this._disposables)f.dispose();this._disposables.length=0}register(f){return this._disposables.push(f),f}unregister(f){const v=this._disposables.indexOf(f);v!==-1&&this._disposables.splice(v,1)}},l.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(f){this._isDisposed||f===this._value||(this._value?.dispose(),this._value=f)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},l.toDisposable=function(f){return{dispose:f}},l.disposeArray=u,l.getDisposeArrayDisposable=function(f){return{dispose:()=>u(f)}}},1505:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.FourKeyMap=l.TwoKeyMap=void 0;class u{constructor(){this._data={}}set(v,g,S){this._data[v]||(this._data[v]={}),this._data[v][g]=S}get(v,g){return this._data[v]?this._data[v][g]:void 0}clear(){this._data={}}}l.TwoKeyMap=u,l.FourKeyMap=class{constructor(){this._data=new u}set(f,v,g,S,w){this._data.get(f,v)||this._data.set(f,v,new u),this._data.get(f,v).set(g,S,w)}get(f,v,g,S){return this._data.get(f,v)?.get(g,S)}clear(){this._data.clear()}}},6114:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.isChromeOS=l.isLinux=l.isWindows=l.isIphone=l.isIpad=l.isMac=l.getSafariVersion=l.isSafari=l.isLegacyEdge=l.isFirefox=l.isNode=void 0,l.isNode=typeof process<"u"&&"title"in process;const u=l.isNode?"node":navigator.userAgent,f=l.isNode?"node":navigator.platform;l.isFirefox=u.includes("Firefox"),l.isLegacyEdge=u.includes("Edge"),l.isSafari=/^((?!chrome|android).)*safari/i.test(u),l.getSafariVersion=function(){if(!l.isSafari)return 0;const v=u.match(/Version\/(\d+)/);return v===null||v.length<2?0:parseInt(v[1])},l.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(f),l.isIpad=f==="iPad",l.isIphone=f==="iPhone",l.isWindows=["Windows","Win16","Win32","WinCE"].includes(f),l.isLinux=f.indexOf("Linux")>=0,l.isChromeOS=/\bCrOS\b/.test(u)},6106:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.SortedList=void 0;let u=0;l.SortedList=class{constructor(f){this._getKey=f,this._array=[]}clear(){this._array.length=0}insert(f){this._array.length!==0?(u=this._search(this._getKey(f)),this._array.splice(u,0,f)):this._array.push(f)}delete(f){if(this._array.length===0)return!1;const v=this._getKey(f);if(v===void 0||(u=this._search(v),u===-1)||this._getKey(this._array[u])!==v)return!1;do if(this._array[u]===f)return this._array.splice(u,1),!0;while(++u<this._array.length&&this._getKey(this._array[u])===v);return!1}*getKeyIterator(f){if(this._array.length!==0&&(u=this._search(f),!(u<0||u>=this._array.length)&&this._getKey(this._array[u])===f))do yield this._array[u];while(++u<this._array.length&&this._getKey(this._array[u])===f)}forEachByKey(f,v){if(this._array.length!==0&&(u=this._search(f),!(u<0||u>=this._array.length)&&this._getKey(this._array[u])===f))do v(this._array[u]);while(++u<this._array.length&&this._getKey(this._array[u])===f)}values(){return[...this._array].values()}_search(f){let v=0,g=this._array.length-1;for(;g>=v;){let S=v+g>>1;const w=this._getKey(this._array[S]);if(w>f)g=S-1;else{if(!(w<f)){for(;S>0&&this._getKey(this._array[S-1])===f;)S--;return S}v=S+1}}return v}}},7226:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DebouncedIdleTask=l.IdleTaskQueue=l.PriorityTaskQueue=void 0;const f=u(6114);class v{constructor(){this._tasks=[],this._i=0}enqueue(w){this._tasks.push(w),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(w){this._idleCallback=void 0;let E=0,x=0,m=w.timeRemaining(),y=0;for(;this._i<this._tasks.length;){if(E=Date.now(),this._tasks[this._i]()||this._i++,E=Math.max(1,Date.now()-E),x=Math.max(E,x),y=w.timeRemaining(),1.5*x>y)return m-E<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(m-E))}ms`),void this._start();m=y}this.clear()}}class g extends v{_requestCallback(w){return setTimeout((()=>w(this._createDeadline(16))))}_cancelCallback(w){clearTimeout(w)}_createDeadline(w){const E=Date.now()+w;return{timeRemaining:()=>Math.max(0,E-Date.now())}}}l.PriorityTaskQueue=g,l.IdleTaskQueue=!f.isNode&&"requestIdleCallback"in window?class extends v{_requestCallback(S){return requestIdleCallback(S)}_cancelCallback(S){cancelIdleCallback(S)}}:g,l.DebouncedIdleTask=class{constructor(){this._queue=new l.IdleTaskQueue}set(S){this._queue.clear(),this._queue.enqueue(S)}flush(){this._queue.flush()}}},9282:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.updateWindowsModeWrappedState=void 0;const f=u(643);l.updateWindowsModeWrappedState=function(v){const g=v.buffer.lines.get(v.buffer.ybase+v.buffer.y-1),S=g?.get(v.cols-1),w=v.buffer.lines.get(v.buffer.ybase+v.buffer.y);w&&S&&(w.isWrapped=S[f.CHAR_DATA_CODE_INDEX]!==f.NULL_CELL_CODE&&S[f.CHAR_DATA_CODE_INDEX]!==f.WHITESPACE_CELL_CODE)}},3734:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ExtendedAttrs=l.AttributeData=void 0;class u{constructor(){this.fg=0,this.bg=0,this.extended=new f}static toColorRGB(g){return[g>>>16&255,g>>>8&255,255&g]}static fromColorRGB(g){return(255&g[0])<<16|(255&g[1])<<8|255&g[2]}clone(){const g=new u;return g.fg=this.fg,g.bg=this.bg,g.extended=this.extended.clone(),g}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}l.AttributeData=u;class f{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(g){this._ext=g}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(g){this._ext&=-469762049,this._ext|=g<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(g){this._ext&=-67108864,this._ext|=67108863&g}get urlId(){return this._urlId}set urlId(g){this._urlId=g}get underlineVariantOffset(){const g=(3758096384&this._ext)>>29;return g<0?4294967288^g:g}set underlineVariantOffset(g){this._ext&=536870911,this._ext|=g<<29&3758096384}constructor(g=0,S=0){this._ext=0,this._urlId=0,this._ext=g,this._urlId=S}clone(){return new f(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}l.ExtendedAttrs=f},9092:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Buffer=l.MAX_BUFFER_SIZE=void 0;const f=u(6349),v=u(7226),g=u(3734),S=u(8437),w=u(4634),E=u(511),x=u(643),m=u(4863),y=u(7116);l.MAX_BUFFER_SIZE=4294967295,l.Buffer=class{constructor(b,_,k){this._hasScrollback=b,this._optionsService=_,this._bufferService=k,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=S.DEFAULT_ATTR_DATA.clone(),this.savedCharset=y.DEFAULT_CHARSET,this.markers=[],this._nullCell=E.CellData.fromCharData([0,x.NULL_CELL_CHAR,x.NULL_CELL_WIDTH,x.NULL_CELL_CODE]),this._whitespaceCell=E.CellData.fromCharData([0,x.WHITESPACE_CELL_CHAR,x.WHITESPACE_CELL_WIDTH,x.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new v.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(b){return b?(this._nullCell.fg=b.fg,this._nullCell.bg=b.bg,this._nullCell.extended=b.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new g.ExtendedAttrs),this._nullCell}getWhitespaceCell(b){return b?(this._whitespaceCell.fg=b.fg,this._whitespaceCell.bg=b.bg,this._whitespaceCell.extended=b.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new g.ExtendedAttrs),this._whitespaceCell}getBlankLine(b,_){return new S.BufferLine(this._bufferService.cols,this.getNullCell(b),_)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const b=this.ybase+this.y-this.ydisp;return b>=0&&b<this._rows}_getCorrectBufferLength(b){if(!this._hasScrollback)return b;const _=b+this._optionsService.rawOptions.scrollback;return _>l.MAX_BUFFER_SIZE?l.MAX_BUFFER_SIZE:_}fillViewportRows(b){if(this.lines.length===0){b===void 0&&(b=S.DEFAULT_ATTR_DATA);let _=this._rows;for(;_--;)this.lines.push(this.getBlankLine(b))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new f.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(b,_){const k=this.getNullCell(S.DEFAULT_ATTR_DATA);let j=0;const T=this._getCorrectBufferLength(_);if(T>this.lines.maxLength&&(this.lines.maxLength=T),this.lines.length>0){if(this._cols<b)for(let I=0;I<this.lines.length;I++)j+=+this.lines.get(I).resize(b,k);let D=0;if(this._rows<_)for(let I=this._rows;I<_;I++)this.lines.length<_+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new S.BufferLine(b,k)):this.ybase>0&&this.lines.length<=this.ybase+this.y+D+1?(this.ybase--,D++,this.ydisp>0&&this.ydisp--):this.lines.push(new S.BufferLine(b,k)));else for(let I=this._rows;I>_;I--)this.lines.length>_+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(T<this.lines.maxLength){const I=this.lines.length-T;I>0&&(this.lines.trimStart(I),this.ybase=Math.max(this.ybase-I,0),this.ydisp=Math.max(this.ydisp-I,0),this.savedY=Math.max(this.savedY-I,0)),this.lines.maxLength=T}this.x=Math.min(this.x,b-1),this.y=Math.min(this.y,_-1),D&&(this.y+=D),this.savedX=Math.min(this.savedX,b-1),this.scrollTop=0}if(this.scrollBottom=_-1,this._isReflowEnabled&&(this._reflow(b,_),this._cols>b))for(let D=0;D<this.lines.length;D++)j+=+this.lines.get(D).resize(b,k);this._cols=b,this._rows=_,this._memoryCleanupQueue.clear(),j>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let b=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,b=!1);let _=0;for(;this._memoryCleanupPosition<this.lines.length;)if(_+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),_>100)return!0;return b}get _isReflowEnabled(){const b=this._optionsService.rawOptions.windowsPty;return b&&b.buildNumber?this._hasScrollback&&b.backend==="conpty"&&b.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(b,_){this._cols!==b&&(b>this._cols?this._reflowLarger(b,_):this._reflowSmaller(b,_))}_reflowLarger(b,_){const k=(0,w.reflowLargerGetLinesToRemove)(this.lines,this._cols,b,this.ybase+this.y,this.getNullCell(S.DEFAULT_ATTR_DATA));if(k.length>0){const j=(0,w.reflowLargerCreateNewLayout)(this.lines,k);(0,w.reflowLargerApplyNewLayout)(this.lines,j.layout),this._reflowLargerAdjustViewport(b,_,j.countRemoved)}}_reflowLargerAdjustViewport(b,_,k){const j=this.getNullCell(S.DEFAULT_ATTR_DATA);let T=k;for(;T-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<_&&this.lines.push(new S.BufferLine(b,j))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-k,0)}_reflowSmaller(b,_){const k=this.getNullCell(S.DEFAULT_ATTR_DATA),j=[];let T=0;for(let D=this.lines.length-1;D>=0;D--){let I=this.lines.get(D);if(!I||!I.isWrapped&&I.getTrimmedLength()<=b)continue;const L=[I];for(;I.isWrapped&&D>0;)I=this.lines.get(--D),L.unshift(I);const q=this.ybase+this.y;if(q>=D&&q<D+L.length)continue;const H=L[L.length-1].getTrimmedLength(),Q=(0,w.reflowSmallerGetNewLineLengths)(L,this._cols,b),F=Q.length-L.length;let J;J=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+F):Math.max(0,this.lines.length-this.lines.maxLength+F);const ie=[];for(let B=0;B<F;B++){const K=this.getBlankLine(S.DEFAULT_ATTR_DATA,!0);ie.push(K)}ie.length>0&&(j.push({start:D+L.length+T,newLines:ie}),T+=ie.length),L.push(...ie);let X=Q.length-1,de=Q[X];de===0&&(X--,de=Q[X]);let fe=L.length-F-1,$=H;for(;fe>=0;){const B=Math.min($,de);if(L[X]===void 0)break;if(L[X].copyCellsFrom(L[fe],$-B,de-B,B,!0),de-=B,de===0&&(X--,de=Q[X]),$-=B,$===0){fe--;const K=Math.max(fe,0);$=(0,w.getWrappedLineTrimmedLength)(L,K,this._cols)}}for(let B=0;B<L.length;B++)Q[B]<b&&L[B].setCell(Q[B],k);let P=F-J;for(;P-- >0;)this.ybase===0?this.y<_-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+T)-_&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+F,this.ybase+_-1)}if(j.length>0){const D=[],I=[];for(let X=0;X<this.lines.length;X++)I.push(this.lines.get(X));const L=this.lines.length;let q=L-1,H=0,Q=j[H];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+T);let F=0;for(let X=Math.min(this.lines.maxLength-1,L+T-1);X>=0;X--)if(Q&&Q.start>q+F){for(let de=Q.newLines.length-1;de>=0;de--)this.lines.set(X--,Q.newLines[de]);X++,D.push({index:q+1,amount:Q.newLines.length}),F+=Q.newLines.length,Q=j[++H]}else this.lines.set(X,I[q--]);let J=0;for(let X=D.length-1;X>=0;X--)D[X].index+=J,this.lines.onInsertEmitter.fire(D[X]),J+=D[X].amount;const ie=Math.max(0,L+T-this.lines.maxLength);ie>0&&this.lines.onTrimEmitter.fire(ie)}}translateBufferLineToString(b,_,k=0,j){const T=this.lines.get(b);return T?T.translateToString(_,k,j):""}getWrappedRangeForLine(b){let _=b,k=b;for(;_>0&&this.lines.get(_).isWrapped;)_--;for(;k+1<this.lines.length&&this.lines.get(k+1).isWrapped;)k++;return{first:_,last:k}}setupTabStops(b){for(b!=null?this.tabs[b]||(b=this.prevStop(b)):(this.tabs={},b=0);b<this._cols;b+=this._optionsService.rawOptions.tabStopWidth)this.tabs[b]=!0}prevStop(b){for(b==null&&(b=this.x);!this.tabs[--b]&&b>0;);return b>=this._cols?this._cols-1:b<0?0:b}nextStop(b){for(b==null&&(b=this.x);!this.tabs[++b]&&b<this._cols;);return b>=this._cols?this._cols-1:b<0?0:b}clearMarkers(b){this._isClearing=!0;for(let _=0;_<this.markers.length;_++)this.markers[_].line===b&&(this.markers[_].dispose(),this.markers.splice(_--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let b=0;b<this.markers.length;b++)this.markers[b].dispose(),this.markers.splice(b--,1);this._isClearing=!1}addMarker(b){const _=new m.Marker(b);return this.markers.push(_),_.register(this.lines.onTrim((k=>{_.line-=k,_.line<0&&_.dispose()}))),_.register(this.lines.onInsert((k=>{_.line>=k.index&&(_.line+=k.amount)}))),_.register(this.lines.onDelete((k=>{_.line>=k.index&&_.line<k.index+k.amount&&_.dispose(),_.line>k.index&&(_.line-=k.amount)}))),_.register(_.onDispose((()=>this._removeMarker(_)))),_}_removeMarker(b){this._isClearing||this.markers.splice(this.markers.indexOf(b),1)}}},8437:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferLine=l.DEFAULT_ATTR_DATA=void 0;const f=u(3734),v=u(511),g=u(643),S=u(482);l.DEFAULT_ATTR_DATA=Object.freeze(new f.AttributeData);let w=0;class E{constructor(m,y,b=!1){this.isWrapped=b,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*m);const _=y||v.CellData.fromCharData([0,g.NULL_CELL_CHAR,g.NULL_CELL_WIDTH,g.NULL_CELL_CODE]);for(let k=0;k<m;++k)this.setCell(k,_);this.length=m}get(m){const y=this._data[3*m+0],b=2097151&y;return[this._data[3*m+1],2097152&y?this._combined[m]:b?(0,S.stringFromCodePoint)(b):"",y>>22,2097152&y?this._combined[m].charCodeAt(this._combined[m].length-1):b]}set(m,y){this._data[3*m+1]=y[g.CHAR_DATA_ATTR_INDEX],y[g.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[m]=y[1],this._data[3*m+0]=2097152|m|y[g.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*m+0]=y[g.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|y[g.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(m){return this._data[3*m+0]>>22}hasWidth(m){return 12582912&this._data[3*m+0]}getFg(m){return this._data[3*m+1]}getBg(m){return this._data[3*m+2]}hasContent(m){return 4194303&this._data[3*m+0]}getCodePoint(m){const y=this._data[3*m+0];return 2097152&y?this._combined[m].charCodeAt(this._combined[m].length-1):2097151&y}isCombined(m){return 2097152&this._data[3*m+0]}getString(m){const y=this._data[3*m+0];return 2097152&y?this._combined[m]:2097151&y?(0,S.stringFromCodePoint)(2097151&y):""}isProtected(m){return 536870912&this._data[3*m+2]}loadCell(m,y){return w=3*m,y.content=this._data[w+0],y.fg=this._data[w+1],y.bg=this._data[w+2],2097152&y.content&&(y.combinedData=this._combined[m]),268435456&y.bg&&(y.extended=this._extendedAttrs[m]),y}setCell(m,y){2097152&y.content&&(this._combined[m]=y.combinedData),268435456&y.bg&&(this._extendedAttrs[m]=y.extended),this._data[3*m+0]=y.content,this._data[3*m+1]=y.fg,this._data[3*m+2]=y.bg}setCellFromCodepoint(m,y,b,_){268435456&_.bg&&(this._extendedAttrs[m]=_.extended),this._data[3*m+0]=y|b<<22,this._data[3*m+1]=_.fg,this._data[3*m+2]=_.bg}addCodepointToCell(m,y,b){let _=this._data[3*m+0];2097152&_?this._combined[m]+=(0,S.stringFromCodePoint)(y):2097151&_?(this._combined[m]=(0,S.stringFromCodePoint)(2097151&_)+(0,S.stringFromCodePoint)(y),_&=-2097152,_|=2097152):_=y|4194304,b&&(_&=-12582913,_|=b<<22),this._data[3*m+0]=_}insertCells(m,y,b){if((m%=this.length)&&this.getWidth(m-1)===2&&this.setCellFromCodepoint(m-1,0,1,b),y<this.length-m){const _=new v.CellData;for(let k=this.length-m-y-1;k>=0;--k)this.setCell(m+y+k,this.loadCell(m+k,_));for(let k=0;k<y;++k)this.setCell(m+k,b)}else for(let _=m;_<this.length;++_)this.setCell(_,b);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,b)}deleteCells(m,y,b){if(m%=this.length,y<this.length-m){const _=new v.CellData;for(let k=0;k<this.length-m-y;++k)this.setCell(m+k,this.loadCell(m+y+k,_));for(let k=this.length-y;k<this.length;++k)this.setCell(k,b)}else for(let _=m;_<this.length;++_)this.setCell(_,b);m&&this.getWidth(m-1)===2&&this.setCellFromCodepoint(m-1,0,1,b),this.getWidth(m)!==0||this.hasContent(m)||this.setCellFromCodepoint(m,0,1,b)}replaceCells(m,y,b,_=!1){if(_)for(m&&this.getWidth(m-1)===2&&!this.isProtected(m-1)&&this.setCellFromCodepoint(m-1,0,1,b),y<this.length&&this.getWidth(y-1)===2&&!this.isProtected(y)&&this.setCellFromCodepoint(y,0,1,b);m<y&&m<this.length;)this.isProtected(m)||this.setCell(m,b),m++;else for(m&&this.getWidth(m-1)===2&&this.setCellFromCodepoint(m-1,0,1,b),y<this.length&&this.getWidth(y-1)===2&&this.setCellFromCodepoint(y,0,1,b);m<y&&m<this.length;)this.setCell(m++,b)}resize(m,y){if(m===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const b=3*m;if(m>this.length){if(this._data.buffer.byteLength>=4*b)this._data=new Uint32Array(this._data.buffer,0,b);else{const _=new Uint32Array(b);_.set(this._data),this._data=_}for(let _=this.length;_<m;++_)this.setCell(_,y)}else{this._data=this._data.subarray(0,b);const _=Object.keys(this._combined);for(let j=0;j<_.length;j++){const T=parseInt(_[j],10);T>=m&&delete this._combined[T]}const k=Object.keys(this._extendedAttrs);for(let j=0;j<k.length;j++){const T=parseInt(k[j],10);T>=m&&delete this._extendedAttrs[T]}}return this.length=m,4*b*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const m=new Uint32Array(this._data.length);return m.set(this._data),this._data=m,1}return 0}fill(m,y=!1){if(y)for(let b=0;b<this.length;++b)this.isProtected(b)||this.setCell(b,m);else{this._combined={},this._extendedAttrs={};for(let b=0;b<this.length;++b)this.setCell(b,m)}}copyFrom(m){this.length!==m.length?this._data=new Uint32Array(m._data):this._data.set(m._data),this.length=m.length,this._combined={};for(const y in m._combined)this._combined[y]=m._combined[y];this._extendedAttrs={};for(const y in m._extendedAttrs)this._extendedAttrs[y]=m._extendedAttrs[y];this.isWrapped=m.isWrapped}clone(){const m=new E(0);m._data=new Uint32Array(this._data),m.length=this.length;for(const y in this._combined)m._combined[y]=this._combined[y];for(const y in this._extendedAttrs)m._extendedAttrs[y]=this._extendedAttrs[y];return m.isWrapped=this.isWrapped,m}getTrimmedLength(){for(let m=this.length-1;m>=0;--m)if(4194303&this._data[3*m+0])return m+(this._data[3*m+0]>>22);return 0}getNoBgTrimmedLength(){for(let m=this.length-1;m>=0;--m)if(4194303&this._data[3*m+0]||50331648&this._data[3*m+2])return m+(this._data[3*m+0]>>22);return 0}copyCellsFrom(m,y,b,_,k){const j=m._data;if(k)for(let D=_-1;D>=0;D--){for(let I=0;I<3;I++)this._data[3*(b+D)+I]=j[3*(y+D)+I];268435456&j[3*(y+D)+2]&&(this._extendedAttrs[b+D]=m._extendedAttrs[y+D])}else for(let D=0;D<_;D++){for(let I=0;I<3;I++)this._data[3*(b+D)+I]=j[3*(y+D)+I];268435456&j[3*(y+D)+2]&&(this._extendedAttrs[b+D]=m._extendedAttrs[y+D])}const T=Object.keys(m._combined);for(let D=0;D<T.length;D++){const I=parseInt(T[D],10);I>=y&&(this._combined[I-y+b]=m._combined[I])}}translateToString(m,y,b,_){y=y??0,b=b??this.length,m&&(b=Math.min(b,this.getTrimmedLength())),_&&(_.length=0);let k="";for(;y<b;){const j=this._data[3*y+0],T=2097151&j,D=2097152&j?this._combined[y]:T?(0,S.stringFromCodePoint)(T):g.WHITESPACE_CELL_CHAR;if(k+=D,_)for(let I=0;I<D.length;++I)_.push(y);y+=j>>22||1}return _&&_.push(y),k}}l.BufferLine=E},4841:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.getRangeLength=void 0,l.getRangeLength=function(u,f){if(u.start.y>u.end.y)throw new Error(`Buffer range end (${u.end.x}, ${u.end.y}) cannot be before start (${u.start.x}, ${u.start.y})`);return f*(u.end.y-u.start.y)+(u.end.x-u.start.x+1)}},4634:(h,l)=>{function u(f,v,g){if(v===f.length-1)return f[v].getTrimmedLength();const S=!f[v].hasContent(g-1)&&f[v].getWidth(g-1)===1,w=f[v+1].getWidth(0)===2;return S&&w?g-1:g}Object.defineProperty(l,"__esModule",{value:!0}),l.getWrappedLineTrimmedLength=l.reflowSmallerGetNewLineLengths=l.reflowLargerApplyNewLayout=l.reflowLargerCreateNewLayout=l.reflowLargerGetLinesToRemove=void 0,l.reflowLargerGetLinesToRemove=function(f,v,g,S,w){const E=[];for(let x=0;x<f.length-1;x++){let m=x,y=f.get(++m);if(!y.isWrapped)continue;const b=[f.get(x)];for(;m<f.length&&y.isWrapped;)b.push(y),y=f.get(++m);if(S>=x&&S<m){x+=b.length-1;continue}let _=0,k=u(b,_,v),j=1,T=0;for(;j<b.length;){const I=u(b,j,v),L=I-T,q=g-k,H=Math.min(L,q);b[_].copyCellsFrom(b[j],T,k,H,!1),k+=H,k===g&&(_++,k=0),T+=H,T===I&&(j++,T=0),k===0&&_!==0&&b[_-1].getWidth(g-1)===2&&(b[_].copyCellsFrom(b[_-1],g-1,k++,1,!1),b[_-1].setCell(g-1,w))}b[_].replaceCells(k,g,w);let D=0;for(let I=b.length-1;I>0&&(I>_||b[I].getTrimmedLength()===0);I--)D++;D>0&&(E.push(x+b.length-D),E.push(D)),x+=b.length-1}return E},l.reflowLargerCreateNewLayout=function(f,v){const g=[];let S=0,w=v[S],E=0;for(let x=0;x<f.length;x++)if(w===x){const m=v[++S];f.onDeleteEmitter.fire({index:x-E,amount:m}),x+=m-1,E+=m,w=v[++S]}else g.push(x);return{layout:g,countRemoved:E}},l.reflowLargerApplyNewLayout=function(f,v){const g=[];for(let S=0;S<v.length;S++)g.push(f.get(v[S]));for(let S=0;S<g.length;S++)f.set(S,g[S]);f.length=v.length},l.reflowSmallerGetNewLineLengths=function(f,v,g){const S=[],w=f.map(((y,b)=>u(f,b,v))).reduce(((y,b)=>y+b));let E=0,x=0,m=0;for(;m<w;){if(w-m<g){S.push(w-m);break}E+=g;const y=u(f,x,v);E>y&&(E-=y,x++);const b=f[x].getWidth(E-1)===2;b&&E--;const _=b?g-1:g;S.push(_),m+=_}return S},l.getWrappedLineTrimmedLength=u},5295:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferSet=void 0;const f=u(8460),v=u(844),g=u(9092);class S extends v.Disposable{constructor(E,x){super(),this._optionsService=E,this._bufferService=x,this._onBufferActivate=this.register(new f.EventEmitter),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 g.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new g.Buffer(!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,x){this._normal.resize(E,x),this._alt.resize(E,x),this.setupTabStops(E)}setupTabStops(E){this._normal.setupTabStops(E),this._alt.setupTabStops(E)}}l.BufferSet=S},511:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CellData=void 0;const f=u(482),v=u(643),g=u(3734);class S extends g.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new g.ExtendedAttrs,this.combinedData=""}static fromCharData(E){const x=new S;return x.setFromCharData(E),x}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,f.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(E){this.fg=E[v.CHAR_DATA_ATTR_INDEX],this.bg=0;let x=!1;if(E[v.CHAR_DATA_CHAR_INDEX].length>2)x=!0;else if(E[v.CHAR_DATA_CHAR_INDEX].length===2){const m=E[v.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=m&&m<=56319){const y=E[v.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=y&&y<=57343?this.content=1024*(m-55296)+y-56320+65536|E[v.CHAR_DATA_WIDTH_INDEX]<<22:x=!0}else x=!0}else this.content=E[v.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|E[v.CHAR_DATA_WIDTH_INDEX]<<22;x&&(this.combinedData=E[v.CHAR_DATA_CHAR_INDEX],this.content=2097152|E[v.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}l.CellData=S},643:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.WHITESPACE_CELL_CODE=l.WHITESPACE_CELL_WIDTH=l.WHITESPACE_CELL_CHAR=l.NULL_CELL_CODE=l.NULL_CELL_WIDTH=l.NULL_CELL_CHAR=l.CHAR_DATA_CODE_INDEX=l.CHAR_DATA_WIDTH_INDEX=l.CHAR_DATA_CHAR_INDEX=l.CHAR_DATA_ATTR_INDEX=l.DEFAULT_EXT=l.DEFAULT_ATTR=l.DEFAULT_COLOR=void 0,l.DEFAULT_COLOR=0,l.DEFAULT_ATTR=256|l.DEFAULT_COLOR<<9,l.DEFAULT_EXT=0,l.CHAR_DATA_ATTR_INDEX=0,l.CHAR_DATA_CHAR_INDEX=1,l.CHAR_DATA_WIDTH_INDEX=2,l.CHAR_DATA_CODE_INDEX=3,l.NULL_CELL_CHAR="",l.NULL_CELL_WIDTH=1,l.NULL_CELL_CODE=0,l.WHITESPACE_CELL_CHAR=" ",l.WHITESPACE_CELL_WIDTH=1,l.WHITESPACE_CELL_CODE=32},4863:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Marker=void 0;const f=u(8460),v=u(844);class g{get id(){return this._id}constructor(w){this.line=w,this.isDisposed=!1,this._disposables=[],this._id=g._nextId++,this._onDispose=this.register(new f.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,v.disposeArray)(this._disposables),this._disposables.length=0)}register(w){return this._disposables.push(w),w}}l.Marker=g,g._nextId=1},7116:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DEFAULT_CHARSET=l.CHARSETS=void 0,l.CHARSETS={},l.DEFAULT_CHARSET=l.CHARSETS.B,l.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},l.CHARSETS.A={"#":"£"},l.CHARSETS.B=void 0,l.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},l.CHARSETS.C=l.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},l.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},l.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},l.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},l.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},l.CHARSETS.E=l.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},l.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},l.CHARSETS.H=l.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},l.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(h,l)=>{var u,f,v;Object.defineProperty(l,"__esModule",{value:!0}),l.C1_ESCAPED=l.C1=l.C0=void 0,(function(g){g.NUL="\0",g.SOH="",g.STX="",g.ETX="",g.EOT="",g.ENQ="",g.ACK="",g.BEL="\x07",g.BS="\b",g.HT=" ",g.LF=`
|
|
85
|
-
`,g.VT="\v",g.FF="\f",g.CR="\r",g.SO="",g.SI="",g.DLE="",g.DC1="",g.DC2="",g.DC3="",g.DC4="",g.NAK="",g.SYN="",g.ETB="",g.CAN="",g.EM="",g.SUB="",g.ESC="\x1B",g.FS="",g.GS="",g.RS="",g.US="",g.SP=" ",g.DEL=""})(u||(l.C0=u={})),(function(g){g.PAD="",g.HOP="",g.BPH="",g.NBH="",g.IND="",g.NEL="
",g.SSA="",g.ESA="",g.HTS="",g.HTJ="",g.VTS="",g.PLD="",g.PLU="",g.RI="",g.SS2="",g.SS3="",g.DCS="",g.PU1="",g.PU2="",g.STS="",g.CCH="",g.MW="",g.SPA="",g.EPA="",g.SOS="",g.SGCI="",g.SCI="",g.CSI="",g.ST="",g.OSC="",g.PM="",g.APC=""})(f||(l.C1=f={})),(function(g){g.ST=`${u.ESC}\\`})(v||(l.C1_ESCAPED=v={}))},7399:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.evaluateKeyboardEvent=void 0;const f=u(2584),v={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:["'",'"']};l.evaluateKeyboardEvent=function(g,S,w,E){const x={type:0,cancel:!1,key:void 0},m=(g.shiftKey?1:0)|(g.altKey?2:0)|(g.ctrlKey?4:0)|(g.metaKey?8:0);switch(g.keyCode){case 0:g.key==="UIKeyInputUpArrow"?x.key=S?f.C0.ESC+"OA":f.C0.ESC+"[A":g.key==="UIKeyInputLeftArrow"?x.key=S?f.C0.ESC+"OD":f.C0.ESC+"[D":g.key==="UIKeyInputRightArrow"?x.key=S?f.C0.ESC+"OC":f.C0.ESC+"[C":g.key==="UIKeyInputDownArrow"&&(x.key=S?f.C0.ESC+"OB":f.C0.ESC+"[B");break;case 8:x.key=g.ctrlKey?"\b":f.C0.DEL,g.altKey&&(x.key=f.C0.ESC+x.key);break;case 9:if(g.shiftKey){x.key=f.C0.ESC+"[Z";break}x.key=f.C0.HT,x.cancel=!0;break;case 13:x.key=g.altKey?f.C0.ESC+f.C0.CR:f.C0.CR,x.cancel=!0;break;case 27:x.key=f.C0.ESC,g.altKey&&(x.key=f.C0.ESC+f.C0.ESC),x.cancel=!0;break;case 37:if(g.metaKey)break;m?(x.key=f.C0.ESC+"[1;"+(m+1)+"D",x.key===f.C0.ESC+"[1;3D"&&(x.key=f.C0.ESC+(w?"b":"[1;5D"))):x.key=S?f.C0.ESC+"OD":f.C0.ESC+"[D";break;case 39:if(g.metaKey)break;m?(x.key=f.C0.ESC+"[1;"+(m+1)+"C",x.key===f.C0.ESC+"[1;3C"&&(x.key=f.C0.ESC+(w?"f":"[1;5C"))):x.key=S?f.C0.ESC+"OC":f.C0.ESC+"[C";break;case 38:if(g.metaKey)break;m?(x.key=f.C0.ESC+"[1;"+(m+1)+"A",w||x.key!==f.C0.ESC+"[1;3A"||(x.key=f.C0.ESC+"[1;5A")):x.key=S?f.C0.ESC+"OA":f.C0.ESC+"[A";break;case 40:if(g.metaKey)break;m?(x.key=f.C0.ESC+"[1;"+(m+1)+"B",w||x.key!==f.C0.ESC+"[1;3B"||(x.key=f.C0.ESC+"[1;5B")):x.key=S?f.C0.ESC+"OB":f.C0.ESC+"[B";break;case 45:g.shiftKey||g.ctrlKey||(x.key=f.C0.ESC+"[2~");break;case 46:x.key=m?f.C0.ESC+"[3;"+(m+1)+"~":f.C0.ESC+"[3~";break;case 36:x.key=m?f.C0.ESC+"[1;"+(m+1)+"H":S?f.C0.ESC+"OH":f.C0.ESC+"[H";break;case 35:x.key=m?f.C0.ESC+"[1;"+(m+1)+"F":S?f.C0.ESC+"OF":f.C0.ESC+"[F";break;case 33:g.shiftKey?x.type=2:g.ctrlKey?x.key=f.C0.ESC+"[5;"+(m+1)+"~":x.key=f.C0.ESC+"[5~";break;case 34:g.shiftKey?x.type=3:g.ctrlKey?x.key=f.C0.ESC+"[6;"+(m+1)+"~":x.key=f.C0.ESC+"[6~";break;case 112:x.key=m?f.C0.ESC+"[1;"+(m+1)+"P":f.C0.ESC+"OP";break;case 113:x.key=m?f.C0.ESC+"[1;"+(m+1)+"Q":f.C0.ESC+"OQ";break;case 114:x.key=m?f.C0.ESC+"[1;"+(m+1)+"R":f.C0.ESC+"OR";break;case 115:x.key=m?f.C0.ESC+"[1;"+(m+1)+"S":f.C0.ESC+"OS";break;case 116:x.key=m?f.C0.ESC+"[15;"+(m+1)+"~":f.C0.ESC+"[15~";break;case 117:x.key=m?f.C0.ESC+"[17;"+(m+1)+"~":f.C0.ESC+"[17~";break;case 118:x.key=m?f.C0.ESC+"[18;"+(m+1)+"~":f.C0.ESC+"[18~";break;case 119:x.key=m?f.C0.ESC+"[19;"+(m+1)+"~":f.C0.ESC+"[19~";break;case 120:x.key=m?f.C0.ESC+"[20;"+(m+1)+"~":f.C0.ESC+"[20~";break;case 121:x.key=m?f.C0.ESC+"[21;"+(m+1)+"~":f.C0.ESC+"[21~";break;case 122:x.key=m?f.C0.ESC+"[23;"+(m+1)+"~":f.C0.ESC+"[23~";break;case 123:x.key=m?f.C0.ESC+"[24;"+(m+1)+"~":f.C0.ESC+"[24~";break;default:if(!g.ctrlKey||g.shiftKey||g.altKey||g.metaKey)if(w&&!E||!g.altKey||g.metaKey)!w||g.altKey||g.ctrlKey||g.shiftKey||!g.metaKey?g.key&&!g.ctrlKey&&!g.altKey&&!g.metaKey&&g.keyCode>=48&&g.key.length===1?x.key=g.key:g.key&&g.ctrlKey&&(g.key==="_"&&(x.key=f.C0.US),g.key==="@"&&(x.key=f.C0.NUL)):g.keyCode===65&&(x.type=1);else{const y=v[g.keyCode],b=y?.[g.shiftKey?1:0];if(b)x.key=f.C0.ESC+b;else if(g.keyCode>=65&&g.keyCode<=90){const _=g.ctrlKey?g.keyCode-64:g.keyCode+32;let k=String.fromCharCode(_);g.shiftKey&&(k=k.toUpperCase()),x.key=f.C0.ESC+k}else if(g.keyCode===32)x.key=f.C0.ESC+(g.ctrlKey?f.C0.NUL:" ");else if(g.key==="Dead"&&g.code.startsWith("Key")){let _=g.code.slice(3,4);g.shiftKey||(_=_.toLowerCase()),x.key=f.C0.ESC+_,x.cancel=!0}}else g.keyCode>=65&&g.keyCode<=90?x.key=String.fromCharCode(g.keyCode-64):g.keyCode===32?x.key=f.C0.NUL:g.keyCode>=51&&g.keyCode<=55?x.key=String.fromCharCode(g.keyCode-51+27):g.keyCode===56?x.key=f.C0.DEL:g.keyCode===219?x.key=f.C0.ESC:g.keyCode===220?x.key=f.C0.FS:g.keyCode===221&&(x.key=f.C0.GS)}return x}},482:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Utf8ToUtf32=l.StringToUtf32=l.utf32ToString=l.stringFromCodePoint=void 0,l.stringFromCodePoint=function(u){return u>65535?(u-=65536,String.fromCharCode(55296+(u>>10))+String.fromCharCode(u%1024+56320)):String.fromCharCode(u)},l.utf32ToString=function(u,f=0,v=u.length){let g="";for(let S=f;S<v;++S){let w=u[S];w>65535?(w-=65536,g+=String.fromCharCode(55296+(w>>10))+String.fromCharCode(w%1024+56320)):g+=String.fromCharCode(w)}return g},l.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(u,f){const v=u.length;if(!v)return 0;let g=0,S=0;if(this._interim){const w=u.charCodeAt(S++);56320<=w&&w<=57343?f[g++]=1024*(this._interim-55296)+w-56320+65536:(f[g++]=this._interim,f[g++]=w),this._interim=0}for(let w=S;w<v;++w){const E=u.charCodeAt(w);if(55296<=E&&E<=56319){if(++w>=v)return this._interim=E,g;const x=u.charCodeAt(w);56320<=x&&x<=57343?f[g++]=1024*(E-55296)+x-56320+65536:(f[g++]=E,f[g++]=x)}else E!==65279&&(f[g++]=E)}return g}},l.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(u,f){const v=u.length;if(!v)return 0;let g,S,w,E,x=0,m=0,y=0;if(this.interim[0]){let k=!1,j=this.interim[0];j&=(224&j)==192?31:(240&j)==224?15:7;let T,D=0;for(;(T=63&this.interim[++D])&&D<4;)j<<=6,j|=T;const I=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,L=I-D;for(;y<L;){if(y>=v)return 0;if(T=u[y++],(192&T)!=128){y--,k=!0;break}this.interim[D++]=T,j<<=6,j|=63&T}k||(I===2?j<128?y--:f[x++]=j:I===3?j<2048||j>=55296&&j<=57343||j===65279||(f[x++]=j):j<65536||j>1114111||(f[x++]=j)),this.interim.fill(0)}const b=v-4;let _=y;for(;_<v;){for(;!(!(_<b)||128&(g=u[_])||128&(S=u[_+1])||128&(w=u[_+2])||128&(E=u[_+3]));)f[x++]=g,f[x++]=S,f[x++]=w,f[x++]=E,_+=4;if(g=u[_++],g<128)f[x++]=g;else if((224&g)==192){if(_>=v)return this.interim[0]=g,x;if(S=u[_++],(192&S)!=128){_--;continue}if(m=(31&g)<<6|63&S,m<128){_--;continue}f[x++]=m}else if((240&g)==224){if(_>=v)return this.interim[0]=g,x;if(S=u[_++],(192&S)!=128){_--;continue}if(_>=v)return this.interim[0]=g,this.interim[1]=S,x;if(w=u[_++],(192&w)!=128){_--;continue}if(m=(15&g)<<12|(63&S)<<6|63&w,m<2048||m>=55296&&m<=57343||m===65279)continue;f[x++]=m}else if((248&g)==240){if(_>=v)return this.interim[0]=g,x;if(S=u[_++],(192&S)!=128){_--;continue}if(_>=v)return this.interim[0]=g,this.interim[1]=S,x;if(w=u[_++],(192&w)!=128){_--;continue}if(_>=v)return this.interim[0]=g,this.interim[1]=S,this.interim[2]=w,x;if(E=u[_++],(192&E)!=128){_--;continue}if(m=(7&g)<<18|(63&S)<<12|(63&w)<<6|63&E,m<65536||m>1114111)continue;f[x++]=m}}return x}}},225:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.UnicodeV6=void 0;const f=u(1480),v=[[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]],g=[[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]];let S;l.UnicodeV6=class{constructor(){if(this.version="6",!S){S=new Uint8Array(65536),S.fill(1),S[0]=0,S.fill(0,1,32),S.fill(0,127,160),S.fill(2,4352,4448),S[9001]=2,S[9002]=2,S.fill(2,11904,42192),S[12351]=1,S.fill(2,44032,55204),S.fill(2,63744,64256),S.fill(2,65040,65050),S.fill(2,65072,65136),S.fill(2,65280,65377),S.fill(2,65504,65511);for(let w=0;w<v.length;++w)S.fill(0,v[w][0],v[w][1]+1)}}wcwidth(w){return w<32?0:w<127?1:w<65536?S[w]:(function(E,x){let m,y=0,b=x.length-1;if(E<x[0][0]||E>x[b][1])return!1;for(;b>=y;)if(m=y+b>>1,E>x[m][1])y=m+1;else{if(!(E<x[m][0]))return!0;b=m-1}return!1})(w,g)?0:w>=131072&&w<=196605||w>=196608&&w<=262141?2:1}charProperties(w,E){let x=this.wcwidth(w),m=x===0&&E!==0;if(m){const y=f.UnicodeService.extractWidth(E);y===0?m=!1:y>x&&(x=y)}return f.UnicodeService.createPropertyValue(0,x,m)}}},5981:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.WriteBuffer=void 0;const f=u(8460),v=u(844);class g extends v.Disposable{constructor(w){super(),this._action=w,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new f.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(w,E){if(E!==void 0&&this._syncCalls>E)return void(this._syncCalls=0);if(this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let x;for(this._isSyncWriting=!0;x=this._writeBuffer.shift();){this._action(x);const m=this._callbacks.shift();m&&m()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(w,E){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(E),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=w.length,this._writeBuffer.push(w),this._callbacks.push(E)}_innerWrite(w=0,E=!0){const x=w||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const m=this._writeBuffer[this._bufferOffset],y=this._action(m,E);if(y){const _=k=>Date.now()-x>=12?setTimeout((()=>this._innerWrite(0,k))):this._innerWrite(x,k);return void y.catch((k=>(queueMicrotask((()=>{throw k})),Promise.resolve(!1)))).then(_)}const b=this._callbacks[this._bufferOffset];if(b&&b(),this._bufferOffset++,this._pendingData-=m.length,Date.now()-x>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(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()}}l.WriteBuffer=g},5941:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.toRgbString=l.parseColor=void 0;const u=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,f=/^[\da-f]+$/;function v(g,S){const w=g.toString(16),E=w.length<2?"0"+w:w;switch(S){case 4:return w[0];case 8:return E;case 12:return(E+E).slice(0,3);default:return E+E}}l.parseColor=function(g){if(!g)return;let S=g.toLowerCase();if(S.indexOf("rgb:")===0){S=S.slice(4);const w=u.exec(S);if(w){const E=w[1]?15:w[4]?255:w[7]?4095:65535;return[Math.round(parseInt(w[1]||w[4]||w[7]||w[10],16)/E*255),Math.round(parseInt(w[2]||w[5]||w[8]||w[11],16)/E*255),Math.round(parseInt(w[3]||w[6]||w[9]||w[12],16)/E*255)]}}else if(S.indexOf("#")===0&&(S=S.slice(1),f.exec(S)&&[3,6,9,12].includes(S.length))){const w=S.length/3,E=[0,0,0];for(let x=0;x<3;++x){const m=parseInt(S.slice(w*x,w*x+w),16);E[x]=w===1?m<<4:w===2?m:w===3?m>>4:m>>8}return E}},l.toRgbString=function(g,S=16){const[w,E,x]=g;return`rgb:${v(w,S)}/${v(E,S)}/${v(x,S)}`}},5770:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.PAYLOAD_LIMIT=void 0,l.PAYLOAD_LIMIT=1e7},6351:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DcsHandler=l.DcsParser=void 0;const f=u(482),v=u(8742),g=u(5770),S=[];l.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=S,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=S}registerHandler(E,x){this._handlers[E]===void 0&&(this._handlers[E]=[]);const m=this._handlers[E];return m.push(x),{dispose:()=>{const y=m.indexOf(x);y!==-1&&m.splice(y,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=S,this._ident=0}hook(E,x){if(this.reset(),this._ident=E,this._active=this._handlers[E]||S,this._active.length)for(let m=this._active.length-1;m>=0;m--)this._active[m].hook(x);else this._handlerFb(this._ident,"HOOK",x)}put(E,x,m){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(E,x,m);else this._handlerFb(this._ident,"PUT",(0,f.utf32ToString)(E,x,m))}unhook(E,x=!0){if(this._active.length){let m=!1,y=this._active.length-1,b=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,m=x,b=this._stack.fallThrough,this._stack.paused=!1),!b&&m===!1){for(;y>=0&&(m=this._active[y].unhook(E),m!==!0);y--)if(m instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,m;y--}for(;y>=0;y--)if(m=this._active[y].unhook(!1),m instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,m}else this._handlerFb(this._ident,"UNHOOK",E);this._active=S,this._ident=0}};const w=new v.Params;w.addParam(0),l.DcsHandler=class{constructor(E){this._handler=E,this._data="",this._params=w,this._hitLimit=!1}hook(E){this._params=E.length>1||E.params[0]?E.clone():w,this._data="",this._hitLimit=!1}put(E,x,m){this._hitLimit||(this._data+=(0,f.utf32ToString)(E,x,m),this._data.length>g.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(E){let x=!1;if(this._hitLimit)x=!1;else if(E&&(x=this._handler(this._data,this._params),x instanceof Promise))return x.then((m=>(this._params=w,this._data="",this._hitLimit=!1,m)));return this._params=w,this._data="",this._hitLimit=!1,x}}},2015:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.EscapeSequenceParser=l.VT500_TRANSITION_TABLE=l.TransitionTable=void 0;const f=u(844),v=u(8742),g=u(6242),S=u(6351);class w{constructor(y){this.table=new Uint8Array(y)}setDefault(y,b){this.table.fill(y<<4|b)}add(y,b,_,k){this.table[b<<8|y]=_<<4|k}addMany(y,b,_,k){for(let j=0;j<y.length;j++)this.table[b<<8|y[j]]=_<<4|k}}l.TransitionTable=w;const E=160;l.VT500_TRANSITION_TABLE=(function(){const m=new w(4095),y=Array.apply(null,Array(256)).map(((D,I)=>I)),b=(D,I)=>y.slice(D,I),_=b(32,127),k=b(0,24);k.push(25),k.push.apply(k,b(28,32));const j=b(0,14);let T;for(T in m.setDefault(1,0),m.addMany(_,0,2,0),j)m.addMany([24,26,153,154],T,3,0),m.addMany(b(128,144),T,3,0),m.addMany(b(144,152),T,3,0),m.add(156,T,0,0),m.add(27,T,11,1),m.add(157,T,4,8),m.addMany([152,158,159],T,0,7),m.add(155,T,11,3),m.add(144,T,11,9);return m.addMany(k,0,3,0),m.addMany(k,1,3,1),m.add(127,1,0,1),m.addMany(k,8,0,8),m.addMany(k,3,3,3),m.add(127,3,0,3),m.addMany(k,4,3,4),m.add(127,4,0,4),m.addMany(k,6,3,6),m.addMany(k,5,3,5),m.add(127,5,0,5),m.addMany(k,2,3,2),m.add(127,2,0,2),m.add(93,1,4,8),m.addMany(_,8,5,8),m.add(127,8,5,8),m.addMany([156,27,24,26,7],8,6,0),m.addMany(b(28,32),8,0,8),m.addMany([88,94,95],1,0,7),m.addMany(_,7,0,7),m.addMany(k,7,0,7),m.add(156,7,0,0),m.add(127,7,0,7),m.add(91,1,11,3),m.addMany(b(64,127),3,7,0),m.addMany(b(48,60),3,8,4),m.addMany([60,61,62,63],3,9,4),m.addMany(b(48,60),4,8,4),m.addMany(b(64,127),4,7,0),m.addMany([60,61,62,63],4,0,6),m.addMany(b(32,64),6,0,6),m.add(127,6,0,6),m.addMany(b(64,127),6,0,0),m.addMany(b(32,48),3,9,5),m.addMany(b(32,48),5,9,5),m.addMany(b(48,64),5,0,6),m.addMany(b(64,127),5,7,0),m.addMany(b(32,48),4,9,5),m.addMany(b(32,48),1,9,2),m.addMany(b(32,48),2,9,2),m.addMany(b(48,127),2,10,0),m.addMany(b(48,80),1,10,0),m.addMany(b(81,88),1,10,0),m.addMany([89,90,92],1,10,0),m.addMany(b(96,127),1,10,0),m.add(80,1,11,9),m.addMany(k,9,0,9),m.add(127,9,0,9),m.addMany(b(28,32),9,0,9),m.addMany(b(32,48),9,9,12),m.addMany(b(48,60),9,8,10),m.addMany([60,61,62,63],9,9,10),m.addMany(k,11,0,11),m.addMany(b(32,128),11,0,11),m.addMany(b(28,32),11,0,11),m.addMany(k,10,0,10),m.add(127,10,0,10),m.addMany(b(28,32),10,0,10),m.addMany(b(48,60),10,8,10),m.addMany([60,61,62,63],10,0,11),m.addMany(b(32,48),10,9,12),m.addMany(k,12,0,12),m.add(127,12,0,12),m.addMany(b(28,32),12,0,12),m.addMany(b(32,48),12,9,12),m.addMany(b(48,64),12,0,11),m.addMany(b(64,127),12,12,13),m.addMany(b(64,127),10,12,13),m.addMany(b(64,127),9,12,13),m.addMany(k,13,13,13),m.addMany(_,13,13,13),m.add(127,13,0,13),m.addMany([27,156,24,26],13,14,0),m.add(E,0,2,0),m.add(E,8,5,8),m.add(E,6,0,6),m.add(E,11,0,11),m.add(E,13,13,13),m})();class x extends f.Disposable{constructor(y=l.VT500_TRANSITION_TABLE){super(),this._transitions=y,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new v.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(b,_,k)=>{},this._executeHandlerFb=b=>{},this._csiHandlerFb=(b,_)=>{},this._escHandlerFb=b=>{},this._errorHandlerFb=b=>b,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,f.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new g.OscParser),this._dcsParser=this.register(new S.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(y,b=[64,126]){let _=0;if(y.prefix){if(y.prefix.length>1)throw new Error("only one byte as prefix supported");if(_=y.prefix.charCodeAt(0),_&&60>_||_>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(y.intermediates){if(y.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let j=0;j<y.intermediates.length;++j){const T=y.intermediates.charCodeAt(j);if(32>T||T>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");_<<=8,_|=T}}if(y.final.length!==1)throw new Error("final must be a single byte");const k=y.final.charCodeAt(0);if(b[0]>k||k>b[1])throw new Error(`final must be in range ${b[0]} .. ${b[1]}`);return _<<=8,_|=k,_}identToString(y){const b=[];for(;y;)b.push(String.fromCharCode(255&y)),y>>=8;return b.reverse().join("")}setPrintHandler(y){this._printHandler=y}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(y,b){const _=this._identifier(y,[48,126]);this._escHandlers[_]===void 0&&(this._escHandlers[_]=[]);const k=this._escHandlers[_];return k.push(b),{dispose:()=>{const j=k.indexOf(b);j!==-1&&k.splice(j,1)}}}clearEscHandler(y){this._escHandlers[this._identifier(y,[48,126])]&&delete this._escHandlers[this._identifier(y,[48,126])]}setEscHandlerFallback(y){this._escHandlerFb=y}setExecuteHandler(y,b){this._executeHandlers[y.charCodeAt(0)]=b}clearExecuteHandler(y){this._executeHandlers[y.charCodeAt(0)]&&delete this._executeHandlers[y.charCodeAt(0)]}setExecuteHandlerFallback(y){this._executeHandlerFb=y}registerCsiHandler(y,b){const _=this._identifier(y);this._csiHandlers[_]===void 0&&(this._csiHandlers[_]=[]);const k=this._csiHandlers[_];return k.push(b),{dispose:()=>{const j=k.indexOf(b);j!==-1&&k.splice(j,1)}}}clearCsiHandler(y){this._csiHandlers[this._identifier(y)]&&delete this._csiHandlers[this._identifier(y)]}setCsiHandlerFallback(y){this._csiHandlerFb=y}registerDcsHandler(y,b){return this._dcsParser.registerHandler(this._identifier(y),b)}clearDcsHandler(y){this._dcsParser.clearHandler(this._identifier(y))}setDcsHandlerFallback(y){this._dcsParser.setHandlerFallback(y)}registerOscHandler(y,b){return this._oscParser.registerHandler(y,b)}clearOscHandler(y){this._oscParser.clearHandler(y)}setOscHandlerFallback(y){this._oscParser.setHandlerFallback(y)}setErrorHandler(y){this._errorHandler=y}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(y,b,_,k,j){this._parseStack.state=y,this._parseStack.handlers=b,this._parseStack.handlerPos=_,this._parseStack.transition=k,this._parseStack.chunkPos=j}parse(y,b,_){let k,j=0,T=0,D=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,D=this._parseStack.chunkPos+1;else{if(_===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const I=this._parseStack.handlers;let L=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(_===!1&&L>-1){for(;L>=0&&(k=I[L](this._params),k!==!0);L--)if(k instanceof Promise)return this._parseStack.handlerPos=L,k}this._parseStack.handlers=[];break;case 4:if(_===!1&&L>-1){for(;L>=0&&(k=I[L](),k!==!0);L--)if(k instanceof Promise)return this._parseStack.handlerPos=L,k}this._parseStack.handlers=[];break;case 6:if(j=y[this._parseStack.chunkPos],k=this._dcsParser.unhook(j!==24&&j!==26,_),k)return k;j===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(j=y[this._parseStack.chunkPos],k=this._oscParser.end(j!==24&&j!==26,_),k)return k;j===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,D=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let I=D;I<b;++I){switch(j=y[I],T=this._transitions.table[this.currentState<<8|(j<160?j:E)],T>>4){case 2:for(let F=I+1;;++F){if(F>=b||(j=y[F])<32||j>126&&j<E){this._printHandler(y,I,F),I=F-1;break}if(++F>=b||(j=y[F])<32||j>126&&j<E){this._printHandler(y,I,F),I=F-1;break}if(++F>=b||(j=y[F])<32||j>126&&j<E){this._printHandler(y,I,F),I=F-1;break}if(++F>=b||(j=y[F])<32||j>126&&j<E){this._printHandler(y,I,F),I=F-1;break}}break;case 3:this._executeHandlers[j]?this._executeHandlers[j]():this._executeHandlerFb(j),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:I,code:j,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const L=this._csiHandlers[this._collect<<8|j];let q=L?L.length-1:-1;for(;q>=0&&(k=L[q](this._params),k!==!0);q--)if(k instanceof Promise)return this._preserveStack(3,L,q,T,I),k;q<0&&this._csiHandlerFb(this._collect<<8|j,this._params),this.precedingJoinState=0;break;case 8:do switch(j){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(j-48)}while(++I<b&&(j=y[I])>47&&j<60);I--;break;case 9:this._collect<<=8,this._collect|=j;break;case 10:const H=this._escHandlers[this._collect<<8|j];let Q=H?H.length-1:-1;for(;Q>=0&&(k=H[Q](),k!==!0);Q--)if(k instanceof Promise)return this._preserveStack(4,H,Q,T,I),k;Q<0&&this._escHandlerFb(this._collect<<8|j),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|j,this._params);break;case 13:for(let F=I+1;;++F)if(F>=b||(j=y[F])===24||j===26||j===27||j>127&&j<E){this._dcsParser.put(y,I,F),I=F-1;break}break;case 14:if(k=this._dcsParser.unhook(j!==24&&j!==26),k)return this._preserveStack(6,[],0,T,I),k;j===27&&(T|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let F=I+1;;F++)if(F>=b||(j=y[F])<32||j>127&&j<E){this._oscParser.put(y,I,F),I=F-1;break}break;case 6:if(k=this._oscParser.end(j!==24&&j!==26),k)return this._preserveStack(5,[],0,T,I),k;j===27&&(T|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&T}}}l.EscapeSequenceParser=x},6242:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.OscHandler=l.OscParser=void 0;const f=u(5770),v=u(482),g=[];l.OscParser=class{constructor(){this._state=0,this._active=g,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(S,w){this._handlers[S]===void 0&&(this._handlers[S]=[]);const E=this._handlers[S];return E.push(w),{dispose:()=>{const x=E.indexOf(w);x!==-1&&E.splice(x,1)}}}clearHandler(S){this._handlers[S]&&delete this._handlers[S]}setHandlerFallback(S){this._handlerFb=S}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=g}reset(){if(this._state===2)for(let S=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;S>=0;--S)this._active[S].end(!1);this._stack.paused=!1,this._active=g,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||g,this._active.length)for(let S=this._active.length-1;S>=0;S--)this._active[S].start();else this._handlerFb(this._id,"START")}_put(S,w,E){if(this._active.length)for(let x=this._active.length-1;x>=0;x--)this._active[x].put(S,w,E);else this._handlerFb(this._id,"PUT",(0,v.utf32ToString)(S,w,E))}start(){this.reset(),this._state=1}put(S,w,E){if(this._state!==3){if(this._state===1)for(;w<E;){const x=S[w++];if(x===59){this._state=2,this._start();break}if(x<48||57<x)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+x-48}this._state===2&&E-w>0&&this._put(S,w,E)}}end(S,w=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let E=!1,x=this._active.length-1,m=!1;if(this._stack.paused&&(x=this._stack.loopPosition-1,E=w,m=this._stack.fallThrough,this._stack.paused=!1),!m&&E===!1){for(;x>=0&&(E=this._active[x].end(S),E!==!0);x--)if(E instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=x,this._stack.fallThrough=!1,E;x--}for(;x>=0;x--)if(E=this._active[x].end(!1),E instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=x,this._stack.fallThrough=!0,E}else this._handlerFb(this._id,"END",S);this._active=g,this._id=-1,this._state=0}}},l.OscHandler=class{constructor(S){this._handler=S,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(S,w,E){this._hitLimit||(this._data+=(0,v.utf32ToString)(S,w,E),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(S){let w=!1;if(this._hitLimit)w=!1;else if(S&&(w=this._handler(this._data),w instanceof Promise))return w.then((E=>(this._data="",this._hitLimit=!1,E)));return this._data="",this._hitLimit=!1,w}}},8742:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Params=void 0;const u=2147483647;class f{static fromArray(g){const S=new f;if(!g.length)return S;for(let w=Array.isArray(g[0])?1:0;w<g.length;++w){const E=g[w];if(Array.isArray(E))for(let x=0;x<E.length;++x)S.addSubParam(E[x]);else S.addParam(E)}return S}constructor(g=32,S=32){if(this.maxLength=g,this.maxSubParamsLength=S,S>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(g),this.length=0,this._subParams=new Int32Array(S),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(g),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const g=new f(this.maxLength,this.maxSubParamsLength);return g.params.set(this.params),g.length=this.length,g._subParams.set(this._subParams),g._subParamsLength=this._subParamsLength,g._subParamsIdx.set(this._subParamsIdx),g._rejectDigits=this._rejectDigits,g._rejectSubDigits=this._rejectSubDigits,g._digitIsSub=this._digitIsSub,g}toArray(){const g=[];for(let S=0;S<this.length;++S){g.push(this.params[S]);const w=this._subParamsIdx[S]>>8,E=255&this._subParamsIdx[S];E-w>0&&g.push(Array.prototype.slice.call(this._subParams,w,E))}return g}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(g){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(g<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=g>u?u:g}}addSubParam(g){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(g<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=g>u?u:g,this._subParamsIdx[this.length-1]++}}hasSubParams(g){return(255&this._subParamsIdx[g])-(this._subParamsIdx[g]>>8)>0}getSubParams(g){const S=this._subParamsIdx[g]>>8,w=255&this._subParamsIdx[g];return w-S>0?this._subParams.subarray(S,w):null}getSubParamsAll(){const g={};for(let S=0;S<this.length;++S){const w=this._subParamsIdx[S]>>8,E=255&this._subParamsIdx[S];E-w>0&&(g[S]=this._subParams.slice(w,E))}return g}addDigit(g){let S;if(this._rejectDigits||!(S=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const w=this._digitIsSub?this._subParams:this.params,E=w[S-1];w[S-1]=~E?Math.min(10*E+g,u):g}}l.Params=f},5741:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.AddonManager=void 0,l.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let u=this._addons.length-1;u>=0;u--)this._addons[u].instance.dispose()}loadAddon(u,f){const v={instance:f,dispose:f.dispose,isDisposed:!1};this._addons.push(v),f.dispose=()=>this._wrappedAddonDispose(v),f.activate(u)}_wrappedAddonDispose(u){if(u.isDisposed)return;let f=-1;for(let v=0;v<this._addons.length;v++)if(this._addons[v]===u){f=v;break}if(f===-1)throw new Error("Could not dispose an addon that has not been loaded");u.isDisposed=!0,u.dispose.apply(u.instance),this._addons.splice(f,1)}}},8771:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferApiView=void 0;const f=u(3785),v=u(511);l.BufferApiView=class{constructor(g,S){this._buffer=g,this.type=S}init(g){return this._buffer=g,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(g){const S=this._buffer.lines.get(g);if(S)return new f.BufferLineApiView(S)}getNullCell(){return new v.CellData}}},3785:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferLineApiView=void 0;const f=u(511);l.BufferLineApiView=class{constructor(v){this._line=v}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(v,g){if(!(v<0||v>=this._line.length))return g?(this._line.loadCell(v,g),g):this._line.loadCell(v,new f.CellData)}translateToString(v,g,S){return this._line.translateToString(v,g,S)}}},8285:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferNamespaceApi=void 0;const f=u(8771),v=u(8460),g=u(844);class S extends g.Disposable{constructor(E){super(),this._core=E,this._onBufferChange=this.register(new v.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new f.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new f.BufferApiView(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)}}l.BufferNamespaceApi=S},7975:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ParserApi=void 0,l.ParserApi=class{constructor(u){this._core=u}registerCsiHandler(u,f){return this._core.registerCsiHandler(u,(v=>f(v.toArray())))}addCsiHandler(u,f){return this.registerCsiHandler(u,f)}registerDcsHandler(u,f){return this._core.registerDcsHandler(u,((v,g)=>f(v,g.toArray())))}addDcsHandler(u,f){return this.registerDcsHandler(u,f)}registerEscHandler(u,f){return this._core.registerEscHandler(u,f)}addEscHandler(u,f){return this.registerEscHandler(u,f)}registerOscHandler(u,f){return this._core.registerOscHandler(u,f)}addOscHandler(u,f){return this.registerOscHandler(u,f)}}},7090:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.UnicodeApi=void 0,l.UnicodeApi=class{constructor(u){this._core=u}register(u){this._core.unicodeService.register(u)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(u){this._core.unicodeService.activeVersion=u}}},744:function(h,l,u){var f=this&&this.__decorate||function(m,y,b,_){var k,j=arguments.length,T=j<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,b,_);else for(var D=m.length-1;D>=0;D--)(k=m[D])&&(T=(j<3?k(T):j>3?k(y,b,T):k(y,b))||T);return j>3&&T&&Object.defineProperty(y,b,T),T},v=this&&this.__param||function(m,y){return function(b,_){y(b,_,m)}};Object.defineProperty(l,"__esModule",{value:!0}),l.BufferService=l.MINIMUM_ROWS=l.MINIMUM_COLS=void 0;const g=u(8460),S=u(844),w=u(5295),E=u(2585);l.MINIMUM_COLS=2,l.MINIMUM_ROWS=1;let x=l.BufferService=class extends S.Disposable{get buffer(){return this.buffers.active}constructor(m){super(),this.isUserScrolling=!1,this._onResize=this.register(new g.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new g.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(m.rawOptions.cols||0,l.MINIMUM_COLS),this.rows=Math.max(m.rawOptions.rows||0,l.MINIMUM_ROWS),this.buffers=this.register(new w.BufferSet(m,this))}resize(m,y){this.cols=m,this.rows=y,this.buffers.resize(m,y),this._onResize.fire({cols:m,rows:y})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(m,y=!1){const b=this.buffer;let _;_=this._cachedBlankLine,_&&_.length===this.cols&&_.getFg(0)===m.fg&&_.getBg(0)===m.bg||(_=b.getBlankLine(m,y),this._cachedBlankLine=_),_.isWrapped=y;const k=b.ybase+b.scrollTop,j=b.ybase+b.scrollBottom;if(b.scrollTop===0){const T=b.lines.isFull;j===b.lines.length-1?T?b.lines.recycle().copyFrom(_):b.lines.push(_.clone()):b.lines.splice(j+1,0,_.clone()),T?this.isUserScrolling&&(b.ydisp=Math.max(b.ydisp-1,0)):(b.ybase++,this.isUserScrolling||b.ydisp++)}else{const T=j-k+1;b.lines.shiftElements(k+1,T-1,-1),b.lines.set(j,_.clone())}this.isUserScrolling||(b.ydisp=b.ybase),this._onScroll.fire(b.ydisp)}scrollLines(m,y,b){const _=this.buffer;if(m<0){if(_.ydisp===0)return;this.isUserScrolling=!0}else m+_.ydisp>=_.ybase&&(this.isUserScrolling=!1);const k=_.ydisp;_.ydisp=Math.max(Math.min(_.ydisp+m,_.ybase),0),k!==_.ydisp&&(y||this._onScroll.fire(_.ydisp))}};l.BufferService=x=f([v(0,E.IOptionsService)],x)},7994:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CharsetService=void 0,l.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(u){this.glevel=u,this.charset=this._charsets[u]}setgCharset(u,f){this._charsets[u]=f,this.glevel===u&&(this.charset=f)}}},1753:function(h,l,u){var f=this&&this.__decorate||function(_,k,j,T){var D,I=arguments.length,L=I<3?k:T===null?T=Object.getOwnPropertyDescriptor(k,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(_,k,j,T);else for(var q=_.length-1;q>=0;q--)(D=_[q])&&(L=(I<3?D(L):I>3?D(k,j,L):D(k,j))||L);return I>3&&L&&Object.defineProperty(k,j,L),L},v=this&&this.__param||function(_,k){return function(j,T){k(j,T,_)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CoreMouseService=void 0;const g=u(2585),S=u(8460),w=u(844),E={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:_=>_.button!==4&&_.action===1&&(_.ctrl=!1,_.alt=!1,_.shift=!1,!0)},VT200:{events:19,restrict:_=>_.action!==32},DRAG:{events:23,restrict:_=>_.action!==32||_.button!==3},ANY:{events:31,restrict:_=>!0}};function x(_,k){let j=(_.ctrl?16:0)|(_.shift?4:0)|(_.alt?8:0);return _.button===4?(j|=64,j|=_.action):(j|=3&_.button,4&_.button&&(j|=64),8&_.button&&(j|=128),_.action===32?j|=32:_.action!==0||k||(j|=3)),j}const m=String.fromCharCode,y={DEFAULT:_=>{const k=[x(_,!1)+32,_.col+32,_.row+32];return k[0]>255||k[1]>255||k[2]>255?"":`\x1B[M${m(k[0])}${m(k[1])}${m(k[2])}`},SGR:_=>{const k=_.action===0&&_.button!==4?"m":"M";return`\x1B[<${x(_,!0)};${_.col};${_.row}${k}`},SGR_PIXELS:_=>{const k=_.action===0&&_.button!==4?"m":"M";return`\x1B[<${x(_,!0)};${_.x};${_.y}${k}`}};let b=l.CoreMouseService=class extends w.Disposable{constructor(_,k){super(),this._bufferService=_,this._coreService=k,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new S.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const j of Object.keys(E))this.addProtocol(j,E[j]);for(const j of Object.keys(y))this.addEncoding(j,y[j]);this.reset()}addProtocol(_,k){this._protocols[_]=k}addEncoding(_,k){this._encodings[_]=k}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(_){if(!this._protocols[_])throw new Error(`unknown protocol "${_}"`);this._activeProtocol=_,this._onProtocolChange.fire(this._protocols[_].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(_){if(!this._encodings[_])throw new Error(`unknown encoding "${_}"`);this._activeEncoding=_}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(_){if(_.col<0||_.col>=this._bufferService.cols||_.row<0||_.row>=this._bufferService.rows||_.button===4&&_.action===32||_.button===3&&_.action!==32||_.button!==4&&(_.action===2||_.action===3)||(_.col++,_.row++,_.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,_,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(_))return!1;const k=this._encodings[this._activeEncoding](_);return k&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(k):this._coreService.triggerDataEvent(k,!0)),this._lastEvent=_,!0}explainEvents(_){return{down:!!(1&_),up:!!(2&_),drag:!!(4&_),move:!!(8&_),wheel:!!(16&_)}}_equalEvents(_,k,j){if(j){if(_.x!==k.x||_.y!==k.y)return!1}else if(_.col!==k.col||_.row!==k.row)return!1;return _.button===k.button&&_.action===k.action&&_.ctrl===k.ctrl&&_.alt===k.alt&&_.shift===k.shift}};l.CoreMouseService=b=f([v(0,g.IBufferService),v(1,g.ICoreService)],b)},6975:function(h,l,u){var f=this&&this.__decorate||function(b,_,k,j){var T,D=arguments.length,I=D<3?_:j===null?j=Object.getOwnPropertyDescriptor(_,k):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(b,_,k,j);else for(var L=b.length-1;L>=0;L--)(T=b[L])&&(I=(D<3?T(I):D>3?T(_,k,I):T(_,k))||I);return D>3&&I&&Object.defineProperty(_,k,I),I},v=this&&this.__param||function(b,_){return function(k,j){_(k,j,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CoreService=void 0;const g=u(1439),S=u(8460),w=u(844),E=u(2585),x=Object.freeze({insertMode:!1}),m=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let y=l.CoreService=class extends w.Disposable{constructor(b,_,k){super(),this._bufferService=b,this._logService=_,this._optionsService=k,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new S.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new S.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new S.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new S.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,g.clone)(x),this.decPrivateModes=(0,g.clone)(m)}reset(){this.modes=(0,g.clone)(x),this.decPrivateModes=(0,g.clone)(m)}triggerDataEvent(b,_=!1){if(this._optionsService.rawOptions.disableStdin)return;const k=this._bufferService.buffer;_&&this._optionsService.rawOptions.scrollOnUserInput&&k.ybase!==k.ydisp&&this._onRequestScrollToBottom.fire(),_&&this._onUserInput.fire(),this._logService.debug(`sending data "${b}"`,(()=>b.split("").map((j=>j.charCodeAt(0))))),this._onData.fire(b)}triggerBinaryEvent(b){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${b}"`,(()=>b.split("").map((_=>_.charCodeAt(0))))),this._onBinary.fire(b))}};l.CoreService=y=f([v(0,E.IBufferService),v(1,E.ILogService),v(2,E.IOptionsService)],y)},9074:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DecorationService=void 0;const f=u(8055),v=u(8460),g=u(844),S=u(6106);let w=0,E=0;class x extends g.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new S.SortedList((b=>b?.marker.line)),this._onDecorationRegistered=this.register(new v.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new v.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,g.toDisposable)((()=>this.reset())))}registerDecoration(b){if(b.marker.isDisposed)return;const _=new m(b);if(_){const k=_.marker.onDispose((()=>_.dispose()));_.onDispose((()=>{_&&(this._decorations.delete(_)&&this._onDecorationRemoved.fire(_),k.dispose())})),this._decorations.insert(_),this._onDecorationRegistered.fire(_)}return _}reset(){for(const b of this._decorations.values())b.dispose();this._decorations.clear()}*getDecorationsAtCell(b,_,k){let j=0,T=0;for(const D of this._decorations.getKeyIterator(_))j=D.options.x??0,T=j+(D.options.width??1),b>=j&&b<T&&(!k||(D.options.layer??"bottom")===k)&&(yield D)}forEachDecorationAtCell(b,_,k,j){this._decorations.forEachByKey(_,(T=>{w=T.options.x??0,E=w+(T.options.width??1),b>=w&&b<E&&(!k||(T.options.layer??"bottom")===k)&&j(T)}))}}l.DecorationService=x;class m extends g.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=f.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=f.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(b){super(),this.options=b,this.onRenderEmitter=this.register(new v.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new v.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=b.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.InstantiationService=l.ServiceCollection=void 0;const f=u(2585),v=u(8343);class g{constructor(...w){this._entries=new Map;for(const[E,x]of w)this.set(E,x)}set(w,E){const x=this._entries.get(w);return this._entries.set(w,E),x}forEach(w){for(const[E,x]of this._entries.entries())w(E,x)}has(w){return this._entries.has(w)}get(w){return this._entries.get(w)}}l.ServiceCollection=g,l.InstantiationService=class{constructor(){this._services=new g,this._services.set(f.IInstantiationService,this)}setService(S,w){this._services.set(S,w)}getService(S){return this._services.get(S)}createInstance(S,...w){const E=(0,v.getServiceDependencies)(S).sort(((y,b)=>y.index-b.index)),x=[];for(const y of E){const b=this._services.get(y.id);if(!b)throw new Error(`[createInstance] ${S.name} depends on UNKNOWN service ${y.id}.`);x.push(b)}const m=E.length>0?E[0].index:w.length;if(w.length!==m)throw new Error(`[createInstance] First service dependency of ${S.name} at position ${m+1} conflicts with ${w.length} static arguments`);return new S(...w,...x)}}},7866:function(h,l,u){var f=this&&this.__decorate||function(m,y,b,_){var k,j=arguments.length,T=j<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,b,_);else for(var D=m.length-1;D>=0;D--)(k=m[D])&&(T=(j<3?k(T):j>3?k(y,b,T):k(y,b))||T);return j>3&&T&&Object.defineProperty(y,b,T),T},v=this&&this.__param||function(m,y){return function(b,_){y(b,_,m)}};Object.defineProperty(l,"__esModule",{value:!0}),l.traceCall=l.setTraceLogger=l.LogService=void 0;const g=u(844),S=u(2585),w={trace:S.LogLevelEnum.TRACE,debug:S.LogLevelEnum.DEBUG,info:S.LogLevelEnum.INFO,warn:S.LogLevelEnum.WARN,error:S.LogLevelEnum.ERROR,off:S.LogLevelEnum.OFF};let E,x=l.LogService=class extends g.Disposable{get logLevel(){return this._logLevel}constructor(m){super(),this._optionsService=m,this._logLevel=S.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),E=this}_updateLogLevel(){this._logLevel=w[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(m){for(let y=0;y<m.length;y++)typeof m[y]=="function"&&(m[y]=m[y]())}_log(m,y,b){this._evalLazyOptionalParams(b),m.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+y,...b)}trace(m,...y){this._logLevel<=S.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,m,y)}debug(m,...y){this._logLevel<=S.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,m,y)}info(m,...y){this._logLevel<=S.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,m,y)}warn(m,...y){this._logLevel<=S.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,m,y)}error(m,...y){this._logLevel<=S.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,m,y)}};l.LogService=x=f([v(0,S.IOptionsService)],x),l.setTraceLogger=function(m){E=m},l.traceCall=function(m,y,b){if(typeof b.value!="function")throw new Error("not supported");const _=b.value;b.value=function(...k){if(E.logLevel!==S.LogLevelEnum.TRACE)return _.apply(this,k);E.trace(`GlyphRenderer#${_.name}(${k.map((T=>JSON.stringify(T))).join(", ")})`);const j=_.apply(this,k);return E.trace(`GlyphRenderer#${_.name} return`,j),j}}},7302:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.OptionsService=l.DEFAULT_OPTIONS=void 0;const f=u(8460),v=u(844),g=u(6114);l.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:g.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const S=["normal","bold","100","200","300","400","500","600","700","800","900"];class w extends v.Disposable{constructor(x){super(),this._onOptionChange=this.register(new f.EventEmitter),this.onOptionChange=this._onOptionChange.event;const m={...l.DEFAULT_OPTIONS};for(const y in x)if(y in m)try{const b=x[y];m[y]=this._sanitizeAndValidateOption(y,b)}catch(b){console.error(b)}this.rawOptions=m,this.options={...m},this._setupOptions(),this.register((0,v.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(x,m){return this.onOptionChange((y=>{y===x&&m(this.rawOptions[x])}))}onMultipleOptionChange(x,m){return this.onOptionChange((y=>{x.indexOf(y)!==-1&&m()}))}_setupOptions(){const x=y=>{if(!(y in l.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);return this.rawOptions[y]},m=(y,b)=>{if(!(y in l.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);b=this._sanitizeAndValidateOption(y,b),this.rawOptions[y]!==b&&(this.rawOptions[y]=b,this._onOptionChange.fire(y))};for(const y in this.rawOptions){const b={get:x.bind(this,y),set:m.bind(this,y)};Object.defineProperty(this.options,y,b)}}_sanitizeAndValidateOption(x,m){switch(x){case"cursorStyle":if(m||(m=l.DEFAULT_OPTIONS[x]),!(function(y){return y==="block"||y==="underline"||y==="bar"})(m))throw new Error(`"${m}" is not a valid value for ${x}`);break;case"wordSeparator":m||(m=l.DEFAULT_OPTIONS[x]);break;case"fontWeight":case"fontWeightBold":if(typeof m=="number"&&1<=m&&m<=1e3)break;m=S.includes(m)?m:l.DEFAULT_OPTIONS[x];break;case"cursorWidth":m=Math.floor(m);case"lineHeight":case"tabStopWidth":if(m<1)throw new Error(`${x} cannot be less than 1, value: ${m}`);break;case"minimumContrastRatio":m=Math.max(1,Math.min(21,Math.round(10*m)/10));break;case"scrollback":if((m=Math.min(m,4294967295))<0)throw new Error(`${x} cannot be less than 0, value: ${m}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(m<=0)throw new Error(`${x} cannot be less than or equal to 0, value: ${m}`);break;case"rows":case"cols":if(!m&&m!==0)throw new Error(`${x} must be numeric, value: ${m}`);break;case"windowsPty":m=m??{}}return m}}l.OptionsService=w},2660:function(h,l,u){var f=this&&this.__decorate||function(w,E,x,m){var y,b=arguments.length,_=b<3?E:m===null?m=Object.getOwnPropertyDescriptor(E,x):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(w,E,x,m);else for(var k=w.length-1;k>=0;k--)(y=w[k])&&(_=(b<3?y(_):b>3?y(E,x,_):y(E,x))||_);return b>3&&_&&Object.defineProperty(E,x,_),_},v=this&&this.__param||function(w,E){return function(x,m){E(x,m,w)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkService=void 0;const g=u(2585);let S=l.OscLinkService=class{constructor(w){this._bufferService=w,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(w){const E=this._bufferService.buffer;if(w.id===void 0){const k=E.addMarker(E.ybase+E.y),j={data:w,id:this._nextId++,lines:[k]};return k.onDispose((()=>this._removeMarkerFromLink(j,k))),this._dataByLinkId.set(j.id,j),j.id}const x=w,m=this._getEntryIdKey(x),y=this._entriesWithId.get(m);if(y)return this.addLineToLink(y.id,E.ybase+E.y),y.id;const b=E.addMarker(E.ybase+E.y),_={id:this._nextId++,key:this._getEntryIdKey(x),data:x,lines:[b]};return b.onDispose((()=>this._removeMarkerFromLink(_,b))),this._entriesWithId.set(_.key,_),this._dataByLinkId.set(_.id,_),_.id}addLineToLink(w,E){const x=this._dataByLinkId.get(w);if(x&&x.lines.every((m=>m.line!==E))){const m=this._bufferService.buffer.addMarker(E);x.lines.push(m),m.onDispose((()=>this._removeMarkerFromLink(x,m)))}}getLinkData(w){return this._dataByLinkId.get(w)?.data}_getEntryIdKey(w){return`${w.id};;${w.uri}`}_removeMarkerFromLink(w,E){const x=w.lines.indexOf(E);x!==-1&&(w.lines.splice(x,1),w.lines.length===0&&(w.data.id!==void 0&&this._entriesWithId.delete(w.key),this._dataByLinkId.delete(w.id)))}};l.OscLinkService=S=f([v(0,g.IBufferService)],S)},8343:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.createDecorator=l.getServiceDependencies=l.serviceRegistry=void 0;const u="di$target",f="di$dependencies";l.serviceRegistry=new Map,l.getServiceDependencies=function(v){return v[f]||[]},l.createDecorator=function(v){if(l.serviceRegistry.has(v))return l.serviceRegistry.get(v);const g=function(S,w,E){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(x,m,y){m[u]===m?m[f].push({id:x,index:y}):(m[f]=[{id:x,index:y}],m[u]=m)})(g,S,E)};return g.toString=()=>v,l.serviceRegistry.set(v,g),g}},2585:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.IDecorationService=l.IUnicodeService=l.IOscLinkService=l.IOptionsService=l.ILogService=l.LogLevelEnum=l.IInstantiationService=l.ICharsetService=l.ICoreService=l.ICoreMouseService=l.IBufferService=void 0;const f=u(8343);var v;l.IBufferService=(0,f.createDecorator)("BufferService"),l.ICoreMouseService=(0,f.createDecorator)("CoreMouseService"),l.ICoreService=(0,f.createDecorator)("CoreService"),l.ICharsetService=(0,f.createDecorator)("CharsetService"),l.IInstantiationService=(0,f.createDecorator)("InstantiationService"),(function(g){g[g.TRACE=0]="TRACE",g[g.DEBUG=1]="DEBUG",g[g.INFO=2]="INFO",g[g.WARN=3]="WARN",g[g.ERROR=4]="ERROR",g[g.OFF=5]="OFF"})(v||(l.LogLevelEnum=v={})),l.ILogService=(0,f.createDecorator)("LogService"),l.IOptionsService=(0,f.createDecorator)("OptionsService"),l.IOscLinkService=(0,f.createDecorator)("OscLinkService"),l.IUnicodeService=(0,f.createDecorator)("UnicodeService"),l.IDecorationService=(0,f.createDecorator)("DecorationService")},1480:(h,l,u)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.UnicodeService=void 0;const f=u(8460),v=u(225);class g{static extractShouldJoin(w){return(1&w)!=0}static extractWidth(w){return w>>1&3}static extractCharKind(w){return w>>3}static createPropertyValue(w,E,x=!1){return(16777215&w)<<3|(3&E)<<1|(x?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new f.EventEmitter,this.onChange=this._onChange.event;const w=new v.UnicodeV6;this.register(w),this._active=w.version,this._activeProvider=w}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(w){if(!this._providers[w])throw new Error(`unknown Unicode version "${w}"`);this._active=w,this._activeProvider=this._providers[w],this._onChange.fire(w)}register(w){this._providers[w.version]=w}wcwidth(w){return this._activeProvider.wcwidth(w)}getStringCellWidth(w){let E=0,x=0;const m=w.length;for(let y=0;y<m;++y){let b=w.charCodeAt(y);if(55296<=b&&b<=56319){if(++y>=m)return E+this.wcwidth(b);const j=w.charCodeAt(y);56320<=j&&j<=57343?b=1024*(b-55296)+j-56320+65536:E+=this.wcwidth(j)}const _=this.charProperties(b,x);let k=g.extractWidth(_);g.extractShouldJoin(_)&&(k-=g.extractWidth(x)),E+=k,x=_}return E}charProperties(w,E){return this._activeProvider.charProperties(w,E)}}l.UnicodeService=g}},i={};function o(h){var l=i[h];if(l!==void 0)return l.exports;var u=i[h]={exports:{}};return n[h].call(u.exports,u,u.exports,o),u.exports}var d={};return(()=>{var h=d;Object.defineProperty(h,"__esModule",{value:!0}),h.Terminal=void 0;const l=o(9042),u=o(3236),f=o(844),v=o(5741),g=o(8285),S=o(7975),w=o(7090),E=["cols","rows"];class x extends f.Disposable{constructor(y){super(),this._core=this.register(new u.Terminal(y)),this._addonManager=this.register(new v.AddonManager),this._publicOptions={...this._core.options};const b=k=>this._core.options[k],_=(k,j)=>{this._checkReadonlyOptions(k),this._core.options[k]=j};for(const k in this._core.options){const j={get:b.bind(this,k),set:_.bind(this,k)};Object.defineProperty(this._publicOptions,k,j)}}_checkReadonlyOptions(y){if(E.includes(y))throw new Error(`Option "${y}" 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 S.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new w.UnicodeApi(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 g.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const y=this._core.coreService.decPrivateModes;let b="none";switch(this._core.coreMouseService.activeProtocol){case"X10":b="x10";break;case"VT200":b="vt200";break;case"DRAG":b="drag";break;case"ANY":b="any"}return{applicationCursorKeysMode:y.applicationCursorKeys,applicationKeypadMode:y.applicationKeypad,bracketedPasteMode:y.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:b,originMode:y.origin,reverseWraparoundMode:y.reverseWraparound,sendFocusMode:y.sendFocus,wraparoundMode:y.wraparound}}get options(){return this._publicOptions}set options(y){for(const b in y)this._publicOptions[b]=y[b]}blur(){this._core.blur()}focus(){this._core.focus()}input(y,b=!0){this._core.input(y,b)}resize(y,b){this._verifyIntegers(y,b),this._core.resize(y,b)}open(y){this._core.open(y)}attachCustomKeyEventHandler(y){this._core.attachCustomKeyEventHandler(y)}attachCustomWheelEventHandler(y){this._core.attachCustomWheelEventHandler(y)}registerLinkProvider(y){return this._core.registerLinkProvider(y)}registerCharacterJoiner(y){return this._checkProposedApi(),this._core.registerCharacterJoiner(y)}deregisterCharacterJoiner(y){this._checkProposedApi(),this._core.deregisterCharacterJoiner(y)}registerMarker(y=0){return this._verifyIntegers(y),this._core.registerMarker(y)}registerDecoration(y){return this._checkProposedApi(),this._verifyPositiveIntegers(y.x??0,y.width??0,y.height??0),this._core.registerDecoration(y)}hasSelection(){return this._core.hasSelection()}select(y,b,_){this._verifyIntegers(y,b,_),this._core.select(y,b,_)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(y,b){this._verifyIntegers(y,b),this._core.selectLines(y,b)}dispose(){super.dispose()}scrollLines(y){this._verifyIntegers(y),this._core.scrollLines(y)}scrollPages(y){this._verifyIntegers(y),this._core.scrollPages(y)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(y){this._verifyIntegers(y),this._core.scrollToLine(y)}clear(){this._core.clear()}write(y,b){this._core.write(y,b)}writeln(y,b){this._core.write(y),this._core.write(`\r
|
|
86
|
-
`,b)}paste(y){this._core.paste(y)}refresh(y,b){this._verifyIntegers(y,b),this._core.refresh(y,b)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(y){this._addonManager.loadAddon(this,y)}static get strings(){return l}_verifyIntegers(...y){for(const b of y)if(b===1/0||isNaN(b)||b%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...y){for(const b of y)if(b&&(b===1/0||isNaN(b)||b%1!=0||b<0))throw new Error("This API only accepts positive integers")}}h.Terminal=x})(),d})()))})(Xp)),Xp.exports}var tz=ez(),Qp={exports:{}},jS;function nz(){return jS||(jS=1,(function(e,t){(function(n,i){e.exports=i()})(self,(()=>(()=>{var n={};return(()=>{var i=n;Object.defineProperty(i,"__esModule",{value:!0}),i.FitAddon=void 0,i.FitAddon=class{activate(o){this._terminal=o}dispose(){}fit(){const o=this.proposeDimensions();if(!o||!this._terminal||isNaN(o.cols)||isNaN(o.rows))return;const d=this._terminal._core;this._terminal.rows===o.rows&&this._terminal.cols===o.cols||(d._renderService.clear(),this._terminal.resize(o.cols,o.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const o=this._terminal._core,d=o._renderService.dimensions;if(d.css.cell.width===0||d.css.cell.height===0)return;const h=this._terminal.options.scrollback===0?0:o.viewport.scrollBarWidth,l=window.getComputedStyle(this._terminal.element.parentElement),u=parseInt(l.getPropertyValue("height")),f=Math.max(0,parseInt(l.getPropertyValue("width"))),v=window.getComputedStyle(this._terminal.element),g=u-(parseInt(v.getPropertyValue("padding-top"))+parseInt(v.getPropertyValue("padding-bottom"))),S=f-(parseInt(v.getPropertyValue("padding-right"))+parseInt(v.getPropertyValue("padding-left")))-h;return{cols:Math.max(2,Math.floor(S/d.css.cell.width)),rows:Math.max(1,Math.floor(g/d.css.cell.height))}}}})(),n})()))})(Qp)),Qp.exports}var sz=nz();const iz=50,rz=150;function Jp(e){try{e.fit()}catch{}}function az({className:e,initialData:t,onReady:n,fixedSize:i,onMeasure:o,interactive:d=!1,onInput:h}){const l=N.useRef(null),u=N.useRef(null),f=N.useRef(null),v=N.useRef([]),g=N.useRef(null),S=N.useRef(!1),w=N.useRef(o);w.current=o;const E=N.useRef(h);E.current=h;const x=!!i,m=N.useCallback(()=>{if(S.current){v.current=[],g.current=null;return}if(v.current.length>0&&u.current){const k=v.current.join("");v.current=[],u.current.write(k)}g.current=null},[]),y=N.useCallback(k=>{S.current||(v.current.push(k),g.current||(g.current=setTimeout(m,iz)))},[m]),b=N.useCallback(()=>{v.current=[],g.current&&(clearTimeout(g.current),g.current=null),u.current?.clear()},[]),_=N.useCallback(()=>{f.current&&Jp(f.current)},[]);return N.useEffect(()=>{if(!l.current)return;S.current=!1;const k=new tz.Terminal({disableStdin:!0,convertEol:!i,scrollback:5e3,fontSize:13,fontFamily:"'SF Mono', 'Fira Code', 'Cascadia Code', Menlo, Monaco, Consolas, monospace",...i?{cols:i.cols,rows:i.rows}:{},theme:{background:"#000000",foreground:"#e0e0e0",cursor:"#4a9eff",selectionBackground:"#4a9eff44"}}),j=new sz.FitAddon;k.loadAddon(j),k.open(l.current),i||Jp(j),u.current=k,f.current=i?null:j,i&&k.onData(L=>E.current?.(L)),t&&k.write(t),n?.({write:y,clear:b,fit:_});let T=null,D;const I=()=>{S.current||(T&&clearTimeout(T),T=setTimeout(()=>{if(!S.current)if(x){const L=j.proposeDimensions();L&&L.cols>0&&L.rows>0&&w.current?.(L.cols,L.rows)}else Jp(j)},rz))};if(window.addEventListener("resize",I),typeof ResizeObserver<"u"&&(D=new ResizeObserver(I),D.observe(l.current)),x){const L=j.proposeDimensions();L&&L.cols>0&&L.rows>0&&w.current?.(L.cols,L.rows)}return()=>{S.current=!0,window.removeEventListener("resize",I),D?.disconnect(),T&&clearTimeout(T),g.current&&(clearTimeout(g.current),g.current=null),v.current=[],k.dispose(),u.current=null,f.current=null}},[]),N.useEffect(()=>{if(!(!i||S.current||!u.current))try{u.current.resize(i.cols,i.rows)}catch{}},[i?.cols,i?.rows]),N.useEffect(()=>{S.current||!u.current||(u.current.options.disableStdin=!(i&&d))},[i?.cols,i?.rows,d]),r.jsx("div",{ref:l,className:e,"data-testid":"terminal-container",style:i?{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"auto",background:"#000000"}:{width:"100%",height:"100%"}})}const oz=LL;function AS({sessions:e,activeSessionId:t,className:n}){const i=N.useRef(new Map),o=V(m=>m.setTerminalWriteCallback),d=V(m=>m.requestTerminalResize),h=V(m=>m.requestTerminalResync),l=V(m=>m.sendTerminalInput),u=V(m=>m.sessionStates),f=V(m=>t&&m.sessionStates[t]?.terminalRawBuffer||""),v=N.useRef(new Map),g=N.useCallback((m,y,b)=>{const _=V.getState();if(_.activeSessionId!==m)return;const k=_.sessionStates[m]?.sessionRole??"none",j=`${y}x${b}@${k}`;v.current.get(m)!==j&&(v.current.set(m,j),d(m,y,b))},[d]),S=N.useCallback((m,y)=>{V.getState().activeSessionId===m&&l(m,y)},[l]),w=N.useCallback(m=>V.getState().sessionStates[m]?.terminalRawBuffer||"",[]);N.useEffect(()=>{if(!t)return;const m=i.current.get(t);return m&&(o(m.write),m.fit()),()=>{o(null)}},[t,o]);const E=N.useCallback((m,y)=>{i.current.set(m,y);const b=V.getState().activeSessionId;m===b&&(o(y.write),y.fit())},[o]);N.useEffect(()=>{const m=new Set(e.map(y=>y.sessionId));for(const y of i.current.keys())m.has(y)||i.current.delete(y);for(const y of v.current.keys())m.has(y)||v.current.delete(y)},[e]);const x=!!t&&u[t]?.sessionRole==="observer";return r.jsxs("div",{className:n,"data-testid":"multi-terminal-container",style:{position:"relative"},children:[e.map(m=>r.jsx("div",{"data-testid":`terminal-pane-${m.sessionId}`,style:{display:m.sessionId===t?"block":"none",width:"100%",height:"100%"},children:r.jsx(az,{className:"terminal-container",initialData:w(m.sessionId),onReady:y=>E(m.sessionId,y),fixedSize:u[m.sessionId]?.terminalSize??oz,onMeasure:(y,b)=>g(m.sessionId,y,b),interactive:u[m.sessionId]?.sessionRole!=="observer",onInput:y=>S(m.sessionId,y)})},m.sessionId)),t&&f&&!x&&r.jsx("button",{type:"button",className:"terminal-resync-button","data-testid":"terminal-resync-button",title:"Refresh terminal — force a fresh repaint if the view looks out of sync","aria-label":"Refresh terminal",onClick:()=>h(t),style:{position:"absolute",top:8,right:8,zIndex:2},children:"⟳"}),x&&r.jsx("div",{className:"terminal-readonly-badge","data-testid":"terminal-readonly-badge",children:"Read-only — another device is driving this session"}),!f&&r.jsxs("div",{className:"terminal-empty-state","data-testid":"terminal-empty-state",children:[r.jsx("p",{children:"No terminal output yet."}),r.jsx("p",{className:"terminal-empty-hint",children:"Output from the active session will appear here as it runs."})]})]})}function lz(e){return e===null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function cz({files:e,filter:t,onSelect:n,onClose:i,selectedIndex:o=0}){const d=N.useRef(null);N.useEffect(()=>{const g=S=>{d.current&&!d.current.contains(S.target)&&i()};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[i]);const h=N.useRef(null);N.useEffect(()=>{h.current&&o>=0&&h.current.querySelectorAll('[role="option"]')[o]?.scrollIntoView?.({block:"nearest"})},[o]);const l=N.useMemo(()=>{if(!e)return null;if(!t)return e;const g=t.toLowerCase();return e.filter(S=>S.path.toLowerCase().includes(g))},[e,t]);if(l===null)return r.jsx("div",{ref:d,className:"file-picker","data-testid":"file-picker",children:r.jsx("div",{className:"file-picker-empty",children:"Loading files..."})});const u=200,f=l.length>u?l.length-u:0,v=f>0?l.slice(0,u):l;return l.length===0?r.jsx("div",{ref:d,className:"file-picker","data-testid":"file-picker",children:r.jsx("div",{className:"file-picker-empty",children:"No files found"})}):r.jsxs("div",{ref:d,className:"file-picker","data-testid":"file-picker",children:[r.jsx("div",{ref:h,role:"listbox","aria-label":"File picker",children:v.map((g,S)=>r.jsxs("div",{role:"option","aria-selected":S===o,className:`file-picker-item${S===o?" selected":""}`,onClick:()=>n(g.path),children:[r.jsx("span",{className:"file-picker-path",children:g.path}),g.size!==null&&r.jsx("span",{className:"file-picker-size",children:lz(g.size)})]},g.path))}),f>0&&r.jsxs("div",{className:"file-picker-overflow",children:[f," more files..."]})]})}function uz({name:e,path:t,onRemove:n}){return r.jsxs("span",{className:"attachment-chip","data-testid":"attachment-chip",title:t,children:[r.jsx("span",{className:"chip-filename","data-testid":"chip-filename",children:e}),r.jsx("button",{type:"button",className:"chip-remove",onClick:n,"aria-label":`Remove ${e}`,children:"×"})]})}const dz={builtin:"Built-in",project:"Project",user:"User"};function fz({commands:e,filter:t,onSelect:n,onClose:i,selectedIndex:o=0}){const d=N.useRef(null);N.useEffect(()=>{const l=u=>{d.current&&!d.current.contains(u.target)&&i()};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[i]);const h=N.useMemo(()=>{if(!t)return e;const l=t.toLowerCase();return e.filter(u=>u.name.toLowerCase().includes(l)||u.description.toLowerCase().includes(l))},[e,t]);return h.length===0?r.jsx("div",{className:"slash-picker","data-testid":"slash-picker",ref:d,children:r.jsx("div",{role:"listbox","aria-label":"Slash commands",children:r.jsx("div",{className:"slash-picker-empty",children:"No commands found"})})}):r.jsx("div",{className:"slash-picker","data-testid":"slash-picker",ref:d,children:r.jsx("div",{role:"listbox","aria-label":"Slash commands",children:h.map((l,u)=>{const f=u===0||h[u-1].source!==l.source;return r.jsxs(N.Fragment,{children:[f&&r.jsx("div",{className:"slash-picker-group",role:"presentation",children:dz[l.source]??"Other"}),r.jsxs("div",{role:"option","aria-selected":u===o,className:`slash-picker-item${u===o?" selected":""}`,onClick:()=>n(l.name),children:[r.jsxs("div",{className:"slash-picker-name",children:["/",l.name]}),r.jsx("div",{className:"slash-picker-desc",children:l.description}),l.source==="builtin"&&r.jsx("span",{className:"slash-picker-badge slash-picker-badge-builtin",children:"built-in"}),l.source==="user"&&r.jsx("span",{className:"slash-picker-badge",children:"user"})]})]},l.name)})})})}function hz({data:e,mediaType:t,name:n,onRemove:i}){return r.jsxs("span",{className:"image-thumbnail","data-testid":"image-thumbnail",title:n,children:[r.jsx("img",{src:`data:${t};base64,${e}`,alt:n,className:"thumbnail-img"}),r.jsx("button",{type:"button",className:"thumbnail-remove",onClick:i,"aria-label":`Remove ${n}`,children:"×"})]})}const yg=["image/jpeg","image/png","image/gif","image/webp"],v1=2*1024*1024,pz=5,mz=1*1024*1024;function gz(e){return yg.includes(e.type)?e.size>v1?`${e.name} exceeds 2MB limit (${(e.size/(1024*1024)).toFixed(1)}MB).`:null:`Unsupported image type: ${e.type||"unknown"}. Accepted: jpeg, png, gif, webp.`}function vz(e){return new Promise((t,n)=>{const i=new FileReader;i.onload=()=>{const d=i.result.split(",")[1]||"";t(d)},i.onerror=()=>n(new Error("Failed to read file")),i.readAsDataURL(e)})}async function y1(e,t){if(Math.ceil(e.length*3/4)<=mz)return{data:e,mediaType:t};if(typeof document>"u")return{data:e,mediaType:t};const i=t==="image/png"?"image/png":"image/jpeg";return new Promise(o=>{const d=new Image;d.onload=()=>{const h=document.createElement("canvas"),l=1920;let{width:u,height:f}=d;if(u>l||f>l){const w=l/Math.max(u,f);u=Math.round(u*w),f=Math.round(f*w)}h.width=u,h.height=f;const v=h.getContext("2d");if(!v){o({data:e,mediaType:t});return}v.drawImage(d,0,0,u,f);const S=(i==="image/jpeg"?h.toDataURL("image/jpeg",.8):h.toDataURL("image/png")).split(",")[1]||e;o({data:S,mediaType:i})},d.onerror=()=>o({data:e,mediaType:t}),d.src=`data:${t};base64,${e}`})}async function RS(e,t=pz){const n=[],i=[];for(const o of e){if(n.length>=t){i.push(`${o.name}: exceeds ${t}-image limit.`);continue}const d=gz(o);if(d){i.push(d);continue}try{const h=await vz(o),l=await y1(h,o.type);n.push({type:"image",mediaType:l.mediaType,data:l.data,name:o.name})}catch{i.push(`${o.name}: failed to read file.`)}}return{accepted:n,rejected:i}}function ff(e){return Array.from(e).filter(t=>yg.includes(t.type))}async function yz(e,t,n){if(!yg.includes(t))return{accepted:null,rejected:`Unsupported image type: ${t||"unknown"}. Accepted: jpeg, png, gif, webp.`};const i=Math.ceil(e.length*3/4);if(i>v1)return{accepted:null,rejected:`${n} exceeds 2MB limit (${(i/(1024*1024)).toFixed(1)}MB).`};const o=await y1(e,t);return{accepted:{type:"image",mediaType:o.mediaType,data:o.data,name:n},rejected:null}}const bz={display:"inline-flex",alignItems:"center",gap:6},_z={display:"inline-flex",alignItems:"center",gap:6,background:"transparent",border:"none",padding:0,font:"inherit",color:"inherit",cursor:"pointer"},Sz={background:"none",border:"none",padding:"0 4px",cursor:"pointer",color:"inherit",font:"inherit",lineHeight:1};function xz({id:e,lineCount:t,charCount:n,onInspect:i,onRemove:o}){const d=t>1?`Pasted text #${e} · ${t} lines`:`Pasted text #${e} · ${n} chars`;return r.jsxs("span",{className:"attachment-chip pasted-text-chip","data-testid":`pasted-text-chip-${e}`,style:bz,children:[r.jsxs("button",{type:"button",style:_z,"data-testid":`pasted-text-chip-view-${e}`,"aria-label":`View pasted text #${e}`,onClick:()=>i(e),children:[r.jsx("span",{"aria-hidden":"true",children:"📋"}),r.jsx("span",{children:d})]}),r.jsx("button",{type:"button",style:Sz,"aria-label":`Remove ${d}`,"data-testid":`pasted-text-chip-remove-${e}`,onClick:()=>o(e),children:"×"})]})}const em=/\b(?:ultrathink|megathink|think[ \t]+harder|think[ \t]+hard|think)\b/gi;function wz(e){if(typeof e!="string"||e.length===0)return[{kind:"text",text:""}];const t=[];em.lastIndex=0;let n=0,i;for(;(i=em.exec(e))!==null;)i.index>n&&t.push({kind:"text",text:e.slice(n,i.index)}),t.push({kind:"keyword",text:i[0]}),n=i.index+i[0].length,i[0].length===0&&em.lastIndex++;return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t}function kz(e){if(!e)return"";try{const t=new DOMParser().parseFromString(e,"text/html");t.querySelectorAll("br").forEach(o=>o.replaceWith(`
|
|
87
|
-
`)),t.querySelectorAll("p, div, li, tr, h1, h2, h3, h4, h5, h6, pre, blockquote").forEach(o=>o.append(`
|
|
88
|
-
`));const i=t.body.textContent??"";return i.endsWith(`
|
|
89
|
-
`)?i.slice(0,-1):i}catch{return""}}const Cz=300,Ez=250;function Nz({onSend:e,onInterrupt:t,disabled:n,isBusy:i,isStreaming:o,chatActivityState:d,placeholder:h,filePickerFiles:l,onFileTrigger:u,attachments:f,onRemoveAttachment:v,slashCommands:g,onSlashTrigger:S,onImagePaste:w,onImageDrop:E,imageAttachments:x,onRemoveImage:m,onFileAttach:y,controlledValue:b,onValueChange:_,sendOnEnter:k,voiceInput:j,onEvaluate:T,onLargePaste:D,pastedTextBlocks:I,onInspectPastedText:L,onRemovePastedText:q,userMessageHistory:H,highlightThinkingKeywords:Q}){const[F,J]=N.useState(""),ie=b!==void 0?b:F,X=_||J,de=N.useRef(0),fe=N.useRef(""),$=N.useRef("idle"),P=N.useRef(null),B=N.useRef(-1/0),[K,le]=N.useState(!1),[me,be]=N.useState(0),[Ee,se]=N.useState(!1),[Z,ge]=N.useState(0),De=N.useId(),Ge=N.useRef(null),Ve=N.useRef(null),St=N.useMemo(()=>Q?wz(ie):null,[ie,Q]),[Nt,kt]=N.useState({kind:"idle"}),[Tt,at]=N.useState(null),[en,cn]=N.useState("");N.useEffect(()=>{at(null),cn("")},[H]);const Bt=N.useCallback(async()=>{if(!T)return;const te=ie.trim();if(te){kt({kind:"pending"});try{const re=await T(te);kt({kind:"result",result:re})}catch(re){kt({kind:"error",message:re instanceof Error?re.message:String(re)})}}},[T,ie]),hn=N.useCallback(()=>{kt({kind:"idle"})},[]),sn=N.useCallback(te=>{X(te),kt({kind:"idle"}),Ge.current?.focus()},[X]),Ct=N.useMemo(()=>{for(let te=ie.length-1;te>=0;te--)if(ie[te]==="@"&&(te===0||/\s/.test(ie[te-1])))return te;return-1},[ie]),Ut=N.useMemo(()=>!K||Ct<0?"":ie.slice(Ct+1),[K,ie,Ct]),$t=N.useMemo(()=>{if(l===void 0)return[];if(l===null)return[];if(!Ut)return l;const te=Ut.toLowerCase();return l.filter(re=>re.path.toLowerCase().includes(te))},[l,Ut]),Lt=N.useCallback(te=>{if(Ct>=0){const re=ie.slice(0,Ct),ve=ie.slice(Ct+1),Me=ve.search(/\s/),Ze=Me===-1?"":ve.slice(Me);X(re+te+(Ze||" "))}y?.(te),le(!1),be(0)},[ie,Ct,y]),Ht=Ee&&ie.startsWith("/")?ie.slice(1):"",zt=N.useMemo(()=>{if(!g||g.length===0)return[];if(!Ht)return g;const te=Ht.toLowerCase();return g.filter(re=>re.name.toLowerCase().includes(te)||re.description.toLowerCase().includes(te))},[g,Ht]),rn=N.useMemo(()=>{if(!f)return;const te=new Set;return f.filter(re=>te.has(re.path)?!1:(te.add(re.path),!0))},[f]),ze=N.useMemo(()=>{if(!I||I.length===0)return!1;const te=GN(ie);if(te.size===0)return!1;for(const re of I)if(te.has(re.id))return!0;return!1},[ie,I]),Je=N.useMemo(()=>{const te=ie.trim().length>0,re=(rn?.length??0)>0,ve=(x?.length??0)>0;return te||re||ve||ze},[ie,rn,x,ze]),tt=N.useCallback(()=>{const te=ie.trim(),re=rn&&rn.length>0;Je&&(re?e(te,rn):e(te),X(""),le(!1),be(0),se(!1),ge(0),kt({kind:"idle"}),at(null),cn(""),Ge.current&&(Ge.current.style.height="auto"))},[ie,e,rn,Je]),Pt=N.useCallback(te=>{X(`/${te} `),se(!1),ge(0),Ge.current?.focus()},[]),Vt=N.useCallback(()=>{se(!1),ge(0)},[]),Wt=N.useCallback(()=>{const te=(ie??"").length>0,re=(f?.length??0)>0,ve=(x?.length??0)>0,Me=(I?.length??0)>0;if(!te&&!re&&!ve&&!Me)return!1;if(X(""),f&&v)for(const Ze of f)v(Ze.path);if(x&&m)for(let Ze=x.length-1;Ze>=0;Ze--)m(Ze);if(I&&q)for(const Ze of I)q(Ze.id);return Ge.current&&(Ge.current.style.height="auto"),Ge.current?.focus(),!0},[ie,f,x,I,v,m,q,X]),Zt=N.useCallback(te=>{const re=H;if(!re||re.length===0)return;const ve=re.length-1-te;if(ve<0||ve>=re.length)return;const Me=re[ve];Me!==void 0&&(X(Me),at(te),requestAnimationFrame(()=>{const Ze=Ge.current;if(!Ze)return;const Xe=Ze.value.length;Ze.setSelectionRange(Xe,Xe)}))},[H,X]),Dn=N.useCallback(()=>{const te=Ge.current,re=te?.value??ie,ve=te?.selectionStart??re.length,Me=te?.selectionEnd??re.length,Ze=re.slice(0,ve)+" "+re.slice(Me);X(Ze);const Xe=ve+1;requestAnimationFrame(()=>{const Dt=Ge.current;Dt&&Dt.setSelectionRange(Xe,Xe)})},[ie,X]),wn=N.useCallback(()=>{P.current!==null&&(clearTimeout(P.current),P.current=null)},[]),Kn=N.useCallback(te=>{if(te.key!==" "&&te.key!=="Spacebar"||!j?.isAvailable||n||te.metaKey||te.ctrlKey||te.altKey)return!1;if($.current!=="idle")return te.preventDefault(),!0;if(performance.now()-B.current<Ez||j.isRecording)return!1;te.preventDefault();const re=Ge.current,ve=re?.selectionStart??ie.length;return de.current=ve,fe.current=ie.slice(re?.selectionEnd??ve),$.current="arming",wn(),P.current=setTimeout(()=>{P.current=null,$.current==="arming"&&($.current="recording",j?.start())},Cz),!0},[j,n,ie,wn]),je=N.useCallback(()=>{$.current==="arming"&&(wn(),$.current="idle",Dn())},[wn,Dn]),mt=N.useCallback(te=>{te.key!==" "&&te.key!=="Spacebar"||($.current==="arming"?(wn(),$.current="idle",Dn()):$.current==="recording"&&($.current="idle",j?.stop()))},[wn,Dn,j]),xt=N.useCallback(()=>{$.current==="arming"?(wn(),$.current="idle"):$.current==="recording"&&($.current="idle",j?.stop())},[wn,j]),Mt=N.useRef(void 0);Mt.current=j?.stop,N.useEffect(()=>()=>{P.current!==null&&(clearTimeout(P.current),P.current=null),$.current==="recording"&&Mt.current?.(),$.current="idle"},[]);const un=N.useCallback(te=>{if(te.key===" "||te.key==="Spacebar"){if(Kn(te))return}else te.key.length===1&&!te.ctrlKey&&!te.metaKey&&!te.altKey&&(B.current=performance.now()),je();if(Ee){if(te.key==="Escape"){te.preventDefault(),Vt();return}if(te.key==="Enter"&&!te.metaKey&&!te.ctrlKey){if(zt.length>0){te.preventDefault();const re=Math.min(Z,zt.length-1);Pt(zt[re].name);return}Vt()}if(te.key==="ArrowDown"){te.preventDefault(),ge(re=>Math.min(re+1,zt.length-1));return}if(te.key==="ArrowUp"){te.preventDefault(),ge(re=>Math.max(0,re-1));return}}if(K){if(te.key==="ArrowDown"){te.preventDefault(),be(re=>$t.length===0?0:Math.min(re+1,$t.length-1));return}if(te.key==="ArrowUp"){te.preventDefault(),be(re=>Math.max(0,re-1));return}if(te.key==="Enter"){te.preventDefault(),$t.length>0&&Lt($t[me].path);return}if(te.key==="Escape"){te.preventDefault(),le(!1),be(0);return}}if((te.key==="ArrowUp"||te.key==="ArrowDown")&&H&&H.length>0){const re=te.currentTarget,ve=re.selectionStart,Me=re.selectionEnd,Ze=ve===Me,Xe=ve===0,Dt=ve===ie.length;if(Ze){if(te.key==="ArrowUp"&&(Xe||Dt)){if(Tt===null){te.preventDefault(),cn(ie),Zt(0);return}if(Tt<H.length-1){te.preventDefault(),Zt(Tt+1);return}te.preventDefault();return}if(te.key==="ArrowDown"&&Dt&&Tt!==null){te.preventDefault(),Tt>0?Zt(Tt-1):(X(en),at(null),requestAnimationFrame(()=>{const nt=Ge.current;if(!nt)return;const Oe=nt.value.length;nt.setSelectionRange(Oe,Oe)}));return}}}if(te.key==="Enter")(k&&!te.shiftKey||!k&&(te.metaKey||te.ctrlKey))&&(te.preventDefault(),tt());else if(te.key==="Escape"){if(Tt!==null){te.preventDefault(),X(en),at(null),requestAnimationFrame(()=>{const re=Ge.current;if(!re)return;const ve=re.value.length;re.setSelectionRange(ve,ve)});return}te.preventDefault(),t()}else(te.key==="l"||te.key==="L")&&(te.metaKey||te.ctrlKey)&&!te.altKey&&!te.shiftKey&&Wt()&&te.preventDefault()},[Ee,K,$t,me,Lt,tt,t,Vt,Pt,zt,Z,k,Wt,H,ie,Tt,en,Zt,X,Kn,je]),_n=N.useCallback(te=>{const re=te.target.value;if(X(re),Tt!==null&&H){const rt=H[H.length-1-Tt];re!==rt&&(at(null),cn(""))}if(g&&re.startsWith("/")?Ee||(se(!0),ge(0),S?.()):Ee&&Vt(),l!==void 0&&re.includes("@")){let rt=!1;for(let ct=re.length-1;ct>=0;ct--)if(re[ct]==="@"&&(ct===0||/\s/.test(re[ct-1]))){rt=!0;break}rt&&!K&&(le(!0),be(0),u?.())}K&&!re.includes("@")&&(le(!1),be(0));const ve=te.target;ve.style.height="auto";const Me=getComputedStyle(ve),Ze=parseFloat(Me.lineHeight)||20,Xe=(parseFloat(Me.paddingTop)||0)+(parseFloat(Me.paddingBottom)||0),Dt=(parseFloat(Me.borderTopWidth)||0)+(parseFloat(Me.borderBottomWidth)||0),Oe=Ze*5+Xe+Dt,ce=ve.scrollHeight+Dt,ke=Math.min(ce,Oe),Ue=Me.boxSizing==="border-box"?ke:ke-Xe-Dt;ve.style.height=Ue+"px"},[g,Ee,Vt,S,l,K,u,Tt,H,X]),tn=N.useRef("");N.useEffect(()=>{if(j?.isRecording&&j.transcript&&j.transcript!==tn.current){tn.current=j.transcript;const te=ie.slice(0,de.current),re=te.length>0&&!te.endsWith(" ")?" ":"",ve=fe.current,Me=ve.length>0&&!ve.startsWith(" ")?" ":"";X(te+re+j.transcript+Me+ve)}!j?.isRecording&&tn.current&&(tn.current="")},[j?.isRecording,j?.transcript,ie]);const zn=N.useCallback(()=>{j&&(j.isRecording?j.stop():(de.current=ie.length,fe.current="",j.start()))},[j,ie.length]),ss=rn&&rn.length>0,Ie=N.useCallback(te=>{if(n)return;const re=te.clipboardData?.files;if(w&&re&&re.length>0){const ve=ff(re);if(ve.length>0){te.preventDefault(),w(ve);return}}if(D){let ve=te.clipboardData?.getData("text/plain")??"";if(!ve.trim()){const Me=te.clipboardData?.getData("text/html")??"";Me&&(ve=kz(Me))}if(ve&&FN(ve)){te.preventDefault();const Me=D(ve),Ze=Ge.current,Xe=Ze?.selectionStart??ie.length,Dt=Ze?.selectionEnd??ie.length,nt=ie.slice(0,Xe)+Me+ie.slice(Dt);X(nt),requestAnimationFrame(()=>{const Oe=Ge.current;if(!Oe)return;const ce=Xe+Me.length;Oe.setSelectionRange(ce,ce),Oe.focus()})}}},[n,w,D,ie,X]),[ot,pt]=N.useState(!1),At=N.useCallback(te=>{te.preventDefault(),te.dataTransfer&&(te.dataTransfer.dropEffect=n||!E?"none":"copy")},[n,E]),O=N.useCallback(te=>{E&&(te.preventDefault(),pt(!0))},[E]),W=N.useCallback(te=>{E&&pt(!1)},[E]),G=N.useCallback(te=>{if(te.preventDefault(),pt(!1),n||!E)return;const re=te.dataTransfer?.files;if(!re||re.length===0)return;const ve=ff(re);ve.length>0&&E(ve)},[n,E]),M=N.useCallback(te=>{const re=Ve.current;re&&(re.scrollTop=te.currentTarget.scrollTop)},[]),ne=x&&x.length>0;return r.jsxs("div",{className:`input-bar${ot?" dragging":""}`,"data-testid":"input-bar","data-activity-state":d,onDragOver:At,onDragEnter:O,onDragLeave:W,onDrop:G,children:[K&&l!==void 0&&r.jsx(cz,{files:l,filter:Ut,onSelect:Lt,onClose:()=>{le(!1),be(0)},selectedIndex:me}),ss&&r.jsx("div",{className:"attachment-chips","data-testid":"attachment-chips",children:rn.map(te=>r.jsx(uz,{name:te.name,path:te.path,onRemove:()=>v?.(te.path)},te.path))}),ne&&r.jsxs("div",{className:"image-thumbnails","data-testid":"image-thumbnails",children:[x.map((te,re)=>r.jsx(hz,{data:te.data,mediaType:te.mediaType,name:te.name,onRemove:()=>m?.(re)},`${te.name}-${re}`)),x.length>1&&r.jsxs("span",{className:"image-count",children:[x.length," images"]})]}),I&&I.length>0&&r.jsx("div",{className:"attachment-chips pasted-text-chips","data-testid":"pasted-text-chips",children:I.map(te=>{let re=1;for(let ve=0;ve<te.content.length;ve++)te.content.charCodeAt(ve)===10&&re++;return r.jsx(xz,{id:te.id,lineCount:re,charCount:te.content.length,onInspect:L??(()=>{}),onRemove:q??(()=>{})},te.id)})}),r.jsx("span",{id:De,className:"sr-only",children:k?"Press Enter to send, Shift+Enter for newline, Escape to interrupt":"Press Cmd/Ctrl+Enter to send, Escape to interrupt"}),Ee&&g&&r.jsx(fz,{commands:g,filter:Ht,onSelect:Pt,onClose:Vt,selectedIndex:Z}),i&&!o&&r.jsxs("div",{className:"thinking-indicator","data-testid":"thinking-indicator",children:[r.jsx("span",{className:"thinking-dot"}),r.jsx("span",{className:"thinking-dot"}),r.jsx("span",{className:"thinking-dot"}),r.jsx("span",{className:"thinking-text",children:"Thinking..."})]}),Nt.kind!=="idle"&&r.jsx(Az,{state:Nt,onApplyRewrite:sn,onDismiss:hn}),j?.error&&r.jsxs("div",{className:"voice-error","data-testid":"voice-error",role:"alert",children:[r.jsx("span",{className:"voice-error-icon","aria-hidden":"true",children:"⚠"}),r.jsx("span",{className:"voice-error-text",children:j.error})]}),r.jsxs("div",{className:`input-bar-textarea-wrap${St?" has-overlay":""}`,children:[St&&r.jsxs("div",{ref:Ve,className:"input-bar-textarea-overlay","aria-hidden":"true","data-testid":"thinking-keyword-overlay",children:[St.map((te,re)=>te.kind==="keyword"?r.jsx("span",{className:"thinking-keyword","data-testid":"thinking-keyword",children:te.text},re):r.jsx("span",{children:te.text},re)),ie.endsWith(`
|
|
90
|
-
`)&&r.jsx("span",{children:""})]}),r.jsx("textarea",{ref:Ge,value:ie,onChange:_n,onKeyDown:un,onKeyUp:mt,onBlur:xt,onPaste:Ie,onScroll:St?M:void 0,disabled:n,placeholder:i?"Type to send follow-up...":h,"aria-label":"Message input","aria-describedby":De,rows:1})]}),r.jsxs("div",{className:"input-bar-actions",children:[r.jsx("span",{className:"input-bar-keyhint","aria-hidden":"true","data-testid":"input-bar-keyhint",children:k?"⏎ send · ⇧⏎ newline":"⌘⏎ send"}),j?.isAvailable&&r.jsx("button",{"data-testid":"mic-button",className:`btn-mic${j.isRecording?" recording":""}`,onClick:zn,disabled:n,type:"button","aria-label":j.isRecording?"Stop recording":"Start voice input",children:j.isRecording?r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})}):r.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),r.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),r.jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"})]})}),T&&!((o||i)&&!ie.trim())&&r.jsx("button",{"data-testid":"evaluate-button",className:"btn-evaluate",onClick:Bt,disabled:n||!ie.trim()||Nt.kind==="pending",type:"button","aria-label":"Evaluate this draft before sending",title:"Evaluate this draft message — Claude opus will check it for clarity before you send.",children:Nt.kind==="pending"?"Evaluating…":"Evaluate"}),o||i?r.jsxs(r.Fragment,{children:[Je&&r.jsx("button",{"data-testid":"send-button",className:"btn-send",onClick:tt,disabled:n,type:"button","aria-label":"Send follow-up",children:"Send"}),r.jsx("button",{"data-testid":"interrupt-button",className:"btn-interrupt",onClick:t,type:"button","aria-label":"Stop generation",children:"Stop"})]}):r.jsx("button",{"data-testid":"send-button",className:"btn-send",onClick:tt,disabled:n,type:"button","aria-label":"Send message",children:"Send"})]})]})}function jz(e){return e===401||e===403?"Check your ANTHROPIC_API_KEY.":e===429?"Try again in a moment.":typeof e=="number"&&e>=500&&e<600?"Anthropic upstream is unavailable — try again shortly.":null}function Az({state:e,onApplyRewrite:t,onDismiss:n}){if(e.kind==="pending")return r.jsxs("div",{className:"evaluator-panel evaluator-panel--pending","data-testid":"evaluator-panel",role:"status","aria-live":"polite","aria-busy":"true",children:[r.jsx("span",{className:"evaluator-spinner","aria-hidden":"true"}),r.jsx("span",{className:"evaluator-text",children:"Evaluating draft…"})]});if(e.kind==="error")return r.jsxs("div",{className:"evaluator-panel evaluator-panel--error","data-testid":"evaluator-panel",role:"alert",children:[r.jsx("span",{className:"evaluator-label",children:"Evaluator error:"}),r.jsx("span",{className:"evaluator-text",children:e.message}),r.jsx("button",{type:"button",className:"evaluator-dismiss",onClick:n,"aria-label":"Dismiss",children:"×"})]});const{result:i}=e;if(i.error)return r.jsxs("div",{className:"evaluator-panel evaluator-panel--error","data-testid":"evaluator-panel",role:"alert",children:[r.jsxs("span",{className:"evaluator-label",children:["Evaluator error (",i.error.code,"):"]}),r.jsx("span",{className:"evaluator-text",children:i.error.message}),(()=>{const h=jz(i.error.status);return h?r.jsx("span",{className:"evaluator-hint","data-testid":"evaluator-hint",children:h}):null})(),r.jsx("button",{type:"button",className:"evaluator-dismiss",onClick:n,"aria-label":"Dismiss",children:"×"})]});const o=i.verdict,d=i.reasoning||"";return o==="forward"?r.jsxs("div",{className:"evaluator-panel evaluator-panel--forward","data-testid":"evaluator-panel","data-verdict":"forward",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"evaluator-label",children:"Looks clear."}),d&&r.jsx("span",{className:"evaluator-text",children:d}),r.jsx("button",{type:"button",className:"evaluator-dismiss",onClick:n,"aria-label":"Dismiss",children:"×"})]}):o==="rewrite"&&i.rewritten?r.jsxs("div",{className:"evaluator-panel evaluator-panel--rewrite","data-testid":"evaluator-panel","data-verdict":"rewrite",role:"status","aria-live":"polite",children:[r.jsxs("div",{className:"evaluator-row",children:[r.jsx("span",{className:"evaluator-label",children:"Suggested rewrite"}),d&&r.jsxs("span",{className:"evaluator-text",children:["— ",d]})]}),r.jsx("pre",{className:"evaluator-rewrite-text",children:i.rewritten}),r.jsxs("div",{className:"evaluator-actions",children:[r.jsx("button",{type:"button",className:"btn-evaluator-apply","data-testid":"evaluator-apply",onClick:()=>t(i.rewritten),children:"Apply rewrite"}),r.jsx("button",{type:"button",className:"btn-evaluator-dismiss",onClick:n,children:"Keep original"})]})]}):o==="clarify"&&i.clarification?r.jsxs("div",{className:"evaluator-panel evaluator-panel--clarify","data-testid":"evaluator-panel","data-verdict":"clarify",role:"status","aria-live":"polite",children:[r.jsxs("div",{className:"evaluator-row",children:[r.jsx("span",{className:"evaluator-label",children:"Clarification needed"}),d&&r.jsxs("span",{className:"evaluator-text",children:["— ",d]})]}),r.jsx("p",{className:"evaluator-clarification",children:i.clarification}),r.jsx("div",{className:"evaluator-actions",children:r.jsx("button",{type:"button",className:"btn-evaluator-dismiss",onClick:n,children:"Got it"})})]}):r.jsxs("div",{className:"evaluator-panel evaluator-panel--forward","data-testid":"evaluator-panel",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"evaluator-text",children:d||"Evaluator returned an unexpected response."}),r.jsx("button",{type:"button",className:"evaluator-dismiss",onClick:n,"aria-label":"Dismiss",children:"×"})]})}function TS(){if(typeof window>"u")return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function Rz(){return typeof navigator<"u"&&typeof navigator.language=="string"&&navigator.language?navigator.language:"en-US"}function IS(e){return e==="not-allowed"||e==="service-not-allowed"?"Microphone permission denied. Please allow microphone access in your browser settings.":e==="no-speech"?"No speech detected.":e==="audio-capture"?"No microphone available.":e==="network"?"Network error during speech recognition.":`Speech recognition error: ${e}`}const Tz=new Set(["not-allowed","service-not-allowed","audio-capture","aborted"]),Iz=5;function Mz(e={}){const t=e.mode??"continuous",[n,i]=N.useState(!1),[o,d]=N.useState(""),[h,l]=N.useState(null),[u,f]=N.useState(!1),[v,g]=N.useState("none"),S=N.useRef(null),w=N.useRef(""),E=N.useRef([]),x=N.useRef(!1),m=N.useRef(0),y=N.useRef(t);y.current=t,N.useEffect(()=>{let k=!1;async function j(){const T=_s();if(T)try{const D=await T("voice_available");if(k)return;if(D){g("native"),f(!0);return}}catch{}if(TS()){if(k)return;g("web"),f(!0);return}k||(g("none"),f(!1))}return j(),()=>{k=!0}},[]),N.useEffect(()=>{if(v!=="native")return;const k=pg();return k?((async()=>{const T=await k("voice_transcription",L=>{d(L.payload.text),L.payload.is_final&&i(!1)}),D=await k("voice_error",L=>{l(L.payload.message),i(!1)}),I=await k("voice_stopped",()=>{i(!1)});E.current=[T,D,I]})(),()=>{for(const T of E.current)T();E.current=[]}):void 0},[v]),N.useEffect(()=>()=>{const k=S.current;if(k){x.current=!0,k.onresult=null,k.onerror=null,k.onend=null,k.onstart=null;try{k.abort()}catch{}S.current=null}},[]);const b=N.useCallback(()=>{if(l(null),x.current=!1,m.current=0,v==="native"){const k=_s();if(!k)return;d(""),i(!0),k("start_voice_input").catch(j=>{l(String(j)),i(!1)});return}if(v==="web"){const k=TS();if(!k)return;if(S.current){const T=S.current;T.onresult=null,T.onerror=null,T.onend=null,T.onstart=null;try{T.abort()}catch{}}w.current="",d("");const j=new k;j.continuous=!0,j.interimResults=!0,j.lang=Rz(),j.onresult=T=>{let D="",I="";for(let L=T.resultIndex;L<T.results.length;L++){const q=T.results[L];if(!q)continue;const H=q[0]?.transcript??"";if(q.isFinal){const F=(w.current.length>0&&!w.current.endsWith(" ")&&H.length>0&&!H.startsWith(" ")?" ":"")+H;w.current+=F,I+=F}else D+=H}d(w.current+D),(I+D).trim().length>0&&(m.current=0)},j.onerror=T=>{if(Tz.has(T.error)){l(IS(T.error)),x.current=!0,i(!1);return}y.current==="auto-pause"&&(l(IS(T.error)),i(!1))},j.onend=()=>{if(y.current==="continuous"&&!x.current&&m.current<Iz){m.current+=1;try{j.start();return}catch{}}y.current==="continuous"&&!x.current&&l("Voice recognition stopped unexpectedly — tap the mic to retry."),i(!1)},S.current=j;try{j.start(),i(!0)}catch(T){l(String(T)),i(!1),S.current=null}return}},[v]),_=N.useCallback(()=>{if(x.current=!0,v==="native"){const k=_s();if(!k)return;k("stop_voice_input").catch(()=>{});return}if(v==="web"){const k=S.current;if(k)try{k.stop()}catch{}return}},[v]);return{isRecording:n,transcript:o,error:h,isAvailable:u,engine:v,start:b,stop:_}}function Dz(e,t){const n=[];if(e)for(const i of e)n.push({type:"file_ref",path:i.path,name:i.name});if(t)for(const i of t)n.push({type:"image",mediaType:i.mediaType,data:i.data,name:i.name});return n}const MS={idle:"Session idle — ready for input",working:"Session working — response, tool, or agent active",stale:"Session stale — idle for 1 hour or more"};function Lz(e){return e.replace(/^claude-/,"").replace(/-\d.*$/,"")}function Oz(e){const t=e.split("/");return t[t.length-1]||e}function Pz(e){return Vi(e).short}const DS={position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0};function LS(e,t,n){if(t===n||t<0||t>=e.length||n<0||n>e.length)return e;const i=e.slice(),[o]=i.splice(t,1);if(o===void 0)return e;const d=n>t?n-1:n;return i.splice(d,0,o),i}function Bz({sessions:e,onSwitch:t,onClose:n,onRename:i,onNewSession:o,onReorder:d,controlRoom:h,pendingPermissionTotal:l=0,onJumpToPending:u}){const[f,v]=N.useState(null),[g,S]=N.useState(""),w=N.useRef(null),E=N.useRef(!1),x=e.length>1,[m,y]=N.useState(null),[b,_]=N.useState(null),[k,j]=N.useState(null),[T,D]=N.useState(""),I=N.useId();N.useEffect(()=>{f&&w.current&&(w.current.focus(),w.current.select())},[f]);const L=N.useCallback(J=>{E.current=!1,v(J.sessionId),S(J.name)},[]),q=N.useCallback(J=>{if(E.current)return;const ie=g.trim(),X=e.find(de=>de.sessionId===J);ie&&X&&ie!==X.name.trim()&&i(J,ie),v(null)},[g,i,e]),H=N.useCallback(()=>{E.current=!0,v(null)},[]),Q=N.useCallback((J,ie)=>{if(!d||J===ie)return;const X=e.map(B=>B.sessionId),de=X.indexOf(J),fe=X.indexOf(ie);if(de===-1||fe===-1)return;const $=LS(X,de,fe);d($);const P=e.find(B=>B.sessionId===J);if(P){const B=$.indexOf(J)+1;D(`Dropped ${P.name} at position ${B} of ${$.length}.`)}},[e,d]),F=N.useCallback((J,ie)=>{if(!d)return;const X=e.map(K=>K.sessionId),de=X.indexOf(J);if(de===-1)return;const fe=de+ie;if(fe<0||fe>=X.length)return;const $=ie>0?de+2:de-1,P=LS(X,de,$);d(P);const B=e.find(K=>K.sessionId===J);if(B){const K=P.indexOf(J)+1;D(`Dropped ${B.name} at position ${K} of ${P.length}.`)}},[e,d]);return r.jsxs("div",{className:"session-bar","data-testid":"session-bar",children:[r.jsxs("div",{className:"session-tabs",role:"tablist",children:[h?.open&&r.jsxs("div",{className:`session-tab control-room-tab${h.active?" active":""}`,"data-testid":"control-room-tab",role:"tab","aria-selected":h.active,tabIndex:0,onClick:()=>{h.active||h.onActivate()},onKeyDown:J=>{if(J.target===J.currentTarget){if(J.key==="Enter"||J.key===" ")J.preventDefault(),h.active||h.onActivate();else if(J.key==="ArrowRight"||J.key==="ArrowLeft"){J.preventDefault();const ie=J.currentTarget.parentElement?.querySelectorAll('[role="tab"]');if(!ie)return;const X=Array.from(ie).indexOf(J.currentTarget),de=J.key==="ArrowRight"?(X+1)%ie.length:(X-1+ie.length)%ie.length;ie[de]?.focus()}}},children:[r.jsx("span",{className:"control-room-tab-icon","aria-hidden":"true",children:"⌘"}),r.jsx("span",{className:"tab-name",children:"Control Room"}),r.jsx("button",{className:"tab-close","data-testid":"control-room-tab-close","aria-label":"Close Control Room",onClick:J=>{J.stopPropagation(),h.onClose()},type:"button",children:"×"})]}),e.map(J=>{const ie=m===J.sessionId,X=b===J.sessionId&&m!==null&&m!==J.sessionId,de=k===J.sessionId,fe=!d,$=J.isActive&&!h?.active;return r.jsxs("div",{className:`session-tab${$?" active":""}${ie?" dragging":""}${X?" drag-over":""}${de?" lifted":""}`,"data-testid":`session-tab-${J.sessionId}`,role:"tab","aria-selected":$,"aria-describedby":fe?void 0:I,tabIndex:0,title:fe?void 0:"Space (or Shift+Space) to reorder (Arrow Left/Right to move, Enter/Escape to commit/cancel)","aria-keyshortcuts":fe?void 0:"Space Shift+Space ArrowLeft ArrowRight Enter Escape",draggable:!fe&&f!==J.sessionId,onDragStart:P=>{if(!fe){y(J.sessionId);try{P.dataTransfer.setData("text/plain",J.sessionId)}catch{}P.dataTransfer&&(P.dataTransfer.effectAllowed="move"),D(`Picked up ${J.name}. Use Arrow Left or Arrow Right to move, Space or Enter to drop, Escape to cancel.`)}},onDragEnd:()=>{y(null),_(null)},onDragOver:P=>{fe||!m||m===J.sessionId||(P.preventDefault(),P.dataTransfer&&(P.dataTransfer.dropEffect="move"),b!==J.sessionId&&(_(J.sessionId),D(`Over ${J.name}.`)))},onDragLeave:P=>{const B=P.relatedTarget;B&&P.currentTarget.contains(B)||b===J.sessionId&&_(null)},onDrop:P=>{fe||!m||(P.preventDefault(),Q(m,J.sessionId),y(null),_(null))},onClick:()=>{$||t(J.sessionId)},onKeyDown:P=>{if(f!==J.sessionId){if(P.key===" "&&!fe){P.preventDefault(),j(B=>B===J.sessionId?null:(D(`Picked up ${J.name}. Use Arrow Left or Arrow Right to move, Space or Enter to drop, Escape to cancel.`),J.sessionId));return}if(k===J.sessionId){if(P.key==="Escape"){P.preventDefault(),j(null),D(`Cancelled reorder of ${J.name}.`);return}if(P.key==="Enter"){P.preventDefault(),j(null);return}if(P.key==="ArrowRight"){P.preventDefault(),F(J.sessionId,1);return}if(P.key==="ArrowLeft"){P.preventDefault(),F(J.sessionId,-1);return}}if(P.key==="Enter"||P.key===" ")P.preventDefault(),$||t(J.sessionId);else if(P.key==="ArrowRight"||P.key==="ArrowLeft"){P.preventDefault();const B=P.currentTarget.parentElement?.querySelectorAll('[role="tab"]');if(!B)return;const K=Array.from(B).indexOf(P.currentTarget),le=P.key==="ArrowRight"?(K+1)%B.length:(K-1+B.length)%B.length;B[le]?.focus()}}},children:[(()=>{const P=J.status??(J.isBusy?"working":"idle");return r.jsx("span",{className:`tab-status-dot status-${P}`,"data-testid":"status-dot",title:MS[P],"aria-label":MS[P]})})(),J.pendingPermission&&(()=>{const P=J.pendingPermissionCount??1;return r.jsx("span",{className:"tab-pending-permission","data-testid":"tab-pending-permission",title:`${P} permission request${P===1?"":"s"} — waiting for your approval`,"aria-label":`${P} permission request${P===1?"":"s"} waiting for your approval`,children:P>1?`!${P}`:"!"})})(),f===J.sessionId?r.jsx("input",{ref:w,className:"tab-rename-input",value:g,onChange:P=>S(P.target.value),onKeyDown:P=>{P.key==="Enter"?(P.preventDefault(),q(J.sessionId)):P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),H())},onBlur:()=>q(J.sessionId),onClick:P=>P.stopPropagation()}):r.jsx("span",{className:"tab-name",onDoubleClick:P=>{P.preventDefault(),P.stopPropagation(),L(J)},children:J.name}),J.cwd&&r.jsx("span",{className:"tab-cwd",title:J.cwd,"aria-label":`Working directory: ${J.cwd}`,children:Oz(J.cwd)}),J.model&&r.jsx("span",{className:"tab-model",title:`Model: ${J.model}`,"aria-label":`Model: ${J.model}`,children:Lz(J.model)}),J.provider&&r.jsx("span",{className:"tab-provider","data-provider":Vi(J.provider).type,title:Vi(J.provider).tooltip,"aria-label":Vi(J.provider).tooltip,children:Pz(J.provider)}),J.stdinForwardingDisabled&&r.jsx("span",{className:"tab-stdin-disabled-badge","data-testid":"tab-stdin-disabled-badge",title:"Stdin forwarding lost — restart this session","aria-label":"Stdin forwarding disabled",children:"stdin lost"}),x&&r.jsx("button",{className:"tab-close","data-testid":"tab-close","aria-label":`Close session ${J.name}`,onClick:P=>{P.stopPropagation(),n(J.sessionId)},type:"button",children:"×"})]},J.sessionId)})]}),r.jsx("button",{className:"btn-new-session","data-testid":"new-session-btn",onClick:o,"aria-label":"Create new session",title:"New session (Ctrl+N)",type:"button",children:"+"}),l>0&&r.jsx("button",{className:"session-bar-pending-total","data-testid":"pending-permission-total",onClick:u,"aria-label":`${l} permission request${l===1?"":"s"} waiting — go to the next`,title:`${l} permission request${l===1?"":"s"} waiting — click to go to the next`,type:"button",children:r.jsxs("span",{"aria-hidden":"true",children:["⚠ ",l," pending"]})}),r.jsx("span",{id:I,style:DS,children:"Press Space to pick up this tab for reorder, then use Arrow Left or Arrow Right to move it. Press Space or Enter to drop, Escape to cancel."}),r.jsx("div",{"data-testid":"session-bar-reorder-announcer",role:"status","aria-live":"polite","aria-atomic":"true",style:DS,children:T})]})}const $z=200;function zz(e,t){if(e.toolInput&&typeof e.toolInput=="object"){const n=JSON.stringify(e.toolInput);return t?"\n```json\n"+n+"\n```":` ${n}`}return e.content?t?"\n```\n"+e.content+"\n```":` ${e.content}`:""}function Uz(e,t){return e.length<=t?{text:e,truncated:!1}:{text:e.slice(0,t).trimEnd()+"…",truncated:!0}}function OS(e,t={}){const n=t.toolResultPreviewChars??$z,i=!!t.markdown,o=[];for(const d of e)if(!(d.type==="system"||d.type==="thinking"))switch(d.type){case"user_input":o.push(`[You] ${d.content}`.trimEnd());break;case"response":d.content&&d.content.trim().length>0&&o.push(`[Claude] ${d.content}`.trimEnd());break;case"tool_use":{const h=d.tool??"tool";if(o.push(`[Tool: ${h}]${zz(d,i)}`.trimEnd()),d.toolResult&&d.toolResult.length>0){const{text:l,truncated:u}=Uz(d.toolResult,n),f=u||d.toolResultTruncated?" (truncated)":"";i?o.push(`[Tool result]${f}
|
|
91
|
-
\`\`\`
|
|
92
|
-
${l}
|
|
93
|
-
\`\`\``):o.push(`[Tool result]${f} ${l}`.trimEnd())}break}case"prompt":{const h=d.tool??"tool",l=d.answered?` → ${d.answered}`:" (no response)";o.push(`[Permission: ${h}]${l}`);break}case"error":o.push(`[Error] ${d.content}`.trimEnd());break}return o.join(`
|
|
94
|
-
|
|
95
|
-
`)}const PS=40;function tm(e){return e.length<=PS?e:e.slice(0,PS-1)+"…"}function Tm(e){if(!e)return null;for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type!=="tool_use")continue;if(!(n.toolResult!==void 0||(n.toolResultImages?.length??0)>0))return{tool:n.tool??"tool",serverName:n.serverName,startedAt:n.timestamp}}return null}const qz=1800*1e3;function Hz(e,t){return e>=t-6e4?"activity-indicator--red":e>=6e4?"activity-indicator--orange":e>=3e4?"activity-indicator--yellow":"activity-indicator--green"}function Fz(){const e=V(L=>{const q=L.activeSessionId;return q?L.sessionStates[q]?.isIdle??!0:!0}),t=V(L=>{const q=L.activeSessionId;return q?L.sessionStates[q]?.lastClientActivityAt??null:null}),{tool:n,startedAt:i,serverName:o,agentDescription:d,agentStartedAt:h,pendingShells:l,transcriptTasks:u,scheduledWakeup:f}=V(Mc(L=>{const q=L.activeSessionId,H=q?L.sessionStates[q]:null,Q=H?.activeTools,F=Q&&Q.length>0?Q[Q.length-1]:null,J=F?null:Tm(H?.messages),ie=F??J,X=H?.activeAgents,de=X&&X.length>0?X[X.length-1]:null;return{tool:ie?.tool??null,startedAt:ie?.startedAt??null,serverName:ie?.serverName??null,agentDescription:de?.description??null,agentStartedAt:de?.startedAt??null,pendingShells:H?.pendingBackgroundShells??null,transcriptTasks:H?.transcriptBackgroundTasks??null,scheduledWakeup:H?.scheduledWakeup??null}})),{headlineShell:v,overflowShells:g}=N.useMemo(()=>{if(!l||l.length===0)return{headlineShell:null,overflowShells:[]};let L=l[0];for(let H=1;H<l.length;H++)l[H].startedAt>L.startedAt&&(L=l[H]);const q=l.filter(H=>H!==L);return q.sort((H,Q)=>Q.startedAt-H.startedAt),{headlineShell:L,overflowShells:q}},[l]),[S,w]=N.useState(!1);N.useEffect(()=>{g.length===0&&S&&w(!1)},[g.length,S]);const E=N.useRef(null),x=N.useRef(null),m=N.useId();N.useEffect(()=>{if(!S)return;const L=H=>{const Q=H.target;Q&&(E.current&&E.current.contains(Q)||x.current&&x.current.contains(Q)||w(!1))},q=H=>{H.key==="Escape"&&(w(!1),x.current?.focus())};return document.addEventListener("mousedown",L),document.addEventListener("keydown",q),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("keydown",q)}},[S]);const y=V(L=>L.serverResultTimeoutMs??qz),[b,_]=N.useState(()=>Date.now());if(N.useEffect(()=>{if(e)return;const L=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(L)},[e]),e){if(v){const L=v.command&&v.command.length>0?v.command:v.shellId,q=tm(L),H=g.length,Q=H+1;return r.jsxs("div",{className:"activity-indicator activity-indicator--green","aria-label":"Waiting on background work",title:L,children:[r.jsx("span",{className:"activity-indicator__dot","aria-hidden":"true"}),r.jsxs("span",{className:"activity-indicator__label","data-testid":"activity-indicator-label",children:["Waiting on background work · ",q]}),H>0&&r.jsx("button",{ref:x,type:"button",className:"activity-indicator__disclosure","data-testid":"activity-indicator-disclosure","aria-expanded":S,"aria-controls":S?m:void 0,"aria-label":`Show all ${Q} pending background shells`,onClick:()=>w(F=>!F),children:r.jsxs("span",{"data-testid":"activity-indicator-more-badge",children:["+",H," more"]})}),S&&H>0&&r.jsx("div",{id:m,ref:E,className:"activity-indicator__popover","data-testid":"activity-indicator-popover",role:"dialog","aria-label":"Pending background shells",children:r.jsx("ul",{className:"activity-indicator__popover-list",children:[v,...g].map(F=>{const J=F.command&&F.command.length>0?F.command:F.shellId,ie=_p(Math.max(0,b-F.startedAt));return r.jsxs("li",{className:"activity-indicator__popover-item","data-testid":`activity-indicator-popover-item-${F.shellId}`,children:[r.jsx("code",{className:"activity-indicator__popover-command",title:J,children:J}),r.jsx("span",{className:"activity-indicator__popover-elapsed",children:ie})]},F.shellId)})})})]})}if(u&&u.length>0){let L=u[0];for(let F=1;F<u.length;F++)u[F].startedAt>L.startedAt&&(L=u[F]);const q=L.description||L.toolUseId,H=tm(q),Q=u.length-1;return r.jsxs("div",{className:"activity-indicator activity-indicator--green","aria-label":"Waiting on background work",title:q,"data-testid":"activity-indicator-transcript-tasks",children:[r.jsx("span",{className:"activity-indicator__dot","aria-hidden":"true"}),r.jsxs("span",{className:"activity-indicator__label","data-testid":"activity-indicator-label",children:["Waiting on background work · ",H,Q>0?` (+${Q} more)`:""]})]})}if(f){const L=new Date(f.at),q=`${String(L.getHours()).padStart(2,"0")}:${String(L.getMinutes()).padStart(2,"0")}`,H=f.reason?` · ${tm(f.reason)}`:"";return r.jsxs("div",{className:"activity-indicator activity-indicator--green","aria-label":"Agent resumes automatically",title:f.reason||void 0,"data-testid":"activity-indicator-scheduled-wakeup",children:[r.jsx("span",{className:"activity-indicator__dot","aria-hidden":"true"}),r.jsxs("span",{className:"activity-indicator__label","data-testid":"activity-indicator-label",children:["Resumes at ",q,H]})]})}return null}if(t==null){const L=d!=null?`Running ${d}`:n!=null?`Running ${fa(n,o??void 0)}`:"Working…";return r.jsxs("div",{className:"activity-indicator activity-indicator--green","aria-label":"Agent is working",children:[r.jsx("span",{className:"activity-indicator__dot","aria-hidden":"true"}),r.jsx("span",{className:"activity-indicator__label","data-testid":"activity-indicator-label",children:L})]})}const k=Math.max(0,b-t),j=y-k,T=j>0&&j<=6e4,D=Hz(k,y);let I;return d!=null&&h!=null?I=`Running ${d} · ${_p(b-h)}`:n!=null&&i!=null?I=`Running ${fa(n,o??void 0)} · ${_p(b-i)}`:I=`Working… last activity ${cN(k)}`,r.jsxs("div",{className:`activity-indicator ${D}`,"aria-label":"Agent is working",children:[r.jsx("span",{className:"activity-indicator__dot","aria-hidden":"true"}),r.jsx("span",{className:"activity-indicator__label","data-testid":"activity-indicator-label",children:I}),T&&r.jsxs("span",{className:"activity-indicator__warning",children:["approaching timeout (",Math.ceil(j/1e3),"s left)"]})]})}function Kz(){const e=V(l=>{const u=l.activeSessionId;return u?l.sessionStates[u]?.inactivityWarning??null:null}),t=V(l=>l.sendInput),n=V(l=>l.connectionPhase==="connected"),[,i]=N.useState(0);if(N.useEffect(()=>{if(!e)return;const l=window.setInterval(()=>i(u=>u+1),1e3);return()=>window.clearInterval(l)},[e]),!e)return null;const o=Math.max(0,Date.now()-e.receivedAt),d=e.idleMs+o,h=()=>{n&&t(e.prefab)};return r.jsxs("div",{className:"check-in-chip",children:[r.jsxs("span",{className:"check-in-chip__sr",role:"status","aria-live":"polite",children:["Agent has gone quiet. ",e.prefab]}),r.jsx("span",{className:"check-in-chip__dot","aria-hidden":"true"}),r.jsxs("span",{className:"check-in-chip__label","aria-hidden":"true",children:["Agent quiet for ",F0(d)]}),r.jsx("button",{type:"button",className:"check-in-chip__action",onClick:h,disabled:!n,"aria-label":`Send check-in: ${e.prefab}`,children:e.prefab})]})}const Wz=3;function Gz({meta:e}){const[t,n]=N.useState(!1),i=`evaluator-rewrite-${e.evaluatorIterationId}-details`;return r.jsxs("div",{className:"evaluator-rewrite-banner","data-testid":"evaluator-rewrite-banner",children:[r.jsxs("button",{type:"button",className:"evaluator-rewrite-toggle","aria-expanded":t,"aria-controls":i,onClick:()=>n(o=>!o),children:[r.jsx("span",{className:"evaluator-rewrite-icon","aria-hidden":"true",children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:r.jsx("path",{d:"M12 2L14.09 8.26L20 9.27L15.55 13.97L16.91 20L12 16.9L7.09 20L8.45 13.97L4 9.27L9.91 8.26L12 2Z"})})}),r.jsx("span",{className:"evaluator-rewrite-summary",children:"Your message was rewritten to be clearer — see why"}),r.jsx("span",{className:"evaluator-rewrite-chevron","aria-hidden":"true",children:t?"▾":"▸"})]}),t&&r.jsxs("div",{id:i,className:"evaluator-rewrite-details","data-testid":"evaluator-rewrite-details",children:[r.jsxs("div",{className:"evaluator-rewrite-section",children:[r.jsx("div",{className:"evaluator-rewrite-label",children:"Original"}),r.jsx("div",{className:"evaluator-rewrite-original",children:e.originalDraft})]}),r.jsxs("div",{className:"evaluator-rewrite-section",children:[r.jsx("div",{className:"evaluator-rewrite-label",children:"Rewritten"}),r.jsx("div",{className:"evaluator-rewrite-rewritten",children:e.rewritten})]}),e.reasoning&&r.jsxs("div",{className:"evaluator-rewrite-section",children:[r.jsx("div",{className:"evaluator-rewrite-label",children:"Why"}),r.jsx("div",{className:"evaluator-rewrite-reasoning",children:e.reasoning})]})]})]})}function Vz({evaluatorIteration:e,originalDraft:t,clarification:n,reasoning:i,onSubmit:o}){const[d,h]=N.useState(""),l=N.useRef(!1),u=N.useRef(o);u.current=o,N.useEffect(()=>{l.current=!1,h("")},[e]);const f=Math.max(Wz,e),v=()=>{if(l.current)return;const S=d.trim();S&&(l.current=!0,u.current(S))},g=S=>{S.key==="Enter"&&!S.shiftKey&&(S.preventDefault(),v())};return r.jsxs("div",{className:"evaluator-clarify-prompt","data-testid":"evaluator-clarify-prompt",children:[r.jsxs("div",{className:"evaluator-clarify-header",children:[r.jsx("span",{className:"evaluator-clarify-title",children:"Need a bit more detail"}),r.jsxs("span",{className:"evaluator-clarify-iteration","data-testid":"evaluator-clarify-iteration","aria-label":`Clarify iteration ${e} of ${f}`,children:["Iteration ",e,"/",f]})]}),r.jsxs("div",{className:"evaluator-clarify-section",children:[r.jsx("div",{className:"evaluator-clarify-label",children:"Your draft"}),r.jsx("div",{className:"evaluator-clarify-original",children:t})]}),r.jsxs("div",{className:"evaluator-clarify-section","data-testid":"evaluator-clarify-question-region",role:"status","aria-live":"polite","aria-atomic":"true",children:[r.jsx("div",{className:"evaluator-clarify-label",children:"Question"}),r.jsx("div",{className:"evaluator-clarify-question",children:n})]}),i&&r.jsxs("div",{className:"evaluator-clarify-section evaluator-clarify-reasoning-section",children:[r.jsx("div",{className:"evaluator-clarify-label",children:"Why"}),r.jsx("div",{className:"evaluator-clarify-reasoning",children:i})]}),r.jsxs("div",{className:"evaluator-clarify-input-row",children:[r.jsx("textarea",{className:"evaluator-clarify-input","data-testid":"evaluator-clarify-input",value:d,onChange:S=>h(S.target.value),onKeyDown:g,placeholder:"Answer the question…","aria-label":"Clarification answer",rows:2}),r.jsx("button",{type:"button",className:"evaluator-clarify-send","data-testid":"evaluator-clarify-send",onClick:v,disabled:!d.trim(),children:"Send"})]})]})}const Yz={display:"block",marginTop:4,fontSize:"0.8em",fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, monospace",opacity:.75},Zz={marginLeft:12,background:"transparent",border:"1px solid currentColor",color:"inherit",padding:"2px 10px",borderRadius:4,cursor:"pointer",fontSize:"0.85em"};function Xz({message:e,attemptedSessionId:t,onDismiss:n}){const i=typeof t=="string"&&t.trim().length>0;return r.jsxs("div",{className:"stream-stall-chip","data-testid":"session-not-found-chip",role:"status",title:e,children:[r.jsx("span",{className:"stream-stall-chip-text",children:"Session was restarted on the server — pick a session from the sidebar to continue."}),i&&r.jsxs("span",{"data-testid":"session-not-found-chip-id",style:Yz,children:["Attempted id: ",t]}),r.jsx("button",{type:"button",onClick:n,"data-testid":"session-not-found-chip-dismiss","aria-label":"Dismiss session-not-found notice",style:Zz,children:"Dismiss"})]})}function Qz({planHtml:e,onApprove:t,onFeedback:n}){return e?r.jsxs("div",{className:"plan-approval","data-testid":"plan-approval",role:"region","aria-label":"Plan ready for approval","aria-live":"polite",children:[r.jsx("div",{className:"plan-content","data-testid":"plan-content",dangerouslySetInnerHTML:{__html:_f.sanitize(e)}}),r.jsxs("div",{className:"plan-buttons",children:[r.jsx("button",{className:"btn-plan-approve",onClick:t,type:"button",children:"Approve"}),r.jsx("button",{className:"btn-plan-feedback",onClick:n,type:"button",children:"Feedback"})]})]}):null}function BS(e,t){if(!e||e<=0||!t)return null;const n=Date.now()-t;return Math.max(0,Math.ceil((e-n)/1e3))}function Jz(e){return`~${Math.floor(e/60)}:${String(e%60).padStart(2,"0")}`}function eU({visible:e,attempt:t,maxAttempts:n,message:i,onRetry:o,onStartServer:d,restartEtaMs:h,restartingSince:l,shutdownReason:u,terminal:f}){const v=!f&&!!h&&h>0&&!!l&&u!=="shutdown",[g,S]=N.useState(()=>v?BS(h,l):null);if(N.useEffect(()=>{if(!e||!v){S(null);return}let x;const m=()=>{const y=BS(h,l);S(y),y!=null&&y<=0&&x!==void 0&&clearInterval(x)};return m(),x=setInterval(m,1e3),()=>clearInterval(x)},[e,v,h,l]),!e)return null;let w;f?w=i||"Server appears to be down":u==="shutdown"?w="Server shut down":v&&g!=null&&g>0?w=`Server restarting... ${Jz(g)}`:v||i?w=i||"Server restarting...":w="Connection lost. Reconnecting...";let E=null;return v&&(u==="restart"?E="Graceful restart":(!u||u==="crash")&&(E="Recovering from crash")),r.jsxs("div",{className:"reconnect-banner","data-testid":"reconnect-banner",role:"status","aria-live":"polite",children:[r.jsxs("span",{className:"reconnect-message",children:[w,f?"":` (attempt ${t}/${n})`]}),E&&r.jsx("span",{className:"reconnect-detail","data-testid":"reconnect-detail",children:E}),d&&r.jsx("button",{className:"btn-retry","data-testid":"banner-start-server-button",onClick:d,type:"button",children:"Start Server"}),r.jsx("button",{className:"btn-retry","data-testid":"retry-button",onClick:o,type:"button",children:"Reconnect"})]})}function tU({lanBind:e,quickTunnel:t,onDismiss:n}){if(!e&&!t)return null;const i=[];return e&&i.push("Server is listening on all network interfaces — devices on your network can reach its auth and pairing endpoints. Restrict with --host 127.0.0.1."),t&&i.push("A public quick tunnel is configured — once established, anyone with its URL can probe this server (bearer-token gated). Use --tunnel none or --tunnel named to change this."),r.jsxs("div",{className:"exposure-warning-banner","data-testid":"exposure-warning-banner",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"exposure-warning-icon","aria-hidden":"true",children:"!"}),r.jsx("span",{className:"exposure-warning-message","data-testid":"exposure-warning-message",children:i.join(" ")}),r.jsx("button",{className:"btn-retry","data-testid":"exposure-dismiss-button",onClick:n,type:"button",children:"Dismiss"})]})}function nU({warnings:e,dismissed:t,onDismiss:n}){return t||!e||e.length===0?null:r.jsxs("div",{className:"exposure-warning-banner","data-testid":"billing-warning-banner",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"exposure-warning-icon","aria-hidden":"true",children:"$"}),r.jsx("span",{className:"exposure-warning-message","data-testid":"billing-warning-message",children:e.map(i=>i.message).join(" ")}),r.jsx("button",{className:"btn-retry","data-testid":"billing-dismiss-button",onClick:n,type:"button",children:"Dismiss"})]})}const sU={connected:"Connected to Chroxy server",connecting:"Connecting to Chroxy server",reconnecting:"Reconnecting to Chroxy server",server_restarting:"Chroxy server restarting",server_down:"Chroxy server appears to be down. Reconnect to try again.",disconnected:"Disconnected from Chroxy server"};function iU(e){return sU[e]??`Connection status: ${e}`}const rU={position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0};function aU({phase:e,debounceMs:t=1500}){const[n,i]=N.useState(""),o=N.useRef(""),d=N.useRef(null);return N.useEffect(()=>{if(d.current!=null&&(clearTimeout(d.current),d.current=null),e!==o.current)return d.current=setTimeout(()=>{d.current=null,e!==o.current&&(o.current=e,i(iU(e)))},t),()=>{d.current!=null&&(clearTimeout(d.current),d.current=null)}},[e,t]),r.jsx("div",{"data-testid":"connection-announcer",role:"status","aria-live":"polite","aria-atomic":"true",style:rU,children:n})}function oU({visible:e,sessionId:t,onRestart:n}){return!e||!t?null:r.jsxs("div",{className:"stdin-disabled-banner","data-testid":"stdin-disabled-banner",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"stdin-disabled-banner-icon","aria-hidden":"true",children:"!"}),r.jsx("span",{className:"stdin-disabled-banner-message",children:"Stdin forwarding lost — restart this session to continue."}),r.jsx("button",{className:"btn-retry","data-testid":"stdin-disabled-restart-button",onClick:()=>n(t),type:"button",children:"Restart Session"})]})}function ma(){if(typeof navigator>"u"||!navigator)return!1;const e=navigator.userAgent||"";return/Mac|iPod|iPhone|iPad/.test(e)}function yr(e){return ma()?e:e.replace(/\bCmd\b/g,"Ctrl")}const lU=5;function cU(e){const t=e.split("/");return t.length<=3?e:".../"+t.slice(-2).join("/")}function uU(e){const t=Date.now()-e;if(t<0)return"just now";const n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n} min ago`;const i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function dU(){return[{keys:yr("Cmd+K"),label:"Command palette"}]}function fU({onNewSession:e,recentSessions:t,onResumeSession:n,className:i}){const o=t.slice(0,lU),d=dU();return r.jsx("div",{className:["welcome-screen",i].filter(Boolean).join(" "),"data-testid":"welcome-screen",children:r.jsxs("div",{className:"welcome-inner",children:[r.jsxs("div",{className:"welcome-header",children:[r.jsx("h1",{className:"welcome-logo",children:"Chroxy"}),r.jsx("p",{className:"welcome-tagline",children:"CLI Agent IDE"})]}),r.jsx("div",{className:"welcome-actions",children:r.jsxs("button",{type:"button",className:"welcome-card welcome-card-primary","data-testid":"welcome-new-session",onClick:e,children:[r.jsx("span",{className:"welcome-card-icon",children:"+"}),r.jsx("span",{className:"welcome-card-label",children:"New Session"})]})}),o.length>0&&r.jsxs("div",{className:"welcome-recent","data-testid":"welcome-recent-list",children:[r.jsx("h2",{className:"welcome-section-title",children:"Recent Sessions"}),r.jsx("ul",{className:"welcome-recent-items",children:o.map(h=>r.jsx("li",{"data-testid":`welcome-recent-item-${h.conversationId}`,children:r.jsxs("button",{type:"button",className:"welcome-recent-btn",onClick:()=>n(h.conversationId,h.cwd),children:[r.jsx("span",{className:"welcome-recent-preview",children:h.preview}),r.jsxs("span",{className:"welcome-recent-meta",children:[r.jsx("span",{className:"welcome-recent-cwd","data-testid":`welcome-recent-cwd-${h.conversationId}`,children:cU(h.cwd)}),r.jsx("span",{className:"welcome-recent-time",children:uU(h.updatedAt)})]})]})},h.conversationId))})]}),r.jsx("div",{className:"welcome-shortcuts",children:d.map(h=>r.jsxs("span",{className:"welcome-shortcut",children:[r.jsx("kbd",{children:h.keys})," ",h.label]},h.keys))})]})})}const $S=3,hU={permission:"Permission",question:"Question",completed:"Completed",error:"Error"};function pU({notifications:e,onApprove:t,onDeny:n,onDismiss:i,onSwitchSession:o}){const d=e.filter(u=>u.readAt===void 0);if(d.length===0)return null;const h=d.slice(0,$S),l=d.length-$S;return r.jsxs("div",{className:"notification-banners",role:"log","aria-label":"Background session notifications",children:[h.map(u=>r.jsxs("div",{className:`notification-banner notification-banner--${u.eventType}`,children:[r.jsxs("div",{className:"notification-banner-content",children:[r.jsx("span",{className:"notification-banner-type",children:hU[u.eventType]}),r.jsx("button",{type:"button",className:"notification-banner-session",onClick:()=>o(u.sessionId),children:u.sessionName}),r.jsx("span",{className:"notification-banner-message",children:u.message})]}),r.jsx("div",{className:"notification-banner-actions",children:u.eventType==="permission"&&u.requestId?r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"notification-banner-btn notification-banner-btn--allow","aria-label":"Allow",onClick:()=>t(u.requestId,u.id),children:"Allow"}),r.jsx("button",{type:"button",className:"notification-banner-btn notification-banner-btn--deny","aria-label":"Deny",onClick:()=>n(u.requestId,u.id),children:"Deny"})]}):r.jsx("button",{type:"button",className:"notification-banner-btn notification-banner-btn--dismiss","aria-label":"Dismiss",onClick:()=>i(u.id),children:"Dismiss"})})]},u.id)),l>0&&r.jsxs("div",{className:"notification-banner-overflow",children:["+",l," more"]})]})}function mU({requests:e,onApprove:t,onDeny:n}){return!e||e.length===0?null:r.jsx("div",{className:"pair-requests","data-testid":"pair-requests",role:"log","aria-label":"Pending device pairing requests",children:e.map(i=>r.jsxs("div",{className:"pair-request-banner","data-testid":`pair-request-${i.requestId}`,children:[r.jsxs("div",{className:"pair-request-content",children:[r.jsx("span",{className:"pair-request-title",children:"Pairing request"}),r.jsx("span",{className:"pair-request-device","data-testid":"pair-request-device",children:i.deviceName||"Unknown device"}),r.jsx("span",{className:"pair-request-compare",children:"Compare this code with the new device:"}),r.jsx("span",{className:"pair-request-code","data-testid":"pair-request-code",children:i.verifyCode})]}),r.jsxs("div",{className:"pair-request-actions",children:[r.jsx("button",{type:"button",className:"pair-request-btn pair-request-btn--approve","data-testid":"pair-request-approve","aria-label":`Approve pairing for ${i.deviceName||"unknown device"}`,onClick:()=>t(i.requestId),children:"Approve"}),r.jsx("button",{type:"button",className:"pair-request-btn pair-request-btn--deny","data-testid":"pair-request-deny","aria-label":`Deny pairing for ${i.deviceName||"unknown device"}`,onClick:()=>n(i.requestId),children:"Deny"})]})]},i.requestId))})}function b1(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function _1(e,t){const n=e.replace(/\\/g,"/");return n.endsWith("/")?`${n}${t}`:`${n}/${t}`}function gU(e){return[...e].sort((t,n)=>{if(t.isDirectory!==n.isDirectory)return t.isDirectory?-1:1;const i=t.name.toLowerCase(),o=n.name.toLowerCase();return i<o?-1:i>o?1:0})}function vU(e,t,n,i){const o=[],d=(h,l)=>{const u=t.get(h);if(u)for(const f of gU(u)){const v=_1(h,f.name),g=f.isDirectory&&n.has(v),S=f.isDirectory?t.get(v):void 0;o.push({entry:f,path:v,depth:l,expanded:g,loading:f.isDirectory&&i.has(v),childCount:f.isDirectory&&S?S.length:null}),g&&d(v,l+1)}};return d(e,0),o}function yU(e,t){const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function bU(e,t){if(!e||!t)return[];const n=t.replace(/\\/g,"/").replace(/\/$/,""),i=e.replace(/\\/g,"/");let o;if(i.startsWith(n+"/"))o=i.slice(n.length+1);else{if(b1(i))return[];o=i.replace(/^\.?\//,"")}const d=o.split("/").filter(Boolean),h=[];for(let l=0;l<d.length-1;l++)h.push(n+"/"+d.slice(0,l+1).join("/"));return h}function _U(e,t){if(!t)return[];const n=t.replace(/\\/g,"/").replace(/\/$/,""),i=n.split("/").pop()||n;if(!e)return[{label:i,path:n,isLeaf:!0}];const o=e.replace(/\\/g,"/");let d;if(o.startsWith(n+"/"))d=o.slice(n.length+1);else{if(b1(o))return[{label:i,path:n,isLeaf:!0}];d=o.replace(/^\.?\//,"")}const h=d.split("/").filter(Boolean),l=[{label:i,path:n,isLeaf:h.length===0}];for(let u=0;u<h.length;u++)l.push({label:h[u],path:n+"/"+h.slice(0,u+1).join("/"),isLeaf:u===h.length-1});return l}function SU(e,t){if(t)return"📁";switch(e.includes(".")?e.split(".").pop()?.toLowerCase():""){case"js":case"mjs":case"cjs":return"🟨";case"ts":case"tsx":return"🔵";case"jsx":return"🟡";case"json":return"📋";case"md":case"mdx":return"📝";case"css":case"scss":case"less":return"🎨";case"html":case"htm":return"🌐";case"py":return"🐍";case"rs":return"⚙";case"go":return"🐹";case"rb":return"💎";case"sh":case"bash":case"zsh":return"📟";case"yml":case"yaml":return"⚙";case"toml":return"⚙";case"lock":return"🔒";case"svg":case"png":case"jpg":case"jpeg":case"gif":case"webp":return"🖼";default:return"📄"}}function xU(e){switch(e){case"modified":return{char:"M",className:"git-modified"};case"added":return{char:"A",className:"git-added"};case"deleted":return{char:"D",className:"git-deleted"};case"renamed":return{char:"R",className:"git-renamed"};case"untracked":return{char:"U",className:"git-untracked"};default:return null}}function Im(e){return e===null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wU(e,t){if(!e||!t)return!0;const n=e.replace(/\\/g,"/"),i=t.replace(/\\/g,"/");return n===i?!0:i.startsWith("/")||/^[A-Za-z]:\//.test(i)?!1:n.endsWith("/"+i.replace(/^\.?\//,""))}function kU(e,t){const n=new Map;if(!e||!t)return n;for(const i of e.unstaged)n.set(i.path,i.status);for(const i of e.staged)n.has(i.path)||n.set(i.path,i.status);for(const i of e.untracked)n.has(i)||n.set(i,"untracked");return n}function Mm(e,t){return e.startsWith(t+"/")?e.slice(t.length+1):e}function CU({item:e,rootPath:t,gitStatusMap:n,selected:i,onToggle:o,onFileClick:d}){const{entry:h,path:l,depth:u,expanded:f,loading:v,childCount:g}=e,S=Mm(l,t),w=n.get(S),E=w?xU(w):null,x=h.isDirectory?v?"⋯":f?"▾":"▸":"";return r.jsx("li",{className:"file-tree-item",role:"none",children:r.jsxs("button",{type:"button",role:"treeitem","aria-level":u+1,"aria-expanded":h.isDirectory?f:void 0,"aria-selected":i||void 0,className:`file-tree-btn${h.isDirectory?" is-directory":""}${i?" is-selected":""}`,style:{paddingLeft:`${6+u*14}px`},onClick:()=>h.isDirectory?o(l):d(l),title:h.isDirectory?h.name:`${h.name}${h.size!==null?` (${Im(h.size)})`:""}`,children:[r.jsx("span",{className:`file-tree-chevron${h.isDirectory?"":" file-tree-chevron--leaf"}`,"aria-hidden":"true",children:x}),r.jsx("span",{className:"file-tree-icon","aria-hidden":"true",children:SU(h.name,h.isDirectory)}),r.jsx("span",{className:"file-tree-name",children:h.name}),E&&r.jsx("span",{className:`file-tree-git ${E.className}`,"aria-label":`git ${w}`,children:E.char}),h.isDirectory&&g!==null&&r.jsx("span",{className:"file-tree-count","aria-label":`${g} item${g===1?"":"s"}`,children:g}),!h.isDirectory&&h.size!==null&&r.jsx("span",{className:"file-tree-size",children:Im(h.size)})]})})}const EU={function:"ƒ",method:"ƒ",class:"C",interface:"I",type:"T",enum:"E",const:"k",variable:"v"};function NU({groups:e,loading:t,onPick:n}){return t&&e.length===0?r.jsx("div",{className:"symbol-panel-status","data-testid":"symbol-panel-loading",children:"Loading symbols…"}):e.length===0?r.jsx("div",{className:"symbol-panel-status","data-testid":"symbol-panel-empty",children:"No symbols"}):r.jsx("div",{className:"symbol-panel","data-testid":"symbol-panel",children:e.map(([i,o])=>r.jsxs("div",{className:"symbol-group",children:[r.jsxs("div",{className:"symbol-group-kind","data-testid":`symbol-group-${i}`,children:[i,r.jsx("span",{className:"symbol-group-count",children:o.length})]}),r.jsx("ul",{className:"symbol-list",role:"list",children:o.map((d,h)=>r.jsx("li",{children:r.jsxs("button",{type:"button",className:"symbol-item","data-testid":`symbol-item-${d.name}`,onClick:()=>n(d.line),title:`${d.kind} · line ${d.line}`,children:[r.jsx("span",{className:"symbol-item-icon","aria-hidden":"true",children:EU[d.kind]??"•"}),r.jsx("span",{className:"symbol-item-name",children:d.name}),d.exported&&r.jsx("span",{className:"symbol-item-exported",title:"exported",children:"↗"}),r.jsx("span",{className:"symbol-item-line",children:d.line})]})},`${d.name}-${d.line}-${h}`))})]},i))})}function jU(){const e=V(ze=>ze.requestFileListing),t=V(ze=>ze.requestFileContent),n=V(ze=>ze.requestGitStatus),i=V(ze=>ze.setFileBrowserCallback),o=V(ze=>ze.setFileContentCallback),d=V(ze=>ze.setGitStatusCallback),h=V(ze=>ze.requestSymbols),l=V(ze=>ze.symbols),u=V(ze=>ze.symbolsLoading),f=V(ze=>ze.serverCapabilities.ide===!0),v=V(ze=>ze.fileBrowserPendingOpen),g=V(ze=>ze.requestResolveSymbol),S=V(ze=>ze.requestFindReferences),w=V(ze=>ze.symbolLocation),E=V(ze=>ze.openFileInBrowser),[x,m]=N.useState(new Map),[y,b]=N.useState(new Set),[_,k]=N.useState(new Set),[j,T]=N.useState(!1),[D,I]=N.useState(null),L=V(ze=>ze.activeSessionId),q=V(ze=>L?ze.sessionStates[L]?.selectedFilePath??null:null),[H,Q]=N.useState(q),F=N.useRef(q),J=N.useCallback(ze=>{F.current=ze,Q(ze);const Je=V.getState().activeSessionId;if(Je){const{sessionStates:tt}=V.getState(),Pt=tt[Je];Pt&&V.setState({sessionStates:{...tt,[Je]:{...Pt,selectedFilePath:ze}}})}},[]),[ie,X]=N.useState(null),[de,fe]=N.useState(null),[$,P]=N.useState(null),[B,K]=N.useState(!1),[le,me]=N.useState(!1),[be,Ee]=N.useState(null),[se,Z]=N.useState(null),[ge,De]=N.useState(null),Ge=N.useRef(null),Ve=N.useRef(null),St=N.useRef(null),[Nt,kt]=N.useState(null),[Tt,at]=N.useState(null),en=N.useRef(null);N.useEffect(()=>(i(Je=>{T(!1),I(Je.error),Je.path&&(Je.parentPath===null&&De(Je.path),m(tt=>{const Pt=new Map(tt);return Pt.set(Je.path,Je.entries),Pt}),k(tt=>{if(!tt.has(Je.path))return tt;const Pt=new Set(tt);return Pt.delete(Je.path),Pt}))}),()=>i(null)),[i]),N.useLayoutEffect(()=>{F.current=H},[H]),N.useEffect(()=>(o(Je=>{if(Je.requestId!=null){const tt=V.getState().lastFileContentRequestId;if(tt!=null&&Je.requestId!==tt)return}else if(!wU(Je.path,F.current))return;X(Je.content),fe(Je.language),P(Je.size),K(Je.truncated),Ee(Je.error),me(!1)}),()=>o(null)),[o]),N.useEffect(()=>(d(Je=>{Z(Je)}),()=>d(null)),[d]),N.useEffect(()=>{m(new Map),b(new Set),k(new Set),I(null),X(null),fe(null),P(null),K(!1),Ee(null),Z(null),at(null),en.current=null,De(null);const ze=V.getState(),Je=ze.activeSessionId,tt=Je?ze.sessionStates[Je]?.selectedFilePath??null:null;Q(tt),T(!0),e(),n(),tt&&(me(!0),t(tt))},[L,e,n,t]);const cn=N.useMemo(()=>kU(se,ge),[se,ge]),Bt=N.useCallback(ze=>{!y.has(ze)&&!x.has(ze)&&!_.has(ze)&&(k(tt=>new Set(tt).add(ze)),e(ze)),b(tt=>yU(tt,ze))},[y,x,_,e]),hn=N.useCallback(ze=>{const Je=bU(_1(ze,"x"),ge||"");for(const tt of Je)!x.has(tt)&&!_.has(tt)&&(k(Pt=>new Set(Pt).add(tt)),e(tt));b(tt=>{const Pt=new Set(tt);return Je.forEach(Vt=>Pt.add(Vt)),Pt})},[x,_,e,ge]),sn=N.useCallback(ze=>{J(ze),me(!0),Ee(null),X(null),t(ze)},[t]),Ct=N.useCallback(ze=>{if(!f)return;const Je=ze.metaKey||ze.ctrlKey,tt=ze.altKey;if(!Je&&!tt)return;const Pt=ze.target,Wt=(typeof Pt.className=="string"?Pt.className:"").match(/(?:^|\s)syn-(\w+)/);if(!Wt||!["plain","function","type","property"].includes(Wt[1]))return;const Zt=(Pt.textContent||"").trim();if(!/^[A-Za-z_$][\w$]*$/.test(Zt))return;ze.preventDefault();const Dn=H&&ge?Mm(H,ge):void 0;Je?g(Zt,Dn):S(Zt,Dn)},[f,H,ge,g,S]);N.useEffect(()=>{v&&(sn(v.path),Ve.current=v.line??null)},[v,sn]);const Ut=N.useCallback(()=>{J(null),X(null),Ee(null),at(null),en.current=null},[]);N.useEffect(()=>{if(!H||!f||!ge)return;const ze=Mm(H,ge);en.current!==ze&&(en.current=ze,at(ze),h(ze))},[H,ge,f,h]);const $t=N.useMemo(()=>{if(!l||!Tt||l.path!==Tt)return[];const ze=new Map;for(const Je of l.symbols){const tt=ze.get(Je.kind);tt?tt.push(Je):ze.set(Je.kind,[Je])}return[...ze.entries()].sort((Je,tt)=>Je[0]<tt[0]?-1:1)},[l,Tt]),Lt=N.useCallback(ze=>{const Je=Ge.current?.querySelector(`[data-line="${ze}"]`);Je&&(Je.scrollIntoView({block:"center",behavior:"smooth"}),Je.classList.add("file-viewer-line--active"),window.setTimeout(()=>Je.classList.remove("file-viewer-line--active"),1400))},[]);N.useEffect(()=>{if(Ve.current==null||ie==null)return;const ze=Ve.current;Ve.current=null;const Je=window.setTimeout(()=>Lt(ze),0);return()=>window.clearTimeout(Je)},[ie,Lt]),N.useEffect(()=>{if(!w||St.current===w.nonce)return;if(St.current=w.nonce,w.file&&w.line!=null){E(w.file,w.line),kt(null);return}kt(w.symbol||"symbol");const ze=window.setTimeout(()=>kt(null),2200);return()=>window.clearTimeout(ze)},[w,E]);const Ht=N.useMemo(()=>_U(H,ge||""),[H,ge]),zt=N.useMemo(()=>ge?vU(ge,x,y,_):[],[ge,x,y,_]),rn=N.useMemo(()=>!ie||!de||de==="image"?null:ie.split(`
|
|
96
|
-
`).map(Je=>$0(Je,de)),[ie,de]);return r.jsxs("div",{className:"file-browser-panel","data-testid":"file-browser-panel",children:[r.jsxs("div",{className:`file-browser-tree${H?" with-viewer":""}`,children:[r.jsxs("nav",{className:"file-browser-breadcrumb","aria-label":"File browser breadcrumb",children:[Ht.map((ze,Je)=>r.jsxs("span",{children:[Je>0&&r.jsx("span",{className:"file-browser-sep",children:"/"}),ze.isLeaf?r.jsx("span",{className:"file-browser-crumb file-browser-crumb--current",children:ze.label}):r.jsx("button",{type:"button",className:"file-browser-crumb",onClick:()=>hn(ze.path),children:ze.label})]},ze.path)),se?.branch&&r.jsx("span",{className:"file-browser-branch",title:`Branch: ${se.branch}`,children:se.branch})]}),r.jsxs("div",{className:"file-browser-entries",children:[j&&x.size===0&&r.jsx("div",{className:"file-browser-loading",children:"Loading..."}),!j&&D&&r.jsx("div",{className:"file-browser-error",children:D}),!D&&x.size>0&&zt.length===0&&r.jsx("div",{className:"file-browser-empty",children:"Empty directory"}),zt.length>0&&r.jsx("ul",{className:"file-tree-list",role:"tree",children:zt.map(ze=>r.jsx(CU,{item:ze,rootPath:ge||"",gitStatusMap:cn,selected:H===ze.path,onToggle:Bt,onFileClick:sn},ze.path))})]})]}),H&&r.jsxs("div",{className:"file-browser-viewer",children:[r.jsxs("div",{className:"file-viewer-header",children:[r.jsx("span",{className:"file-viewer-path",title:H,children:H.split("/").pop()}),$!==null&&r.jsx("span",{className:"file-viewer-size",children:Im($)}),B&&r.jsx("span",{className:"file-viewer-truncated",children:"Truncated"}),r.jsx("button",{type:"button",className:"file-viewer-close",onClick:Ut,"aria-label":"Close file",children:"×"})]}),f&&ie!==null&&de!=="image"&&r.jsx(NU,{groups:$t,loading:u,onPick:Lt}),r.jsxs("div",{className:"file-viewer-content",ref:Ge,children:[Nt&&r.jsxs("div",{className:"file-viewer-def-notfound","data-testid":"def-not-found",role:"status",children:["Definition not found for ",r.jsx("code",{children:Nt})]}),le&&r.jsx("div",{className:"file-viewer-loading",children:"Loading file..."}),!le&&be&&r.jsx("div",{className:"file-viewer-error",children:be}),!le&&!be&&ie!==null&&de==="image"&&r.jsx("div",{className:"file-viewer-image",children:r.jsx("img",{src:ie,alt:H.split("/").pop()||"Image preview",style:{maxWidth:"100%",maxHeight:"80vh",objectFit:"contain"}})}),!le&&!be&&ie!==null&&de!=="image"&&r.jsx("pre",{className:f?"file-viewer-code file-viewer-code--ide":"file-viewer-code",onClick:Ct,title:f?"Cmd/Ctrl+click a symbol to jump to its definition":void 0,children:r.jsx("code",{children:rn?rn.map((ze,Je)=>r.jsxs("span",{className:"file-viewer-line","data-line":Je+1,children:[r.jsx("span",{className:"file-viewer-line-num",children:Je+1}),ze.map((tt,Pt)=>r.jsx("span",{className:`syn-${tt.type}`,children:tt.text},Pt)),`
|
|
97
|
-
`]},Je)):ie})})]})]})]})}function AU(e){const t=new Date(e),n=new Date,i=t.toDateString()===n.toDateString(),o=t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});if(i)return o;const d=new Date(n);return d.setDate(d.getDate()-1),t.toDateString()===d.toDateString()?`Yesterday ${o}`:t.toLocaleDateString(void 0,{month:"short",day:"numeric"})+" "+o}function RU(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function TU({checkpoint:e,isLatest:t,onRestore:n,onDelete:i,confirmingDelete:o,setConfirmingDelete:d}){const h=o===e.id,l=!!e.name?.trim();return r.jsxs("div",{className:`cp-node${t?" cp-latest":""}`,"data-testid":"checkpoint-node",children:[r.jsx("div",{className:"cp-dot"}),r.jsxs("div",{className:"cp-card",children:[r.jsxs("div",{className:"cp-header",children:[r.jsx("span",{className:"cp-name",title:l?e.name:e.id,children:l?e.name:`Checkpoint ${e.id.slice(0,8)}`}),r.jsx("span",{className:"cp-time",title:AU(e.createdAt),children:RU(e.createdAt)})]}),e.description?.trim()&&r.jsx("div",{className:"cp-desc",children:e.description}),r.jsxs("div",{className:"cp-meta",children:[r.jsxs("span",{className:"cp-messages",title:`${e.messageCount} messages`,children:[e.messageCount," msgs"]}),e.hasGitSnapshot&&r.jsx("span",{className:"cp-git-badge",title:"Includes git snapshot",children:"git"})]}),r.jsxs("div",{className:"cp-actions",children:[r.jsx("button",{type:"button",className:"cp-btn cp-restore",onClick:()=>n(e.id),title:"Restore to this checkpoint (creates new session)",children:"Restore"}),h?r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"cp-btn cp-delete-confirm",onClick:()=>{i(e.id),d(null)},children:"Confirm"}),r.jsx("button",{type:"button",className:"cp-btn cp-cancel",onClick:()=>d(null),children:"Cancel"})]}):r.jsx("button",{type:"button",className:"cp-btn cp-delete",onClick:()=>d(e.id),title:"Delete checkpoint",children:"Delete"})]})]})]})}function IU(){const e=V(m=>m.checkpoints),t=V(m=>m.listCheckpoints),n=V(m=>m.createCheckpoint),i=V(m=>m.restoreCheckpoint),o=V(m=>m.deleteCheckpoint),d=V(m=>m.connectionPhase),[h,l]=N.useState(""),[u,f]=N.useState(!1),[v,g]=N.useState(null);N.useEffect(()=>{d==="connected"&&t()},[d,t]);const S=N.useMemo(()=>[...e].sort((m,y)=>y.createdAt-m.createdAt),[e]),w=N.useCallback(()=>{const m=h.trim()||void 0;n(m),l(""),f(!1)},[h,n]),E=N.useCallback(m=>{i(m)},[i]),x=N.useCallback(m=>{o(m)},[o]);return r.jsxs("div",{className:"checkpoint-timeline","data-testid":"checkpoint-timeline",children:[r.jsx("div",{className:"cp-create-section",children:u?r.jsxs("div",{className:"cp-create-form",children:[r.jsx("input",{type:"text",className:"cp-create-input",placeholder:"Checkpoint name (optional)",value:h,onChange:m=>l(m.target.value),onKeyDown:m=>{m.key==="Enter"&&w(),m.key==="Escape"&&f(!1)},autoFocus:!0}),r.jsx("button",{type:"button",className:"cp-btn cp-create-btn",onClick:w,children:"Create"}),r.jsx("button",{type:"button",className:"cp-btn cp-cancel",onClick:()=>f(!1),children:"Cancel"})]}):r.jsx("button",{type:"button",className:"cp-btn cp-new-btn",onClick:()=>f(!0),children:"+ New Checkpoint"})}),S.length===0?r.jsx("div",{className:"cp-empty",children:"No checkpoints yet. Create one to save your current conversation state."}):r.jsx("div",{className:"cp-timeline-track",children:S.map((m,y)=>r.jsx(TU,{checkpoint:m,isLatest:y===0,onRestore:E,onDelete:x,confirmingDelete:v,setConfirmingDelete:g},m.id))})]})}function S1({cost:e,provider:t}){if(e==null)return"No usage yet — cost will appear after the first turn completes.";const n=`Total session cost so far: $${e.toFixed(4)}.`;return t&&vw.has(t)?`${n} Estimated client-side from token usage (Codex/Gemini don't return a server-authoritative cost).`:n}function x1({percent:e,contextSummary:t,inputTokens:n,outputTokens:i}){if(e==null&&!t&&n==null&&i==null)return"No context usage yet — meter fills after the first turn completes.";const o=e!=null?`Most recent turn used ${DU(e)}% of the model's context window.`:"Most recent turn context usage.",d=t?` (${t})`:"",h=n!=null&&i!=null?" "+MU({inputTokens:n,outputTokens:i}):"";return`${o}${d} This is per-turn — resets each turn and the visible width caps at 100%.${h}`}function MU({inputTokens:e,outputTokens:t}){const n=e+t;return`Breakdown: ${Ga(e)} input + ${Ga(t)} output = ${Ga(n)} tokens.`}function DU(e){const t=Math.round(e*10)/10;return Number.isInteger(t)?String(t):t.toFixed(1)}function LU({model:e,contextWindow:t}){if(!e)return"Active model unknown.";const n=t?` Context window: ${t.toLocaleString()} tokens.`:"";return`Active model: ${e}.${n}`}function w1(e){return!e||e<=0?"":`${e} background ${e===1?"agent":"agents"} currently active in this session.`}function OU(e){const t=e.replace(/\/+$/,"").split("/");return t.length<=2?e:t.slice(-2).join("/")}const zS={connected:"Connected",connecting:"Connecting",reconnecting:"Reconnecting",server_restarting:"Restarting",server_down:"Server down",disconnected:"Disconnected"},US=80,nm=100;function PU({connectionPhase:e,chatActivityState:t,tunnelReady:n=!0,serverPhase:i,tunnelProgress:o,serverVersion:d,cwd:h,model:l,cost:u,context:f,contextPercent:v,inputTokens:g,outputTokens:S,isBusy:w,agentCount:E,onShowQr:x,onShareSession:m,provider:y,contextWindow:b,onCompact:_,interventions:k,activeSessionId:j}){const[T,D]=N.useState(!1);N.useEffect(()=>{D(!1)},[j]);const I=k?.length??0,L=d??"0.10.0",H=i==="tunnel_warming"||i==="tunnel_verifying"||e==="connected"&&!n&&i==null;let Q;H?Q=o?`Tunnel warming up… (${o.attempt}/${o.maxAttempts})`:"Tunnel warming up…":Q=zS[e]??e;const F=H?"connecting":e,J=S1({cost:u??void 0,provider:y}),ie=x1({percent:v??null,contextSummary:f,inputTokens:g,outputTokens:S}),X=LU({model:l,contextWindow:b}),de=w1(E),fe=`Chroxy server v${L}`,$=H?Q:zS[e]??`Connection status: ${e}`;return r.jsxs("footer",{className:"footer-bar","data-testid":"footer-bar",children:[r.jsxs("div",{className:"footer-left",children:[r.jsxs("span",{className:"footer-version",title:fe,"aria-label":fe,children:["v",L]}),r.jsx("span",{className:`footer-status-dot ${F}`,"data-activity":F==="connected"?t:void 0,title:$,"aria-label":$}),r.jsx("span",{className:"footer-status-label","aria-hidden":"true",children:Q}),h&&r.jsx("span",{className:"footer-cwd",title:h,"aria-label":`Working directory: ${h}`,children:OU(h)})]}),r.jsxs("div",{className:"footer-right",children:[x&&r.jsx("button",{className:"footer-qr-btn",onClick:x,type:"button","aria-label":"Show QR code",title:"Show QR code — scan with the Chroxy mobile app to pair",children:"QR"}),m&&r.jsx("button",{className:"footer-qr-btn",onClick:m,type:"button","aria-label":"Share this session","data-testid":"btn-share-session",title:"Share this session — scanner gets a session-bound token (#3070)",children:"Share"}),w&&r.jsx("span",{className:"footer-busy",role:"img","aria-label":"Agent working"}),I>0&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{type:"button",className:`footer-interventions${T?" open":""}`,onClick:()=>D(P=>!P),"aria-expanded":T,"aria-label":`${I} chroxy ${I===1?"intervention":"interventions"} (click to ${T?"hide":"show"} details)`,title:"chroxy intervened during this session — click for details","data-testid":"footer-interventions",children:[I," ",I===1?"intervention":"interventions"]}),T&&r.jsx(BU,{interventions:k,onClose:()=>D(!1)})]}),E!=null&&E>0&&r.jsxs("span",{className:"footer-agents",title:de,"aria-label":de,children:[E," ",E===1?"agent":"agents"]}),l&&r.jsx("span",{className:"footer-model",title:X,"aria-label":X,children:l}),u!=null&&r.jsxs("span",{className:"footer-cost",title:J,"aria-label":J,children:["$",u.toFixed(4)]}),f&&r.jsx("span",{className:"footer-context",title:ie,"aria-label":ie,children:v!=null?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`footer-context-bar${v>=nm?" high over-budget":v>=US?" high":v>=50?" medium":""}`,role:"progressbar","aria-label":"Context window usage","aria-valuenow":Math.min(Math.round(v),100),"aria-valuemin":0,"aria-valuemax":100,children:r.jsx("span",{className:"footer-context-fill",style:{width:`${Math.min(v,100)}%`}})}),r.jsxs("span",{className:"footer-context-label",children:[Math.round(v),"%"]})]}):f}),v!=null&&v>=US&&_&&r.jsx("button",{type:"button",className:`footer-compact-suggest${v>=nm?" over-budget":""}`,onClick:_,"data-testid":"btn-compact-session",title:v>=nm?"Context window full — send /compact to free space (the model may already be silently truncating older context).":"Context is filling up — send /compact to summarise older turns and free space.","aria-label":"Compact session — send /compact to free context space",children:"/compact"})]})]})}function BU({interventions:e,onClose:t}){const n=[...e].reverse();return r.jsxs("div",{className:"footer-interventions-panel",role:"dialog","aria-label":"Recent chroxy interventions","data-testid":"footer-interventions-panel",children:[r.jsxs("div",{className:"footer-interventions-panel-header",children:[r.jsx("span",{children:"Recent chroxy interventions"}),r.jsx("button",{type:"button",onClick:t,"aria-label":"Close interventions panel",className:"footer-interventions-close",children:"×"})]}),r.jsx("ul",{className:"footer-interventions-list",children:n.map(i=>r.jsxs("li",{className:"footer-interventions-item","data-testid":`intervention-${i.toolUseId}`,children:[r.jsx("div",{className:"footer-interventions-reason",children:$U(i)}),r.jsx("div",{className:"footer-interventions-meta",children:zU(i.timestamp)})]},i.toolUseId))})]})}function $U(e){if(e.kind==="multi_question")return`Multi-question form intercepted (${e.count} questions) — asked agent to ask one at a time`;{const t=e.kind;return`chroxy intervention: ${String(t)}`}}function zU(e){const t=Date.now()-e;if(t<0)return"just now";const n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;const i=Math.floor(n/60);if(i<60)return`${i}m ago`;const o=Math.floor(i/60);return o<24?`${o}h ago`:new Date(e).toISOString().slice(0,10)}function UU(e,t,n){const i=t,o={navigation:"Global",view:"Global",session:"Session",sidebar:"Sidebar",composer:"Input",other:"Global"},d=Array.from({length:9},(g,S)=>e.get(`session.switch.${S+1}`)),h=(()=>{const g=d[0];if(!g)return!1;const S=Nm(g.binding);if(S.key!=="1")return!1;for(let w=0;w<d.length;w+=1){const E=d[w];if(!E)return!1;const x=Nm(E.binding);if(x.key!==String(w+1)||x.meta!==S.meta||x.shift!==S.shift||x.alt!==S.alt)return!1}return!0})(),l=d[0],u=l?Jo(l.binding,i).replace(/1$/,"1-9"):"Cmd+1-9",f=[];for(const g of e.list()){if(/^session\.switch\.[2-9]$/.test(g.id)){if(h)continue;f.push({keys:Jo(g.binding,i),description:g.description,section:o[g.category]||"Global"});continue}if(g.id==="session.switch.1"){h?f.push({keys:u,description:"Switch to tab by number",section:o[g.category]||"Global"}):f.push({keys:Jo(g.binding,i),description:g.description,section:o[g.category]||"Global"});continue}f.push({keys:Jo(g.binding,i),description:g.description,section:o[g.category]||"Global"})}const v=[{keys:"Cmd+Y",description:"Allow current permission prompt",section:"Session"},{keys:"Cmd+Shift+Y",description:"Allow current permission prompt for this session (rule-eligible tools)",section:"Session"},{keys:"Cmd+Enter",description:"Send message",section:"Input"},{keys:"Escape",description:"Close modal / cancel",section:"Global"}];return hs()&&n&&v.push({keys:"Ctrl+V",description:"Paste image from clipboard (Cmd+V stays as text paste)",section:"Input"}),[...f,...v].map(g=>({...g,keys:yr(g.keys)}))}function qU(){return typeof window>"u"?null:window.__TAURI__?.clipboardManager??null}async function Pc(e){if(hs()){const t=qU();if(t?.writeText)try{return await t.writeText(e),!0}catch{return!1}}if(typeof navigator>"u"||!navigator.clipboard)return!1;try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}function HU(){N.useEffect(()=>{const e=pg();if(!e)return;const t=[];return t.push(e("server_ready",n=>{const{url:i,token:o,port:d}=n.payload;if(V.setState({serverStartupLogs:null}),window.location.href.includes("/dashboard")){const h=`ws://localhost:${d}/ws`;V.getState().connect(h,o)}else window.location.href=i})),t.push(e("server_stopped",()=>{V.getState().disconnect()})),t.push(e("server_restarting",()=>{V.setState({connectionPhase:"server_restarting"})})),t.push(e("server_error",n=>{V.getState().disconnect(),V.setState({connectionError:n.payload.message});const i=_s();i&&i("get_server_logs").then(o=>{Array.isArray(o)&&V.setState({serverStartupLogs:o})}).catch(()=>{})})),t.push(e("navigate_console",()=>{V.getState().setViewMode("console")})),t.push(e("update_available",n=>{V.getState().addInfoNotification(`Chroxy ${n.payload} is available.`)})),t.push(e("update_installed",n=>{V.getState().addInfoNotification(`Chroxy ${n.payload} installed. Restart to apply.`)})),()=>{t.forEach(n=>n.then(i=>i()).catch(i=>{console.warn("[useTauriEvents] listener registration/cleanup failed:",i)}))}},[])}function FU(e){const t=V(i=>G0(i.activity??{bySession:{}},(i.sessions??[]).map(o=>({sessionId:o.sessionId,cwd:o.cwd,name:o.name,worktree:o.worktree}))).total.failed),n=N.useRef(null);N.useEffect(()=>{const i=_s();if(!i)return;const o=`${e}:${t}`;o!==n.current&&(n.current=o,Promise.resolve(i("update_tray_badge",{blocked:e,failed:t})).catch(()=>{}))},[e,t])}function KU(e,t){for(const n of e)if(!(!n.requestId||!n.expiresAt||n.answered)&&!t?.[n.requestId])return{requestId:n.requestId,tool:n.tool||"Unknown"};return null}function WU(e){const{storeMessages:t,resolvedPermissions:n,sendPermissionResponse:i,activeSessionProvider:o,availableProviders:d,connected:h}=e,l=N.useMemo(()=>KU(t,n),[t,n]),u=t1(o,d),f=N.useRef({primary:l,providerSupportsRules:u,connected:h,sendPermissionResponse:i});f.current={primary:l,providerSupportsRules:u,connected:h,sendPermissionResponse:i};const v=N.useRef(null);N.useEffect(()=>{v.current=null},[l?.requestId]),N.useEffect(()=>{const g=w=>{const{primary:E,providerSupportsRules:x,connected:m,sendPermissionResponse:y}=f.current;if(!E||!m||v.current===E.requestId)return;const b=cf(E.tool)&&x,_=w==="allowSession"&&!b?"allow":w;v.current=E.requestId,y(E.requestId,_)},S=w=>{const E=w.target?.tagName;if(!(E==="INPUT"||E==="TEXTAREA"||E==="SELECT")){if(w.key.toLowerCase()==="y"&&(w.metaKey||w.ctrlKey)){if(!f.current.primary)return;if(w.preventDefault(),w.shiftKey){const x=f.current.primary;x&&cf(x.tool)&&f.current.providerSupportsRules&&g("allowSession")}else g("allow")}else if(w.key==="Escape"){if(!f.current.primary||document.querySelector("[data-modal-overlay]"))return;g("deny")}}};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[])}const GU=[{event:"menu://new-session",prop:"onNewSession"},{event:"menu://connect-to-server",prop:"onConnectToServer"},{event:"menu://disconnect",prop:"onDisconnect"},{event:"menu://view-toggle-sidebar",prop:"onToggleSidebar"},{event:"menu://view-toggle-plan-mode",prop:"onTogglePlanMode"},{event:"menu://view-show-qr",prop:"onShowQr"},{event:"menu://view-reload",prop:"onReload"},{event:"menu://tunnel-settings",prop:"onTunnelSettings"},{event:"menu://preferences",prop:"onPreferences"}];function VU(e){const{onNewSession:t,onConnectToServer:n,onDisconnect:i,onToggleSidebar:o,onTogglePlanMode:d,onShowQr:h,onReload:l,onTunnelSettings:u,onPreferences:f}=e;N.useEffect(()=>{const v=pg();if(!v)return;const g=[],S={onNewSession:t,onConnectToServer:n,onDisconnect:i,onToggleSidebar:o,onTogglePlanMode:d,onShowQr:h,onReload:l,onTunnelSettings:u,onPreferences:f};for(const{event:w,prop:E}of GU){const x=S[E];g.push(v(w,()=>{x?.()}))}return()=>{g.forEach(w=>w.then(E=>E()).catch(()=>{}))}},[t,n,i,o,d,h,l,u,f])}function YU({onNewSession:e,onShowQr:t,openSettings:n,setSidebarOpen:i,setPermissionMode:o}){const d=N.useCallback(()=>{n()},[n]),h=N.useCallback(()=>{V.getState().disconnect()},[]),l=N.useCallback(()=>{i(g=>!g)},[i]),u=N.useCallback(()=>{const g=V.getState();g.permissionMode==="plan"?o(g.previousPermissionMode||"approve"):o("plan")},[o]),f=N.useCallback(()=>{window.location.reload()},[]),v=N.useCallback(()=>{n()},[n]);VU({onNewSession:e,onConnectToServer:d,onDisconnect:h,onToggleSidebar:l,onTogglePlanMode:u,onShowQr:t,onReload:f,onTunnelSettings:v,onPreferences:v})}async function to(e,t){const n=_s();if(!n)return null;try{return await n(e,t)}catch{return null}}async function k1(){return to("get_server_info")}async function C1(){await to("start_server")}async function ZU(){await to("stop_server")}async function Gd(){await to("restart_server")}async function Dm(){return to("get_tunnel_mode")}async function E1(e){const t=_s();t&&await t("set_tunnel_mode",{mode:e})}async function N1(){return to("get_expose_on_lan")}async function j1(e){if(!hs())return;const t=_s();if(!t)throw new Error("Tauri invoke is unavailable");await t("set_expose_on_lan",{expose:e})}async function A1(){return to("get_summon_hotkey")}async function Lm(e){if(!hs())return;const t=_s();if(!t)throw new Error("Tauri invoke is unavailable");await t("set_summon_hotkey",{accelerator:e})}async function R1(){if(!hs())return null;const e=_s();if(!e)throw new Error("Tauri invoke is unavailable");return await e("get_allow_auto_permission_mode",void 0)}async function T1(e){if(!hs())return;const t=_s();if(!t)throw new Error("Tauri invoke is unavailable");await t("set_allow_auto_permission_mode",{value:e})}async function I1(){if(!hs())return null;const e=_s();if(!e)throw new Error("Tauri invoke is unavailable");return await e("private_no_it_all_status",void 0)}async function M1(){if(!hs())return null;const e=_s();if(!e)throw new Error("Tauri invoke is unavailable");return await e("launch_private_no_it_all",void 0)}async function D1(e){if(!hs())return;const t=_s();if(!t)throw new Error("Tauri invoke is unavailable");await t("reveal_in_finder",{path:e})}const XU=Object.freeze(Object.defineProperty({__proto__:null,getAllowAutoPermissionMode:R1,getExposeOnLan:N1,getPrivateNoItAllStatus:I1,getServerInfo:k1,getSummonHotkey:A1,getTunnelMode:Dm,launchPrivateNoItAll:M1,restartServer:Gd,revealInFinder:D1,setAllowAutoPermissionMode:T1,setExposeOnLan:j1,setSummonHotkey:Lm,setTunnelMode:E1,startServer:C1,stopServer:ZU},Symbol.toStringTag,{value:"Module"}));function QU(e){const t=N.useRef(new Set);N.useEffect(()=>{if(typeof Notification>"u"||Notification.permission!=="granted")return;const n=new Set(e.map(i=>i.requestId));for(const i of t.current)n.has(i)||t.current.delete(i);for(const i of e)i.answered||i.expiresAt<=Date.now()||t.current.has(i.requestId)||document.hasFocus()||(t.current.add(i.requestId),new Notification("Chroxy: Permission Requested",{body:i.description,tag:`chroxy-perm-${i.requestId}`}))},[e])}const JU=3e3,e9=120;let sm=null;function t9(){if(typeof window>"u")return null;const e=window.AudioContext||window.webkitAudioContext;if(!e)return null;if(sm===null)try{sm=new e}catch{return null}return sm}function n9(){const e=t9();if(e)try{e.state==="suspended"&&e.resume().catch(()=>{});const t=e.currentTime,n=e.createGain();n.connect(e.destination),n.gain.setValueAtTime(1e-4,t),n.gain.exponentialRampToValueAtTime(.15,t+.01);const i=e9/1e3,o=[880,1318.51],d=o.map((l,u)=>{const f=e.createOscillator();return f.type="sine",f.frequency.setValueAtTime(l,t+u*i),f.connect(n),f.start(t+u*i),f.stop(t+(u+1)*i),f});n.gain.setValueAtTime(.15,t+o.length*i-.02),n.gain.exponentialRampToValueAtTime(1e-4,t+o.length*i);const h=d[d.length-1];h&&(h.onended=()=>{for(const l of d)try{l.disconnect()}catch{}try{n.disconnect()}catch{}})}catch{}}function s9(e,t){const{enabled:n}=t,i=N.useRef(new Set),o=N.useRef(0);N.useEffect(()=>{const d=new Set(e.map(u=>u.requestId));for(const u of i.current)d.has(u)||i.current.delete(u);if(!n)return;const h=Date.now();let l=!1;for(const u of e)u.answered||u.expiresAt<=h||i.current.has(u.requestId)||(i.current.add(u.requestId),l=!0);l&&(h-o.current<JU||(o.current=h,n9()))},[e,n])}async function i9(){const e=_s();if(!e)return null;const t=await e("read_clipboard_image");return t?{base64:t,mediaType:"image/png",name:`clipboard-${Date.now()}.png`}:null}function r9(e){const{shortcutRegistry:t,sessions:n,activeSessionId:i,viewMode:o,setViewMode:d,setSplitMode:h,terminalOnly:l,setPaletteOpen:u,setSidebarOpen:f,setSettingsOpen:v,openSettings:g,setShowCreateSession:S,setShortcutHelpOpen:w,handleSwitchSession:E,handleCloseSession:x,handleCopyTranscript:m,sendInterrupt:y,setPermissionMode:b,appendImageAttachments:_,openFilePalette:k,openSymbolSearch:j,openCodeSearch:T,showQr:D}=e;N.useEffect(()=>{const I=L=>{const q=L.target instanceof HTMLElement?L.target:null;if(L.key==="Backspace"&&(!q||!["INPUT","TEXTAREA"].includes(q.tagName)&&!q.isContentEditable)){L.preventDefault();return}if(hs()&&ma()&&L.ctrlKey&&!L.metaKey&&!L.altKey&&!L.shiftKey&&(L.key==="v"||L.key==="V")){L.preventDefault(),(async()=>{try{const Q=await i9();if(!Q){V.getState().addInfoNotification("No image on clipboard");return}const{accepted:F,rejected:J}=await yz(Q.base64,Q.mediaType,Q.name);F?_([F]):J&&V.getState().addInfoNotification(J)}catch(Q){V.getState().addInfoNotification(`Failed to read clipboard image: ${Q instanceof Error?Q.message:String(Q)}`)}})();return}const H=t.matchEvent(L,"global");if(H){if(H.startsWith("session.switch.")){const Q=parseInt(H.slice(15),10)-1,F=n[Q];F&&(L.preventDefault(),E(F.sessionId));return}if(H==="session.close"){i&&n.length>1&&(L.preventDefault(),x(i));return}if(H==="help.toggle"){const Q=document.querySelectorAll("[data-modal-overlay]"),F=Q.length===1&&Q[0]?.classList.contains("shortcut-help-overlay");(Q.length===0||F)&&(L.preventDefault(),w(J=>!J));return}switch(L.preventDefault(),H){case"palette.toggle":case"palette.toggle.vscode":u(Q=>!Q);break;case"file.openPalette":k?.();break;case"search.inProject":T?.();break;case"symbol.search":j?.();break;case"sidebar.toggle":f(Q=>!Q);break;case"settings.open":g?g():v(Q=>!Q);break;case"device.pairQr":D?.();break;case"session.new":S(!0);break;case"view.toggleChatTerminal":if(l)break;d(o==="chat"?"terminal":"chat");break;case"view.cycleSplit":if(l)break;h(Q=>{const F=Q===null?"horizontal":Q==="horizontal"?"vertical":null;return rf(F),F});break;case"session.copyTranscript":m();break;case"session.interrupt":y();break;case"session.prev":case"session.next":{const Q=n.findIndex(J=>J.sessionId===i);if(Q<0)break;const F=H==="session.prev"?(Q-1+n.length)%n.length:(Q+1)%n.length;E(n[F].sessionId);break}case"session.togglePlanMode":{const Q=V.getState(),F=Q.permissionMode;b(F==="plan"?Q.previousPermissionMode||"approve":"plan");break}}return}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[n,i,E,x,o,d,l,y,m,t,_,b,h,u,f,v,g,S,w])}const im=200;function a9({isOpen:e,onClose:t}){const n=V(y=>y.fetchFileList),i=V(y=>y.filePickerFiles),o=V(y=>y.openFileInBrowser),[d,h]=N.useState(""),[l,u]=N.useState(0),f=N.useRef(null),v=N.useRef(null);N.useEffect(()=>{if(!e)return;n(),h(""),u(0);const y=window.setTimeout(()=>f.current?.focus(),0);return()=>window.clearTimeout(y)},[e,n]);const g=N.useMemo(()=>{if(!i)return[];if(!d)return i;const y=d.toLowerCase();return i.filter(b=>b.path.toLowerCase().includes(y))},[i,d]);N.useEffect(()=>{u(y=>g.length===0?0:Math.min(y,g.length-1))},[g.length]),N.useEffect(()=>{v.current?.querySelectorAll('[role="option"]')?.[l]?.scrollIntoView?.({block:"nearest"})},[l]);const S=N.useCallback(y=>{const b=g[y];b&&(o(b.path),t())},[g,o,t]),w=N.useCallback(y=>{y.key==="Escape"?(y.preventDefault(),t()):y.key==="ArrowDown"?(y.preventDefault(),u(b=>Math.min(b+1,g.length-1))):y.key==="ArrowUp"?(y.preventDefault(),u(b=>Math.max(b-1,0))):y.key==="Enter"&&(y.preventDefault(),S(l))},[g.length,l,S,t]);if(!e)return null;const E=g.length>im?g.length-im:0,x=E>0?g.slice(0,im):g,m=i===null;return r.jsx("div",{className:"file-open-palette-overlay","data-modal-overlay":!0,"data-testid":"file-open-palette",onKeyDown:w,onMouseDown:y=>{y.target===y.currentTarget&&t()},children:r.jsxs("div",{className:"file-open-palette",role:"dialog","aria-label":"Go to file",children:[r.jsx("input",{ref:f,className:"file-open-palette-input",type:"text",placeholder:"Go to file…",value:d,onChange:y=>{h(y.target.value),u(0)},"data-testid":"file-open-palette-input","aria-label":"Go to file"}),r.jsxs("div",{ref:v,className:"file-open-palette-list",role:"listbox","aria-label":"Files",children:[m&&r.jsx("div",{className:"file-open-palette-status",children:"Loading files…"}),!m&&g.length===0&&r.jsx("div",{className:"file-open-palette-status","data-testid":"file-open-palette-empty",children:"No files found"}),x.map((y,b)=>r.jsx("div",{role:"option","aria-selected":b===l,className:`file-open-palette-item${b===l?" selected":""}`,"data-testid":`file-open-item-${y.path}`,onMouseEnter:()=>u(b),onMouseDown:_=>{_.preventDefault(),S(b)},children:r.jsx("span",{className:"file-open-palette-path",children:y.path})},y.path)),E>0&&r.jsxs("div",{className:"file-open-palette-status",children:[E," more…"]})]})]})})}const Cc=200,o9={function:"ƒ",method:"ƒ",class:"C",interface:"I",type:"T",enum:"E",const:"k",variable:"v"};function l9({isOpen:e,onClose:t}){const n=V(_=>_.requestWorkspaceSymbols),i=V(_=>_.workspaceSymbols),o=V(_=>_.workspaceSymbolsLoading),d=V(_=>_.openFileInBrowser),[h,l]=N.useState(""),[u,f]=N.useState(0),v=N.useRef(null),g=N.useRef(null);N.useEffect(()=>{if(!e)return;n(),l(""),f(0);const _=window.setTimeout(()=>v.current?.focus(),0);return()=>window.clearTimeout(_)},[e,n]);const S=i?.symbols??null,w=N.useMemo(()=>{if(!S)return[];if(!h)return S;const _=h.toLowerCase();return S.filter(k=>k.name.toLowerCase().includes(_))},[S,h]);N.useEffect(()=>{f(_=>w.length===0?0:Math.min(_,Math.min(w.length,Cc)-1))},[w.length]),N.useEffect(()=>{g.current?.querySelectorAll('[role="option"]')?.[u]?.scrollIntoView?.({block:"nearest"})},[u]);const E=N.useCallback(_=>{const k=w[_];k&&(d(k.file,k.line),t())},[w,d,t]),x=N.useCallback(_=>{_.key==="Escape"?(_.preventDefault(),t()):_.key==="ArrowDown"?(_.preventDefault(),f(k=>Math.min(k+1,Math.min(w.length,Cc)-1))):_.key==="ArrowUp"?(_.preventDefault(),f(k=>Math.max(k-1,0))):_.key==="Enter"&&(_.preventDefault(),E(u))},[w.length,u,E,t]);if(!e)return null;const m=w.length>Cc?w.length-Cc:0,y=m>0?w.slice(0,Cc):w,b=o||S===null;return r.jsx("div",{className:"file-open-palette-overlay","data-modal-overlay":!0,"data-testid":"symbol-search-palette",onKeyDown:x,onMouseDown:_=>{_.target===_.currentTarget&&t()},children:r.jsxs("div",{className:"file-open-palette",role:"dialog","aria-label":"Search symbols",children:[r.jsx("input",{ref:v,className:"file-open-palette-input",type:"text",placeholder:"Search symbols…",value:h,onChange:_=>{l(_.target.value),f(0)},"data-testid":"symbol-search-input","aria-label":"Search symbols"}),r.jsxs("div",{ref:g,className:"file-open-palette-list",role:"listbox","aria-label":"Symbols",children:[b&&r.jsx("div",{className:"file-open-palette-status",children:"Indexing symbols…"}),!b&&w.length===0&&r.jsx("div",{className:"file-open-palette-status","data-testid":"symbol-search-empty",children:"No symbols"}),y.map((_,k)=>r.jsxs("div",{role:"option","aria-selected":k===u,className:`file-open-palette-item${k===u?" selected":""}`,"data-testid":`symbol-search-item-${_.name}`,onMouseEnter:()=>f(k),onMouseDown:j=>{j.preventDefault(),E(k)},children:[r.jsx("span",{className:"symbol-item-icon","aria-hidden":"true",children:o9[_.kind]??"•"}),r.jsx("span",{className:"file-open-palette-path",children:_.name}),r.jsxs("span",{className:"symbol-item-line",children:[_.file.split("/").pop(),":",_.line]})]},`${_.file}:${_.line}:${_.name}:${k}`)),m>0&&r.jsxs("div",{className:"file-open-palette-status",children:[m," more…"]})]})]})})}const Ec=200,c9=200,Go=2;function u9({isOpen:e,onClose:t}){const n=V(j=>j.requestSearchContent),i=V(j=>j.codeSearchResults),o=V(j=>j.codeSearchLoading),d=V(j=>j.openFileInBrowser),[h,l]=N.useState(""),[u,f]=N.useState(0),v=N.useRef(null),g=N.useRef(null),S=N.useRef(null);N.useEffect(()=>{if(!e)return;l(""),f(0);const j=window.setTimeout(()=>v.current?.focus(),0);return()=>window.clearTimeout(j)},[e]),N.useEffect(()=>{if(!e)return;S.current&&window.clearTimeout(S.current);const j=h.trim();if(!(j.length<Go))return S.current=window.setTimeout(()=>n(j),c9),()=>{S.current&&window.clearTimeout(S.current)}},[h,e,n]);const w=h.trim(),E=!!i&&i.query===w,x=N.useMemo(()=>w.length<Go||!E?[]:i.results,[i,E,w]);N.useEffect(()=>{f(j=>x.length===0?0:Math.min(j,Math.min(x.length,Ec)-1))},[x.length]),N.useEffect(()=>{g.current?.querySelectorAll('[role="option"]')?.[u]?.scrollIntoView?.({block:"nearest"})},[u]);const m=N.useCallback(j=>{const T=x[j];T&&(d(T.file,T.line),t())},[x,d,t]),y=N.useCallback(j=>{j.key==="Escape"?(j.preventDefault(),t()):j.key==="ArrowDown"?(j.preventDefault(),f(T=>Math.min(T+1,Math.min(x.length,Ec)-1))):j.key==="ArrowUp"?(j.preventDefault(),f(T=>Math.max(T-1,0))):j.key==="Enter"&&(j.preventDefault(),m(u))},[x.length,u,m,t]);if(!e)return null;const b=x.length>Ec?x.length-Ec:0,_=b>0?x.slice(0,Ec):x,k=w.length>=Go&&(o||!E);return r.jsx("div",{className:"file-open-palette-overlay","data-modal-overlay":!0,"data-testid":"code-search-palette",onKeyDown:y,onMouseDown:j=>{j.target===j.currentTarget&&t()},children:r.jsxs("div",{className:"file-open-palette",role:"dialog","aria-label":"Search in files",children:[r.jsx("input",{ref:v,className:"file-open-palette-input",type:"text",placeholder:"Search in files…",value:h,onChange:j=>{l(j.target.value),f(0)},"data-testid":"code-search-input","aria-label":"Search in files"}),r.jsxs("div",{ref:g,className:"file-open-palette-list",role:"listbox","aria-label":"Search results",children:[w.length<Go&&r.jsx("div",{className:"file-open-palette-status","data-testid":"code-search-hint",children:"Type 2+ characters to search"}),w.length>=Go&&k&&r.jsx("div",{className:"file-open-palette-status",children:"Searching…"}),w.length>=Go&&!k&&x.length===0&&r.jsx("div",{className:"file-open-palette-status","data-testid":"code-search-empty",children:"No matches"}),_.map((j,T)=>r.jsxs("div",{role:"option","aria-selected":T===u,className:`file-open-palette-item${T===u?" selected":""}`,"data-testid":`code-search-item-${T}`,onMouseEnter:()=>f(T),onMouseDown:D=>{D.preventDefault(),m(T)},children:[r.jsx("span",{className:"code-search-preview",title:j.text,children:j.text.trim()||" "}),r.jsxs("span",{className:"symbol-item-line",children:[j.file.split("/").pop(),":",j.line]})]},`${j.file}:${j.line}:${j.column}:${T}`)),b>0&&r.jsxs("div",{className:"file-open-palette-status",children:[b," more…"]}),E&&i.truncated&&_.length>0&&r.jsx("div",{className:"file-open-palette-status","data-testid":"code-search-truncated",children:"Results truncated — refine your search"})]})]})})}const Nc=200;function d9({isOpen:e,onClose:t}){const n=V(m=>m.referencesResult),i=V(m=>m.referencesLoading),o=V(m=>m.referencesSymbol),d=V(m=>m.openFileInBrowser),[h,l]=N.useState(0),u=N.useRef(null);N.useEffect(()=>{if(!e)return;l(0);const m=window.setTimeout(()=>u.current?.focus(),0);return()=>window.clearTimeout(m)},[e]);const f=!!n&&n.symbol===o,v=N.useMemo(()=>f?n.results:[],[n,f]);N.useEffect(()=>{l(m=>v.length===0?0:Math.min(m,Math.min(v.length,Nc)-1))},[v.length]),N.useEffect(()=>{u.current?.querySelectorAll('[role="option"]')?.[h]?.scrollIntoView?.({block:"nearest"})},[h]);const g=N.useCallback(m=>{const y=v[m];y&&(d(y.file,y.line),t())},[v,d,t]),S=N.useCallback(m=>{m.key==="Escape"?(m.preventDefault(),t()):m.key==="ArrowDown"?(m.preventDefault(),l(y=>Math.min(y+1,Math.min(v.length,Nc)-1))):m.key==="ArrowUp"?(m.preventDefault(),l(y=>Math.max(y-1,0))):m.key==="Enter"&&(m.preventDefault(),g(h))},[v.length,h,g,t]);if(!e)return null;const w=v.length>Nc?v.length-Nc:0,E=w>0?v.slice(0,Nc):v,x=i||!f;return r.jsx("div",{className:"file-open-palette-overlay","data-modal-overlay":!0,"data-testid":"references-palette",onMouseDown:m=>{m.target===m.currentTarget&&t()},children:r.jsxs("div",{className:"file-open-palette",role:"dialog","aria-label":"References",children:[r.jsxs("div",{className:"file-open-palette-header","data-testid":"references-header",children:["References to ",r.jsx("code",{children:o}),f&&!x&&r.jsxs("span",{className:"references-count",children:[" · ",v.length]})]}),r.jsxs("div",{ref:u,className:"file-open-palette-list",role:"listbox","aria-label":"References",tabIndex:0,onKeyDown:S,children:[x&&r.jsx("div",{className:"file-open-palette-status",children:"Searching…"}),!x&&v.length===0&&r.jsx("div",{className:"file-open-palette-status","data-testid":"references-empty",children:"No references found"}),!x&&E.map((m,y)=>r.jsxs("div",{role:"option","aria-selected":y===h,className:`file-open-palette-item${y===h?" selected":""}`,"data-testid":`references-item-${y}`,onMouseEnter:()=>l(y),onMouseDown:b=>{b.preventDefault(),g(y)},children:[r.jsx("span",{className:"code-search-preview",title:m.text,children:m.text.trim()||" "}),r.jsxs("span",{className:"symbol-item-line",children:[m.file.split("/").pop(),":",m.line]})]},`${m.file}:${m.line}:${m.column}:${y}`)),w>0&&r.jsxs("div",{className:"file-open-palette-status",children:[w," more…"]}),f&&n.truncated&&E.length>0&&r.jsx("div",{className:"file-open-palette-status","data-testid":"references-truncated",children:"Results truncated"})]})]})})}function f9(e){const{storeMessages:t,streamingMessageId:n}=e,i=N.useMemo(()=>RN(t,n),[t,n]),{chatMessages:o,chatToolGroupPayloads:d,chatTailMessageId:h,storeMsgMap:l,stalledPromptIds:u}=i;return{chatMessages:o,chatToolGroupPayloads:d,chatTailMessageId:h,storeMsgMap:l,stalledPromptIds:u}}const h9="modulepreload",p9=function(e){return"/dashboard/"+e},qS={},HS=function(t,n,i){let o=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(v=>Promise.resolve(v).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const h=document.querySelector("meta[property=csp-nonce]"),l=h?.nonce||h?.getAttribute("nonce");o=u(n.map(f=>{if(f=p9(f),f in qS)return;qS[f]=!0;const v=f.endsWith(".css"),g=v?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${g}`))return;const S=document.createElement("link");if(S.rel=v?"stylesheet":h9,v||(S.as="script"),S.crossOrigin="",S.href=f,l&&S.setAttribute("nonce",l),document.head.appendChild(S),v)return new Promise((w,E)=>{S.addEventListener("load",w),S.addEventListener("error",()=>E(new Error(`Unable to preload CSS for ${f}`)))})}))}function d(h){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=h,window.dispatchEvent(l),!l.defaultPrevented)throw h}return o.then(h=>{for(const l of h||[])l.status==="rejected"&&d(l.reason);return t().catch(d)})};function m9(e){const[t,n]=N.useState(!0);return N.useEffect(()=>{if(!e){n(!0);return}let i=!1,o=null;async function d(){try{const{getServerInfo:h}=await HS(async()=>{const{getServerInfo:u}=await Promise.resolve().then(()=>XU);return{getServerInfo:u}},void 0),l=await h();if(!l||l.tunnelMode==="none"){n(!0);return}}catch{}try{const{getAuthToken:h}=await HS(async()=>{const{getAuthToken:f}=await Promise.resolve().then(()=>VB);return{getAuthToken:f}},void 0),l=h();if(!l)return;if((await fetch("/connect",{headers:{Authorization:`Bearer ${l}`}})).ok){i||n(!0);return}}catch{}i||(n(!1),o=setTimeout(d,3e3))}return d(),()=>{i=!0,o&&clearTimeout(o)}},[e]),t}function g9(e,t){const[n,i]=N.useState(!1),[o,d]=N.useState(null),[h,l]=N.useState(!1),[u,f]=N.useState(null),[v,g]=N.useState(null),S=N.useCallback(async b=>{i(!0),l(!0),f(null),d(null),g(null);const _=li();if(!_){l(!1),f("No auth token available");return}const k=b==="/qr";try{const[j,T]=await Promise.all([fetch(b,{headers:{Authorization:`Bearer ${_}`}}),k?fetch("/pairing-code",{headers:{Authorization:`Bearer ${_}`}}).catch(()=>null):Promise.resolve(null)]);if(j.ok){const D=await j.text();d(D),f(null)}else{const D=await j.json().catch(()=>({error:"Request failed"}));f(D.error||`HTTP ${j.status}`),d(null)}if(T&&T.ok){const D=await T.json().catch(()=>null);D?.code&&g(String(D.code))}}catch(j){f(j instanceof Error?j.message:"Failed to fetch QR code"),d(null)}finally{l(!1)}},[]),w=N.useCallback(()=>S("/qr"),[S]),E=N.useCallback(async()=>{const b=li();if(!b)return{posted:!1,reason:"no_token"};try{const _=await fetch("/pair-discord",{method:"POST",headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}}),k=await _.json().catch(()=>null);return _.ok&&k?.posted?{posted:!0,expiresInSeconds:k.expiresInSeconds}:{posted:!1,reason:k?.reason||k?.error||`http_${_.status}`}}catch{return{posted:!1,reason:"post_failed"}}},[]),[x,m]=N.useState("link"),y=N.useCallback(()=>{e&&(m("share"),S(`/qr/session/${encodeURIComponent(e)}`))},[e,S]);return N.useEffect(()=>{n&&x==="share"||n||m("link")},[n,x]),N.useEffect(()=>{t!==0&&n&&w()},[t]),{qrModalOpen:n,setQrModalOpen:i,qrSvg:o,qrLoading:h,qrError:u,qrPairingCode:v,qrShareMode:x,handleShowQr:w,handleShareSession:y,handlePostPairLinkToDiscord:E}}function v9(){const[e,t]=N.useState(()=>K_()),[n,i]=N.useState(()=>U_()),[o,d]=N.useState(()=>q_()),h=V(v=>v.activeServerId);N.useEffect(()=>{t(K_())},[h]),N.useEffect(()=>{i(U_()),d(q_())},[h]);const l=N.useCallback(v=>{t(v),jP(v)},[]),u=N.useCallback(v=>{i(v),_P(v)},[]),f=N.useCallback((v,g)=>{d(S=>{const w={...S,[v]:g};return SP(w),w})},[]);return{tabOrder:e,sidebarRepoOrder:n,sidebarSessionOrder:o,handleReorderTabs:l,handleReorderRepos:u,handleReorderSidebarSessions:f}}function y9(){const[e,t]=N.useState(()=>new URLSearchParams(window.location.search).get("settings")==="1"),[n,i]=N.useState(!1),[o,d]=N.useState(()=>wP()),[h,l]=N.useState(!1),[u,f]=N.useState(!1),v=N.useCallback(()=>{l(!0),f(!0),d(null),rf(null)},[]),[g,S]=N.useState(0),[w,E]=N.useState(void 0),x=N.useCallback(()=>{t(!1),u?S(y=>y+1):E("settings"),v()},[u,v]);N.useEffect(()=>{u&&w!==void 0&&E(void 0)},[u,w]);const m=N.useCallback(()=>{l(!1),f(!1)},[]);return{controlRoomOpen:h,controlRoomActive:u,setControlRoomActive:f,settingsRedirectNonce:g,controlRoomInitialTab:w,settingsOpen:e,setSettingsOpen:t,shortcutHelpOpen:n,setShortcutHelpOpen:i,splitMode:o,setSplitMode:d,openControlRoom:v,openSettings:x,closeControlRoom:m}}const b9=new Set(["allow","allowAlways","deny"]);function _9(e){const t=[],n=new Map,i=[],o=new Map;let d="",h=null;for(const l of e){const u=l.payload||{};if(l.type==="tool_start"){const f=typeof u.toolUseId=="string"?u.toolUseId:null;if(!f)continue;const v=typeof u.tool=="string"?u.tool:"tool",g=typeof u.serverName=="string"?u.serverName:void 0,S=u.input&&typeof u.input=="object"||typeof u.input=="string"?u.input:void 0,w=n.get(f);if(w){w.toolName=v,w.input=S??w.input,w.serverName=g??w.serverName;continue}const E={toolUseId:f,toolName:v,input:S,serverName:g,hasResult:!1};n.set(f,E),t.push(E)}else if(l.type==="tool_input_delta"){const f=typeof u.toolUseId=="string"?u.toolUseId:null,v=typeof u.partialJson=="string"?u.partialJson:null;if(!f||v===null)continue;const g=n.get(f);if(!g)continue;g.inputPartial=(g.inputPartial||"")+v}else if(l.type==="tool_result"){const f=typeof u.toolUseId=="string"?u.toolUseId:null,v=typeof u.result=="string"?u.result:"";if(!f)continue;let g=n.get(f);g||(g={toolUseId:f,toolName:"tool",hasResult:!1},n.set(f,g),t.push(g)),g.result=v,g.hasResult=!0}else if(l.type==="stream_delta"){const f=typeof u.delta=="string"?u.delta:null;if(f){const v=typeof u.messageId=="string"?u.messageId:null;v&&h&&v!==h&&d.length>0&&(d+=`
|
|
98
|
-
|
|
99
|
-
`),d+=f,v&&(h=v)}}else if(l.type==="permission_request"){const f=typeof u.requestId=="string"?u.requestId:null;if(!f)continue;const v=typeof u.tool=="string"?u.tool:"tool",g=typeof u.description=="string"?u.description:"",S=o.get(f);if(S){S.tool=v,S.description=g||S.description;continue}const w={requestId:f,tool:v,description:g};o.set(f,w),i.push(w)}else if(l.type==="permission_resolved"){const f=typeof u.requestId=="string"?u.requestId:null;if(!f)continue;const v=b9.has(u.decision)?u.decision:"denied";let g=o.get(f);g||(g={requestId:f,tool:"tool",description:""},o.set(f,g),i.push(g)),g.serverDecision=v}}return{tools:t,assistantText:d,permissions:i}}function L1({events:e,parentToolUseId:t}){const n=N.useMemo(()=>_9(e),[e]),[i,o]=N.useState({}),d=u=>o(f=>({...f,[u]:!f[u]})),h=V(u=>u.resolvedPermissions),l=V(u=>u.sendPermissionResponse);return n.tools.length===0&&!n.assistantText&&n.permissions.length===0?null:r.jsxs("div",{className:"child-agent-event-list","data-testid":`child-agent-events-${t}`,children:[r.jsx("div",{className:"child-agent-event-list-header","data-testid":"child-agent-events-header",children:"Subagent progress"}),n.tools.map(u=>{const f=!!i[u.toolUseId],v=Ym(u.input)||(u.inputPartial?Y0(u.inputPartial):"")||(u.inputPartial?u.inputPartial.slice(0,100):"");return r.jsxs("div",{className:`child-agent-tool${f?" expanded":""}`,"data-testid":`child-agent-tool-${u.toolUseId}`,role:"button",tabIndex:0,"aria-expanded":f,onClick:g=>{g.stopPropagation(),d(u.toolUseId)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),g.stopPropagation(),d(u.toolUseId))},children:[!u.hasResult&&r.jsx("span",{className:"child-agent-tool-pulse","data-testid":`child-agent-tool-pulse-${u.toolUseId}`,"aria-hidden":"true"}),r.jsx("span",{className:"child-agent-tool-name",children:fa(u.toolName,u.serverName)}),v&&r.jsx("span",{className:"child-agent-tool-input","data-testid":`child-agent-tool-input-${u.toolUseId}`,style:{color:"#666"},children:v}),f&&u.result!==void 0&&r.jsx("div",{className:"child-agent-tool-result","data-testid":`child-agent-tool-result-${u.toolUseId}`,onClick:g=>g.stopPropagation(),children:r.jsx("pre",{children:u.result})})]},u.toolUseId)}),n.permissions.map(u=>{const v=h?.[u.requestId]??null??u.serverDecision??null,g=v==="deny"||v==="denied"?"Denied":v?"Allowed":null;return r.jsxs("div",{className:`child-agent-permission${v?" answered":""}`,"data-testid":`child-agent-permission-${u.requestId}`,onClick:S=>S.stopPropagation(),role:"presentation",children:[r.jsxs("div",{className:"child-agent-permission-desc",children:[r.jsx("span",{className:"child-agent-permission-tool",children:u.tool}),u.description?`: ${u.description}`:": Permission requested"]}),v?r.jsx("div",{className:"child-agent-permission-answer","data-testid":`child-agent-permission-answer-${u.requestId}`,children:g}):r.jsxs("div",{className:"child-agent-permission-buttons",children:[r.jsx("button",{className:"btn-allow",type:"button","data-testid":`child-agent-permission-allow-${u.requestId}`,"aria-label":`Allow ${u.tool} for subagent`,onClick:S=>{S.stopPropagation(),l(u.requestId,"allow")},children:"Allow"}),r.jsx("button",{className:"btn-deny",type:"button","data-testid":`child-agent-permission-deny-${u.requestId}`,"aria-label":`Deny ${u.tool} for subagent`,onClick:S=>{S.stopPropagation(),l(u.requestId,"deny")},children:"Deny"})]})]},u.requestId)}),n.assistantText&&r.jsx("div",{className:"child-agent-stream-text","data-testid":`child-agent-stream-text-${t}`,onClick:u=>u.stopPropagation(),children:n.assistantText})]})}function S9(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function x9(e){if(!e)return"";const t=Gm(e);return t!==void 0?JSON.stringify(t,null,2):e}function w9({message:e,expanded:t,onToggle:n}){if(e.type==="thinking")return r.jsx("div",{className:"tool-group-entry tool-group-entry--thinking","data-testid":`tool-group-entry-${e.id}`,children:r.jsx("span",{className:"tool-group-entry-name",children:"Thinking"})});const i=fa(e.tool??"Tool",e.serverName),o=Z0(e.tool),d=o?"":Ym(e.toolInput),h=e.toolResult!==void 0||(e.toolResultImages?.length??0)>0,l=`tool-group-entry-marker tool-group-entry-marker--${h?"complete":"pending"}`,u=m=>{m.stopPropagation(),n(e.id)},f=m=>{(m.key==="Enter"||m.key===" "&&!m.repeat)&&(m.preventDefault(),m.stopPropagation(),n(e.id))},v=o?"":S9(e.toolInput),g=v||o?"":x9(e.toolInputPartial),S=v||g,w=!v&&g!=="",E=e.toolResult??"",x=h?"(no result)":"(no result yet)";return r.jsxs("div",{className:`tool-group-entry${t?" tool-group-entry--expanded":""}`,"data-testid":`tool-group-entry-${e.id}`,children:[r.jsxs("div",{className:"tool-group-entry-row","data-testid":`tool-group-entry-row-${e.id}`,role:"button",tabIndex:0,"aria-expanded":t,onClick:u,onKeyDown:f,children:[r.jsx("span",{className:l,"aria-hidden":"true",children:h?"✓":"›"}),r.jsx("span",{className:"tool-group-entry-name",children:i}),d&&r.jsx("span",{className:"tool-group-entry-input",children:d}),r.jsx("span",{className:"tool-group-entry-toggle","aria-hidden":"true",children:t?"▾":"▸"})]}),t&&r.jsxs("div",{className:"tool-group-entry-detail","data-testid":`tool-group-entry-detail-${e.id}`,"data-streaming":w?"true":void 0,onClick:m=>m.stopPropagation(),children:[r.jsxs("div",{className:"tool-group-entry-detail-section",children:[r.jsx("div",{className:"tool-group-entry-detail-label",children:"Input"}),r.jsx("pre",{className:"tool-group-entry-detail-content",children:S||"(no input)"})]}),r.jsxs("div",{className:"tool-group-entry-detail-section",children:[r.jsx("div",{className:"tool-group-entry-detail-label",children:"Result"}),r.jsx("pre",{className:"tool-group-entry-detail-content",children:E||x})]}),e.childAgentEvents&&e.childAgentEvents.length>0&&e.toolUseId&&r.jsxs("div",{className:"tool-group-entry-detail-section",children:[r.jsx("div",{className:"tool-group-entry-detail-label",children:"Subagent"}),r.jsx(L1,{events:e.childAgentEvents,parentToolUseId:e.toolUseId})]})]})]})}function k9({messages:e,isActive:t,isTail:n=!1}){const i=`group:${e[0]?.id??"empty"}`,o=N.useContext(gg),{initial:d,persist:h}=p1(i,t||n),[l,u]=N.useState(d),f=N.useRef(t),v=N.useRef(n);t&&(v.current=n),N.useEffect(()=>{f.current&&!t&&(v.current||(u(!1),h(!1))),!f.current&&t&&(u(!0),h(!0)),f.current=t},[t,h]);const[g,S]=N.useState(()=>{const _=new Set;for(const k of e)o.get(`entry:${k.id}`)&&_.add(k.id);return _}),w=_=>{S(k=>{const j=new Set(k);return j.has(_)?(j.delete(_),o.set(`entry:${_}`,!1)):(j.add(_),o.set(`entry:${_}`,!0)),j})},E=e.filter(_=>_.type==="tool_use").length,x=jN(NN(e)),m=t?`Working... (${E} tool${E!==1?"s":""})`:`${E} tool${E!==1?"s":""} used`,y=x?`${m} — ${x}`:m,b=()=>u(_=>{const k=!_;return h(k),k});return r.jsxs("div",{className:`tool-group${l?" expanded":""}${t?" active":""}`,"data-testid":"tool-group","aria-expanded":l,children:[r.jsxs("button",{type:"button",className:"tool-group-header","data-testid":"tool-group-header","aria-expanded":l,onClick:b,children:[t&&r.jsx("span",{className:"tool-group-pulse","aria-hidden":"true"}),r.jsx("span",{className:"tool-group-summary",children:y}),r.jsx("span",{className:"tool-group-chevron","aria-hidden":"true",children:l?"▾":"▸"})]}),l&&r.jsx("div",{className:"tool-group-list","data-testid":"tool-group-list",children:e.map(_=>r.jsx(w9,{message:_,expanded:g.has(_.id),onToggle:w},_.id))})]})}const C9=/^\s*\[([ x~])\]\s+(.+)\s+\(([^)]+)\)\s*$/;function E9(e){switch(e){case"x":return"completed";case"~":return"in_progress";case" ":return"pending";default:return null}}function O1(e){if(typeof e!="string"||e.length===0)return null;const t=e.split(`
|
|
100
|
-
`);if(t.length===0)return null;const n=t[0]??"";if(!/^Todo list\s*\(\d+\s+items?\)/.test(n))return null;const i=[];let o;for(let d=1;d<t.length;d++){const h=t[d]??"";if(h.trim().length===0)continue;const l=h.match(C9);if(l){const u=E9(l[1]??""),f=(l[2]??"").trim(),v=(l[3]??"").trim();if(u&&v.length>0&&f.length>0){i.push({id:v,status:u,content:f});continue}}h.includes("showing first")&&(o=h.trim())}return{header:n,items:i,truncationMarker:o}}const N9={completed:"✓",in_progress:"⋯",pending:"○"},FS={completed:"completed",in_progress:"in progress",pending:"pending"};function j9({text:e,parsed:t,onParseFail:n}){const i=t!==void 0?t:O1(e??"");return i?r.jsxs("div",{className:"todo-list","data-testid":"todo-list",children:[r.jsx("div",{className:"todo-list-header","data-testid":"todo-list-header",children:i.header}),i.items.length===0?r.jsx("div",{className:"todo-list-empty",children:"No items."}):r.jsx("ul",{className:"todo-list-items",children:i.items.map(o=>r.jsxs("li",{className:`todo-list-item todo-list-item--${o.status}`,"data-testid":`todo-list-item-${o.id}`,children:[r.jsx("span",{className:"todo-list-marker","aria-label":FS[o.status],title:FS[o.status],children:N9[o.status]}),r.jsx("span",{className:"todo-list-content",children:o.content})]},o.id))}),i.truncationMarker&&r.jsx("div",{className:"todo-list-truncated","data-testid":"todo-list-truncated",children:i.truncationMarker})]}):(n?.(),null)}function A9({toolName:e,toolUseId:t,input:n,inputPartial:i,result:o,serverName:d,isTail:h=!1,resultImages:l,childAgentEvents:u}){const{initial:f,persist:v}=p1(`tool:${t}`,h),[g,S]=N.useState(f),w=o!==void 0||(l?.length??0)>0,E=Z0(e),x=N.useMemo(()=>{if(E)return"";const L=Ym(n);if(L)return L;if(!i)return"";const q=Y0(i);return q||i.slice(0,100)},[n,i,E]),m=`tool-result-${t}`,y=g&&o&&e==="TodoWrite"?O1(o):null,[b,_]=N.useState(!1),k=N.useMemo(()=>o?o.split(`
|
|
101
|
-
`).length:0,[o]),j=!y&&k>UN,T=N.useMemo(()=>{if(!g||w||!i||E)return null;const L=Gm(i);return L!==void 0?{text:JSON.stringify(L,null,2),parsed:!0}:{text:i,parsed:!1}},[g,w,i,E]),D=()=>S(L=>{const q=!L;return v(q),q}),I=L=>{(L.key==="Enter"||L.key===" "&&!L.repeat)&&(L.preventDefault(),D())};return r.jsxs("div",{className:`tool-bubble${g?" expanded":""}`,"data-testid":`tool-bubble-${t}`,"data-tool-id":t,role:"button",tabIndex:0,"aria-expanded":g,"aria-controls":g&&o?m:void 0,onClick:D,onKeyDown:I,children:[!w&&r.jsx("span",{className:"tool-bubble-pulse","data-testid":`tool-bubble-pulse-${t}`,"aria-hidden":"true"}),r.jsx("span",{className:"tool-name",children:fa(e,d)}),x&&r.jsx("span",{className:"tool-input","data-testid":"tool-input-summary",style:{color:"#666"},children:x}),g&&o&&r.jsx("div",{className:`tool-result${j?" tool-result--unbounded":""}`,id:m,onClick:L=>L.stopPropagation(),children:y?r.jsx(j9,{parsed:y}):j&&!b?r.jsxs(r.Fragment,{children:[r.jsx("pre",{children:o.split(`
|
|
102
|
-
`).slice(0,Jb).join(`
|
|
103
|
-
`)}),r.jsxs("button",{type:"button",className:"tool-result-expand","data-testid":`tool-result-expand-${t}`,onClick:()=>_(!0),children:["Show ",k-Jb," more lines"]})]}):r.jsxs(r.Fragment,{children:[r.jsx("pre",{children:o}),j&&r.jsx("button",{type:"button",className:"tool-result-expand","data-testid":`tool-result-collapse-${t}`,onClick:()=>_(!1),children:"Show less"})]})}),g&&u&&u.length>0&&r.jsx("div",{className:"tool-bubble-child-events","data-testid":`tool-bubble-child-events-${t}`,onClick:L=>L.stopPropagation(),children:r.jsx(L1,{events:u,parentToolUseId:t})}),g&&!w&&T&&r.jsx("div",{className:"tool-input-partial","data-testid":`tool-input-partial-${t}`,"data-parsed":T.parsed?"true":"false",onClick:L=>L.stopPropagation(),children:r.jsx("pre",{children:T.text})})]})}function R9(e){switch(e){case"added":return"A";case"deleted":return"D";case"renamed":return"R";case"untracked":return"U";default:return"M"}}function P1(e){switch(e){case"added":return"diff-status-added";case"deleted":return"diff-status-deleted";case"renamed":return"diff-status-renamed";case"untracked":return"diff-status-untracked";default:return"diff-status-modified"}}function B1({file:e}){const t=e.path.includes("/")?e.path.split("/").pop():e.path,n=e.path.includes("/")?e.path.slice(0,e.path.lastIndexOf("/")+1):"";return r.jsxs("span",{className:"diff-file-path",title:e.path,children:[n&&r.jsx("span",{className:"diff-file-dir",children:n}),r.jsx("span",{className:"diff-file-name",children:t})]})}function KS({header:e}){return r.jsx("div",{className:"diff-hunk-header","data-testid":"hunk-header",children:e})}function T9({line:e}){const t=e.type==="addition"?"diff-line-add":e.type==="deletion"?"diff-line-del":"diff-line-ctx",n=e.type==="addition"?"+":e.type==="deletion"?"-":" ";return r.jsxs("div",{className:`diff-line ${t}`,"data-testid":"diff-line",children:[r.jsx("span",{className:"diff-line-prefix",children:n}),r.jsx("span",{className:"diff-line-content",children:e.content})]})}function I9({left:e,right:t}){return r.jsxs("div",{className:"diff-split-row","data-testid":"split-row",children:[r.jsx("div",{className:`diff-split-cell ${e?e.type==="deletion"?"diff-line-del":"diff-line-ctx":"diff-line-empty"}`,children:e&&r.jsx("span",{className:"diff-line-content",children:e.content})}),r.jsx("div",{className:`diff-split-cell ${t?t.type==="addition"?"diff-line-add":"diff-line-ctx":"diff-line-empty"}`,children:t&&r.jsx("span",{className:"diff-line-content",children:t.content})})]})}function M9(e){const t=[];let n=0;for(;n<e.length;){const i=e[n];if(i.type==="context")t.push({left:i,right:i}),n++;else if(i.type==="deletion"){const o=[];for(;n<e.length&&e[n].type==="deletion";)o.push(e[n]),n++;const d=[];for(;n<e.length&&e[n].type==="addition";)d.push(e[n]),n++;const h=Math.max(o.length,d.length);for(let l=0;l<h;l++)t.push({left:o[l]??null,right:d[l]??null})}else t.push({left:null,right:i}),n++}return t}function $1({hunk:e,viewMode:t,selectable:n=!1,selected:i=!1,onToggle:o}){const d=`diff-hunk${n?` diff-hunk-selectable${i?"":" diff-hunk-rejected"}`:""}`;return r.jsxs("div",{className:d,"data-testid":"diff-hunk",children:[n?r.jsxs("label",{className:"diff-hunk-toggle-row",children:[r.jsx("input",{type:"checkbox",className:"diff-hunk-toggle",checked:i,onChange:o,"data-testid":"hunk-toggle","aria-label":i?"Reject this hunk":"Accept this hunk"}),r.jsx(KS,{header:e.header})]}):r.jsx(KS,{header:e.header}),t==="unified"?e.lines.map((h,l)=>r.jsx(T9,{line:h},l)):M9(e.lines).map((h,l)=>r.jsx(I9,{left:h.left,right:h.right},l))]})}function D9({file:e,viewMode:t}){return r.jsxs("div",{className:"diff-file-view","data-testid":"diff-file-view",children:[r.jsxs("div",{className:"diff-file-header",children:[r.jsx("span",{className:`diff-status-badge ${P1(e.status)}`,children:R9(e.status)}),r.jsx(B1,{file:e}),r.jsxs("span",{className:"diff-file-stats",children:[e.additions>0&&r.jsxs("span",{className:"diff-stat-add",children:["+",e.additions]}),e.deletions>0&&r.jsxs("span",{className:"diff-stat-del",children:["-",e.deletions]})]})]}),e.hunks.length===0?r.jsx("div",{className:"diff-empty-file",children:"Binary file or no diff available"}):e.hunks.map((n,i)=>r.jsx($1,{hunk:n,viewMode:t},i))]})}function L9(){const e=V(b=>b.setDiffCallback),t=V(b=>b.requestDiff),n=V(b=>b.connectionPhase),[i,o]=N.useState([]),[d,h]=N.useState(null),[l,u]=N.useState(!0),[f,v]=N.useState("unified"),[g,S]=N.useState(null),w=N.useRef(null);N.useEffect(()=>(e(b=>{o(b.files),h(b.error),u(!1)}),()=>e(null)),[e]),N.useEffect(()=>{n==="connected"&&(u(!0),t())},[n,t]);const E=N.useCallback(()=>{u(!0),t()},[t]),x=N.useCallback(b=>{S(b);const _=document.querySelector(`[data-diff-path="${CSS.escape(b)}"]`);_&&_.scrollIntoView&&_.scrollIntoView({behavior:"smooth",block:"start"})},[]),m=i.reduce((b,_)=>b+_.additions,0),y=i.reduce((b,_)=>b+_.deletions,0);return r.jsxs("div",{className:"diff-viewer-panel","data-testid":"diff-viewer-panel",children:[r.jsxs("div",{className:"diff-toolbar",children:[r.jsxs("span",{className:"diff-toolbar-title",children:["Changes",i.length>0&&r.jsxs("span",{className:"diff-toolbar-stats",children:[" ",i.length," file",i.length!==1?"s":"",m>0&&r.jsxs("span",{className:"diff-stat-add",children:[" +",m]}),y>0&&r.jsxs("span",{className:"diff-stat-del",children:[" -",y]})]})]}),r.jsxs("div",{className:"diff-toolbar-actions",children:[r.jsx("button",{type:"button",className:`diff-view-btn${f==="unified"?" active":""}`,onClick:()=>v("unified"),children:"Unified"}),r.jsx("button",{type:"button",className:`diff-view-btn${f==="split"?" active":""}`,onClick:()=>v("split"),children:"Split"}),r.jsx("button",{type:"button",className:"diff-refresh-btn",onClick:E,title:"Refresh diff",children:"Refresh"})]})]}),r.jsxs("div",{className:"diff-body",children:[i.length>0&&r.jsx("div",{className:"diff-sidebar","data-testid":"diff-sidebar",children:i.map(b=>r.jsxs("button",{type:"button",className:`diff-sidebar-item${g===b.path?" active":""}`,onClick:()=>x(b.path),title:b.path,children:[r.jsx("span",{className:`diff-status-dot ${P1(b.status)}`}),r.jsx(B1,{file:b}),r.jsxs("span",{className:"diff-sidebar-stats",children:[b.additions>0&&r.jsxs("span",{className:"diff-stat-add",children:["+",b.additions]}),b.deletions>0&&r.jsxs("span",{className:"diff-stat-del",children:["-",b.deletions]})]})]},b.path))}),r.jsxs("div",{className:"diff-content",ref:w,children:[l&&r.jsx("div",{className:"diff-loading",children:"Loading diff..."}),!l&&d&&r.jsx("div",{className:"diff-error",children:d}),!l&&!d&&i.length===0&&r.jsx("div",{className:"diff-empty",children:"No uncommitted changes."}),!l&&!d&&i.map(b=>r.jsx("div",{"data-diff-path":b.path,children:r.jsx(D9,{file:b,viewMode:f})},b.path))]})]})]})}const z1={Write:{field:"content",base:()=>"",proposed:e=>String(e.content??"")},Edit:{field:"new_string",base:e=>String(e.old_string??""),proposed:e=>String(e.new_string??"")}};function O9(e){return Object.prototype.hasOwnProperty.call(z1,e)}function P9({tool:e,input:t,onEditedInputChange:n}){const i=z1[e],{base:o,hunks:d}=N.useMemo(()=>{if(!i)return{base:"",hunks:[]};const S=i.base(t);return{base:S,hunks:H4(S,i.proposed(t))}},[i,t]),[h,l]=N.useState(()=>new Set(d.map((S,w)=>w)));N.useEffect(()=>{l(new Set(d.map((S,w)=>w))),n(null)},[d]);function u(S){l(w=>{const E=new Set(w);E.has(S)?E.delete(S):E.add(S);const x=E.size===d.length;return n(x?null:{[i.field]:W4(o,d,E)}),E})}if(!i||d.length===0)return null;const f=d.length-h.size,v=h.size===0,g=v?`All hunks dropped — Approve writes ${e==="Write"?"an empty file":"no change"}.`:f===0?"Review the proposed change — uncheck a hunk to drop it from the write.":`${f} hunk${f===1?"":"s"} dropped — Approve writes the narrowed content.`;return r.jsxs("div",{className:"prewrite-diff-review","data-testid":"prewrite-diff-review",children:[r.jsx("div",{className:`prewrite-diff-hint${v?" prewrite-diff-hint-warn":""}`,"data-testid":"prewrite-diff-hint",children:g}),d.map((S,w)=>r.jsx($1,{hunk:S,viewMode:"unified",selectable:!0,selected:h.has(w),onToggle:()=>u(w)},w))]})}function B9(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),i=t%60;return`${n}:${i<10?"0":""}${i}`}function $9({requestId:e,tool:t,description:n,remainingMs:i,onRespond:o,sessionLabel:d}){const[h,l]=N.useState(i),u=N.useRef(null),f=N.useRef(performance.now()+i),v=N.useRef(!1),[g,S]=N.useState(!1),w=V(fe=>fe.resolvedPermissions?.[e]??null),E=V(fe=>fe.connectionPhase==="connected"),x=V(fe=>{const $=fe.activeSessionId;return $?fe.sessions.find(B=>B.sessionId===$)?.provider??null:null}),m=V(fe=>fe.availableProviders),y=t1(x,m),b=V(fe=>!!fe.serverCapabilities?.ide),_=V(fe=>fe.requestPermissionInput),k=V(fe=>fe.permissionInputs?.[e]),j=b&&O9(t),[T,D]=N.useState(null);N.useEffect(()=>{j&&!w&&k===void 0&&_(e)},[j,w,k,_,e]),N.useEffect(()=>{if(u.current&&clearInterval(u.current),l(i),!(i<=0||w))return f.current=performance.now()+i,u.current=setInterval(()=>{const fe=Math.max(0,f.current-performance.now());l(fe),fe<=0&&u.current&&clearInterval(u.current)},1e3),()=>{u.current&&clearInterval(u.current)}},[i,w]);const I=N.useCallback(fe=>{if(v.current||w||h<=0||!E)return;v.current=!0,S(!0);const $=cf(t)&&y,P=fe==="allowSession"&&!$?"allow":fe;u.current&&clearInterval(u.current),o(e,P,P==="deny"?null:T)},[e,o,w,h,t,y,E,T]),L=h<=0,q=h>0&&h<=3e4,H=!w&&!L,Q=H&&cf(t)&&y,[F,J]=N.useState(!1),ie=ma(),X=ie?"⌘Y":"Ctrl+Y",de=ie?"⌘⇧Y":"Ctrl+Shift+Y";return F?null:r.jsxs("div",{className:`permission-prompt${w?" answered":""}`,"data-testid":"permission-prompt",role:"alertdialog","aria-live":"assertive","aria-label":`Permission request${d?` from ${d}`:""}`,"aria-describedby":`perm-desc-${e}`,children:[d&&r.jsx("div",{className:"perm-session","data-testid":"perm-session",title:`Requested by ${d}`,children:d}),r.jsxs("div",{className:"perm-desc",id:`perm-desc-${e}`,children:[r.jsx("span",{className:"perm-tool",children:t}),": ",n||"Permission requested"]}),j&&H&&k?.found&&k.input&&r.jsx(P9,{tool:t,input:k.input,onEditedInputChange:D}),!w&&r.jsx("div",{className:`perm-countdown${q?" urgent":""}${L?" expired":""}`,"data-testid":"perm-countdown","aria-live":"off",children:L?"Timed out":B9(h)}),H&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"perm-buttons",children:[r.jsx("button",{className:"btn-allow",onClick:()=>I("allow"),type:"button","aria-label":`Allow ${t}`,title:`Allow (${X})`,disabled:g||!E,children:"Allow"}),Q&&r.jsx("button",{className:"btn-allow-session",onClick:()=>I("allowSession"),type:"button","aria-label":`Allow ${t} for this session`,"data-testid":"btn-allow-session",title:`Allow for Session (${de})`,disabled:g||!E,children:"Allow for Session"}),r.jsx("button",{className:"btn-deny",onClick:()=>I("deny"),type:"button","aria-label":`Deny ${t}`,disabled:g||!E,children:"Deny"})]}),!E&&r.jsx("div",{className:"perm-disconnected-hint","data-testid":"perm-disconnected-hint",role:"status",children:"Disconnected — reconnect to answer."}),r.jsxs("div",{className:"perm-shortcut-hints","data-testid":"perm-shortcut-hints","aria-hidden":"true",children:[r.jsxs("span",{className:"perm-shortcut",children:[r.jsx("kbd",{className:"perm-kbd",children:X}),r.jsx("span",{className:"perm-shortcut-label",children:"allow"})]}),Q&&r.jsxs("span",{className:"perm-shortcut",children:[r.jsx("kbd",{className:"perm-kbd",children:de}),r.jsx("span",{className:"perm-shortcut-label",children:"session"})]})]})]}),L&&!w&&r.jsxs("div",{className:"perm-expired-info","data-testid":"perm-expired-info",children:[r.jsx("span",{className:"perm-expired-msg",children:"Permission expired — Claude will continue without this tool"}),r.jsx("button",{className:"btn-dismiss",onClick:()=>J(!0),type:"button","aria-label":"Dismiss expired permission",children:"Dismiss"})]}),w&&r.jsx("div",{className:"perm-answer","data-testid":"perm-answer",children:w==="deny"?"Denied":w==="allowSession"?"Allowed for session":"Allowed"})]})}function z9({question:e,options:t,answered:n,questions:i,allowMultiQuestion:o,allowSingleMultiSelect:d,pendingPermission:h,onSelect:l}){return h?r.jsx("div",{className:"question-prompt question-prompt--pending-permission","data-testid":"question-prompt-pending-permission",role:"status",children:r.jsx("div",{className:"question-text",children:"Pending permission to view question…"})}):Array.isArray(i)&&i.length>1&&n==null?o?r.jsx(WS,{questions:i,onSelect:l}):r.jsx(U9,{count:i.length}):T4(i)&&n==null&&d?r.jsx(WS,{questions:i,onSelect:l}):r.jsx(q9,{question:e,options:t,answered:n,onSelect:l})}function U9({count:e}){return r.jsx("div",{className:"question-prompt question-prompt--deferred","data-testid":"multi-question-deferred-notice",role:"status",children:r.jsxs("div",{className:"question-text",children:["Claude tried to ask ",e," questions at once. Waiting for it to retry one at a time…"]})})}function WS({questions:e,onSelect:t}){const[n,i]=N.useState({}),[o,d]=N.useState({}),h=N.useRef(!1),l=N.useId(),u=(S,w)=>{i(E=>j4(E,S,w))},f=(S,w)=>{d(E=>N4(E,S,w))},v=()=>{h.current||(h.current=!0,t(A4(e,{singleSelectByIdx:n,multiSelectByIdx:o})))},g=R4(e,{singleSelectByIdx:n});return r.jsxs("div",{className:"question-prompt question-prompt--multi","data-testid":"question-prompt-multi",children:[e.map((S,w)=>{const E=S.multiSelect===!0,x=`${l}-q-${w}`;return r.jsxs("div",{className:"question-prompt-multi-row","data-testid":`question-multi-row-${w}`,children:[r.jsx("div",{className:"question-text",id:x,children:S.question}),r.jsx("div",{className:`question-options${E?" question-options--multi":""}`,role:E?"group":"radiogroup","aria-labelledby":x,...E?{}:{"aria-required":!0},children:S.options.map(m=>{const y=`q-${w}-${m.value}`,b=`q-${w}`,_=S.multiSelect===!0,k=_?(o[w]||[]).includes(m.value):n[w]===m.value;return r.jsxs("label",{htmlFor:y,className:`question-option question-option--${_?"checkbox":"radio"}${k?" chosen":""}`,"data-testid":`question-multi-option-${w}-${m.value}`,children:[r.jsx("input",{id:y,type:_?"checkbox":"radio",name:b,checked:k,onChange:()=>_?f(w,m.value):u(w,m.value)}),r.jsx("span",{children:m.label})]},m.value)})})]},`q-${w}`)}),r.jsx("button",{type:"button",className:"question-multi-submit","data-testid":"question-multi-submit",disabled:!g,"aria-disabled":!g,onClick:v,children:"Submit"})]})}function q9({question:e,options:t,answered:n,onSelect:i}){const[o,d]=N.useState(""),[h,l]=N.useState(!1),[u,f]=N.useState("Other"),[v,g]=N.useState(!1),S=N.useRef(!1);N.useEffect(()=>{n!=null&&h&&(l(!1),d(""))},[n,h]);const w=()=>{if(S.current)return;const I=o.trim();I&&(S.current=!0,i(h?{otherLabel:u,freeformText:I}:I))},E=I=>{I.key==="Enter"&&(I.preventDefault(),w())},x=I=>{if(I===mm){const L=t.find(q=>q.value===I);f(L?.label||"Other"),l(!0);return}i(I)},m=n!=null&&t.some(I=>I.value===n),y=n!=null&&!m,b=!n&&(t.length===0||h),_=t.length>0&&!y&&(n!=null||!h),k=n!=null&&m,j=k?t.find(I=>I.value===n)?.label??n:void 0,T=k&&!v,D=_&&(n==null||v);return r.jsxs("div",{className:"question-prompt","data-testid":"question-prompt",children:[r.jsx("div",{className:"question-text",children:e}),T&&r.jsxs("button",{type:"button",className:"question-answered-summary","data-testid":"question-answered-summary","aria-expanded":!1,onClick:()=>g(!0),children:[r.jsx("span",{className:"question-answered-marker","aria-hidden":"true",children:"✓"}),r.jsx("span",{className:"question-answered-label",children:j}),r.jsx("span",{className:"question-answered-chevron","aria-hidden":"true",children:"▸"})]}),D&&r.jsxs(r.Fragment,{children:[k&&r.jsxs("button",{type:"button",className:"question-answered-summary question-answered-summary--expanded","data-testid":"question-answered-summary","aria-expanded":!0,onClick:()=>g(!1),children:[r.jsx("span",{className:"question-answered-marker","aria-hidden":"true",children:"✓"}),r.jsx("span",{className:"question-answered-label",children:j}),r.jsx("span",{className:"question-answered-chevron","aria-hidden":"true",children:"▾"})]}),r.jsx("div",{className:"question-options",children:t.map(I=>r.jsx("button",{className:`question-option${n===I.value?" chosen":""}`,disabled:n!=null,onClick:()=>x(I.value),type:"button",children:I.label},I.value))})]}),b&&r.jsxs("div",{className:"question-freetext",children:[r.jsx("input",{type:"text",value:o,onChange:I=>d(I.target.value),onKeyDown:E,placeholder:"Type your response…","aria-label":"Your response",className:"question-freetext-input",autoFocus:h}),r.jsx("button",{type:"button",onClick:w,disabled:!o.trim(),className:"question-freetext-send",children:"Send"}),h&&r.jsx("button",{type:"button",onClick:()=>{l(!1),d("")},className:"question-freetext-cancel",children:"Cancel"})]}),y&&r.jsxs("div",{className:"question-answered","data-testid":"question-answered-summary",children:[r.jsx("span",{className:"question-answered-marker","aria-hidden":"true",children:"✓"}),r.jsx("span",{className:"question-answered-label",children:n})]})]})}function bg({testId:e,role:t,headline:n,title:i,variant:o,subtext:d,children:h}){return r.jsxs("div",{className:"stream-stall-chip","data-testid":e,"data-variant":o,role:t,title:i,children:[r.jsx("span",{className:"stream-stall-chip-text",children:n}),d,h]})}function H9({errorText:e,onRetry:t,timeoutMs:n,provider:i,onViewLogs:o}){const d=N.useCallback(()=>{t?.()},[t]),h=N.useCallback(()=>{o?.()},[o]),l=Zm("stream_stall"),u=typeof n=="number"&&Number.isFinite(n)&&n>0?`No response for ${lN(n)} — retry?`:l.headline,f=typeof i=="string"&&i.trim().length>0?Vi(i.trim()).short:null,v=f?`${f} · ${u}`:u;return r.jsxs(bg,{testId:"stream-stall-chip",role:l.role,title:e,headline:v,children:[t&&r.jsx("button",{type:"button",className:"stream-stall-chip-retry","data-testid":"stream-stall-chip-retry",onClick:d,children:"Retry"}),o&&r.jsx("button",{type:"button",className:"stream-stall-chip-view-logs","data-testid":"stream-stall-chip-view-logs",onClick:h,children:"View logs"})]})}function F9({errorText:e,onRetry:t}){const n=N.useCallback(()=>{t?.()},[t]),i=Zm("ASK_USER_QUESTION_STALL");return r.jsx(bg,{testId:"ask-user-question-stall-chip",role:i.role,title:e,headline:i.headline,children:t&&r.jsx("button",{type:"button",className:"stream-stall-chip-retry","data-testid":"ask-user-question-stall-chip-retry",onClick:n,children:"Retry"})})}const K9={display:"block",marginTop:4,fontSize:"0.8em",fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, monospace",opacity:.75};function W9({errorText:e,attemptedResumeId:t,variant:n="recoverable"}){const i=typeof t=="string"&&t.trim().length>0,d=Zm(n==="exhausted"?"resume_unknown_exhausted":"resume_unknown");return r.jsx(bg,{testId:"resume-unknown-chip",variant:n,role:d.role,title:e,headline:d.headline,subtext:i&&r.jsxs("span",{"data-testid":"resume-unknown-chip-id",style:K9,children:["Attempted id: ",t]})})}function G9(e,t){if(!e||t.length<=1)return;const n=t.find(d=>d.sessionId===e);if(!n)return;const i=n.name?.trim()||e,o=n.provider?.trim();return o?`${i} · ${o}`:i}function V9(e){const{storeMsgMap:t,chatToolGroupPayloads:n,chatTailMessageId:i,sendPermissionResponse:o,sendUserQuestionResponse:d,markPromptAnswered:h,storeMessages:l,sendInput:u,streamStallTimeoutMs:f,allowMultiQuestionForm:v,activeSessionProvider:g,activeSessionCaps:S,setViewMode:w,stalledPromptIds:E,hasPendingAskUserQuestionPermission:x,sessions:m}=e;return N.useCallback(y=>{if(y.type==="tool_group"){const _=n.get(y.id);return _?r.jsx(k9,{messages:_.messages,isActive:_.isActive,isTail:y.id===i}):null}const b=t.get(y.id);if(!b)return null;if(b.requestId&&b.expiresAt&&!b.answered){const _=Math.max(0,b.expiresAt-Date.now());return r.jsx($9,{requestId:b.requestId,tool:b.tool||"Unknown",description:b.content,remainingMs:_,onRespond:(k,j,T)=>o(k,j,T),sessionLabel:G9(b.originSessionId,m)})}if(b.type==="prompt"&&b.options&&!b.requestId)return E.has(b.id)?null:r.jsx(z9,{question:b.content,options:b.options,questions:b.questions,answered:b.answered,allowMultiQuestion:v,allowSingleMultiSelect:XN(g,S),pendingPermission:!b.answered&&x,onSelect:_=>{d(_,b.toolUseId),h(b.id,H0(_))}});if(b.type==="tool_use"&&b.toolUseId)return r.jsx(A9,{toolName:b.tool||"Tool",toolUseId:b.toolUseId,input:b.toolInput,inputPartial:b.toolInputPartial,result:b.toolResult,serverName:b.serverName,isTail:y.id===i,resultImages:b.toolResultImages,childAgentEvents:b.childAgentEvents});if(b.type==="system"&&b.evaluator?.kind==="rewrite")return r.jsx(Gz,{meta:b.evaluator});if(b.type==="error"&&b.code==="stream_stall"){const _=y.id===i,k=_?[...l].reverse().find(j=>j.type==="user_input"):void 0;return r.jsx(H9,{errorText:b.content,onRetry:k?()=>u(k.content):void 0,timeoutMs:f??void 0,provider:g??void 0,onViewLogs:_?()=>w("system"):void 0})}if(b.type==="error"&&Vm(b.code)){const k=y.id===i?[...l].reverse().find(j=>j.type==="user_input"):void 0;return r.jsx(F9,{errorText:b.content,onRetry:k?()=>u(k.content):void 0})}return b.type==="error"&&(b.code==="resume_unknown"||b.code==="resume_unknown_exhausted")?r.jsx(W9,{variant:b.code==="resume_unknown_exhausted"?"exhausted":"recoverable",errorText:b.content,attemptedResumeId:b.attemptedResumeId}):null},[t,n,i,o,d,h,l,u,f,v,g,S,w,E,x,m])}function Y9(e,t){const n=getComputedStyle(e),i=parseFloat(n.fontSize);return t*i}function Z9(e,t){const n=getComputedStyle(e.ownerDocument.body),i=parseFloat(n.fontSize);return t*i}function X9(e){return e/100*window.innerHeight}function Q9(e){return e/100*window.innerWidth}function J9(e){switch(typeof e){case"number":return[e,"px"];case"string":{const t=parseFloat(e);return e.endsWith("%")?[t,"%"]:e.endsWith("px")?[t,"px"]:e.endsWith("rem")?[t,"rem"]:e.endsWith("em")?[t,"em"]:e.endsWith("vh")?[t,"vh"]:e.endsWith("vw")?[t,"vw"]:[t,"%"]}}}function Ic({groupSize:e,panelElement:t,styleProp:n}){let i;const[o,d]=J9(n);switch(d){case"%":{i=o/100*e;break}case"px":{i=o;break}case"rem":{i=Z9(t,o);break}case"em":{i=Y9(t,o);break}case"vh":{i=X9(o);break}case"vw":{i=Q9(o);break}}return i}function Gs(e){return parseFloat(e.toFixed(3))}function ul({group:e}){const{orientation:t,panels:n}=e;return n.reduce((i,o)=>(i+=t==="horizontal"?o.element.offsetWidth:o.element.offsetHeight,i),0)}function Om(e){const{panels:t}=e,n=ul({group:e});return n===0?t.map(i=>({groupResizeBehavior:i.panelConstraints.groupResizeBehavior,collapsedSize:0,collapsible:i.panelConstraints.collapsible===!0,defaultSize:void 0,disabled:i.panelConstraints.disabled,minSize:0,maxSize:100,panelId:i.id})):t.map(i=>{const{element:o,panelConstraints:d}=i;let h=0;if(d.collapsedSize!==void 0){const v=Ic({groupSize:n,panelElement:o,styleProp:d.collapsedSize});h=Gs(v/n*100)}let l;if(d.defaultSize!==void 0){const v=Ic({groupSize:n,panelElement:o,styleProp:d.defaultSize});l=Gs(v/n*100)}let u=0;if(d.minSize!==void 0){const v=Ic({groupSize:n,panelElement:o,styleProp:d.minSize});u=Gs(v/n*100)}let f=100;if(d.maxSize!==void 0){const v=Ic({groupSize:n,panelElement:o,styleProp:d.maxSize});f=Gs(v/n*100)}return{groupResizeBehavior:d.groupResizeBehavior,collapsedSize:h,collapsible:d.collapsible===!0,defaultSize:l,disabled:d.disabled,minSize:u,maxSize:f,panelId:i.id}})}function Bn(e,t="Assertion error"){if(!e)throw Error(t)}function Pm(e,t){return Array.from(t).sort(e==="horizontal"?e7:t7)}function e7(e,t){const n=e.element.offsetLeft-t.element.offsetLeft;return n!==0?n:e.element.offsetWidth-t.element.offsetWidth}function t7(e,t){const n=e.element.offsetTop-t.element.offsetTop;return n!==0?n:e.element.offsetHeight-t.element.offsetHeight}function U1(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function q1(e,t){return{x:e.x>=t.left&&e.x<=t.right?0:Math.min(Math.abs(e.x-t.left),Math.abs(e.x-t.right)),y:e.y>=t.top&&e.y<=t.bottom?0:Math.min(Math.abs(e.y-t.top),Math.abs(e.y-t.bottom))}}function n7({orientation:e,rects:t,targetRect:n}){const i={x:n.x+n.width/2,y:n.y+n.height/2};let o,d=Number.MAX_VALUE;for(const h of t){const{x:l,y:u}=q1(i,h),f=e==="horizontal"?l:u;f<d&&(d=f,o=h)}return Bn(o,"No rect found"),o}let Td;function s7(){return Td===void 0&&(typeof matchMedia=="function"?Td=!!matchMedia("(pointer:coarse)").matches:Td=!1),Td}function H1(e){const{element:t,orientation:n,panels:i,separators:o}=e,d=Pm(n,Array.from(t.children).filter(U1).map(E=>({element:E}))).map(({element:E})=>E),h=[];let l=!1,u=!1,f=-1,v=-1,g=0,S,w=[];{let E=-1;for(const x of d)x.hasAttribute("data-panel")&&(E++,x.hasAttribute("data-disabled")||(g++,f===-1&&(f=E),v=E))}if(g>1){let E=-1;for(const x of d)if(x.hasAttribute("data-panel")){E++;const m=i.find(y=>y.element===x);if(m){if(S){const y=S.element.getBoundingClientRect(),b=x.getBoundingClientRect();let _;if(u){const k=n==="horizontal"?new DOMRect(y.right,y.top,0,y.height):new DOMRect(y.left,y.bottom,y.width,0),j=n==="horizontal"?new DOMRect(b.left,b.top,0,b.height):new DOMRect(b.left,b.top,b.width,0);switch(w.length){case 0:{_=[k,j];break}case 1:{const T=w[0],D=n7({orientation:n,rects:[y,b],targetRect:T.element.getBoundingClientRect()});_=[T,D===y?j:k];break}default:{_=w;break}}}else w.length?_=w:_=[n==="horizontal"?new DOMRect(y.right,b.top,b.left-y.right,b.height):new DOMRect(b.left,y.bottom,b.width,b.top-y.bottom)];for(const k of _){let j="width"in k?k:k.element.getBoundingClientRect();const T=s7()?e.resizeTargetMinimumSize.coarse:e.resizeTargetMinimumSize.fine;if(j.width<T){const I=T-j.width;j=new DOMRect(j.x-I/2,j.y,j.width+I,j.height)}if(j.height<T){const I=T-j.height;j=new DOMRect(j.x,j.y-I/2,j.width,j.height+I)}const D=E<=f||E>v;!l&&!D&&h.push({group:e,groupSize:ul({group:e}),panels:[S,m],separator:"width"in k?void 0:k,rect:j}),l=!1}}u=!1,S=m,w=[]}}else if(x.hasAttribute("data-separator")){x.ariaDisabled!==null&&(l=!0);const m=o.find(y=>y.element===x);m?w.push(m):(S=void 0,w=[])}else u=!0}return h}class F1{#e={};addListener(t,n){const i=this.#e[t];return i===void 0?this.#e[t]=[n]:i.includes(n)||i.push(n),()=>{this.removeListener(t,n)}}emit(t,n){const i=this.#e[t];if(i!==void 0)if(i.length===1)i[0].call(null,n);else{let o=!1,d=null;const h=Array.from(i);for(let l=0;l<h.length;l++){const u=h[l];try{u.call(null,n)}catch(f){d===null&&(o=!0,d=f)}}if(o)throw d}}removeAllListeners(){this.#e={}}removeListener(t,n){const i=this.#e[t];if(i!==void 0){const o=i.indexOf(n);o>=0&&i.splice(o,1)}}}let Gi=new Map;const K1=new F1;function i7(e){Gi=new Map(Gi),Gi.delete(e)}function GS(e,t){for(const[n]of Gi)if(n.id===e)return n}function ua(e,t){for(const[n,i]of Gi)if(n.id===e)return i;if(t)throw Error(`Could not find data for Group with id ${e}`)}function no(){return Gi}function _g(e,t){return K1.addListener("groupChange",n=>{n.group.id===e&&t(n)})}function wr(e,t){const n=Gi.get(e);Gi=new Map(Gi),Gi.set(e,t),K1.emit("groupChange",{group:e,prev:n,next:t})}function r7(e,t,n){let i,o={x:1/0,y:1/0};for(const d of t){const h=q1(n,d.rect);switch(e){case"horizontal":{h.x<=o.x&&(i=d,o=h);break}case"vertical":{h.y<=o.y&&(i=d,o=h);break}}}return i?{distance:o,hitRegion:i}:void 0}function a7(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function o7(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:ZS(e),b:ZS(t)};let i;for(;n.a.at(-1)===n.b.at(-1);)i=n.a.pop(),n.b.pop();Bn(i,"Stacking order can only be calculated for elements with a common ancestor");const o={a:YS(VS(n.a)),b:YS(VS(n.b))};if(o.a===o.b){const d=i.childNodes,h={a:n.a.at(-1),b:n.b.at(-1)};let l=d.length;for(;l--;){const u=d[l];if(u===h.a)return 1;if(u===h.b)return-1}}return Math.sign(o.a-o.b)}const l7=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function c7(e){const t=getComputedStyle(W1(e)??e).display;return t==="flex"||t==="inline-flex"}function u7(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||c7(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||l7.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function VS(e){let t=e.length;for(;t--;){const n=e[t];if(Bn(n,"Missing node"),u7(n))return n}return null}function YS(e){return e&&Number(getComputedStyle(e).zIndex)||0}function ZS(e){const t=[];for(;e;)t.push(e),e=W1(e);return t}function W1(e){const{parentNode:t}=e;return a7(t)?t.host:t}function d7(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function f7({groupElement:e,hitRegion:t,pointerEventTarget:n}){if(!U1(n)||n.contains(e)||e.contains(n))return!0;if(o7(n,e)>0){let i=n;for(;i;){if(i.contains(e))return!0;if(d7(i.getBoundingClientRect(),t))return!1;i=i.parentElement}}return!0}function Sg(e,t){const n=[];return t.forEach((i,o)=>{if(o.disabled)return;const d=H1(o),h=r7(o.orientation,d,{x:e.clientX,y:e.clientY});h&&h.distance.x<=0&&h.distance.y<=0&&f7({groupElement:o.element,hitRegion:h.hitRegion.rect,pointerEventTarget:e.target})&&n.push(h.hitRegion)}),n}function h7(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function Ts(e,t,n=0){return Math.abs(Gs(e)-Gs(t))<=n}function Ki(e,t){return Ts(e,t)?0:e>t?1:-1}function el({overrideDisabledPanels:e,panelConstraints:t,prevSize:n,size:i}){const{collapsedSize:o=0,collapsible:d,disabled:h,maxSize:l=100,minSize:u=0}=t;if(h&&!e)return n;if(Ki(i,u)<0)if(d){const f=(o+u)/2;Ki(i,f)<0?i=o:i=u}else i=u;return i=Math.min(l,i),i=Gs(i),i}function Hc({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:i,prevLayout:o,trigger:d}){if(Ts(e,0))return t;const h=d==="imperative-api",l=Object.values(t),u=Object.values(o),f=[...l],[v,g]=i;Bn(v!=null,"Invalid first pivot index"),Bn(g!=null,"Invalid second pivot index");let S=0;switch(d){case"keyboard":{{const x=e<0?g:v,m=n[x];Bn(m,`Panel constraints not found for index ${x}`);const{collapsedSize:y=0,collapsible:b,minSize:_=0}=m;if(b){const k=l[x];if(Bn(k!=null,`Previous layout not found for panel index ${x}`),Ts(k,y)){const j=_-k;Ki(j,Math.abs(e))>0&&(e=e<0?0-j:j)}}}{const x=e<0?v:g,m=n[x];Bn(m,`No panel constraints found for index ${x}`);const{collapsedSize:y=0,collapsible:b,minSize:_=0}=m;if(b){const k=l[x];if(Bn(k!=null,`Previous layout not found for panel index ${x}`),Ts(k,_)){const j=k-y;Ki(j,Math.abs(e))>0&&(e=e<0?0-j:j)}}}break}default:{const x=e<0?g:v,m=n[x];Bn(m,`Panel constraints not found for index ${x}`);const y=l[x],{collapsible:b,collapsedSize:_,minSize:k}=m;if(b&&Ki(y,k)<0)if(e>0){const j=k-_,T=j/2,D=y+e;Ki(D,k)<0&&(e=Ki(e,T)<=0?0:j)}else{const j=k-_,T=100-j/2,D=y-e;Ki(D,k)<0&&(e=Ki(100+e,T)>0?0:-j)}break}}{const x=e<0?1:-1;let m=e<0?g:v,y=0;for(;;){const _=l[m];Bn(_!=null,`Previous layout not found for panel index ${m}`);const k=el({overrideDisabledPanels:h,panelConstraints:n[m],prevSize:_,size:100})-_;if(y+=k,m+=x,m<0||m>=n.length)break}const b=Math.min(Math.abs(e),Math.abs(y));e=e<0?0-b:b}{let x=e<0?v:g;for(;x>=0&&x<n.length;){const m=Math.abs(e)-Math.abs(S),y=l[x];Bn(y!=null,`Previous layout not found for panel index ${x}`);const b=y-m,_=el({overrideDisabledPanels:h,panelConstraints:n[x],prevSize:y,size:b});if(!Ts(y,_)&&(S+=y-_,f[x]=_,S.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?x--:x++}}if(h7(u,f))return o;{const x=e<0?g:v,m=l[x];Bn(m!=null,`Previous layout not found for panel index ${x}`);const y=m+S,b=el({overrideDisabledPanels:h,panelConstraints:n[x],prevSize:m,size:y});if(f[x]=b,!Ts(b,y)){let _=y-b,k=e<0?g:v;for(;k>=0&&k<n.length;){const j=f[k];Bn(j!=null,`Previous layout not found for panel index ${k}`);const T=j+_,D=el({overrideDisabledPanels:h,panelConstraints:n[k],prevSize:j,size:T});if(Ts(j,D)||(_-=D-j,f[k]=D),Ts(_,0))break;e>0?k--:k++}}}const w=Object.values(f).reduce((x,m)=>m+x,0);if(!Ts(w,100,.1))return o;const E=Object.keys(o);return f.reduce((x,m,y)=>(x[E[y]]=m,x),{})}function Ya(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(t[n]===void 0||Ki(e[n],t[n])!==0)return!1;return!0}function Za({layout:e,panelConstraints:t}){const n=Object.values(e),i=[...n],o=i.reduce((l,u)=>l+u,0);if(i.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${i.map(l=>`${l}%`).join(", ")}`);if(!Ts(o,100)&&i.length>0)for(let l=0;l<t.length;l++){const u=i[l];Bn(u!=null,`No layout data found for index ${l}`);const f=100/o*u;i[l]=f}let d=0;for(let l=0;l<t.length;l++){const u=n[l];Bn(u!=null,`No layout data found for index ${l}`);const f=i[l];Bn(f!=null,`No layout data found for index ${l}`);const v=el({overrideDisabledPanels:!0,panelConstraints:t[l],prevSize:u,size:f});f!=v&&(d+=f-v,i[l]=v)}if(!Ts(d,0))for(let l=0;l<t.length;l++){const u=i[l];Bn(u!=null,`No layout data found for index ${l}`);const f=u+d,v=el({overrideDisabledPanels:!0,panelConstraints:t[l],prevSize:u,size:f});if(u!==v&&(d-=v-u,i[l]=v,Ts(d,0)))break}const h=Object.keys(e);return i.reduce((l,u,f)=>(l[h[f]]=u,l),{})}function G1({groupId:e,panelId:t}){const n=()=>{const l=no();for(const[u,{defaultLayoutDeferred:f,derivedPanelConstraints:v,layout:g,groupSize:S,separatorToPanels:w}]of l)if(u.id===e)return{defaultLayoutDeferred:f,derivedPanelConstraints:v,group:u,groupSize:S,layout:g,separatorToPanels:w};throw Error(`Group ${e} not found`)},i=()=>{const l=n().derivedPanelConstraints.find(u=>u.panelId===t);if(l!==void 0)return l;throw Error(`Panel constraints not found for Panel ${t}`)},o=()=>{const l=n().group.panels.find(u=>u.id===t);if(l!==void 0)return l;throw Error(`Layout not found for Panel ${t}`)},d=()=>{const l=n().layout[t];if(l!==void 0)return l;throw Error(`Layout not found for Panel ${t}`)},h=l=>{const u=d();if(l===u)return;const{defaultLayoutDeferred:f,derivedPanelConstraints:v,group:g,groupSize:S,layout:w,separatorToPanels:E}=n(),x=g.panels.findIndex(_=>_.id===t),m=x===g.panels.length-1,y=Hc({delta:m?u-l:l-u,initialLayout:w,panelConstraints:v,pivotIndices:m?[x-1,x]:[x,x+1],prevLayout:w,trigger:"imperative-api"}),b=Za({layout:y,panelConstraints:v});Ya(w,b)||wr(g,{defaultLayoutDeferred:f,derivedPanelConstraints:v,groupSize:S,layout:b,separatorToPanels:E})};return{collapse:()=>{const{collapsible:l,collapsedSize:u}=i(),{mutableValues:f}=o(),v=d();l&&v!==u&&(f.expandToSize=v,h(u))},expand:()=>{const{collapsible:l,collapsedSize:u,minSize:f}=i(),{mutableValues:v}=o(),g=d();if(l&&g===u){let S=v.expandToSize??f;S===0&&(S=1),h(S)}},getSize:()=>{const{group:l}=n(),u=d(),{element:f}=o(),v=l.orientation==="horizontal"?f.offsetWidth:f.offsetHeight;return{asPercentage:u,inPixels:v}},isCollapsed:()=>{const{collapsible:l,collapsedSize:u}=i(),f=d();return l&&Ts(u,f)},resize:l=>{const{group:u}=n(),{element:f}=o(),v=ul({group:u}),g=Ic({groupSize:v,panelElement:f,styleProp:l}),S=Gs(g/v*100);h(S)}}}function XS(e){if(e.defaultPrevented)return;const t=no();Sg(e,t).forEach(n=>{if(n.separator&&!n.separator.disableDoubleClick){const i=n.panels.find(o=>o.panelConstraints.defaultSize!==void 0);if(i){const o=i.panelConstraints.defaultSize,d=G1({groupId:n.group.id,panelId:i.id});d&&o!==void 0&&(d.resize(o),e.preventDefault())}}})}function Vd(e){const t=no();for(const[n]of t)if(n.separators.some(i=>i.element===e))return n;throw Error("Could not find parent Group for separator element")}function V1({groupId:e}){const t=()=>{const n=no();for(const[i,o]of n)if(i.id===e)return{group:i,...o};throw Error(`Could not find Group with id "${e}"`)};return{getLayout(){const{defaultLayoutDeferred:n,layout:i}=t();return n?{}:i},setLayout(n){const{defaultLayoutDeferred:i,derivedPanelConstraints:o,group:d,groupSize:h,layout:l,separatorToPanels:u}=t(),f=Za({layout:n,panelConstraints:o});return i?l:(Ya(l,f)||wr(d,{defaultLayoutDeferred:i,derivedPanelConstraints:o,groupSize:h,layout:f,separatorToPanels:u}),f)}}}function za(e,t){const n=Vd(e),i=ua(n.id,!0),o=n.separators.find(v=>v.element===e);Bn(o,"Matching separator not found");const d=i.separatorToPanels.get(o);Bn(d,"Matching panels not found");const h=d.map(v=>n.panels.indexOf(v)),l=V1({groupId:n.id}).getLayout(),u=Hc({delta:t,initialLayout:l,panelConstraints:i.derivedPanelConstraints,pivotIndices:h,prevLayout:l,trigger:"keyboard"}),f=Za({layout:u,panelConstraints:i.derivedPanelConstraints});Ya(l,f)||wr(n,{defaultLayoutDeferred:i.defaultLayoutDeferred,derivedPanelConstraints:i.derivedPanelConstraints,groupSize:i.groupSize,layout:f,separatorToPanels:i.separatorToPanels})}function QS(e){if(e.defaultPrevented)return;const t=e.currentTarget,n=Vd(t);if(!n.disabled)switch(e.key){case"ArrowDown":{e.preventDefault(),n.orientation==="vertical"&&za(t,5);break}case"ArrowLeft":{e.preventDefault(),n.orientation==="horizontal"&&za(t,-5);break}case"ArrowRight":{e.preventDefault(),n.orientation==="horizontal"&&za(t,5);break}case"ArrowUp":{e.preventDefault(),n.orientation==="vertical"&&za(t,-5);break}case"End":{e.preventDefault(),za(t,100);break}case"Enter":{e.preventDefault();const i=Vd(t),o=ua(i.id,!0),{derivedPanelConstraints:d,layout:h,separatorToPanels:l}=o,u=i.separators.find(S=>S.element===t);Bn(u,"Matching separator not found");const f=l.get(u);Bn(f,"Matching panels not found");const v=f[0],g=d.find(S=>S.panelId===v.id);if(Bn(g,"Panel metadata not found"),g.collapsible){const S=h[v.id],w=g.collapsedSize===S?i.mutableState.expandedPanelSizes[v.id]??g.minSize:g.collapsedSize;za(t,w-S)}break}case"F6":{e.preventDefault();const i=Vd(t).separators.map(h=>h.element),o=Array.from(i).findIndex(h=>h===e.currentTarget);Bn(o!==null,"Index not found");const d=e.shiftKey?o>0?o-1:i.length-1:o+1<i.length?o+1:0;i[d].focus({preventScroll:!0});break}case"Home":{e.preventDefault(),za(t,-100);break}}}let rl={cursorFlags:0,state:"inactive"};const xg=new F1;function Xa(){return rl}function p7(e){return xg.addListener("change",e)}function m7(e){const t=rl,n={...rl};n.cursorFlags=e,rl=n,xg.emit("change",{prev:t,next:n})}function al(e){const t=rl;rl=e,xg.emit("change",{prev:t,next:e})}function JS(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=no(),n=Sg(e,t),i=new Map;let o=!1;n.forEach(d=>{d.separator&&(o||(o=!0,d.separator.element.focus({preventScroll:!0})));const h=t.get(d.group);h&&i.set(d.group,h.layout)}),al({cursorFlags:0,hitRegions:n,initialLayoutMap:i,pointerDownAtPoint:{x:e.clientX,y:e.clientY},state:"active"}),n.length&&e.preventDefault()}const g7=e=>e,rm=()=>{},Y1=1,Z1=2,X1=4,Q1=8,e0=3,t0=12;let Id;function n0(){return Id===void 0&&(Id=!1,typeof window<"u"&&(window.navigator.userAgent.includes("Chrome")||window.navigator.userAgent.includes("Firefox"))&&(Id=!0)),Id}function v7({cursorFlags:e,groups:t,state:n}){let i=0,o=0;switch(n){case"active":case"hover":t.forEach(d=>{if(!d.mutableState.disableCursor)switch(d.orientation){case"horizontal":{i++;break}case"vertical":{o++;break}}})}if(!(i===0&&o===0)){switch(n){case"active":{if(e&&n0()){const d=(e&Y1)!==0,h=(e&Z1)!==0,l=(e&X1)!==0,u=(e&Q1)!==0;if(d)return l?"se-resize":u?"ne-resize":"e-resize";if(h)return l?"sw-resize":u?"nw-resize":"w-resize";if(l)return"s-resize";if(u)return"n-resize"}break}}return n0()?i>0&&o>0?"move":i>0?"ew-resize":"ns-resize":i>0&&o>0?"grab":i>0?"col-resize":"row-resize"}}const s0=new WeakMap;function wg(e){if(e.defaultView===null||e.defaultView===void 0)return;let{prevStyle:t,styleSheet:n}=s0.get(e)??{};n===void 0&&(n=new e.defaultView.CSSStyleSheet,e.adoptedStyleSheets&&e.adoptedStyleSheets.push(n));const i=Xa();switch(i.state){case"active":case"hover":{const o=v7({cursorFlags:i.cursorFlags,groups:i.hitRegions.map(h=>h.group),state:i.state}),d=`*, *:hover {cursor: ${o} !important; }`;if(t===d)return;t=d,o?n.cssRules.length===0?n.insertRule(d):n.replaceSync(d):n.cssRules.length===1&&n.deleteRule(0);break}case"inactive":{t=void 0,n.cssRules.length===1&&n.deleteRule(0);break}}s0.set(e,{prevStyle:t,styleSheet:n})}function J1({document:e,event:t,hitRegions:n,initialLayoutMap:i,mountedGroups:o,pointerDownAtPoint:d,prevCursorFlags:h}){let l=0;n.forEach(f=>{const{group:v,groupSize:g}=f,{orientation:S,panels:w}=v,{disableCursor:E}=v.mutableState;let x=0;d?S==="horizontal"?x=(t.clientX-d.x)/g*100:x=(t.clientY-d.y)/g*100:S==="horizontal"?x=t.clientX<0?-100:100:x=t.clientY<0?-100:100;const m=i.get(v),y=o.get(v);if(!m||!y)return;const{defaultLayoutDeferred:b,derivedPanelConstraints:_,groupSize:k,layout:j,separatorToPanels:T}=y;if(_&&j&&T){const D=Hc({delta:x,initialLayout:m,panelConstraints:_,pivotIndices:f.panels.map(I=>w.indexOf(I)),prevLayout:j,trigger:"mouse-or-touch"});if(Ya(D,j)){if(x!==0&&!E)switch(S){case"horizontal":{l|=x<0?Y1:Z1;break}case"vertical":{l|=x<0?X1:Q1;break}}}else wr(f.group,{defaultLayoutDeferred:b,derivedPanelConstraints:_,groupSize:k,layout:D,separatorToPanels:T})}});let u=0;t.movementX===0?u|=h&e0:u|=l&e0,t.movementY===0?u|=h&t0:u|=l&t0,m7(u),wg(e)}function i0(e){const t=no(),n=Xa();n.state==="active"&&J1({document:e.currentTarget,event:e,hitRegions:n.hitRegions,initialLayoutMap:n.initialLayoutMap,mountedGroups:t,prevCursorFlags:n.cursorFlags})}function r0(e){if(e.defaultPrevented)return;const t=Xa(),n=no();switch(t.state){case"active":{if(e.buttons===0){al({cursorFlags:0,state:"inactive"}),t.hitRegions.forEach(i=>{const o=ua(i.group.id,!0);wr(i.group,o)});return}for(const i of t.hitRegions)if(i.separator){const{element:o}=i.separator;o.hasPointerCapture?.(e.pointerId)||o.setPointerCapture?.(e.pointerId)}J1({document:e.currentTarget,event:e,hitRegions:t.hitRegions,initialLayoutMap:t.initialLayoutMap,mountedGroups:n,pointerDownAtPoint:t.pointerDownAtPoint,prevCursorFlags:t.cursorFlags});break}default:{const i=Sg(e,n);i.length===0?t.state!=="inactive"&&al({cursorFlags:0,state:"inactive"}):al({cursorFlags:0,hitRegions:i,state:"hover"}),wg(e.currentTarget);break}}}function a0(e){e.relatedTarget instanceof HTMLIFrameElement&&Xa().state==="hover"&&al({cursorFlags:0,state:"inactive"})}function o0(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=Xa();t.state==="active"&&(al({cursorFlags:0,state:"inactive"}),t.hitRegions.length>0&&(wg(e.currentTarget),t.hitRegions.forEach(n=>{const i=ua(n.group.id,!0);wr(n.group,i)}),e.preventDefault()))}function l0(e){let t=0,n=0;const i={};for(const d of e)if(d.defaultSize!==void 0){t++;const h=Gs(d.defaultSize);n+=h,i[d.panelId]=h}else i[d.panelId]=void 0;const o=e.length-t;if(o!==0){const d=Gs((100-n)/o);for(const h of e)h.defaultSize===void 0&&(i[h.panelId]=d)}return i}function y7(e,t,n){if(!n[0])return;const i=e.panels.find(u=>u.element===t);if(!i||!i.onResize)return;const o=ul({group:e}),d=e.orientation==="horizontal"?i.element.offsetWidth:i.element.offsetHeight,h=i.mutableValues.prevSize,l={asPercentage:Gs(d/o*100),inPixels:d};i.mutableValues.prevSize=l,i.onResize(l,i.id,h)}function b7(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function _7({group:e,nextGroupSize:t,prevGroupSize:n,prevLayout:i}){if(n<=0||t<=0||n===t)return i;let o=0,d=0,h=!1;const l=new Map,u=[];for(const g of e.panels){const S=i[g.id]??0;if(g.panelConstraints.groupResizeBehavior==="preserve-pixel-size"){h=!0;const w=S/100*n,E=Gs(w/t*100);l.set(g.id,E),o+=E}else u.push(g.id),d+=S}if(!h||u.length===0)return i;const f=100-o,v={...i};if(l.forEach((g,S)=>{v[S]=g}),d>0)for(const g of u){const S=i[g]??0;v[g]=Gs(S/d*f)}else{const g=Gs(f/u.length);for(const S of u)v[S]=g}return v}function S7(e,t){const n=e.map(o=>o.id),i=Object.keys(t);if(n.length!==i.length)return!1;for(const o of n)if(!i.includes(o))return!1;return!0}const Vo=new Map;function x7(e){let t=!0;Bn(e.element.ownerDocument.defaultView,"Cannot register an unmounted Group");const n=e.element.ownerDocument.defaultView.ResizeObserver,i=new Set,o=new Set,d=new n(E=>{for(const x of E){const{borderBoxSize:m,target:y}=x;if(y===e.element){if(t){const b=ul({group:e});if(b===0)return;const _=ua(e.id);if(!_)return;const k=Om(e),j=_.defaultLayoutDeferred?l0(k):_.layout,T=_7({group:e,nextGroupSize:b,prevGroupSize:_.groupSize,prevLayout:j}),D=Za({layout:T,panelConstraints:k});if(!_.defaultLayoutDeferred&&Ya(_.layout,D)&&b7(_.derivedPanelConstraints,k)&&_.groupSize===b)return;wr(e,{defaultLayoutDeferred:!1,derivedPanelConstraints:k,groupSize:b,layout:D,separatorToPanels:_.separatorToPanels})}}else y7(e,y,m)}});d.observe(e.element),e.panels.forEach(E=>{Bn(!i.has(E.id),`Panel ids must be unique; id "${E.id}" was used more than once`),i.add(E.id),E.onResize&&d.observe(E.element)});const h=ul({group:e}),l=Om(e),u=e.panels.map(({id:E})=>E).join(",");let f=e.mutableState.defaultLayout;f&&(S7(e.panels,f)||(f=void 0));const v=e.mutableState.layouts[u]??f??l0(l),g=Za({layout:v,panelConstraints:l}),S=e.element.ownerDocument;Vo.set(S,(Vo.get(S)??0)+1);const w=new Map;return H1(e).forEach(E=>{E.separator&&w.set(E.separator,E.panels)}),wr(e,{defaultLayoutDeferred:h===0,derivedPanelConstraints:l,groupSize:h,layout:g,separatorToPanels:w}),e.separators.forEach(E=>{Bn(!o.has(E.id),`Separator ids must be unique; id "${E.id}" was used more than once`),o.add(E.id),E.element.addEventListener("keydown",QS)}),Vo.get(S)===1&&(S.addEventListener("dblclick",XS,!0),S.addEventListener("pointerdown",JS,!0),S.addEventListener("pointerleave",i0),S.addEventListener("pointermove",r0),S.addEventListener("pointerout",a0),S.addEventListener("pointerup",o0,!0)),function(){t=!1,Vo.set(S,Math.max(0,(Vo.get(S)??0)-1)),i7(e),e.separators.forEach(E=>{E.element.removeEventListener("keydown",QS)}),Vo.get(S)||(S.removeEventListener("dblclick",XS,!0),S.removeEventListener("pointerdown",JS,!0),S.removeEventListener("pointerleave",i0),S.removeEventListener("pointermove",r0),S.removeEventListener("pointerout",a0),S.removeEventListener("pointerup",o0,!0)),d.disconnect()}}function w7(){const[e,t]=N.useState({}),n=N.useCallback(()=>t({}),[]);return[e,n]}function kg(e){const t=N.useId();return`${e??t}`}const so=typeof window<"u"?N.useLayoutEffect:N.useEffect;function Bc(e){const t=N.useRef(e);return so(()=>{t.current=e},[e]),N.useCallback((...n)=>t.current?.(...n),[t])}function Cg(...e){return Bc(t=>{e.forEach(n=>{if(n)switch(typeof n){case"function":{n(t);break}case"object":{n.current=t;break}}})})}function Eg(e){const t=N.useRef({...e});return so(()=>{for(const n in e)t.current[n]=e[n]},[e]),t.current}const ek=N.createContext(null);function k7(e,t){const n=N.useRef({getLayout:()=>({}),setLayout:g7});N.useImperativeHandle(t,()=>n.current,[]),so(()=>{Object.assign(n.current,V1({groupId:e}))})}function tk({children:e,className:t,defaultLayout:n,disableCursor:i,disabled:o,elementRef:d,groupRef:h,id:l,onLayoutChange:u,onLayoutChanged:f,orientation:v="horizontal",resizeTargetMinimumSize:g={coarse:20,fine:10},style:S,...w}){const E=N.useRef({onLayoutChange:{},onLayoutChanged:{}}),x=Bc(H=>{Ya(E.current.onLayoutChange,H)||(E.current.onLayoutChange=H,u?.(H))}),m=Bc(H=>{Ya(E.current.onLayoutChanged,H)||(E.current.onLayoutChanged=H,f?.(H))}),y=kg(l),b=N.useRef(null),[_,k]=w7(),j=N.useRef({lastExpandedPanelSizes:{},layouts:{},panels:[],resizeTargetMinimumSize:g,separators:[]}),T=Cg(b,d);k7(y,h);const D=Bc((H,Q)=>{const F=Xa(),J=GS(H),ie=ua(H);if(ie){let X=!1;return F.state==="active"&&(X=F.hitRegions.some(de=>de.group===J)),{flexGrow:ie.layout[Q]??1,pointerEvents:X?"none":void 0}}if(n?.[Q])return{flexGrow:n?.[Q]}}),I=Eg({defaultLayout:n,disableCursor:i}),L=N.useMemo(()=>({get disableCursor(){return!!I.disableCursor},getPanelStyles:D,id:y,orientation:v,registerPanel:H=>{const Q=j.current;return Q.panels=Pm(v,[...Q.panels,H]),k(),()=>{Q.panels=Q.panels.filter(F=>F!==H),k()}},registerSeparator:H=>{const Q=j.current;return Q.separators=Pm(v,[...Q.separators,H]),k(),()=>{Q.separators=Q.separators.filter(F=>F!==H),k()}},updatePanelProps:(H,{disabled:Q})=>{const F=j.current.panels.find(X=>X.id===H);F&&(F.panelConstraints.disabled=Q);const J=GS(y),ie=ua(y);J&&ie&&wr(J,{...ie,derivedPanelConstraints:Om(J)})},updateSeparatorProps:(H,{disabled:Q,disableDoubleClick:F})=>{const J=j.current.separators.find(ie=>ie.id===H);J&&(J.disabled=Q,J.disableDoubleClick=F)}}),[D,y,k,v,I]),q=N.useRef(null);return so(()=>{const H=b.current;if(H===null)return;const Q=j.current;let F;if(I.defaultLayout!==void 0&&Object.keys(I.defaultLayout).length===Q.panels.length){F={};for(const P of Q.panels){const B=I.defaultLayout[P.id];B!==void 0&&(F[P.id]=B)}}const J={disabled:!!o,element:H,id:y,mutableState:{defaultLayout:F,disableCursor:!!I.disableCursor,expandedPanelSizes:j.current.lastExpandedPanelSizes,layouts:j.current.layouts},orientation:v,panels:Q.panels,resizeTargetMinimumSize:Q.resizeTargetMinimumSize,separators:Q.separators};q.current=J;const ie=x7(J),{defaultLayoutDeferred:X,derivedPanelConstraints:de,layout:fe}=ua(J.id,!0);!X&&de.length>0&&(x(fe),m(fe));const $=_g(y,P=>{const{defaultLayoutDeferred:B,derivedPanelConstraints:K,layout:le}=P.next;if(B||K.length===0)return;const me=J.panels.map(({id:Ee})=>Ee).join(",");J.mutableState.layouts[me]=le,K.forEach(Ee=>{if(Ee.collapsible){const{layout:se}=P.prev??{};if(se){const Z=Ts(Ee.collapsedSize,le[Ee.panelId]),ge=Ts(Ee.collapsedSize,se[Ee.panelId]);Z&&!ge&&(J.mutableState.expandedPanelSizes[Ee.panelId]=se[Ee.panelId])}}});const be=Xa().state!=="active";x(le),be&&m(le)});return()=>{q.current=null,ie(),$()}},[o,y,m,x,v,_,I]),N.useEffect(()=>{const H=q.current;H&&(H.mutableState.defaultLayout=n,H.mutableState.disableCursor=!!i)}),r.jsx(ek.Provider,{value:L,children:r.jsx("div",{...w,className:t,"data-group":!0,"data-testid":y,id:y,ref:T,style:{height:"100%",width:"100%",overflow:"hidden",...S,display:"flex",flexDirection:v==="horizontal"?"row":"column",flexWrap:"nowrap",touchAction:v==="horizontal"?"pan-y":"pan-x"},children:e})})}tk.displayName="Group";function Ng(){const e=N.useContext(ek);return Bn(e,"Group Context not found; did you render a Panel or Separator outside of a Group?"),e}function C7(e,t){const{id:n}=Ng(),i=N.useRef({collapse:rm,expand:rm,getSize:()=>({asPercentage:0,inPixels:0}),isCollapsed:()=>!1,resize:rm});N.useImperativeHandle(t,()=>i.current,[]),so(()=>{Object.assign(i.current,G1({groupId:n,panelId:e}))})}function Bm({children:e,className:t,collapsedSize:n="0%",collapsible:i=!1,defaultSize:o,disabled:d,elementRef:h,groupResizeBehavior:l="preserve-relative-size",id:u,maxSize:f="100%",minSize:v="0%",onResize:g,panelRef:S,style:w,...E}){const x=!!u,m=kg(u),y=Eg({disabled:d}),b=N.useRef(null),_=Cg(b,h),{getPanelStyles:k,id:j,orientation:T,registerPanel:D,updatePanelProps:I}=Ng(),L=g!==null,q=Bc((J,ie,X)=>{g?.(J,u,X)});so(()=>{const J=b.current;if(J!==null){const ie={element:J,id:m,idIsStable:x,mutableValues:{expandToSize:void 0,prevSize:void 0},onResize:L?q:void 0,panelConstraints:{groupResizeBehavior:l,collapsedSize:n,collapsible:i,defaultSize:o,disabled:y.disabled,maxSize:f,minSize:v}};return D(ie)}},[l,n,i,o,L,m,x,f,v,q,D,y]),N.useEffect(()=>{I(m,{disabled:d})},[d,m,I]),C7(m,S);const H=()=>{const J=k(j,m);if(J)return JSON.stringify(J)},Q=N.useSyncExternalStore(J=>_g(j,J),H,H);let F;return Q?F=JSON.parse(Q):o?F={flexGrow:void 0,flexShrink:void 0,flexBasis:o}:F={flexGrow:1},r.jsx("div",{...E,"data-disabled":d||void 0,"data-panel":!0,"data-testid":m,id:m,ref:_,style:{...E7,display:"flex",flexBasis:0,flexShrink:1,overflow:"visible",...F},children:r.jsx("div",{className:t,style:{maxHeight:"100%",maxWidth:"100%",flexGrow:1,overflow:"auto",...w,touchAction:T==="horizontal"?"pan-y":"pan-x"},children:e})})}Bm.displayName="Panel";const E7={minHeight:0,maxHeight:"100%",height:"auto",minWidth:0,maxWidth:"100%",width:"auto",border:"none",borderWidth:0,padding:0,margin:0};function N7({layout:e,panelConstraints:t,panelId:n,panelIndex:i}){let o,d;const h=e[n],l=t.find(u=>u.panelId===n);if(l){const u=l.maxSize,f=l.collapsible?l.collapsedSize:l.minSize,v=[i,i+1];d=Za({layout:Hc({delta:f-h,initialLayout:e,panelConstraints:t,pivotIndices:v,prevLayout:e}),panelConstraints:t})[n],o=Za({layout:Hc({delta:u-h,initialLayout:e,panelConstraints:t,pivotIndices:v,prevLayout:e}),panelConstraints:t})[n]}return{valueControls:n,valueMax:o,valueMin:d,valueNow:h}}function nk({children:e,className:t,disabled:n,disableDoubleClick:i,elementRef:o,id:d,style:h,...l}){const u=kg(d),f=Eg({disabled:n,disableDoubleClick:i}),[v,g]=N.useState({}),[S,w]=N.useState("inactive"),E=N.useRef(null),x=Cg(E,o),{disableCursor:m,id:y,orientation:b,registerSeparator:_,updateSeparatorProps:k}=Ng(),j=b==="horizontal"?"vertical":"horizontal";so(()=>{const D=E.current;if(D!==null){const I={disabled:f.disabled,disableDoubleClick:f.disableDoubleClick,element:D,id:u},L=_(I),q=p7(Q=>{w(Q.next.state!=="inactive"&&Q.next.hitRegions.some(F=>F.separator===I)?Q.next.state:"inactive")}),H=_g(y,Q=>{const{derivedPanelConstraints:F,layout:J,separatorToPanels:ie}=Q.next,X=ie.get(I);if(X){const de=X[0],fe=X.indexOf(de);g(N7({layout:J,panelConstraints:F,panelId:de.id,panelIndex:fe}))}});return()=>{q(),H(),L()}}},[y,u,_,f]),N.useEffect(()=>{k(u,{disabled:n,disableDoubleClick:i})},[n,i,u,k]);let T;return n&&!m&&(T="not-allowed"),r.jsx("div",{...l,"aria-controls":v.valueControls,"aria-disabled":n||void 0,"aria-orientation":j,"aria-valuemax":v.valueMax,"aria-valuemin":v.valueMin,"aria-valuenow":v.valueNow,children:e,className:t,"data-separator":n?"disabled":S,"data-testid":u,id:u,ref:x,role:"separator",style:{flexBasis:"auto",cursor:T,...h,flexGrow:0,flexShrink:0,touchAction:"none"},tabIndex:n?void 0:0})}nk.displayName="Separator";function j7({direction:e,first:t,second:n,onReset:i}){return r.jsxs(tk,{orientation:e,className:`split-pane split-${e}`,children:[r.jsx(Bm,{defaultSize:50,minSize:20,children:r.jsx("div",{className:"split-panel-content",children:t})}),r.jsx(nk,{className:"split-resize-handle",onDoubleClick:i}),r.jsx(Bm,{defaultSize:50,minSize:20,children:r.jsx("div",{className:"split-panel-content",children:n})})]})}function A7({viewMode:e,setViewMode:t,splitMode:n,setSplitMode:i,persistSplitMode:o,showChatTab:d=!0,showTerminalTab:h=!0,showConsoleTab:l,unreadSystemCount:u,checkpointsOpen:f,setCheckpointsOpen:v}){const g=N.useRef(null),[S,w]=N.useState(!1),[E,x]=N.useState(!1),m=N.useRef({isDragging:!1,startX:0,scrollLeft:0}),y=N.useCallback(()=>{const T=g.current;T&&(w(T.scrollLeft>1),x(T.scrollLeft<T.scrollWidth-T.clientWidth-1))},[]);N.useEffect(()=>{const T=g.current;if(!T)return;y();let D;return typeof ResizeObserver<"u"&&(D=new ResizeObserver(y),D.observe(T)),T.addEventListener("scroll",y,{passive:!0}),()=>{D?.disconnect(),T.removeEventListener("scroll",y)}},[y,l,u]);const b=N.useCallback(T=>{const D=g.current;if(!D)return;const I=D.querySelector(".view-tab")?.getBoundingClientRect().width??100;D.scrollBy({left:T*(I+8),behavior:"smooth"})},[]),_=N.useCallback(T=>{if(T.target.closest("button"))return;const D=g.current;D&&(m.current={isDragging:!0,startX:T.clientX,scrollLeft:D.scrollLeft},D.setPointerCapture(T.pointerId),D.style.cursor="grabbing")},[]),k=N.useCallback(T=>{if(!m.current.isDragging)return;const D=g.current;if(!D)return;const I=T.clientX-m.current.startX;D.scrollLeft=m.current.scrollLeft-I},[]),j=N.useCallback(T=>{if(!m.current.isDragging)return;m.current.isDragging=!1;const D=g.current;D&&(D.releasePointerCapture(T.pointerId),D.style.cursor="")},[]);return r.jsxs("div",{className:"view-switch-wrapper",children:[S&&r.jsx("button",{className:"view-switch-arrow view-switch-arrow-left",onClick:()=>b(-1),type:"button","aria-label":"Scroll tabs left",children:"‹"}),r.jsxs("div",{className:"view-switch",ref:g,onPointerDown:_,onPointerMove:k,onPointerUp:j,onPointerCancel:j,children:[d&&r.jsx("button",{className:`view-tab${e==="chat"&&!n?" active":""}`,onClick:()=>{t("chat"),i(null),o(null)},type:"button",children:"Chat"}),h&&r.jsx("button",{className:`view-tab${e==="terminal"&&!n?" active":""}`,onClick:()=>{t("terminal"),i(null),o(null)},type:"button",children:"Terminal"}),d&&h&&r.jsx("button",{className:`view-tab${n?" active":""}`,onClick:()=>{const T=n?null:"horizontal";i(T),o(T)},type:"button",title:`Split view (${yr("Cmd+\\")})`,children:"Split"}),r.jsx("button",{className:`view-tab${e==="files"?" active":""}`,onClick:()=>t("files"),type:"button",children:"Files"}),r.jsxs("button",{className:`view-tab${e==="system"?" active":""}`,onClick:()=>{t("system"),i(null),o(null)},type:"button",children:["System",u>0&&r.jsx("span",{className:"system-badge",children:u})]}),l&&r.jsx("button",{className:`view-tab${e==="console"?" active":""}`,onClick:()=>{t("console"),i(null),o(null)},type:"button",children:"Console"}),r.jsx("button",{className:`view-tab${e==="snapshots"?" active":""}`,onClick:()=>{t("snapshots"),i(null),o(null)},type:"button",children:"Snapshots"}),r.jsx("button",{className:`view-tab${e==="pool"?" active":""}`,onClick:()=>{t("pool"),i(null),o(null)},type:"button",children:"Pool"}),r.jsx("button",{className:`view-tab${e==="pages"?" active":""}`,onClick:()=>{t("pages"),i(null),o(null)},type:"button",children:"Pages"}),r.jsx("div",{className:"view-switch-spacer"}),r.jsx("button",{className:`view-tab view-tab-right${f?" active":""}`,onClick:()=>v(T=>!T),type:"button",title:"Toggle checkpoint timeline",children:"Checkpoints"}),r.jsx("button",{className:`view-tab${e==="diff"?" active":""}`,onClick:()=>t("diff"),type:"button",children:"Diff"})]}),E&&r.jsx("button",{className:"view-switch-arrow view-switch-arrow-right",onClick:()=>b(1),type:"button","aria-label":"Scroll tabs right",children:"›"})]})}const R7=[];function c0(e){const t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);if(n<60)return`${n}s`;const i=Math.floor(n/60),o=n%60;if(i<60)return`${i}m ${o}s`;const d=Math.floor(i/60),h=i%60;return`${d}h ${h}m`}function T7({agent:e}){const[t,n]=N.useState(()=>c0(e.startedAt));return N.useEffect(()=>{const i=setInterval(()=>{n(c0(e.startedAt))},1e3);return()=>clearInterval(i)},[e.startedAt]),r.jsxs("div",{className:"agent-card","data-testid":"agent-card",children:[r.jsxs("div",{className:"agent-card-header",children:[r.jsx("span",{className:"agent-pulse"}),r.jsx("span",{className:"agent-id",title:e.toolUseId,children:e.toolUseId.slice(0,12)}),r.jsx("span",{className:"agent-elapsed",children:t})]}),r.jsx("div",{className:"agent-description",children:e.description})]})}function I7(){const e=V(t=>{const n=t.activeSessionId;return!n||!t.sessionStates[n]?R7:t.sessionStates[n].activeAgents});return r.jsxs("div",{className:"agent-monitor-panel","data-testid":"agent-monitor-panel",children:[r.jsx("div",{className:"agent-monitor-header",children:r.jsxs("span",{className:"agent-monitor-title",children:["Active Agents",e.length>0&&r.jsx("span",{className:"agent-count",children:e.length})]})}),r.jsx("div",{className:"agent-monitor-body",children:e.length===0?r.jsx("div",{className:"agent-empty","data-testid":"agent-empty",children:"No agents currently running."}):e.map(t=>r.jsx(T7,{agent:t},t.toolUseId))})]})}function u0({label:e="Loading session...",className:t}){return r.jsxs("div",{className:`session-loading-skeleton${t?` ${t}`:""}`,"data-testid":"session-loading-skeleton",children:[r.jsx("p",{className:"skeleton-label",children:e}),r.jsx("div",{className:"skeleton-line skeleton-line-wide"}),r.jsx("div",{className:"skeleton-line skeleton-line-medium"}),r.jsx("div",{className:"skeleton-line skeleton-line-narrow"}),r.jsx("div",{className:"skeleton-line skeleton-line-wide"}),r.jsx("div",{className:"skeleton-line skeleton-line-medium"})]})}function M7({error:e,logs:t,onRetry:n,onStartServer:i}){const o=t&&t.length>0;return r.jsx("div",{className:"startup-error-screen","data-testid":"startup-error-screen",children:r.jsxs("div",{className:"startup-error-content",children:[r.jsx("h2",{className:"startup-error-title",children:"Server Failed to Start"}),r.jsx("p",{className:"startup-error-message",children:e}),o&&r.jsxs("div",{className:"startup-error-logs","data-testid":"startup-error-logs",children:[r.jsx("h3",{className:"startup-error-logs-title",children:"Server Logs"}),r.jsx("pre",{className:"startup-error-logs-content",children:t.map((d,h)=>r.jsx("div",{children:d},h))})]}),r.jsxs("div",{className:"startup-error-actions",children:[i&&r.jsx("button",{className:"startup-error-retry-btn startup-error-start-btn",onClick:i,type:"button","aria-label":"Start Server","data-testid":"error-start-server-button",children:"Start Server"}),r.jsx("button",{className:"startup-error-retry-btn",onClick:n,type:"button","aria-label":"Retry",children:"Reconnect"})]})]})})}const D7=["debug","info","warn","error","audit"];function d0(){const e=V(_=>_.logEntries),t=V(_=>_.clearLogEntries),n=V(_=>_.activeSessionId),i=V(_=>_.sessions.length),[o,d]=N.useState(new Set(["info","warn","error","audit"])),[h,l]=N.useState(!0),[u,f]=N.useState(!0),[v,g]=N.useState(!1),S=N.useRef(null),w=N.useRef(null),E=i>1,x=e.filter(_=>o.has(_.level)?E&&h&&n?!_.sessionId||_.sessionId===n:!0:!1),m=x.length>0?x[x.length-1].id:null;N.useEffect(()=>{u&&S.current&&(S.current.scrollTop=S.current.scrollHeight)},[m,u]),N.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const y=N.useCallback(_=>{d(k=>{const j=new Set(k);return j.has(_)?j.delete(_):j.add(_),j})},[]),b=N.useCallback(()=>{const _=x.map(k=>`${f0(k.timestamp)} [${k.level.toUpperCase()}] [${k.component}] ${k.message}`).join(`
|
|
104
|
-
`);navigator.clipboard&&navigator.clipboard.writeText(_).then(()=>{g(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>g(!1),2e3)}).catch(()=>{})},[x]);return r.jsxs("div",{className:"log-panel","data-testid":"log-panel",children:[r.jsxs("div",{className:"log-toolbar","data-testid":"log-toolbar",children:[r.jsx("div",{className:"log-filters",children:D7.map(_=>r.jsx("button",{type:"button",className:`log-filter-btn log-filter-${_}${o.has(_)?" active":""}`,"data-testid":`log-filter-${_}`,"aria-pressed":o.has(_),"aria-label":`Filter ${_} messages`,onClick:()=>y(_),children:_},_))}),r.jsxs("div",{className:"log-actions",children:[E&&r.jsxs("label",{className:"log-autoscroll","data-testid":"log-session-filter",children:[r.jsx("input",{type:"checkbox",checked:h,onChange:_=>l(_.target.checked)}),"This session"]}),r.jsxs("label",{className:"log-autoscroll","data-testid":"log-autoscroll",children:[r.jsx("input",{type:"checkbox",checked:u,onChange:_=>f(_.target.checked)}),"Auto-scroll"]}),r.jsx("button",{type:"button",className:"log-action-btn","data-testid":"log-copy",onClick:b,children:v?"Copied!":"Copy"}),r.jsx("button",{type:"button",className:"log-action-btn","data-testid":"log-clear",onClick:t,children:"Clear"})]})]}),r.jsx("div",{className:"log-list",ref:S,"data-testid":"log-list",role:"log","aria-live":"polite","aria-label":"Log entries",children:x.length===0?r.jsx("div",{className:"log-empty","data-testid":"log-empty",children:"No log entries"}):x.map(_=>r.jsxs("div",{className:`log-line log-level-${_.level}`,"data-testid":"log-line",children:[r.jsx("span",{className:"log-time",children:f0(_.timestamp)}),r.jsx("span",{className:`log-level log-level-tag-${_.level}`,children:_.level.toUpperCase()}),r.jsxs("span",{className:"log-component",children:["[",_.component,"]"]}),r.jsx("span",{className:"log-message",children:_.message})]},_.id))})]})}function f0(e){return new Date(e).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function L7(){const[e,t]=N.useState(null),[n,i]=N.useState(null),[o,d]=N.useState(!0),[h,l]=N.useState(!1),[u,f]=N.useState(!1),[v,g]=N.useState(null),[S,w]=N.useState(null),E=V(k=>k.serverPhase),x=V(k=>k.tunnelProgress),m=E==="tunnel_warming"||E==="tunnel_verifying";N.useEffect(()=>{const k=li();if(!k){i("No auth token available"),d(!1);return}let j=!1,T=null;async function D(){try{const I=await fetch("/connect",{headers:{Authorization:`Bearer ${k}`}});if(I.ok){const L=await I.json();j||(t(L),l(!1))}else{const q=(await I.json().catch(()=>({error:"Request failed"}))).error||`HTTP ${I.status}`;if(I.status===404&&!j){l(!0),d(!1),T=setTimeout(D,3e3);return}j||i(q)}}catch(I){j||i(I instanceof Error?I.message:"Failed to fetch")}finally{j||d(!1)}try{const I=await fetch("/qr",{headers:{Authorization:`Bearer ${k}`}});if(I.ok){const L=await I.text();j||g(L)}}catch{}}return D(),()=>{j=!0,T&&clearTimeout(T)}},[]),N.useEffect(()=>{if(E!=="ready"||e)return;const k=li();if(!k)return;let j=!1;async function T(){try{const D=await fetch("/connect",{headers:{Authorization:`Bearer ${k}`}});if(D.ok){const I=await D.json();j||(t(I),l(!1))}}catch{}try{const D=await fetch("/qr",{headers:{Authorization:`Bearer ${k}`}});if(D.ok){const I=await D.text();j||g(I)}}catch{}}return T(),()=>{j=!0}},[E,e]),N.useEffect(()=>{const k=li();if(!k)return;const j=async()=>{try{const I=await fetch("/qr",{headers:{Authorization:`Bearer ${k}`}});I.ok&&g(await I.text())}catch{}},T=()=>{document.visibilityState==="visible"&&j()};document.addEventListener("visibilitychange",T);const D=setInterval(j,5e4);return()=>{document.removeEventListener("visibilitychange",T),clearInterval(D)}},[]);const y=N.useRef(null);N.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const b=N.useCallback((k,j)=>{navigator.clipboard&&navigator.clipboard.writeText(k).then(()=>{w(j),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>w(null),2e3)}).catch(()=>{})},[]);if(o)return r.jsxs("div",{className:"console-page",children:[r.jsx("h2",{children:"Connection Info"}),r.jsx("div",{className:"console-loading",children:"Loading..."})]});if(n)return r.jsxs("div",{className:"console-page",children:[r.jsx("h2",{children:"Connection Info"}),r.jsx("div",{className:"console-error",children:n})]});if(!e){const k=m||h,j=x?`Tunnel warming up… (attempt ${x.attempt}/${x.maxAttempts}) — QR will appear shortly`:"Tunnel warming up… — QR will appear shortly";return r.jsxs("div",{className:"console-page",children:[r.jsx("h2",{children:"Connection Info"}),k?r.jsxs("div",{className:"console-tunnel-setup",children:[r.jsx("div",{className:"console-tunnel-spinner"}),r.jsx("span",{children:j})]}):r.jsx("div",{className:"console-error",children:"No connection info available"}),r.jsx("h2",{children:"Server Logs"}),r.jsx(d0,{})]})}const _=`${e.httpUrl}/dashboard?token=${encodeURIComponent(e.apiToken)}`;return r.jsxs("div",{className:"console-page",children:[r.jsx("h2",{children:"Connection Info"}),r.jsxs("div",{className:"console-card",children:[r.jsxs("div",{className:"console-row",children:[r.jsx("span",{className:"console-label",children:"Tunnel URL"}),r.jsx("span",{className:"console-value","data-testid":"tunnel-url",children:e.httpUrl}),r.jsx("button",{className:"console-copy-btn","data-testid":"copy-tunnel-url",onClick:()=>b(e.httpUrl,"tunnel"),type:"button",children:S==="tunnel"?"Copied!":"Copy"})]}),r.jsxs("div",{className:"console-row",children:[r.jsx("span",{className:"console-label",children:"Dashboard"}),r.jsxs("span",{className:"console-value","data-testid":"dashboard-url",children:[e.httpUrl,"/dashboard"]}),r.jsx("button",{className:"console-copy-btn","data-testid":"copy-dashboard-url",onClick:()=>b(_,"dashboard"),type:"button",children:S==="dashboard"?"Copied!":"Copy"}),r.jsx("a",{href:_,target:"_blank",rel:"noopener noreferrer",className:"console-open-btn",children:"Open"})]}),r.jsxs("div",{className:"console-row",children:[r.jsx("span",{className:"console-label",children:"API Token"}),r.jsx("span",{className:"console-value console-token","data-testid":"token-value",children:u?e.apiToken:"••••••••"}),r.jsx("button",{className:"console-copy-btn","data-testid":"token-reveal",onClick:()=>f(k=>!k),type:"button",children:u?"Hide":"Reveal"}),r.jsx("button",{className:"console-copy-btn","data-testid":"copy-token",onClick:()=>b(e.apiToken,"token"),type:"button",children:S==="token"?"Copied!":"Copy"})]}),r.jsxs("div",{className:"console-row",children:[r.jsx("span",{className:"console-label",children:"Tunnel Mode"}),r.jsx("span",{className:"console-value",children:e.tunnelMode})]})]}),v&&r.jsxs("div",{className:"console-qr-section",children:[r.jsx("h3",{children:"Pair Mobile App"}),r.jsx("div",{className:"console-qr","data-testid":"qr-container",dangerouslySetInnerHTML:{__html:_f.sanitize(v,{USE_PROFILES:{svg:!0}})}}),r.jsx("p",{className:"console-qr-hint",children:"Scan with the Chroxy app to pair your phone"})]}),r.jsx("h2",{children:"Server Logs"}),r.jsx(d0,{})]})}function O7(e){if(!e)return"";const t=Date.parse(e);if(!Number.isFinite(t))return e;const n=new Date(t),i=new Date;return n.getFullYear()===i.getFullYear()&&n.getMonth()===i.getMonth()&&n.getDate()===i.getDate()?n.toLocaleTimeString():n.toLocaleString()}function P7({snapshot:e,onDelete:t,isDeleting:n}){const[i,o]=N.useState(!1),d=O7(e.createdAt);return r.jsxs("div",{className:"env-card","data-testid":`snapshot-card-${e.slug}`,children:[r.jsxs("div",{className:"env-card-header",children:[r.jsx("span",{className:"env-card-name","data-testid":`snapshot-name-${e.slug}`,children:e.name||e.slug}),d&&r.jsx("span",{className:"env-status-badge","data-testid":`snapshot-created-${e.slug}`,style:{color:"var(--text-secondary)"},children:d})]}),r.jsxs("div",{className:"env-card-details",children:[r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Tag"}),r.jsx("span",{className:"env-card-value",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.85em"},"data-testid":`snapshot-tag-${e.slug}`,children:e.tag})]}),e.sourceCwd&&r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"CWD"}),r.jsx("span",{className:"env-card-value",children:e.sourceCwd})]}),e.sourceImage&&r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Base"}),r.jsx("span",{className:"env-card-value",children:e.sourceImage})]}),e.sourceSessionId&&r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Session"}),r.jsx("span",{className:"env-card-value",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.85em"},children:e.sourceSessionId})]})]}),r.jsx("div",{className:"env-card-actions",children:i?r.jsxs("div",{className:"env-confirm-row",children:[r.jsx("span",{children:"Delete this snapshot?"}),r.jsx("button",{className:"btn-env-confirm-yes","data-testid":`snapshot-confirm-yes-${e.slug}`,onClick:()=>{o(!1),t(e.slug)},children:"Yes"}),r.jsx("button",{className:"btn-env-confirm-no","data-testid":`snapshot-confirm-no-${e.slug}`,onClick:()=>o(!1),children:"No"})]}):r.jsx("button",{className:"btn-env-destroy","data-testid":`snapshot-delete-${e.slug}`,onClick:()=>o(!0),disabled:n,title:"Delete snapshot (removes Docker image + metadata)",children:n?"Deleting…":"Delete"})})]})}function B7({fetchImpl:e,getToken:t}={}){const[n,i]=N.useState([]),[o,d]=N.useState(!0),[h,l]=N.useState(null),[u,f]=N.useState(null),[v,g]=N.useState(null),S=e??((m,y)=>window.fetch(m,y)),w=t??li,E=N.useCallback(async()=>{d(!0),l(null);const m=w();try{const y=await S("/api/snapshots",{headers:m?{Authorization:`Bearer ${m}`}:void 0});if(!y.ok){const _=await y.json().catch(()=>({error:`HTTP ${y.status}`}));throw new Error(_.error||`HTTP ${y.status}`)}const b=await y.json();i(Array.isArray(b.snapshots)?b.snapshots:[])}catch(y){l(y instanceof Error?y.message:"Failed to load snapshots")}finally{d(!1)}},[S,w]),x=N.useCallback(async m=>{g(m),l(null),f(null);const y=w();try{const b=await S(`/api/snapshots/${encodeURIComponent(m)}`,{method:"DELETE",headers:y?{Authorization:`Bearer ${y}`}:void 0});if(!b.ok){const k=await b.json().catch(()=>({error:`HTTP ${b.status}`}));throw new Error(k.error||`HTTP ${b.status}`)}const _=await b.json().catch(()=>({}));if(i(k=>k.filter(j=>j.slug!==m)),_.imageRemoved===!1){const k=_.tag||m;f(`Snapshot deleted, but its Docker image (${k}) could not be removed — it may still be in use or the daemon is unavailable. Run \`docker rmi ${k}\` to clean it up manually.`)}E()}catch(b){l(b instanceof Error?b.message:"Failed to delete snapshot")}finally{g(null)}},[E,S,w]);return N.useEffect(()=>{E()},[E]),r.jsxs("div",{className:"environment-panel","data-testid":"snapshots-panel",children:[r.jsxs("div",{className:"env-panel-header",children:[r.jsx("h2",{children:"Snapshots"}),r.jsx("button",{className:"btn-env-new","data-testid":"snapshots-refresh",onClick:()=>{E()},disabled:o,children:o?"Loading…":"Refresh"})]}),h&&r.jsx("div",{className:"env-empty","data-testid":"snapshots-error",style:{color:"var(--status-error, #ef4444)"},children:h}),u&&r.jsxs("div",{className:"env-empty","data-testid":"snapshots-warning",role:"status","aria-live":"polite",style:{color:"var(--status-warning, #f59e0b)",display:"flex",alignItems:"flex-start",gap:"0.75rem",justifyContent:"space-between"},children:[r.jsx("span",{children:u}),r.jsx("button",{className:"btn-env-new","data-testid":"snapshots-warning-dismiss",onClick:()=>f(null),"aria-label":"Dismiss warning",title:"Dismiss",children:"Dismiss"})]}),!h&&!o&&n.length===0&&r.jsxs("div",{className:"env-empty","data-testid":"snapshots-empty",children:[r.jsx("p",{children:"No snapshots saved yet."}),r.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9em"},children:"Snapshots are committed Docker images from a docker-byok session's writable layer. Take one from a live session to preserve installed packages, auth state, or scratch files for later reuse."})]}),r.jsx("div",{className:"env-grid",children:n.map(m=>r.jsx(P7,{snapshot:m,onDelete:x,isDeleting:v===m.slug},m.slug))})]})}const $7=5e3;function z7(e){return typeof e!="number"||!Number.isFinite(e)?"—":`${(e*100).toFixed(1)}%`}function U7(e){if(!Number.isFinite(e)||e<0)return"0s";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),i=t%60;return n<60?i?`${n}m ${i}s`:`${n}m`:`${Math.floor(n/60)}h ${n%60}m`}function q7(e){return Number.isFinite(e)?new Date(e).toLocaleTimeString():""}function H7({fetchImpl:e,getToken:t,pollMs:n}={}){const[i,o]=N.useState(null),[d,h]=N.useState(!0),[l,u]=N.useState(null),f=e??((_,k)=>window.fetch(_,k)),v=t??li,g=n??$7,S=N.useCallback(async()=>{u(null);const _=v();try{const k=await f("/api/pool/stats",{headers:_?{Authorization:`Bearer ${_}`}:void 0});if(!k.ok){const T=await k.json().catch(()=>({error:`HTTP ${k.status}`}));throw new Error(T.error||`HTTP ${k.status}`)}const j=await k.json();o(j)}catch(k){u(k instanceof Error?k.message:"Failed to load pool stats")}finally{h(!1)}},[f,v]),w=N.useRef(S);w.current=S,N.useEffect(()=>{if(w.current(),g<=0)return;const _=setInterval(()=>{w.current()},g);return()=>clearInterval(_)},[g]);const E=i?.enabled===!0,x=i?.buckets??[],m=i?.recentEvictions??[],y=i?.evictionsByReason??{},b=Object.entries(y).sort((_,k)=>k[1]-_[1]);return r.jsxs("div",{className:"environment-panel","data-testid":"pool-stats-panel",children:[r.jsxs("div",{className:"env-panel-header",children:[r.jsx("h2",{children:"Container Pool"}),r.jsx("button",{className:"btn-env-new","data-testid":"pool-stats-refresh",onClick:()=>{S()},disabled:d,children:d?"Loading…":"Refresh"})]}),l&&r.jsx("div",{className:"env-empty","data-testid":"pool-stats-error",style:{color:"var(--status-error, #ef4444)"},children:l}),!l&&i&&!E&&r.jsxs("div",{className:"env-empty","data-testid":"pool-stats-disabled",children:[r.jsx("p",{children:"The docker-byok container pool is disabled."}),r.jsxs("p",{style:{color:"var(--text-secondary)",fontSize:"0.9em"},children:["Set ",r.jsx("code",{children:"CHROXY_DOCKER_BYOK_POOL=1"})," on the server to enable cross-session container reuse, then this panel will show pool size, hit rate, and recent evictions."]})]}),!l&&E&&i&&r.jsxs("div",{"data-testid":"pool-stats-body",children:[r.jsx("div",{className:"env-card","data-testid":"pool-stats-summary",children:r.jsxs("div",{className:"env-card-details",children:[r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Hit rate"}),r.jsx("span",{className:"env-card-value","data-testid":"pool-stats-hitrate",children:z7(i.hitRate)})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Hits / Misses"}),r.jsxs("span",{className:"env-card-value","data-testid":"pool-stats-hitmiss",children:[i.hits??0," / ",i.misses??0]})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Parked containers"}),r.jsx("span",{className:"env-card-value","data-testid":"pool-stats-total-size",children:i.totalSize??0})]}),typeof i.shutdowns=="number"&&i.shutdowns>0&&r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Shutdowns"}),r.jsx("span",{className:"env-card-value",children:i.shutdowns})]})]})}),r.jsx("h3",{style:{marginTop:"1rem"},children:"Parked by key"}),x.length===0?r.jsx("div",{className:"env-empty","data-testid":"pool-stats-buckets-empty",children:"No containers parked."}):r.jsx("div",{className:"env-grid",children:x.map(_=>r.jsxs("div",{className:"env-card","data-testid":`pool-bucket-${_.key}`,children:[r.jsx("div",{className:"env-card-header",children:r.jsx("span",{className:"env-card-name",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.8em",wordBreak:"break-all"},children:_.key})}),r.jsxs("div",{className:"env-card-details",children:[r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Size"}),r.jsx("span",{className:"env-card-value",children:_.size})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Oldest idle"}),r.jsx("span",{className:"env-card-value",children:U7(_.oldestIdleMs)})]})]})]},_.key))}),r.jsx("h3",{style:{marginTop:"1rem"},children:"Evictions by reason"}),b.length===0?r.jsx("div",{className:"env-empty","data-testid":"pool-stats-evictions-empty",children:"No evictions recorded."}):r.jsx("div",{className:"env-card","data-testid":"pool-stats-evictions-by-reason",children:r.jsx("div",{className:"env-card-details",children:b.map(([_,k])=>r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label","data-testid":`pool-eviction-reason-${_}`,children:_}),r.jsx("span",{className:"env-card-value",children:k})]},_))})}),m.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("h3",{style:{marginTop:"1rem"},children:"Recent evictions"}),r.jsx("div",{className:"env-card","data-testid":"pool-stats-recent-evictions",children:r.jsx("div",{className:"env-card-details",children:m.slice().reverse().map((_,k)=>r.jsxs("div",{className:"env-card-row","data-testid":"pool-recent-eviction",children:[r.jsx("span",{className:"env-card-label",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.8em"},children:_.containerId?_.containerId.slice(0,12):"—"}),r.jsxs("span",{className:"env-card-value",children:[_.reason,Number.isFinite(_.timestamp)&&r.jsx("span",{style:{color:"var(--text-secondary)",marginLeft:"0.5rem"},children:q7(_.timestamp)})]})]},`${_.containerId??"x"}-${_.timestamp}-${k}`))})})]})]})]})}function F7(e){return!Number.isFinite(e)||e<0?"—":e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function K7(e){const t=Date.parse(e);return Number.isNaN(t)?"—":new Date(t).toLocaleString()}function W7({fetchImpl:e,getToken:t,copyImpl:n,origin:i}={}){const[o,d]=N.useState(null),[h,l]=N.useState(!0),[u,f]=N.useState(null),[v,g]=N.useState(null),[S,w]=N.useState(null),[E,x]=N.useState(!1),[m,y]=N.useState(""),[b,_]=N.useState(""),[k,j]=N.useState(!1),[T,D]=N.useState(null),[I,L]=N.useState(null),[q,H]=N.useState(!1),Q=e??((se,Z)=>window.fetch(se,Z)),F=t??li,J=n??Pc,ie=i??(typeof window<"u"?window.location.origin:""),X=N.useCallback(()=>{const se=F();return se?{Authorization:`Bearer ${se}`}:void 0},[F]),de=N.useCallback(async()=>{f(null),l(!0);try{const se=await Q("/api/pages",{headers:X()});if(!se.ok){const ge=await se.json().catch(()=>({error:`HTTP ${se.status}`}));throw new Error(ge.error||`HTTP ${se.status}`)}const Z=await se.json();d(Array.isArray(Z.pages)?Z.pages:[])}catch(se){f(se instanceof Error?se.message:"Failed to load pages")}finally{l(!1)}},[Q,X]),fe=N.useRef(de);fe.current=de;const $=N.useRef(null),P=N.useRef(null);N.useEffect(()=>(fe.current(),()=>{$.current&&clearTimeout($.current),P.current&&clearTimeout(P.current)}),[]);const B=N.useCallback(async se=>{await J(`${ie}${se.path}`)&&(g(se.slug),$.current&&clearTimeout($.current),$.current=setTimeout(()=>{$.current=null,g(ge=>ge===se.slug?null:ge)},1500))},[J,ie]),K=N.useCallback(async se=>{f(null),w(se);try{const Z=await Q(`/api/pages/${encodeURIComponent(se)}`,{method:"DELETE",headers:X()});if(!Z.ok){const ge=await Z.json().catch(()=>({error:`HTTP ${Z.status}`}));throw new Error(ge.error||`HTTP ${Z.status}`)}d(ge=>ge&&ge.filter(De=>De.slug!==se))}catch(Z){f(Z instanceof Error?Z.message:`Failed to delete ${se}`)}finally{w(Z=>Z===se?null:Z)}},[Q,X]),le=N.useCallback(async se=>{if(se){D(null);try{const Z=await se.text();_(Z),y(ge=>ge||se.name.replace(/\.html?$/i,""))}catch{D(`Could not read ${se.name}`)}}},[]),me=N.useCallback(async()=>{if(!b.trim()){D("Paste or load some HTML to publish.");return}D(null),L(null),H(!1),j(!0);try{const se=await Q("/api/pages",{method:"POST",headers:{...X()??{},"Content-Type":"application/json"},body:JSON.stringify({title:m.trim()||"Untitled",html:b})});if(!se.ok){const ge=await se.json().catch(()=>({error:`HTTP ${se.status}`}));throw new Error(ge.error||`HTTP ${se.status}`)}const Z=await se.json();Z.path?L(`${ie}${Z.path}`):D("Published, but the server returned no share URL."),y(""),_(""),await de()}catch(se){D(se instanceof Error?se.message:"Failed to publish")}finally{j(!1)}},[b,m,Q,X,ie,de]),be=N.useCallback(async()=>{if(!I)return;await J(I)&&(H(!0),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{P.current=null,H(!1)},1500))},[I,J]),Ee=o??[];return r.jsxs("div",{className:"environment-panel","data-testid":"pages-panel",children:[r.jsxs("div",{className:"env-panel-header",children:[r.jsx("h2",{children:"Pages"}),r.jsxs("div",{style:{display:"flex",gap:"0.5em"},children:[r.jsx("button",{className:"btn-env-new","data-testid":"pages-publish-toggle",onClick:()=>x(se=>!se),"aria-expanded":E,children:E?"Cancel":"+ Publish HTML"}),r.jsx("button",{className:"btn-env-new","data-testid":"pages-refresh",onClick:()=>{de()},disabled:h,children:h?"Loading…":"Refresh"})]})]}),E&&r.jsxs("div",{className:"env-card","data-testid":"pages-publish-form",style:{marginBottom:"0.75em"},children:[r.jsxs("div",{className:"env-card-details",children:[r.jsxs("label",{className:"env-card-row",style:{flexDirection:"column",alignItems:"stretch",gap:"0.25em"},children:[r.jsx("span",{className:"env-card-label",children:"Title"}),r.jsx("input",{type:"text","data-testid":"pages-publish-title",value:m,onChange:se=>y(se.target.value),placeholder:"Untitled",disabled:k})]}),r.jsxs("label",{className:"env-card-row",style:{flexDirection:"column",alignItems:"stretch",gap:"0.25em"},children:[r.jsx("span",{className:"env-card-label",children:"HTML"}),r.jsx("textarea",{"data-testid":"pages-publish-html",value:b,onChange:se=>_(se.target.value),placeholder:"Paste a self-contained HTML artifact, or load a .html file below",rows:6,disabled:k,style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.8em",resize:"vertical"}})]}),r.jsxs("label",{className:"env-card-row",style:{gap:"0.5em"},children:[r.jsx("span",{className:"env-card-label",children:"Load file"}),r.jsx("input",{type:"file",accept:".html,.htm,text/html","data-testid":"pages-publish-file",disabled:k,onChange:se=>{le(se.target.files?.[0])}})]})]}),T&&r.jsx("div",{className:"env-empty","data-testid":"pages-publish-error",style:{color:"var(--status-error, #ef4444)"},children:T}),I!==null&&r.jsxs("div",{className:"env-card-row","data-testid":"pages-publish-result",style:{gap:"0.5em",alignItems:"center"},children:[r.jsx("span",{className:"env-card-label",children:"Published"}),r.jsx("a",{href:I,target:"_blank",rel:"noreferrer","data-testid":"pages-publish-result-url",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.8em",wordBreak:"break-all"},children:I}),r.jsx("button",{className:"btn-env-action","data-testid":"pages-publish-result-copy",onClick:()=>{be()},children:q?"Copied!":"Copy link"})]}),r.jsx("div",{className:"env-card-actions",children:r.jsx("button",{className:"btn-env-action","data-testid":"pages-publish-submit",onClick:()=>{me()},disabled:k||!b.trim(),children:k?"Publishing…":"Publish"})})]}),u&&r.jsx("div",{className:"env-empty","data-testid":"pages-error",style:{color:"var(--status-error, #ef4444)"},children:u}),!u&&o&&Ee.length===0&&r.jsxs("div",{className:"env-empty","data-testid":"pages-empty",children:[r.jsx("p",{children:"No pages published yet."}),r.jsxs("p",{style:{color:"var(--text-secondary)",fontSize:"0.9em"},children:["Publish an HTML artifact with ",r.jsx("code",{children:"chroxy publish <file>"})," and it appears here with a shareable link."]})]}),Ee.length>0&&r.jsx("div",{className:"env-grid","data-testid":"pages-list",children:Ee.map(se=>r.jsxs("div",{className:"env-card","data-testid":`page-card-${se.slug}`,children:[r.jsx("div",{className:"env-card-header",children:r.jsx("span",{className:"env-card-name","data-testid":`page-title-${se.slug}`,children:se.title||se.slug})}),r.jsxs("div",{className:"env-card-details",children:[r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Slug"}),r.jsx("span",{className:"env-card-value",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.8em"},children:se.slug})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Created"}),r.jsx("span",{className:"env-card-value",children:K7(se.createdAt)})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Size"}),r.jsx("span",{className:"env-card-value",children:F7(se.bytes)})]})]}),r.jsxs("div",{className:"env-card-actions",children:[r.jsx("button",{className:"btn-env-action","data-testid":`page-copy-${se.slug}`,onClick:()=>{B(se)},children:v===se.slug?"Copied!":"Copy link"}),r.jsx("button",{className:"btn-env-action btn-env-danger","data-testid":`page-delete-${se.slug}`,onClick:()=>{K(se.slug)},disabled:S===se.slug,children:S===se.slug?"Deleting…":"Delete"})]})]},se.slug))})]})}const G7=[],V7={agent:"◆",shell:"$",tool:"⚙"},jc={agent:"Subagent",shell:"Background shell",tool:"Tool"},Md={running:"Running",blocked:"Blocked",done:"Done",failed:"Failed"};function sk(e){return e==="done"||e==="failed"}function h0(e){const t=Math.max(0,Math.floor(e/1e3)),n=t%60,i=Math.floor(t/60)%60,o=Math.floor(t/3600);return o>0?`${o}:${String(i).padStart(2,"0")}:${String(n).padStart(2,"0")}`:i>0?`${i}:${String(n).padStart(2,"0")}`:`${n}s`}function ik(e){for(const t of e)if(!sk(t.entry.status)||ik(t.children))return!0;return!1}function Y7(e,t){const[n,i]=N.useState(()=>t());return N.useEffect(()=>{if(!e)return;i(t());const o=window.setInterval(()=>i(t()),1e3);return()=>window.clearInterval(o)},[e,t]),n}function Z7({entry:e,depth:t,now:n,expanded:i,onToggleExpand:o,onCancelActivity:d,cancellingActivityIds:h,onJump:l}){const u=sk(e.status),f=e.status==="blocked",v=(u&&e.endedAt!==void 0?e.endedAt:n)-e.startedAt,g=`control-room-entry status-${e.status}`+(f?" control-room-entry-blocked":""),S=d!==void 0&&e.kind==="agent"&&!u,w=S&&(h?.has(e.id)??!1);return r.jsxs("li",{className:"control-room-entry-row","data-testid":`control-room-entry-${e.id}`,children:[r.jsxs("div",{className:"control-room-entry-rowline",children:[r.jsxs("button",{type:"button",className:g,style:{paddingLeft:6+t*14},"aria-expanded":i,"data-status":e.status,"data-testid":`control-room-entry-toggle-${e.id}`,onClick:()=>o(e.id),title:`${jc[e.kind]} · ${Md[e.status]}`,children:[r.jsx("span",{className:"control-room-entry-icon","aria-hidden":"true",children:V7[e.kind]}),r.jsx("span",{className:"control-room-entry-label","data-testid":`control-room-entry-label-${e.id}`,children:e.label||jc[e.kind]}),r.jsx("span",{className:`control-room-status-badge status-${e.status}`,"data-testid":`control-room-status-${e.id}`,role:"status","aria-label":`Status: ${Md[e.status]}`,children:Md[e.status]}),r.jsx("span",{className:"control-room-entry-elapsed","data-testid":`control-room-elapsed-${e.id}`,"aria-label":`Elapsed ${h0(v)}`,children:h0(v)})]}),S&&r.jsx("button",{type:"button",className:"control-room-cancel-btn","data-testid":`control-room-cancel-${e.id}`,onClick:()=>d(e.id),disabled:w,"aria-busy":w,title:w?"Cancelling…":`Cancel ${e.label||jc[e.kind]}`,"aria-label":w?"Cancelling subagent":`Cancel subagent ${e.label||""}`.trim(),children:w?"Cancelling…":"Cancel"}),l&&f&&r.jsx("button",{type:"button",className:"control-room-jump-btn","data-testid":`control-room-jump-${e.id}`,onClick:l,title:"Switch to this session to respond","aria-label":`Jump to the session blocked on ${e.label||jc[e.kind]}`,children:"Jump to session"})]}),i&&r.jsxs("div",{className:"control-room-entry-output","data-testid":`control-room-output-${e.id}`,children:[r.jsxs("div",{className:"control-room-output-row",children:[r.jsx("span",{className:"control-room-output-key",children:"Kind"}),r.jsx("span",{className:"control-room-output-val",children:jc[e.kind]})]}),r.jsxs("div",{className:"control-room-output-row",children:[r.jsx("span",{className:"control-room-output-key",children:"Status"}),r.jsx("span",{className:"control-room-output-val",children:Md[e.status]})]}),e.outputRef?r.jsxs("div",{className:"control-room-output-row",children:[r.jsx("span",{className:"control-room-output-key",children:"Output"}),r.jsxs("span",{className:"control-room-output-val control-room-output-ref","data-testid":`control-room-output-ref-${e.id}`,children:[e.outputRef.kind,": ",e.outputRef.id]})]}):r.jsx("div",{className:"control-room-output-empty","data-testid":`control-room-output-empty-${e.id}`,children:"No linked output yet"})]})]})}function rk({nodes:e,depth:t,now:n,expandedIds:i,onToggleExpand:o,onCancelActivity:d,cancellingActivityIds:h,onJump:l}){return r.jsx("ul",{className:"control-room-entry-list","data-testid":t===0?"control-room-tree":void 0,children:e.map(u=>r.jsxs("li",{className:"control-room-entry-group",children:[r.jsx("ul",{className:"control-room-entry-list-inner",children:r.jsx(Z7,{entry:u.entry,depth:t,now:n,expanded:i.has(u.entry.id),onToggleExpand:o,onCancelActivity:d,cancellingActivityIds:h,onJump:l})}),u.children.length>0&&r.jsx(rk,{nodes:u.children,depth:t+1,now:n,expandedIds:i,onToggleExpand:o,onCancelActivity:d,cancellingActivityIds:h,onJump:l})]},u.entry.id))})}function ak({activity:e,sessionId:t,now:n=Date.now,onCancelActivity:i,cancellingActivityIds:o,onJumpToSession:d}){const h=t!==null?SN(e,t):G7,l=ik(h),u=Y7(l,n),[f,v]=N.useState(()=>new Set);N.useEffect(()=>{v(new Set)},[t]);const g=N.useCallback(w=>{v(E=>{const x=new Set(E);return x.has(w)?x.delete(w):x.add(w),x})},[]);if(t===null)return r.jsx("div",{className:"control-room-panel","data-testid":"control-room-panel",children:r.jsx("div",{className:"control-room-empty","data-testid":"control-room-empty",children:"No active session"})});if(h.length===0)return r.jsx("div",{className:"control-room-panel","data-testid":"control-room-panel",children:r.jsx("div",{className:"control-room-empty","data-testid":"control-room-empty",children:"No activity in flight"})});const S=d?()=>d(t):void 0;return r.jsx("div",{className:"control-room-panel","data-testid":"control-room-panel",children:r.jsx(rk,{nodes:h,depth:0,now:u,expandedIds:f,onToggleExpand:g,onCancelActivity:i,cancellingActivityIds:o,onJump:S})})}const X7={live:"bad",investigate:"warn",abandoned:"warn",recent:"warn",onboarded:"ok"},Q7={live:"LIVE",investigate:"Investigate",abandoned:"Likely abandoned",recent:"Recent / your call",onboarded:"Onboarded"},jg=[{key:"dirty",label:"Dirty",test:e=>e.tree.state==="dirty"},{key:"live",label:"Live",test:e=>e.live},{key:"prs",label:"Has PRs",test:e=>(e.openPRs??0)>0},{key:"triage",label:"Needs triage",test:e=>e.verdict==="investigate"||e.verdict==="abandoned"||e.verdict==="recent"}],ok=[{key:"default",label:"Server order"},{key:"verdict",label:"Verdict (priority)"},{key:"name",label:"Name (A–Z)"},{key:"recent",label:"Last touched"},{key:"worktrees",label:"Worktrees"},{key:"prs",label:"Open PRs"},{key:"tree",label:"Tree changes"}],p0={live:0,investigate:1,abandoned:2,recent:3,onboarded:4};function m0(e){return e.tree.state==="clean"?0:e.tree.untracked+e.tree.modified+e.tree.staged}function J7(e,t){if(t.size===0)return e.slice();const n=jg.filter(i=>t.has(i.key));return e.filter(i=>n.every(o=>o.test(i)))}function eq(e,t){const n=e.slice();if(t==="default")return n;const i=(d,h)=>d.name.localeCompare(h.name)||d.path.localeCompare(h.path),o={verdict:(d,h)=>p0[d.verdict]-p0[h.verdict]||i(d,h),name:(d,h)=>i(d,h),recent:(d,h)=>g0(h.lastTouched)-g0(d.lastTouched)||i(d,h),worktrees:(d,h)=>h.worktrees-d.worktrees||i(d,h),prs:(d,h)=>(h.openPRs??-1)-(d.openPRs??-1)||i(d,h),tree:(d,h)=>m0(h)-m0(d)||i(d,h)};return n.sort(o[t])}function g0(e){const t=Date.parse(e);return Number.isNaN(t)?0:t}const lk="chroxy_cr_filters",ck="chroxy_cr_sort",tq=new Set(jg.map(e=>e.key)),nq=new Set(ok.map(e=>e.key));function sq(){try{const e=localStorage.getItem(lk);if(!e)return new Set;const t=e.split(",").map(n=>n.trim()).filter(n=>tq.has(n));return new Set(t)}catch{return new Set}}function iq(e){try{localStorage.setItem(lk,[...e].join(","))}catch{}}function rq(){try{const e=localStorage.getItem(ck);if(e&&nq.has(e))return e}catch{}return"default"}function aq(e){try{localStorage.setItem(ck,e)}catch{}}const oq={investigate:!0},uk=20;function ci(e,t){const n=Math.floor((t-e)/1e3);if(!Number.isFinite(n)||n<60)return"generated just now";const i=Math.floor(n/60);if(i<60)return`generated ${i}m ago`;const o=Math.floor(i/60);return o<24?`generated ${o}h ago`:`generated ${Math.floor(o/24)}d ago`}function lq(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function am(e){const t=e.replace(/\\/g,"/");return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function cq(e,t){const n=am(e);for(const d of t)if(am(d.cwd)===n)return d.sessionId;let i=null;const o=n==="/"?"/":`${n}/`;for(const d of t){const h=am(d.cwd);if(h.startsWith(o)){const l=h.length;(i===null||l>i.depth)&&(i={sessionId:d.sessionId,depth:l})}}return i?i.sessionId:null}const uq=[{key:"live",label:"Live agents",accent:"bad"},{key:"onboarded",label:"Onboarded",accent:"ok"},{key:"abandoned",label:"Likely abandoned",accent:"warn"},{key:"investigate",label:"Needs investigation",accent:"warn"},{key:"recent",label:"Recent / your call",accent:"warn"}];function dq({repo:e}){const{verdict:t}=e,n=X7[t];return r.jsx("span",{className:`cr-tag cr-tag-${n}`,"data-testid":`cr-verdict-${t}`,"data-accent":n,children:Q7[t]})}function fq({repo:e}){const t=e.ahead??0,n=e.behind??0;if(t===0&&n===0)return null;const i=t>0?`${t} commit${t===1?"":"s"} ahead of upstream`:"",o=n>0?`${n} commit${n===1?"":"s"} behind upstream`:"",d=[i,o].filter(Boolean).join(", ");return r.jsxs("span",{className:"cr-aheadbehind","data-testid":`cr-aheadbehind-${e.name}`,role:"img","aria-label":d,children:[t>0&&r.jsxs("span",{className:"cr-ahead",title:i,"aria-hidden":"true",children:["↑",t]}),n>0&&r.jsxs("span",{className:"cr-behind",title:o,"aria-hidden":"true",children:["↓",n]})]})}function hq({value:e,testid:t}){if(e===null)return r.jsx("td",{className:"cr-num",children:r.jsx("span",{className:"cr-dim",children:"—"})});const n=e>=uk;return r.jsx("td",{className:"cr-num",children:r.jsx("span",{className:n?"cr-bad":void 0,"data-testid":t,"data-high":n?"true":"false",children:e})})}function pq({repo:e}){const t=e.prChecks;if(!t)return null;const{failing:n,pending:i,approved:o,changesRequested:d}=t;if(n===0&&i===0&&o===0&&d===0)return null;const h=S=>S===1?"":"s",l=n>0?`${n} open PR${h(n)} with failing CI`:"",u=i>0?`${i} open PR${h(i)} with CI in progress`:"",f=d>0?`${d} open PR${h(d)} with changes requested`:"",v=o>0?`${o} approved open PR${h(o)}`:"",g=[l,u,f,v].filter(Boolean).join(", ");return r.jsxs("span",{className:"cr-prchecks","data-testid":`cr-prchecks-${e.name}`,role:"img","aria-label":g,children:[n>0&&r.jsxs("span",{className:"cr-pr-fail","data-testid":`cr-pr-fail-${e.name}`,title:l,"aria-hidden":"true",children:["✗",n]}),i>0&&r.jsxs("span",{className:"cr-pr-pending",title:u,"aria-hidden":"true",children:["●",i]}),d>0&&r.jsxs("span",{className:"cr-pr-changes",title:f,"aria-hidden":"true",children:["✎",d]}),o>0&&r.jsxs("span",{className:"cr-pr-approved","data-testid":`cr-pr-approved-${e.name}`,title:v,"aria-hidden":"true",children:["✓",o]})]})}function mq({repo:e}){if(e.openPRs===null)return r.jsx("td",{className:"cr-num",children:r.jsx("span",{className:"cr-dim",children:"—"})});const t=e.openPRs>=uk;return r.jsxs("td",{className:"cr-num",children:[r.jsx("span",{className:t?"cr-bad":void 0,"data-testid":`cr-prs-${e.name}`,"data-high":t?"true":"false",children:e.openPRs}),r.jsx(pq,{repo:e})]})}function gq({repo:e}){if(e.tree.state==="clean")return r.jsx("td",{className:"cr-tree","data-testid":`cr-tree-${e.name}`,children:"clean"});const{untracked:t,modified:n,staged:i}=e.tree,o=t+n+i;return r.jsxs("td",{className:"cr-tree","data-testid":`cr-tree-${e.name}`,children:[o," ",r.jsxs("span",{className:"cr-dim",children:["(",t,"u/",n,"m/",i,"s)"]})]})}function vq({attribution:e}){return e===null?r.jsx("td",{children:r.jsx("span",{className:"cr-dim",children:"—"})}):r.jsx("td",{children:e?r.jsx("span",{className:"cr-ok",children:"✓"}):r.jsx("span",{className:"cr-bad",children:"✗"})})}function yq({repo:e,onInvestigate:t,onOpenSession:n,onConfigureRepo:i}){const o=oq[e.verdict]===!0&&!!t,[d,h]=N.useState(!1),l=N.useCallback(()=>{Pc(e.path).then(u=>{u&&(h(!0),window.setTimeout(()=>h(!1),1500))})},[e.path]);return r.jsxs("td",{className:"cr-actions",children:[e.prsUrl&&r.jsx("a",{className:"cr-action","data-testid":`cr-action-prs-${e.name}`,href:e.prsUrl,target:"_blank",rel:"noopener noreferrer",title:`Open ${e.name}'s pull requests on GitHub`,children:"View PRs"}),r.jsx("button",{type:"button",className:"cr-action","data-testid":`cr-action-copy-${e.name}`,onClick:l,title:`Copy ${e.path}`,children:d?"Copied":"Copy path"}),o&&r.jsx("button",{type:"button",className:"cr-action cr-action-investigate","data-testid":`cr-action-investigate-${e.name}`,"aria-label":`Investigate ${e.name} — open a session in ${e.path}`,title:`Investigate ${e.name} — open a session in ${e.path}`,onClick:()=>t({cwd:e.path,name:e.name,reason:e.note??""}),children:"Investigate"}),n&&r.jsx("button",{type:"button",className:"cr-action","data-testid":`cr-action-open-${e.name}`,"aria-label":`Open a session in ${e.name} (${e.path})`,title:e.live?`Open another session in ${e.path} (a live session is already running here)`:`Open a session in ${e.path}`,onClick:()=>n({cwd:e.path,name:e.name}),children:"Open session"}),i&&r.jsx("button",{type:"button",className:"cr-action cr-action-gear","data-testid":`cr-action-configure-${e.name}`,"aria-label":`Configure ${e.name} (${e.path})`,title:`Per-repo settings for ${e.path}`,onClick:()=>i({path:e.path,name:e.name}),children:"⚙"})]})}function bq({repo:e,activity:t,sessions:n,expanded:i,onToggleExpand:o,now:d,onInvestigate:h,onOpenSession:l,onConfigureRepo:u,onCancelActivity:f,onInterruptSession:v,cancellingActivityIds:g}){const S=cq(e.path,n),w=S!==null,E=S&&g?new Set([...g].filter(x=>x.startsWith(`${S}:`)).map(x=>x.slice(S.length+1))):void 0;return r.jsxs(r.Fragment,{children:[r.jsxs("tr",{"data-testid":`cr-row-${e.name}`,className:e.live?"cr-row-live":void 0,children:[r.jsxs("td",{children:[w?r.jsxs("button",{type:"button",className:"cr-drill-toggle","data-testid":`cr-drill-toggle-${e.name}`,"aria-expanded":i,onClick:()=>o(e.path),title:i?"Hide live activity":"Show live activity",children:[r.jsx("span",{className:"cr-drill-chevron","aria-hidden":"true",children:i?"▼":"▶"}),r.jsx("b",{"data-testid":`cr-name-${e.name}`,children:e.name})]}):r.jsx("b",{"data-testid":`cr-name-${e.name}`,children:e.name}),e.live&&r.jsx("span",{className:"cr-live-dot","data-testid":`cr-live-dot-${e.name}`,role:"img","aria-label":"Live agent",title:"Live agent here right now"}),r.jsxs("div",{className:"cr-branchrow",children:[r.jsx("span",{className:"cr-dim cr-mono cr-branch","data-testid":`cr-branch-${e.name}`,title:e.branch,children:e.branch}),r.jsx(fq,{repo:e})]})]}),r.jsx("td",{children:r.jsx(dq,{repo:e})}),r.jsx("td",{children:r.jsx("div",{className:"cr-onboarding",title:e.onboarding,children:e.onboarding})}),r.jsx(gq,{repo:e}),r.jsx(hq,{value:e.worktrees,testid:`cr-wt-${e.name}`}),r.jsx(mq,{repo:e}),r.jsx(vq,{attribution:e.attribution}),r.jsx("td",{className:"cr-dim cr-last",children:_q(e.lastTouched)}),r.jsx(yq,{repo:e,onInvestigate:h,onOpenSession:l,onConfigureRepo:u})]}),e.note&&r.jsx("tr",{className:"cr-act","data-testid":`cr-note-row-${e.name}`,children:r.jsxs("td",{colSpan:9,children:[r.jsx("span",{className:"cr-arrow","aria-hidden":"true",children:"↳"})," ",e.note]})}),w&&i&&r.jsx("tr",{className:"cr-activity-row","data-testid":`cr-activity-row-${e.name}`,children:r.jsx("td",{colSpan:9,children:r.jsxs("div",{className:"cr-activity-drill",children:[r.jsxs("div",{className:"cr-activity-heading","data-testid":`cr-activity-heading-${e.name}`,children:[r.jsxs("span",{children:["Live activity · ",e.name]}),v&&S&&r.jsx("button",{type:"button",className:"cr-interrupt-btn","data-testid":`cr-interrupt-${e.name}`,onClick:()=>v(S),title:"Interrupt the current turn in this session",children:"Interrupt turn"})]}),r.jsx(ak,{activity:t,sessionId:S,now:d,onCancelActivity:f&&S?x=>f(x,S):void 0,cancellingActivityIds:E})]})})})]})}function _q(e){const t=Date.parse(e);if(Number.isNaN(t))return e;const n=Math.floor((Date.now()-t)/1e3);if(n<60)return"just now";const i=Math.floor(n/60);if(i<60)return`${i} minute${i===1?"":"s"} ago`;const o=Math.floor(i/60);if(o<24)return`${o} hour${o===1?"":"s"} ago`;const d=Math.floor(o/24);if(d<30)return`${d} day${d===1?"":"s"} ago`;const h=Math.floor(d/30);return`${h} month${h===1?"":"s"} ago`}const Sq=Pd();function xq({snapshot:e,loading:t,connected:n,onRefresh:i,activity:o,sessions:d,now:h=Date.now,onInvestigate:l,onOpenSession:u,onConfigureRepo:f,onCancelActivity:v,onInterruptSession:g}={}){const S=V(se=>se.hostStatus),w=V(se=>se.hostStatusLoading),E=V(se=>se.connectionPhase==="connected"),x=V(se=>se.requestHostStatus),m=V(se=>se.activity),y=V(se=>se.sessions),b=V(se=>se.sendCancelActivity),_=V(se=>se.sendInterrupt),k=V(se=>se.cancellingActivityIds),j=e!==void 0?e:S,T=t!==void 0?t:w,D=n!==void 0?n:E,I=i??x,L=o??m??Sq,q=d??y??[],H=v??((se,Z)=>{b(se,Z)}),Q=g??(se=>{_(se)}),[F,J]=N.useState(()=>new Set),ie=N.useCallback(se=>{J(Z=>{const ge=new Set(Z);return ge.has(se)?ge.delete(se):ge.add(se),ge})},[]),[X,de]=N.useState(sq),[fe,$]=N.useState(rq);N.useEffect(()=>{iq(X)},[X]),N.useEffect(()=>{aq(fe)},[fe]);const P=N.useCallback(se=>{de(Z=>{const ge=new Set(Z);return ge.has(se)?ge.delete(se):ge.add(se),ge})},[]),B=N.useCallback(()=>de(new Set),[]),K=j?j.repos:[],le=N.useMemo(()=>eq(J7(K,X),fe),[K,X,fe]),me=T||!D,be=()=>{me||I()},Ee=j?Date.parse(j.generatedAt):NaN;return r.jsxs("div",{className:"cr-section","data-testid":"control-room-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"cr-eyebrow",children:["host · repo status",j?` · ${lq(j.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Project & onboarding status"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"cr-refresh",onClick:be,disabled:me,"aria-busy":T,title:D?void 0:"Not connected — reconnect to run the survey",children:T?"Refreshing…":"Refresh"})]}),j?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"cr-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",j.error.code,"):"]})," ",j.error.message]}),j&&r.jsxs("p",{className:"cr-sub","data-testid":"cr-sub",children:["All ",j.repos.length," managed repo",j.repos.length===1?"":"s"," under"," ",r.jsx("span",{className:"cr-mono",children:j.root})," — git state, pull-model onboarding, and a triage verdict for each. ",r.jsx("span",{className:"cr-live-dot cr-live-dot-inline","aria-hidden":"true"})," = a live agent you told me about."]}),j&&!Number.isNaN(Ee)&&r.jsx("p",{className:"cr-generated","data-testid":"cr-generated",children:ci(Ee,h())})]}),!j&&r.jsx("div",{className:"cr-empty","data-testid":"cr-empty",children:T?r.jsx("span",{children:"Running the host survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No host status survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"cr-empty-refresh",onClick:be,disabled:!D,title:D?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!D&&r.jsx("p",{className:"cr-dim","data-testid":"cr-not-connected",children:"Not connected to the server."})]})}),j&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"cr-chips","data-testid":"cr-chips",children:uq.map(se=>r.jsxs("span",{className:"cr-chip","data-testid":`cr-chip-${se.key}`,children:[r.jsx("span",{className:`cr-dot cr-dot-${se.accent}`,"aria-hidden":"true"}),se.label,": ",r.jsx("b",{"data-testid":`cr-chip-count-${se.key}`,children:j.summary[se.key]})]},se.key))}),r.jsxs("div",{className:"cr-callout","data-testid":"cr-callout",children:[r.jsx("b",{children:"How to read the verdict:"})," ",r.jsx("b",{children:"LIVE"})," = agent working now, leave it."," ",r.jsx("b",{children:"Likely abandoned"})," = dirty tree last touched months ago with no live agent — almost certainly an old/terminated session. ",r.jsx("b",{children:"Recent / your call"})," = uncommitted work from the last few days. ",r.jsx("b",{children:"Investigate"})," = a worktree leak. ",r.jsx("b",{children:"Onboarded"})," = on the pull-model; local clone may just need a checkout+pull."]}),j.repos.length>0&&r.jsxs("div",{className:"cr-controls","data-testid":"cr-controls",children:[r.jsxs("div",{className:"cr-filters",role:"group","aria-label":"Filter repos",children:[jg.map(se=>{const Z=X.has(se.key);return r.jsx("button",{type:"button",className:`cr-filter${Z?" cr-filter-on":""}`,"data-testid":`cr-filter-${se.key}`,"aria-pressed":Z,onClick:()=>P(se.key),children:se.label},se.key)}),X.size>0&&r.jsx("button",{type:"button",className:"cr-filter-clear","data-testid":"cr-clear-filters",onClick:B,children:"Clear"})]}),r.jsxs("label",{className:"cr-sort-label",children:["Sort",r.jsx("select",{className:"cr-sort","data-testid":"cr-sort",value:fe,onChange:se=>$(se.target.value),children:ok.map(se=>r.jsx("option",{value:se.key,children:se.label},se.key))})]}),r.jsx("span",{className:"cr-dim cr-visible-count","data-testid":"cr-visible-count",children:X.size>0?`${le.length} of ${j.repos.length} repos`:`${j.repos.length} repos`})]}),r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"cr-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Repo / branch"}),r.jsx("th",{children:"Verdict"}),r.jsx("th",{children:"Onboarding"}),r.jsx("th",{children:"Tree"}),r.jsx("th",{children:"Wt"}),r.jsx("th",{children:"PRs"}),r.jsx("th",{children:"Attr"}),r.jsx("th",{children:"Last"}),r.jsx("th",{children:"Actions"})]})}),r.jsx("tbody",{children:j.repos.length===0?r.jsx("tr",{"data-testid":"cr-no-repos",children:r.jsxs("td",{colSpan:9,className:"cr-dim",children:["No repos found under ",j.root,"."]})}):le.length===0?r.jsx("tr",{"data-testid":"cr-no-matches",children:r.jsxs("td",{colSpan:9,className:"cr-dim",children:["No repos match the active filters."," ",r.jsx("button",{type:"button",className:"cr-link-btn","data-testid":"cr-no-matches-clear",onClick:B,children:"Clear filters"})]})}):le.map(se=>r.jsx(bq,{repo:se,activity:L,sessions:q,expanded:F.has(se.path),onToggleExpand:ie,now:h,onInvestigate:l,onOpenSession:u,onConfigureRepo:f,onCancelActivity:H,onInterruptSession:Q,cancellingActivityIds:k},se.path))})]})})]})]})}const wq={busy:"ok",idle:"ok",stopped:"warn",unregistered:"warn",offline:"bad"},kq={busy:"Busy",idle:"Idle",stopped:"Stopped",unregistered:"Unregistered",offline:"Offline"},Cq=[{key:"total",label:"Runners",accent:"neutral"},{key:"idle",label:"Idle",accent:"ok"},{key:"busy",label:"Busy",accent:"ok"},{key:"stopped",label:"Stopped",accent:"warn"},{key:"unregistered",label:"Unregistered",accent:"warn"},{key:"offline",label:"Offline",accent:"bad"}];function Eq(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Nq({runner:e}){const t=wq[e.verdict];return r.jsx("span",{className:`cr-tag cr-tag-${t}`,"data-testid":`runner-verdict-${e.name}`,"data-accent":t,children:kq[e.verdict]})}function jq({runner:e}){const{service:t}=e;if(t.manager==="none"||!t.label)return r.jsx("td",{className:"cr-dim","data-testid":`runner-svc-${e.name}`,children:"no service"});if(t.running)return r.jsxs("td",{"data-testid":`runner-svc-${e.name}`,children:[r.jsx("span",{className:"cr-ok",children:"running"}),t.pid!==null&&r.jsxs("span",{className:"cr-dim cr-mono",children:[" pid ",t.pid]})]});const n=t.lastExitCode!==null&&t.lastExitCode!==0;return r.jsxs("td",{"data-testid":`runner-svc-${e.name}`,children:[r.jsx("span",{className:n?"cr-bad":"cr-dim",children:"stopped"}),t.lastExitCode!==null&&r.jsxs("span",{className:"cr-dim cr-mono",children:[" exit ",t.lastExitCode]})]})}function Aq({runner:e}){if(e.githubStatus===null)return r.jsx("td",{className:"cr-dim","data-testid":`runner-gh-${e.name}`,children:"—"});const t=e.githubStatus==="online";return r.jsxs("td",{"data-testid":`runner-gh-${e.name}`,children:[r.jsx("span",{className:t?"cr-ok":"cr-bad",children:e.githubStatus}),e.busy&&r.jsx("span",{className:"cr-dim",children:" · busy"})]})}function Rq({runner:e}){return r.jsxs("tr",{"data-testid":`runner-row-${e.name}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`runner-name-${e.name}`,children:e.name}),r.jsx("div",{className:"cr-dim cr-mono cr-branch",title:e.dir,children:e.dir})]}),r.jsx("td",{children:r.jsx(Nq,{runner:e})}),r.jsx(jq,{runner:e}),r.jsx(Aq,{runner:e}),r.jsx("td",{className:"cr-dim",children:e.os??"—"}),r.jsx("td",{className:"cr-dim cr-mono",children:e.labels.length>0?e.labels.join(", "):"—"})]})}function Tq({group:e}){return r.jsxs(r.Fragment,{children:[r.jsx("tr",{className:"runner-repo-row","data-testid":`runner-repo-${e.name}`,children:r.jsxs("td",{colSpan:6,children:[r.jsx("b",{className:"runner-repo-name",children:e.name}),r.jsxs("span",{className:"cr-dim",children:[" · ",e.runners.length," runner",e.runners.length===1?"":"s"]}),e.runnersUrl&&r.jsx("a",{className:"cr-action runner-settings-link","data-testid":`runner-settings-${e.name}`,href:e.runnersUrl,target:"_blank",rel:"noopener noreferrer",title:`Open ${e.name}'s runner settings on GitHub`,children:"Runner settings"})]})}),e.runners.map(t=>r.jsx(Rq,{runner:t},t.dir))]})}function Iq({snapshot:e,loading:t,connected:n,onRefresh:i,now:o=Date.now}={}){const d=V(y=>y.runnerStatus),h=V(y=>y.runnerStatusLoading),l=V(y=>y.connectionPhase==="connected"),u=V(y=>y.requestRunnerStatus),f=e!==void 0?e:d,v=t!==void 0?t:h,g=n!==void 0?n:l,S=i??u,w=v||!g,E=()=>{w||S()},x=N.useMemo(()=>f?f.repos.reduce((y,b)=>y+b.runners.length,0):0,[f]),m=f?Date.parse(f.generatedAt):NaN;return r.jsxs("div",{className:"cr-section","data-testid":"runner-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"runner-eyebrow",children:["host · self-hosted runners",f?` · ${Eq(f.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Self-hosted runners"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"runner-refresh",onClick:E,disabled:w,"aria-busy":v,title:g?void 0:"Not connected — reconnect to run the survey",children:v?"Refreshing…":"Refresh"})]}),f?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"runner-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",f.error.code,"):"]})," ",f.error.message]}),f&&r.jsxs("p",{className:"cr-sub","data-testid":"runner-sub",children:[x," runner",x===1?"":"s"," across ",f.repos.length," project",f.repos.length===1?"":"s"," under"," ",r.jsx("span",{className:"cr-mono",children:f.root})," — local service state cross-checked against GitHub."]}),f&&!Number.isNaN(m)&&r.jsx("p",{className:"cr-generated","data-testid":"runner-generated",children:ci(m,o())})]}),!f&&r.jsx("div",{className:"cr-empty","data-testid":"runner-empty",children:v?r.jsx("span",{children:"Running the runner survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No self-hosted runner survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"runner-empty-refresh",onClick:E,disabled:!g,title:g?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!g&&r.jsx("p",{className:"cr-dim","data-testid":"runner-not-connected",children:"Not connected to the server."})]})}),f&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"cr-chips","data-testid":"runner-chips",children:Cq.map(y=>r.jsxs("span",{className:"cr-chip","data-testid":`runner-chip-${y.key}`,children:[y.accent!=="neutral"&&r.jsx("span",{className:`cr-dot cr-dot-${y.accent}`,"aria-hidden":"true"}),y.label,": ",r.jsx("b",{"data-testid":`runner-chip-count-${y.key}`,children:f.summary[y.key]})]},y.key))}),r.jsxs("div",{className:"cr-callout","data-testid":"runner-callout",children:[r.jsx("b",{children:"How to read the verdict:"})," ",r.jsx("b",{children:"Idle"})," = service running and GitHub-online, ready for jobs."," ",r.jsx("b",{children:"Busy"})," = running a job now. ",r.jsx("b",{children:"Stopped"})," = the runner service is registered but not running (a non-zero exit means it crashed). ",r.jsx("b",{children:"Unregistered"})," = an install directory with no service."," ",r.jsx("b",{children:"Offline"})," = the local service and GitHub disagree — worth a look."]}),r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"runner-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Runner / dir"}),r.jsx("th",{children:"Status"}),r.jsx("th",{children:"Service"}),r.jsx("th",{children:"GitHub"}),r.jsx("th",{children:"OS"}),r.jsx("th",{children:"Labels"})]})}),r.jsx("tbody",{children:f.repos.length===0?r.jsx("tr",{"data-testid":"runner-no-repos",children:r.jsxs("td",{colSpan:6,className:"cr-dim",children:["No self-hosted runners found under ",f.root,"."]})}):f.repos.map(y=>r.jsx(Tq,{group:y},y.githubUrl))})]})})]})]})}const v0='a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';function Vc({open:e,onClose:t,title:n,children:i,maxWidth:o,closeOnBackdrop:d=!0}){const h=N.useId(),l=N.useRef(null),u=N.useRef(null),f=N.useCallback(v=>{if(v.key==="Escape"){const g=document.querySelectorAll("[data-modal-overlay]");g.length>0&&g[g.length-1]===l.current&&t()}},[t]);return N.useEffect(()=>{if(e)return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e,f]),N.useEffect(()=>{if(!e)return;const v=document.activeElement,g=u.current;if(!g)return;const S=()=>Array.from(g.querySelectorAll(v0)),E=Array.from(g.querySelectorAll(v0))[0];E?E.focus():(g.setAttribute("tabindex","-1"),g.focus());const x=m=>{if(m.key!=="Tab")return;const y=document.querySelectorAll("[data-modal-overlay]");if(y.length>0&&y[y.length-1]!==l.current)return;const b=S(),_=b[0],k=b[b.length-1];if(!_||!k){m.preventDefault();return}const j=document.activeElement;m.shiftKey?(j===_||!g.contains(j))&&(m.preventDefault(),k.focus()):(j===k||!g.contains(j))&&(m.preventDefault(),_.focus())};return document.addEventListener("keydown",x),()=>{document.removeEventListener("keydown",x),v&&typeof v.focus=="function"&&v.focus()}},[e]),e?r.jsx("div",{ref:l,className:"modal-overlay","data-modal-overlay":!0,"data-testid":"modal-overlay",onClick:d?t:void 0,children:r.jsxs("div",{ref:u,className:"modal-content",role:"dialog","aria-modal":"true","aria-labelledby":h,style:o?{maxWidth:o}:void 0,onClick:v=>v.stopPropagation(),children:[r.jsx("h3",{id:h,className:"modal-title",children:n}),i]})}):null}function Sf({open:e,title:t,message:n,confirmLabel:i="Confirm",cancelLabel:o="Cancel",danger:d=!1,onConfirm:h,onCancel:l}){return r.jsx(Vc,{open:e,onClose:l,title:t,maxWidth:"420px",children:r.jsxs("div",{className:"confirm-dialog","data-testid":"confirm-dialog",children:[r.jsx("div",{className:"confirm-dialog-message","data-testid":"confirm-dialog-message",children:n}),r.jsxs("div",{className:"modal-buttons",children:[r.jsx("button",{type:"button",className:"btn-modal-cancel","data-testid":"confirm-dialog-cancel",onClick:l,children:o}),r.jsx("button",{type:"button",className:d?"btn-modal-danger":"btn-modal-create","data-testid":"confirm-dialog-confirm",onClick:h,children:i})]})]})})}const Mq={running:"var(--status-running, #22c55e)",stopped:"var(--status-stopped, #eab308)",error:"var(--status-error, #ef4444)"};function Dq({status:e}){return r.jsx("span",{className:"env-status-badge",style:{color:Mq[e]||"var(--text-secondary)"},children:e})}function Lq({env:e,onDestroy:t}){const[n,i]=N.useState(!1);return r.jsxs("div",{className:"env-card",children:[r.jsxs("div",{className:"env-card-header",children:[r.jsx("span",{className:"env-card-name",children:e.name}),r.jsx(Dq,{status:e.status})]}),r.jsxs("div",{className:"env-card-details",children:[r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Image"}),r.jsx("span",{className:"env-card-value",children:e.image})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"CWD"}),r.jsx("span",{className:"env-card-value",children:e.cwd})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Resources"}),r.jsxs("span",{className:"env-card-value",children:[e.memoryLimit," RAM, ",e.cpuLimit," CPU"]})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Sessions"}),r.jsxs("span",{className:"env-card-value",children:[e.sessions.length," connected"]})]}),r.jsxs("div",{className:"env-card-row",children:[r.jsx("span",{className:"env-card-label",children:"Container"}),r.jsx("span",{className:"env-card-value",style:{fontFamily:"var(--font-mono, monospace)",fontSize:"0.85em"},children:e.containerId?.slice(0,12)||"n/a"})]})]}),r.jsx("div",{className:"env-card-actions",children:n?r.jsxs("div",{className:"env-confirm-row",children:[r.jsx("span",{children:"Destroy this environment?"}),r.jsx("button",{className:"btn-env-confirm-yes",onClick:()=>t(e.id),children:"Yes"}),r.jsx("button",{className:"btn-env-confirm-no",onClick:()=>i(!1),children:"No"})]}):r.jsx("button",{className:"btn-env-destroy",onClick:()=>i(!0),disabled:e.sessions.length>0,title:e.sessions.length>0?"Disconnect all sessions first":"Destroy environment",children:"Destroy"})})]})}function Oq({onClose:e}){const t=V(E=>E.createEnvironment),n=V(E=>E.sessionCwd),[i,o]=N.useState(""),[d,h]=N.useState(n||""),[l,u]=N.useState(""),[f,v]=N.useState(""),[g,S]=N.useState(""),w=E=>{E.preventDefault(),!(!i.trim()||!d.trim())&&(t({name:i.trim(),cwd:d.trim(),image:l.trim()||void 0,memoryLimit:f.trim()||void 0,cpuLimit:g.trim()||void 0}),e())};return r.jsxs("form",{className:"env-create-form",onSubmit:w,children:[r.jsxs("div",{className:"env-form-field",children:[r.jsx("label",{htmlFor:"env-name",children:"Name"}),r.jsx("input",{id:"env-name",type:"text",placeholder:"my-project",value:i,onChange:E=>o(E.target.value),autoFocus:!0})]}),r.jsxs("div",{className:"env-form-field",children:[r.jsx("label",{htmlFor:"env-cwd",children:"Working Directory"}),r.jsx("input",{id:"env-cwd",type:"text",placeholder:"/home/user/project",value:d,onChange:E=>h(E.target.value)})]}),r.jsxs("div",{className:"env-form-field",children:[r.jsx("label",{htmlFor:"env-image",children:"Docker Image"}),r.jsx("input",{id:"env-image",type:"text",placeholder:"node:22-slim (default)",value:l,onChange:E=>u(E.target.value)})]}),r.jsxs("div",{className:"env-form-row",children:[r.jsxs("div",{className:"env-form-field",children:[r.jsx("label",{htmlFor:"env-memory",children:"Memory"}),r.jsx("input",{id:"env-memory",type:"text",placeholder:"2g (default)",value:f,onChange:E=>v(E.target.value)})]}),r.jsxs("div",{className:"env-form-field",children:[r.jsx("label",{htmlFor:"env-cpu",children:"CPUs"}),r.jsx("input",{id:"env-cpu",type:"text",placeholder:"2 (default)",value:g,onChange:E=>S(E.target.value)})]})]}),r.jsxs("div",{className:"env-form-buttons",children:[r.jsx("button",{type:"button",className:"btn-env-cancel",onClick:e,children:"Cancel"}),r.jsx("button",{type:"submit",className:"btn-env-create",disabled:!i.trim()||!d.trim(),children:"Create Environment"})]})]})}function Pq(){const e=V(Mc(h=>h.environments)),t=V(h=>h.requestEnvironments),n=V(h=>h.destroyEnvironment),i=V(h=>h.connectionPhase),[o,d]=N.useState(!1);return N.useEffect(()=>{i==="connected"&&t()},[i,t]),r.jsxs("div",{className:"environment-panel",children:[r.jsxs("div",{className:"env-panel-header",children:[r.jsx("h2",{children:"Environments"}),r.jsx("button",{className:"btn-env-new",onClick:()=>d(!0),children:"+ New Environment"})]}),o&&r.jsx(Oq,{onClose:()=>d(!1)}),e.length===0&&!o&&r.jsxs("div",{className:"env-empty",children:[r.jsx("p",{children:"No persistent environments."}),r.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"0.9em"},children:"Environments are long-lived Docker containers that outlive sessions. Create one to avoid reinstalling dependencies on every session restart."})]}),r.jsx("div",{className:"env-grid",children:e.map(h=>r.jsx(Lq,{env:h,onDestroy:n},h.id))})]})}function Bq(e){return e.action==="destroy"?"destroyed":e.action==="stop"?e.status==="stopped"?"stopped":e.status??"stopped":e.action==="restart"?e.status==="running"?"restarted":e.status??"restarted":e.status??"done"}const $q={running:"ok",stopped:"warn",exited:"warn",error:"bad"};function zq(e){return $q[e]??"neutral"}const Uq=[{key:"total",label:"Containers",accent:"neutral"},{key:"running",label:"Running",accent:"ok"},{key:"stopped",label:"Stopped",accent:"warn"},{key:"other",label:"Other",accent:"bad"}];function qq(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function Hq(e){if(e===null||!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60);if(n<60)return`${n}m`;const i=Math.floor(n/60),o=n%60;if(i<24)return o>0?`${i}h ${o}m`:`${i}h`;const d=Math.floor(i/24),h=i%24;return h>0?`${d}d ${h}h`:`${d}d`}function Fq(e){if(e===null||!Number.isFinite(e)||e<0)return"—";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,i=0;for(;n>=1024&&i<t.length-1;)n/=1024,i++;return`${n.toFixed(n<10?2:1)} ${t[i]}`}function Kq({container:e}){const t=zq(e.status);return r.jsx("span",{className:`cr-tag cr-tag-${t}`,"data-testid":`container-status-${e.id}`,"data-accent":t,children:e.status})}function Wq({container:e}){const{stats:t}=e;return!t||t.cpuPercent===null&&t.memBytes===null&&t.memPercent===null?r.jsx("td",{className:"cr-dim","data-testid":`container-stats-${e.id}`,children:"—"}):r.jsxs("td",{"data-testid":`container-stats-${e.id}`,children:[t.cpuPercent!==null&&r.jsxs("span",{className:"cr-mono",children:[t.cpuPercent.toFixed(1),"% cpu"]}),t.memBytes!==null&&r.jsxs("span",{className:"cr-dim cr-mono",children:[t.cpuPercent!==null?" · ":"",Fq(t.memBytes),t.memPercent!==null?` (${t.memPercent.toFixed(1)}%)`:""]})]})}function Gq({container:e,pending:t,result:n,connected:i,onAction:o}){const d=!!e.containerId&&!e.composeProject,h=e.status==="running",l=t||!i;return r.jsxs("td",{"data-testid":`container-actions-${e.id}`,children:[r.jsxs("div",{className:"cr-actions",children:[d&&r.jsx("button",{type:"button",className:"cr-action","data-testid":`container-stop-${e.id}`,disabled:l||!h,onClick:()=>o("stop"),title:h?"Stop this container":"Container is not running",children:"Stop"}),d&&r.jsx("button",{type:"button",className:"cr-action","data-testid":`container-restart-${e.id}`,disabled:l,onClick:()=>o("restart"),title:"Restart this container",children:"Restart"}),r.jsx("button",{type:"button",className:"cr-action cr-action-danger","data-testid":`container-destroy-${e.id}`,disabled:l,onClick:()=>o("destroy"),title:"Destroy this environment",children:"Destroy"})]}),t?r.jsx("span",{className:"cr-dim","data-testid":`container-action-pending-${e.id}`,children:"Working…"}):n?n.error?r.jsx("span",{className:"cr-bad","data-testid":`container-action-error-${e.id}`,role:"alert",children:n.error}):r.jsx("span",{className:"cr-ok","data-testid":`container-action-ok-${e.id}`,children:Bq(n)}):null]})}function Vq({container:e,pending:t,result:n,connected:i,onAction:o}){return r.jsxs("tr",{"data-testid":`container-row-${e.id}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`container-name-${e.id}`,children:e.name||e.id}),r.jsxs("div",{className:"cr-dim cr-mono cr-branch",children:[e.backend,e.containerId?` · ${e.containerId.slice(0,12)}`:"",e.composeProject?` · ${e.composeProject}`:""]})]}),r.jsx("td",{children:r.jsx(Kq,{container:e})}),r.jsx("td",{className:"cr-dim cr-mono",children:e.image??"—"}),r.jsx("td",{className:"cr-dim","data-testid":`container-sessions-${e.id}`,children:e.sessionCount>0?`${e.sessionCount}`:"—"}),r.jsx("td",{className:"cr-dim",children:Hq(e.uptimeMs)}),r.jsx(Wq,{container:e}),r.jsx(Gq,{container:e,pending:t,result:n,connected:i,onAction:d=>o(e.id,d)})]})}function Yq(e){const t=[],n=new Map;for(const i of e){const o=i.cwd||"(no workdir)";n.has(o)||(n.set(o,[]),t.push(o)),n.get(o).push(i)}return t.map(i=>({cwd:i,containers:n.get(i)}))}function Zq({group:e,actioningIds:t,actionResults:n,connected:i,onAction:o}){return r.jsxs(r.Fragment,{children:[r.jsx("tr",{className:"runner-repo-row","data-testid":`container-cwd-${e.cwd}`,children:r.jsxs("td",{colSpan:7,children:[r.jsx("b",{className:"runner-repo-name cr-mono",children:e.cwd}),r.jsxs("span",{className:"cr-dim",children:[" · ",e.containers.length," container",e.containers.length===1?"":"s"]})]})}),e.containers.map(d=>r.jsx(Vq,{container:d,pending:t.has(d.id),result:n[d.id],connected:i,onAction:o},d.id))]})}function Xq({snapshot:e,loading:t,connected:n,onRefresh:i,actioningIds:o,actionResults:d,onAction:h,now:l=Date.now}={}){const u=V(ie=>ie.containersStatus),f=V(ie=>ie.containersStatusLoading),v=V(ie=>ie.connectionPhase==="connected"),g=V(ie=>ie.requestContainersStatus),S=V(ie=>ie.containerActioningIds),w=V(ie=>ie.containerActionResults),E=V(ie=>ie.sendContainersAction),x=e!==void 0?e:u,m=t!==void 0?t:f,y=n!==void 0?n:v,b=i??g,_=o??S,k=d??w,j=h??E,[T,D]=N.useState(null),[I,L]=N.useState(!1),q=(ie,X)=>{if(X==="destroy"){const de=x?.containers.find(fe=>fe.id===ie)??null;D(de);return}j(ie,X)},H=m||!y,Q=()=>{H||b()},F=N.useMemo(()=>x?Yq(x.containers):[],[x]),J=x?Date.parse(x.generatedAt):NaN;return r.jsxs("div",{className:"cr-section","data-testid":"containers-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"containers-eyebrow",children:["host · containers & environments",x?` · ${qq(x.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Containers"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"containers-refresh",onClick:Q,disabled:H,"aria-busy":m,title:y?void 0:"Not connected — reconnect to run the survey",children:m?"Refreshing…":"Refresh"})]}),x&&r.jsxs("p",{className:"cr-sub","data-testid":"containers-sub",children:[x.summary.total," container",x.summary.total===1?"":"s"," across ",F.length," workdir",F.length===1?"":"s"," — chroxy-managed environments only."]}),x?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"containers-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",x.error.code,"):"]})," ",x.error.message]}),x?.dockerStatsNote&&r.jsx("p",{className:"cr-dim","data-testid":"containers-stats-note",children:x.dockerStatsNote}),x&&!Number.isNaN(J)&&r.jsx("p",{className:"cr-generated","data-testid":"containers-generated",children:ci(J,l())})]}),!x&&r.jsx("div",{className:"cr-empty","data-testid":"containers-empty",children:m?r.jsx("span",{children:"Running the containers survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No containers survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"containers-empty-refresh",onClick:Q,disabled:!y,title:y?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!y&&r.jsx("p",{className:"cr-dim","data-testid":"containers-not-connected",children:"Not connected to the server."})]})}),x&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"cr-chips","data-testid":"containers-chips",children:Uq.map(ie=>r.jsxs("span",{className:"cr-chip","data-testid":`containers-chip-${ie.key}`,children:[ie.accent!=="neutral"&&r.jsx("span",{className:`cr-dot cr-dot-${ie.accent}`,"aria-hidden":"true"}),ie.label,": ",r.jsx("b",{"data-testid":`containers-chip-count-${ie.key}`,children:x.summary[ie.key]})]},ie.key))}),r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"containers-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Container / backend"}),r.jsx("th",{children:"Status"}),r.jsx("th",{children:"Image"}),r.jsx("th",{children:"Sessions"}),r.jsx("th",{children:"Uptime"}),r.jsx("th",{children:"Resources"}),r.jsx("th",{children:"Actions"})]})}),r.jsx("tbody",{children:x.containers.length===0?r.jsx("tr",{"data-testid":"containers-none",children:r.jsx("td",{colSpan:7,className:"cr-dim",children:"No chroxy-managed containers or environments."})}):F.map(ie=>r.jsx(Zq,{group:ie,actioningIds:_,actionResults:k,connected:y,onAction:q},ie.cwd))})]})})]}),r.jsxs("section",{className:"cr-manage-environments","data-testid":"containers-manage",children:[r.jsx("button",{type:"button",className:"cr-action","data-testid":"containers-manage-toggle","aria-expanded":I,"aria-controls":"containers-manage-panel-region",onClick:()=>L(ie=>!ie),title:"Create or destroy persistent environments",children:I?"Hide environment management":"Manage environments"}),I&&r.jsx("div",{id:"containers-manage-panel-region","data-testid":"containers-manage-panel",children:r.jsx(Pq,{})})]}),r.jsx(Sf,{open:T!==null,title:"Destroy environment?",danger:!0,confirmLabel:"Destroy",message:T?r.jsxs(r.Fragment,{children:["This permanently removes the container for"," ",r.jsx("b",{children:T.name||T.id}),T.cwd?r.jsxs(r.Fragment,{children:[" (",T.cwd,")"]}):null,". Any unsaved work inside it is lost."]}):null,onConfirm:()=>{T&&j(T.id,"destroy"),D(null)},onCancel:()=>D(null)})]})}function Qq(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function y0({present:e,detail:t,testid:n}){return e?r.jsxs("td",{"data-testid":n,children:[r.jsx("span",{className:"cr-ok",children:"✓"}),t?r.jsxs("span",{className:"cr-dim cr-mono",children:[" ",t]}):null]}):r.jsx("td",{className:"cr-dim","data-testid":n,children:"—"})}function Jq({entry:e}){if(e.imageAllowed===null)return r.jsx("td",{className:"cr-dim","data-testid":`repo-config-verdict-${e.path}`,title:"The built-in default image is not subject to the allowlist",children:"n/a"});const t=e.imageAllowed?"ok":"bad";return r.jsx("td",{"data-testid":`repo-config-verdict-${e.path}`,children:r.jsx("span",{className:`cr-tag cr-tag-${t}`,"data-accent":t,children:e.imageAllowed?"allowed":"denied"})})}function eH({entry:e}){return e.error?r.jsxs("tr",{"data-testid":`repo-config-row-${e.path}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`repo-config-name-${e.path}`,children:e.name||e.path}),r.jsx("div",{className:"cr-dim cr-mono cr-branch",children:e.path})]}),r.jsx("td",{className:"cr-bad",colSpan:4,"data-testid":`repo-config-error-${e.path}`,role:"alert",children:e.error})]}):r.jsxs("tr",{"data-testid":`repo-config-row-${e.path}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`repo-config-name-${e.path}`,children:e.name||e.path}),r.jsx("div",{className:"cr-dim cr-mono cr-branch",children:e.path})]}),r.jsx(y0,{present:e.devcontainer.present,testid:`repo-config-devcontainer-${e.path}`}),r.jsx(y0,{present:e.compose.present,detail:e.compose.files.length>0?e.compose.files.join(", "):void 0,testid:`repo-config-compose-${e.path}`}),r.jsxs("td",{"data-testid":`repo-config-image-${e.path}`,children:[r.jsx("span",{className:"cr-mono",children:e.image??"—"}),e.imageSource?r.jsxs("span",{className:"cr-dim",children:[" · ",e.imageSource]}):null]}),r.jsx(Jq,{entry:e})]})}function tH({snapshot:e,loading:t,connected:n,onRefresh:i,now:o=Date.now}={}){const d=V(m=>m.repoRuntimeConfig),h=V(m=>m.repoRuntimeConfigLoading),l=V(m=>m.connectionPhase==="connected"),u=V(m=>m.requestRepoRuntimeConfig),f=e!==void 0?e:d,v=t!==void 0?t:h,g=n!==void 0?n:l,S=i??u,w=v||!g,E=()=>{w||S()},x=f?Date.parse(f.generatedAt):NaN;return r.jsxs("div",{className:"cr-section","data-testid":"repo-config-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"repo-config-eyebrow",children:["host · repo runtime config",f?` · ${Qq(f.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Repo runtime config"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"repo-config-refresh",onClick:E,disabled:w,"aria-busy":v,title:g?void 0:"Not connected — reconnect to run the survey",children:v?"Refreshing…":"Refresh"})]}),f&&r.jsxs("p",{className:"cr-sub","data-testid":"repo-config-sub",children:[f.summary.total," repo",f.summary.total===1?"":"s"," — read-only view of what governs each repo's container runtimes."]}),f?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"repo-config-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",f.error.code,"):"]})," ",f.error.message]}),f&&!Number.isNaN(x)&&r.jsx("p",{className:"cr-generated","data-testid":"repo-config-generated",children:ci(x,o())})]}),!f&&r.jsx("div",{className:"cr-empty","data-testid":"repo-config-empty",children:v?r.jsx("span",{children:"Running the repo runtime config survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No repo runtime config survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"repo-config-empty-refresh",onClick:E,disabled:!g,title:g?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!g&&r.jsx("p",{className:"cr-dim","data-testid":"repo-config-not-connected",children:"Not connected to the server."})]})}),f&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-chips","data-testid":"repo-config-defaults",children:[r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-backend",children:["Backend: ",r.jsx("b",{children:f.backend}),r.jsxs("span",{className:"cr-dim",children:[" (",f.backendSource,")"]})]}),r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-isolation",children:["Isolation: ",r.jsx("b",{children:f.isolation})]}),r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-allowlist",children:["Image allowlist: ",r.jsx("b",{children:f.allowlist.patterns.length}),r.jsxs("span",{className:"cr-dim",children:[" pattern",f.allowlist.patterns.length===1?"":"s"," (",f.allowlist.source,")"]})]})]}),r.jsxs("div",{className:"cr-chips","data-testid":"repo-config-summary",children:[r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-chip-total",children:["Repos: ",r.jsx("b",{children:f.summary.total})]}),r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-chip-devcontainer",children:[r.jsx("span",{className:"cr-dot cr-dot-ok","aria-hidden":"true"}),"Devcontainer: ",r.jsx("b",{children:f.summary.withDevcontainer})]}),r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-chip-compose",children:[r.jsx("span",{className:"cr-dot cr-dot-ok","aria-hidden":"true"}),"Compose: ",r.jsx("b",{children:f.summary.withCompose})]}),f.summary.imagesDenied>0&&r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-chip-denied",children:[r.jsx("span",{className:"cr-dot cr-dot-bad","aria-hidden":"true"}),"Images denied: ",r.jsx("b",{children:f.summary.imagesDenied})]}),f.summary.errored>0&&r.jsxs("span",{className:"cr-chip","data-testid":"repo-config-chip-errored",children:[r.jsx("span",{className:"cr-dot cr-dot-bad","aria-hidden":"true"}),"Errored: ",r.jsx("b",{children:f.summary.errored})]})]}),r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"repo-config-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Repo"}),r.jsx("th",{children:"Devcontainer"}),r.jsx("th",{children:"Compose"}),r.jsx("th",{children:"Image"}),r.jsx("th",{children:"Allowlist"})]})}),r.jsx("tbody",{children:f.repos.length===0?r.jsx("tr",{"data-testid":"repo-config-none",children:r.jsx("td",{colSpan:5,className:"cr-dim",children:"No managed repos found."})}):f.repos.map(m=>r.jsx(eH,{entry:m},m.path))})]})})]})]})}function b0(e,t){return e==="recycle"&&t?`recycle:${t}`:e}function nH(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function $m(e){if(e===null)return"∞";if(!Number.isFinite(e)||e<0)return"—";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60);if(n<60)return`${n}m`;const i=Math.floor(n/60),o=n%60;if(i<24)return o>0?`${i}h ${o}m`:`${i}h`;const d=Math.floor(i/24),h=i%24;return h>0?`${d}d ${h}h`:`${d}d`}function zm({id:e,pending:t,result:n}){return t?r.jsx("span",{className:"cr-dim","data-testid":`byok-action-pending-${e}`,children:"Working…"}):n?n.error?r.jsx("span",{className:"cr-bad","data-testid":`byok-action-error-${e}`,role:"alert",children:n.error}):r.jsx("span",{className:"cr-ok","data-testid":`byok-action-ok-${e}`,children:n.note??"done"}):null}function sH({bucket:e,pending:t,result:n,connected:i,onRecycle:o}){return r.jsxs("tr",{"data-testid":`byok-bucket-row-${e.key}`,children:[r.jsx("td",{children:r.jsx("b",{className:"cr-mono","data-testid":`byok-bucket-key-${e.key}`,children:e.key})}),r.jsx("td",{className:"cr-dim","data-testid":`byok-bucket-size-${e.key}`,children:e.size}),r.jsx("td",{className:"cr-dim","data-testid":`byok-bucket-idle-${e.key}`,children:$m(e.oldestIdleMs)}),r.jsxs("td",{"data-testid":`byok-bucket-actions-${e.key}`,children:[r.jsx("div",{className:"cr-actions",children:r.jsx("button",{type:"button",className:"cr-action cr-action-danger","data-testid":`byok-recycle-${e.key}`,disabled:t||!i,onClick:()=>o(e.key),title:"Evict all warm containers for this resource shape",children:"Recycle"})}),r.jsx(zm,{id:`recycle:${e.key}`,pending:t,result:n})]})]})}function iH({snapshot:e,loading:t,connected:n,onRefresh:i,actioningIds:o,actionResults:d,onAction:h,now:l=Date.now}={}){const u=V(K=>K.byokPoolStatus),f=V(K=>K.byokPoolStatusLoading),v=V(K=>K.connectionPhase==="connected"),g=V(K=>K.requestByokPoolStatus),S=V(K=>K.byokPoolActioningIds),w=V(K=>K.byokPoolActionResults),E=V(K=>K.sendByokPoolAction),x=e!==void 0?e:u,m=t!==void 0?t:f,y=n!==void 0?n:v,b=i??g,_=o??S,k=d??w,j=h??E,[T,D]=N.useState(null),[I,L]=N.useState(""),[q,H]=N.useState(""),Q=m||!y,F=()=>{Q||b()},J=x?Date.parse(x.generatedAt):NaN,ie=x?.stats??null,X=x?.limits??null,de=N.useMemo(()=>ie?.buckets??[],[ie]),fe=N.useMemo(()=>ie?Object.entries(ie.evictionsByReason).filter(([,K])=>K>0):[],[ie]),$=_.has("drain"),P=_.has("resize"),B=()=>{if(P||!y)return;const K=I.trim()===""?void 0:Number(I),le=q.trim()===""?void 0:Number(q),me={};Number.isInteger(K)&&K>=1&&(me.maxPerKey=K),Number.isInteger(le)&&le>=1&&(me.maxTotal=le),!(me.maxPerKey===void 0&&me.maxTotal===void 0)&&j("resize",me)};return r.jsxs("div",{className:"cr-section","data-testid":"byok-pool-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"byok-pool-eyebrow",children:["host · BYOK warm-container pool",x?` · ${nH(x.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"BYOK Pool"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"byok-pool-refresh",onClick:F,disabled:Q,"aria-busy":m,title:y?void 0:"Not connected — reconnect to run the survey",children:m?"Refreshing…":"Refresh"})]}),x?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"byok-pool-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",x.error.code,"):"]})," ",x.error.message]}),x&&!x.enabled&&x.note&&r.jsx("p",{className:"cr-callout","data-testid":"byok-pool-disabled",children:x.note}),x&&!Number.isNaN(J)&&r.jsx("p",{className:"cr-generated","data-testid":"byok-pool-generated",children:ci(J,l())})]}),!x&&r.jsx("div",{className:"cr-empty","data-testid":"byok-pool-empty",children:m?r.jsx("span",{children:"Running the BYOK pool survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No BYOK pool survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"byok-pool-empty-refresh",onClick:F,disabled:!y,title:y?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!y&&r.jsx("p",{className:"cr-dim","data-testid":"byok-pool-not-connected",children:"Not connected to the server."})]})}),x&&x.enabled&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-chips","data-testid":"byok-pool-chips",children:[r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-warm",children:["Warm: ",r.jsx("b",{"data-testid":"byok-pool-chip-warm-count",children:ie?.totalSize??0})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-hitrate",children:["Hit rate: ",r.jsx("b",{children:ie?`${(ie.hitRate*100).toFixed(0)}%`:"—"})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-hits",children:["Hits: ",r.jsx("b",{children:ie?.hits??0})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-misses",children:["Misses: ",r.jsx("b",{children:ie?.misses??0})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-releases",children:["Releases: ",r.jsx("b",{children:ie?.releases??0})]})]}),X&&r.jsxs("div",{className:"cr-chips","data-testid":"byok-pool-limit-chips",children:[r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-idle",children:["Idle TTL: ",r.jsx("b",{children:$m(X.idleTimeoutMs)})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-perkey",children:["Per-shape cap: ",r.jsx("b",{children:X.maxPerKey})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-total",children:["Total cap: ",r.jsx("b",{children:X.maxTotal})]}),r.jsxs("span",{className:"cr-chip","data-testid":"byok-pool-chip-maxage",children:["Max age: ",r.jsx("b",{children:$m(X.maxAgeMs)})]})]}),fe.length>0&&r.jsxs("p",{className:"cr-dim","data-testid":"byok-pool-evictions",children:["Evictions:"," ",fe.map(([K,le],me)=>r.jsxs("span",{className:"cr-mono",children:[me>0?" · ":"",K," ",le]},K))]}),r.jsxs("section",{className:"cr-actions-bar","data-testid":"byok-pool-actions",children:[r.jsx("div",{className:"cr-actions",children:r.jsx("button",{type:"button",className:"cr-action cr-action-danger","data-testid":"byok-pool-drain",disabled:$||!y,onClick:()=>D({action:"drain"}),title:"Evict every idle warm container across all shapes",children:"Drain all"})}),r.jsx(zm,{id:"drain",pending:$,result:k.drain}),r.jsxs("div",{className:"cr-resize","data-testid":"byok-pool-resize",children:[r.jsxs("label",{children:["Per-shape cap",r.jsx("input",{type:"number",min:1,"data-testid":"byok-pool-resize-perkey",value:I,placeholder:X?String(X.maxPerKey):"",onChange:K=>L(K.target.value),disabled:P||!y})]}),r.jsxs("label",{children:["Total cap",r.jsx("input",{type:"number",min:1,"data-testid":"byok-pool-resize-total",value:q,placeholder:X?String(X.maxTotal):"",onChange:K=>H(K.target.value),disabled:P||!y})]}),r.jsx("button",{type:"button",className:"cr-action","data-testid":"byok-pool-resize-apply",disabled:P||!y,onClick:B,title:"Tighten the runtime caps (the server clamps to the host-configured ceiling)",children:"Resize"}),r.jsx(zm,{id:"resize",pending:P,result:k.resize})]})]}),r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"byok-pool-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Resource shape (key)"}),r.jsx("th",{children:"Warm"}),r.jsx("th",{children:"Oldest idle"}),r.jsx("th",{children:"Actions"})]})}),r.jsx("tbody",{children:de.length===0?r.jsx("tr",{"data-testid":"byok-pool-no-buckets",children:r.jsx("td",{colSpan:4,className:"cr-dim",children:"No warm containers parked right now."})}):de.map(K=>r.jsx(sH,{bucket:K,pending:_.has(b0("recycle",K.key)),result:k[b0("recycle",K.key)],connected:y,onRecycle:le=>D({action:"recycle",key:le})},K.key))})]})})]}),r.jsx(Sf,{open:T!==null,title:T?.action==="drain"?"Drain the BYOK pool?":"Recycle this shape?",danger:!0,confirmLabel:T?.action==="drain"?"Drain all":"Recycle",message:T?.action==="drain"?r.jsxs(r.Fragment,{children:["This evicts ",r.jsx("b",{children:"every"})," idle warm container across all resource shapes. In-flight sessions keep their containers; the next acquire creates fresh ones."]}):T?.action==="recycle"?r.jsxs(r.Fragment,{children:["This evicts every idle warm container for ",r.jsx("b",{className:"cr-mono",children:T.key}),". The next acquire for that shape creates a fresh container."]}):null,onConfirm:()=>{T?.action==="drain"?j("drain"):T?.action==="recycle"&&T.key&&j("recycle",{key:T.key}),D(null)},onCancel:()=>D(null)})]})}function om(e){if(e===null||!Number.isFinite(e)||e<0)return"—";if(e<1024)return`${e} B`;const t=["KiB","MiB","GiB","TiB"];let n=e/1024,i=0;for(;n>=1024&&i<t.length-1;)n/=1024,i++;return`${n.toFixed(n<10?2:1)} ${t[i]}`}function rH(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function lm({id:e,pending:t,result:n}){return t?r.jsx("span",{className:"cr-dim","data-testid":`host-prune-pending-${e}`,children:"Pruning…"}):n?n.error?r.jsx("span",{className:"cr-bad","data-testid":`host-prune-error-${e}`,role:"alert",children:n.error}):r.jsx("span",{className:"cr-ok","data-testid":`host-prune-ok-${e}`,children:n.note??"done"}):null}function aH({snapshot:e,loading:t,connected:n,onRefresh:i,actioningIds:o,actionResults:d,onAction:h,now:l=Date.now}={}){const u=V(X=>X.hostPruneStatus),f=V(X=>X.hostPruneStatusLoading),v=V(X=>X.connectionPhase==="connected"),g=V(X=>X.requestHostPruneStatus),S=V(X=>X.hostPruneActioningIds),w=V(X=>X.hostPruneActionResults),E=V(X=>X.sendHostPruneAction),x=e!==void 0?e:u,m=t!==void 0?t:f,y=n!==void 0?n:v,b=i??g,_=o??S,k=d??w,j=h??E,[T,D]=N.useState(null),I=m||!y,L=()=>{I||b()},q=x?Date.parse(x.generatedAt):NaN,H=_.size>0,Q=(x?.summary.containerCount??0)>0,F=(x?.summary.imageCount??0)>0,J=x!=null&&x.dockerAvailable&&!Q&&!F,ie={containers:"Prune containers",images:"Prune images",all:"Prune all"};return r.jsxs("div",{className:"cr-section","data-testid":"host-prune-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"host-prune-eyebrow",children:["host · reclaimable docker pressure",x?` · ${rH(x.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Host prune"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"host-prune-refresh",onClick:L,disabled:I,"aria-busy":m,title:y?void 0:"Not connected — reconnect to run the survey",children:m?"Refreshing…":"Refresh"})]}),x?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"host-prune-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",x.error.code,"):"]})," ",x.error.message]}),x&&!x.dockerAvailable&&r.jsx("p",{className:"cr-callout","data-testid":"host-prune-no-docker",children:x.note||"docker is unavailable on this host."}),x?.dockerAvailable&&x.note&&r.jsx("p",{className:"cr-dim","data-testid":"host-prune-note",children:x.note}),x&&!Number.isNaN(q)&&r.jsx("p",{className:"cr-generated","data-testid":"host-prune-generated",children:ci(q,l())})]}),!x&&r.jsx("div",{className:"cr-empty","data-testid":"host-prune-empty",children:m?r.jsx("span",{children:"Running the host prune survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No host prune survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"host-prune-empty-refresh",onClick:L,disabled:!y,title:y?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!y&&r.jsx("p",{className:"cr-dim","data-testid":"host-prune-not-connected",children:"Not connected to the server."})]})}),x?.dockerAvailable&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-chips","data-testid":"host-prune-chips",children:[r.jsxs("span",{className:"cr-chip","data-testid":"host-prune-chip-containers",children:["Stopped containers: ",r.jsx("b",{"data-testid":"host-prune-chip-containers-count",children:x.summary.containerCount})]}),r.jsxs("span",{className:"cr-chip","data-testid":"host-prune-chip-images",children:["Orphan images: ",r.jsx("b",{"data-testid":"host-prune-chip-images-count",children:x.summary.imageCount})]}),r.jsxs("span",{className:"cr-chip","data-testid":"host-prune-chip-reclaimable",children:["Reclaimable: ",r.jsxs("b",{children:["~",om(x.summary.reclaimableBytes)]})]})]}),r.jsxs("section",{className:"cr-actions-bar","data-testid":"host-prune-actions",children:[r.jsxs("div",{className:"cr-actions",children:[r.jsx("button",{type:"button",className:"cr-action cr-action-danger","data-testid":"host-prune-containers",disabled:H||!y||!Q,onClick:()=>D("containers"),title:"Remove all stopped chroxy containers",children:ie.containers}),r.jsx("button",{type:"button",className:"cr-action cr-action-danger","data-testid":"host-prune-images",disabled:H||!y||!F,onClick:()=>D("images"),title:"Remove all orphan chroxy snapshot images",children:ie.images}),r.jsx("button",{type:"button",className:"cr-action cr-action-danger","data-testid":"host-prune-all",disabled:H||!y||!Q&&!F,onClick:()=>D("all"),title:"Remove all reclaimable chroxy containers + images",children:ie.all})]}),r.jsx(lm,{id:"containers",pending:_.has("containers"),result:k.containers}),r.jsx(lm,{id:"images",pending:_.has("images"),result:k.images}),r.jsx(lm,{id:"all",pending:_.has("all"),result:k.all})]}),J&&r.jsx("p",{className:"cr-dim","data-testid":"host-prune-clean",children:"Nothing reclaimable — no stopped chroxy containers or orphan snapshot images."}),Q&&r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"host-prune-containers-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Stopped container"}),r.jsx("th",{children:"State"}),r.jsx("th",{children:"Size"})]})}),r.jsx("tbody",{children:x.containers.map(X=>r.jsxs("tr",{"data-testid":`host-prune-container-${X.id}`,children:[r.jsxs("td",{children:[r.jsx("b",{className:"cr-mono",children:X.name})," ",r.jsx("span",{className:"cr-dim cr-mono",children:X.id.slice(0,12)})]}),r.jsx("td",{className:"cr-dim",children:X.state}),r.jsx("td",{className:"cr-dim",children:om(X.sizeBytes)})]},X.id))})]})}),F&&r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"host-prune-images-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Orphan image"}),r.jsx("th",{children:"Size"})]})}),r.jsx("tbody",{children:x.images.map(X=>r.jsxs("tr",{"data-testid":`host-prune-image-${X.id}`,children:[r.jsxs("td",{children:[r.jsx("b",{className:"cr-mono",children:X.ref})," ",r.jsx("span",{className:"cr-dim cr-mono",children:X.id.slice(0,12)})]}),r.jsx("td",{className:"cr-dim",children:om(X.sizeBytes)})]},X.id))})]})})]}),r.jsx(Sf,{open:T!==null,title:"Prune chroxy docker resources?",danger:!0,confirmLabel:T?ie[T]:"Prune",message:T?r.jsxs(r.Fragment,{children:["This permanently removes"," ",T==="containers"?"all stopped chroxy containers":T==="images"?"all orphan chroxy snapshot images":"all reclaimable chroxy containers and orphan snapshot images",". Retained snapshots and live environments are never touched. This cannot be undone."]}):null,onConfirm:()=>{T&&j(T),D(null)},onCancel:()=>D(null)})]})}function Ag(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function oH({udid:e,pending:t,result:n}){return t?r.jsx("span",{className:"cr-dim","data-testid":`simulator-pending-${e}`,children:"Working…"}):n?n.error?r.jsx("span",{className:"cr-bad","data-testid":`simulator-error-${e}`,role:"alert",children:n.error}):r.jsx("span",{className:"cr-ok","data-testid":`simulator-ok-${e}`,children:n.note??"done"}):null}function lH({snapshot:e,loading:t,connected:n,onRefresh:i,actioningIds:o,actionResults:d,onAction:h,now:l=Date.now}={}){const u=V(q=>q.simulatorStatus),f=V(q=>q.simulatorStatusLoading),v=V(q=>q.connectionPhase==="connected"),g=V(q=>q.requestSimulatorStatus),S=V(q=>q.simulatorActioningIds),w=V(q=>q.simulatorActionResults),E=V(q=>q.sendSimulatorAction),x=e!==void 0?e:u,m=t!==void 0?t:f,y=n!==void 0?n:v,b=i??g,_=o??S,k=d??w,j=h??E,T=m||!y,D=()=>{T||b()},I=x?Date.parse(x.generatedAt):NaN,L=x?.readyForMaestro;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-section","data-testid":"device-runtimes-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"device-runtimes-eyebrow",children:["host · ios simulators",x?` · ${Ag(x.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Device runtimes"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"device-runtimes-refresh",onClick:D,disabled:T,"aria-busy":m,title:y?void 0:"Not connected — reconnect to run the survey",children:m?"Refreshing…":"Refresh"})]}),x?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"device-runtimes-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",x.error.code,"):"]})," ",x.error.message]}),x&&!x.available&&r.jsx("p",{className:"cr-callout","data-testid":"device-runtimes-unavailable",children:x.note||"iOS simulators are not available on this host."}),x&&!Number.isNaN(I)&&r.jsx("p",{className:"cr-generated","data-testid":"device-runtimes-generated",children:ci(I,l())})]}),!x&&r.jsx("div",{className:"cr-empty","data-testid":"device-runtimes-empty",children:m?r.jsx("span",{children:"Running the simulator survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No simulator survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"device-runtimes-empty-refresh",onClick:D,disabled:!y,title:y?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!y&&r.jsx("p",{className:"cr-dim","data-testid":"device-runtimes-not-connected",children:"Not connected to the server."})]})}),x?.available&&L&&r.jsxs(r.Fragment,{children:[r.jsx("section",{className:`cr-callout ${L.ready?"cr-callout-ok":"cr-callout-bad"}`,"data-testid":"device-runtimes-verdict","data-ready":L.ready?"true":"false",children:L.ready?r.jsxs("p",{"data-testid":"device-runtimes-verdict-ready",children:[r.jsx("b",{children:"✓ Ready for Maestro"}),L.bootedSimulator?` — ${L.bootedSimulator} booted, Metro + mock server reachable.`:""]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{"data-testid":"device-runtimes-verdict-not-ready",children:r.jsx("b",{children:"✗ Not ready for Maestro"})}),r.jsx("ul",{className:"cr-reasons","data-testid":"device-runtimes-verdict-reasons",children:L.reasons.map((q,H)=>r.jsx("li",{children:q},H))})]})}),x.devices.length===0?r.jsx("p",{className:"cr-dim","data-testid":"device-runtimes-no-devices",children:"No iOS simulators are installed on this host."}):r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"device-runtimes-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Simulator"}),r.jsx("th",{children:"Runtime"}),r.jsx("th",{children:"State"}),r.jsx("th",{children:"Action"})]})}),r.jsx("tbody",{children:x.devices.map(q=>{const H=q.state==="Booted",Q=_.has(q.udid);return r.jsxs("tr",{"data-testid":`simulator-row-${q.udid}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`simulator-name-${q.udid}`,children:q.name})," ",r.jsx("span",{className:"cr-dim cr-mono",children:q.udid.slice(0,8)}),q.deviceType&&q.deviceType!==q.name&&r.jsx("div",{className:"cr-dim","data-testid":`simulator-devicetype-${q.udid}`,children:q.deviceType})]}),r.jsx("td",{className:"cr-dim","data-testid":`simulator-runtime-${q.udid}`,children:q.runtime}),r.jsx("td",{children:r.jsx("span",{className:`cr-tag ${H?"cr-tag-ok":"cr-tag-dim"}`,"data-testid":`simulator-state-${q.udid}`,children:q.state})}),r.jsxs("td",{"data-testid":`simulator-actions-${q.udid}`,children:[H?r.jsx("button",{type:"button",className:"cr-action","data-testid":`simulator-shutdown-${q.udid}`,disabled:Q||!y,onClick:()=>j("shutdown",q.udid),title:"Shut down this simulator",children:"Shut down"}):r.jsx("button",{type:"button",className:"cr-action","data-testid":`simulator-boot-${q.udid}`,disabled:Q||!y,onClick:()=>j("boot",q.udid),title:"Boot this simulator",children:"Boot"})," ",r.jsx(oH,{udid:q.udid,pending:Q,result:k[q.udid]})]})]},q.udid)})})]})})]})]}),r.jsx(fH,{now:l}),r.jsx(uH,{now:l})]})}function cH({distro:e,pending:t,result:n}){return t?r.jsx("span",{className:"cr-dim","data-testid":`wsl-pending-${e}`,children:"Working…"}):n?n.error?r.jsx("span",{className:"cr-bad","data-testid":`wsl-error-${e}`,role:"alert",children:n.error}):r.jsx("span",{className:"cr-ok","data-testid":`wsl-ok-${e}`,children:n.note??"done"}):null}function uH({snapshot:e,loading:t,connected:n,onRefresh:i,actioningIds:o,actionResults:d,onAction:h,now:l=Date.now}={}){const u=V(L=>L.wslStatus),f=V(L=>L.wslStatusLoading),v=V(L=>L.connectionPhase==="connected"),g=V(L=>L.requestWslStatus),S=V(L=>L.wslActioningIds),w=V(L=>L.wslActionResults),E=V(L=>L.sendWslAction),x=e!==void 0?e:u,m=t!==void 0?t:f,y=n!==void 0?n:v,b=i??g,_=o??S,k=d??w,j=h??E;N.useEffect(()=>{e===void 0&&v&&u===null&&!f&&g()},[e,v,u,f,g]);const T=m||!y,D=()=>{T||b()},I=x?Date.parse(x.generatedAt):NaN;return r.jsxs("div",{className:"cr-section","data-testid":"wsl-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"wsl-eyebrow",children:["host · wsl2 distros",x?` · ${Ag(x.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h2",{className:"cr-title",children:"WSL2 distros"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"wsl-refresh",onClick:D,disabled:T,"aria-busy":m,title:y?void 0:"Not connected — reconnect to run the survey",children:m?"Refreshing…":"Refresh"})]}),x?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"wsl-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",x.error.code,"):"]})," ",x.error.message]}),x&&!x.available&&r.jsx("p",{className:"cr-callout","data-testid":"wsl-unavailable",children:x.note||"WSL is not available on this host."}),x&&!Number.isNaN(I)&&r.jsx("p",{className:"cr-generated","data-testid":"wsl-generated",children:ci(I,l())})]}),!x&&r.jsx("div",{className:"cr-empty","data-testid":"wsl-empty",children:m?r.jsx("span",{children:"Running the WSL survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No WSL survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"wsl-empty-refresh",onClick:D,disabled:!y,title:y?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!y&&r.jsx("p",{className:"cr-dim","data-testid":"wsl-not-connected",children:"Not connected to the server."})]})}),x?.available&&(x.distros.length===0?r.jsx("p",{className:"cr-dim","data-testid":"wsl-no-distros",children:"No WSL distros are installed on this host."}):r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"wsl-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Distro"}),r.jsx("th",{children:"Version"}),r.jsx("th",{children:"State"}),r.jsx("th",{children:"Action"})]})}),r.jsx("tbody",{children:x.distros.map(L=>{const q=L.state==="Running",H=L.state==="Stopped",Q=_.has(L.name);return r.jsxs("tr",{"data-testid":`wsl-row-${L.name}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`wsl-name-${L.name}`,children:L.name})," ",L.isDefault&&r.jsx("span",{className:"cr-tag cr-tag-ok","data-testid":`wsl-default-${L.name}`,children:"default"})]}),r.jsx("td",{className:"cr-dim","data-testid":`wsl-version-${L.name}`,children:L.version===null?"—":`WSL ${L.version}`}),r.jsx("td",{children:r.jsx("span",{className:`cr-tag ${q?"cr-tag-ok":"cr-tag-dim"}`,"data-testid":`wsl-state-${L.name}`,children:L.state})}),r.jsxs("td",{"data-testid":`wsl-actions-${L.name}`,children:[q?r.jsx("button",{type:"button",className:"cr-action","data-testid":`wsl-terminate-${L.name}`,disabled:Q||!y,onClick:()=>j("terminate",L.name),title:"Terminate this distro",children:"Terminate"}):r.jsx("button",{type:"button",className:"cr-action","data-testid":`wsl-start-${L.name}`,disabled:Q||!y||!H,onClick:()=>j("start",L.name),title:H?"Start this distro":`Cannot start (state: ${L.state})`,children:"Start"})," ",r.jsx(cH,{distro:L.name,pending:Q,result:k[L.name]})]})]},L.name)})})]})}))]})}function dH({id:e,pending:t,result:n}){return t?r.jsx("span",{className:"cr-dim","data-testid":`emulator-pending-${e}`,children:"Working…"}):n?n.error?r.jsx("span",{className:"cr-bad","data-testid":`emulator-error-${e}`,role:"alert",children:n.error}):r.jsx("span",{className:"cr-ok","data-testid":`emulator-ok-${e}`,children:n.note??"done"}):null}function fH({snapshot:e,loading:t,connected:n,onRefresh:i,actioningIds:o,actionResults:d,onAction:h,now:l=Date.now}={}){const u=V(q=>q.emulatorStatus),f=V(q=>q.emulatorStatusLoading),v=V(q=>q.connectionPhase==="connected"),g=V(q=>q.requestEmulatorStatus),S=V(q=>q.emulatorActioningIds),w=V(q=>q.emulatorActionResults),E=V(q=>q.sendEmulatorAction),x=e!==void 0?e:u,m=t!==void 0?t:f,y=n!==void 0?n:v,b=i??g,_=o??S,k=d??w,j=h??((q,H)=>E(q,H));N.useEffect(()=>{e===void 0&&v&&u===null&&!f&&g()},[e,v,u,f,g]);const T=m||!y,D=()=>{T||b()},I=x?Date.parse(x.generatedAt):NaN,L=x?.readyForMaestro;return r.jsxs("div",{className:"cr-section","data-testid":"emulator-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"emulator-eyebrow",children:["host · android emulators",x?` · ${Ag(x.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h2",{className:"cr-title",children:"Android emulators"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"emulator-refresh",onClick:D,disabled:T,"aria-busy":m,title:y?void 0:"Not connected — reconnect to run the survey",children:m?"Refreshing…":"Refresh"})]}),x?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"emulator-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",x.error.code,"):"]})," ",x.error.message]}),x&&!x.available&&r.jsx("p",{className:"cr-callout","data-testid":"emulator-unavailable",children:x.note||"Android emulators are not available on this host."}),x&&!Number.isNaN(I)&&r.jsx("p",{className:"cr-generated","data-testid":"emulator-generated",children:ci(I,l())})]}),!x&&r.jsx("div",{className:"cr-empty","data-testid":"emulator-empty",children:m?r.jsx("span",{children:"Running the emulator survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No emulator survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"emulator-empty-refresh",onClick:D,disabled:!y,title:y?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!y&&r.jsx("p",{className:"cr-dim","data-testid":"emulator-not-connected",children:"Not connected to the server."})]})}),x?.available&&L&&r.jsxs(r.Fragment,{children:[r.jsx("section",{className:`cr-callout ${L.ready?"cr-callout-ok":"cr-callout-bad"}`,"data-testid":"emulator-verdict","data-ready":L.ready?"true":"false",children:L.ready?r.jsxs("p",{"data-testid":"emulator-verdict-ready",children:[r.jsx("b",{children:"✓ Ready for Maestro"}),L.runningDevice?` — ${L.runningDevice} running, Metro + mock server reachable.`:""]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{"data-testid":"emulator-verdict-not-ready",children:r.jsx("b",{children:"✗ Not ready for Maestro"})}),r.jsx("ul",{className:"cr-reasons","data-testid":"emulator-verdict-reasons",children:L.reasons.map((q,H)=>r.jsx("li",{children:q},H))})]})}),x.devices.length===0?r.jsx("p",{className:"cr-dim","data-testid":"emulator-no-devices",children:"No AVDs are installed on this host."}):r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"emulator-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Emulator"}),r.jsx("th",{children:"State"}),r.jsx("th",{children:"Action"})]})}),r.jsx("tbody",{children:x.devices.map(q=>{const H=q.state!=="stopped",Q=H?q.serial??q.avd??"":q.avd??"",F=Q.length>0&&_.has(Q),J=q.serial||q.avd||"unknown";return r.jsxs("tr",{"data-testid":`emulator-row-${J}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`emulator-name-${J}`,children:q.avd||q.serial||"unknown"})," ",q.serial&&r.jsx("span",{className:"cr-dim cr-mono",children:q.serial})]}),r.jsx("td",{children:r.jsx("span",{className:`cr-tag ${q.state==="running"?"cr-tag-ok":q.state==="starting"?"cr-tag-warn":"cr-tag-dim"}`,"data-testid":`emulator-state-${J}`,children:q.state})}),r.jsxs("td",{"data-testid":`emulator-actions-${J}`,children:[H?r.jsx("button",{type:"button",className:"cr-action","data-testid":`emulator-kill-${J}`,disabled:F||!y||!q.serial,onClick:()=>q.serial&&j("kill",{serial:q.serial}),title:"Kill this emulator",children:"Kill"}):r.jsx("button",{type:"button",className:"cr-action","data-testid":`emulator-boot-${J}`,disabled:F||!y||!q.avd,onClick:()=>q.avd&&j("boot",{avd:q.avd}),title:"Boot this emulator",children:"Boot"})," ",Q.length>0&&r.jsx(dH,{id:J,pending:F,result:k[Q]})]})]},J)})})]})})]})]})}const hH=[{key:"total",label:"Repos",accent:"neutral"},{key:"configured",label:"Configured",accent:"ok"},{key:"notConfigured",label:"Not configured",accent:"neutral"},{key:"degraded",label:"Degraded",accent:"warn"},{key:"relayInstalled",label:"Relay installed",accent:"neutral"},{key:"relayFailing",label:"Relay failing",accent:"bad"},{key:"relayDrifted",label:"Relay drifted",accent:"warn"}];function pH(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function mH(e){return!Number.isFinite(e)||e<0?"—":e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function dk(e,t){if(!e)return"—";const n=Date.parse(e);if(Number.isNaN(n))return"—";const i=Math.floor((t-n)/1e3);if(!Number.isFinite(i)||i<60)return"just now";const o=Math.floor(i/60);if(o<60)return`${o}m ago`;const d=Math.floor(o/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}function gH(e){return!e||!e.configured?{label:"Not configured",accent:"neutral"}:e.reason!==null?{label:"Degraded",accent:"warn"}:{label:"Configured",accent:"ok"}}function vH({repo:e}){const{label:t,accent:n}=gH(e.repoMemory);return r.jsx("span",{className:`cr-tag${n==="neutral"?"":` cr-tag-${n}`}`,"data-testid":`integration-status-${e.name}`,"data-accent":n,title:e.repoMemory?.reason??void 0,children:t})}function yH({repo:e}){const t=e.repoMemory;return!t||!t.configured||!t.cache?r.jsx("td",{className:"cr-dim","data-testid":`integration-cache-${e.name}`,children:"—"}):t.cache.present?r.jsx("td",{"data-testid":`integration-cache-${e.name}`,children:r.jsx("span",{className:"cr-mono",children:mH(t.cache.sizeBytes)})}):r.jsx("td",{className:"cr-dim","data-testid":`integration-cache-${e.name}`,children:"no cache yet"})}function bH({repo:e}){const t=e.repoMemory?.report??null;if(!t)return r.jsx("td",{className:"cr-dim","data-testid":`integration-ratio-${e.name}`,children:"—"});const n=t.cacheHits+t.cacheMisses;return n===0?r.jsx("td",{className:"cr-dim","data-testid":`integration-ratio-${e.name}`,children:"no events"}):r.jsxs("td",{"data-testid":`integration-ratio-${e.name}`,children:[r.jsxs("span",{className:"cr-ok",children:[(t.cacheHitRatio*100).toFixed(1),"%"]}),r.jsxs("span",{className:"cr-dim cr-mono",children:[" (",t.cacheHits,"/",n,")"]})]})}function _H({repo:e}){const t=e.repoMemory?.report??null,n=t?.topMissedQueries??[];if(!t||n.length===0)return r.jsx("td",{className:"cr-dim","data-testid":`integration-missed-${e.name}`,children:"—"});const i=n.reduce((d,h)=>d+h.count,0),o=n.map(d=>`${d.query} (${d.count})`).join(`
|
|
105
|
-
`);return r.jsxs("td",{"data-testid":`integration-missed-${e.name}`,title:o,children:[r.jsx("span",{className:"cr-warn",children:i}),r.jsxs("span",{className:"cr-dim cr-mono",children:[" (",n.length,")"]})]})}const SH={ok:{label:"OK",accent:"ok"},failing:{label:"Failing",accent:"bad"},drifted:{label:"Drifted",accent:"warn"},not_installed:{label:"Not installed",accent:"neutral"},unknown:{label:"Unknown",accent:"neutral"}};function Yc(e){return e.repoRelay??null}function xH({repo:e}){const t=Yc(e),{label:n,accent:i}=SH[t?.verdict??"not_installed"];return r.jsx("span",{className:`cr-tag${i==="neutral"?"":` cr-tag-${i}`}`,"data-testid":`integration-relay-status-${e.name}`,"data-accent":i,title:t?.reason??void 0,children:n})}function wH({repo:e}){const t=Yc(e);if(!t||!t.installed)return r.jsx("td",{className:"cr-dim","data-testid":`integration-relay-version-${e.name}`,children:"—"});const n=t.pinnedVersion??(t.pinnedSha?t.pinnedSha.slice(0,7):null),i=t.verdict==="drifted",o=t.driftUnknown?t.reason??(t.pinnedSha?"sha pin has no # vX.Y.Z comment — drift unknown":"pin does not resolve to a version — drift unknown"):void 0;if(!n&&!t.latestVersion)return r.jsx("td",{className:"cr-dim","data-testid":`integration-relay-version-${e.name}`,title:o,children:"—"});const d=!!(t.latestVersion&&n!==t.latestVersion&&(i||t.driftUnknown));return r.jsxs("td",{className:"cr-mono","data-testid":`integration-relay-version-${e.name}`,title:o,children:[r.jsx("span",{className:i?"cr-warn":void 0,children:n??"—"}),d&&r.jsxs("span",{className:"cr-dim",children:[" → ",t.latestVersion]})]})}function kH({repo:e,now:t}){const n=Yc(e),i=n?.runs[0]??null;if(!n||!n.installed||!i)return r.jsx("td",{className:"cr-dim","data-testid":`integration-relay-lastrun-${e.name}`,title:n?.reason??void 0,children:n?.workflowUrl?r.jsx("a",{href:n.workflowUrl,target:"_blank",rel:"noopener noreferrer","data-testid":`integration-relay-link-${e.name}`,title:"Open the workflow in the GitHub Actions UI",children:"—"}):"—"});const o=i.conclusion??i.status??"unknown",d=i.conclusion==="success"?"cr-ok":i.conclusion==="failure"?"cr-bad":"cr-dim";return r.jsxs("td",{"data-testid":`integration-relay-lastrun-${e.name}`,title:n.reason??void 0,children:[r.jsx("span",{className:d,children:o}),r.jsxs("span",{className:"cr-dim",children:[" · ",dk(i.createdAt,t)]}),n.workflowUrl&&r.jsxs(r.Fragment,{children:[" ",r.jsx("a",{href:n.workflowUrl,target:"_blank",rel:"noopener noreferrer","data-testid":`integration-relay-link-${e.name}`,title:"Open the workflow in the GitHub Actions UI",children:"↗"})]})]})}function CH({repo:e}){const t=Yc(e);return!t||!t.installed||t.failureStreak===0?r.jsx("td",{className:"cr-dim","data-testid":`integration-relay-streak-${e.name}`,children:"—"}):r.jsx("td",{"data-testid":`integration-relay-streak-${e.name}`,children:r.jsxs("span",{className:"cr-bad",children:[t.failureStreak,"×"]})})}function EH({repo:e,reindexing:t,result:n,connected:i,onReindex:o}){if(e.repoMemory?.configured!==!0)return r.jsx("td",{className:"cr-dim","data-testid":`integration-actions-${e.name}`,children:"—"});const d=t||!i;return r.jsxs("td",{"data-testid":`integration-actions-${e.name}`,children:[r.jsx("button",{type:"button",className:"cr-refresh","data-testid":`integration-reindex-${e.name}`,onClick:()=>{d||o(e.path)},disabled:d,"aria-busy":t,title:i?"Run repo-memory index to refresh the summary cache":"Not connected — reconnect to reindex",children:t?"Reindexing…":"Reindex"}),!t&&n&&n.error!==null&&r.jsx("div",{className:"cr-bad","data-testid":`integration-reindex-error-${e.name}`,children:n.error}),!t&&n&&n.error===null&&r.jsx("div",{className:"cr-dim","data-testid":`integration-reindex-result-${e.name}`,children:n.counts?`✓ ${n.counts.summarized} summarized · ${n.counts.fresh} fresh · ${n.counts.skipped} skipped`:"✓ reindexed — refresh for cache stats"})]})}function NH({repo:e,rerunning:t,result:n,connected:i,onRerun:o}){const d=Yc(e);if(!d||!d.installed)return r.jsx("td",{className:"cr-dim","data-testid":`integration-relay-actions-${e.name}`,children:"—"});const h=d.runs[0]??null,l=h!==null&&h.conclusion==="failure",u=t||!i;return r.jsxs("td",{"data-testid":`integration-relay-actions-${e.name}`,children:[l&&r.jsx("button",{type:"button",className:"cr-refresh","data-testid":`integration-relay-rerun-${e.name}`,onClick:()=>{u||o(e.path,h.databaseId)},disabled:u,"aria-busy":t,title:i?"Re-run the failed repo-relay run via gh run rerun":"Not connected — reconnect to re-run",children:t?"Re-running…":"Re-run"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":`integration-relay-syncnow-${e.name}`,disabled:!0,title:"Blocked on blamechris/repo-relay#168 — repo-relay has no workflow_dispatch trigger yet, so a manual relay pass cannot be fired",children:"Sync now"}),!t&&n&&n.error!==null&&r.jsx("div",{className:"cr-bad","data-testid":`integration-relay-rerun-error-${e.name}`,children:n.error}),!t&&n&&n.error===null&&r.jsx("div",{className:"cr-dim","data-testid":`integration-relay-rerun-result-${e.name}`,children:"✓ re-run requested — refresh to see the new run"})]})}function jH({repo:e,now:t,reindexing:n,reindexResult:i,rerunning:o,rerunResult:d,connected:h,onReindex:l,onRelayRerun:u}){const f=e.repoMemory,v=f?.report??null,g=f?.configured===!0,S=v?.lastActivity??f?.cache?.lastModified??null;return r.jsxs("tr",{"data-testid":`integration-row-${e.name}`,children:[r.jsxs("td",{children:[r.jsx("b",{"data-testid":`integration-name-${e.name}`,children:e.name}),r.jsx("div",{className:"cr-dim cr-mono cr-branch",title:e.path,children:e.path})]}),r.jsx("td",{children:r.jsx(vH,{repo:e})}),r.jsx("td",{className:"cr-dim","data-testid":`integration-config-${e.name}`,children:g?r.jsxs(r.Fragment,{children:[f.summarizer??"—",f.toolGroups.length>0&&r.jsxs("span",{className:"cr-mono",children:[" · ",f.toolGroups.join(", ")]})]}):"—"}),r.jsx(yH,{repo:e}),r.jsx(bH,{repo:e}),r.jsx(_H,{repo:e}),r.jsx("td",{className:"cr-dim cr-mono","data-testid":`integration-tokens-${e.name}`,children:v?`~${v.estimatedTokensSaved.toLocaleString("en-US")}`:"—"}),r.jsx("td",{className:"cr-dim","data-testid":`integration-stale-${e.name}`,children:v&&v.cacheEntryCount!==null?`${v.cacheEntryCount}${v.staleEntryCount!==null&&v.staleEntryCount>0?` (${v.staleEntryCount} stale)`:""}`:"—"}),r.jsx("td",{className:"cr-dim","data-testid":`integration-activity-${e.name}`,children:dk(S,t)}),r.jsx(EH,{repo:e,reindexing:n,result:i,connected:h,onReindex:l}),r.jsx("td",{children:r.jsx(xH,{repo:e})}),r.jsx(wH,{repo:e}),r.jsx(kH,{repo:e,now:t}),r.jsx(CH,{repo:e}),r.jsx(NH,{repo:e,rerunning:o,result:d,connected:h,onRerun:u})]})}function AH({snapshot:e,loading:t,connected:n,onRefresh:i,reindexingRepoPaths:o,reindexResults:d,onReindex:h,relayRerunningRepoPaths:l,relayRerunResults:u,onRelayRerun:f,now:v=Date.now}={}){const g=V($=>$.integrationStatus),S=V($=>$.integrationStatusLoading),w=V($=>$.connectionPhase==="connected"),E=V($=>$.requestIntegrationStatus),x=V($=>$.reindexingRepoPaths),m=V($=>$.reindexResults),y=V($=>$.sendRepoMemoryReindex),b=V($=>$.relayRerunningRepoPaths),_=V($=>$.relayRerunResults),k=V($=>$.sendRepoRelayRerun),j=e!==void 0?e:g,T=t!==void 0?t:S,D=n!==void 0?n:w,I=i??E,L=o??x,q=d??m,H=h??y,Q=l??b,F=u??_,J=f??k,ie=T||!D,X=()=>{ie||I()},de=j?Date.parse(j.generatedAt):NaN,fe=v();return r.jsxs("div",{className:"cr-section","data-testid":"integration-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"integration-eyebrow",children:["host · integrations",j?` · ${pH(j.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Integrations"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"integration-refresh",onClick:X,disabled:ie,"aria-busy":T,title:D?void 0:"Not connected — reconnect to run the survey",children:T?"Refreshing…":"Refresh"})]}),j&&r.jsxs("p",{className:"cr-sub","data-testid":"integration-sub",children:["repo-memory and repo-relay status across ",j.repos.length," repo",j.repos.length===1?"":"s"," under"," ",r.jsx("span",{className:"cr-mono",children:j.root})," — config, cache, and telemetry from the read-only CLI report; workflow presence, version drift, and run health from the filesystem + gh."]}),j&&!Number.isNaN(de)&&r.jsx("p",{className:"cr-generated","data-testid":"integration-generated",children:ci(de,fe)})]}),!j&&r.jsx("div",{className:"cr-empty","data-testid":"integration-empty",children:T?r.jsx("span",{children:"Running the integrations survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No integrations survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"integration-empty-refresh",onClick:X,disabled:!D,title:D?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!D&&r.jsx("p",{className:"cr-dim","data-testid":"integration-not-connected",children:"Not connected to the server."})]})}),j&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"cr-chips","data-testid":"integration-chips",children:hH.map($=>r.jsxs("span",{className:"cr-chip","data-testid":`integration-chip-${$.key}`,children:[$.accent!=="neutral"&&r.jsx("span",{className:`cr-dot cr-dot-${$.accent}`,"aria-hidden":"true"}),$.label,": ",r.jsx("b",{"data-testid":`integration-chip-count-${$.key}`,children:j.summary[$.key]??0})]},$.key))}),j.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"integration-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",j.error.code,"):"]})," ",j.error.message]}),j.repoMemoryCli&&!j.repoMemoryCli.found&&r.jsxs("div",{className:"cr-callout","data-testid":"integration-cli-note",children:[r.jsx("b",{children:"repo-memory CLI unavailable:"})," ",j.repoMemoryCli.note??"binary not found"," — config and cache columns still populate; the telemetry columns are degraded for every configured repo."]}),j.ghCli&&!j.ghCli.found&&r.jsxs("div",{className:"cr-callout","data-testid":"integration-gh-note",children:[r.jsx("b",{children:"gh CLI unavailable:"})," ",j.ghCli.note??"binary not found"," — relay install and version-pin columns still populate from the filesystem; the run and release columns are degraded for every repo with repo-relay installed."]}),r.jsx("section",{className:"cr-table-wrap",children:r.jsxs("table",{className:"cr-table","data-testid":"integration-table",children:[r.jsxs("thead",{children:[r.jsxs("tr",{children:[r.jsx("th",{rowSpan:2,children:"Repo"}),r.jsx("th",{colSpan:9,className:"cr-th-group","data-testid":"integration-group-memory",children:"repo-memory"}),r.jsx("th",{colSpan:5,className:"cr-th-group","data-testid":"integration-group-relay",children:"repo-relay"})]}),r.jsxs("tr",{children:[r.jsx("th",{children:"Status"}),r.jsx("th",{children:"Summarizer / tools"}),r.jsx("th",{children:"Cache"}),r.jsx("th",{children:"Hit ratio"}),r.jsx("th",{children:"Missed"}),r.jsx("th",{children:"Tokens saved"}),r.jsx("th",{children:"Entries"}),r.jsx("th",{children:"Last activity"}),r.jsx("th",{children:"Actions"}),r.jsx("th",{children:"Status"}),r.jsx("th",{children:"Version"}),r.jsx("th",{children:"Last run"}),r.jsx("th",{children:"Streak"}),r.jsx("th",{children:"Actions"})]})]}),r.jsx("tbody",{children:j.repos.length===0?r.jsx("tr",{"data-testid":"integration-no-repos",children:r.jsxs("td",{colSpan:15,className:"cr-dim",children:["No repos found under ",j.root,"."]})}):j.repos.map($=>r.jsx(jH,{repo:$,now:fe,reindexing:L.has($.path),reindexResult:q[$.path],rerunning:Q.has($.path),rerunResult:F[$.path],connected:D,onReindex:H,onRelayRerun:J},$.path))})]})})]})]})}function RH(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function TH(e,t){if(!e)return"—";const n=Date.parse(e);if(Number.isNaN(n))return"—";const i=Math.floor((t-n)/1e3);if(!Number.isFinite(i)||i<60)return"just now";const o=Math.floor(i/60);if(o<60)return`${o}m ago`;const d=Math.floor(o/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}function fk(e){if(!e)return null;const t=e.split(/[\\/]+/).filter(Boolean);return t.length>0?t[t.length-1]:null}function IH(e){const t=new Set;for(const n of e){const i=fk(n?.cwd);i&&t.add(i)}return t}const MH={push:"Push",pull_request:"PR",issues:"Issue",ping:"Ping"};function DH(e,t,n){const i=e.slice().reverse(),o=!n&&t.size>0;let d=0;const h=new Map;for(const u of i){if(o){const g=fk(u.repo);if(!g||!t.has(g)){d++;continue}}const f=u.repo??"(unknown repo)",v=h.get(f);v?v.push(u):h.set(f,[u])}return{groups:[...h.entries()].map(([u,f])=>({repo:u,events:f})),hiddenCount:d}}function LH({kind:e}){return r.jsx("span",{className:"cr-tag","data-testid":`repo-event-kind-${e}`,"data-accent":"neutral",children:MH[e]})}function OH({event:e,now:t}){const n=typeof e.url=="string"&&e.url.startsWith("https://")?e.url:null;return r.jsxs("li",{className:"cr-repo-event","data-testid":"repo-event-row",children:[r.jsx(LH,{kind:e.kind}),r.jsx("span",{className:"cr-repo-event-summary","data-testid":"repo-event-summary",children:e.summary}),e.actor&&r.jsxs("span",{className:"cr-dim","data-testid":"repo-event-actor",children:[" · ",e.actor]}),r.jsxs("span",{className:"cr-dim","data-testid":"repo-event-time",children:[" · ",TH(e.at,t)]}),n&&r.jsxs(r.Fragment,{children:[" ",r.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer","data-testid":"repo-event-link",title:"Open on GitHub",children:"↗"})]})]})}function PH({snapshot:e,loading:t,connected:n,sessions:i,onRefresh:o,now:d=Date.now}={}){const h=V(H=>H.repoEventsSnapshot),l=V(H=>H.repoEventsLoading),u=V(H=>H.connectionPhase==="connected"),f=V(H=>H.sessions),v=V(H=>H.requestRepoEvents),g=e!==void 0?e:h,S=t!==void 0?t:l,w=n!==void 0?n:u,E=i!==void 0?i:f,x=o??v,[m,y]=N.useState(!1),b=S||!w,_=()=>{b||x()},k=d(),j=g?Date.parse(g.generatedAt):NaN,T=g?.events??[],D=IH(E??[]),{groups:I,hiddenCount:L}=DH(T,D,m),q=!m&&D.size>0;return r.jsxs("div",{className:"cr-section","data-testid":"repo-events-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"repo-events-eyebrow",children:["host · repo events",g?` · ${RH(g.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Repo events"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"repo-events-refresh",onClick:_,disabled:b,"aria-busy":S,title:w?void 0:"Not connected — reconnect to run the survey",children:S?"Refreshing…":"Refresh"})]}),g&&r.jsxs("p",{className:"cr-sub","data-testid":"repo-events-sub",children:["GitHub-webhook activity (push / PR / issue) buffered from"," ",r.jsx("span",{className:"cr-mono",children:"POST /api/github/webhook"}),q?", scoped to the repos your sessions are working in.":" across all monitored repos."]}),g&&!Number.isNaN(j)&&r.jsx("p",{className:"cr-generated","data-testid":"repo-events-generated",children:ci(j,k)})]}),g?.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"repo-events-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",g.error.code,"):"]})," ",g.error.message]}),!g&&r.jsx("div",{className:"cr-empty","data-testid":"repo-events-empty",children:S?r.jsx("span",{children:"Running the repo-events survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No repo-events survey yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"repo-events-empty-refresh",onClick:_,disabled:!w,title:w?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!w&&r.jsx("p",{className:"cr-dim","data-testid":"repo-events-not-connected",children:"Not connected to the server."})]})}),g&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-chips","data-testid":"repo-events-chips",children:[r.jsxs("span",{className:"cr-chip","data-testid":"repo-events-chip-total",children:["Events: ",r.jsx("b",{"data-testid":"repo-events-chip-count-total",children:T.length})]}),r.jsxs("span",{className:"cr-chip","data-testid":"repo-events-chip-repos",children:["Repos: ",r.jsx("b",{"data-testid":"repo-events-chip-count-repos",children:new Set(T.map(H=>H.repo??"(unknown repo)")).size})]}),D.size>0&&r.jsxs("label",{className:"cr-chip","data-testid":"repo-events-show-all",children:[r.jsx("input",{type:"checkbox",checked:m,onChange:H=>y(H.target.checked),"data-testid":"repo-events-show-all-toggle"})," ","Show all repos"]})]}),T.length===0?r.jsxs("div",{className:"cr-empty","data-testid":"repo-events-none-buffered",children:[r.jsx("p",{children:"No repo events buffered yet."}),r.jsxs("p",{className:"cr-dim",children:["Point a GitHub webhook (pull_request / issues / push) at"," ",r.jsx("span",{className:"cr-mono",children:"POST /api/github/webhook"})," with the configured secret — events appear here as they arrive."]})]}):I.length===0?r.jsxs("div",{className:"cr-empty","data-testid":"repo-events-all-hidden",children:[r.jsx("p",{children:"No events for the repos your sessions are working in."}),r.jsxs("button",{type:"button",className:"cr-refresh","data-testid":"repo-events-all-hidden-showall",onClick:()=>y(!0),children:["Show all ",T.length," event",T.length===1?"":"s"]})]}):r.jsxs("section",{className:"cr-repo-event-groups","data-testid":"repo-events-groups",children:[I.map(H=>r.jsxs("div",{className:"cr-repo-event-group","data-testid":`repo-events-group-${H.repo}`,children:[r.jsx("h3",{className:"cr-repo-event-repo","data-testid":"repo-events-group-repo",children:H.repo}),r.jsx("ul",{className:"cr-repo-event-list",children:H.events.map((Q,F)=>r.jsx(OH,{event:Q,now:k},`${Q.at}-${F}`))})]},H.repo)),L>0&&r.jsxs("button",{type:"button",className:"cr-refresh","data-testid":"repo-events-showall-more",onClick:()=>y(!0),children:["Show ",L," more from other repos"]})]})]})]})}function BH(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function $H(e,t){if(!e)return"never";const n=Date.parse(e);if(Number.isNaN(n))return"never";const i=Math.floor((t-n)/1e3);if(!Number.isFinite(i)||i<60)return"just now";const o=Math.floor(i/60);if(o<60)return`${o}m ago`;const d=Math.floor(o/60);if(d<24)return`${d}h ago`;const h=Math.floor(d/24);return h<30?`${h}d ago`:`${Math.floor(h/30)}mo ago`}function zH(e){const t=e.replace(/\/+$/,"").split("/");return t[t.length-1]||e}function UH(e){return e.slice().sort((t,n)=>{const i=t.lastUsed?Date.parse(t.lastUsed):NaN,o=n.lastUsed?Date.parse(n.lastUsed):NaN,d=!Number.isNaN(i),h=!Number.isNaN(o);return d&&h?o-i:d?-1:h?1:t.name<n.name?-1:t.name>n.name?1:0})}function qH(e){return e.trustState==="pending"?{label:"Trust pending",accent:"warn"}:null}function HH({skill:e,nowMs:t,testIdPrefix:n}){const[i,o]=N.useState(!1),d=qH(e),h=typeof e.description=="string"&&e.description.trim().length>0,l=`${n}-${e.name}`;return r.jsxs("li",{className:"cr-skill","data-testid":`skill-row-${l}`,children:[r.jsxs("button",{type:"button",className:"cr-skill-head","data-testid":`skill-head-${l}`,onClick:()=>h&&o(u=>!u),"aria-expanded":h?i:void 0,disabled:!h,children:[r.jsx("span",{className:"cr-skill-name","data-testid":`skill-name-${l}`,children:e.name}),e.activation==="manual"&&r.jsx("span",{className:"cr-tag","data-testid":`skill-manual-${l}`,title:"Manual activation — opt in per session",children:"manual"}),e.active===!1&&r.jsx("span",{className:"cr-tag","data-testid":`skill-inactive-${l}`,title:"Not in the default-active set",children:"inactive"}),e.overridesGlobal&&r.jsx("span",{className:"cr-tag cr-tag-warn","data-testid":`skill-override-${l}`,title:"Shadows a global skill of the same name",children:"overrides global"}),d&&r.jsx("span",{className:`cr-tag cr-tag-${d.accent}`,"data-testid":`skill-trust-${l}`,title:e.communityAuthor?`community/${e.communityAuthor}`:void 0,children:d.label}),r.jsx("span",{className:"cr-skill-meta cr-dim","data-testid":`skill-usage-${l}`,children:e.useCount>0?`used ${$H(e.lastUsed,t)} · ${e.useCount}×`:"never used"})]}),r.jsxs("div",{className:"cr-skill-sub cr-dim cr-mono","data-testid":`skill-sub-${l}`,children:[e.providers.length>0?e.providers.join(", "):"all providers",e.version?` · v${e.version}`:"",e.hash?` · ${e.hash}`:"",e.installed?` · installed ${e.installed}`:"",e.usedRepos.length>0?` · in ${e.usedRepos.map(zH).join(", ")}`:""]}),h&&i&&r.jsx("p",{className:"cr-skill-desc","data-testid":`skill-desc-${l}`,children:e.description})]})}function _0({title:e,subtitle:t,skills:n,nowMs:i,testId:o,testIdPrefix:d,error:h,emptyNote:l}){const u=UH(n);return r.jsxs("section",{className:"cr-skill-card","data-testid":o,children:[r.jsxs("header",{className:"cr-skill-card-head",children:[r.jsx("h2",{className:"cr-skill-card-title","data-testid":`${o}-title`,children:e}),h?r.jsx("span",{className:"cr-tag cr-tag-bad","data-testid":`${o}-error`,title:h,children:"scan failed"}):r.jsxs("span",{className:"cr-chip","data-testid":`${o}-count`,children:[n.length," skill",n.length===1?"":"s"]})]}),t&&r.jsx("p",{className:"cr-sub cr-dim","data-testid":`${o}-sub`,children:t}),h?r.jsxs("p",{className:"cr-callout","data-testid":`${o}-error-detail`,children:[r.jsx("b",{children:"Overlay scan failed:"})," ",h]}):u.length===0?r.jsx("p",{className:"cr-dim","data-testid":`${o}-empty`,children:l}):r.jsx("ul",{className:"cr-skill-list","data-testid":`${o}-list`,children:u.map(f=>r.jsx(HH,{skill:f,nowMs:i,testIdPrefix:d},f.name))})]})}function FH({snapshot:e,loading:t,connected:n,onRefresh:i,now:o=Date.now}={}){const d=V(k=>k.skillsInventory),h=V(k=>k.skillsInventoryLoading),l=V(k=>k.connectionPhase==="connected"),u=V(k=>k.requestSkillsInventory),f=e!==void 0?e:d,v=t!==void 0?t:h,g=n!==void 0?n:l,S=i??u,w=v||!g,E=()=>{w||S()},x=f?Date.parse(f.generatedAt):NaN,m=o(),y=f?.repos??[],b=y.filter(k=>k.skills.length>0).length,_=f?new Set([...f.global,...y.flatMap(k=>k.skills)].filter(k=>k.useCount>0).map(k=>k.name)).size:0;return r.jsxs("div",{className:"cr-section","data-testid":"skills-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"skills-eyebrow",children:["host · skills",f?` · ${BH(f.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Skills"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"skills-refresh",onClick:E,disabled:w,"aria-busy":v,title:g?void 0:"Not connected — reconnect to run the survey",children:v?"Refreshing…":"Refresh"})]}),f&&r.jsxs("p",{className:"cr-sub","data-testid":"skills-sub",children:["Installed chroxy skills across the global ",r.jsx("span",{className:"cr-mono",children:"~/.chroxy/skills/"})," tier and the per-repo ",r.jsx("span",{className:"cr-mono",children:".chroxy/skills/"})," overlays under"," ",r.jsx("span",{className:"cr-mono",children:f.root})," — descriptions, trust state, hashes, install dates, and usage history. Sorted by most recently used."]}),f&&!Number.isNaN(x)&&r.jsx("p",{className:"cr-generated","data-testid":"skills-generated",children:ci(x,m)})]}),!f&&r.jsx("div",{className:"cr-empty","data-testid":"skills-empty",children:v?r.jsx("span",{children:"Running the skills inventory survey…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No skills inventory yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"skills-empty-refresh",onClick:E,disabled:!g,title:g?void 0:"Not connected — reconnect to run the survey",children:"Run survey"}),!g&&r.jsx("p",{className:"cr-dim","data-testid":"skills-not-connected",children:"Not connected to the server."})]})}),f&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-chips","data-testid":"skills-chips",children:[r.jsxs("span",{className:"cr-chip","data-testid":"skills-chip-global",children:["Global: ",r.jsx("b",{"data-testid":"skills-chip-count-global",children:f.global.length})]}),r.jsxs("span",{className:"cr-chip","data-testid":"skills-chip-overlays",children:["Repos with overlay: ",r.jsx("b",{"data-testid":"skills-chip-count-overlays",children:b})]}),r.jsxs("span",{className:"cr-chip","data-testid":"skills-chip-used",children:["Used: ",r.jsx("b",{"data-testid":"skills-chip-count-used",children:_})]})]}),f.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"skills-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",f.error.code,"):"]})," ",f.error.message]}),r.jsx(_0,{title:"Global",subtitle:r.jsx("span",{className:"cr-mono",children:"~/.chroxy/skills/"}),skills:f.global,nowMs:m,testId:"skills-card-global",testIdPrefix:"global",error:f.globalError??null,emptyNote:"No global skills installed."}),y.map(k=>r.jsx(_0,{title:k.name,subtitle:r.jsxs("span",{className:"cr-mono",children:[k.path,"/.chroxy/skills/"]}),skills:k.skills,nowMs:m,testId:`skills-card-repo-${k.name}`,testIdPrefix:`repo-${k.name}`,error:k.error,emptyNote:"No repo-local skills overlay."},k.path))]})]})}const KH={injected:"ok",busy:"warn","not-tui":"warn","no-session":"bad","pty-dead":"bad"},WH={injected:"Woke session",busy:"Busy · notified","not-tui":"Notified","no-session":"No session","pty-dead":"PTY closed"};function GH(e){const t=/^(\d{4}-\d{2}-\d{2})/.exec(e);return t?t[1]:e}function VH(e){return Number.isFinite(e)?new Date(e).toISOString().slice(11,19):"—"}function YH({outcome:e}){const t=KH[e];return r.jsx("span",{className:`cr-tag cr-tag-${t}`,"data-testid":`mailbox-outcome-${e}`,"data-accent":t,title:e,children:WH[e]})}function ZH({reg:e}){return r.jsxs("tr",{"data-testid":`mailbox-reg-${e.agentCommId}`,children:[r.jsx("td",{children:r.jsx("b",{className:"cr-mono","data-testid":`mailbox-reg-id-${e.agentCommId}`,children:e.agentCommId})}),r.jsxs("td",{children:[r.jsx("span",{"data-testid":`mailbox-reg-session-${e.agentCommId}`,children:e.sessionName??"(unnamed)"}),r.jsx("div",{className:"cr-dim cr-mono cr-branch",title:e.sessionId,children:e.sessionId})]}),r.jsx("td",{children:e.isBusy?r.jsx("span",{className:"cr-warn","data-testid":`mailbox-reg-state-${e.agentCommId}`,children:"Busy"}):r.jsx("span",{className:"cr-ok","data-testid":`mailbox-reg-state-${e.agentCommId}`,children:"Idle"})}),r.jsx("td",{className:"cr-dim","data-testid":`mailbox-reg-pty-${e.agentCommId}`,children:e.isTui?"claude-tui":"notify-only"})]})}function XH({event:e,index:t}){return r.jsxs("tr",{"data-testid":`mailbox-event-${t}`,children:[r.jsx("td",{className:"cr-dim cr-mono","data-testid":`mailbox-event-time-${t}`,title:new Date(e.at).toISOString(),children:VH(e.at)}),r.jsx("td",{className:"cr-mono",children:e.to}),r.jsx("td",{className:"cr-dim",children:e.from}),r.jsx("td",{className:"cr-dim cr-mono","data-testid":`mailbox-event-unread-${t}`,children:e.unreadCount===null?"—":e.unreadCount}),r.jsx("td",{children:r.jsx(YH,{outcome:e.outcome})})]})}function QH({snapshot:e,loading:t,connected:n,onRefresh:i,now:o=Date.now}={}){const d=V(m=>m.mailboxStatus),h=V(m=>m.mailboxStatusLoading),l=V(m=>m.connectionPhase==="connected"),u=V(m=>m.requestMailboxStatus),f=e!==void 0?e:d,v=t!==void 0?t:h,g=n!==void 0?n:l,S=i??u,w=v||!g,E=()=>{w||S()},x=f?Date.parse(f.generatedAt):NaN;return r.jsxs("div",{className:"cr-section","data-testid":"mailbox-section",children:[r.jsxs("header",{className:"cr-header",children:[r.jsxs("div",{className:"cr-eyebrow","data-testid":"mailbox-eyebrow",children:["host · mailbox",f?` · ${GH(f.generatedAt)}`:""]}),r.jsxs("div",{className:"cr-titlerow",children:[r.jsx("h1",{className:"cr-title",children:"Mailbox"}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"mailbox-refresh",onClick:E,disabled:w,"aria-busy":v,title:g?void 0:"Not connected — reconnect to run the survey",children:v?"Refreshing…":"Refresh"})]}),f&&r.jsxs("p",{className:"cr-sub","data-testid":"mailbox-sub",children:[f.registrations.length," registration",f.registrations.length===1?"":"s"," ·"," ",f.recentEvents.length," recent deliver",f.recentEvents.length===1?"y":"ies"," — agents addressable by the live-interrupt route, and what it did with the last pings."]}),f&&f.error&&r.jsxs("p",{className:"cr-callout cr-callout-bad","data-testid":"mailbox-error",role:"alert",children:[r.jsxs("b",{children:["Survey failed (",f.error.code,"):"]})," ",f.error.message]}),f&&!Number.isNaN(x)&&r.jsx("p",{className:"cr-generated","data-testid":"mailbox-generated",children:ci(x,o())})]}),!f&&r.jsx("div",{className:"cr-empty","data-testid":"mailbox-empty",children:v?r.jsx("span",{children:"Loading the mailbox snapshot…"}):r.jsxs(r.Fragment,{children:[r.jsx("p",{children:"No mailbox snapshot yet."}),r.jsx("button",{type:"button",className:"cr-refresh","data-testid":"mailbox-empty-refresh",onClick:E,disabled:!g,title:g?void 0:"Not connected — reconnect to run the survey",children:"Load snapshot"}),!g&&r.jsx("p",{className:"cr-dim","data-testid":"mailbox-not-connected",children:"Not connected to the server."})]})}),f&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cr-chips","data-testid":"mailbox-chips",children:[r.jsxs("span",{className:"cr-chip","data-testid":"mailbox-chip-registrations",children:["Registered: ",r.jsx("b",{"data-testid":"mailbox-chip-count-registrations",children:f.registrations.length})]}),r.jsxs("span",{className:"cr-chip","data-testid":"mailbox-chip-deliveries",children:["Recent deliveries: ",r.jsx("b",{"data-testid":"mailbox-chip-count-deliveries",children:f.recentEvents.length})]})]}),r.jsxs("div",{className:"cr-callout","data-testid":"mailbox-callout",children:[r.jsx("b",{children:"How delivery works:"})," when mail arrives, chroxy notifies and — if the recipient is a"," ",r.jsx("b",{children:"live, idle claude-tui"}),' session — injects a "run receive_next" wakeup (',r.jsx("b",{children:"Woke session"}),")."," ","A ",r.jsx("b",{children:"busy"})," recipient is notified and drains on its next idle via the portable hook. A"," ",r.jsx("b",{children:"non-tui"})," session is notify-only. ",r.jsx("b",{children:"No session"})," / ",r.jsx("b",{children:"PTY closed"})," mean the id resolved to nothing live."]}),r.jsxs("section",{className:"cr-table-wrap",children:[r.jsx("h2",{className:"cr-subtitle","data-testid":"mailbox-registrations-title",children:"Registrations"}),r.jsxs("table",{className:"cr-table","data-testid":"mailbox-registrations-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Mailbox id"}),r.jsx("th",{children:"Session"}),r.jsx("th",{children:"State"}),r.jsx("th",{children:"Delivery"})]})}),r.jsx("tbody",{children:f.registrations.length===0?r.jsx("tr",{"data-testid":"mailbox-no-registrations",children:r.jsx("td",{colSpan:4,className:"cr-dim",children:"No sessions are registered as mailbox recipients."})}):f.registrations.map(m=>r.jsx(ZH,{reg:m},m.agentCommId))})]})]}),r.jsxs("section",{className:"cr-table-wrap",children:[r.jsx("h2",{className:"cr-subtitle","data-testid":"mailbox-deliveries-title",children:"Recent deliveries"}),r.jsxs("table",{className:"cr-table","data-testid":"mailbox-deliveries-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:"Time (UTC)"}),r.jsx("th",{children:"To"}),r.jsx("th",{children:"From"}),r.jsx("th",{children:"Unread"}),r.jsx("th",{children:"Outcome"})]})}),r.jsx("tbody",{children:f.recentEvents.length===0?r.jsx("tr",{"data-testid":"mailbox-no-deliveries",children:r.jsx("td",{colSpan:5,className:"cr-dim",children:"No mailbox deliveries recorded yet."})}):f.recentEvents.map((m,y)=>r.jsx(XH,{event:m,index:y},`${m.at}-${y}`))})]})]})]})]})}const Dd={running:"Running",blocked:"Blocked",failed:"Failed",idle:"Idle"};function S0({rollup:e,testidPrefix:t}){return r.jsxs("span",{className:"mc-rollup","data-testid":t,children:[r.jsxs("span",{className:"mc-chip mc-chip-running","data-testid":`${t}-running`,children:[e.running," running"]}),r.jsxs("span",{className:"mc-chip mc-chip-blocked","data-testid":`${t}-blocked`,children:[e.blocked," blocked"]}),r.jsxs("span",{className:"mc-chip mc-chip-failed","data-testid":`${t}-failed`,children:[e.failed," failed"]})]})}function JH({activity:e,sessions:t,external:n=[],onCancelActivity:i,cancellingActivityIds:o,onJumpToSession:d,now:h=Date.now}){const l=G0(e,t),u=N.useCallback(S=>{if(!o||o.size===0)return;const w=`${S}:`,E=new Set;for(const x of o)x.startsWith(w)&&E.add(x.slice(w.length));return E},[o]),[f,v]=N.useState(()=>new Set),g=N.useCallback(S=>{v(w=>{const E=new Set(w);return E.has(S)?E.delete(S):E.add(S),E})},[]);return l.groups.length===0&&n.length===0?r.jsx("div",{className:"mission-control","data-testid":"mission-control",children:r.jsx("div",{className:"mission-control-empty","data-testid":"mission-control-empty",children:"No active sessions"})}):r.jsxs("div",{className:"mission-control","data-testid":"mission-control",children:[r.jsxs("header",{className:"mission-control-header",children:[r.jsx("span",{className:"mc-total-label",children:"All sessions"}),r.jsx(S0,{rollup:l.total,testidPrefix:"mission-control-total"})]}),l.groups.map(S=>r.jsxs("section",{className:"mission-control-group","data-testid":"mission-control-group","data-group-key":S.key,children:[r.jsxs("h3",{className:"mission-control-group-head",children:[r.jsx("span",{className:"mission-control-group-label","data-testid":"mission-control-group-label",children:S.label}),S.worktree&&r.jsx("span",{className:"mc-worktree-badge","data-testid":"mission-control-group-worktree",children:"worktree"}),r.jsx(S0,{rollup:S.rollup,testidPrefix:"mission-control-group-rollup"})]}),r.jsx("ul",{className:"mission-control-session-list control-room-entry-list",children:S.sessions.map(w=>{const E=f.has(w.sessionId),x=`mission-control-session-tree-${w.sessionId}`;return r.jsxs("li",{className:"mission-control-session","data-testid":`mission-control-session-${w.sessionId}`,children:[r.jsxs("button",{type:"button",className:`control-room-entry mission-control-session-row status-${w.status}`,"data-status":w.status,"data-testid":`mission-control-session-toggle-${w.sessionId}`,"aria-expanded":E,"aria-controls":E?x:void 0,onClick:()=>g(w.sessionId),children:[r.jsx("span",{className:"control-room-entry-label mission-control-session-name",children:w.name}),r.jsx("span",{className:`control-room-status-badge status-${w.status}`,"data-testid":`mission-control-session-status-${w.sessionId}`,role:"status","aria-label":`Status: ${Dd[w.status]}`,children:Dd[w.status]})]}),E&&r.jsx("div",{className:"mission-control-session-tree",id:x,"data-testid":x,children:r.jsx(ak,{activity:e,sessionId:w.sessionId,now:h,onCancelActivity:i?m=>i(m,w.sessionId):void 0,cancellingActivityIds:u(w.sessionId),onJumpToSession:d})})]},w.sessionId)})})]},S.key)),n.length>0&&r.jsxs("section",{className:"mission-control-group mission-control-external","data-testid":"mission-control-external",children:[r.jsxs("h3",{className:"mission-control-group-head",children:[r.jsx("span",{className:"mission-control-group-label",children:"External sessions"}),r.jsx("span",{className:"mc-readonly-badge","data-testid":"mission-control-external-readonly",title:"Sessions chroxy didn't launch (seen via /api/events) — observe-only",children:"read-only"})]}),r.jsx("ul",{className:"mission-control-session-list control-room-entry-list",children:n.map(S=>r.jsx("li",{className:"mission-control-session mission-control-external-session","data-testid":`mission-control-external-${S.sessionId}`,children:r.jsxs("div",{className:`control-room-entry mission-control-session-row status-${S.status} is-readonly`,"data-status":S.status,children:[r.jsx("span",{className:"control-room-entry-label mission-control-session-name",children:S.name}),S.subagents>0&&r.jsxs("span",{className:"mc-subagents","data-testid":`mission-control-external-subagents-${S.sessionId}`,children:[S.subagents," subagent",S.subagents===1?"":"s"]}),r.jsx("span",{className:`control-room-status-badge status-${S.status}`,"data-testid":`mission-control-external-status-${S.sessionId}`,role:"status","aria-label":`Status: ${Dd[S.status]}`,children:Dd[S.status]})]})},`${S.source}\0${S.sessionId}`))})]})]})}const eF=new Set(["meta","control","shift","alt","option","os","hyper","super","capslock","numlock","scrolllock","fn","dead"]);function tF({onCapture:e,onCancel:t}){const n=N.useRef(null);return N.useEffect(()=>{n.current?.focus()},[]),N.useEffect(()=>{const i=o=>{if(o.preventDefault(),o.stopPropagation(),o.key==="Escape"){t();return}const d=(o.key||"").toLowerCase();if(eF.has(d))return;const h=[];(o.metaKey||o.ctrlKey)&&h.push("cmd"),o.shiftKey&&h.push("shift"),o.altKey&&h.push("alt"),h.push(d);const l=il(h.join("+"));e(l)};return window.addEventListener("keydown",i,{capture:!0}),()=>window.removeEventListener("keydown",i,{capture:!0})},[e,t]),r.jsx("button",{ref:n,type:"button",className:"keybind-capture","aria-label":"Press a key combination, or Escape to cancel","data-testid":"keybind-capture",onBlur:t,onClick:i=>i.preventDefault(),children:"Press a key combination…"})}const nF={navigation:"Navigation",composer:"Composer",session:"Session",view:"View",sidebar:"Sidebar",other:"Other"},sF=["navigation","view","session","sidebar","composer","other"];function iF(){const e=mg(),[t,n]=N.useState(null),[i,o]=N.useState(null),d=ma(),h=(()=>{const f=new Map;for(const v of e.list()){const g=f.get(v.category)||[];g.push(v),f.set(v.category,g)}return sF.filter(v=>f.has(v)).map(v=>({category:v,entries:f.get(v)}))})(),l=f=>v=>{try{e.setBinding(f,v),o(null),n(null)}catch(g){o(g instanceof Error?g.message:String(g))}},u=()=>{n(null),o(null)};return r.jsxs("section",{className:"settings-section","data-testid":"shortcuts-section",children:[r.jsxs("div",{className:"settings-section-header",children:[r.jsx("h3",{children:"Keyboard Shortcuts"}),r.jsx("button",{type:"button",className:"settings-link-button",onClick:()=>e.resetAll(),"data-testid":"shortcuts-reset-all",children:"Reset all"})]}),r.jsx("p",{className:"settings-hint",children:"Click Edit next to a shortcut and press a new key combination. Press Escape to cancel."}),i&&r.jsx("div",{className:"settings-error",role:"alert","data-testid":"shortcuts-error",children:i}),h.map(({category:f,entries:v})=>r.jsxs("div",{className:"shortcuts-group",children:[r.jsx("h4",{className:"shortcuts-group-title",children:nF[f]}),r.jsx("ul",{className:"shortcuts-list",children:v.map(g=>{const S=t===g.id,w=Jo(g.binding,d),E=Jo(g.defaultBinding,d),x=g.scope==="sessionbar",m="Not rebindable yet — this shortcut is fixed in this release.";return r.jsxs("li",{className:"shortcuts-section-row","data-testid":`shortcut-row-${g.id}`,children:[r.jsxs("div",{className:"shortcuts-section-row-description",children:[r.jsx("span",{children:g.description}),g.isCustomized&&r.jsxs("span",{className:"shortcuts-section-row-default",title:`Default: ${E}`,children:["(default ",E,")"]}),x&&r.jsx("span",{className:"shortcuts-section-row-readonly","data-testid":`shortcut-readonly-${g.id}`,title:m,children:"(not rebindable)"})]}),r.jsxs("div",{className:"shortcuts-section-row-controls",children:[S?r.jsx(tF,{onCapture:l(g.id),onCancel:u}):r.jsx("kbd",{className:"shortcuts-section-row-binding","data-testid":`shortcut-binding-${g.id}`,children:w}),!S&&r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",className:"settings-secondary-button",onClick:()=>{n(g.id),o(null)},disabled:x,title:x?m:void 0,"data-testid":`shortcut-edit-${g.id}`,"aria-label":`Edit shortcut for ${g.description}`,children:"Edit"}),r.jsx("button",{type:"button",className:"settings-secondary-button",onClick:()=>e.resetBinding(g.id),disabled:!g.isCustomized,title:x?m:void 0,"data-testid":`shortcut-reset-${g.id}`,"aria-label":`Reset shortcut for ${g.description}`,children:"Reset"})]})]})]},g.id)})})]},f))]})}const cm="Not connected to the server — your change was not saved. Reconnect and try again.";function rF(e){return e.status==="set"?e.source==="env"?"Set (environment)":e.source==="store"?"Set (stored)":"Set":e.source==="oauth"?"OAuth (subscription)":"Missing"}function aF({entry:e}){const t=V(y=>y.setCredential),n=V(y=>y.deleteCredential),i=V(y=>y.testCredential),o=V(y=>y.credentialTestResults[e.key]),[d,h]=N.useState(!1),[l,u]=N.useState(""),[f,v]=N.useState(null),[g,S]=N.useState(null),w=e.source==="env",E=N.useCallback(()=>{v(null);const y=l.trim();if(y.length===0){v("Enter a value.");return}t(e.key,y)?(S(null),u(""),h(!1)):S(cm)},[l,t,e.key]),x=N.useCallback(()=>{v(null);const y=n(e.key);S(y?null:cm)},[n,e.key]),m=N.useCallback(()=>{v(null);const y=i(e.key);S(y?null:cm)},[i,e.key]);return r.jsxs("div",{className:"settings-field","data-testid":`credential-row-${e.key}`,children:[r.jsxs("div",{children:[r.jsx("strong",{children:e.provider})," — ",r.jsx("code",{children:e.key})]}),r.jsxs("div",{"data-testid":`credential-status-${e.key}`,children:["Status: ",rF(e),e.status==="set"&&e.source!=="oauth"&&e.masked?` — ${e.masked}`:""]}),w&&r.jsx("p",{className:"settings-hint","data-testid":`credential-env-hint-${e.key}`,children:"Defined in your shell environment, which takes precedence over a stored value — so it can't be changed or removed here. To manage this key from the dashboard, unset the environment variable and reconnect."}),d&&!w&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:`credential-input-${e.key}`,children:e.label}),r.jsx("input",{id:`credential-input-${e.key}`,type:"password",autoComplete:"off",spellCheck:!1,value:l,onChange:y=>u(y.target.value),"data-testid":`credential-input-${e.key}`})]}),f&&r.jsx("p",{className:"settings-hint","data-testid":`credential-error-${e.key}`,style:{color:"var(--error, #f00)"},children:f}),r.jsxs("div",{className:"settings-field",children:[r.jsx("button",{type:"button",onClick:E,disabled:l.trim().length===0,"data-testid":`credential-save-${e.key}`,children:"Save"}),r.jsx("button",{type:"button",onClick:()=>{h(!1),u(""),v(null)},"data-testid":`credential-cancel-${e.key}`,children:"Cancel"})]})]}),!d&&r.jsxs("div",{className:"settings-field",children:[!w&&r.jsx("button",{type:"button",onClick:()=>h(!0),"data-testid":`credential-edit-${e.key}`,children:e.status==="set"&&e.source==="store"?"Edit":"Set key"}),r.jsx("button",{type:"button",onClick:m,"data-testid":`credential-test-${e.key}`,children:"Test"}),e.source==="store"&&r.jsx("button",{type:"button",onClick:x,"data-testid":`credential-remove-${e.key}`,children:"Remove"})]}),o&&r.jsx("p",{className:"settings-hint",role:"status","data-testid":`credential-test-result-${e.key}`,style:{color:o.ok?"var(--success-fg, #4ade80)":"var(--error, #f00)"},children:o.ok?`OK${o.model?` (${o.model})`:""}${typeof o.latencyMs=="number"?` — ${o.latencyMs}ms`:""}`:`Failed: ${o.error??"unknown error"}`}),g&&r.jsx("p",{className:"settings-hint",role:"alert","data-testid":`credential-ws-closed-${e.key}`,style:{color:"var(--error, #f00)"},children:g})]})}function oF({isOpen:e}){const t=V(o=>o.credentialsStatus),n=V(o=>o.refreshCredentialsStatus);N.useEffect(()=>{e&&n()},[e,n]);const i=t?.credentials??[];return r.jsxs("section",{className:"settings-section","data-testid":"provider-credentials-section",children:[r.jsx("h3",{children:"Provider Credentials"}),r.jsxs("p",{className:"settings-hint",children:["Manage provider API keys and OAuth tokens here instead of exporting shell env vars. Keys are saved to ",r.jsx("code",{children:"~/.chroxy/credentials.json"})," (mode 0600, owner-only) and are never shown again after saving — only a masked preview. A matching environment variable always takes precedence over a stored value."]}),t?.fileError&&r.jsx("p",{className:"settings-hint","data-testid":"provider-credentials-file-error",style:{color:"var(--warning-fg, #fbbf24)"},children:t.fileError}),i.length===0?r.jsx("p",{className:"settings-hint","data-testid":"provider-credentials-loading",children:"Loading credential status…"}):i.map(o=>r.jsx(aF,{entry:o},o.key)),r.jsxs("p",{className:"settings-hint",children:["OAuth status is read-only. To sign in with a Claude subscription, run"," ",r.jsx("code",{children:"claude login"})," in a terminal — see the providers docs."]})]})}const hk={id:"default",name:"Default",description:"Purple and blue dark theme",colors:{},terminal:{background:"#000000",foreground:"#e0e0e0",cursor:"#4a9eff",selectionBackground:"#4a9eff44"}},lF={id:"hacker",name:"Hacker",description:"Black and lime green",colors:{"bg-primary":"#000000","bg-secondary":"#0a0a0a","bg-tertiary":"#050505","bg-card":"#111111","bg-input":"#000000","bg-terminal":"#000000","bg-header":"#080808","bg-session-bar":"#060606","bg-code-block":"#020202","bg-tool-bubble":"#0a0a0a","bg-permission":"#0a1a0a","bg-question":"#0a1a0a","bg-plan-banner":"#0a1a0a","bg-modal":"#0a0a0a","text-primary":"#00ff41","text-secondary":"#00cc33","text-muted":"#009926","text-dim":"#006619","text-disabled":"#004d13","text-error":"#ff4444","text-system":"#00aa2e","text-link":"#00ff41","text-emphasis":"#33ff66","text-heading":"#00ff41","text-blockquote":"#008822","accent-blue":"#00ff41","accent-green":"#00ff41","accent-purple":"#00cc33","accent-orange":"#ccff00","accent-red":"#ff4444","accent-blue-light":"#00ff4122","accent-blue-subtle":"#00ff4133","accent-blue-border":"#00ff4144","accent-blue-border-strong":"#00ff4166","accent-green-light":"#00ff4122","accent-green-border":"#00ff4133","accent-green-border-strong":"#00ff4166","accent-purple-light":"#00cc3322","accent-purple-subtle":"#00cc3333","accent-purple-border-strong":"#00cc3366","accent-purple-code":"#33ff66","accent-orange-light":"#ccff0011","accent-orange-subtle":"#ccff0022","accent-orange-medium":"#ccff0033","accent-orange-border":"#ccff0044","accent-orange-border-strong":"#ccff0066","accent-red-light":"#ff444411","accent-red-subtle":"#ff444422","accent-red-border":"#ff444444","border-primary":"#1a3a1a","border-secondary":"#2a4a2a","border-subtle":"#336633","border-focus":"#00ff41","border-permission":"#1a3a1a","border-question":"#1a3a1a","status-connected":"#00ff41","status-disconnected":"#ff4444","status-connecting":"#ccff00","status-restarting":"#ccff00","warning-fg":"#ccff00","warning-bg-subtle":"#ccff0022","banner-border-subtle":"#1a3a1a","syntax-keyword":"#00ff41","syntax-string":"#33ff66","syntax-comment":"#336633","syntax-number":"#ccff00","syntax-function":"#00ff41","syntax-operator":"#00cc33","syntax-punctuation":"#336633","syntax-plain":"#00ff41","syntax-type":"#33ff66","syntax-property":"#00cc33","diff-add-bg":"#0a1a0a","diff-remove-bg":"#1a0a0a","diff-add-text":"#00ff41","diff-remove-text":"#ff4444","scrollbar-track":"transparent","scrollbar-thumb":"#1a3a1a","scrollbar-thumb-hover":"#2a4a2a"},terminal:{background:"#000000",foreground:"#00ff41",cursor:"#00ff41",selectionBackground:"#00ff4144"}},cF={id:"midnight",name:"Midnight",description:"Deep blue with softer contrast",colors:{"bg-primary":"#0a0e1a","bg-secondary":"#111827","bg-tertiary":"#0d1220","bg-card":"#1e293b","bg-input":"#0a0e1a","bg-terminal":"#060a14","bg-header":"#0c1120","bg-session-bar":"#0a0e18","bg-code-block":"#060a14","bg-tool-bubble":"#0d1220","bg-permission":"#141830","bg-question":"#0f1a2e","bg-plan-banner":"#181430","bg-modal":"#111827","text-primary":"#e2e8f0","text-secondary":"#b0bcd0","text-muted":"#7888a0","text-dim":"#5a6880","text-disabled":"#475060","text-error":"#f0a0a0","text-system":"#90a0b8","text-link":"#60a5fa","text-emphasis":"#c8d4e4","text-heading":"#e8ecf4","text-blockquote":"#8898b0","accent-blue":"#60a5fa","accent-green":"#34d399","accent-purple":"#a78bfa","accent-orange":"#fbbf24","accent-red":"#f87171","accent-blue-light":"#60a5fa22","accent-blue-subtle":"#60a5fa33","accent-blue-border":"#60a5fa44","accent-blue-border-strong":"#60a5fa66","accent-green-light":"#34d39922","accent-green-border":"#34d39933","accent-green-border-strong":"#34d39966","accent-purple-light":"#a78bfa22","accent-purple-subtle":"#a78bfa33","accent-purple-border-strong":"#a78bfa66","accent-purple-code":"#c4b5fd","accent-orange-light":"#fbbf2411","accent-orange-subtle":"#fbbf2422","accent-orange-medium":"#fbbf2433","accent-orange-border":"#fbbf2444","accent-orange-border-strong":"#fbbf2466","accent-red-light":"#f8717111","accent-red-subtle":"#f8717122","accent-red-border":"#f8717144","border-primary":"#1e293b","border-secondary":"#334155","border-subtle":"#475569","border-focus":"#60a5fa","border-permission":"#2e2860","border-question":"#1e3a5e","status-connected":"#34d399","status-disconnected":"#f87171","status-connecting":"#fbbf24","status-restarting":"#fbbf24","warning-fg":"#fbbf24","warning-bg-subtle":"#fbbf2422","banner-border-subtle":"#1e293b","syntax-keyword":"#c4b5fd","syntax-string":"#34d399","syntax-comment":"#64748b","syntax-number":"#fbbf24","syntax-function":"#60a5fa","syntax-operator":"#d0d8e4","syntax-punctuation":"#7888a0","syntax-plain":"#93c5fd","syntax-type":"#60a5fa","syntax-property":"#34d399","diff-add-bg":"#0f2418","diff-remove-bg":"#240f0f","diff-add-text":"#34d399","diff-remove-text":"#f87171","scrollbar-track":"transparent","scrollbar-thumb":"#1e293b","scrollbar-thumb-hover":"#334155"},terminal:{background:"#060a14",foreground:"#e2e8f0",cursor:"#60a5fa",selectionBackground:"#60a5fa44"}},uF={id:"light",name:"Light",description:"Clean light theme for daytime",colors:{"bg-primary":"#ffffff","bg-secondary":"#f5f5f5","bg-tertiary":"#fafafa","bg-card":"#ffffff","bg-input":"#ffffff","bg-terminal":"#fafafa","bg-header":"#f8f8f8","bg-session-bar":"#f0f0f0","bg-code-block":"#f5f5f5","bg-tool-bubble":"#f0f4f8","bg-permission":"#fef9ee","bg-question":"#eef4fe","bg-plan-banner":"#f3eefe","bg-modal":"#ffffff","text-primary":"#1a1a2e","text-secondary":"#4a4a5a","text-muted":"#6b7280","text-dim":"#9ca3af","text-disabled":"#c0c4cc","text-error":"#dc2626","text-system":"#6b7280","text-link":"#2563eb","text-emphasis":"#111827","text-heading":"#0f172a","text-blockquote":"#64748b","accent-blue":"#2563eb","accent-green":"#16a34a","accent-purple":"#7c3aed","accent-orange":"#d97706","accent-red":"#dc2626","accent-blue-light":"#2563eb18","accent-blue-subtle":"#2563eb22","accent-blue-border":"#2563eb44","accent-blue-border-strong":"#2563eb66","accent-green-light":"#16a34a18","accent-green-border":"#16a34a33","accent-green-border-strong":"#16a34a66","accent-purple-light":"#7c3aed18","accent-purple-subtle":"#7c3aed22","accent-purple-border-strong":"#7c3aed55","accent-purple-code":"#6d28d9","accent-orange-light":"#d9770611","accent-orange-subtle":"#d9770618","accent-orange-medium":"#d9770622","accent-orange-border":"#d9770644","accent-orange-border-strong":"#d9770666","accent-red-light":"#dc262611","accent-red-subtle":"#dc262618","accent-red-border":"#dc262644","border-primary":"#e2e8f0","border-secondary":"#cbd5e1","border-subtle":"#94a3b8","border-focus":"#2563eb","border-permission":"#f59e0b44","border-question":"#2563eb44","status-connected":"#16a34a","status-disconnected":"#dc2626","status-connecting":"#d97706","status-restarting":"#d97706","warning-fg":"#d97706","warning-bg-subtle":"#d9770618","banner-border-subtle":"#cbd5e1","syntax-keyword":"#7c3aed","syntax-string":"#16a34a","syntax-comment":"#9ca3af","syntax-number":"#d97706","syntax-function":"#2563eb","syntax-operator":"#374151","syntax-punctuation":"#6b7280","syntax-plain":"#1e293b","syntax-type":"#0891b2","syntax-property":"#b45309","diff-add-bg":"#dcfce7","diff-remove-bg":"#fee2e2","diff-add-text":"#166534","diff-remove-text":"#991b1b","scrollbar-track":"#f1f5f9","scrollbar-thumb":"#cbd5e1","scrollbar-thumb-hover":"#94a3b8"},terminal:{background:"#fafafa",foreground:"#1a1a2e",cursor:"#2563eb",selectionBackground:"#2563eb33"}},dF={id:"solarized",name:"Solarized",description:"Ethan Schoonover's iconic palette",colors:{"bg-primary":"#002b36","bg-secondary":"#073642","bg-tertiary":"#002b36","bg-card":"#073642","bg-input":"#002b36","bg-terminal":"#001e26","bg-header":"#073642","bg-session-bar":"#002b36","bg-code-block":"#001e26","bg-tool-bubble":"#073642","bg-permission":"#073642","bg-question":"#073642","bg-plan-banner":"#073642","bg-modal":"#073642","text-primary":"#839496","text-secondary":"#93a1a1","text-muted":"#657b83","text-dim":"#586e75","text-disabled":"#475b62","text-error":"#dc322f","text-system":"#657b83","text-link":"#268bd2","text-emphasis":"#eee8d5","text-heading":"#fdf6e3","text-blockquote":"#657b83","accent-blue":"#268bd2","accent-green":"#859900","accent-purple":"#6c71c4","accent-orange":"#cb4b16","accent-red":"#dc322f","accent-blue-light":"#268bd222","accent-blue-subtle":"#268bd233","accent-blue-border":"#268bd244","accent-blue-border-strong":"#268bd266","accent-green-light":"#85990022","accent-green-border":"#85990033","accent-green-border-strong":"#85990066","accent-purple-light":"#6c71c422","accent-purple-subtle":"#6c71c433","accent-purple-border-strong":"#6c71c466","accent-purple-code":"#d33682","accent-orange-light":"#cb4b1611","accent-orange-subtle":"#cb4b1622","accent-orange-medium":"#cb4b1633","accent-orange-border":"#cb4b1644","accent-orange-border-strong":"#cb4b1666","accent-red-light":"#dc322f11","accent-red-subtle":"#dc322f22","accent-red-border":"#dc322f44","border-primary":"#073642","border-secondary":"#586e75","border-subtle":"#657b83","border-focus":"#268bd2","border-permission":"#b5890044","border-question":"#268bd244","status-connected":"#859900","status-disconnected":"#dc322f","status-connecting":"#b58900","status-restarting":"#b58900","warning-fg":"#b58900","warning-bg-subtle":"#b5890022","banner-border-subtle":"#073642","syntax-keyword":"#859900","syntax-string":"#2aa198","syntax-comment":"#586e75","syntax-number":"#d33682","syntax-function":"#268bd2","syntax-operator":"#839496","syntax-punctuation":"#657b83","syntax-plain":"#839496","syntax-type":"#b58900","syntax-property":"#cb4b16","diff-add-bg":"#073642","diff-remove-bg":"#3c1111","diff-add-text":"#859900","diff-remove-text":"#dc322f","scrollbar-track":"transparent","scrollbar-thumb":"#073642","scrollbar-thumb-hover":"#586e75"},terminal:{background:"#001e26",foreground:"#839496",cursor:"#268bd2",selectionBackground:"#073642"}},fF={id:"monokai",name:"Monokai",description:"Classic warm developer palette",colors:{"bg-primary":"#272822","bg-secondary":"#2d2e27","bg-tertiary":"#222318","bg-card":"#3e3d32","bg-input":"#272822","bg-terminal":"#1e1f1a","bg-header":"#2d2e27","bg-session-bar":"#222318","bg-code-block":"#1e1f1a","bg-tool-bubble":"#2d2e27","bg-permission":"#3e3a20","bg-question":"#2a2e3a","bg-plan-banner":"#352a3e","bg-modal":"#2d2e27","text-primary":"#f8f8f2","text-secondary":"#cfcfc2","text-muted":"#a6a699","text-dim":"#75715e","text-disabled":"#555548","text-error":"#f92672","text-system":"#a6a699","text-link":"#66d9ef","text-emphasis":"#ffffff","text-heading":"#f8f8f2","text-blockquote":"#75715e","accent-blue":"#66d9ef","accent-green":"#a6e22e","accent-purple":"#ae81ff","accent-orange":"#fd971f","accent-red":"#f92672","accent-blue-light":"#66d9ef22","accent-blue-subtle":"#66d9ef33","accent-blue-border":"#66d9ef44","accent-blue-border-strong":"#66d9ef66","accent-green-light":"#a6e22e22","accent-green-border":"#a6e22e33","accent-green-border-strong":"#a6e22e66","accent-purple-light":"#ae81ff22","accent-purple-subtle":"#ae81ff33","accent-purple-border-strong":"#ae81ff66","accent-purple-code":"#ae81ff","accent-orange-light":"#fd971f11","accent-orange-subtle":"#fd971f22","accent-orange-medium":"#fd971f33","accent-orange-border":"#fd971f44","accent-orange-border-strong":"#fd971f66","accent-red-light":"#f9267211","accent-red-subtle":"#f9267222","accent-red-border":"#f9267244","border-primary":"#3e3d32","border-secondary":"#555548","border-subtle":"#75715e","border-focus":"#66d9ef","border-permission":"#fd971f44","border-question":"#66d9ef44","status-connected":"#a6e22e","status-disconnected":"#f92672","status-connecting":"#fd971f","status-restarting":"#fd971f","warning-fg":"#fd971f","warning-bg-subtle":"#fd971f22","banner-border-subtle":"#3e3d32","syntax-keyword":"#f92672","syntax-string":"#a6e22e","syntax-comment":"#75715e","syntax-number":"#ae81ff","syntax-function":"#66d9ef","syntax-operator":"#f92672","syntax-punctuation":"#a6a699","syntax-plain":"#f8f8f2","syntax-type":"#66d9ef","syntax-property":"#fd971f","diff-add-bg":"#2a3a1a","diff-remove-bg":"#3a1a2a","diff-add-text":"#a6e22e","diff-remove-text":"#f92672","scrollbar-track":"transparent","scrollbar-thumb":"#3e3d32","scrollbar-thumb-hover":"#555548"},terminal:{background:"#1e1f1a",foreground:"#f8f8f2",cursor:"#f8f8f2",selectionBackground:"#49483e"}},hF={id:"nord",name:"Nord",description:"Arctic, north-bluish color palette",colors:{"bg-primary":"#2e3440","bg-secondary":"#3b4252","bg-tertiary":"#2e3440","bg-card":"#3b4252","bg-input":"#2e3440","bg-terminal":"#242933","bg-header":"#3b4252","bg-session-bar":"#2e3440","bg-code-block":"#242933","bg-tool-bubble":"#3b4252","bg-permission":"#3b3e4a","bg-question":"#2e3a4a","bg-plan-banner":"#3a354a","bg-modal":"#3b4252","text-primary":"#d8dee9","text-secondary":"#e5e9f0","text-muted":"#a0aab8","text-dim":"#7b8694","text-disabled":"#616e7c","text-error":"#bf616a","text-system":"#a0aab8","text-link":"#88c0d0","text-emphasis":"#eceff4","text-heading":"#eceff4","text-blockquote":"#7b8694","accent-blue":"#88c0d0","accent-green":"#a3be8c","accent-purple":"#b48ead","accent-orange":"#d08770","accent-red":"#bf616a","accent-blue-light":"#88c0d022","accent-blue-subtle":"#88c0d033","accent-blue-border":"#88c0d044","accent-blue-border-strong":"#88c0d066","accent-green-light":"#a3be8c22","accent-green-border":"#a3be8c33","accent-green-border-strong":"#a3be8c66","accent-purple-light":"#b48ead22","accent-purple-subtle":"#b48ead33","accent-purple-border-strong":"#b48ead66","accent-purple-code":"#b48ead","accent-orange-light":"#d0877011","accent-orange-subtle":"#d0877022","accent-orange-medium":"#d0877033","accent-orange-border":"#d0877044","accent-orange-border-strong":"#d0877066","accent-red-light":"#bf616a11","accent-red-subtle":"#bf616a22","accent-red-border":"#bf616a44","border-primary":"#3b4252","border-secondary":"#434c5e","border-subtle":"#4c566a","border-focus":"#88c0d0","border-permission":"#d0877044","border-question":"#88c0d044","status-connected":"#a3be8c","status-disconnected":"#bf616a","status-connecting":"#ebcb8b","status-restarting":"#ebcb8b","warning-fg":"#ebcb8b","warning-bg-subtle":"#ebcb8b22","banner-border-subtle":"#3b4252","syntax-keyword":"#81a1c1","syntax-string":"#a3be8c","syntax-comment":"#616e7c","syntax-number":"#b48ead","syntax-function":"#88c0d0","syntax-operator":"#81a1c1","syntax-punctuation":"#7b8694","syntax-plain":"#d8dee9","syntax-type":"#8fbcbb","syntax-property":"#d08770","diff-add-bg":"#2e3e30","diff-remove-bg":"#3e2e30","diff-add-text":"#a3be8c","diff-remove-text":"#bf616a","scrollbar-track":"transparent","scrollbar-thumb":"#3b4252","scrollbar-thumb-hover":"#434c5e"},terminal:{background:"#242933",foreground:"#d8dee9",cursor:"#88c0d0",selectionBackground:"#434c5e"}},pF={id:"high-contrast",name:"High Contrast",description:"Maximum readability with strong contrast",colors:{"bg-primary":"#000000","bg-secondary":"#0a0a0a","bg-tertiary":"#000000","bg-card":"#121212","bg-input":"#000000","bg-terminal":"#000000","bg-header":"#0a0a0a","bg-session-bar":"#050505","bg-code-block":"#0a0a0a","bg-tool-bubble":"#0a0a0a","bg-permission":"#1a1a00","bg-question":"#00001a","bg-plan-banner":"#1a001a","bg-modal":"#0a0a0a","text-primary":"#ffffff","text-secondary":"#f0f0f0","text-muted":"#cccccc","text-dim":"#aaaaaa","text-disabled":"#777777","text-error":"#ff3333","text-system":"#cccccc","text-link":"#5599ff","text-emphasis":"#ffffff","text-heading":"#ffffff","text-blockquote":"#bbbbbb","accent-blue":"#4499ff","accent-green":"#33ff33","accent-purple":"#cc66ff","accent-orange":"#ffaa00","accent-red":"#ff3333","accent-blue-light":"#4499ff33","accent-blue-subtle":"#4499ff44","accent-blue-border":"#4499ff66","accent-blue-border-strong":"#4499ff99","accent-green-light":"#33ff3333","accent-green-border":"#33ff3344","accent-green-border-strong":"#33ff3399","accent-purple-light":"#cc66ff33","accent-purple-subtle":"#cc66ff44","accent-purple-border-strong":"#cc66ff99","accent-purple-code":"#dd88ff","accent-orange-light":"#ffaa0022","accent-orange-subtle":"#ffaa0033","accent-orange-medium":"#ffaa0044","accent-orange-border":"#ffaa0066","accent-orange-border-strong":"#ffaa0099","accent-red-light":"#ff333322","accent-red-subtle":"#ff333333","accent-red-border":"#ff333366","border-primary":"#444444","border-secondary":"#666666","border-subtle":"#888888","border-focus":"#4499ff","border-permission":"#ffaa0066","border-question":"#4499ff66","status-connected":"#33ff33","status-disconnected":"#ff3333","status-connecting":"#ffaa00","status-restarting":"#ffaa00","warning-fg":"#ffaa00","warning-bg-subtle":"#ffaa0033","banner-border-subtle":"#444444","syntax-keyword":"#ff6699","syntax-string":"#33ff33","syntax-comment":"#888888","syntax-number":"#ffaa00","syntax-function":"#4499ff","syntax-operator":"#ffffff","syntax-punctuation":"#cccccc","syntax-plain":"#ffffff","syntax-type":"#00ddff","syntax-property":"#ffcc00","diff-add-bg":"#003300","diff-remove-bg":"#330000","diff-add-text":"#33ff33","diff-remove-text":"#ff3333","scrollbar-track":"#111111","scrollbar-thumb":"#555555","scrollbar-thumb-hover":"#777777"},terminal:{background:"#000000",foreground:"#ffffff",cursor:"#ffffff",selectionBackground:"#4499ff55"}},pk=[hk,lF,cF,uF,dF,fF,hF,pF];function Rg(e){return pk.find(t=>t.id===e)??hk}const mk="chroxy_persist_theme",x0=["bg-primary","bg-secondary","bg-tertiary","bg-card","bg-input","bg-terminal","bg-header","bg-session-bar","bg-code-block","bg-tool-bubble","bg-permission","bg-question","bg-plan-banner","bg-modal","text-primary","text-secondary","text-muted","text-dim","text-disabled","text-error","text-system","text-link","text-emphasis","text-heading","text-blockquote","accent-blue","accent-green","accent-purple","accent-orange","accent-red","accent-cyan","accent-blue-light","accent-blue-subtle","accent-blue-border","accent-blue-border-strong","accent-green-light","accent-green-border","accent-green-border-strong","accent-purple-light","accent-purple-subtle","accent-purple-border-strong","accent-purple-code","accent-orange-light","accent-orange-subtle","accent-orange-medium","accent-orange-border","accent-orange-border-strong","accent-red-light","accent-red-subtle","accent-red-border","accent-orange-500","accent-yellow-500","accent-red-500","border-primary","border-secondary","border-subtle","border-focus","border-permission","border-question","banner-border-subtle","warning-fg","warning-bg-subtle","status-connected","status-disconnected","status-connecting","status-restarting","syntax-keyword","syntax-string","syntax-comment","syntax-number","syntax-function","syntax-operator","syntax-punctuation","syntax-plain","syntax-type","syntax-property","diff-add-bg","diff-remove-bg","diff-add-text","diff-remove-text","scrollbar-track","scrollbar-thumb","scrollbar-thumb-hover"];Rg("default");function gk(e){const t=document.documentElement;if(e.id==="default"||Object.keys(e.colors).length===0)for(const n of x0)t.style.removeProperty(`--${n}`);else{for(const n of x0)n in e.colors||t.style.removeProperty(`--${n}`);for(const[n,i]of Object.entries(e.colors))t.style.setProperty(`--${n}`,i)}try{localStorage.setItem(mk,e.id)}catch{}}function mF(){return pk}function gF(){try{return localStorage.getItem(mk)??"default"}catch{return"default"}}const w0=gF();if(w0!=="default"){const e=Rg(w0);gk(e)}function vF(e){const{title:t,className:n}=e,i=e.mode??lf,o=e$(e),d=n?`cost-badge ${n}`:"cost-badge";return r.jsx("span",{className:d,"data-testid":"sidebar-cost-badge","data-cost-badge-mode":i,title:t,"aria-label":t,children:o})}const yF=400;function vk(e){const{serverValue:t,scopeKey:n,debounceMs:i=yF,onFlush:o,equals:d}=e,h=d??Object.is,[l,u]=N.useState(t),[f,v]=N.useState(!1),[g,S]=N.useState(void 0),w=N.useRef(f);N.useEffect(()=>{w.current=f},[f]);const E=N.useRef(g);N.useEffect(()=>{E.current=g},[g]);const x=N.useRef(l);N.useEffect(()=>{x.current=l},[l]);const m=N.useRef(n),y=N.useRef(null),b=N.useRef(o);N.useEffect(()=>{b.current=o},[o]);const _=N.useRef(h);N.useEffect(()=>{_.current=h},[h]);const k=N.useCallback(()=>{y.current!==null&&(clearTimeout(y.current),y.current=null)},[]);N.useEffect(()=>{if(!(m.current===n)){k(),m.current=n,u(t),v(!1),S(void 0);return}const q=w.current,H=_.current(t,x.current);if(q&&!H){S(t);return}if(H){v(!1),S(void 0);return}u(t),v(!1),S(void 0)},[n,t,k]),N.useEffect(()=>()=>{k()},[k]);const j=N.useCallback(L=>{if(u(L),v(!0),i<=0)return;const q=m.current;k(),y.current=setTimeout(()=>{y.current=null,m.current===q&&(v(!1),b.current(L))},i)},[i,k]),T=N.useCallback(()=>{S(void 0)},[]),D=N.useCallback(()=>{const L=E.current;L!==void 0&&(k(),u(L),v(!1),S(void 0))},[k]),I=N.useCallback(()=>{k(),v(!1),b.current(x.current)},[k]);return{draft:l,setDraft:j,dirty:f,conflict:g,acceptDraft:T,discardDraft:D,flush:I}}const bF="Auto-permission mode disables all per-tool prompts for non-paired clients. Continue?",_F="Clear your per-device overrides? Notifications on this device will fall back to global defaults.",yk={permission:{label:"Permission requests",hint:"Tool-use prompts that need an allow / deny decision."},result:{label:"Task completion",hint:"Sent when a Claude turn finishes and no one is watching."},activity_update:{label:"Activity updates",hint:"Foreground task progress while you are away."},activity_waiting:{label:"Waiting for input",hint:"Claude asked a question or is paused on a prompt."},activity_error:{label:"Session errors",hint:"Crashes, tunnel drops, and unrecoverable session failures."},inactivity_warning:{label:"Inactivity warnings",hint:"Heads-up before a long-idle session is auto-paused."},billing_warning:{label:"Billing alerts",hint:"Metered-credit and datacenter-egress warnings from the billing canary."},live_activity:{label:"Live Activity (iOS)",hint:"iOS Dynamic Island / lock-screen Live Activity updates."},session_online:{label:"External session online",hint:"An external session reported in via /api/events."},session_offline:{label:"External session offline",hint:"An external session ended or went away."},session_activity:{label:"External session activity",hint:"Subagent and tool activity from external sessions."},mailbox:{label:"Mailbox",hint:"New agent-to-agent mailbox messages waiting for a session."}},hf=["permission","activity_waiting","activity_error","activity_update","inactivity_warning","billing_warning","result","session_online","session_offline","session_activity","mailbox","live_activity"],SF=["permission","activity_error"];function xF(){const e=(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}})();return JN(e).map(t=>({value:t,label:t===e?`${t} (this device)`:t}))}function wF(e){const{window:t,categories:n,bypassCategories:i,onWindowChange:o,onBypassChange:d}=e,h=N.useMemo(()=>xF(),[]),l=N.useMemo(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}},[]),u=N.useMemo(()=>({enabled:t!=null,start:t?.start??"22:00",end:t?.end??"07:00",timezone:t?.timezone??l}),[t,l]),f=N.useCallback((F,J)=>F.enabled?J.enabled&&F.start===J.start&&F.end===J.end&&F.timezone===J.timezone:!J.enabled,[]),{draft:v,setDraft:g,conflict:S,acceptDraft:w,discardDraft:E,flush:x}=vk({serverValue:u,scopeKey:"quiet-hours",debounceMs:0,onFlush:F=>{F.enabled?o({start:F.start,end:F.end,timezone:F.timezone}):o(null)},equals:f}),{enabled:m,start:y,end:b,timezone:_}=v,k=S===void 0?void 0:S.enabled?{start:S.start,end:S.end,timezone:S.timezone}:null,j=N.useCallback(F=>{g({enabled:F,start:y,end:b,timezone:_}),F?t==null&&o({start:y,end:b,timezone:_}):o(null)},[t,y,b,_,o,g]),T=N.useCallback(()=>{x()},[x]),D=N.useCallback(()=>{E()},[E]),I=N.useCallback(F=>{g({enabled:m,start:F,end:b,timezone:_})},[g,m,b,_]),L=N.useCallback(F=>{g({enabled:m,start:y,end:F,timezone:_})},[g,m,y,_]),q=N.useCallback(F=>{g({enabled:m,start:y,end:b,timezone:F})},[g,m,y,b]),H=N.useCallback((F,J)=>{const ie=new Set(i);J?ie.add(F):ie.delete(F),d([...ie])},[i,d]),Q=N.useMemo(()=>{const F=hf.filter(ie=>ie in n||i.includes(ie)),J=i.filter(ie=>!hf.includes(ie)&&!(ie in n));return[...F,...J]},[n,i]);return r.jsxs("div",{className:"quiet-hours-editor","data-testid":"quiet-hours-editor",children:[r.jsxs("div",{className:"settings-field settings-field-checkbox",children:[r.jsxs("label",{htmlFor:"quiet-hours-enabled",children:[r.jsx("input",{id:"quiet-hours-enabled",type:"checkbox",checked:m,onChange:F=>j(F.target.checked),"data-testid":"quiet-hours-enabled-toggle"}),"Quiet hours"]}),r.jsx("p",{className:"settings-hint",children:"Mute pushes during a fixed window each day. Operator-blocking categories (permission prompts, session errors) still fire by default — uncheck them below to silence them too."})]}),m&&r.jsxs(r.Fragment,{children:[k!==void 0&&r.jsxs("div",{className:"settings-hint quiet-hours-conflict-banner",role:"alert","data-testid":"quiet-hours-conflict-banner",children:[r.jsx("p",{children:"Another client updated quiet hours while you were editing. Keep your unsaved changes, or discard them and load the latest values?"}),r.jsxs("div",{className:"settings-field",children:[r.jsx("button",{type:"button",onClick:w,"data-testid":"quiet-hours-conflict-accept",children:"Keep my edits"}),r.jsx("button",{type:"button",onClick:D,"data-testid":"quiet-hours-conflict-discard",children:"Discard and load latest"})]})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"quiet-hours-start",children:"From"}),r.jsx("input",{id:"quiet-hours-start",type:"time",value:y,onChange:F=>I(F.target.value),"data-testid":"quiet-hours-start-input"})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"quiet-hours-end",children:"To"}),r.jsx("input",{id:"quiet-hours-end",type:"time",value:b,onChange:F=>L(F.target.value),"data-testid":"quiet-hours-end-input"})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"quiet-hours-timezone",children:"Timezone"}),r.jsx("select",{id:"quiet-hours-timezone",value:_,onChange:F=>q(F.target.value),"data-testid":"quiet-hours-timezone-select",children:h.map(F=>r.jsx("option",{value:F.value,children:F.label},F.value))})]}),r.jsx("div",{className:"settings-field",children:r.jsx("button",{type:"button",onClick:T,"data-testid":"quiet-hours-save-button",disabled:y===(t?.start??"")&&b===(t?.end??"")&&_===(t?.timezone??""),children:"Save quiet hours"})}),r.jsxs("fieldset",{className:"quiet-hours-bypass","data-testid":"quiet-hours-bypass-fieldset",children:[r.jsx("legend",{children:"Bypass during quiet hours"}),r.jsx("p",{className:"settings-hint",children:"Categories checked here still fire even at 3am. Uncheck to silence them."}),r.jsx("ul",{className:"notification-prefs-list",children:Q.map(F=>{const ie=yk[F]?.label??F,X=i.includes(F),de=`quiet-hours-bypass-${F}`;return r.jsx("li",{className:"settings-field settings-field-checkbox",children:r.jsxs("label",{htmlFor:de,children:[r.jsx("input",{id:de,type:"checkbox",checked:X,onChange:fe=>H(F,fe.target.checked),"data-testid":`quiet-hours-bypass-toggle-${F}`}),ie]})},F)})})]})]})]})}function kF(e){return e.length<=24?e:`${e.slice(0,24)}…`}function CF(e){const{devices:t,currentDeviceKey:n,onClear:i}=e,d=Object.keys(t).slice().sort((h,l)=>h===n?-1:l===n?1:h.localeCompare(l));return r.jsxs("fieldset",{className:"settings-fieldset notification-prefs-devices","data-testid":"notification-prefs-devices-list",children:[r.jsx("legend",{children:"Per-device overrides"}),r.jsx("p",{className:"settings-hint",children:"Each entry is a device (browser tab or mobile app) that has set its own notification preferences. Clear an entry to drop its overrides — useful when a push token refreshes or an app is reinstalled and the old entry becomes orphaned."}),d.length===0?r.jsx("p",{className:"settings-hint","data-testid":"notification-prefs-devices-empty",children:"No per-device overrides yet. Mute a category on this device above to create one."}):r.jsx("ul",{className:"notification-prefs-devices-list",children:d.map(h=>{const l=h===n,u=t[h];return u?r.jsxs("li",{className:"notification-prefs-device-entry","data-testid":`notification-prefs-device-entry-${h}`,children:[r.jsxs("span",{className:"notification-prefs-device-label",children:[r.jsx("code",{children:kF(h)}),l&&r.jsx("span",{className:"notification-prefs-device-self-tag",children:" (this device)"}),u.platform?r.jsxs("span",{className:"notification-prefs-device-meta","data-testid":`notification-prefs-device-platform-${h}`,children:[" · ",oO(u.platform)]}):null,u.lastSeenAt?r.jsxs("span",{className:"notification-prefs-device-meta","data-testid":`notification-prefs-device-last-seen-${h}`,children:[" · Last seen ",lO(u.lastSeenAt)]}):null]}),r.jsx("button",{type:"button",className:"notification-prefs-device-clear",onClick:()=>i(h),"data-testid":`notification-prefs-device-clear-${h}`,children:"Clear"})]},h):null})})]})}function EF({theme:e}){const t=e.colors["bg-primary"]||"#0f0f1a",n=e.colors["accent-blue"]||"#4a9eff",i=e.colors["text-primary"]||"#ffffff",o=e.terminal.background,d=e.terminal.foreground;return r.jsxs("div",{className:"theme-swatches",children:[r.jsx("span",{className:"theme-swatch",style:{backgroundColor:t},title:"Background"}),r.jsx("span",{className:"theme-swatch",style:{backgroundColor:n},title:"Accent"}),r.jsx("span",{className:"theme-swatch",style:{backgroundColor:i},title:"Text"}),r.jsx("span",{className:"theme-swatch",style:{backgroundColor:o,border:`1px solid ${d}`},title:"Terminal"}),r.jsx("span",{className:"theme-swatch",style:{backgroundColor:d},title:"Terminal text"})]})}function bk({active:e,showConsoleTab:t,onToggleConsoleTab:n,interventionPingEnabled:i,onToggleInterventionPing:o}){const d=e,h=V(ae=>ae.activeTheme),l=V(ae=>ae.setTheme),u=V(ae=>ae.defaultProvider),f=V(ae=>ae.setDefaultProvider),v=V(ae=>ae.defaultModel),g=V(ae=>ae.setDefaultModel),S=V(ae=>ae.availableModels??[]),w=V(ae=>ae.availableProviders??[]),E=V(ae=>ae.inputSettings),x=V(ae=>ae.updateInputSettings),m=V(ae=>ae.costBadgeMode),y=V(ae=>ae.setCostBadgeMode),b=V(ae=>ae.confirmSessionClose),_=V(ae=>ae.setConfirmSessionClose),k=V(ae=>ae.activeSessionId),j=V(ae=>ae.sessions),T=V(ae=>ae.setPromptEvaluator),D=V(ae=>ae.setChroxyContextHint),I=V(ae=>ae.setSessionPreamble),L=V(ae=>ae.byokCredentialsStatus),q=V(ae=>ae.refreshByokCredentialsStatus),H=V(ae=>ae.setByokCredentials),Q=V(ae=>ae.clearByokCredentials),F=V(ae=>ae.notificationPrefs),J=V(ae=>ae.refreshNotificationPrefs),ie=V(ae=>ae.setNotificationPrefsCategory),X=V(ae=>ae.currentDeviceKey),de=V(ae=>ae.setNotificationPrefsDevice),fe=V(ae=>ae.deleteNotificationPrefsDevice),$=V(ae=>ae.setNotificationPrefsQuietHours),P=V(ae=>ae.setNotificationPrefsBypassCategories),B=V(ae=>!!ae.serverCapabilities?.notificationPrefs),K=j.find(ae=>ae.sessionId===k)?.promptEvaluator,le=j.find(ae=>ae.sessionId===k)?.chroxyContextHint,me=j.find(ae=>ae.sessionId===k)?.sessionPreamble,be=mF(),Ee=hs(),se=Ee&&ma()&&!1,[Z,ge]=N.useState("none"),[De,Ge]=N.useState(null),[Ve,St]=N.useState("none"),[Nt,kt]=N.useState(!1),[Tt,at]=N.useState(!1),[en,cn]=N.useState(!1),[Bt,hn]=N.useState(null),[sn,Ct]=N.useState(""),[Ut,$t]=N.useState(null),[Lt,Ht]=N.useState(null),[zt,rn]=N.useState(!1),[ze,Je]=N.useState(null),[tt,Pt]=N.useState(!1),[Vt,Wt]=N.useState(null),[Zt,Dn]=N.useState(null),[wn,Kn]=N.useState(""),[je,mt]=N.useState(null),[xt,Mt]=N.useState(null),[un,_n]=N.useState(null),[tn,zn]=N.useState(!1),[ss,Ie]=N.useState(null),[ot,pt]=N.useState(!1),[At,O]=N.useState("idle"),[W,G]=N.useState(null),M=Ee&&ma(),ne=N.useCallback(async()=>{O("running"),G(null);try{const ae=_s();if(!ae)throw new Error("Tauri invoke unavailable");await ae("reset_speech_permissions"),O("success")}catch(ae){O("error"),G(ae instanceof Error?ae.message:String(ae))}},[]),[te,re]=N.useState(!1),{draft:ve,setDraft:Me,conflict:Ze,acceptDraft:Xe,discardDraft:Dt}=vk({serverValue:typeof me=="string"?me:"",scopeKey:k??null,debounceMs:400,onFlush:I}),nt="Settings save failed — server disconnected. Reconnect and try again.";N.useEffect(()=>{!d||!Ee||(Ge(null),kt(!1),Ie(null),pt(!1),re(!1),O("idle"),G(null),Ht(null),rn(!1),Wt(null),Dn(null),Pt(!1),Je(null),se&&I1().then(ae=>{Je(ae)}).catch(ae=>{Wt(ae instanceof Error?ae.message:String(ae))}),A1().then(ae=>{$t(ae??null),Ct(ae??"")}).catch(()=>{}),Dm().then(ae=>{ae&&ge(ae)}),hn(null),N1().then(ae=>{ae!==null?(at(ae),cn(ae)):hn("Could not load the LAN-exposure setting.")}).catch(ae=>{hn(ae instanceof Error?ae.message:String(ae))}),k1().then(ae=>{ae?.tunnelMode&&St(ae.tunnelMode)}),R1().then(ae=>{ae!==null&&zn(ae)}).catch(ae=>{Ie(ae instanceof Error?ae.message:String(ae))}))},[d,Ee,se]),N.useEffect(()=>{d&&q()},[d,q]),N.useEffect(()=>{d&&B&&J()},[d,B,J]),N.useEffect(()=>{d||(Mt(null),_n(null))},[d]);const Oe=N.useCallback(()=>{mt(null);const ae=wn.trim();if(!ae.startsWith("sk-ant-")){mt('Anthropic API keys start with "sk-ant-".');return}H(ae)?(Mt(null),Kn("")):Mt(nt)},[wn,H]),ce=N.useCallback(()=>{mt(null);const ae=Q();Mt(ae?null:nt)},[Q]),ke=N.useCallback((ae,vt)=>{const yt=ie(ae,vt);_n(yt?null:nt)},[ie]),Ue=N.useCallback((ae,vt,yt)=>{const ue=de(ae,vt,yt);_n(ue?null:nt)},[de]),rt=N.useCallback(ae=>{if(ae===X&&!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(_F):!0))return;const vt=fe(ae);_n(vt?null:nt)},[fe,X]),ct=N.useCallback(ae=>{const vt=$(ae);_n(vt?null:nt)},[$]),et=N.useCallback(ae=>{const vt=P(ae);_n(vt?null:nt)},[P]),st=N.useCallback(async ae=>{if(Ie(null),ae&&!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(bF):!0))return;const vt=tn;zn(ae),re(!0);try{await T1(ae),pt(!0)}catch(yt){zn(vt),Ie(yt instanceof Error?yt.message:String(yt))}finally{re(!1)}},[tn]),gt=N.useCallback(async ae=>{Ge(null);const vt=Z;ge(ae);try{await E1(ae)}catch(yt){const ue=await Dm();ge(ue??vt),Ge(yt instanceof Error?yt.message:String(yt))}},[Z]),it=N.useCallback(async ae=>{hn(null);const vt=Tt;at(ae);try{await j1(ae)}catch(yt){at(vt),hn(yt instanceof Error?yt.message:String(yt))}},[Tt]),ft=N.useCallback(async()=>{const ae=sn.trim();Ht(null),rn(!0);try{await Lm(ae||null),$t(ae||null),Ct(ae)}catch(vt){Ht(vt instanceof Error?vt.message:String(vt))}finally{rn(!1)}},[sn]),lt=N.useCallback(async()=>{Ht(null),rn(!0);try{await Lm(null),$t(null),Ct("")}catch(ae){Ht(ae instanceof Error?ae.message:String(ae))}finally{rn(!1)}},[]),ut=N.useCallback(async()=>{Wt(null),Dn(null),Pt(!0);try{const ae=await M1();Dn(ae?.appPath??null)}catch(ae){Wt(ae instanceof Error?ae.message:String(ae))}finally{Pt(!1)}},[]),Ne=N.useMemo(()=>w.length>0&&!w.some(ae=>ae.name===u)?w[0].name:u,[w,u]),Ae=N.useCallback(ae=>{l(ae),gk(Rg(ae))},[l]),Ke=N.useCallback(ae=>{f(ae.target.value)},[f]),$e=N.useCallback(ae=>{g(ae.target.value)},[g]),Le=N.useCallback(ae=>{Jw(ae.target.value)&&y(ae.target.value)},[y]),We=N.useCallback(ae=>{x({chatEnterToSend:ae.target.value==="enter"})},[x]),Rt=N.useCallback(ae=>{O0(ae.target.value)&&x({voiceInputMode:ae.target.value})},[x]);return d?r.jsxs("div",{className:"settings-body","data-testid":"settings-content",children:[r.jsxs("section",{className:"settings-section",children:[r.jsx("h3",{children:"Appearance"}),r.jsx("div",{className:"theme-grid",children:be.map(ae=>r.jsxs("button",{className:`theme-card${h===ae.id?" active":""}`,onClick:()=>Ae(ae.id),type:"button","aria-pressed":h===ae.id,children:[r.jsx(EF,{theme:ae}),r.jsx("span",{className:"theme-card-name",children:ae.name}),r.jsx("span",{className:"theme-card-desc",children:ae.description}),h===ae.id&&r.jsx("span",{className:"theme-card-check","aria-hidden":"true",children:"✓"})]},ae.id))})]}),r.jsxs("section",{className:"settings-section",children:[r.jsx("h3",{children:"Session Defaults"}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"default-provider",children:"Default provider"}),r.jsx("select",{id:"default-provider","aria-label":"Default provider",value:Ne,onChange:Ke,children:w.length>0?w.map(ae=>r.jsx("option",{value:ae.name,children:hm[ae.name]||ae.name},ae.name)):r.jsxs(r.Fragment,{children:[r.jsx("option",{value:"claude-sdk",children:"Claude Code (SDK)"}),r.jsx("option",{value:"claude-cli",children:"Claude Code (CLI)"})]})})]}),S.length>0&&r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"default-model",children:"Default model"}),r.jsxs("select",{id:"default-model","aria-label":"Default model",value:v,onChange:$e,children:[r.jsx("option",{value:"",children:"Server default"}),S.map(ae=>r.jsx("option",{value:ae.id,children:ae.label},ae.id))]})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"cost-badge-mode",children:"Header badge shows"}),r.jsx("select",{id:"cost-badge-mode","aria-label":"Header badge display",value:m,onChange:Le,"data-testid":"cost-badge-mode-select",children:QB.map(ae=>r.jsx("option",{value:ae,children:JB[ae]},ae))}),r.jsx("p",{className:"settings-hint",children:"Choose what the badge in the top bar displays — provider and model, the running dollar cost, token count, percent of the context window used, or the session-type tag."})]}),r.jsxs("div",{className:"settings-field settings-field-checkbox",children:[r.jsxs("label",{htmlFor:"confirm-session-close",children:[r.jsx("input",{id:"confirm-session-close",type:"checkbox",checked:b,onChange:ae=>_(ae.target.checked),"data-testid":"confirm-session-close-toggle"}),"Confirm before closing a session"]}),r.jsx("p",{className:"settings-hint",children:"Ask for confirmation before closing a session tab so you don't terminate a session by accident. Closing the Control Room tab never asks."})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"send-shortcut",children:"Send message with"}),r.jsxs("select",{id:"send-shortcut","aria-label":"Send shortcut",value:E.chatEnterToSend?"enter":"cmd-enter",onChange:We,children:[r.jsx("option",{value:"enter",children:"Enter"}),r.jsx("option",{value:"cmd-enter",children:"Cmd/Ctrl+Enter"})]})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"voice-input-mode",children:"Voice input"}),r.jsxs("select",{id:"voice-input-mode","aria-label":"Voice input mode","aria-describedby":"voice-input-mode-hint",value:E.voiceInputMode,onChange:Rt,children:[r.jsx("option",{value:"continuous",children:"Keep listening until I click stop"}),r.jsx("option",{value:"auto-pause",children:"Stop after silence (browser decides)"})]}),r.jsxs("p",{id:"voice-input-mode-hint",className:"settings-hint","data-testid":"voice-input-mode-hint",children:["Click the mic button to start dictation and click again to stop — the button is a toggle, not push-to-hold.",r.jsx("strong",{children:" “Keep listening until I click stop”"})," ","holds the mic open through pauses and restarts recognition automatically."," ",r.jsx("strong",{children:"“Stop after silence (browser decides)”"})," ","lets the browser end recognition after a short silence in your speech. Only applies to the browser speech engine — the macOS native speech helper manages its own end-of-utterance timing."]})]}),M&&r.jsxs("div",{className:"settings-field","data-testid":"speech-reset-row",children:[r.jsx("label",{htmlFor:"speech-reset-button",children:"Reset macOS speech permissions"}),r.jsx("button",{type:"button",id:"speech-reset-button",className:"settings-secondary-button",onClick:ne,disabled:At==="running","data-testid":"speech-reset-button",children:At==="running"?"Resetting…":"Reset now"}),At==="success"&&r.jsx("p",{className:"settings-hint","data-testid":"speech-reset-success",role:"status",children:"Speech permissions reset. Click the mic again — macOS will prompt for permission, and the new entitled helper signature will be allowed."}),At==="error"&&W&&r.jsxs("p",{className:"settings-hint settings-error","data-testid":"speech-reset-error",role:"alert",children:["Reset failed: ",W]}),At==="idle"&&r.jsxs("p",{className:"settings-hint",children:["Use this if voice input still says “permission denied” after upgrading. Chroxy v0.9.40+ ships with a new helper signature; macOS may cache a denial for the old signature. Resets ",r.jsx("code",{children:"Microphone"})," and"," ",r.jsx("code",{children:"SpeechRecognition"})," for ",r.jsx("code",{children:"com.chroxy.desktop"}),"."]})]})]}),r.jsx(iF,{}),(typeof K=="boolean"||typeof le=="boolean"||typeof me=="string")&&r.jsxs("section",{className:"settings-section","data-testid":"active-session-section",children:[r.jsx("h3",{children:"Active session"}),typeof K=="boolean"&&r.jsxs("div",{className:"settings-field settings-field-checkbox",children:[r.jsxs("label",{htmlFor:"prompt-evaluator-toggle",children:[r.jsx("input",{id:"prompt-evaluator-toggle",type:"checkbox",checked:K,onChange:ae=>T(ae.target.checked),"data-testid":"prompt-evaluator-toggle"}),"Auto-evaluate prompts before send"]}),r.jsx("p",{className:"settings-hint",children:"Run a quality check on each prompt before it's sent. Catches ambiguous wording and surfaces clarifications inline. Applies to this session only."})]}),typeof le=="boolean"&&r.jsxs("div",{className:"settings-field settings-field-checkbox",children:[r.jsxs("label",{htmlFor:"chroxy-context-hint-toggle",children:[r.jsx("input",{id:"chroxy-context-hint-toggle",type:"checkbox",checked:le,onChange:ae=>D(ae.target.checked),"data-testid":"chroxy-context-hint-toggle"}),"Tell the model it's running inside Chroxy"]}),r.jsx("p",{className:"settings-hint",children:"Prepends a short note to the system prompt so the model knows it's bridged to a phone over a Cloudflare tunnel and can prefer concise, mobile-friendly output (narrower code blocks, no wide ASCII diagrams). Applies to this session only."})]}),typeof me=="string"&&r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"session-preamble-input",children:"Always include this context in every message"}),Ze!==void 0&&r.jsxs("div",{className:"settings-hint session-preamble-conflict-banner",role:"alert","data-testid":"session-preamble-conflict-banner",children:[r.jsx("p",{children:"Another client updated this session's preamble while you were editing. Keep your unsaved changes, or discard them and load the latest value?"}),r.jsxs("div",{className:"settings-field",children:[r.jsx("button",{type:"button",onClick:Xe,"data-testid":"session-preamble-conflict-accept",children:"Keep my edits"}),r.jsx("button",{type:"button",onClick:Dt,"data-testid":"session-preamble-conflict-discard",children:"Discard and load latest"})]})]}),r.jsx("textarea",{id:"session-preamble-input",value:ve,onChange:ae=>Me(ae.target.value),rows:4,maxLength:4e3,placeholder:"e.g. This is a Godot 4 project — prefer GDScript over C#. Always respond in concise bullet points.","data-testid":"session-preamble-input",className:"settings-textarea"}),r.jsx("p",{className:"settings-hint",children:"Prepended to the system prompt every turn so you don't have to retype the same context in each message. Capped at 4000 characters. Applies to this session only and persists across server restarts."})]})]}),w.some(ae=>!!ae.auth)&&r.jsxs("section",{className:"settings-section","data-testid":"auth-status-section",children:[r.jsx("h3",{children:"Provider auth status"}),r.jsxs("p",{className:"settings-hint",children:["Which billing identity each provider would use for new sessions. The server reports this from the same checks ",r.jsx("code",{children:"chroxy doctor"})," runs."]}),r.jsxs("ul",{className:"auth-status-legend","aria-label":"Color legend",children:[r.jsxs("li",{children:[r.jsx("span",{className:"auth-status-swatch","data-tone":"oauth","aria-hidden":"true"})," Subscription / login"]}),r.jsxs("li",{children:[r.jsx("span",{className:"auth-status-swatch","data-tone":"env","aria-hidden":"true"})," API key"]}),r.jsxs("li",{children:[r.jsx("span",{className:"auth-status-swatch","data-tone":"missing","aria-hidden":"true"})," Not configured"]}),r.jsxs("li",{children:[r.jsx("span",{className:"auth-status-swatch","data-tone":"none","aria-hidden":"true"})," Custom provider"]})]}),r.jsx("ul",{className:"auth-status-list",children:w.map(ae=>{if(!ae.auth)return null;const vt=hm[ae.name]||ae.name,yt=ae.auth.ready?ae.auth.source:"missing";return r.jsxs("li",{className:"auth-status-row","data-provider":ae.name,"data-tone":yt,"data-testid":`auth-status-${ae.name}`,children:[r.jsx("span",{className:"auth-status-name",children:vt}),r.jsx("span",{className:"auth-status-detail",children:ae.auth.detail}),!ae.auth.ready&&ae.auth.hint&&r.jsx("span",{className:"auth-status-hint",children:ae.auth.hint})]},ae.name)})})]}),r.jsxs("section",{className:"settings-section","data-testid":"byok-credentials-section",children:[r.jsx("h3",{children:"BYOK credentials"}),r.jsxs("p",{className:"settings-hint",children:["Paste an Anthropic API key for the ",r.jsx("code",{children:"claude-byok"})," provider. Saved to ",r.jsx("code",{children:"~/.chroxy/credentials.json"})," with mode 0600. An ",r.jsx("code",{children:"ANTHROPIC_API_KEY"})," environment variable takes precedence if set."]}),r.jsx("div",{className:"settings-field","data-testid":"byok-status",children:r.jsxs("span",{children:["Status:"," ",L?.status==="set"?`Set (${L.source}) — ${L.masked}`:"Missing"]})}),L?.status==="missing"&&L.reason&&r.jsx("p",{className:"settings-hint","data-testid":"byok-reason",children:L.reason}),L?.fileExists&&L.source!=="file"&&r.jsx("p",{className:"settings-hint","data-testid":"byok-stale-file-notice",style:{color:"var(--warning-fg, #fbbf24)"},children:L.source==="env"?r.jsxs(r.Fragment,{children:["Your ",r.jsx("code",{children:"ANTHROPIC_API_KEY"})," environment variable is currently being used. But a saved ",r.jsx("code",{children:"credentials.json"})," file is still on disk and will be used again the moment the env var is unset. Click Remove to delete the file."]}):r.jsxs(r.Fragment,{children:["A saved ",r.jsx("code",{children:"credentials.json"})," file is on disk but cannot be read (see Status above for the reason). Click Remove to delete the unreadable file, then paste your key again to save a fresh, readable copy."]})}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"byok-key-input",children:"API key"}),r.jsx("input",{id:"byok-key-input",type:"password",autoComplete:"off",spellCheck:!1,placeholder:"sk-ant-...",value:wn,onChange:ae=>Kn(ae.target.value),"data-testid":"byok-key-input"})]}),je&&r.jsx("p",{className:"settings-hint","data-testid":"byok-error",style:{color:"var(--error, #f00)"},children:je}),xt&&r.jsx("p",{className:"settings-hint",role:"alert","data-testid":"byok-ws-closed-error",style:{color:"var(--error, #f00)"},children:xt}),r.jsxs("div",{className:"settings-field",children:[r.jsx("button",{type:"button",onClick:Oe,disabled:wn.trim().length===0,"data-testid":"byok-save-button",children:"Save"}),L?.fileExists&&r.jsx("button",{type:"button",onClick:ce,"data-testid":"byok-clear-button",children:"Remove"})]})]}),r.jsx(oF,{isOpen:d}),r.jsxs("section",{className:"settings-section","data-testid":"notification-prefs-section",children:[r.jsx("h3",{children:"Notifications"}),r.jsx("p",{className:"settings-hint",children:"Choose which push categories reach your devices. Server-side rate limits still apply as a defensive floor — these toggles can only mute further, never amplify."}),un&&r.jsx("p",{className:"settings-hint",role:"alert","data-testid":"notification-prefs-ws-closed-error",style:{color:"var(--error, #f00)"},children:un}),B?F==null?r.jsx("p",{className:"settings-hint","data-testid":"notification-prefs-loading",children:"Loading preferences…"}):r.jsxs(r.Fragment,{children:[(()=>{const ae=F.categories,vt=hf.filter(bt=>bt in ae),yt=Object.keys(ae).filter(bt=>!hf.includes(bt)),ue=[...vt,...yt],Gt=X?F.devices?.[X]?.categories??{}:{};return r.jsx("ul",{className:"notification-prefs-list",children:ue.map(bt=>{const Qt=yk[bt],Kt=Qt?.label??bt,Jt=Qt?.hint,Yt=ae[bt]!==!1,An=`notification-prefs-${bt}`,xn=Gt[bt]===!1,Rn=`notification-prefs-device-${bt}`;return r.jsxs("li",{className:"settings-field settings-field-checkbox",children:[r.jsxs("label",{htmlFor:An,children:[r.jsx("input",{id:An,type:"checkbox",checked:Yt,onChange:En=>ke(bt,En.target.checked),"data-testid":`notification-prefs-toggle-${bt}`}),Kt]}),Jt&&r.jsx("p",{className:"settings-hint",children:Jt}),X&&r.jsxs("div",{className:"notification-prefs-device-row","data-testid":`notification-prefs-device-row-${bt}`,children:[r.jsx("input",{id:Rn,type:"checkbox",checked:xn,onChange:En=>Ue(X,bt,!En.target.checked),"data-testid":`notification-prefs-device-toggle-${bt}`}),r.jsx("label",{htmlFor:Rn,children:"Mute on this device"})]})]},bt)})})})(),r.jsx(wF,{window:F.quietHours,categories:F.categories,bypassCategories:F.bypassCategories??SF,onWindowChange:ct,onBypassChange:et}),r.jsx(CF,{devices:F.devices,currentDeviceKey:X,onClear:rt})]}):r.jsx("p",{className:"settings-hint","data-testid":"notification-prefs-not-supported",children:"Your server does not support notification preferences. Upgrade to chroxy v0.9.14 or newer to manage per-category opt-in, per-device mutes, and quiet hours from here."})]}),(n||o)&&r.jsxs("section",{className:"settings-section","data-testid":"dashboard-section",children:[r.jsx("h3",{children:"Dashboard"}),n&&r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"show-console-tab",children:"Show Console tab"}),r.jsx("input",{id:"show-console-tab",type:"checkbox",checked:t??!1,onChange:ae=>n(ae.target.checked)})]}),o&&r.jsxs("div",{className:"settings-field settings-field-checkbox",children:[r.jsxs("label",{htmlFor:"intervention-ping-toggle",children:[r.jsx("input",{id:"intervention-ping-toggle",type:"checkbox",checked:i??!0,onChange:ae=>o(ae.target.checked),"data-testid":"intervention-ping-toggle"}),"Play a sound when the agent needs input"]}),r.jsx("p",{className:"settings-hint",children:"A short chirp plays in this browser tab whenever a session needs an intervention (permission prompt or question) — so you get pulled back in even with the tab minimized or idle. Applies to this device only. Repeat alerts for the same request are deduped, and bursts across multiple sessions are throttled into a single ping."})]})]}),Ee&&r.jsxs("section",{className:"settings-section",children:[r.jsx("h3",{children:"Security"}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"allow-auto-perm",children:"Allow auto-permission mode"}),r.jsx("input",{id:"allow-auto-perm",type:"checkbox",checked:tn,disabled:te,onChange:ae=>st(ae.target.checked)})]}),r.jsx("p",{className:"settings-help",children:"When enabled, sessions on the host can switch to auto-permission mode (no per-tool prompts). Paired QR clients are always blocked from this regardless of the toggle."}),ss&&r.jsx("p",{className:"tunnel-mode-error",role:"alert",children:ss}),ot&&!ss&&r.jsx("button",{type:"button",className:"tunnel-restart-btn",disabled:Nt,onClick:async()=>{kt(!0),await Gd(),pt(!1),setTimeout(()=>kt(!1),3e3)},children:Nt?"Restarting...":"Restart Server to Apply"})]}),Ee&&r.jsxs("section",{className:"settings-section",children:[r.jsx("h3",{children:"Network"}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"expose-on-lan",children:"Expose on local network"}),r.jsx("input",{id:"expose-on-lan",type:"checkbox","data-testid":"expose-on-lan-toggle",checked:Tt,onChange:ae=>it(ae.target.checked)})]}),r.jsx("p",{className:"settings-help",children:"Off (default): the server is reachable only from this machine (loopback). On: binds all network interfaces so phones on the same Wi-Fi can scan the QR code and connect. Leave off and use a tunnel (below) for remote access."}),r.jsxs("div",{className:"settings-field",children:[Bt&&r.jsx("p",{className:"tunnel-mode-error",role:"alert",children:Bt}),Tt!==en?r.jsx("button",{type:"button",className:"tunnel-restart-btn",disabled:Nt,onClick:async()=>{kt(!0),await Gd(),cn(Tt),setTimeout(()=>kt(!1),3e3)},children:Nt?"Restarting...":"Restart Server to Apply"}):r.jsx("p",{className:"tunnel-mode-note",children:"Server restart required after change"})]}),r.jsxs("div",{className:"settings-field",children:[r.jsx("span",{id:"tunnel-mode-label",children:"Tunnel mode"}),r.jsx("div",{className:"tunnel-mode-options",role:"radiogroup","aria-labelledby":"tunnel-mode-label",children:[{value:"none",label:"Off",desc:"No public tunnel"},{value:"quick",label:"Quick Tunnel",desc:"Random Cloudflare URL"},{value:"named",label:"Named Tunnel",desc:"Stable URL, requires setup"}].map(ae=>r.jsxs("button",{type:"button",role:"radio",className:`tunnel-mode-option${Z===ae.value?" active":""}`,onClick:()=>gt(ae.value),"aria-checked":Z===ae.value,children:[r.jsx("span",{className:"tunnel-mode-label",children:ae.label}),r.jsx("span",{className:"tunnel-mode-desc",children:ae.desc})]},ae.value))}),De&&r.jsx("p",{className:"tunnel-mode-error",children:De}),Z!==Ve?r.jsx("button",{type:"button",className:"tunnel-restart-btn",disabled:Nt,onClick:async()=>{kt(!0),await Gd(),St(Z),setTimeout(()=>kt(!1),3e3)},children:Nt?"Restarting...":"Restart Server to Apply"}):r.jsx("p",{className:"tunnel-mode-note",children:"Server restart required after change"})]})]}),Ee&&r.jsxs("section",{className:"settings-section",children:[r.jsx("h3",{children:"Desktop"}),r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{htmlFor:"summon-hotkey",children:"Summon hotkey"}),r.jsxs("div",{className:"summon-hotkey-row",children:[r.jsx("input",{id:"summon-hotkey",type:"text","aria-label":"Summon hotkey accelerator",placeholder:"e.g. CmdOrCtrl+Shift+K",value:sn,onChange:ae=>Ct(ae.target.value),spellCheck:!1,autoCapitalize:"off",autoCorrect:"off","data-testid":"summon-hotkey-input"}),r.jsx("button",{type:"button",className:"summon-hotkey-save",disabled:zt||sn.trim()===(Ut??""),onClick:ft,"data-testid":"summon-hotkey-save",children:zt?"Saving…":"Save"}),r.jsx("button",{type:"button",className:"summon-hotkey-clear",disabled:zt||!sn.trim()&&!Ut,onClick:lt,"data-testid":"summon-hotkey-clear",children:"Clear"})]}),Lt&&r.jsx("p",{className:"tunnel-mode-error","data-testid":"summon-hotkey-error",children:Lt}),r.jsxs("p",{className:"settings-hint",children:["A system-wide shortcut to bring Chroxy to the front, in Tauri accelerator syntax (e.g. ",r.jsx("code",{children:"CmdOrCtrl+Shift+K"}),"). Applies immediately — no restart. Leave blank to disable; the tray “Show Chroxy” item is always available."]})]}),se&&ze?.available&&r.jsxs("div",{className:"settings-field",children:[r.jsx("label",{children:"No It All"}),r.jsx("button",{type:"button",className:"settings-secondary-button",disabled:tt,onClick:ut,"data-testid":"private-no-it-all-launch",children:tt?"Building...":"Build and Open"}),r.jsxs("p",{className:"settings-hint",children:["Private dev launcher for the local sibling checkout at"," ",r.jsx("code",{children:ze.repoPath}),". It is not bundled into release builds."]}),Zt&&r.jsxs("p",{className:"settings-hint","data-testid":"private-no-it-all-app-path",children:["Opened ",r.jsx("code",{children:Zt}),"."]}),Vt&&r.jsx("p",{className:"tunnel-mode-error","data-testid":"private-no-it-all-error",children:Vt})]})]})]}):null}function NF({isOpen:e,onClose:t,showConsoleTab:n,onToggleConsoleTab:i,interventionPingEnabled:o,onToggleInterventionPing:d}){const h=N.useRef(null);return N.useEffect(()=>{if(!e)return;const l=u=>{if(u.key==="Escape"){const f=document.querySelectorAll("[data-modal-overlay]");f.length>0&&f[f.length-1]===h.current&&(u.preventDefault(),t())}};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[e,t]),e?r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:h,className:"settings-backdrop","data-modal-overlay":!0,onClick:t}),r.jsxs("div",{className:"settings-panel",role:"dialog","aria-modal":"true","aria-labelledby":"settings-title",children:[r.jsxs("div",{className:"settings-header",children:[r.jsx("h2",{id:"settings-title",children:"Settings"}),r.jsx("button",{className:"settings-close",onClick:t,"aria-label":"Close settings",type:"button",children:"×"})]}),r.jsx(bk,{active:e,showConsoleTab:n,onToggleConsoleTab:i,interventionPingEnabled:o,onToggleInterventionPing:d})]})]}):null}const Ua=[{key:"repos",label:"Project status",survey:!0,requestType:"host_status_request",snapshotKey:"hostStatus",loadingKey:"hostStatusLoading",requestKey:"requestHostStatus"},{key:"runners",label:"Self-hosted runners",survey:!0,requestType:"runner_status_request",snapshotKey:"runnerStatus",loadingKey:"runnerStatusLoading",requestKey:"requestRunnerStatus"},{key:"containers",label:"Containers",survey:!0,requestType:"containers_status_request",snapshotKey:"containersStatus",loadingKey:"containersStatusLoading",requestKey:"requestContainersStatus"},{key:"repo-config",label:"Repo runtime config",survey:!0,requestType:"repo_runtime_config_request",snapshotKey:"repoRuntimeConfig",loadingKey:"repoRuntimeConfigLoading",requestKey:"requestRepoRuntimeConfig"},{key:"byok-pool",label:"BYOK pool",survey:!0,requestType:"byok_pool_status_request",snapshotKey:"byokPoolStatus",loadingKey:"byokPoolStatusLoading",requestKey:"requestByokPoolStatus"},{key:"host-prune",label:"Host prune",survey:!0,requestType:"host_prune_status_request",snapshotKey:"hostPruneStatus",loadingKey:"hostPruneStatusLoading",requestKey:"requestHostPruneStatus"},{key:"device-runtimes",label:"Device runtimes",survey:!0,requestType:"simulator_status_request",snapshotKey:"simulatorStatus",loadingKey:"simulatorStatusLoading",requestKey:"requestSimulatorStatus"},{key:"integrations",label:"Integrations",survey:!0,requestType:"integration_status_request",snapshotKey:"integrationStatus",loadingKey:"integrationStatusLoading",requestKey:"requestIntegrationStatus"},{key:"skills",label:"Skills",survey:!0,requestType:"skills_inventory_request",snapshotKey:"skillsInventory",loadingKey:"skillsInventoryLoading",requestKey:"requestSkillsInventory"},{key:"mailbox",label:"Mailbox",survey:!0,requestType:"mailbox_status_request",snapshotKey:"mailboxStatus",loadingKey:"mailboxStatusLoading",requestKey:"requestMailboxStatus"},{key:"repo-events",label:"Repo events",survey:!0,requestType:"repo_events_request",snapshotKey:"repoEventsSnapshot",loadingKey:"repoEventsLoading",requestKey:"requestRepoEvents"},{key:"mission-control",label:"Mission control",survey:!1},{key:"settings",label:"Settings",survey:!1}],jF=new Set(Ua.map(e=>e.key)),_k=new Map(Ua.filter(e=>e.survey).map(e=>[e.key,e]));new Set(_k.keys());const AF=6e4,Sk="chroxy_cr_tab";function RF(){try{const e=localStorage.getItem(Sk);if(e&&jF.has(e))return e}catch{}return"repos"}function TF(e){try{localStorage.setItem(Sk,e)}catch{}}function IF(e){if(!e)return!0;const t=Date.parse(e);return Number.isNaN(t)?!0:Date.now()-t>=AF}function MF(){const e=V(f=>f.activity),t=V(f=>f.sessions),n=V(f=>f.externalSessionsSnapshot),i=V(f=>f.requestExternalSessions);N.useEffect(()=>{i()},[i]);const o=t.map(f=>({sessionId:f.sessionId,cwd:f.cwd,name:f.name,worktree:f.worktree})),d=n?.sessions??[],h=V(f=>f.sendCancelActivity),l=V(f=>f.switchSession),u=V(f=>f.cancellingActivityIds);return r.jsx(JH,{activity:e,sessions:o,external:d,onCancelActivity:(f,v)=>h(f,v),cancellingActivityIds:u,onJumpToSession:f=>l(f)})}function DF({onInvestigate:e,onOpenSession:t,onConfigureRepo:n,initialTab:i,forceTab:o,forceTabNonce:d,showConsoleTab:h,onToggleConsoleTab:l,interventionPingEnabled:u,onToggleInterventionPing:f}={}){const[v,g]=N.useState(()=>i??RF()),S=N.useCallback($=>{g($),TF($)},[]),w=N.useRef(d);N.useEffect(()=>{d!==w.current&&(w.current=d,o&&S(o))},[o,d,S]);const E=V($=>$.connectionPhase==="connected"),x=_k.get(v),m=V($=>x?$[x.snapshotKey]:null),y=V($=>x?$[x.loadingKey]:!1),b=V($=>x?$[x.requestKey]:void 0);N.useEffect(()=>{E&&(!x||!b||y||IF(m?.generatedAt)&&b())},[E,x,b,y,m]);const _=N.useRef(null),[k,j]=N.useState({left:!1,right:!1}),T=N.useCallback(()=>{const $=_.current;if(!$)return;const{scrollLeft:P,scrollWidth:B,clientWidth:K}=$,le=P>1,me=P+K<B-1;j(be=>be.left===le&&be.right===me?be:{left:le,right:me})},[]);N.useEffect(()=>{const $=_.current;if(!$||(T(),typeof ResizeObserver>"u"))return;const P=new ResizeObserver(T);return P.observe($),()=>P.disconnect()},[T]);const D=N.useCallback($=>{const P=_.current;P&&P.scrollBy?.({left:$*P.clientWidth*.7,behavior:"smooth"})},[]),I=N.useRef(null),L=N.useRef(null),q=N.useRef(!1),H=N.useCallback(()=>{I.current!==null&&(clearTimeout(I.current),I.current=null),L.current!==null&&(clearInterval(L.current),L.current=null),setTimeout(()=>{q.current=!1},0)},[]),Q=N.useCallback($=>{H(),q.current=!1,I.current=setTimeout(()=>{q.current=!0,L.current=setInterval(()=>{const P=_.current;P?.scrollBy?.({left:$*P.clientWidth*.18})},120)},350)},[H]),F=N.useCallback($=>{if(q.current){q.current=!1;return}D($)},[D]),J=N.useRef({active:!1,startX:0,startScroll:0}),ie=N.useRef(!1),X=N.useCallback($=>{if($.button!==0||$.pointerType!=="mouse")return;const P=_.current;P&&(J.current={active:!0,startX:$.clientX,startScroll:P.scrollLeft},ie.current=!1)},[]),de=N.useCallback($=>{const P=J.current;if(!P.active)return;const B=_.current;if(!B)return;const K=$.clientX-P.startX;!ie.current&&Math.abs(K)<=5||(ie.current=!0,B.setPointerCapture?.($.pointerId),B.scrollLeft=P.startScroll-K)},[]),fe=N.useCallback(()=>{J.current.active=!1,setTimeout(()=>{ie.current=!1},0)},[]);return N.useEffect(()=>H,[H]),N.useEffect(()=>{const $=_.current;if(!$)return;$.querySelector('[role="tab"][aria-selected="true"]')?.scrollIntoView?.({inline:"nearest",block:"nearest"}),T()},[v,T]),r.jsxs("div",{className:"cr-view","data-testid":"control-room-view",children:[r.jsxs("div",{className:"cr-tabs-wrap",children:[r.jsx("button",{type:"button",className:`cr-tab-chevron cr-tab-chevron-left${k.left?"":" cr-tab-chevron-hidden"}`,"aria-label":"Scroll tabs left","aria-hidden":!k.left,tabIndex:-1,"data-testid":"cr-tabs-chevron-left",onClick:()=>F(-1),onPointerDown:()=>Q(-1),onPointerUp:H,onPointerLeave:H,onPointerCancel:H,children:"‹"}),r.jsx("div",{className:"cr-tabs",role:"tablist","aria-label":"Control Room sections","data-testid":"cr-tabs",ref:_,onScroll:T,onPointerDown:X,onPointerMove:de,onPointerUp:fe,onPointerCancel:fe,onPointerLeave:fe,children:Ua.map(($,P)=>{const B=v===$.key;return r.jsx("button",{type:"button",role:"tab","aria-selected":B,tabIndex:B?0:-1,className:`cr-tab${B?" cr-tab-active":""}`,"data-testid":`cr-tab-${$.key}`,onClick:()=>{if(ie.current){ie.current=!1;return}S($.key)},onKeyDown:K=>{if(K.key!=="ArrowRight"&&K.key!=="ArrowLeft")return;K.preventDefault();const le=K.key==="ArrowRight"?(P+1)%Ua.length:(P-1+Ua.length)%Ua.length,me=Ua[le];S(me.key),K.currentTarget.parentElement?.querySelectorAll('[role="tab"]')?.[le]?.focus()},children:$.label},$.key)})}),r.jsx("button",{type:"button",className:`cr-tab-chevron cr-tab-chevron-right${k.right?"":" cr-tab-chevron-hidden"}`,"aria-label":"Scroll tabs right","aria-hidden":!k.right,tabIndex:-1,"data-testid":"cr-tabs-chevron-right",onClick:()=>F(1),onPointerDown:()=>Q(1),onPointerUp:H,onPointerLeave:H,onPointerCancel:H,children:"›"})]}),v==="repos"?r.jsx(xq,{onInvestigate:e,onOpenSession:t,onConfigureRepo:n}):v==="runners"?r.jsx(Iq,{}):v==="containers"?r.jsx(Xq,{}):v==="repo-config"?r.jsx(tH,{}):v==="byok-pool"?r.jsx(iH,{}):v==="host-prune"?r.jsx(aH,{}):v==="device-runtimes"?r.jsx(lH,{}):v==="integrations"?r.jsx(AH,{}):v==="skills"?r.jsx(FH,{}):v==="mailbox"?r.jsx(QH,{}):v==="repo-events"?r.jsx(PH,{}):v==="mission-control"?r.jsx(MF,{}):r.jsx("div",{className:"cr-settings-tab","data-testid":"cr-settings-tab",children:r.jsx(bk,{active:v==="settings",showConsoleTab:h,onToggleConsoleTab:l,interventionPingEnabled:u,onToggleInterventionPing:f})})]})}function LF({isOpen:e,onClose:t,shortcuts:n}){const i=N.useRef(null);if(N.useEffect(()=>{if(!e)return;const d=h=>{if(h.key==="Escape"){const l=document.querySelectorAll("[data-modal-overlay]");l.length>0&&l[l.length-1]===i.current&&(h.preventDefault(),h.stopPropagation(),t())}};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[e,t]),!e)return null;const o=new Map;for(const d of n){const h=o.get(d.section)||[];h.push(d),o.set(d.section,h)}return r.jsx("div",{ref:i,className:"shortcut-help-overlay","data-modal-overlay":!0,onClick:t,children:r.jsxs("div",{className:"shortcut-help-panel",role:"dialog","aria-modal":"true","aria-labelledby":"shortcut-help-title",onClick:d=>d.stopPropagation(),children:[r.jsxs("div",{className:"shortcut-help-header",children:[r.jsx("h2",{id:"shortcut-help-title",children:"Keyboard Shortcuts"}),r.jsx("button",{className:"settings-close",onClick:t,"aria-label":"Close shortcuts",type:"button",children:"×"})]}),r.jsx("div",{className:"shortcut-help-body",children:[...o.entries()].map(([d,h])=>r.jsxs("div",{className:"shortcut-section",children:[r.jsx("h3",{children:d}),r.jsx("dl",{className:"shortcut-list",children:h.map(l=>r.jsxs("div",{className:"shortcut-row",children:[r.jsx("dt",{children:r.jsx("kbd",{children:l.keys})}),r.jsx("dd",{children:l.description})]},l.keys))})]},d))})]})})}const OF={flex:1,overflow:"auto",maxHeight:"min(60vh, 480px)",padding:12,fontFamily:'var(--font-mono, "SF Mono", Menlo, monospace)',fontSize:12,whiteSpace:"pre-wrap",wordBreak:"break-word",background:"var(--bg-input, var(--bg-secondary, #0f0f1a))",border:"1px solid var(--border-primary, #2a2a4e)",borderRadius:6,marginTop:8},PF={display:"flex",justifyContent:"flex-end",gap:8,marginTop:12},k0={background:"transparent",border:"1px solid var(--border-secondary, #3a3a5e)",borderRadius:6,padding:"6px 12px",cursor:"pointer",font:"inherit",color:"inherit"};function BF({id:e,content:t,onClose:n,onRemove:i}){let o=1;for(let h=0;h<t.length;h++)t.charCodeAt(h)===10&&o++;const d=`Pasted text #${e} · ${o} ${o===1?"line":"lines"} · ${t.length} chars`;return r.jsxs(Vc,{open:!0,onClose:n,title:d,maxWidth:"720px",children:[r.jsx("div",{style:OF,"data-testid":"pasted-text-modal-body",children:t}),r.jsxs("div",{style:PF,children:[r.jsx("button",{type:"button",style:k0,"data-testid":"pasted-text-modal-remove",onClick:()=>{i(e),n()},children:"Remove paste"}),r.jsx("button",{type:"button",style:k0,"data-testid":"pasted-text-modal-close",onClick:n,children:"Close"})]})]})}function C0(e){return e==="not_configured"?"No Discord webhook is configured on the host.":e==="post_failed"?"Discord rejected the post — check the webhook.":e==="no_token"||e==="unauthorized"?"Not authorized — reconnect to the daemon and try again.":e==="primary_token_required"?"Only the primary device can post pairing links.":`Could not post to Discord${e?`: ${e}`:""}.`}function $F({open:e,onClose:t,qrSvg:n,loading:i,error:o,title:d="Pair Mobile App",instructions:h="Scan with Chroxy app to pair your phone",pairingCode:l=null,onPostToDiscord:u}){const[f,v]=N.useState(!1),[g,S]=N.useState(null),w=async()=>{if(!(!u||f)){v(!0),S(null);try{const E=await u();if(E.posted){const x=typeof E.expiresInSeconds=="number"?E.expiresInSeconds:60;S({ok:!0,text:`Posted to Discord — expires in ${x}s, approval required on the host.`})}else S({ok:!1,text:C0(E.reason)})}catch{S({ok:!1,text:C0()})}finally{v(!1)}}};return r.jsxs(Vc,{open:e,onClose:t,title:d,maxWidth:"400px",children:[r.jsx("button",{className:"qr-modal-close",onClick:t,"aria-label":"Close",type:"button",children:"×"}),i&&r.jsxs("div",{className:"qr-modal-loading","data-testid":"qr-loading",children:[r.jsx("div",{className:"qr-spinner"}),r.jsx("span",{children:"Loading QR code..."})]}),o&&!i&&r.jsx("div",{className:"qr-modal-error",children:o}),n&&!i&&r.jsxs("div",{className:"qr-modal-content",children:[r.jsx("div",{className:"qr-svg-container","data-testid":"qr-svg-container",dangerouslySetInnerHTML:{__html:_f.sanitize(n,{USE_PROFILES:{svg:!0}})}}),r.jsx("p",{className:"qr-modal-instructions",children:h}),l&&r.jsxs("div",{className:"qr-modal-code","data-testid":"qr-pairing-code",children:[r.jsx("span",{className:"qr-modal-code-label",children:"Or type this code:"}),r.jsx("code",{className:"qr-modal-code-value","data-testid":"qr-pairing-code-value",children:l})]}),u&&r.jsxs("div",{className:"qr-modal-discord","data-testid":"qr-post-discord",children:[r.jsx("button",{type:"button",className:"qr-modal-discord-btn","data-testid":"qr-post-discord-btn",onClick:w,disabled:f,children:f?"Posting…":"Post link to Discord"}),g&&r.jsx("span",{className:g.ok?"qr-modal-discord-ok":"qr-modal-discord-err","data-testid":"qr-post-discord-status",role:g.ok?void 0:"alert",children:g.text})]})]})]})}function zF(e){if(!e)return"";const t=Date.parse(e);if(!Number.isFinite(t))return e;const n=new Date(t),i=new Date;return n.getFullYear()===i.getFullYear()&&n.getMonth()===i.getMonth()&&n.getDate()===i.getDate()?n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function E0({name:e,description:t}){return t?.trim()?r.jsx("span",{className:"skill-desc","data-testid":`skill-desc-${e}`,children:t}):null}function N0({skill:e}){const t=[];return e.source&&t.push({label:"source",value:e.source,testid:`skill-meta-source-${e.name}`}),e.version&&t.push({label:"version",value:e.version,testid:`skill-meta-version-${e.name}`}),e.lastVerified&&t.push({label:"last seen",value:zF(e.lastVerified),testid:`skill-meta-last-verified-${e.name}`}),e.hashPrefix&&t.push({label:"hash",value:e.hashPrefix,testid:`skill-meta-hash-${e.name}`}),t.length===0?null:r.jsx("span",{className:"skill-meta",children:t.map((n,i)=>r.jsxs("span",{className:"skill-meta-field","data-testid":n.testid,children:[i>0&&r.jsx("span",{className:"skill-meta-sep","aria-hidden":!0,children:" · "}),r.jsxs("span",{className:"skill-meta-label",children:[n.label,":"]})," ",r.jsx("span",{className:"skill-meta-value",children:n.value})]},n.label))})}function UF({skills:e,canToggle:t=!1,mismatchedSkillNames:n,onActivate:i,onDeactivate:o,onAcceptTrust:d,pendingCommunitySkills:h,onGrantTrust:l,capabilities:u,pendingTrustGrants:f,onClose:v}){const g=(e||[]).filter(y=>y.activation!=="manual"),S=(e||[]).filter(y=>y.activation==="manual"),w=!!u?.skillTrustGrant&&!!l&&Array.isArray(h)&&h.length>0,E=n||new Set;function x({name:y}){return E.has(y)?r.jsx("span",{className:"skill-mismatch-flag","data-testid":`skill-mismatch-${y}`,title:"Skill content changed since last verified — review before activating",role:"img","aria-label":"Hash mismatch: skill content changed since last verified",children:"⚠️"}):null}function m({name:y}){return!d||!E.has(y)?null:r.jsx("button",{type:"button",className:"skill-accept-trust","data-testid":`skill-accept-trust-${y}`,onClick:()=>d(y),title:"Accept the current content as the new trusted version","aria-label":`Accept new content for skill ${y}`,children:"Accept"})}return r.jsxs("div",{className:"skills-panel","data-testid":"skills-panel",role:"dialog","aria-label":"Skills",children:[r.jsxs("div",{className:"skills-panel-header",children:[r.jsx("h3",{children:"Skills"}),r.jsx("button",{type:"button",className:"skills-panel-close",onClick:v,"aria-label":"Close skills panel","data-testid":"skills-panel-close",children:"×"})]}),(!e||e.length===0)&&!w&&r.jsx("p",{className:"skills-panel-empty","data-testid":"skills-panel-empty",children:"No skills loaded for this session."}),w&&r.jsxs("section",{"data-testid":"skills-panel-pending-section",children:[r.jsx("h4",{children:"Pending review"}),r.jsx("ul",{className:"skills-panel-list",children:h.map(({name:y,author:b,description:_,path:k})=>{const j=Array.isArray(f)&&f.some(T=>T.skillName===y&&T.author===b);return r.jsxs("li",{"data-testid":`skill-pending-${b}/${y}`,children:[r.jsxs("div",{className:"skill-row",children:[r.jsx("span",{className:"skill-name",children:y}),r.jsxs("span",{className:"skill-desc",children:["from: ",b]}),r.jsxs("button",{type:"button",className:"skill-accept-trust","data-testid":`skill-grant-trust-${b}/${y}`,onClick:()=>l(y,b),disabled:j,"aria-busy":j,title:j?`Granting trust to '${b}'…`:`Grant first-activation trust to community author '${b}'`,"aria-label":`Trust author ${b} for skill ${y}`,children:[j&&r.jsx("span",{className:"skill-trust-spinner","data-testid":`skill-grant-trust-spinner-${b}/${y}`,"aria-hidden":!0,children:"⏳"}),j?"Granting…":r.jsxs(r.Fragment,{children:["Trust '",b,"'"]})]})]}),_?.trim()&&r.jsx("span",{className:"skill-desc skill-pending-description","data-testid":`skill-pending-description-${b}/${y}`,children:_}),k?.trim()&&r.jsx("span",{className:"skill-meta skill-pending-path","data-testid":`skill-pending-path-${b}/${y}`,title:k,children:k})]},`${b}/${y}`)})})]}),g.length>0&&r.jsxs("section",{children:[r.jsx("h4",{children:"Always on"}),r.jsx("ul",{className:"skills-panel-list",children:g.map(y=>r.jsxs("li",{"data-testid":`skill-item-${y.name}`,children:[r.jsxs("div",{className:"skill-row",children:[r.jsx("span",{className:"skill-name",children:y.name}),r.jsx(E0,{name:y.name,description:y.description}),r.jsx(x,{name:y.name}),r.jsx(m,{name:y.name})]}),r.jsx(N0,{skill:y})]},y.name))})]}),S.length>0&&r.jsxs("section",{children:[r.jsx("h4",{children:"Manual (toggle on/off)"}),!t&&r.jsx("p",{className:"skills-panel-note","data-testid":"skills-panel-no-toggle-note",children:"Runtime toggle is not supported by this provider. Restart the session with the desired skills to change which manual skills are active."}),r.jsx("ul",{className:"skills-panel-list",children:S.map(y=>r.jsxs("li",{"data-testid":`skill-item-${y.name}`,children:[r.jsxs("div",{className:"skill-row",children:[r.jsxs("label",{children:[r.jsx("input",{type:"checkbox",checked:!!y.active,disabled:!t,onChange:b=>{b.target.checked?i(y.name):o(y.name)},"data-testid":`skill-toggle-${y.name}`}),r.jsx("span",{className:"skill-name",children:y.name}),r.jsx(E0,{name:y.name,description:y.description})]}),r.jsx(x,{name:y.name}),r.jsx(m,{name:y.name})]}),r.jsx(N0,{skill:y})]},y.name))})]})]})}function qF({x:e,y:t,items:n,onDismiss:i}){const o=N.useRef(null),d=N.useRef([]),[h,l]=N.useState(0),u=n.filter(E=>typeof E.onClick=="function"),f=200,v=Math.max(32,u.length*32+8),g=Math.min(e,Math.max(0,window.innerWidth-f)),S=Math.min(t,Math.max(0,window.innerHeight-v));if(N.useEffect(()=>{const E=o.current;if(E){const x=E.getBoundingClientRect(),m=x.right-window.innerWidth,y=x.bottom-window.innerHeight;m>0&&(E.style.left=`${Math.max(0,e-x.width)}px`),y>0&&(E.style.top=`${Math.max(0,t-x.height)}px`)}},[e,t]),N.useEffect(()=>{const E=b=>{o.current&&!o.current.contains(b.target)&&i()},x=b=>{b.key==="Escape"&&(b.stopPropagation(),i())},m=()=>i(),y=()=>i();return document.addEventListener("mousedown",E,!0),document.addEventListener("keydown",x),window.addEventListener("blur",m),window.addEventListener("scroll",y,!0),()=>{document.removeEventListener("mousedown",E,!0),document.removeEventListener("keydown",x),window.removeEventListener("blur",m),window.removeEventListener("scroll",y,!0)}},[i]),N.useEffect(()=>{const E=document.activeElement,x=d.current[0];return x&&x.focus(),()=>{E&&E.isConnected&&E.focus()}},[]),N.useEffect(()=>{const E=d.current[h];E&&document.activeElement!==E&&E.focus()},[h]),u.length===0)return null;const w=E=>{try{E.onClick?.()}finally{i()}};return r.jsx("ul",{ref:o,className:"session-context-menu","data-testid":"session-context-menu",role:"menu","aria-orientation":"vertical",style:{position:"fixed",left:g,top:S,zIndex:1e3},children:u.map((E,x)=>r.jsx("li",{ref:m=>{d.current[x]=m},role:"menuitem",tabIndex:h===x?0:-1,"data-testid":`session-context-menu-item-${E.id}`,className:`session-context-menu-item${E.destructive?" destructive":""}${E.separatorAbove?" separator-above":""}`,onClick:()=>w(E),onKeyDown:m=>{switch(m.key){case"ArrowDown":{m.preventDefault(),m.stopPropagation(),l(y=>(y+1)%u.length);break}case"ArrowUp":{m.preventDefault(),m.stopPropagation(),l(y=>(y-1+u.length)%u.length);break}case"Home":{m.preventDefault(),m.stopPropagation(),l(0);break}case"End":{m.preventDefault(),m.stopPropagation(),l(u.length-1);break}case"Enter":case" ":{m.preventDefault(),m.stopPropagation(),w(E);break}}},children:E.label},E.id))})}var HF=L0();function j0(e){if(!e)return{parent:"",partial:""};const t=e.lastIndexOf("/"),n=e.lastIndexOf("\\"),i=Math.max(t,n);if(i===-1)return{parent:"",partial:e};const o=e.slice(0,i),d=e.slice(i+1);return o?o.length===2&&o[1]===":"?{parent:o+"\\",partial:d}:{parent:o,partial:d}:{parent:e[i],partial:d}}const FF=200;function KF(e){const[t,n]=N.useState([]),i=V(f=>f.requestDirectoryListing),o=V(f=>f.setDirectoryListingCallback),d=N.useRef(null),h=N.useRef(""),l=N.useRef(e);l.current=e;const u=N.useCallback(f=>{if(f.error||!f.entries){n([]);return}const v=f.path||f.parentPath||"";if(v&&h.current&&v!==h.current)return;const{partial:g}=j0(l.current),S=v,w=f.entries.filter(E=>E.isDirectory).filter(E=>!g||E.name.toLowerCase().startsWith(g.toLowerCase())).map(E=>{const x=S.endsWith("/")||S.endsWith("\\")?"":"/";return`${S}${x}${E.name}`});n(w)},[]);return N.useEffect(()=>{if(!e||e.length<2){n([]),o(null);return}const{parent:f}=j0(e);if(!f){n([]),o(null);return}const g=e.endsWith("/")||e.endsWith("\\")?e.replace(/[/\\]+$/,""):f;return d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{h.current=g,o(u),i(g)},FF),()=>{d.current&&clearTimeout(d.current)}},[e,u,i,o]),N.useEffect(()=>()=>o(null),[o]),{suggestions:t}}function WF(e){const t=e.split("/").filter(Boolean),n=[{label:"/",path:"/"}];for(let i=0;i<t.length;i++)n.push({label:t[i],path:"/"+t.slice(0,i+1).join("/")});return n}function GF({entries:e,currentPath:t,loading:n,error:i,onNavigate:o,onSelect:d,onCancel:h}){const l=WF(t),u=e.filter(f=>f.isDirectory);return r.jsxs("div",{className:"directory-browser",children:[r.jsx("nav",{className:"directory-browser-breadcrumb",role:"navigation","aria-label":"Breadcrumb",children:l.map((f,v)=>r.jsxs("span",{children:[v>1&&r.jsx("span",{className:"directory-browser-sep",children:"/"}),v<l.length-1?r.jsx("button",{type:"button",className:"directory-browser-crumb",onClick:()=>o(f.path),children:f.label}):r.jsx("span",{className:"directory-browser-crumb directory-browser-crumb--current","aria-current":"location",children:f.label})]},f.path))}),r.jsxs("div",{className:"directory-browser-list-container",children:[n&&r.jsx("div",{className:"directory-browser-loading",children:"Loading..."}),!n&&i&&r.jsx("div",{className:"directory-browser-error",role:"alert",children:i}),!n&&!i&&u.length===0&&r.jsx("div",{className:"directory-browser-empty",children:"No subdirectories"}),!n&&u.length>0&&r.jsx("ul",{className:"directory-browser-list",role:"list",children:u.map(f=>r.jsx("li",{children:r.jsxs("button",{type:"button",className:"directory-browser-entry",onClick:()=>o(t.endsWith("/")?`${t}${f.name}`:`${t}/${f.name}`),children:[r.jsx("span",{className:"directory-browser-icon","aria-hidden":"true",children:"📁"}),f.name]})},f.name))})]}),r.jsxs("div",{className:"directory-browser-actions",children:[r.jsx("button",{type:"button",className:"btn-modal-cancel","aria-label":"Cancel",onClick:h,children:"Cancel"}),r.jsx("button",{type:"button",className:"btn-modal-create","aria-label":"Select",onClick:()=>d(t),children:"Select"})]})]})}function xk(e){return e.replace(/[/\\]+$/,"").split(/[/\\]/).pop()||e}function A0(e){return!e||e==="/"?e:e.replace(/\/+$/,"")}function VF(e,t){return!!(!t||A0(t)===A0(e)||e.startsWith("~"))}function Ld(e,t){const n=xk(e)||"Session";if(!t.includes(n))return n;let i=2;for(;t.includes(`${n} (${i})`);)i++;return`${n} (${i})`}const R0=[],YF=[],ZF=Date.UTC(2026,5,15);function XF(e=Date.now()){return e>=ZF}function QF(e,t=Date.now()){const n=XF(t);return{"claude-sdk":n?"Programmatic credit pool — monthly metered credits":"Uses your Claude subscription","claude-cli":n?"Programmatic credit pool — monthly metered credits":"Uses your Claude subscription","claude-tui":"Uses your Claude subscription (interactive TUI — bypasses programmatic credit metering)","claude-byok":"Direct Anthropic API — per-token billing with your own ANTHROPIC_API_KEY. No claude binary required.","docker-cli":"Docker-isolated — Anthropic API (your ANTHROPIC_API_KEY forwarded to the container)","docker-sdk":"Docker-isolated — Anthropic API (your ANTHROPIC_API_KEY forwarded to the container)","docker-byok":"Direct Anthropic API (your ANTHROPIC_API_KEY) — tool execution sandboxed in a Docker container. Same billing as claude-byok, isolated filesystem.",codex:"Uses OpenAI API credits",gemini:"Uses Google API credits"}[e]}const JF=[["containerized","Containerized"],["resume","Resume"],["planMode","Plan"],["permissions","Permissions"],["terminal","Terminal"]];function T0(e){if(!e)return[];const t=[];let n=0;for(;n<e.length;){const i=e.indexOf("`",n);if(i===-1){t.push(e.slice(n));break}i>n&&t.push(e.slice(n,i));const o=e.indexOf("`",i+1);if(o===-1){t.push(e.slice(i));break}t.push({code:e.slice(i+1,o)}),n=o+1}return t}function eK(e,t,n,i){const o=typeof t=="string"?t.trim():"";if(o&&i===e)return n.some(d=>d.id===o||d.fullId===o)?o:void 0}function tK({open:e,onClose:t,onCreate:n,initialCwd:i,knownCwds:o=R0,existingNames:d=R0,serverError:h,isCreating:l}){const u=V(je=>je.defaultProvider),f=V(je=>je.defaultModel),v=V(je=>je.availableModels)||YF,g=V(je=>je.availableModelsProvider),S=V(je=>je.availableProviders),w=V(je=>je.availablePermissionModes),[E,x]=N.useState(""),[m,y]=N.useState(!1),[b,_]=N.useState(""),[k,j]=N.useState(u),[T,D]=N.useState(""),[I,L]=N.useState(!1),[q,H]=N.useState(""),[Q,F]=N.useState(!1),[J,ie]=N.useState("inherit"),[X,de]=N.useState(""),fe=V(je=>je.environments),[$,P]=N.useState(!1),[B,K]=N.useState(-1),le=N.useRef(null),me=N.useId(),[be,Ee]=N.useState(!1),[se,Z]=N.useState(""),[ge,De]=N.useState([]),[Ge,Ve]=N.useState(!1),[St,Nt]=N.useState(null),kt=V(je=>je.requestDirectoryListing),Tt=V(je=>je.setDirectoryListingCallback),at=V(je=>je.defaultCwd),en=V(je=>je.requestSessionPreset),cn=V(je=>je.sessionPresetSnapshots),[Bt,hn]=N.useState(!1),sn=typeof en=="function"?en:void 0,Ct=N.useRef(""),Ut=N.useRef(""),{suggestions:$t}=KF(b),Lt=N.useMemo(()=>{const je=o.filter(xt=>!b||xt.toLowerCase().includes(b.toLowerCase()));return[...new Set([...$t,...je])].sort()},[o,$t,b]),Ht=b.trim();N.useEffect(()=>{if(!e||!Ht||!sn)return;const je=setTimeout(()=>{sn(Ht)},400);return()=>clearTimeout(je)},[e,Ht,sn]);const zt=Ht?cn?.[Ht]:void 0;N.useEffect(()=>{hn(!1)},[Ht]);const rn=N.useRef(!1);N.useEffect(()=>{const je=e&&!rn.current;if(rn.current=e,!je)return;const mt=i||"";if(_(mt),Ut.current=mt,y(!1),D(""),S.length>0&&!S.some(xt=>xt.name===u)?j(S[0].name):j(u),L(!1),H(""),F(!1),ie("inherit"),P(!1),K(-1),Ee(!1),De([]),Tt(null),mt){const xt=Ld(mt,d);x(xt),Ct.current=xt}else x(""),Ct.current=""},[e,i,d,S,u]),N.useEffect(()=>{!e||S.length===0||S.some(je=>je.name===k)||j(S[0].name)},[e,S,k]),N.useEffect(()=>{ie("inherit")},[k]);const ze=S.find(je=>je.name===k),Je=ze?.auth?.ready===!1,tt=N.useCallback(()=>{const je=Ct.current.trim();if(!je){HF.flushSync(()=>D("Session name is required"));return}if(Je)return;const mt=eK(k,f,v,g),xt=k==="claude-tui"?J==="on"?!0:J==="off"?!1:void 0:void 0;n({name:je,cwd:Ut.current.trim(),provider:k,permissionMode:q||void 0,model:mt,worktree:Q||void 0,environmentId:X||void 0,skipPermissions:xt})},[n,k,q,f,v,g,Q,X,J,Je]),Pt=N.useCallback(je=>{if(_(je),Ut.current=je,P(!1),K(-1),!m){const mt=Ld(je,d);x(mt),Ct.current=mt}},[m,d]),Vt=N.useCallback(je=>{Z(je),Ve(!0),De([]),Nt(null);const mt=je;Tt(xt=>{const Mt=xt.path||xt.parentPath||"";VF(mt,Mt)&&(Mt&&Mt!==mt&&Z(Mt),Ve(!1),xt.error?(Nt(xt.error),De([])):xt.entries?(Nt(null),De(xt.entries)):De([]))}),kt(je)},[kt,Tt]),Wt=N.useCallback(async()=>{const je=typeof window<"u"?window.__TAURI_INTERNALS__:void 0;if(je)try{const xt=await je.invoke("pick_directory",{defaultPath:b||i||at||void 0});if(xt&&(_(xt),Ut.current=xt,!m)){const Mt=Ld(xt,d);x(Mt),Ct.current=Mt}return}catch{}const mt=b||i||at||"/";Ee(!0),Vt(mt)},[b,i,at,Vt,m,d]),Zt=N.useCallback(je=>{if(_(je),Ut.current=je,Ee(!1),Tt(null),!m){const mt=Ld(je,d);x(mt),Ct.current=mt}},[m,d,Tt]),Dn=N.useCallback(()=>{Ee(!1),Tt(null)},[Tt]),wn=N.useCallback(je=>{if(je.key==="Tab"&&$&&Lt.length>0){je.preventDefault();const mt=B>=0?B:0,xt=Lt[mt],Mt=xt.endsWith("/")?xt:xt+"/";Pt(Mt);return}if($&&Lt.length>0){if(je.key==="ArrowDown"){je.preventDefault(),K(mt=>Math.min(mt+1,Lt.length-1));return}if(je.key==="ArrowUp"){je.preventDefault(),K(mt=>Math.max(mt-1,-1));return}if(je.key==="Enter"&&B>=0){je.preventDefault(),Pt(Lt[B]);return}if(je.key==="Escape"){je.preventDefault(),P(!1);return}}je.key==="Enter"&&(je.preventDefault(),tt())},[$,Lt,B,Pt,tt]),Kn=N.useCallback(je=>{je.key==="Enter"&&(je.preventDefault(),tt())},[tt]);return r.jsxs(Vc,{open:e,onClose:t,title:"New Session",closeOnBackdrop:!1,children:[r.jsx("input",{type:"text",placeholder:"Session name","aria-label":"Session name",value:E,onChange:je=>{const mt=je.target.value;x(mt),Ct.current=mt,y(!0),D("")},onKeyDown:Kn,autoComplete:"off","aria-invalid":T?!0:void 0,"aria-describedby":T?"session-name-error":void 0}),T&&r.jsx("span",{id:"session-name-error",className:"form-error",role:"alert",children:T}),be?r.jsx(GF,{entries:ge,currentPath:se,loading:Ge,error:St,onNavigate:Vt,onSelect:Zt,onCancel:Dn}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"cwd-input-row",children:[r.jsxs("div",{className:"cwd-combobox",children:[r.jsx("input",{ref:le,type:"text",placeholder:"Working directory (optional)","aria-label":"Working directory",value:b,onChange:je=>{const mt=je.target.value;_(mt),Ut.current=mt,P(!0),K(-1)},onFocus:()=>P(!0),onBlur:()=>{setTimeout(()=>P(!1),150)},onKeyDown:wn,autoComplete:"off",role:"combobox","aria-expanded":$&&Lt.length>0,"aria-controls":me,"aria-autocomplete":"list","aria-activedescendant":$&&B>=0?`${me}-opt-${B}`:void 0}),Lt.length>0&&r.jsx("button",{type:"button",className:"cwd-dropdown-toggle",tabIndex:-1,"aria-label":"Show directory suggestions",onClick:()=>{P(!$),le.current?.focus()},children:r.jsx("span",{className:"cwd-dropdown-arrow"})}),$&&Lt.length>0&&r.jsx("ul",{id:me,className:"cwd-suggestions",role:"listbox",children:Lt.map((je,mt)=>{const xt=xk(je);return r.jsxs("li",{id:`${me}-opt-${mt}`,role:"option","aria-selected":mt===B,className:`cwd-suggestion${mt===B?" selected":""}`,onMouseDown:Mt=>{Mt.preventDefault(),Pt(je)},children:[r.jsx("span",{className:"cwd-suggestion-name",children:xt}),r.jsx("span",{className:"cwd-suggestion-path",children:je})]},je)})})]}),r.jsx("button",{type:"button",className:"cwd-browse-btn",onClick:Wt,"aria-label":"Browse directories",children:"Browse..."})]}),b&&!Lt.includes(b)&&r.jsx("span",{className:"cwd-hint",children:"New directory — session will start here"}),zt&&r.jsxs("div",{className:"repo-preset-disclosure","data-testid":"repo-preset-disclosure",children:[r.jsx("button",{type:"button",className:"repo-preset-summary","data-testid":"repo-preset-summary",onClick:()=>hn(je=>!je),"aria-expanded":Bt,children:zt.trustState==="pending"?r.jsx("span",{children:"Repo preset pending review — approve it in the repo drawer to apply"}):zt.active?r.jsxs("span",{children:["Repo preset applies: preamble ",zt.preambleLength," chars",zt.seedLength>0?` · seed ${zt.seedLength} chars`:" · no seed",zt.capped?" · capped":""," — view"]}):r.jsx("span",{children:"Repo preset present but disabled"})}),Bt&&r.jsxs("div",{className:"repo-preset-detail","data-testid":"repo-preset-detail",children:[zt.preamble&&r.jsxs("div",{className:"repo-preset-field",children:[r.jsx("div",{className:"repo-preset-label",children:"Preamble (system prompt, every turn)"}),r.jsx("pre",{className:"repo-preset-text","data-testid":"repo-preset-preamble",children:zt.preamble})]}),zt.seed&&r.jsxs("div",{className:"repo-preset-field",children:[r.jsx("div",{className:"repo-preset-label",children:"Seed (staged editable into the composer)"}),r.jsx("pre",{className:"repo-preset-text","data-testid":"repo-preset-seed",children:zt.seed})]})]})]})]}),r.jsxs("div",{className:"provider-section",children:[r.jsxs("div",{className:"provider-select",children:[r.jsx("label",{htmlFor:"provider-select",children:"Provider"}),r.jsx("select",{id:"provider-select",value:k,onChange:je=>j(je.target.value),"aria-label":"Select provider",children:S.length>0?S.map(je=>{const mt=je.auth?.ready===!1,xt=hm[je.name]||je.name,Mt=mt?`${xt} (unavailable)`:xt,un=mt?je.auth?.detail||je.auth?.hint||"credentials missing":void 0;return r.jsx("option",{value:je.name,title:un,children:Mt},je.name)}):r.jsxs(r.Fragment,{children:[r.jsx("option",{value:"claude-sdk",children:"Claude Code (SDK)"}),r.jsx("option",{value:"claude-cli",children:"Claude Code (CLI)"})]})}),Je?null:(()=>{const je=S.find(xt=>xt.name===k)?.auth,mt=je?.detail||QF(k);return mt?r.jsx("span",{className:"provider-billing-hint","data-testid":"provider-billing-hint","data-source":je?.source??"static",children:mt}):null})()]}),Je&&(()=>{const je=S.find(Mt=>Mt.name===k)?.auth,mt=je?.hint||"credentials missing",xt=je?.detail;return r.jsxs("div",{className:"provider-fix-hint","data-testid":"provider-fix-hint",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"provider-fix-hint-label",children:"How to enable:"})," ",r.jsx("span",{className:"provider-fix-hint-body",children:T0(mt).map((Mt,un)=>typeof Mt=="string"?r.jsx("span",{children:Mt},un):r.jsx("code",{children:Mt.code},un))}),xt&&xt!==mt&&r.jsx("span",{className:"provider-fix-hint-detail",children:T0(xt).map((Mt,un)=>typeof Mt=="string"?r.jsx("span",{children:Mt},un):r.jsx("code",{children:Mt.code},un))})]})})(),S.length>0&&(()=>{const je=S.find(xt=>xt.name===k);if(!je?.capabilities)return null;const mt=JF.filter(([xt])=>je.capabilities[xt]);return mt.length===0?null:r.jsx("div",{className:"provider-capabilities","data-testid":"provider-capabilities",children:mt.map(([xt,Mt])=>r.jsx("span",{className:"capability-badge","data-capability":xt,children:Mt},Mt))})})(),S.length>0&&(()=>{const je=S.find(xt=>xt.name===k),mt=iE(je?.capabilities);return mt?r.jsx("div",{className:"provider-limitation-note","data-testid":"provider-limitation-note",children:mt}):null})(),S.length>0&&ze?.capabilities?.containerized&&!Je&&!X&&r.jsxs("div",{className:"provider-container-hint","data-testid":"provider-container-hint",role:"note",children:[r.jsx("span",{className:"provider-container-hint-label",children:"Container settings:"})," ",r.jsx("span",{className:"provider-container-hint-body",children:fe.length>0?"Pick an Environment in Advanced to use its image / memory / CPU. Otherwise the provider defaults apply (node:22-slim, 2g RAM, 2 CPUs).":"Uses the provider defaults (node:22-slim, 2g RAM, 2 CPUs). Open the Environments panel to create one with a custom image / memory / CPU / container user."})]})]}),r.jsx("div",{className:"advanced-toggle",children:r.jsxs("button",{type:"button",className:"advanced-toggle-btn",onClick:()=>L(!I),"aria-expanded":I,children:[I?"▼":"▶"," Advanced"]})}),I&&r.jsxs("div",{className:"advanced-section","data-testid":"advanced-section",children:[r.jsxs("div",{className:"form-field",children:[r.jsx("label",{htmlFor:"permission-mode-select",children:"Permission mode"}),r.jsxs("select",{id:"permission-mode-select",value:q,onChange:je=>H(je.target.value),"aria-label":"Permission mode","aria-describedby":"permission-mode-hint",children:[r.jsx("option",{value:"",children:"Server default"}),(w.length>0?w:[{id:"approve",label:"Approve"},{id:"acceptEdits",label:"Accept Edits"},{id:"auto",label:"Auto (skip all prompts)"},{id:"plan",label:"Plan"}]).map(je=>r.jsx("option",{value:je.id,children:je.label},je.id))]}),r.jsx("span",{id:"permission-mode-hint",className:"form-hint",children:(()=>{const je=w.find(mt=>mt.id===q);return je?.description?je.description:q==="auto"?"Equivalent to `claude --dangerously-skip-permissions`. Every tool call auto-approves with no prompt.":q==="acceptEdits"?"Read/Write/Edit/Grep/Glob/NotebookEdit auto-approve. Bash, MCP, and other tools still gate on approval.":q==="plan"?"Claude is asked to plan before acting; each tool call still gates on your approval.":q==="approve"?"Default. Each tool call gates on your approval in the dashboard or mobile app.":"Uses whatever the server’s --default-permission-mode was set to (usually Approve)."})()})]}),r.jsxs("div",{className:"form-field form-field--checkbox",children:[r.jsxs("label",{className:"checkbox-label",children:[r.jsx("input",{type:"checkbox",id:"worktree-checkbox",checked:Q,onChange:je=>F(je.target.checked),disabled:!Ut.current.trim(),"aria-describedby":"worktree-hint"}),r.jsx("span",{className:"label-text",children:"Isolate filesystem (worktree)"})]}),r.jsx("span",{id:"worktree-hint",className:"form-hint",children:Q?"CWD must point to an existing git repository":"Runs in an isolated git worktree — requires a git repo CWD"})]}),k==="claude-tui"&&r.jsxs("div",{className:"form-field","data-testid":"skip-permissions-field",role:"radiogroup","aria-labelledby":"skip-permissions-legend","aria-describedby":"skip-permissions-hint",children:[r.jsx("span",{id:"skip-permissions-legend",className:"form-field-label",children:"Permission prompts"}),r.jsxs("label",{className:"radio-label",children:[r.jsx("input",{type:"radio",name:"skip-permissions","data-testid":"skip-permissions-radio-inherit",value:"inherit",checked:J==="inherit",onChange:()=>ie("inherit")}),r.jsx("span",{className:"label-text",children:"Use server default"})]}),r.jsxs("label",{className:"radio-label",children:[r.jsx("input",{type:"radio",name:"skip-permissions","data-testid":"skip-permissions-radio-off",value:"off",checked:J==="off",onChange:()=>ie("off")}),r.jsx("span",{className:"label-text",children:"Require permission prompts (override server default)"})]}),r.jsxs("label",{className:"radio-label",children:[r.jsx("input",{type:"radio",name:"skip-permissions","data-testid":"skip-permissions-radio-on",value:"on",checked:J==="on",onChange:()=>ie("on")}),r.jsx("span",{className:"label-text",children:"Skip permission prompts (dangerous)"})]}),r.jsxs("span",{id:"skip-permissions-hint",className:"form-hint form-hint--warning",children:["“Skip” spawns the claude TUI with ",r.jsx("code",{children:"--dangerously-skip-permissions"})," and disables chroxy’s tool-call gate entirely. Every tool runs with no prompt and no audit trail. Use only in trusted contexts (e.g. isolated workspace, throwaway worktree, or container)."]})]}),fe.length>0&&r.jsxs("div",{className:"form-field",children:[r.jsx("label",{htmlFor:"env-select",children:"Environment"}),r.jsxs("select",{id:"env-select",value:X,onChange:je=>de(je.target.value),"aria-describedby":"env-hint",children:[r.jsx("option",{value:"",children:"None (ephemeral container)"}),fe.filter(je=>je.status==="running").map(je=>r.jsxs("option",{value:je.id,children:[je.name," (",je.image,")"]},je.id))]}),r.jsx("span",{id:"env-hint",className:"form-hint",children:"Connect to a persistent environment container"})]})]}),h&&r.jsx("span",{className:"form-error",role:"alert",children:h}),r.jsxs("div",{className:"modal-buttons",children:[r.jsx("button",{className:"btn-modal-cancel",onClick:t,type:"button",children:"Cancel"}),r.jsx("button",{className:"btn-modal-create",onClick:tt,type:"button",disabled:l||Je,title:Je?"Selected provider is not configured — see fix-hint above":void 0,children:l?"Creating...":"Create"})]})]})}function nK({repoPath:e,repoName:t,onClose:n}){const i=V(j=>j.requestSessionPreset),o=V(j=>j.setSessionPresetOverride),d=V(j=>j.approveSessionPreset),h=V(j=>j.revokeSessionPreset),l=V(j=>j.sessionPresetSnapshots[e]),[u,f]=N.useState(""),[v,g]=N.useState(""),[S,w]=N.useState(!0),[E,x]=N.useState(null);N.useEffect(()=>{e&&i(e)},[e,i]),N.useEffect(()=>{E!==e&&l!==void 0&&(f(l?.preamble??""),g(l?.seed??""),w(l?l.enabled:!0),x(e))},[l,e,E]);const m=l?.trustState??null,y=l?.source??null,b=y==="repo"&&m==="pending",_=()=>{const j=u.trim(),T=v.trim();!j&&!T?o(e,null):o(e,{preamble:j,seed:T,enabled:S}),x(null)},k=()=>{o(e,null),f(""),g(""),w(!0),x(null)};return r.jsxs("div",{className:"repo-preset-drawer","data-testid":"repo-preset-drawer",role:"dialog","aria-label":`Per-repo settings for ${t}`,children:[r.jsxs("div",{className:"repo-preset-drawer-header",children:[r.jsxs("div",{children:[r.jsx("h3",{className:"repo-preset-drawer-title",children:t}),r.jsx("div",{className:"repo-preset-drawer-path",children:e})]}),r.jsx("button",{type:"button",className:"repo-preset-drawer-close","data-testid":"repo-preset-drawer-close",onClick:n,"aria-label":"Close per-repo settings",children:"✕"})]}),r.jsxs("section",{className:"repo-preset-section",children:[r.jsx("h4",{children:"Session preset"}),l&&r.jsxs("div",{className:"repo-preset-trust","data-testid":"repo-preset-trust",children:[r.jsxs("span",{children:["Source: ",r.jsx("strong",{children:y==="daemon"?"daemon config":"repo file"})," · Trust:"," ",r.jsx("strong",{"data-testid":"repo-preset-trust-state",children:m??"none"}),l.active?" · active":" · inactive"]}),b&&r.jsx("button",{type:"button",className:"repo-preset-approve","data-testid":"repo-preset-approve",onClick:()=>{d(e),x(null)},children:"Approve"}),y==="repo"&&m==="trusted"&&r.jsx("button",{type:"button",className:"repo-preset-revoke","data-testid":"repo-preset-revoke",onClick:()=>{h(e),x(null)},children:"Revoke"})]}),b&&r.jsx("p",{className:"repo-preset-pending-note","data-testid":"repo-preset-pending-note",children:"This repo ships a checked-in preset. It is inert until you approve its content — review it below, then click Approve."}),r.jsxs("label",{className:"repo-preset-toggle",children:[r.jsx("input",{type:"checkbox","data-testid":"repo-preset-enabled",checked:S,onChange:j=>w(j.target.checked)}),"Enabled"]}),r.jsx("label",{className:"repo-preset-field-label",htmlFor:"repo-preset-preamble-input",children:"Preamble — prepended to the system prompt every turn"}),r.jsx("textarea",{id:"repo-preset-preamble-input","data-testid":"repo-preset-preamble-input",className:"repo-preset-textarea",value:u,onChange:j=>f(j.target.value),rows:6,placeholder:"e.g. Use pnpm, not npm. Always read docs/ARCH.md first."}),r.jsx("label",{className:"repo-preset-field-label",htmlFor:"repo-preset-seed-input",children:"Seed — staged editable into the composer on session create (never auto-sent)"}),r.jsx("textarea",{id:"repo-preset-seed-input","data-testid":"repo-preset-seed-input",className:"repo-preset-textarea",value:v,onChange:j=>g(j.target.value),rows:4,placeholder:"e.g. Start by summarizing the open work in this repo."}),r.jsxs("div",{className:"repo-preset-actions",children:[r.jsx("button",{type:"button",className:"repo-preset-save","data-testid":"repo-preset-save",onClick:_,children:"Save override"}),r.jsx("button",{type:"button",className:"repo-preset-clear","data-testid":"repo-preset-clear",onClick:k,children:"Clear override"})]}),r.jsxs("p",{className:"repo-preset-note",children:["Saving writes a daemon-side override in ",r.jsx("code",{children:"~/.chroxy/config.json"})," (pre-trusted). It wins over a checked-in ",r.jsx("code",{children:".chroxy/session.json"}),"."]})]})]})}const sK=5e3;function iK({items:e,onDismiss:t}){const n=N.useRef(new Map),i=(l,u)=>{const f=setTimeout(()=>{t(l),n.current.delete(l)},u),v=n.current.get(l);n.current.set(l,{timer:f,remaining:u,startedAt:performance.now(),pauseReasons:v?.pauseReasons??new Set})},o=l=>{const u=n.current.get(l);u?.timer&&clearTimeout(u.timer),n.current.delete(l)},d=(l,u)=>{const f=n.current.get(l);if(!f||(f.pauseReasons.add(u),!f.timer))return;clearTimeout(f.timer);const v=performance.now()-f.startedAt,g=Math.max(0,f.remaining-v);n.current.set(l,{timer:null,remaining:g,startedAt:0,pauseReasons:f.pauseReasons})},h=(l,u)=>{const f=n.current.get(l);if(f&&(f.pauseReasons.delete(u),!f.timer&&!(f.pauseReasons.size>0))){if(f.remaining<=0){t(l),n.current.delete(l);return}i(l,f.remaining)}};return N.useEffect(()=>{e.forEach(u=>{if(u.actionDisabled===!0){const f=n.current.get(u.id);f&&(f.timer&&clearTimeout(f.timer),n.current.delete(u.id));return}n.current.has(u.id)||i(u.id,sK)});const l=new Set(e.map(u=>u.id));for(const[u,f]of n.current)l.has(u)||(f.timer&&clearTimeout(f.timer),n.current.delete(u))},[e,t]),N.useEffect(()=>()=>{for(const l of n.current.values())l.timer&&clearTimeout(l.timer)},[]),r.jsx("div",{className:"toast-container","data-testid":"toast-container",children:e.map(l=>r.jsxs("div",{className:`toast ${l.level==="info"?"toast-info":l.level==="warning"?"toast-warning":"toast-error"}`,role:l.level==="info"||l.level==="warning"?"status":"alert","aria-live":l.level==="info"||l.level==="warning"?"polite":"assertive","data-testid":`toast-${l.id}`,onMouseEnter:()=>d(l.id,"hover"),onMouseLeave:()=>h(l.id,"hover"),onFocus:u=>{u.currentTarget.contains(u.relatedTarget)||d(l.id,"focus")},onBlur:u=>{u.currentTarget.contains(u.relatedTarget)||h(l.id,"focus")},children:[r.jsxs("span",{className:"toast-msg",children:[l.message,l.subMessage?r.jsx("span",{className:"toast-submsg","data-testid":`toast-partial-cost-${l.id}`,children:l.subMessage}):null]}),l.action?r.jsx("button",{className:"toast-action","data-testid":`toast-action-${l.id}`,disabled:l.actionDisabled===!0,"aria-disabled":l.actionDisabled===!0?!0:void 0,onClick:()=>{if(l.actionDisabled!==!0){o(l.id);try{l.action.onClick()}catch(u){console.error("[toast] action handler threw:",u)}t(l.id)}},type:"button",children:l.actionDisabled===!0?l.actionDisabledLabel??l.action.label:l.action.label}):null,r.jsx("button",{className:"toast-close","data-testid":`toast-close-${l.id}`,"aria-label":"Close notification",onClick:()=>{o(l.id),t(l.id)},type:"button",children:"×"})]},l.id))})}function rK({commands:e,isOpen:t,onClose:n,mruList:i}){const[o,d]=N.useState(""),[h,l]=N.useState(0),u=N.useRef(null),f=N.useMemo(()=>{if(!o)return e;const E=o.toLowerCase();return e.filter(x=>x.name.toLowerCase().includes(E))},[e,o]),v=N.useMemo(()=>{const E=new Map;for(const x of f){const m=E.get(x.category)||[];m.push(x),E.set(x.category,m)}if(i&&i.length>0){const x=new Map(i.map((m,y)=>[m,y]));for(const[,m]of E)m.sort((y,b)=>{const _=x.get(y.id),k=x.get(b.id);return _!==void 0&&k!==void 0?_-k:_!==void 0?-1:k!==void 0?1:0})}return E},[f,i]),g=N.useMemo(()=>{const E=[];for(const[,x]of v)E.push(...x);return E},[v]);if(N.useEffect(()=>{t&&(d(""),l(0),requestAnimationFrame(()=>u.current?.focus()))},[t]),N.useEffect(()=>{l(0)},[o]),!t)return null;const S=E=>{E.action(),n()},w=E=>{switch(E.key){case"ArrowDown":E.preventDefault(),g.length>0&&l(x=>(x+1)%g.length);break;case"ArrowUp":E.preventDefault(),g.length>0&&l(x=>(x-1+g.length)%g.length);break;case"Enter":E.preventDefault(),g[h]&&S(g[h]);break;case"Escape":E.preventDefault(),n();break}};return r.jsxs("div",{className:"command-palette","data-testid":"command-palette",children:[r.jsx("div",{className:"command-palette-backdrop","data-testid":"command-palette-backdrop",onClick:n}),r.jsxs("div",{className:"command-palette-dialog",children:[r.jsx("input",{ref:u,className:"command-palette-search",role:"combobox","aria-expanded":!0,"aria-controls":"command-palette-list","aria-autocomplete":"list",placeholder:"Type a command...",value:o,onChange:E=>d(E.target.value),onKeyDown:w,autoFocus:!0}),r.jsxs("div",{id:"command-palette-list",role:"listbox",className:"command-palette-list",children:[g.length===0&&r.jsx("div",{className:"command-palette-empty",children:"No matching commands"}),Array.from(v.entries()).map(([E,x])=>r.jsxs("div",{className:"command-palette-group",children:[r.jsx("div",{className:"command-palette-category",children:E}),x.map(m=>{const y=g.indexOf(m);return r.jsxs("div",{role:"option","aria-selected":y===h,className:`command-palette-item${y===h?" selected":""}`,onClick:()=>S(m),children:[r.jsx("span",{className:"command-palette-item-name",children:m.name}),m.shortcut&&r.jsx("span",{className:"command-palette-item-shortcut",children:yr(m.shortcut)})]},m.id)})]},E))]})]})]})}function aK(e){const t=e.inspectedPastedTextId!=null?e.pastedTextBlocks.find(n=>n.id===e.inspectedPastedTextId):void 0;return r.jsxs(r.Fragment,{children:[r.jsx(NF,{isOpen:e.settingsOpen,onClose:e.onSettingsClose,showConsoleTab:e.showConsoleTab,onToggleConsoleTab:e.onToggleConsoleTab,interventionPingEnabled:e.interventionPingEnabled,onToggleInterventionPing:e.onToggleInterventionPing}),r.jsx(LF,{isOpen:e.shortcutHelpOpen,onClose:e.onShortcutHelpClose,shortcuts:e.shortcuts}),e.inspectedPastedTextId!=null&&t&&r.jsx(BF,{id:t.id,content:t.content,onClose:e.onPastedTextClose,onRemove:e.onRemovePastedText}),r.jsx($F,{open:e.qrModalOpen,onClose:e.onQrClose,qrSvg:e.qrSvg,loading:e.qrLoading,error:e.qrError??void 0,title:e.qrShareMode==="share"?"Share This Session":"Pair Mobile App",instructions:e.qrShareMode==="share"?"Scan to chat into this session only — the scanner cannot list, switch, or destroy other sessions.":"Scan with Chroxy app to pair your phone",pairingCode:e.qrShareMode==="share"?null:e.qrPairingCode,onPostToDiscord:e.qrShareMode==="share"?void 0:e.onPostPairLinkToDiscord}),e.skillsPanelOpen&&r.jsx(UF,{skills:e.skills,canToggle:e.skillsCanToggle,mismatchedSkillNames:e.mismatchedSkillNames,onActivate:e.onActivateSkill,onDeactivate:e.onDeactivateSkill,onAcceptTrust:e.onAcceptSkillTrust,pendingCommunitySkills:e.pendingCommunitySkills,onGrantTrust:e.onGrantSkillTrust,capabilities:e.skillsPanelCapabilities,pendingTrustGrants:e.pendingTrustGrants,onClose:e.onSkillsPanelClose}),e.sidebarContextMenu&&r.jsx(qF,{x:e.sidebarContextMenu.x,y:e.sidebarContextMenu.y,items:e.sidebarContextMenuItems,onDismiss:e.onDismissSidebarContextMenu}),r.jsx(tK,{open:e.showCreateSession,onClose:e.onCreateSessionClose,onCreate:e.onCreateSession,initialCwd:e.createSessionInitialCwd,knownCwds:e.knownCwds,existingNames:e.existingSessionNames,serverError:e.sessionCreateError,isCreating:e.isCreatingSession}),e.repoPresetDrawer&&r.jsx(nK,{repoPath:e.repoPresetDrawer.path,repoName:e.repoPresetDrawer.name,onClose:e.onRepoPresetDrawerClose}),r.jsx(Sf,{open:e.closeConfirmOpen,title:"Close session?",message:e.closeConfirmMessage,confirmLabel:"Close session",cancelLabel:"Cancel",danger:!0,onConfirm:e.onCloseConfirm,onCancel:e.onCloseConfirmCancel}),r.jsx(iK,{items:e.toastItems,onDismiss:e.onToastDismiss}),r.jsx(rK,{commands:e.commands,isOpen:e.paletteOpen,onClose:e.onPaletteClose,mruList:e.mruList})]})}function oK({open:e,onClose:t,availableModels:n,activeModel:i,defaultModelId:o,providerLabel:d,onSelect:h}){const[l,u]=N.useState(""),f=N.useRef(null);N.useEffect(()=>{e&&u("")},[e]);const v=N.useMemo(()=>n.find(m=>m.id===i||m.fullId===i)?.id??i??null,[n,i]),g=N.useMemo(()=>{const x=l.trim().toLowerCase();return x?n.filter(m=>m.label?.toLowerCase().includes(x)||m.id.toLowerCase().includes(x)||m.fullId?.toLowerCase().includes(x)):n},[n,l]),S=N.useCallback(x=>{h(x),t()},[h,t]),w=N.useCallback(x=>{if(x.key!=="ArrowDown"&&x.key!=="ArrowUp")return;x.preventDefault();const m=Array.from(f.current?.querySelectorAll('[role="option"]:not([disabled])')??[]);if(m.length===0)return;const y=m.findIndex(_=>_===document.activeElement),b=x.key==="ArrowDown"?(y+1)%m.length:(y-1+m.length)%m.length;m[b]?.focus()},[]),E=N.useCallback(x=>{if(x.key==="ArrowDown"){x.preventDefault(),f.current?.querySelector('[role="option"]:not([disabled])')?.focus();return}if(x.key==="Enter"){const m=g.filter(y=>y.disabled!==!0);m.length===1&&(x.preventDefault(),S(m[0].id))}},[g,S]);return r.jsx(Vc,{open:e,onClose:t,title:"Select model",maxWidth:"520px",closeOnBackdrop:!0,children:r.jsxs("div",{className:"model-picker","data-testid":"model-picker",children:[r.jsx("input",{type:"text",className:"model-picker-search",placeholder:"Search models…",value:l,onChange:x=>u(x.target.value),onKeyDown:E,"aria-label":"Search models","data-testid":"model-picker-search"}),r.jsxs("div",{ref:f,className:"model-picker-list",role:"listbox","aria-label":"Models","data-testid":"model-picker-list",onKeyDown:w,children:[d?r.jsx("div",{className:"model-picker-group","data-testid":"model-picker-group",children:d}):null,g.length===0?r.jsxs("div",{className:"model-picker-empty","data-testid":"model-picker-empty",children:["No models match “",l,"”."]}):g.map(x=>{const m=o!=null&&x.id===o,y=x.id===v,b=x.disabled===!0;return r.jsxs("button",{type:"button",role:"option","aria-selected":y,disabled:b,className:`model-picker-item${y?" model-picker-item-active":""}`,"data-testid":`model-picker-item-${x.id}`,title:x.fullId||x.id,onClick:()=>{b||S(x.id)},children:[r.jsxs("span",{className:"model-picker-item-label",children:[x.label||x.id,m?" (default)":""]}),y?r.jsx("span",{className:"model-picker-item-check","aria-hidden":"true",children:"✓"}):null]},x.id)})]})]})})}function lK(e,t){const n=e.find(d=>d.id===t||d.fullId===t),i=n?.fullId||n?.id||t;if(!i)return"Active model. Click the model picker in the header to switch.";const o=typeof n?.contextWindow=="number"&&n.contextWindow>0?` Context window: ${n.contextWindow.toLocaleString()} tokens.`:"";return`Active model: ${i}.${o}`}function cK({availableModels:e,activeModel:t,defaultModelId:n,onModelChange:i,availablePermissionModes:o,permissionMode:d,onPermissionModeChange:h,showPermissionMode:l=!0,showThinkingLevel:u,thinkingLevel:f,onThinkingLevelChange:v,readOnlyModel:g=null,providerLabel:S=null}){const[w,E]=N.useState(!1);N.useEffect(()=>{e.length===0&&E(!1)},[e.length]);const x=N.useMemo(()=>lK(e,t),[e,t]),m=N.useMemo(()=>e.find(k=>k.id===t||k.fullId===t)??null,[e,t]),y=m?.id??t??"",b=n!=null&&y===n,_=(n?e.find(k=>k.id===n)?.label:e[0]?.label)??"recommended";return r.jsxs(r.Fragment,{children:[e.length>0&&r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button","data-testid":"chat-settings-trigger","data-kind":"model",className:"chat-settings-model-btn",onClick:()=>E(!0),title:x,"aria-label":x,"aria-haspopup":"dialog",children:b?`Default (${_})`:m?.label??t??`Default (${_})`}),r.jsx(oK,{open:w,onClose:()=>E(!1),availableModels:e,activeModel:t,defaultModelId:n,providerLabel:S,onSelect:i})]}),e.length===0&&g!==null&&r.jsx("span",{"data-testid":"active-model-badge","data-kind":"model-readonly",className:"chat-settings-readonly-badge",title:x,"aria-label":x,role:"status",children:g||"Default"}),l&&o.length>0&&r.jsx("select",{"data-kind":"permission","aria-label":"Permission mode",value:d||"",onChange:k=>h(k.target.value),title:o.find(k=>k.id===d)?.description,children:o.map(k=>r.jsx("option",{value:k.id,title:k.description,children:k.label},k.id))}),u&&r.jsxs("select",{"data-kind":"thinking","aria-label":"Thinking level",value:f||"default",onChange:k=>v(k.target.value),children:[r.jsx("option",{value:"default",children:"Auto"}),r.jsx("option",{value:"high",children:"High"}),r.jsx("option",{value:"max",children:"Max"})]})]})}const uK={permission:"Permission",question:"Question",completed:"Completed",error:"Error"},I0=99;function dK(e,t){const n=Math.max(0,t-e),i=Math.floor(n/1e3);if(i<60)return"just now";const o=Math.floor(i/60);if(o<60)return`${o}m ago`;const d=Math.floor(o/60);return d<24?`${d}h ago`:`${Math.floor(d/24)}d ago`}function fK(){return r.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"}),r.jsx("path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0"})]})}function hK(){return r.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function pK({notifications:e,onSwitchSession:t,onMarkRead:n,onMarkAllRead:i,onDismiss:o}){const[d,h]=N.useState(!1),[l,u]=N.useState(0),f=N.useRef(null),v=N.useRef(null),g=N.useRef([]),S=N.useId(),w=N.useMemo(()=>[...e].sort((b,_)=>_.timestamp-b.timestamp),[e]),E=N.useMemo(()=>e.reduce((b,_)=>_.readAt===void 0?b+1:b,0),[e]),x=Date.now();N.useEffect(()=>{if(!d)return;const b=j=>{const T=j.target;v.current&&v.current.contains(T)||f.current&&f.current.contains(T)||h(!1)},_=j=>{j.key==="Escape"&&(j.stopPropagation(),h(!1))},k=()=>h(!1);return document.addEventListener("mousedown",b,!0),document.addEventListener("keydown",_),window.addEventListener("blur",k),()=>{document.removeEventListener("mousedown",b,!0),document.removeEventListener("keydown",_),window.removeEventListener("blur",k)}},[d]),N.useEffect(()=>{if(!d)return;u(0);const b=g.current[0];b&&b.focus()},[d]),N.useEffect(()=>{if(!d)return;const b=document.activeElement,_=b&&b!==document.body&&!v.current?.contains(b)?b:f.current;return()=>{_&&_.isConnected&&_.focus()}},[d]),N.useEffect(()=>{if(!d)return;const b=g.current[l];b&&document.activeElement!==b&&b.focus()},[l,d]),N.useEffect(()=>{d&&l>=w.length&&w.length>0&&u(w.length-1)},[w.length,l,d]);const m=E===0?null:E>I0?`${I0}+`:String(E),y=E===0?"Notifications":`Notifications, ${E} unread`;return r.jsxs("div",{className:"notifications-widget",children:[r.jsxs("button",{ref:f,type:"button",className:"header-icon-btn notifications-widget-trigger","data-testid":"notifications-widget-trigger",onClick:()=>h(b=>!b),"aria-label":y,"aria-haspopup":"menu","aria-expanded":d,"aria-controls":S,title:y,children:[r.jsx("span",{className:"notifications-widget-icon",children:r.jsx(fK,{})}),m!==null&&r.jsx("span",{className:"notifications-widget-badge","data-testid":"notifications-widget-badge","aria-hidden":"true",children:m})]}),d&&r.jsxs("div",{ref:v,id:S,className:"notifications-widget-panel","data-testid":"notifications-widget-panel","aria-label":"Intervention notifications",children:[r.jsxs("div",{className:"notifications-widget-header",children:[r.jsx("span",{className:"notifications-widget-title",children:"Notifications"}),E>0&&r.jsx("button",{type:"button",className:"notifications-widget-mark-all","data-testid":"notifications-widget-mark-all-read",onClick:i,children:"Mark all read"})]}),w.length===0?r.jsx("div",{className:"notifications-widget-empty","data-testid":"notifications-widget-empty",children:"No notifications."}):r.jsx("ul",{className:"notifications-widget-list","data-testid":"notifications-widget-list",role:"menu","aria-label":"Intervention notifications","aria-orientation":"vertical",children:w.map((b,_)=>{const k=b.readAt===void 0,j=["notifications-widget-item",k?"notifications-widget-item--unread":"notifications-widget-item--read",`notifications-widget-item--${b.eventType}`].join(" "),T=l===_,D=I=>{switch(I.key){case"ArrowDown":{I.preventDefault(),I.stopPropagation(),u(L=>(L+1)%w.length);break}case"ArrowUp":{I.preventDefault(),I.stopPropagation(),u(L=>(L-1+w.length)%w.length);break}case"Home":{I.preventDefault(),I.stopPropagation(),u(0);break}case"End":{I.preventDefault(),I.stopPropagation(),u(w.length-1);break}case"Enter":case" ":{I.preventDefault(),I.stopPropagation(),n(b.id),t(b.sessionId),h(!1);break}}};return r.jsxs("li",{className:j,"data-testid":`notifications-widget-item-${b.id}`,"data-read":k?"false":"true",children:[r.jsxs("button",{ref:I=>{g.current[_]=I},type:"button",role:"menuitem",tabIndex:T?0:-1,className:"notifications-widget-item-body","data-testid":`notifications-widget-item-body-${b.id}`,onClick:()=>{n(b.id),t(b.sessionId),h(!1)},onKeyDown:D,children:[r.jsx("span",{className:"notifications-widget-item-type",children:uK[b.eventType]}),r.jsx("span",{className:"notifications-widget-item-session",children:b.sessionName}),r.jsx("span",{className:"notifications-widget-item-message",children:b.message}),r.jsx("span",{className:"notifications-widget-item-time",children:dK(b.timestamp,x)})]}),r.jsxs("div",{className:"notifications-widget-item-actions",children:[k&&r.jsx("button",{type:"button",tabIndex:-1,className:"notifications-widget-item-mark-read","data-testid":`notifications-widget-item-mark-read-${b.id}`,"aria-label":"Mark as read",title:"Mark as read",onClick:I=>{I.stopPropagation(),n(b.id)},children:r.jsx(hK,{})}),r.jsx("button",{type:"button",tabIndex:-1,className:"notifications-widget-item-dismiss","data-testid":`notifications-widget-item-dismiss-${b.id}`,"aria-label":"Dismiss",title:"Dismiss",onClick:I=>{I.stopPropagation(),o(b.id)},children:"×"})]})]},b.id)})})]})]})}function mK({items:e,triggerLabel:t="More actions"}){const[n,i]=N.useState(!1),[o,d]=N.useState(0),h=N.useRef(null),l=N.useRef(null),u=N.useRef([]),f=N.useId(),v=e.filter(S=>typeof S.onClick=="function");if(N.useEffect(()=>{if(!n)return;const S=x=>{const m=x.target;l.current&&l.current.contains(m)||h.current&&h.current.contains(m)||i(!1)},w=x=>{x.key==="Escape"&&(x.stopPropagation(),i(!1))},E=()=>i(!1);return document.addEventListener("mousedown",S,!0),document.addEventListener("keydown",w),window.addEventListener("blur",E),()=>{document.removeEventListener("mousedown",S,!0),document.removeEventListener("keydown",w),window.removeEventListener("blur",E)}},[n]),N.useEffect(()=>{if(!n)return;d(0);const S=u.current[0];S&&S.focus()},[n]),N.useEffect(()=>{if(!n)return;const S=document.activeElement,w=S&&S!==document.body&&!l.current?.contains(S)?S:h.current;return()=>{w&&w.isConnected&&w.focus()}},[n]),N.useEffect(()=>{if(!n)return;const S=u.current[o];S&&document.activeElement!==S&&S.focus()},[o,n]),N.useEffect(()=>{n&&o>=v.length&&v.length>0&&d(v.length-1)},[v.length,o,n]),v.length===0)return null;const g=S=>{try{S.onClick?.()}finally{i(!1)}};return r.jsxs("div",{className:"header-overflow",children:[r.jsx("button",{ref:h,type:"button",className:"header-icon-btn header-overflow-trigger","data-testid":"header-overflow-trigger",onClick:()=>i(S=>!S),"aria-label":t,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":f,title:t,children:"⋯"}),n&&r.jsx("ul",{ref:l,id:f,className:"header-overflow-menu","data-testid":"header-overflow-menu",role:"menu","aria-orientation":"vertical",children:v.map((S,w)=>r.jsxs("li",{ref:E=>{u.current[w]=E},role:"menuitem",tabIndex:o===w?0:-1,"data-testid":`header-overflow-item-${S.id}`,className:"header-overflow-menu-item",title:S.title,onClick:()=>g(S),onKeyDown:E=>{switch(E.key){case"ArrowDown":{E.preventDefault(),E.stopPropagation(),d(x=>(x+1)%v.length);break}case"ArrowUp":{E.preventDefault(),E.stopPropagation(),d(x=>(x-1+v.length)%v.length);break}case"Home":{E.preventDefault(),E.stopPropagation(),d(0);break}case"End":{E.preventDefault(),E.stopPropagation(),d(v.length-1);break}case"Enter":case" ":{E.preventDefault(),E.stopPropagation(),g(S);break}}},children:[S.icon?r.jsx("span",{className:"header-overflow-menu-icon","aria-hidden":"true",children:S.icon}):null,r.jsx("span",{className:"header-overflow-menu-label",children:S.label})]},S.id))})]})}const M0=" ",gK=80,vK=100;function yK({cost:e,context:t,contextPercent:n,inputTokens:i,outputTokens:o,contextWindow:d,isBusy:h,agentCount:l,provider:u,model:f,costBadgeMode:v}){const g=u?Vi(u):null,S=S1({cost:e,provider:u}),w=x1({percent:n??null,contextSummary:t,inputTokens:i,outputTokens:o}),E=w1(l),x=(i??0)+(o??0),m=x>0&&d!=null&&d>0&&n!=null,y=n??0,b=Math.min(y,100),_=y>=vK?" high over-budget":y>=gK?" high":y>=50?" medium":"";return r.jsxs("div",{className:"status-bar","data-testid":"status-bar",children:[r.jsxs("div",{className:"status-bar-group status-bar-left",children:[g&&r.jsx("span",{className:"status-provider","data-provider":g.type,title:g.tooltip,"aria-label":g.tooltip,"data-testid":"status-provider",children:g.short}),f&&r.jsx("span",{className:"status-model","data-testid":"status-model",title:f,children:f})]}),r.jsxs("div",{className:"status-bar-group status-bar-right",children:[h&&r.jsx("span",{className:"busy-indicator","data-testid":"busy-indicator",role:"img","aria-label":"Agent working"}),v?r.jsx(vF,{mode:v,cost:e,provider:u,model:f,inputTokens:i,outputTokens:o,contextPercent:n,title:S,className:"status-cost"}):r.jsx("span",{className:"status-cost",title:S,"aria-label":S,children:e!=null?`$${e.toFixed(4)}`:M0}),m?r.jsxs("span",{className:"status-context-meter status-context-meter--stacked","data-testid":"status-context-meter",title:w,"aria-label":w,children:[r.jsxs("span",{className:"status-context-label","data-testid":"status-context-label",children:[Ga(x)," / ",Ga(d)," tokens"]}),r.jsx("span",{className:`status-context-bar${_}`,role:"progressbar","aria-label":"Context window usage","aria-valuenow":Math.min(Math.round(y),100),"aria-valuemin":0,"aria-valuemax":100,children:r.jsx("span",{className:"status-context-fill",style:{width:`${b}%`}})})]}):r.jsx("span",{className:"status-context",title:w,"aria-label":w,children:t||M0}),l!=null&&l>0&&r.jsxs("span",{className:"agent-badge","data-testid":"agent-badge",title:E,"aria-label":E,children:[l," ",l===1?"agent":"agents"]})]})]})}function bK(e){return r.jsxs("header",{id:"header",children:[r.jsxs("div",{className:"header-main",children:[r.jsxs("div",{className:"header-left",children:[r.jsx("span",{className:"logo",children:"Chroxy"}),(()=>{const t=`Chroxy server v${e.serverVersion??"0.10.0"}`;return r.jsxs("span",{className:"version-badge",title:t,"aria-label":t,children:["v",e.serverVersion??"0.10.0"]})})(),(()=>{const t=e.serverPhase==="tunnel_warming"||e.serverPhase==="tunnel_verifying"||e.isConnected&&!e.tunnelReady&&e.serverPhase==null,n=t?"connecting":e.connectionPhase,o={connected:"Connected to Chroxy server",connecting:t?"Tunnel warming up…":"Connecting to Chroxy server…",reconnecting:"Reconnecting to Chroxy server…",server_restarting:"Server restarting…",server_down:"Chroxy server appears to be down",disconnected:"Disconnected from Chroxy server"}[n]??`Connection status: ${n}`;return r.jsx("span",{className:`status-dot ${n}`,"data-activity":n==="connected"?e.chatActivityState:void 0,title:o,"aria-label":o})})()]}),r.jsx("div",{className:"header-center",children:r.jsx(cK,{availableModels:e.showModelPicker?e.availableModels:[],activeModel:e.activeModel,defaultModelId:e.defaultModelId,onModelChange:e.onModelChange,readOnlyModel:e.readOnlyModel,providerLabel:e.provider,availablePermissionModes:e.availablePermissionModes,permissionMode:e.permissionMode,onPermissionModeChange:e.onPermissionModeChange,showPermissionMode:e.showPermissionMode,showThinkingLevel:e.showThinkingLevel,thinkingLevel:e.thinkingLevel,onThinkingLevelChange:t=>e.onThinkingLevelChange(t)})}),r.jsxs("div",{className:"header-right",children:[r.jsx(pK,{notifications:e.sessionNotifications,onSwitchSession:e.onSwitchSession,onMarkRead:e.onMarkNotificationRead,onMarkAllRead:e.onMarkAllNotificationsRead,onDismiss:e.onDismissNotification}),(()=>{const t=[{id:"new-session",label:"New Session",icon:"+",title:`New session (${yr("Cmd+N")})`,onClick:e.onNewSession},{id:"new-shell",label:"New Shell",icon:"🖥",title:"Open an embedded terminal shell",onClick:e.onNewShell},{id:"skills",label:"Skills",icon:"🧩",title:"Skills",onClick:e.onToggleSkillsPanel},{id:"pair-device",label:"Pair a device",icon:"📱",title:`Pair a device — scan the QR with the Chroxy mobile app (${yr("Cmd+Shift+L")})`,onClick:e.onShowQr},e.showCopyTranscript?{id:"copy-transcript",label:e.transcriptCopied?"Transcript copied":"Copy transcript",icon:e.transcriptCopied?"✓":"⎘",title:e.transcriptCopied?"Copied!":`Copy transcript (${yr("Cmd+Shift+T")})`,onClick:e.onCopyTranscript}:{id:"copy-transcript",label:"Copy transcript"},{id:"settings",label:"Settings",icon:"⚙",title:`Settings (${yr("Cmd+,")})`,onClick:e.onOpenSettings},{id:"revoke-token",label:"Revoke token",icon:"🛑",title:"Immediately revoke the API token (severs shells, forces re-auth)",onClick:e.onRevokeToken}];return r.jsx(mK,{items:t})})()]})]}),r.jsx("div",{className:"header-meta",children:r.jsx(yK,{cost:e.cost,context:e.context,contextPercent:e.contextPercent,inputTokens:e.inputTokens,outputTokens:e.outputTokens,contextWindow:e.contextWindow,isBusy:e.isBusy,agentCount:e.agentCount,provider:e.provider,model:e.modelLabel,costBadgeMode:e.costBadgeMode})})]})}function D0(e){if(!e)return;const t=e.inputTokens+e.outputTokens;if(t!==0)return`${Ga(t)} tokens`}function _K(){const e=mg(),t=V(U=>U.connectionPhase),n=V(U=>U.serverVersion),i=V(U=>U.sessionCwd),o=V(U=>U.sessions.find(Re=>Re.sessionId===U.activeSessionId)?.cwd??null),d=V(U=>U.sessions.find(Re=>Re.sessionId===U.activeSessionId)?.provider??null),h=V(U=>U.serverCapabilities?.userShell===!0),l=V(U=>U.serverCapabilities?.ide===!0),u=V(U=>U.serverCapabilities?.tokenRevoke===!0),f=d===yf,v=d===j_,g=f||v,S=V(U=>U.defaultCwd),w=V(U=>U.sessions),E=V(U=>U.monthlyBudget),x=V(U=>U.sessionStates),m=V(U=>U.activeSessionId),y=V(U=>U.viewMode),b=V(U=>U.subscribeTerminalMirror),_=V(U=>U.unsubscribeTerminalMirror),k=V(U=>U.availableModels),j=V(U=>U.availableModelsProvider),T=V(U=>U.costBadgeMode),D=V(U=>U.defaultModelId),I=V(U=>U.availablePermissionModes),L=V(U=>U.availableProviders),q=V(U=>U.serverErrors),H=V(U=>U.infoNotifications??[]),Q=V(U=>U.connectionError),F=V(U=>U.serverPhase),J=V(U=>U.tunnelProgress),ie=V(U=>U.serverExposure),X=V(U=>U.exposureBannerDismissed),de=V(U=>U.dismissExposureBanner),fe=V(U=>U.billingCanary),$=V(U=>U.billingBannerDismissed),P=V(U=>U.dismissBillingBanner),B=V(U=>U.serverStartupLogs),K=V(U=>U.connectionRetryCount),le=V(U=>U.shutdownReason),me=V(U=>U.restartEtaMs),be=V(U=>U.restartingSince),Ee=V(U=>U.filePickerFiles),se=V(U=>U.sessionNotifications),Z=V(U=>U.pendingPairRequests),ge=V(U=>U.approvePairRequest),De=V(U=>U.denyPairRequest),Ge=V(U=>U.inputSettings),Ve=V(U=>U.connectedClients),St=V(U=>U.primaryClientId),Nt=V(U=>{const Re=U.activeSessionId;return Re&&U.sessionStates[Re]?U.sessionStates[Re].sessionRole:null}),kt=V(U=>U.claimPrimary),Tt=V(U=>U.pairingRefreshedCount),at=V(U=>U.streamStallTimeoutMs);HU();const en=V(U=>U.inputSettings.voiceInputMode),cn=Mz({mode:en}),{messages:Bt,streamingMessageId:hn,queuedMessages:sn,activeModel:Ct,permissionMode:Ut,contextUsage:$t,sessionCost:Lt,isIdle:Ht,activeAgents:zt,isPlanPending:rn,thinkingLevel:ze,skills:Je,mismatchedSkillNames:tt,pendingCommunitySkills:Pt,pendingTrustGrants:Vt,pendingEvaluatorClarify:Wt,interventions:Zt}=V(Mc(U=>U.getActiveSessionState())),Dn=N.useMemo(()=>new Set(tt||[]),[tt]),wn=N.useMemo(()=>new Set((sn||[]).map(U=>U.clientMessageId).filter(U=>!!U)),[sn]),Kn=N.useMemo(()=>{const U=Tm(Bt);return U?`Running ${fa(U.tool,U.serverName)}…`:void 0},[Bt]),je=N.useMemo(()=>{const U=Tm(Bt);if(U)return`var(--${BN(U.tool,U.serverName).colorToken})`},[Bt]),mt=N.useMemo(()=>ZN(d),[d]),xt=V(U=>U.resolvedPermissions),Mt=N.useMemo(()=>{for(const U of Bt){if(U.type!=="prompt"||!U.requestId||U.tool!=="AskUserQuestion"||U.answered==="allow"||U.answered==="allowSession")continue;const Re=xt?.[U.requestId];if(!(Re==="allow"||Re==="allowSession"))return!0}return!1},[Bt,xt]),un=N.useMemo(()=>{const U=d,Qe=L.find(Sn=>Sn.name===U)?.capabilities,jt=j==null||U==null||j===U;return{showModelPicker:Qe?.modelSwitch!==!1&&jt,readOnlyModel:Qe?.modelSwitch===!1?Ct:null,showPermissionMode:Qe?.permissionModeSwitch!==!1,showThinkingLevel:!!Qe?.thinkingLevel}},[d,L,j,Ct]),_n=N.useMemo(()=>Bt.filter(U=>U.requestId&&U.expiresAt&&U.type==="prompt"&&!U.answered).map(U=>({id:U.id,requestId:U.requestId,tool:U.tool||"Unknown",description:U.content,expiresAt:U.expiresAt,answered:U.answered})),[Bt]);QU(_n);const[tn,zn]=N.useState(()=>NP());s9(_n,{enabled:tn});const ss=N.useMemo(()=>{let U=0,Re="";for(const Qe of Bt)Qe.type==="user_input"&&typeof Qe.content=="string"&&Qe.content.length>0&&(U++,Re=Qe.id);return`${U}${Re}`},[Bt]),Ie=N.useMemo(()=>Bt.filter(U=>U.type==="user_input"&&typeof U.content=="string"&&U.content.length>0).map(U=>U.content),[ss]),ot=V(U=>U.slashCommands),pt=N.useMemo(()=>{const U=Re=>Re==="builtin"?0:Re==="project"?1:2;return[...ot].sort((Re,Qe)=>U(Re.source)-U(Qe.source))},[ot]),At=V(U=>U.connect),O=V(U=>U.retryConnection),W=V(U=>U.sendInput),G=V(U=>U.addInfoNotification),M=V(U=>U.sendInterrupt),ne=V(U=>U.sendCancelQueued),te=N.useCallback(U=>{ne(U)},[ne]),[re,ve]=N.useState(0),Me=V(U=>U.evaluateDraft),Ze=V(U=>U.sendPermissionResponse),Xe=V(U=>U.switchSession),Dt=V(U=>U.sessionNotFoundError),nt=V(U=>U.dismissSessionNotFoundError),Oe=V(U=>U.destroySession),ce=V(U=>U.renameSession),ke=V(U=>U.createSession),Ue=V(U=>U.revokeToken),rt=V(U=>U.confirmSessionClose),ct=V(U=>U.setViewMode);N.useEffect(()=>{if(v&&y==="chat"){ct("terminal");return}if(y==="terminal"&&d!=null&&!g){ct("chat");return}if(y==="terminal"&&g&&m&&t==="connected")return b(m),()=>_(m)},[y,m,d,v,g,t,b,_,ct]);const et=V(U=>U.setModel),st=V(U=>U.setPermissionMode),gt=V(U=>U.setThinkingLevel),it=V(U=>U.requestListSkills),ft=V(U=>U.activateSkill),lt=V(U=>U.deactivateSkill),ut=V(U=>U.acceptSkillTrust),Ne=V(U=>U.connectionPhase==="connected"&&!!U.serverCapabilities?.skillTrustAccept),Ae=V(U=>U.grantCommunitySkillTrust),Ke=V(U=>U.connectionPhase==="connected"&&!!U.serverCapabilities?.skillTrustGrant),[$e,Le]=N.useState(!1),We=V(U=>U.dismissServerError),Rt=V(U=>U.dismissInfoNotification),ae=V(U=>U.dismissSessionNotification),vt=V(U=>U.markSessionNotificationRead),yt=V(U=>U.markAllSessionNotificationsRead),ue=V(U=>U.conversationHistory),Gt=V(U=>U.fetchConversationHistory),bt=V(U=>U.resumeConversation),Qt=V(U=>U.sendUserQuestionResponse),Kt=V(U=>U.markPromptAnswered),Jt=V(U=>U.fetchFileList),Yt=V(U=>U.fetchSlashCommands),An=V(U=>U.searchResults),bn=V(U=>U.searchLoading),xn=V(U=>U.searchQuery),Rn=V(U=>U.searchConversations),En=V(U=>U.clearSearchResults),Un=u8(g),[Vn,Jn]=N.useState(!1),[is,ya]=N.useState(!1),[ki,io]=N.useState(!1),[hl,Zi]=N.useState(!1),Cr=V(U=>U.referencesOpen),[Zc,Er]=N.useState(!1),[Xc,ba]=N.useState(null),[Ci,ro]=N.useState(null),[Zs,Ls]=N.useState(!1),[pl,Ei]=N.useState(null),[ao,Nr]=N.useState([]),[Xi,oo]=N.useState([]),[Ss,ui]=N.useState(!0),[lo,_a]=N.useState(()=>hP()??240),[xf,ml]=N.useState(""),[jr,Ar]=N.useState(null),[Rr,Qc]=N.useState(!1),{controlRoomOpen:Jc,controlRoomActive:Tr,setControlRoomActive:eu,settingsRedirectNonce:gl,controlRoomInitialTab:wf,settingsOpen:kf,setSettingsOpen:tu,shortcutHelpOpen:Cf,setShortcutHelpOpen:nu,splitMode:Ir,setSplitMode:co,openControlRoom:su,openSettings:vl,closeControlRoom:Ef}=y9();N.useEffect(()=>{v&&Ir&&(co(null),rf(null))},[v,Ir,co]);const[Mr,yl]=N.useState(null),uo=N.useRef(null),Os=N.useCallback(({cwd:U=null,seed:Re=null}={})=>{uo.current=Re||null,ba(U),Er(!0)},[]),[iu,ru]=N.useState(!1),Sa=N.useRef(null),au=N.useCallback(()=>{const U=OS(Bt);U&&Pc(U).then(Re=>{if(!Re){V.getState().addServerError("Failed to copy transcript to clipboard. Please try again.",void 0,"warning");return}ru(!0),Sa.current&&clearTimeout(Sa.current),Sa.current=setTimeout(()=>ru(!1),1500)})},[Bt]);N.useEffect(()=>()=>{Sa.current&&clearTimeout(Sa.current)},[]);const ou=N.useCallback(U=>{const Re=V.getState().sessionStates[U],Qe=Re?OS(Re.messages):"";if(!Qe){V.getState().addInfoNotification("No transcript to copy for this session yet.");return}Pc(Qe).then(jt=>{if(!jt){V.getState().addServerError("Failed to copy transcript to clipboard. Please try again.",void 0,"warning");return}V.getState().addInfoNotification("Transcript copied to clipboard.")})},[]),bl=N.useRef(new Set),lu=N.useCallback(U=>{if(bl.current.has(U))return;const Re=V.getState(),jt=Re.sessions.find(Sn=>Sn.sessionId===U)?.cwd||null;bl.current.add(U),Re.addInfoNotification("Summarizing session…"),Re.summarizeSession(U).then(({summary:Sn})=>{Os({cwd:jt,seed:Sn})}).catch(Sn=>{V.getState().addServerError(Sn instanceof Error?Sn.message:"Could not summarize this session.",void 0,"warning")}).finally(()=>{bl.current.delete(U)})},[Os]),[_l,cu]=N.useState(()=>EP()),[Li,fo]=N.useState(!1);N.useEffect(()=>{fo(!1)},[m]);const Xs=N.useCallback(U=>{eu(!1),U!==m&&(fo(!0),Xe(U))},[Xe,m]),ho=N.useCallback((U,Re)=>{Or(U),Re?Oe(U,!0):Oe(U)},[Oe]),xa=N.useCallback(U=>{if(w.find(Qe=>Qe.sessionId===U)?.isBusy){if(!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm("This session is still running. Delete it anyway? The in-flight turn will be interrupted and any uncommitted work in its worktree may be lost."):!0))return;ho(U,!0);return}if(rt){yl(U);return}ho(U)},[w,rt,ho]),uu=N.useCallback(U=>{const Re=w.find(Qe=>Qe.sessionId===U);Re&&(ke({name:Re.name,cwd:Re.cwd||void 0,provider:Re.provider,model:Re.model||void 0,permissionMode:Re.permissionMode||void 0,worktree:Re.worktree}),Or(U),Oe(U))},[w,Oe,ke]),du=N.useCallback((U,Re)=>{Re.currentTarget instanceof HTMLElement&&Re.currentTarget.focus(),Ar({target:U,x:Re.clientX,y:Re.clientY})},[]),fu=N.useCallback(()=>{Ar(null)},[]),hu=N.useMemo(()=>jr?r8({target:jr.target,sessions:w,conversationHistory:ue,isTauri:hs(),createSession:ke,resumeConversation:bt,revealInFinder:D1,onRevealError:U=>{V.getState().addServerError(U)},copyToClipboard:U=>{Pc(U).then(Re=>{Re||V.getState().addServerError("Failed to copy to clipboard. Please try again.",void 0,"warning")})},openCreateSessionAt:U=>{Os({cwd:U})},copySessionTranscript:ou,summarizeAndCreateSession:lu,confirmCloseSession:xa}):[],[jr,w,ue,ke,bt,xa,Os,ou,lu]),di=N.useCallback(U=>{U.length!==0&&oo(Re=>[...Re,...U])},[]),pu=N.useRef(null);r9({shortcutRegistry:e,sessions:w,activeSessionId:m,viewMode:y,setViewMode:ct,setSplitMode:co,terminalOnly:v,setPaletteOpen:Jn,setSidebarOpen:ui,setSettingsOpen:tu,openSettings:vl,setShowCreateSession:Er,setShortcutHelpOpen:nu,handleSwitchSession:Xs,handleCloseSession:xa,handleCopyTranscript:au,sendInterrupt:M,setPermissionMode:st,appendImageAttachments:di,openFilePalette:()=>{l&&ya(!0)},openSymbolSearch:()=>{l&&io(!0)},openCodeSearch:()=>{l&&Zi(!0)},showQr:()=>pu.current?.()});const Nf=N.useMemo(()=>Un.map(U=>({...U,action:()=>{c8(U.id),U.id==="new-session"?Os():U.id==="toggle-sidebar"?ui(Re=>!Re):U.action()}})),[Un]);N.useEffect(()=>{if(li()){V.getState().connectLocal();return}const{activeServerId:Re,serverRegistry:Qe,connectToServer:jt}=V.getState();Re&&Qe.some(Sn=>Sn.id===Re)&&jt(Re)},[At]),N.useEffect(()=>{if(Zs&&m){Er(!1),Ls(!1),Ei(null);const U=V.getState().takePendingServerSeed,Qe=(typeof U=="function"?U(m):null)||uo.current;Qe&&(Bi.current.set(m,Qe),fi(Qe),eu(!1),uo.current=null)}},[m,Zs]),N.useEffect(()=>{if(Zs&&q.length>0){const U=q[q.length-1];U&&(Ei(U.message),Ls(!1))}},[q,Zs]),N.useEffect(()=>{Zs&&t!=="connected"&&(Ls(!1),Ei("Connection lost — try again"))},[t,Zs]);const{chatMessages:mu,chatToolGroupPayloads:gu,chatTailMessageId:vu,storeMsgMap:wa,stalledPromptIds:ka}=f9({storeMessages:Bt,streamingMessageId:hn}),Dr=N.useMemo(()=>Bt.filter(U=>U.type==="system").map(fm),[Bt]),Ca=N.useRef(new Map),yu=Ca.current.get(m)??0,Sl=y==="system"?0:Dr.length-yu,xl=Sl>0?Sl:0;N.useEffect(()=>{const U=Ca.current;(U.get(m)??0)>Dr.length&&U.set(m,Dr.length),y==="system"&&U.set(m,Dr.length)},[y,Dr.length,m]);const[po,bu]=N.useState(()=>Date.now());N.useEffect(()=>{const U=window.setInterval(()=>bu(Date.now()),6e4);return()=>window.clearInterval(U)},[]);const Ea=N.useCallback(U=>{const Re=x[U.sessionId];return fN({isBusy:U.isBusy,isIdle:Re?.isIdle,streamingMessageId:Re?.streamingMessageId,activeAgentCount:Re?.activeAgents.length??0,lastActivityAt:U.lastActivityAt??U.createdAt,now:po})},[x,po]),{tabOrder:wl,sidebarRepoOrder:_u,sidebarSessionOrder:Su,handleReorderTabs:jf,handleReorderRepos:Af,handleReorderSidebarSessions:Rf}=v9(),es=V(Mc(U=>O4(U.sessionStates,Date.now()))),Oi=N.useMemo(()=>{const U=new Map(w.map(jt=>[jt.sessionId,jt])),Re=[],Qe=new Set;for(const jt of wl){const Sn=U.get(jt);Sn&&!Qe.has(jt)&&(Re.push(Sn),Qe.add(jt))}for(const jt of w)Qe.has(jt.sessionId)||Re.push(jt);return Re.map(jt=>({sessionId:jt.sessionId,name:jt.name,isBusy:jt.isBusy,isActive:jt.sessionId===m,cwd:jt.cwd,model:jt.model??void 0,provider:jt.provider,status:Ea(jt),stdinForwardingDisabled:jt.stdinForwardingDisabled,pendingPermission:(es[jt.sessionId]??0)>0,pendingPermissionCount:es[jt.sessionId]??0}))},[w,m,Ea,wl,es]),kl=P4(es);FU(kl);const Qi=kN({isIdle:Ht??!0,streamingMessageId:hn??null,isPlanPending:rn??!1,pendingPermission:(es[m??""]??0)>0}),xu=N.useCallback(()=>{const U=Oi.map(Qe=>Qe.sessionId),Re=B4(U,es,m);Re&&Xs(Re)},[Oi,es,m,Xs]),Cl=V(Mc(U=>{const Re={};for(const Qe in U.sessionStates)Re[Qe]=U.sessionStates[Qe].cumulativeUsage;return Re})),Pi=N.useMemo(()=>{const U=new Map;for(const Qe of w){if(!Qe.cwd)continue;let jt=U.get(Qe.cwd);if(!jt){const Sn=Qe.cwd.split("/").pop()||Qe.cwd;jt={path:Qe.cwd,name:Sn,source:"auto",exists:!0,activeSessions:[],resumableSessions:[]},U.set(Qe.cwd,jt)}jt.activeSessions.push({sessionId:Qe.sessionId,name:Qe.name,isBusy:Qe.isBusy,provider:Qe.provider,worktree:Qe.worktree,status:Ea(Qe),stdinForwardingDisabled:Qe.stdinForwardingDisabled,cumulativeUsage:Cl[Qe.sessionId]??Qe.cumulativeUsage??null})}return U.size===0?[]:mS([...U.values()],_u,Qe=>Qe.path).map(Qe=>{const jt=Su[Qe.path];return!jt||jt.length===0?Qe:{...Qe,activeSessions:mS(Qe.activeSessions,jt,Sn=>Sn.sessionId)}})},[w,Ea,Cl,_u,Su]),Tf=N.useMemo(()=>[...Pi.map(U=>U.path),...S?[S]:[],...i?[i]:[]],[Pi,S,i]),Lr=N.useMemo(()=>{if(!rn)return"";for(let U=Bt.length-1;U>=0;U--){const Re=Bt[U];if(Re.type==="response"||Re.type==="thinking")return`<p>${Re.content.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br/>")}</p>`}return"<p>Claude has prepared a plan for your review.</p>"},[rn,Bt]),mo=t==="connected",Ni=m?x[m]?.costThresholdWarning??null:null,go=N.useMemo(()=>[...q.filter(U=>!U.sessionId||U.sessionId===m).map(U=>({id:U.id,message:U.message,level:U.severity==="warning"?"warning":"error",...U.action?{action:U.action,actionDisabled:!mo,actionDisabledLabel:"Reconnecting…"}:{},...U.partialCostLine?{subMessage:U.partialCostLine}:{}})),...H.map(U=>({id:U.id,message:U.message,level:"info"})),...Ni&&Ni.dismissedAt==null?[{id:`cost-threshold-${m}`,message:`Session has used $${Ni.costUsd.toFixed(2)}. (Threshold: $${Ni.thresholdUsd.toFixed(2)}).`,level:"info"}]:[]],[q,H,m,mo,Ni]),Bi=N.useRef(new Map),[Ji,fi]=N.useState(""),El=N.useCallback(U=>{fi(U),m&&Bi.current.set(m,U)},[m]),ji=N.useRef(new Map),hi=N.useRef(new Map),[Nl,Na]=N.useState([]),[vo,ja]=N.useState(null),Or=U=>{Bi.current.delete(U),ji.current.delete(U),hi.current.delete(U)};N.useEffect(()=>{const U=new Set(w.map(Re=>Re.sessionId));for(const Re of Bi.current.keys())U.has(Re)||Or(Re);for(const Re of ji.current.keys())U.has(Re)||Or(Re);for(const Re of hi.current.keys())U.has(Re)||Or(Re)},[w]),N.useEffect(()=>{m&&(fi(Bi.current.get(m)??""),Na(ji.current.get(m)??[]),ja(null))},[m]);const If=N.useCallback(U=>{const Re=m;if(!Re)return U;const Qe=(hi.current.get(Re)??0)+1;hi.current.set(Re,Qe);const jt={id:Qe,content:U},Sn=[...ji.current.get(Re)??[],jt];return ji.current.set(Re,Sn),Na(Sn),KN(Qe,U)},[m]),jl=N.useCallback(U=>{const Re=m;if(!Re)return;const Qe=(ji.current.get(Re)??[]).filter(Ur=>Ur.id!==U);ji.current.set(Re,Qe),Na(Qe);const jt=new RegExp(`\\[Pasted text #${U} \\+\\d+ (?:lines|chars)\\]`,"g"),$i=(Bi.current.get(Re)??"").replace(jt,"");Bi.current.set(Re,$i),fi($i),vo===U&&ja(null)},[m,vo]),wu=N.useCallback(U=>{ja(U)},[]),Al=N.useCallback((U,Re)=>{const Qe=Re||ao,jt=Dz(Qe.length>0?Qe:void 0,Xi.length>0?Xi:void 0),Sn=m,$i=Sn?ji.current.get(Sn)??[]:[],Ur=new Map($i.map(ti=>[ti.id,ti.content])),sr=Ur.size>0?WN(U,Ur):U;W(sr,jt.length>0?jt:void 0)==="queued"&&G("Message queued — will send on reconnect."),ve(ti=>ti+1),Nr([]),oo([]),Sn&&Or(Sn),fi(""),Na([]),ja(null)},[W,G,ao,Xi,m]),Qs=N.useCallback(()=>{M()},[M]),er=N.useCallback(()=>{Os()},[Os]),Ps=N.useCallback(()=>{ke({name:"Shell",cwd:S??void 0,provider:j_})},[ke,S]),Pr=N.useCallback(()=>{window.confirm(`Revoke the API token now?
|
|
106
|
-
|
|
107
|
-
This immediately invalidates the current token (no grace period), closes every embedded shell, and signs out all connected devices — including this dashboard. You will need to re-pair with the new token to reconnect.
|
|
108
|
-
|
|
109
|
-
Use this only if the token may be compromised.`)&&Ue()},[Ue]),Rl=N.useCallback(U=>{Os({cwd:U.cwd,seed:U.reason})},[Os]),yo=N.useCallback(U=>{Os({cwd:U.cwd})},[Os]),bo=N.useCallback(U=>{ro(U)},[]),Tl=N.useCallback(U=>{Ei(null),ke({name:U.name,cwd:U.cwd||void 0,provider:U.provider,model:U.model,permissionMode:U.permissionMode,worktree:U.worktree,skipPermissions:U.skipPermissions})?Ls(!0):Ei("Connection lost — try again")},[ke]),tr=N.useCallback(()=>{W("approve"),ve(U=>U+1)},[W]),ku=N.useCallback(()=>{document.querySelector(".input-bar textarea")?.focus()},[]),_o=N.useCallback(U=>{Nr(Re=>{if(Re.some(jt=>jt.path===U))return Re;const Qe=U.split("/").pop()||U;return[...Re,{path:U,name:Qe}]})},[]),Br=N.useCallback(U=>{Nr(Re=>Re.filter(Qe=>Qe.path!==U))},[]),Mf=N.useCallback(async U=>{const Re=ff(U);if(Re.length===0)return;const{accepted:Qe}=await RS(Re);di(Qe)},[di]),Es=N.useCallback(async U=>{const Re=ff(U);if(Re.length===0)return;const{accepted:Qe}=await RS(Re);di(Qe)},[di]),Il=N.useCallback(U=>{oo(Re=>Re.filter((Qe,jt)=>jt!==U))},[]),{qrModalOpen:Ai,setQrModalOpen:Cu,qrSvg:So,qrLoading:nr,qrError:Ml,qrPairingCode:Eu,qrShareMode:Dl,handleShowQr:Aa,handleShareSession:Bs,handlePostPairLinkToDiscord:$r}=g9(m,Tt);YU({onNewSession:er,onShowQr:Aa,openSettings:vl,setSidebarOpen:ui,setPermissionMode:st});const Js=N.useCallback((...U)=>{const Re=Ze(...U);return Re!==!1&&ve(Qe=>Qe+1),Re},[Ze]);WU({storeMessages:Bt,resolvedPermissions:xt,sendPermissionResponse:Js,activeSessionProvider:d,availableProviders:L,connected:t==="connected"});const xo=N.useCallback((...U)=>{const Re=Qt(...U);return Re!==!1&&ve(Qe=>Qe+1),Re},[Qt]),Ra=N.useCallback((U,Re)=>{Js(U,"allow"),ae(Re)},[Js,ae]),$s=N.useCallback((U,Re)=>{Js(U,"deny"),ae(Re)},[Js,ae]),xs=N.useCallback(()=>{O()},[O]),pi=N.useCallback(()=>{C1()},[]),mi=N.useMemo(()=>L.find(U=>U.name===d)?.capabilities??null,[L,d]),zs=V9({storeMsgMap:wa,chatToolGroupPayloads:gu,chatTailMessageId:vu,sendPermissionResponse:Js,sendUserQuestionResponse:xo,markPromptAnswered:Kt,storeMessages:Bt,sendInput:W,streamStallTimeoutMs:at,allowMultiQuestionForm:mt,activeSessionProvider:d,activeSessionCaps:mi,setViewMode:ct,stalledPromptIds:ka,hasPendingAskUserQuestionPermission:Mt,sessions:w}),Ri=UU(e,ma(),ma()),zr=N.useMemo(()=>{const U=k.find(Re=>Re.id===Ct||Re.fullId===Ct);return tE(U,d)},[k,Ct,d]),wo=N.useMemo(()=>{if(!$t||zr==null)return null;const U=$t.inputTokens+$t.outputTokens;return U===0?null:U/zr*100},[$t,zr]),Ll=N.useMemo(()=>Ct?k.find(Re=>Re.id===Ct||Re.fullId===Ct)?.label??Ct:void 0,[Ct,k]),ws=t==="connected";pu.current=ws?Aa:null;const rs=t==="reconnecting"||t==="server_restarting",Tn=t==="server_down",pn=t==="disconnected"&&!!Q&&w.length===0,ei=ws&&w.length===0,Ns=m9(ws);N.useEffect(()=>{ei&&Gt()},[ei,Gt]);const Ol=N.useMemo(()=>ue.filter(U=>U.preview&&U.cwd).map(U=>({conversationId:U.conversationId,preview:U.preview,cwd:U.cwd,updatedAt:U.modifiedAtMs})),[ue]),gi=F==="tunnel_warming"||F==="tunnel_verifying";return r.jsxs("div",{id:"app",className:Pi.length>0?"with-sidebar":"",children:[r.jsx(aU,{phase:t}),r.jsx(eU,{visible:rs||Tn,attempt:K,maxAttempts:5,message:Tn?"Server appears to be down":t==="server_restarting"?"Server restarting...":void 0,terminal:Tn,restartEtaMs:t==="server_restarting"?me:null,restartingSince:t==="server_restarting"?be:null,shutdownReason:t==="server_restarting"?le:null,onRetry:xs,onStartServer:hs()?pi:void 0}),r.jsx("div",{className:`tunnel-warming-banner${gi?"":" tunnel-warming-banner--hidden"}`,"data-testid":"tunnel-warming-banner",role:"status","aria-live":"polite","aria-hidden":gi?void 0:!0,children:gi?r.jsxs(r.Fragment,{children:["Tunnel warming up",J?`… attempt ${J.attempt}/${J.maxAttempts}`:"…"," ","(QR will appear shortly)"]}):null}),ie&&!X&&r.jsx(tU,{lanBind:ie.lanBind,quickTunnel:ie.quickTunnel,onDismiss:de}),fe&&fe.warnings.length>0&&r.jsx(nU,{warnings:fe.warnings,dismissed:$,onDismiss:P}),r.jsx(bK,{serverVersion:n,connectionPhase:t,chatActivityState:Qi.state,serverPhase:F,isConnected:ws,tunnelReady:Ns,showModelPicker:un.showModelPicker,availableModels:k,activeModel:Ct,defaultModelId:D,onModelChange:et,readOnlyModel:un.readOnlyModel,availablePermissionModes:I,permissionMode:Ut,onPermissionModeChange:st,showPermissionMode:un.showPermissionMode,showThinkingLevel:un.showThinkingLevel,thinkingLevel:ze,onThinkingLevelChange:U=>gt(U),sessionNotifications:se,onSwitchSession:Xs,onMarkNotificationRead:vt,onMarkAllNotificationsRead:yt,onDismissNotification:ae,onNewSession:er,onNewShell:h?Ps:void 0,onRevokeToken:u?Pr:void 0,onToggleSkillsPanel:()=>{Le(U=>{const Re=!U;return Re&&it(),Re})},onShowQr:ws?Aa:void 0,showCopyTranscript:y==="chat"&&Bt.length>0,transcriptCopied:iu,onCopyTranscript:au,onOpenSettings:vl,cost:Lt??void 0,context:D0($t),contextPercent:wo,inputTokens:$t?.inputTokens,outputTokens:$t?.outputTokens,contextWindow:Ct?zr??void 0:void 0,isBusy:!Ht,agentCount:zt.length,provider:w.find(U=>U.sessionId===m)?.provider,modelLabel:Ll,costBadgeMode:T}),Pi.length>0&&r.jsx(i8,{repos:Pi,activeSessionId:m,isOpen:Ss,width:lo,filter:xf,serverStatus:ws?"connected":rs?"reconnecting":"disconnected",chatActivityState:Qi.state,tunnelUrl:null,connectedClients:Ve,activePrimaryClientId:T$(m,x,St),activeSessionRole:Nt,onTakeOverPrimary:()=>{m&&kt(m,{force:!0})},onFilterChange:ml,onSessionClick:Xs,onResumeSession:bt,onOpenControlRoom:su,onNewSession:U=>Os({cwd:U||null}),onToggle:()=>ui(U=>!U),onWidthChange:U=>{_a(U),fP(U)},onContextMenu:du,searchResults:An,searchLoading:bn,searchQuery:xn,searchConversations:Rn,clearSearchResults:En,sessions:w,monthlyBudget:E,initialPanelHeight:mP()??200,initialPanelView:vP(),initialPanelCollapsed:bP(),onReorderRepos:Af,onReorderSessions:Rf}),r.jsxs("div",{className:Pi.length>0?"main-wrapper":void 0,children:[(Oi.length>0||Jc)&&r.jsx(Bz,{sessions:Oi,onSwitch:Xs,onClose:xa,onRename:ce,onNewSession:er,onReorder:jf,controlRoom:{open:Jc,active:Tr,onActivate:su,onClose:Ef},pendingPermissionTotal:kl,onJumpToPending:xu}),r.jsx(oU,{visible:!!w.find(U=>U.sessionId===m)?.stdinForwardingDisabled,sessionId:m,onRestart:uu}),pn&&!Tr&&r.jsx(M7,{error:Q,logs:B,onRetry:xs,onStartServer:hs()?pi:void 0}),t==="disconnected"&&!Q&&!ws&&w.length===0&&!Tr&&r.jsx("div",{className:"startup-error-screen","data-testid":"disconnected-screen",children:r.jsxs("div",{className:"startup-error-content",children:[r.jsx("h2",{className:"startup-error-title",children:"Disconnected"}),r.jsx("p",{className:"startup-error-message",children:"Not connected to a Chroxy server."}),r.jsxs("div",{className:"startup-error-actions",children:[hs()&&r.jsx("button",{className:"startup-error-retry-btn startup-error-start-btn",onClick:pi,type:"button","data-testid":"disconnected-start-server-button",children:"Start Server"}),r.jsx("button",{className:"startup-error-retry-btn",onClick:xs,type:"button",children:"Reconnect"})]})]})}),Tr&&r.jsx("div",{className:"main-content","data-testid":"control-room-main",children:r.jsx(DF,{onInvestigate:Rl,onOpenSession:yo,onConfigureRepo:bo,initialTab:wf,forceTab:"settings",forceTabNonce:gl,showConsoleTab:_l,onToggleConsoleTab:U=>{cu(U),H_(U)},interventionPingEnabled:tn,onToggleInterventionPing:U=>{zn(U),F_(U)}})}),ei&&!Tr&&r.jsx(fU,{onNewSession:er,recentSessions:Ol,onResumeSession:bt,className:"main-content"}),r.jsx(mU,{requests:Z,onApprove:ge,onDeny:De}),se.length>0&&r.jsx(pU,{notifications:se,onApprove:Ra,onDeny:$s,onDismiss:ae,onSwitchSession:Xs}),!ei&&!Tr&&r.jsxs(r.Fragment,{children:[r.jsx(A7,{viewMode:y,setViewMode:ct,splitMode:Ir,setSplitMode:co,persistSplitMode:rf,showChatTab:!v,showTerminalTab:g,showConsoleTab:_l,unreadSystemCount:xl,checkpointsOpen:Rr,setCheckpointsOpen:Qc}),r.jsxs("div",{className:`main-content${Rr?" with-checkpoint-panel":""}`,children:[r.jsxs("div",{className:"main-content-primary",children:[Dt&&r.jsx(Xz,{message:Dt.message,attemptedSessionId:Dt.attemptedSessionId,onDismiss:nt}),t==="connecting"?r.jsx(u0,{label:"Connecting..."}):Li?r.jsx(u0,{label:"Switching session..."}):Ir?r.jsx(j7,{direction:Ir,first:r.jsx(Zp,{messages:mu,isStreaming:hn!==null,isBusy:!Ht,chatActivityState:Qi.state,renderMessage:zs,scrollToBottomSignal:re,queuedIds:wn,onCancelQueued:te,workingLabel:Kn,inFlightToolColor:je}),second:r.jsx(AS,{sessions:w,activeSessionId:m,className:"terminal-container"}),onReset:()=>{}}):r.jsxs(r.Fragment,{children:[r.jsx("div",{"data-testid":"chat-pane",style:{display:y==="chat"?"contents":"none"},children:r.jsx(Zp,{messages:mu,isStreaming:hn!==null,isBusy:!Ht,chatActivityState:Qi.state,renderMessage:zs,hidden:y!=="chat",scrollToBottomSignal:re,queuedIds:wn,onCancelQueued:te,workingLabel:Kn,inFlightToolColor:je})}),r.jsx("div",{"data-testid":"terminal-pane",style:{display:y==="terminal"?"contents":"none"},children:r.jsx(AS,{sessions:w,activeSessionId:m,className:"terminal-container"})})]}),y==="files"&&t!=="connecting"&&!Li&&r.jsx(jU,{}),t!=="connecting"&&!Li&&r.jsx("div",{"data-testid":"system-pane",style:{display:y==="system"?"contents":"none"},children:r.jsx(Zp,{messages:Dr,isStreaming:!1,isBusy:!1,renderMessage:zs,hidden:y!=="system"})}),y==="console"&&t!=="connecting"&&!Li&&r.jsx(L7,{}),y==="snapshots"&&t!=="connecting"&&!Li&&r.jsx(B7,{}),y==="pool"&&t!=="connecting"&&!Li&&r.jsx(H7,{}),y==="pages"&&t!=="connecting"&&!Li&&r.jsx(W7,{})]}),Rr&&r.jsx("div",{className:"checkpoint-panel",children:r.jsx(IU,{})}),y==="diff"&&t!=="connecting"&&!Li&&r.jsx(L9,{})]}),zt.length>0&&r.jsx(I7,{}),rn&&r.jsx(Qz,{planHtml:Lr,onApprove:tr,onFeedback:ku}),Wt&&r.jsx(Vz,{evaluatorIteration:Wt.evaluatorIteration,originalDraft:Wt.originalDraft,clarification:Wt.clarification,reasoning:Wt.reasoning,onSubmit:U=>W(U)}),r.jsx(Fz,{}),r.jsx(Kz,{}),r.jsx(Nz,{onSend:Al,onInterrupt:Qs,disabled:!ws,isBusy:!Ht,isStreaming:hn!==null,chatActivityState:Qi.state,placeholder:ws?`Type a message... (${Ge.chatEnterToSend?"Enter":yr("Cmd+Enter")} to send)`:"Connecting...",controlledValue:Ji,onValueChange:El,filePickerFiles:Ee,onFileTrigger:Jt,attachments:ao,onRemoveAttachment:Br,slashCommands:pt,onSlashTrigger:Yt,onImagePaste:Mf,onImageDrop:Es,imageAttachments:Xi,onRemoveImage:Il,onFileAttach:_o,sendOnEnter:Ge.chatEnterToSend,voiceInput:cn.isAvailable?cn:void 0,onEvaluate:ws?Me:void 0,onLargePaste:If,pastedTextBlocks:Nl,onInspectPastedText:wu,onRemovePastedText:jl,userMessageHistory:Ie,highlightThinkingKeywords:un.showThinkingLevel})]})]}),r.jsx(PU,{connectionPhase:t,chatActivityState:Qi.state,tunnelReady:Ns,serverPhase:F,tunnelProgress:J,serverVersion:n,cwd:o??i??void 0,model:Ct||void 0,cost:Lt??void 0,context:D0($t),contextPercent:wo,inputTokens:$t?.inputTokens,outputTokens:$t?.outputTokens,isBusy:!Ht,agentCount:zt.length,onShowQr:ws?Aa:void 0,onShareSession:ws&&m?Bs:void 0,provider:w.find(U=>U.sessionId===m)?.provider,contextWindow:zr??void 0,onCompact:ws&&m?()=>W("/compact"):void 0,interventions:Zt,activeSessionId:m}),r.jsx(aK,{settingsOpen:kf,onSettingsClose:()=>tu(!1),showConsoleTab:_l,onToggleConsoleTab:U=>{cu(U),H_(U)},interventionPingEnabled:tn,onToggleInterventionPing:U=>{zn(U),F_(U)},shortcutHelpOpen:Cf,onShortcutHelpClose:()=>nu(!1),shortcuts:Ri,inspectedPastedTextId:vo,pastedTextBlocks:Nl,onPastedTextClose:()=>ja(null),onRemovePastedText:jl,qrModalOpen:Ai,onQrClose:()=>Cu(!1),qrSvg:So,qrLoading:nr,qrError:Ml,qrShareMode:Dl,qrPairingCode:Eu,onPostPairLinkToDiscord:$r,skillsPanelOpen:$e,skills:Je,skillsCanToggle:!!w.find(U=>U.sessionId===m)?.capabilities?.skillToggle,mismatchedSkillNames:Dn,onActivateSkill:ft,onDeactivateSkill:lt,onAcceptSkillTrust:Ne?ut:void 0,pendingCommunitySkills:Pt,onGrantSkillTrust:Ke?Ae:void 0,skillsPanelCapabilities:{skillTrustGrant:Ke},pendingTrustGrants:Vt,onSkillsPanelClose:()=>Le(!1),sidebarContextMenu:jr,sidebarContextMenuItems:hu,onDismissSidebarContextMenu:fu,showCreateSession:Zc,onCreateSessionClose:()=>{Er(!1),Ls(!1),Ei(null),uo.current=null},onCreateSession:Tl,createSessionInitialCwd:Xc,knownCwds:Tf,existingSessionNames:w.map(U=>U.name),sessionCreateError:pl??void 0,isCreatingSession:Zs,repoPresetDrawer:Ci,onRepoPresetDrawerClose:()=>ro(null),closeConfirmOpen:Mr!==null,closeConfirmMessage:(()=>{const U=w.find(Re=>Re.sessionId===Mr)?.name;return U?`Close "${U}"? The Claude process will be terminated.`:"Close this session? The Claude process will be terminated."})(),onCloseConfirm:()=>{Mr&&ho(Mr),yl(null)},onCloseConfirmCancel:()=>yl(null),toastItems:go,onToastDismiss:U=>{if(U.startsWith("cost-threshold-")){const Qe=U.slice(15),jt=V.getState().sessionStates,Sn=jt[Qe];Sn?.costThresholdWarning&&V.setState({sessionStates:{...jt,[Qe]:{...Sn,costThresholdWarning:{...Sn.costThresholdWarning,dismissedAt:Date.now()}}}});return}const Re=go.find(Qe=>Qe.id===U);Re&&(Re.level==="error"?We(U):Rt(U))},commands:Nf,paletteOpen:Vn,onPaletteClose:()=>Jn(!1),mruList:Vn?l8():void 0}),r.jsx(a9,{isOpen:is,onClose:()=>ya(!1)}),r.jsx(l9,{isOpen:ki,onClose:()=>io(!1)}),r.jsx(u9,{isOpen:hl,onClose:()=>Zi(!1)}),r.jsx(d9,{isOpen:l&&Cr,onClose:()=>V.setState({referencesOpen:!1})})]})}const SK={position:"fixed",inset:0,zIndex:9999,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-primary)",color:"var(--text-primary)",font:'14px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'},xK={maxWidth:560,width:"100%",background:"var(--bg-card)",border:"1px solid var(--scrollbar-thumb)",borderRadius:12,padding:24},wK={margin:"0 0 8px",fontSize:18,fontWeight:600},kK={margin:"0 0 16px",color:"var(--text-dim)"},CK={background:"var(--accent-blue)",color:"var(--bg-primary)",border:"none",borderRadius:8,padding:"8px 16px",fontWeight:600,cursor:"pointer"},EK={marginTop:16,color:"var(--text-dim)"},NK={marginTop:8,maxHeight:240,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:12,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"};class jK extends N.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary] render error:",t,n.componentStack)}handleReload=()=>{window.location.reload()};render(){const{error:t}=this.state;return t?r.jsx("div",{style:SK,role:"alert","data-testid":"error-boundary",children:r.jsxs("div",{style:xK,children:[r.jsx("h1",{style:wK,children:"Something went wrong"}),r.jsx("p",{style:kK,children:"The dashboard hit an unexpected error and couldn't render this view."}),r.jsx("button",{type:"button",style:CK,onClick:this.handleReload,"data-testid":"error-boundary-reload",children:"Reload"}),r.jsxs("details",{style:EK,children:[r.jsx("summary",{children:"Error detail"}),r.jsxs("pre",{style:NK,children:[t.message,t.stack?`
|
|
110
|
-
|
|
111
|
-
${t.stack}`:""]})]})]})}):this.props.children}}VC.createRoot(document.getElementById("root")).render(r.jsx(N.StrictMode,{children:r.jsx(jK,{children:r.jsx(_K,{})})}));
|