From ce02e2fbf61e5667c225fbdc292db47b6ee10bcb Mon Sep 17 00:00:00 2001 From: chenxi Date: Fri, 14 Aug 2026 17:39:49 +0800 Subject: [PATCH] feat(doctor): add verified repair pipeline Add read-only cross-platform diagnostics, typed persisted repair plans, registered SAFE and consent actions, verification, interruption reconciliation, path memory, sanitized support reports, and explicitly authorized PR submission. Cover source, wheel, frozen, Web, Desktop, CLI, backend, daemon, port, stale-state, and bootstrap recovery paths while preserving existing runtime behavior. --- .github/workflows/tests.yml | 3 + README.md | 14 +- README.zh-CN.md | 12 +- argus_doctor.py | 359 ++++++++++ argus_skill/agent_cli/runner_backend.py | 39 +- argus_skill/apps/_watch.py | 6 +- argus_skill/apps/cli/_core.py | 208 +++++- argus_skill/apps/cli/_parser.py | 93 ++- argus_skill/apps/tui_launcher.py | 7 +- argus_skill/core/runtime_env.py | 55 +- argus_skill/daemon/_life_worker_boot.py | 19 +- argus_skill/maintenance/__init__.py | 13 + argus_skill/maintenance/doctor.py | 485 ++++++++++++++ argus_skill/maintenance/models.py | 106 +++ argus_skill/maintenance/repair.py | 627 ++++++++++++++++++ argus_skill/release_manifest.json | 4 +- argus_skill/release_tools/build_release.py | 6 +- argus_skill/team/curator.py | 57 +- argus_skill/team/task_board.py | 16 + argus_skill/tools/ppt_master.py | 13 +- .../tools/subagent/_experiment_preflight.py | 5 +- argus_skill/tools/subagent/_registry.py | 16 +- argus_skill/webapi/routes/meta.py | 28 + desktop/src/renderer/index.html | 1 + desktop/src/renderer/main.ts | 18 + docs/doctor-repair-pipeline.md | 117 ++++ frontend/core/src/release.generated.ts | 4 +- frontend/tui/bundle/argus.mjs | 2 +- ....js => ResearchWorkbenchPanel-BOPEGTC6.js} | 6 +- .../{index-7NNAUeAk.js => index-DYvAJ_cb.js} | 6 +- .../{pdf-BdyXXgZL.js => pdf-Dzq_asqX.js} | 2 +- frontend/web/dist/index.html | 2 +- pyproject.toml | 2 + tests/agent_cli/test_copilot_acp.py | 6 +- tests/apps/test_cli_parser.py | 49 +- tests/core/test_runtime_env.py | 66 +- .../test_final_submission_cert_persists.py | 3 + tests/life/test_state_machine_guards.py | 4 +- tests/maintenance/test_repair_pipeline.py | 384 +++++++++++ tests/release_tools/test_build_release.py | 16 +- .../test_research_visualization_router.py | 2 +- tests/team/test_curator.py | 23 +- tests/team/test_task_board.py | 8 + tests/test_aris_adapted_skills.py | 7 +- tests/test_bootstrap_doctor.py | 96 +++ tests/test_copilot_home_isolation.py | 3 +- tests/test_doctor.py | 46 ++ tests/test_grok_backend.py | 32 +- tests/test_harbor_integration.py | 42 +- tests/test_pi_backend.py | 2 +- tests/test_runner_binary_resolution.py | 88 +-- tests/tools/test_capability_vault.py | 4 +- tests/tools/test_gpu_keepalive_setup.py | 28 +- tests/tools/test_lean_check.py | 10 +- tests/tools/test_setup_codex_config.py | 8 +- tests/tools/test_subagent_supervisor.py | 15 + tests/webapi/test_server_m0.py | 21 + 57 files changed, 3135 insertions(+), 179 deletions(-) create mode 100644 argus_doctor.py create mode 100644 argus_skill/maintenance/__init__.py create mode 100644 argus_skill/maintenance/doctor.py create mode 100644 argus_skill/maintenance/models.py create mode 100644 argus_skill/maintenance/repair.py create mode 100644 docs/doctor-repair-pipeline.md rename frontend/web/dist/assets/{ResearchWorkbenchPanel-D4WnlzR6.js => ResearchWorkbenchPanel-BOPEGTC6.js} (99%) rename frontend/web/dist/assets/{index-7NNAUeAk.js => index-DYvAJ_cb.js} (99%) rename frontend/web/dist/assets/{pdf-BdyXXgZL.js => pdf-Dzq_asqX.js} (99%) create mode 100644 tests/maintenance/test_repair_pipeline.py create mode 100644 tests/test_bootstrap_doctor.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3db197cd9..a593ce0e1 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -60,7 +60,10 @@ env: tests/daemon/test_spawn_helper.py tests/daemon/test_windows_daemon_control.py tests/daemon/test_windows_terminal_process.py + tests/maintenance/test_repair_pipeline.py tests/test_agent_cli_backend.py + tests/test_bootstrap_doctor.py + tests/test_doctor.py tests/webapi/test_commands_m1.py tests/webapi/test_server_m0.py tests/webapi/test_workspace_v2.py diff --git a/README.md b/README.md index 16516f494..cd4f814a3 100644 --- a/README.md +++ b/README.md @@ -157,10 +157,20 @@ argus ``` ```bash -argus --doctor # verify the installation -argus --status # inspect the current runtime +argus doctor # read-only cross-platform diagnosis +argus -doctor --fix-safe # apply registered SAFE repairs, then verify +argus repair --plan --json # persist a reviewable repair plan +argus repair --apply --yes +argus repair --prepare-pr # create a sanitized report; never auto-publishes +argus --status # inspect the current runtime ``` +Doctor never executes recommendation text. Repairs come from a closed action +registry, revalidate the target immediately before mutation, persist an audit +history under `ARGUS_SKILL_HOME/repairs/`, and require explicit consent for +environment changes or external publication. See +[Doctor and Repair Pipeline](docs/doctor-repair-pipeline.md). + ### Codex / Claude Code plugin One-command installation and usage: [docs/plugin.md](docs/plugin.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 34d68cc39..186b48878 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -158,10 +158,18 @@ argus ``` ```bash -argus --doctor # 检查安装与后端 -argus --status # 查看当前运行状态 +argus doctor # 只读跨平台诊断 +argus -doctor --fix-safe # 执行已注册的 SAFE 修复并复验 +argus repair --plan --json # 持久化可审查修复计划 +argus repair --apply --yes +argus repair --prepare-pr # 生成脱敏报告,不会自动发布 +argus --status # 查看当前运行状态 ``` +Doctor 不会执行诊断文本中的任意命令。所有修复来自封闭动作注册表,执行前会重新验证 +目标身份,审计历史保存在 `ARGUS_SKILL_HOME/repairs/`;环境变更和外部发布必须显式 +授权。完整约束见 [Doctor 与 Repair Pipeline](docs/doctor-repair-pipeline.md)。 + ### Codex / Claude Code 插件 一键安装与使用:[docs/plugin.md](docs/plugin.md)。 diff --git a/argus_doctor.py b/argus_doctor.py new file mode 100644 index 000000000..dc654723c --- /dev/null +++ b/argus_doctor.py @@ -0,0 +1,359 @@ +"""Standalone Argus bootstrap diagnostics using only the Python standard library.""" +from __future__ import annotations + +import argparse +import json +import os +import platform +import shutil +import socket +import subprocess +import sys +from pathlib import Path + + +def _finding(code, name, ok, detail, fix=""): + return { + "code": code, + "name": name, + "ok": bool(ok), + "detail": str(detail), + "fix": "" if ok else str(fix), + } + + +def _checkout(path): + candidate = Path(path).expanduser().resolve() + return candidate if (candidate / "pyproject.toml").is_file() and (candidate / "argus_skill").is_dir() else None + + +def _find_checkout(explicit): + if explicit: + return _checkout(explicit) + candidates = [ + os.environ.get("ARGUS_DESKTOP_REPO_ROOT", ""), + Path(__file__).resolve().parent, + Path.cwd(), + Path.home() / "Argus", + ] + for candidate in candidates: + if not candidate: + continue + found = _checkout(candidate) + if found is not None: + return found + return None + + +def _venv_python(root): + if root is None: + return None + relative = Path(".venv/Scripts/python.exe") if os.name == "nt" else Path(".venv/bin/python") + candidate = root / relative + return candidate if candidate.is_file() else None + + +def _command_version(executable, flag="--version"): + try: + command = ( + [str(executable), "-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()"] + if Path(str(executable)).stem.casefold() == "powershell" + else [str(executable), flag] + ) + result = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=5, + ) + except (OSError, subprocess.SubprocessError) as exc: + return False, f"{type(exc).__name__}: {exc}" + text = (result.stdout or result.stderr).strip().splitlines() + return result.returncode == 0, text[0] if text else f"exit {result.returncode}" + + +def run_bootstrap_doctor(root=None): + checkout = _find_checkout(root) + findings = [] + findings.append(_finding( + "ARGUS-HOST-001", + "host", + True, + f"{platform.system()} {platform.release()} {platform.machine()}", + )) + python_ok = sys.version_info >= (3, 11) + findings.append(_finding( + "ARGUS-PYTHON-001", + "bootstrap Python", + python_ok, + f"{platform.python_version()} at {sys.executable}", + "install Python 3.11 or newer using the platform's official installer", + )) + findings.append(_finding( + "ARGUS-INSTALL-001", + "source checkout", + checkout is not None, + str(checkout) if checkout is not None else "Argus source checkout not found", + "pass --root , or restore the checkout before running full Doctor", + )) + + checkout_runtime = _venv_python(checkout) + runtime = checkout_runtime or Path(sys.executable) + try: + result = subprocess.run( + [str(runtime), "-c", "import argus_skill; print(argus_skill.__version__)"], + cwd=str(checkout) if checkout is not None else None, + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=15, + env={**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}, + ) + import_ok = result.returncode == 0 + detail = (result.stdout or result.stderr).strip() or f"exit {result.returncode}" + except (OSError, subprocess.SubprocessError) as exc: + import_ok = False + detail = f"{type(exc).__name__}: {exc}" + findings.append(_finding( + "ARGUS-PYTHON-002", + "Argus Python environment", + checkout_runtime is not None or import_ok, + ( + str(checkout_runtime) if checkout_runtime is not None + else f"current interpreter is usable without checkout .venv: {runtime}" + if import_ok else "checkout .venv is missing and current interpreter cannot import Argus" + ), + "recreate .venv with Python 3.11+ and reinstall the checkout", + )) + findings.append(_finding( + "ARGUS-PYTHON-003", + "Argus Core import", + import_ok, + detail, + "run the selected Python with `-m pip install -e .` after reviewing the environment", + )) + + commands = [("ARGUS-GIT-001", "git"), ("ARGUS-NODE-001", "node")] + if os.name == "nt": + commands.append(("ARGUS-POWERSHELL-001", "powershell")) + for code, name in commands: + executable = shutil.which(name) + ok, detail = _command_version(executable) if executable else (False, f"{name} not found on PATH") + findings.append(_finding( + code, + name, + bool(executable) and ok, + detail, + f"install a supported {name} release and ensure it is on PATH", + )) + + if checkout is not None: + assets = { + "Web": checkout / "frontend" / "web" / "dist" / "index.html", + "TUI": checkout / "frontend" / "tui" / "bundle" / "argus.mjs", + } + missing = [label for label, path in assets.items() if not path.is_file()] + findings.append(_finding( + "ARGUS-WEB-001", + "frontend assets", + not missing, + "Web and TUI assets present" if not missing else f"missing: {', '.join(missing)}", + "restore a complete release checkout or rebuild the declared frontend assets", + )) + desktop = checkout / "desktop" + if (desktop / "package.json").is_file(): + electron = desktop / "node_modules" / "electron" + electron_installed = electron.is_dir() + electron_ready = ( + (electron / "path.txt").is_file() + and ( + os.name != "nt" + or (electron / "dist" / "electron.exe").is_file() + ) + ) if electron_installed else True + findings.append(_finding( + "ARGUS-DESKTOP-001", + "Desktop runtime", + electron_ready, + ( + "Electron runtime present" if electron_installed and electron_ready + else "Desktop dependencies not installed (optional for CLI/Web)" if not electron_installed + else "Electron runtime binary missing" + ), + "run `npm --prefix desktop ci`; Desktop postinstall downloads the declared Electron runtime", + )) + + web_host = os.environ.get("ARGUS_SKILL_WEB_HOST", "127.0.0.1") + try: + web_port = int(os.environ.get("ARGUS_SKILL_WEB_PORT", "8799")) + except ValueError: + web_port = 8799 + try: + with socket.create_connection((web_host, web_port), timeout=0.4): + web_status = "listener reachable" + except OSError: + web_status = "no listener (normal when Argus is stopped)" + findings.append(_finding( + "ARGUS-PORT-001", + "Web endpoint", + True, + f"{web_host}:{web_port} — {web_status}", + )) + + return { + "schema_version": 1, + "mode": "bootstrap", + "ok": all(item["ok"] for item in findings), + "target_host": platform.node(), + "findings": findings, + } + + +def _run_repair_command(command, *, cwd, timeout): + try: + completed = subprocess.run( + [str(item) for item in command], + cwd=str(cwd), + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout, + env={**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}, + ) + except (OSError, subprocess.SubprocessError) as exc: + return {"status": "failed", "detail": f"{type(exc).__name__}: {exc}"} + return { + "status": "applied" if completed.returncode == 0 else "failed", + "returncode": completed.returncode, + "detail": (completed.stderr or completed.stdout or "").strip()[-4000:], + } + + +def run_bootstrap_repair(root, *, install=False, desktop=False): + """Execute only explicit bootstrap actions from this closed registry.""" + checkout = _find_checkout(root) + if checkout is None: + return [{ + "id": "restore_checkout", + "risk": "manual", + "status": "manual_required", + "detail": "a complete checkout is required before bootstrap repair", + }] + actions = [] + runtime = _venv_python(checkout) + if install: + if runtime is None: + created = _run_repair_command( + [sys.executable, "-m", "venv", str(checkout / ".venv")], + cwd=checkout, + timeout=180, + ) + actions.append({"id": "create_venv", "risk": "consent", **created}) + runtime = _venv_python(checkout) + if runtime is None: + actions.append({ + "id": "install_editable", + "risk": "consent", + "status": "failed", + "detail": "virtual-environment interpreter is unavailable", + }) + else: + installed = _run_repair_command( + [runtime, "-m", "pip", "install", "-e", str(checkout)], + cwd=checkout, + timeout=600, + ) + actions.append({"id": "install_editable", "risk": "consent", **installed}) + if desktop: + npm = shutil.which("npm.cmd" if os.name == "nt" else "npm") + package = checkout / "desktop" / "package.json" + if not npm or not package.is_file(): + actions.append({ + "id": "install_desktop", + "risk": "consent", + "status": "failed", + "detail": "npm or desktop/package.json is unavailable", + }) + else: + installed = _run_repair_command( + [npm, "ci"], cwd=package.parent, timeout=900, + ) + actions.append({"id": "install_desktop", "risk": "consent", **installed}) + return actions + + +def _render(report): + lines = ["argus-doctor — bootstrap diagnostics", ""] + for item in report["findings"]: + lines.append(f"{'✓' if item['ok'] else '✗'} {item['code']} {item['name']}: {item['detail']}") + if item["fix"]: + lines.append(f" fix: {item['fix']}") + if report.get("repairs"): + lines.extend(["", "repairs:"]) + for action in report["repairs"]: + lines.append( + f" {action.get('status', 'unknown')}: " + f"{action.get('id', 'unknown')} ({action.get('risk', 'manual')})" + ) + lines.append("") + lines.append("all bootstrap checks passed" if report["ok"] else "bootstrap issues found") + return "\n".join(lines) + + +def main(argv=None): + if os.name == "nt": + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if callable(reconfigure): + reconfigure(encoding="utf-8", errors="replace") + parser = argparse.ArgumentParser(prog="argus-doctor") + parser.add_argument("--root", help="Argus source checkout to inspect") + parser.add_argument("--json", action="store_true", help="print machine-readable findings") + parser.add_argument( + "--repair-install", + action="store_true", + help="recreate the checkout venv when missing and reinstall editable Argus", + ) + parser.add_argument( + "--repair-desktop", + action="store_true", + help="run the locked Desktop npm install, including Electron postinstall", + ) + parser.add_argument("--yes", action="store_true", help="authorize bootstrap mutations") + args = parser.parse_args(argv) + if (args.repair_install or args.repair_desktop) and not args.yes: + sys.stderr.write("argus-doctor: bootstrap repair requires --yes\n") + return 3 + repairs = run_bootstrap_repair( + args.root, + install=args.repair_install, + desktop=args.repair_desktop, + ) if (args.repair_install or args.repair_desktop) else [] + report = run_bootstrap_doctor(args.root) + if repairs: + report["repairs"] = repairs + report["repair_ok"] = all(item.get("status") == "applied" for item in repairs) + report["ok"] = bool(report["ok"] and report["repair_ok"]) + output = ( + json.dumps(report, ensure_ascii=False, indent=2) + if args.json + else _render(report) + ) + buffer = getattr(sys.stdout, "buffer", None) + if os.name == "nt" and buffer is not None: + buffer.write((output + "\n").encode("utf-8")) + buffer.flush() + else: + print(output) + return 0 if report["ok"] else 3 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/argus_skill/agent_cli/runner_backend.py b/argus_skill/agent_cli/runner_backend.py index e0550429a..17bb9f18a 100644 --- a/argus_skill/agent_cli/runner_backend.py +++ b/argus_skill/agent_cli/runner_backend.py @@ -63,6 +63,29 @@ def default_runner_bin(backend: RunnerBackend) -> str: return "codex" +def _resolve_explicit_candidate(candidate: Path) -> str | None: + # Test fixtures, portable shims, and some user-local launchers are valid + # extensionless files even on Windows. ``shutil.which`` applies PATHEXT and + # can miss those exact candidates, so honor an explicitly located file + # before probing sibling .exe/.cmd variants. + if candidate.is_file() and (os.name == "nt" or os.access(candidate, os.X_OK)): + return str(candidate) + resolved = shutil.which(str(candidate)) + if resolved: + return resolved + if os.name != "nt" or candidate.suffix: + return None + extensions = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) + wanted = {f"{candidate.name}{extension}".casefold() for extension in extensions if extension} + try: + for entry in candidate.parent.iterdir(): + if entry.is_file() and entry.name.casefold() in wanted: + return str(entry) + except OSError: + return None + return None + + def resolve_runner_bin( backend: RunnerBackend | str | None, configured: str | None = None, @@ -78,10 +101,17 @@ def resolve_runner_bin( return resolved if Path(expanded).parent != Path("."): return None + for entry in os.environ.get("PATH", "").split(os.pathsep): + if not entry: + continue + resolved = _resolve_explicit_candidate(Path(entry) / expanded) + if resolved: + return resolved if chosen == BACKEND_OPENCODE: opencode_home = Path.home() / ".opencode" / "bin" / expanded - if opencode_home.is_file() and os.access(opencode_home, os.X_OK): - return str(opencode_home) + resolved = _resolve_explicit_candidate(opencode_home) + if resolved: + return resolved if chosen == BACKEND_DSH: # dsh is installed through the nvm-managed Node toolchain, whose bin # directory is absent from non-interactive PATHs (the daemon may be @@ -93,8 +123,9 @@ def resolve_runner_bin( if candidate.is_file() and os.access(candidate, os.X_OK): return str(candidate) user_local = Path.home() / ".local" / "bin" / expanded - if user_local.is_file() and os.access(user_local, os.X_OK): - return str(user_local) + resolved = _resolve_explicit_candidate(user_local) + if resolved: + return resolved return None diff --git a/argus_skill/apps/_watch.py b/argus_skill/apps/_watch.py index bb8f25009..227dd8ee3 100644 --- a/argus_skill/apps/_watch.py +++ b/argus_skill/apps/_watch.py @@ -501,7 +501,11 @@ def _raise_keyboard_interrupt(_signum: int, _frame: Any) -> None: previous_handlers: dict[int, Any] = {} try: - for signum in (signal.SIGINT, getattr(signal, "SIGTERM", None)): + for signum in ( + signal.SIGINT, + getattr(signal, "SIGTERM", None), + getattr(signal, "SIGBREAK", None), + ): if signum is None: continue previous_handlers[int(signum)] = signal.getsignal(signum) diff --git a/argus_skill/apps/cli/_core.py b/argus_skill/apps/cli/_core.py index 334e11cea..8339a4a69 100644 --- a/argus_skill/apps/cli/_core.py +++ b/argus_skill/apps/cli/_core.py @@ -276,8 +276,12 @@ def _lifetime_entry_error(args: argparse.Namespace) -> str: def main(argv: list[str] | None = None) -> int: - from ...core.runtime_env import load_backend_runtime_env + from ...core.runtime_env import ( + configure_framework_python_env, + load_backend_runtime_env, + ) + configure_framework_python_env() load_backend_runtime_env() parser = build_parser() args = parser.parse_args(argv) @@ -364,12 +368,13 @@ def main(argv: list[str] | None = None) -> int: if readiness_modifier and not ( args.setup or getattr(args, "doctor", False) + or getattr(args, "command", None) in {"doctor", "repair"} or args.daemon or args.daemon_fg ): sys.stderr.write( "argus-skill: --backend / --auth-mode / --allow-prerelease " - "require --setup, --doctor, --daemon, or --daemon-fg\n" + "require --setup, doctor/repair, --doctor, --daemon, or --daemon-fg\n" ) return 2 if action_flags > 1: @@ -386,6 +391,14 @@ def main(argv: list[str] | None = None) -> int: "are mutually exclusive.\n" ) return 2 + if args.command == "doctor": + return _run_with_path_resolution_errors(lambda: _cmd_doctor(args)) + if args.command == "repair": + try: + return _run_with_path_resolution_errors(lambda: _cmd_repair(args)) + except (FileNotFoundError, PermissionError, RuntimeError, ValueError) as exc: + sys.stderr.write(f"argus-skill: repair refused: {exc}\n") + return 3 if getattr(args, "update", False) or args.command == "update": from ..update import run_update @@ -663,20 +676,199 @@ def _cmd_daemon_start(args: argparse.Namespace, *, foreground: bool) -> int: return int(receipt.result.get("rc", 3 if receipt.status != "applied" else 0)) -def _cmd_doctor(args: argparse.Namespace) -> int: - from ...webapi.diagnostics import render_report, run_diagnostics +def _doctor_checks(args: argparse.Namespace): + from ...webapi.diagnostics import run_diagnostics bundle = _resolve_project_bundle(args) - checks = run_diagnostics( + legacy = bool(getattr(args, "doctor", False)) + return bundle, run_diagnostics( bundle.project.root, global_root=bundle.global_root, backend=getattr(args, "backend", None), auth_mode=getattr(args, "auth_mode", None), - probe_auth=True, + probe_auth=legacy or bool(getattr(args, "deep", False)), allow_prerelease=bool(getattr(args, "allow_prerelease", False)), ) - sys.stdout.write(render_report(checks) + "\n") - return 0 if all(check.ok for check in checks) else 3 + + +def _doctor_payload(checks, *, verification: bool = False) -> dict[str, Any]: + codes = { + "backend preflight": "ARGUS-BACKEND-001", + "model API capability": "ARGUS-BACKEND-002", + "daemon": "ARGUS-DAEMON-001", + "lock sanity": "ARGUS-STATE-001", + "empty session": "ARGUS-STATE-002", + } + return { + "schema_version": 1, + "ok": all(check.ok for check in checks), + "verification": verification, + "checks": [ + { + "code": codes.get(check.name, "ARGUS-CHECK-001"), + "name": check.name, + "ok": check.ok, + "detail": check.detail, + "fix": check.fix, + } + for check in checks + ], + } + + +def _maintenance_context(args: argparse.Namespace): + from ...core.runtime_identity import source_root + from ...maintenance.doctor import DoctorContext + + global_root = _resolve_global_root(args) + resume = str(getattr(args, "resume", "") or "").strip() + project_root = ( + core_paths.session_state_root(resume, root=global_root) + if resume else global_root + ) + source = source_root() + checkout = source if (source / "pyproject.toml").is_file() else None + from ...maintenance.repair import read_path_memory + + remembered = read_path_memory(global_root) + if checkout is None and remembered.get("checkout"): + candidate = Path(str(remembered["checkout"])).expanduser() + if (candidate / "pyproject.toml").is_file(): + checkout = candidate.resolve() + install_mode = ( + "frozen" if getattr(sys, "frozen", False) + else "source" if checkout is not None + else "wheel" + ) + desktop_user_data = None + if remembered.get("desktop_user_data"): + desktop_user_data = Path(str(remembered["desktop_user_data"])).expanduser() + elif os.name == "nt" and os.environ.get("APPDATA"): + desktop_user_data = Path(os.environ["APPDATA"]) / "argus-desktop" + return DoctorContext( + global_root=global_root, + project_root=project_root, + checkout=checkout, + python_executable=Path(sys.executable), + web_host=str(getattr(args, "web_host", "127.0.0.1") or "127.0.0.1"), + web_port=int(getattr(args, "web_port", 8799) or 8799), + desktop_user_data=desktop_user_data, + install_mode=install_mode, + ) + + +def _cmd_doctor(args: argparse.Namespace) -> int: + import json + + from ...maintenance.doctor import render_full_report, run_full_doctor + from ...maintenance.repair import apply_plan, create_plan + + context = _maintenance_context(args) + report = run_full_doctor( + context, + include_backend=True, + probe_auth=bool(getattr(args, "deep", False)), + ) + repair_payload = None + if bool(getattr(args, "fix_safe", False)): + plan = create_plan(context, [item for item in report.findings if not item.ok]) + repaired = apply_plan(context, plan.plan_id, safe_only=True) + repair_payload = repaired.to_jsonable() + report = run_full_doctor( + context, + include_backend=True, + probe_auth=bool(getattr(args, "deep", False)), + ) + payload = report.to_jsonable() + payload["verification"] = bool(getattr(args, "verify", False)) + if repair_payload is not None: + payload["repair"] = repair_payload + if bool(getattr(args, "json", False)): + sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + else: + sys.stdout.write(render_full_report(report) + "\n") + if repair_payload is not None: + sys.stdout.write( + f"safe repair plan {repair_payload['plan_id']}: " + f"{repair_payload['status']}\n" + ) + return 0 if report.ok else 3 + + +def _cmd_repair(args: argparse.Namespace) -> int: + import json + + from ...maintenance.doctor import render_full_report, run_full_doctor + from ...maintenance.repair import ( + apply_plan, + create_plan, + prepare_pr_report, + submit_pr, + ) + + context = _maintenance_context(args) + json_output = bool(getattr(args, "json", False)) + if bool(getattr(args, "plan", False)) or bool(getattr(args, "safe", False)): + before = run_full_doctor(context, include_backend=True) + plan = create_plan(context, [item for item in before.findings if not item.ok]) + if bool(getattr(args, "plan", False)): + payload = { + "schema_version": 1, + "mode": "plan", + "plan_id": plan.plan_id, + "path": str(plan.path), + "actions": [item.to_jsonable() for item in plan.actions], + "diagnostics": before.to_jsonable(), + } + rc = 0 + else: + result = apply_plan(context, plan.plan_id, safe_only=True) + payload = result.to_jsonable() + rc = 0 if result.status in {"completed", "already_applied"} else 3 + elif getattr(args, "apply", None): + result = apply_plan( + context, + str(args.apply), + confirmed=bool(getattr(args, "yes", False)), + ) + payload = result.to_jsonable() + rc = 0 if result.status in {"completed", "already_applied"} else 3 + elif getattr(args, "prepare_pr", None): + report_path = prepare_pr_report(context, str(args.prepare_pr)) + payload = {"schema_version": 1, "mode": "prepare-pr", "path": str(report_path)} + rc = 0 + elif getattr(args, "submit_pr", None): + url = submit_pr( + context, + str(args.submit_pr), + confirmed=bool(getattr(args, "yes", False)), + ) + payload = {"schema_version": 1, "mode": "submit-pr", "url": url} + rc = 0 + else: # pragma: no cover - argparse requires one mode + raise ValueError("repair mode is required") + + if json_output: + sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + else: + if payload.get("diagnostics"): + from ...maintenance.models import DoctorFinding, DoctorReport + raw = payload["diagnostics"] + findings = tuple(DoctorFinding( + code=item["code"], scope=item["scope"], severity=item["severity"], + ok=item["ok"], status=item["status"], detail=item["detail"], + evidence=item.get("evidence") or {}, + repair_action_ids=tuple(item.get("repair_action_ids") or ()), + recommendation=item.get("recommendation") or "", + ) for item in raw["findings"]) + sys.stdout.write(render_full_report(DoctorReport( + schema_version=1, + target_fingerprint=raw["target_fingerprint"], + generated_at=raw["generated_at"], + findings=findings, + )) + "\n") + sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + return rc def _cmd_daemon_stop(args: argparse.Namespace) -> int: diff --git a/argus_skill/apps/cli/_parser.py b/argus_skill/apps/cli/_parser.py index d80785f6f..d10d45fd9 100644 --- a/argus_skill/apps/cli/_parser.py +++ b/argus_skill/apps/cli/_parser.py @@ -13,7 +13,8 @@ First-time setup and diagnostics: argus --setup - argus --doctor + argus doctor + argus repair --plan argus update Automation: @@ -290,6 +291,32 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="run backend/auth, capability, daemon, and state diagnostics", ) + capability_grp.add_argument( + "-doctor", + dest="doctor", + action="store_true", + help=argparse.SUPPRESS, + ) + capability_grp.add_argument( + "--fix-safe", + action="store_true", + help="with --doctor/-doctor: apply registered SAFE repairs and verify", + ) + capability_grp.add_argument( + "--json", + action="store_true", + help="with --doctor/-doctor: print stable machine-readable findings", + ) + capability_grp.add_argument( + "--deep", + action="store_true", + help="with --doctor/-doctor: include bounded backend authentication probes", + ) + capability_grp.add_argument( + "--verify", + action="store_true", + help="with --doctor/-doctor: label the run as post-repair verification", + ) capability_grp.add_argument( "--backend", choices=("copilot", "codex", "claude", "opencode", "pi", "grok", "qoder", "dsh"), @@ -445,6 +472,70 @@ def build_parser() -> argparse.ArgumentParser: ) subparsers = parser.add_subparsers(dest="command") + doctor_parser = subparsers.add_parser( + "doctor", + help="Run read-only Argus diagnostics", + ) + doctor_parser.add_argument( + "--json", + action="store_true", + help="print a stable machine-readable diagnostic report", + ) + doctor_parser.add_argument( + "--deep", + action="store_true", + help="include backend authentication probes", + ) + doctor_parser.add_argument( + "--verify", + action="store_true", + help="label this run as post-repair verification", + ) + doctor_parser.add_argument( + "--fix-safe", + action="store_true", + help="apply registered SAFE repairs, then rerun Doctor", + ) + repair_parser = subparsers.add_parser( + "repair", + help="Plan or apply registered Argus recovery actions", + ) + repair_mode = repair_parser.add_mutually_exclusive_group(required=True) + repair_mode.add_argument( + "--plan", + action="store_true", + help="show deterministic repair recommendations without modifying state", + ) + repair_mode.add_argument( + "--safe", + action="store_true", + help="plan and apply only registered SAFE actions, then verify", + ) + repair_mode.add_argument( + "--apply", + metavar="PLAN_ID", + help="apply one persisted plan (CONSENT actions also require --yes)", + ) + repair_mode.add_argument( + "--prepare-pr", + metavar="PLAN_ID", + help="write a sanitized upstream repair report without publishing it", + ) + repair_mode.add_argument( + "--submit-pr", + metavar="PLAN_ID", + help="submit an explicitly authorized prepared repository repair", + ) + repair_parser.add_argument( + "--yes", + action="store_true", + help="confirm CONSENT actions or external PR publication", + ) + repair_parser.add_argument( + "--json", + action="store_true", + help="print a stable machine-readable repair result", + ) subparsers.add_parser( "update", help="Safely fast-forward and reinstall this source checkout", diff --git a/argus_skill/apps/tui_launcher.py b/argus_skill/apps/tui_launcher.py index d59304c0e..ee1701290 100644 --- a/argus_skill/apps/tui_launcher.py +++ b/argus_skill/apps/tui_launcher.py @@ -8,12 +8,13 @@ import sys from pathlib import Path -_PYTHON_ADMIN_COMMANDS = frozenset({"update", "wiki", "learn"}) +_PYTHON_ADMIN_COMMANDS = frozenset({"doctor", "repair", "update", "wiki", "learn"}) _PYTHON_ADMIN_FLAGS = frozenset( { "-h", "--help", + "-doctor", "--version", "--update", "--daemon", @@ -72,6 +73,10 @@ { "--drain", "--force", + "--fix-safe", + "--json", + "--deep", + "--verify", "--gc-dry-run", "--no-daemon", "--new", diff --git a/argus_skill/core/runtime_env.py b/argus_skill/core/runtime_env.py index 666f04db4..fa17cdf54 100644 --- a/argus_skill/core/runtime_env.py +++ b/argus_skill/core/runtime_env.py @@ -3,6 +3,7 @@ import os import shlex import stat as stat_module +import sys from collections.abc import MutableMapping from pathlib import Path @@ -17,6 +18,58 @@ }) +def _path_key(value: str) -> str: + """Return a platform-aware comparison key without changing the PATH entry.""" + return os.path.normcase(os.path.abspath(os.path.expanduser(value))) + + +def configure_framework_python_env( + env: MutableMapping[str, str] | None = None, + *, + executable: str | os.PathLike[str] | None = None, +) -> MutableMapping[str, str]: + """Expose the owning Argus interpreter and make bare ``python`` prefer it. + + Console-script launchers and unactivated Windows virtual environments can + run Argus with a correct interpreter while leaving an unrelated Anaconda or + system Python first on ``PATH``. Agent CLIs inherit that mismatch and then + fail to import Argus helpers. Preserve an explicit framework interpreter, + keep frozen-runtime command shims first, and de-duplicate PATH using the + host platform's separator and case rules. + """ + target_env = env if env is not None else os.environ + framework_python = str( + target_env.get("ARGUS_SKILL_PYTHON") or executable or sys.executable + ).strip() + target_env["ARGUS_SKILL_PYTHON"] = framework_python + if os.name == "nt": + target_env.setdefault("PYTHONUTF8", "1") + target_env.setdefault("PYTHONIOENCODING", "utf-8") + + preferred: list[str] = [] + runtime_bin = str(target_env.get("ARGUS_SKILL_RUNTIME_BIN") or "").strip() + if runtime_bin: + preferred.append(runtime_bin) + python_path = Path(framework_python).expanduser() + if python_path.parent != Path(".") or python_path.is_absolute(): + preferred.append(str(python_path.resolve().parent)) + + existing = str(target_env.get("PATH") or "").split(os.pathsep) + ordered: list[str] = [] + seen: set[str] = set() + for entry in [*preferred, *existing]: + clean = entry.strip() + if not clean: + continue + key = _path_key(clean) + if key in seen: + continue + seen.add(key) + ordered.append(clean) + target_env["PATH"] = os.pathsep.join(ordered) + return target_env + + def load_backend_runtime_env( env: MutableMapping[str, str] | None = None, *, @@ -62,4 +115,4 @@ def load_backend_runtime_env( return loaded -__all__ = ["load_backend_runtime_env"] +__all__ = ["configure_framework_python_env", "load_backend_runtime_env"] diff --git a/argus_skill/daemon/_life_worker_boot.py b/argus_skill/daemon/_life_worker_boot.py index 17d8df2ac..f5abd60eb 100644 --- a/argus_skill/daemon/_life_worker_boot.py +++ b/argus_skill/daemon/_life_worker_boot.py @@ -13,12 +13,11 @@ import logging import os -import sys import time from contextlib import nullcontext -from pathlib import Path from typing import Any +from ..core.runtime_env import configure_framework_python_env from ..life.memory import GlobalMemory, LifeMemory, MemoryBundle, ProjectMemory from ._life_worker_identity import ( _apply_continuous_suppression, @@ -103,20 +102,12 @@ def _rf_bootstrap_environment(self) -> None: self._install_signal_handlers() self._started_at = time.time() - # Ensure ARGUS_SKILL_PYTHON is set in the process environment so - # all child processes can find the argus_skill package. Without this, - # shells spawned by codex exec fall back to /usr/bin/python which cannot - # import argus_skill. - _argus_python = os.environ.get("ARGUS_SKILL_PYTHON") or sys.executable - os.environ.setdefault("ARGUS_SKILL_PYTHON", _argus_python) + # Keep every child shell on the same framework interpreter even when + # Argus was launched through a Windows console script without activating + # its virtual environment first. + configure_framework_python_env() if self.config.global_root is not None: os.environ["ARGUS_SKILL_HOME"] = str(self.config.global_root.resolve()) - # Also prepend the venv bin dir to PATH so bare `python` resolves - # to the venv interpreter in child shells. - _venv_bin = str(Path(_argus_python).resolve().parent) - _current_path = os.environ.get("PATH", "") - if _venv_bin not in _current_path: - os.environ["PATH"] = f"{_venv_bin}:{_current_path}" # Make the project's ``code/`` importable in every child shell so inline # scripts and ``code/*.py`` helpers can ``import benchmark_loaders`` / diff --git a/argus_skill/maintenance/__init__.py b/argus_skill/maintenance/__init__.py new file mode 100644 index 000000000..4c9d6f743 --- /dev/null +++ b/argus_skill/maintenance/__init__.py @@ -0,0 +1,13 @@ +"""Deterministic Doctor findings and registered repair execution.""" + +from .doctor import DoctorContext, run_full_doctor +from .models import DoctorFinding, DoctorReport, RepairAction, RepairResult + +__all__ = [ + "DoctorContext", + "DoctorFinding", + "DoctorReport", + "RepairAction", + "RepairResult", + "run_full_doctor", +] diff --git a/argus_skill/maintenance/doctor.py b/argus_skill/maintenance/doctor.py new file mode 100644 index 000000000..036bd899c --- /dev/null +++ b/argus_skill/maintenance/doctor.py @@ -0,0 +1,485 @@ +"""Cross-platform, read-only Doctor inventory and blockage classification.""" +from __future__ import annotations + +import hashlib +import json +import os +import platform +import re +import shutil +import socket +import subprocess +import sys +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any +from urllib.error import HTTPError, URLError +from urllib.request import Request, urlopen + +from .models import DoctorFinding, DoctorReport + + +@dataclass(frozen=True) +class DoctorContext: + global_root: Path + project_root: Path + checkout: Path | None = None + python_executable: Path = Path(sys.executable) + web_host: str = "127.0.0.1" + web_port: int = 8799 + desktop_user_data: Path | None = None + install_mode: str = "source" + + def fingerprint_payload(self) -> dict[str, str | int]: + return { + "global_root": str(self.global_root.expanduser().resolve()), + "project_root": str(self.project_root.expanduser().resolve()), + "checkout": str(self.checkout.expanduser().resolve()) if self.checkout else "", + "python_executable": str(self.python_executable.expanduser().resolve()), + "web_host": self.web_host, + "web_port": int(self.web_port), + "platform": platform.system(), + "install_mode": self.install_mode, + "machine": platform.machine(), + } + + @property + def target_fingerprint(self) -> str: + payload = json.dumps(self.fingerprint_payload(), sort_keys=True).encode("utf-8") + return hashlib.sha256(payload).hexdigest() + + +def _finding( + code: str, + scope: str, + ok: bool, + status: str, + detail: str, + *, + severity: str = "info", + evidence: dict[str, Any] | None = None, + actions: tuple[str, ...] = (), + recommendation: str = "", +) -> DoctorFinding: + return DoctorFinding( + code=code, + scope=scope, # type: ignore[arg-type] + severity=("info" if ok else severity), # type: ignore[arg-type] + ok=ok, + status=status, + detail=detail, + evidence=evidence or {}, + repair_action_ids=actions if not ok else (), + recommendation="" if ok else recommendation, + ) + + +def _command_version(name: str, *, timeout: float = 3.0) -> tuple[bool, str, str]: + executable = shutil.which(name) + if not executable: + return False, "", f"{name} was not found on PATH" + try: + completed = subprocess.run( + [executable, "--version"], + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout, + ) + except (OSError, subprocess.SubprocessError) as exc: + return False, executable, f"{type(exc).__name__}: {exc}" + lines = (completed.stdout or completed.stderr or "").strip().splitlines() + detail = lines[0] if lines else f"exit {completed.returncode}" + return completed.returncode == 0, executable, detail + + +def _probe_web(host: str, port: int) -> tuple[str, dict[str, Any]]: + try: + with socket.create_connection((host, port), timeout=0.4): + pass + except OSError: + return "stopped", {} + try: + request = Request(f"http://{host}:{port}/api/meta") + with urlopen(request, timeout=1.5) as response: # noqa: S310 - loopback/operator target + payload = json.load(response) + if payload.get("service") == "argus-skill-webapi": + return "compatible", payload + return "foreign_http", payload if isinstance(payload, dict) else {} + except HTTPError as exc: + # Desktop protects loopback with a bearer token. A 401 still proves an + # Argus-shaped HTTP listener only when the protocol header is present. + protocol = str(exc.headers.get("x-argus-protocol") or "") + return ("protected_argus" if protocol.startswith("argus.webapi/") else "foreign_http"), { + "http_status": exc.code, + "protocol": protocol, + } + except (URLError, OSError, ValueError, json.JSONDecodeError): + return "occupied_unresponsive", {} + + +def _checkout_finding(context: DoctorContext) -> list[DoctorFinding]: + checkout = context.checkout + if checkout is None: + packaged = context.install_mode in {"wheel", "frozen"} + return [_finding( + "ARGUS-INSTALL-001", "install", packaged, + f"{context.install_mode}_install" if packaged else "checkout_unknown", + ( + f"Argus {context.install_mode} installation at {context.python_executable}" + if packaged else "Argus source checkout could not be identified" + ), + severity="error", actions=("refresh_path_memory",), + recommendation="pass --root or run the standalone argus-doctor from the checkout", + evidence={"install_mode": context.install_mode}, + )] + root = checkout.expanduser().resolve() + valid = (root / "pyproject.toml").is_file() and (root / "argus_skill").is_dir() + findings = [_finding( + "ARGUS-INSTALL-001", "install", valid, + "source_checkout" if valid else "broken_checkout", + str(root) if valid else f"missing pyproject.toml or argus_skill under {root}", + severity="critical", actions=("refresh_path_memory",), + recommendation="restore a complete checkout before applying runtime repairs", + evidence={"checkout": str(root)}, + )] + if not valid: + return findings + + manifest = root / "argus_skill" / "release_manifest.json" + web = root / "frontend" / "web" / "dist" / "index.html" + tui = root / "frontend" / "tui" / "bundle" / "argus.mjs" + missing = [str(path.relative_to(root)) for path in (manifest, web, tui) if not path.is_file()] + findings.append(_finding( + "ARGUS-ASSET-001", "install", not missing, + "assets_ready" if not missing else "assets_missing", + "release manifest and Web/TUI assets are present" if not missing else f"missing: {', '.join(missing)}", + severity="error", actions=("rebuild_release_assets",), + recommendation="rebuild release assets with the checkout interpreter", + evidence={"missing": missing}, + )) + + git_ok, git_bin, git_detail = _command_version("git") + branch = "" + dirty = False + if git_ok: + try: + branch_run = subprocess.run( + [git_bin, "-C", str(root), "branch", "--show-current"], + check=False, capture_output=True, text=True, encoding="utf-8", timeout=3, + ) + status_run = subprocess.run( + [git_bin, "-C", str(root), "status", "--porcelain"], + check=False, capture_output=True, text=True, encoding="utf-8", timeout=3, + ) + branch = branch_run.stdout.strip() + dirty = bool(status_run.stdout.strip()) + except (OSError, subprocess.SubprocessError): + pass + findings.append(_finding( + "ARGUS-GIT-001", "update", git_ok, + "git_ready" if git_ok else "git_missing", git_detail, + severity="error", recommendation="install Git and add it to PATH", + evidence={"executable": git_bin, "branch": branch, "dirty": dirty}, + )) + return findings + + +def _runtime_findings(context: DoctorContext) -> list[DoctorFinding]: + python_path = context.python_executable.expanduser() + python_ok = python_path.is_file() and sys.version_info >= (3, 11) + findings = [_finding( + "ARGUS-PYTHON-001", "cli", python_ok, + "python_ready" if python_ok else "python_invalid", + f"{platform.python_version()} at {python_path}", + severity="critical", actions=("install_editable",), + recommendation="use Python 3.11+ and reinstall Argus into the intended environment", + evidence={"executable": str(python_path), "version": platform.python_version()}, + )] + node_ok, node_bin, node_detail = _command_version("node") + match = re.search(r"v?(\d+)(?:\.(\d+))?", node_detail) + node_version = ( + (int(match.group(1)), int(match.group(2) or 0)) + if match else (0, 0) + ) + node_supported = node_ok and node_version >= (22, 12) + findings.append(_finding( + "ARGUS-NODE-001", "cli", node_supported, + "node_ready" if node_supported else "node_missing_or_unsupported", node_detail, + severity="error", recommendation="install Node.js 22.12+ and add it to PATH", + evidence={"executable": node_bin, "version": node_detail}, + )) + return findings + + +def _desktop_finding(context: DoctorContext) -> DoctorFinding: + if getattr(sys, "frozen", False): + return _finding( + "ARGUS-DESKTOP-001", "desktop", True, "frozen_runtime", + "running from a frozen Argus distribution", + evidence={"executable": sys.executable}, + ) + if context.checkout is None: + return _finding( + "ARGUS-DESKTOP-001", "desktop", True, "not_inspectable", + "no source checkout was selected; Desktop source dependencies were not inspected", + ) + desktop = context.checkout / "desktop" + package = desktop / "package.json" + if not package.is_file(): + return _finding( + "ARGUS-DESKTOP-001", "desktop", True, "not_present", + "this checkout has no Desktop source package", + ) + candidates = [ + desktop / "node_modules" / "electron" / "path.txt", + desktop / "node_modules" / "electron" / "dist" / "electron.exe", + ] + ready = all(path.is_file() for path in candidates) if os.name == "nt" else candidates[0].is_file() + return _finding( + "ARGUS-DESKTOP-001", "desktop", ready, + "electron_ready" if ready else "electron_binary_missing", + "Electron development runtime is installed" if ready else "Electron package exists without an installed runtime binary", + severity="error", actions=("install_electron_binary",), + recommendation="run the registered Electron install action from desktop/", + evidence={"desktop": str(desktop)}, + ) + + +def _desktop_log_finding(context: DoctorContext) -> DoctorFinding: + user_data = context.desktop_user_data + if user_data is None: + return _finding( + "ARGUS-DESKTOP-LOG-001", "desktop", True, "not_configured", + "Desktop user-data path is not configured", + ) + log_path = user_data / "logs" / "desktop.log" + if not log_path.is_file(): + return _finding( + "ARGUS-DESKTOP-LOG-001", "desktop", True, "no_log", + f"no Desktop log at {log_path}", + ) + try: + lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines()[-400:] + except OSError as exc: + return _finding( + "ARGUS-DESKTOP-LOG-001", "desktop", False, "log_unreadable", + f"{type(exc).__name__}: {exc}", severity="warning", + recommendation="export Desktop diagnostics and inspect file permissions", + ) + error_markers = ( + "backend error:", "backend failed", "failed to start", "startup timed out", + "electron uninstall", "uncaught main-process error", + ) + last_error = max( + (index for index, line in enumerate(lines) if any(marker in line.casefold() for marker in error_markers)), + default=-1, + ) + last_ready = max( + (index for index, line in enumerate(lines) if "backend ready:" in line.casefold()), + default=-1, + ) + unresolved = last_error > last_ready + return _finding( + "ARGUS-DESKTOP-LOG-001", "desktop", not unresolved, + "recent_startup_error" if unresolved else "log_healthy", + ( + lines[last_error][-500:] if unresolved + else f"Desktop log has no unresolved startup error: {log_path}" + ), + severity="error", + recommendation="run standalone argus-doctor, then retry Desktop or export diagnostics", + evidence={"path": str(log_path), "last_error_after_ready": unresolved}, + ) + + +def _daemon_findings(context: DoctorContext) -> list[DoctorFinding]: + project_root = context.project_root.expanduser() + try: + from ..daemon.state import read_daemon_status + status = read_daemon_status(project_root) + except Exception as exc: # noqa: BLE001 - Doctor must remain fail-soft + return [_finding( + "ARGUS-DAEMON-001", "daemon", False, "status_unreadable", + f"{type(exc).__name__}: {exc}", severity="error", + recommendation="inspect daemon sidecars and run Doctor again", + )] + if status.alive: + state = str(status.health_state or "unknown") + stalled = bool(status.stalled) + drain_path = project_root / "daemon.drain-request.json" + draining = drain_path.exists() + drain_age = 0.0 + if draining: + try: + drain_payload = json.loads(drain_path.read_text(encoding="utf-8")) + drain_age = max(0.0, time.time() - float(drain_payload.get("requested_at") or 0.0)) + except (OSError, ValueError, TypeError, json.JSONDecodeError): + try: + drain_age = max(0.0, time.time() - drain_path.stat().st_mtime) + except OSError: + drain_age = 0.0 + drain_stuck = draining and drain_age >= 60.0 + semantic = ( + "drain_stuck" if drain_stuck else "draining" if draining + else "stalled" if stalled else state + ) + return [_finding( + "ARGUS-DAEMON-001", "daemon", not stalled and not drain_stuck, + semantic, f"daemon pid {status.pid} is alive; health={semantic}", + severity="error", + actions=("stop_owned_stuck_daemon",) if drain_stuck else (), + recommendation="interrupt the verified owned daemon after reviewing its latest boot log", + evidence={ + "pid": status.pid, + "started_at_iso": status.started_at_iso, + "health_state": state, + "seconds_since_progress": status.seconds_since_progress, + "draining": draining, + "drain_age_seconds": drain_age, + }, + )] + pid_path = project_root / "daemon.pid" + stale_pid = None + try: + stale_pid = int(pid_path.read_text(encoding="ascii").strip()) if pid_path.exists() else None + except (OSError, ValueError): + stale_pid = None + findings = [_finding( + "ARGUS-DAEMON-001", "daemon", True, "stopped", + "no daemon is running", + )] + if pid_path.exists(): + findings.append(_finding( + "ARGUS-STATE-001", "daemon", False, "stale_pid", + f"daemon.pid remains for non-running pid {stale_pid or 'unknown'}", + severity="error", actions=("remove_verified_stale_daemon_pid",), + recommendation="remove only after lock and liveness revalidation", + evidence={"pid": stale_pid, "path": str(pid_path)}, + )) + control_files = [ + name for name in ("daemon.stop-request.json", "daemon.drain-request.json") + if (project_root / name).exists() + ] + if control_files: + findings.append(_finding( + "ARGUS-STATE-002", "daemon", False, "stale_control_request", + f"stopped daemon retains control files: {', '.join(control_files)}", + severity="warning", actions=("remove_dead_daemon_control_files",), + recommendation="remove requests only after confirming no daemon owns them", + evidence={"files": control_files}, + )) + return findings + + +def render_full_report(report: DoctorReport) -> str: + lines = ["argus doctor — cross-platform diagnostics", ""] + for finding in report.findings: + glyph = "✓" if finding.ok else "!" if finding.severity == "warning" else "✗" + lines.append( + f"{glyph} {finding.code} [{finding.scope}/{finding.status}] {finding.detail}" + ) + if finding.recommendation: + lines.append(f" fix: {finding.recommendation}") + if finding.repair_action_ids: + lines.append( + f" repair: {', '.join(finding.repair_action_ids)}" + ) + lines.extend([ + "", + "all blocking checks passed" if report.ok else "blocking issues found", + ]) + return "\n".join(lines) + + +def run_full_doctor( + context: DoctorContext, + *, + include_backend: bool = True, + probe_auth: bool = False, +) -> DoctorReport: + """Return a complete read-only report. No directory is created here.""" + findings: list[DoctorFinding] = [ + _finding( + "ARGUS-HOST-001", "host", True, "supported_host", + f"{platform.system()} {platform.release()} {platform.machine()}", + evidence={ + "system": platform.system(), + "release": platform.release(), + "machine": platform.machine(), + }, + ) + ] + findings.extend(_checkout_finding(context)) + findings.extend(_runtime_findings(context)) + + special_prompt = context.global_root / "special_prompts" / "10-house-rules.md" + findings.append(_finding( + "ARGUS-CONFIG-001", "install", special_prompt.is_file(), + "house_rules_ready" if special_prompt.is_file() else "house_rules_missing", + str(special_prompt), severity="error", actions=("create_house_rules",), + recommendation="review and create machine-specific operator house rules", + )) + + web_status, web_meta = _probe_web(context.web_host, context.web_port) + web_ok = web_status in {"stopped", "compatible", "protected_argus"} + findings.append(_finding( + "ARGUS-WEB-001", "web", web_ok, web_status, + f"{context.web_host}:{context.web_port} is {web_status}", + severity="error", + recommendation="choose a free port or stop only a verified owned listener", + evidence={ + "host": context.web_host, + "port": context.web_port, + "service": web_meta.get("service"), + "runtime": web_meta.get("runtime", {}), + }, + )) + findings.append(_desktop_finding(context)) + findings.append(_desktop_log_finding(context)) + findings.extend(_daemon_findings(context)) + + memory_path = context.global_root / "repairs" / "path-memory.json" + findings.append(_finding( + "ARGUS-PATH-001", "install", memory_path.is_file(), + "path_memory_ready" if memory_path.is_file() else "path_memory_missing", + str(memory_path), severity="warning", actions=("refresh_path_memory",), + recommendation="record canonical runtime paths for future Doctor runs", + )) + + if include_backend: + try: + from ..webapi.diagnostics import run_diagnostics + legacy = run_diagnostics( + context.project_root, + global_root=context.global_root, + probe_auth=probe_auth, + ) + for check in legacy: + if check.name not in {"daemon", "lock sanity", "empty session"}: + code = { + "backend preflight": "ARGUS-BACKEND-001", + "model API capability": "ARGUS-BACKEND-002", + }.get(check.name, "ARGUS-BACKEND-003") + findings.append(_finding( + code, "backend", bool(check.ok), + "ready" if check.ok else "not_ready", check.detail, + severity="error", recommendation=check.fix, + )) + except Exception as exc: # noqa: BLE001 + findings.append(_finding( + "ARGUS-BACKEND-001", "backend", False, "probe_failed", + f"{type(exc).__name__}: {exc}", severity="error", + recommendation="run bootstrap Doctor and inspect backend installation", + )) + + return DoctorReport( + schema_version=1, + target_fingerprint=context.target_fingerprint, + generated_at=datetime.now(timezone.utc).isoformat(), + findings=tuple(findings), + ) diff --git a/argus_skill/maintenance/models.py b/argus_skill/maintenance/models.py new file mode 100644 index 000000000..75dbf0b34 --- /dev/null +++ b/argus_skill/maintenance/models.py @@ -0,0 +1,106 @@ +"""Typed data contracts shared by Doctor, Repair, CLI, and support exports.""" +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +Scope = Literal[ + "host", "install", "cli", "web", "desktop", "backend", "daemon", "project", "update" +] +Severity = Literal["info", "warning", "error", "critical"] +Risk = Literal["safe", "consent", "manual"] + + +@dataclass(frozen=True) +class DoctorFinding: + code: str + scope: Scope + severity: Severity + ok: bool + status: str + detail: str + evidence: dict[str, Any] = field(default_factory=dict) + repair_action_ids: tuple[str, ...] = () + recommendation: str = "" + + def to_jsonable(self) -> dict[str, Any]: + return { + "code": self.code, + "scope": self.scope, + "severity": self.severity, + "ok": self.ok, + "status": self.status, + "detail": self.detail, + "evidence": dict(self.evidence), + "repair_action_ids": list(self.repair_action_ids), + "recommendation": self.recommendation, + } + + +@dataclass(frozen=True) +class DoctorReport: + schema_version: int + target_fingerprint: str + generated_at: str + findings: tuple[DoctorFinding, ...] + + @property + def ok(self) -> bool: + return all( + item.ok or item.severity in {"info", "warning"} + for item in self.findings + ) + + def to_jsonable(self) -> dict[str, Any]: + return { + "schema_version": self.schema_version, + "ok": self.ok, + "target_fingerprint": self.target_fingerprint, + "generated_at": self.generated_at, + "findings": [item.to_jsonable() for item in self.findings], + } + + +@dataclass(frozen=True) +class RepairAction: + id: str + provider: str + risk: Risk + target: str + precondition: dict[str, Any] = field(default_factory=dict) + verify_codes: tuple[str, ...] = () + + def to_jsonable(self) -> dict[str, Any]: + return { + "id": self.id, + "provider": self.provider, + "risk": self.risk, + "target": self.target, + "precondition": dict(self.precondition), + "verify_codes": list(self.verify_codes), + } + + +@dataclass(frozen=True) +class RepairPlanRef: + plan_id: str + path: Path + status: str + actions: tuple[RepairAction, ...] + + +@dataclass(frozen=True) +class RepairResult: + plan_id: str + status: str + actions: tuple[dict[str, Any], ...] + verification: dict[str, Any] + + def to_jsonable(self) -> dict[str, Any]: + return { + "plan_id": self.plan_id, + "status": self.status, + "actions": [dict(item) for item in self.actions], + "verification": dict(self.verification), + } diff --git a/argus_skill/maintenance/repair.py b/argus_skill/maintenance/repair.py new file mode 100644 index 000000000..7654b9a50 --- /dev/null +++ b/argus_skill/maintenance/repair.py @@ -0,0 +1,627 @@ +"""Persisted repair plans and a closed registry of executable actions.""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import tempfile +import time +import uuid +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from .doctor import DoctorContext, run_full_doctor +from .models import DoctorFinding, RepairAction, RepairPlanRef, RepairResult + +_PLAN_SCHEMA_VERSION = 1 +_HISTORY_SCHEMA_VERSION = 1 +_SECRET_PATTERNS = ( + re.compile(r"(?i)(?:gh[pousr]_|sk-|token=)[A-Za-z0-9._~+/=-]{8,}"), + re.compile(r"(?i)bearer\s+[A-Za-z0-9._~+/=-]+"), + re.compile(r"(?i)(?:api[_-]?key|password|secret)\s*[:=]\s*[^\s,;]+"), +) + + +def _redact(value: str) -> str: + text = value.replace(str(Path.home()), "~") + for pattern in _SECRET_PATTERNS: + text = pattern.sub("[REDACTED]", text) + return text + + +def _sanitize_audit(value: Any) -> Any: + if isinstance(value, str): + return _redact(value) + if isinstance(value, dict): + return {str(key): _sanitize_audit(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_sanitize_audit(item) for item in value] + return value + + +def repairs_root(global_root: Path) -> Path: + return global_root.expanduser().resolve() / "repairs" + + +def _atomic_json(path: Path, payload: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(payload, handle, ensure_ascii=False, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + finally: + try: + os.unlink(temporary) + except FileNotFoundError: + pass + + +def _append_history(global_root: Path, event: dict[str, Any]) -> None: + path = repairs_root(global_root) / "history.jsonl" + path.parent.mkdir(parents=True, exist_ok=True) + payload = _sanitize_audit({ + "schema_version": _HISTORY_SCHEMA_VERSION, + "ts": time.time(), + **event, + }) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload, ensure_ascii=False, sort_keys=True) + "\n") + handle.flush() + try: + os.fsync(handle.fileno()) + except OSError: + pass + + +def _path_memory_payload(context: DoctorContext) -> dict[str, Any]: + return { + "schema_version": 1, + "updated_at": datetime.now(timezone.utc).isoformat(), + "checkout": str(context.checkout.expanduser().resolve()) if context.checkout else "", + "python_executable": str(context.python_executable.expanduser().resolve()), + "global_root": str(context.global_root.expanduser().resolve()), + "project_root": str(context.project_root.expanduser().resolve()), + "desktop_user_data": ( + str(context.desktop_user_data.expanduser().resolve()) + if context.desktop_user_data else "" + ), + "web_host": context.web_host, + "web_port": int(context.web_port), + "platform": os.name, + "install_mode": context.install_mode, + } + + +def write_path_memory(context: DoctorContext) -> Path: + path = repairs_root(context.global_root) / "path-memory.json" + _atomic_json(path, _path_memory_payload(context)) + return path + + +def read_path_memory(global_root: Path) -> dict[str, Any]: + path = repairs_root(global_root) / "path-memory.json" + try: + payload = json.loads(path.read_text(encoding="utf-8")) + return payload if isinstance(payload, dict) else {} + except (OSError, json.JSONDecodeError): + return {} + + +def _target_for_action(context: DoctorContext, action_id: str) -> str: + targets = { + "refresh_path_memory": str(repairs_root(context.global_root) / "path-memory.json"), + "ensure_runtime_dirs": str(repairs_root(context.global_root)), + "remove_verified_stale_daemon_pid": str(context.project_root / "daemon.pid"), + "remove_dead_daemon_control_files": str(context.project_root), + "stop_owned_stuck_daemon": str(context.project_root), + "create_house_rules": str(context.global_root / "special_prompts" / "10-house-rules.md"), + "install_editable": str(context.checkout or ""), + "install_electron_binary": str((context.checkout / "desktop") if context.checkout else ""), + "rebuild_release_assets": str(context.checkout or ""), + } + return targets.get(action_id, action_id) + + +def _action_spec(context: DoctorContext, action_id: str) -> RepairAction: + specs: dict[str, tuple[str, str, tuple[str, ...]]] = { + "refresh_path_memory": ("core", "safe", ("ARGUS-PATH-001",)), + "ensure_runtime_dirs": ("core", "safe", ()), + "remove_verified_stale_daemon_pid": ("daemon", "safe", ("ARGUS-STATE-001",)), + "remove_dead_daemon_control_files": ("daemon", "safe", ("ARGUS-STATE-002",)), + "stop_owned_stuck_daemon": ("daemon", "consent", ("ARGUS-DAEMON-001",)), + "create_house_rules": ("config", "consent", ("ARGUS-CONFIG-001",)), + "install_editable": ("python", "consent", ("ARGUS-PYTHON-001",)), + "install_electron_binary": ("desktop", "consent", ("ARGUS-DESKTOP-001",)), + "rebuild_release_assets": ("release", "consent", ("ARGUS-ASSET-001",)), + } + provider, risk, verify = specs.get(action_id, ("manual", "manual", ())) + return RepairAction( + id=action_id, + provider=provider, + risk=risk, # type: ignore[arg-type] + target=_target_for_action(context, action_id), + precondition={"target_fingerprint": context.target_fingerprint}, + verify_codes=verify, + ) + + +def create_plan( + context: DoctorContext, + findings: list[DoctorFinding] | tuple[DoctorFinding, ...], +) -> RepairPlanRef: + root = repairs_root(context.global_root) + now = datetime.now(timezone.utc) + unique = uuid.uuid4().hex[:8] + plan_id = f"rp-{now.strftime('%Y%m%dT%H%M%SZ')}-{unique}" + action_ids: list[str] = [] + evidence_by_action: dict[str, dict[str, Any]] = {} + for finding in findings: + for action_id in finding.repair_action_ids: + if action_id not in action_ids: + action_ids.append(action_id) + evidence_by_action.setdefault(action_id, {}).update(finding.evidence) + # Remembering canonical paths is always safe and makes the next diagnosis + # deterministic, but do not duplicate an explicitly requested action. + if "refresh_path_memory" not in action_ids: + action_ids.append("refresh_path_memory") + action_rows: list[RepairAction] = [] + for action_id in action_ids: + action = _action_spec(context, action_id) + if action_id == "stop_owned_stuck_daemon": + evidence = evidence_by_action.get(action_id, {}) + action = RepairAction( + id=action.id, + provider=action.provider, + risk=action.risk, + target=action.target, + precondition={ + **action.precondition, + "pid": evidence.get("pid"), + "started_at_iso": evidence.get("started_at_iso"), + }, + verify_codes=action.verify_codes, + ) + action_rows.append(action) + actions = tuple(action_rows) + payload = { + "schema_version": _PLAN_SCHEMA_VERSION, + "plan_id": plan_id, + "created_at": now.isoformat(), + "updated_at": now.isoformat(), + "target_fingerprint": context.target_fingerprint, + "target": context.fingerprint_payload(), + "status": "planned", + "findings": [_sanitize_audit(finding.to_jsonable()) for finding in findings], + "actions": [action.to_jsonable() for action in actions], + "outcomes": [], + "verification": {}, + } + path = root / "plans" / f"{plan_id}.json" + _atomic_json(path, payload) + _append_history(context.global_root, {"type": "repair.plan.created", "plan_id": plan_id}) + return RepairPlanRef(plan_id=plan_id, path=path, status="planned", actions=actions) + + +def _load_plan(global_root: Path, plan_id: str) -> tuple[Path, dict[str, Any]]: + if not re.fullmatch(r"rp-[A-Za-z0-9TZ-]+", plan_id): + raise ValueError("invalid repair plan id") + path = repairs_root(global_root) / "plans" / f"{plan_id}.json" + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError as exc: + raise FileNotFoundError(f"repair plan not found: {plan_id}") from exc + if not isinstance(payload, dict) or payload.get("schema_version") != _PLAN_SCHEMA_VERSION: + raise ValueError(f"unsupported or malformed repair plan: {plan_id}") + return path, payload + + +def _safe_remove_stale_pid(context: DoctorContext) -> dict[str, Any]: + from ..core import daemon_lock + + path = context.project_root / "daemon.pid" + pid = daemon_lock.read_daemon_pid(path) + if pid is None and not path.exists(): + return {"status": "not_needed"} + if pid is not None and daemon_lock.is_pid_running(pid): + return {"status": "skipped_live", "pid": pid} + try: + lock = daemon_lock.acquire_global_daemon_lock(pid_path=path) + except daemon_lock.DaemonAlreadyRunning as exc: + return {"status": "skipped_live", "pid": exc.pid} + lock.release() + return {"status": "applied", "previous_pid": pid} + + +def _safe_remove_control_files(context: DoctorContext) -> dict[str, Any]: + from ..daemon.state import read_daemon_status + + status = read_daemon_status(context.project_root) + if status.alive: + return {"status": "skipped_live", "pid": status.pid} + removed: list[str] = [] + for name in ("daemon.stop-request.json", "daemon.drain-request.json"): + path = context.project_root / name + try: + path.unlink() + removed.append(name) + except FileNotFoundError: + pass + return {"status": "applied" if removed else "not_needed", "removed": removed} + + +def _run_registered_command(argv: list[str], *, cwd: Path, timeout: float) -> dict[str, Any]: + completed = subprocess.run( + argv, + cwd=str(cwd), + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout, + env={**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}, + ) + detail = _redact((completed.stderr or completed.stdout or "").strip()[-4_000:]) + return { + "status": "applied" if completed.returncode == 0 else "failed", + "returncode": completed.returncode, + "detail": detail, + } + + +def _apply_registered_action( + context: DoctorContext, + action: RepairAction, + *, + confirmed: bool, +) -> dict[str, Any]: + if action.risk == "manual": + return {"status": "manual_required"} + if action.risk == "consent" and not confirmed: + return {"status": "consent_required"} + if action.id == "refresh_path_memory": + return {"status": "applied", "path": str(write_path_memory(context))} + if action.id == "ensure_runtime_dirs": + for path in ( + context.global_root, + context.global_root / "projects", + context.global_root / "special_prompts", + repairs_root(context.global_root), + ): + path.mkdir(parents=True, exist_ok=True) + return {"status": "applied"} + if action.id == "remove_verified_stale_daemon_pid": + return _safe_remove_stale_pid(context) + if action.id == "remove_dead_daemon_control_files": + return _safe_remove_control_files(context) + if action.id == "stop_owned_stuck_daemon": + from ..daemon.state import read_daemon_status, stop_daemon + + status = read_daemon_status(context.project_root) + expected_pid = int((action.precondition or {}).get("pid") or 0) + expected_started = str((action.precondition or {}).get("started_at_iso") or "") + if not status.alive: + return {"status": "not_needed"} + if expected_pid and status.pid != expected_pid: + return {"status": "skipped_changed_target", "pid": status.pid} + if expected_started and status.started_at_iso != expected_started: + return {"status": "skipped_changed_target", "pid": status.pid} + rc = stop_daemon(context.project_root, timeout=15.0, force=False) + return { + "status": "applied" if rc in {0, 1} else "failed", + "returncode": rc, + "detail": "owned daemon interrupted" if rc in {0, 1} else "daemon did not stop within 15 seconds", + } + if action.id == "create_house_rules": + path = context.global_root / "special_prompts" / "10-house-rules.md" + if path.exists(): + return {"status": "not_needed"} + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("Operational house rules for this machine.\n", encoding="utf-8") + return {"status": "applied", "path": str(path)} + if context.checkout is None: + return {"status": "failed", "detail": "source checkout is unavailable"} + checkout = context.checkout.resolve() + if action.id == "install_editable": + return _run_registered_command( + [str(context.python_executable), "-m", "pip", "install", "-e", str(checkout)], + cwd=checkout, + timeout=300, + ) + if action.id == "install_electron_binary": + desktop = checkout / "desktop" + node = shutil_which("node") + if not node or not (desktop / "package.json").is_file(): + return {"status": "failed", "detail": "Node or desktop/package.json is unavailable"} + return _run_registered_command( + [node, "-e", "require('electron')"], + cwd=desktop, + timeout=300, + ) + if action.id == "rebuild_release_assets": + git = shutil_which("git") + if not git: + return {"status": "failed", "detail": "Git is required to attribute rebuilt files"} + before = subprocess.run( + [git, "-C", str(checkout), "status", "--porcelain"], + check=False, capture_output=True, text=True, encoding="utf-8", timeout=5, + ) + if before.returncode != 0 or before.stdout.strip(): + return { + "status": "failed", + "detail": "checkout must be clean before a repository repair action", + } + result = _run_registered_command( + [str(context.python_executable), "-m", "argus_skill.release_tools.build_release"], + cwd=checkout, + timeout=900, + ) + after = subprocess.run( + [git, "-C", str(checkout), "status", "--porcelain"], + check=False, capture_output=True, text=True, encoding="utf-8", timeout=5, + ) + result["changed_paths"] = sorted( + line[3:].strip().replace("\\", "/") + for line in after.stdout.splitlines() + if len(line) >= 4 + ) + result["repository_changes"] = bool(result["changed_paths"]) + return result + return {"status": "manual_required", "detail": "unregistered action"} + + +def shutil_which(name: str) -> str | None: + # Kept as a seam for tests and provider-specific path memory. + import shutil + + return shutil.which(name) + + +def apply_plan( + context: DoctorContext, + plan_id: str, + *, + safe_only: bool = False, + confirmed: bool = False, +) -> RepairResult: + path, payload = _load_plan(context.global_root, plan_id) + if payload.get("target_fingerprint") != context.target_fingerprint: + raise RuntimeError("repair target fingerprint changed; create a new plan") + if payload.get("status") == "completed": + return RepairResult( + plan_id=plan_id, + status="already_applied", + actions=tuple(payload.get("outcomes") or ()), + verification=dict(payload.get("verification") or {}), + ) + + previous_outcomes = { + str(item.get("id") or ""): dict(item) + for item in payload.get("outcomes") or [] + if isinstance(item, dict) + } + if payload.get("status") == "running": + _append_history(context.global_root, { + "type": "repair.plan.reconciled", + "plan_id": plan_id, + "previous_status": "running", + "status": "interrupted", + }) + payload["status"] = "interrupted" + payload["status"] = "running" + payload["updated_at"] = datetime.now(timezone.utc).isoformat() + _atomic_json(path, payload) + outcomes: list[dict[str, Any]] = [] + for raw in payload.get("actions") or []: + action = RepairAction( + id=str(raw.get("id") or ""), + provider=str(raw.get("provider") or "manual"), + risk=str(raw.get("risk") or "manual"), # type: ignore[arg-type] + target=str(raw.get("target") or ""), + precondition=dict(raw.get("precondition") or {}), + verify_codes=tuple(raw.get("verify_codes") or ()), + ) + previous = previous_outcomes.get(action.id, {}) + if previous.get("status") in {"applied", "not_needed", "already_applied"}: + outcome = {"id": action.id, "status": "already_applied"} + elif action.precondition.get("target_fingerprint") != context.target_fingerprint: + outcome = {"id": action.id, "status": "skipped_changed_target"} + elif safe_only and action.risk != "safe": + outcome = {"id": action.id, "status": "consent_required"} + else: + try: + outcome = {"id": action.id, **_apply_registered_action( + context, + action, + confirmed=confirmed or action.risk == "safe", + )} + except (OSError, subprocess.SubprocessError, ValueError) as exc: + outcome = { + "id": action.id, + "status": "failed", + "detail": _redact(f"{type(exc).__name__}: {exc}"), + } + outcomes.append(outcome) + _append_history(context.global_root, { + "type": "repair.action.finished", + "plan_id": plan_id, + "action": outcome, + }) + + verification = run_full_doctor(context, include_backend=False).to_jsonable() + verification_by_code = { + str(item.get("code") or ""): item + for item in verification.get("findings") or [] + } + outcome_by_id = {str(item.get("id") or ""): item for item in outcomes} + verification_failures: list[str] = [] + for raw in payload.get("actions") or []: + outcome = outcome_by_id.get(str(raw.get("id") or ""), {}) + if outcome.get("status") not in {"applied", "not_needed", "already_applied"}: + continue + for code in raw.get("verify_codes") or []: + finding = verification_by_code.get(str(code)) + if finding is not None and not finding.get("ok"): + verification_failures.append(str(code)) + failed = ( + any(item.get("status") in {"failed", "skipped_changed_target"} for item in outcomes) + or bool(verification_failures) + ) + unresolved = any(item.get("status") in {"consent_required", "manual_required", "skipped_live"} for item in outcomes) + status = "failed" if failed else "partial" if unresolved else "completed" + payload.update({ + "status": status, + "updated_at": datetime.now(timezone.utc).isoformat(), + "outcomes": outcomes, + "verification": verification, + "verification_failures": sorted(set(verification_failures)), + }) + _atomic_json(path, payload) + _append_history(context.global_root, { + "type": "repair.plan.finished", + "plan_id": plan_id, + "status": status, + }) + return RepairResult( + plan_id=plan_id, + status=status, + actions=tuple(outcomes), + verification=verification, + ) + + +def submit_pr( + context: DoctorContext, + plan_id: str, + *, + confirmed: bool, +) -> str: + """Publish a previously repaired and committed branch with explicit consent.""" + if not confirmed: + raise PermissionError("submit-pr requires --yes explicit authorization") + if context.checkout is None: + raise RuntimeError("source checkout is unavailable") + checkout = context.checkout.resolve() + _path, payload = _load_plan(context.global_root, plan_id) + changed_paths = sorted({ + str(path) + for outcome in payload.get("outcomes") or [] + for path in outcome.get("changed_paths") or [] + }) + if not changed_paths: + raise RuntimeError("plan has no registered repository repair changes") + git = shutil_which("git") + gh = shutil_which("gh") + if not git or not gh: + raise RuntimeError("git and authenticated GitHub CLI are required") + + def git_text(*args: str) -> str: + completed = subprocess.run( + [git, "-C", str(checkout), *args], + check=False, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, + ) + if completed.returncode != 0: + raise RuntimeError((completed.stderr or completed.stdout).strip()) + return completed.stdout.strip() + + branch = git_text("branch", "--show-current") + if not branch or branch in {"main", "master"}: + raise RuntimeError("submit-pr requires a non-main repair branch") + if git_text("status", "--porcelain"): + raise RuntimeError("commit and review registered repair changes before submit-pr") + try: + ahead = int(git_text("rev-list", "--count", "origin/main..HEAD") or "0") + except ValueError: + ahead = 0 + if ahead <= 0: + raise RuntimeError("repair branch has no committed changes ahead of origin/main") + auth = subprocess.run( + [gh, "auth", "status"], check=False, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=10, + ) + if auth.returncode != 0: + raise RuntimeError("GitHub CLI is not authenticated") + report = prepare_pr_report(context, plan_id) + title = f"fix(doctor): apply verified repair {plan_id}" + created = subprocess.run( + [ + gh, "pr", "create", "--base", "main", "--head", branch, + "--title", title, "--body-file", str(report), + ], + cwd=str(checkout), check=False, capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=60, + ) + if created.returncode != 0: + raise RuntimeError((created.stderr or created.stdout).strip()) + url = created.stdout.strip().splitlines()[-1] + _append_history(context.global_root, { + "type": "repair.pr.submitted", + "plan_id": plan_id, + "branch": branch, + "url": url, + "changed_paths": changed_paths, + }) + return url + + +def prepare_pr_report(context: DoctorContext, plan_id: str) -> Path: + _path, payload = _load_plan(context.global_root, plan_id) + report = repairs_root(context.global_root) / "reports" / f"{plan_id}.md" + report.parent.mkdir(parents=True, exist_ok=True) + lines = [ + f"# Argus Doctor repair report: {plan_id}", + "", + "## Target class", + "", + f"- Platform: {os.name}", + f"- Checkout: {_redact(str(context.checkout or 'unknown'))}", + f"- Status: {payload.get('status', 'planned')}", + "", + "## Findings", + "", + ] + for finding in payload.get("findings") or []: + lines.append( + f"- `{finding.get('code', 'ARGUS-UNKNOWN')}` " + f"[{finding.get('status', 'unknown')}]: {_redact(str(finding.get('detail') or ''))}" + ) + lines.extend(["", "## Registered actions", ""]) + outcomes = {str(item.get("id")): item for item in payload.get("outcomes") or []} + for action in payload.get("actions") or []: + action_id = str(action.get("id") or "") + outcome = outcomes.get(action_id, {}) + lines.append( + f"- `{action_id}` ({action.get('risk', 'manual')}): " + f"{outcome.get('status', 'planned')}" + ) + changed_paths = sorted({ + str(path) + for outcome in payload.get("outcomes") or [] + for path in outcome.get("changed_paths") or [] + }) + lines.extend(["", "## Candidate changed paths", ""]) + if changed_paths: + lines.extend(f"- `{_redact(path)}`" for path in changed_paths) + else: + lines.append("- None (environment-only repair)") + lines.extend([ + "", + "## Verification", + "", + f"- Doctor verification present: {bool(payload.get('verification'))}", + "- This report was prepared locally and was not published automatically.", + "", + ]) + report.write_text(_redact("\n".join(lines)), encoding="utf-8") + _append_history(context.global_root, { + "type": "repair.pr_report.prepared", + "plan_id": plan_id, + "path": str(report), + }) + return report diff --git a/argus_skill/release_manifest.json b/argus_skill/release_manifest.json index 5553a1ca0..6412e4cec 100644 --- a/argus_skill/release_manifest.json +++ b/argus_skill/release_manifest.json @@ -1,6 +1,6 @@ { "package_version": "0.1.1", - "release_id": "0.1.1+3fe127f899db9e23", + "release_id": "0.1.1+a4de81c666ef26a3", "schema_version": 1, - "source_digest": "3fe127f899db9e23aa1cd36118ac3419edb3e74e83ac34771fc755df6cce36c1" + "source_digest": "a4de81c666ef26a3645b67f679e18132546e5ec92003000d736e503810fa9700" } diff --git a/argus_skill/release_tools/build_release.py b/argus_skill/release_tools/build_release.py index 044ff0e76..7a19a8d8d 100644 --- a/argus_skill/release_tools/build_release.py +++ b/argus_skill/release_tools/build_release.py @@ -25,7 +25,11 @@ def run(*argv: str, cwd: Path = ROOT) -> None: with tempfile.TemporaryDirectory(prefix="argus-python-") as shim_dir: shim = Path(shim_dir) / ("python.cmd" if os.name == "nt" else "python") if os.name == "nt": - shim.write_text(f'@"{sys.executable}" %*\n', encoding="utf-8") + # Keep the batch file ASCII-only. cmd.exe decodes .cmd files with + # the active OEM code page, so embedding a Unicode checkout path + # here corrupts it before Python can start. + env["ARGUS_RELEASE_PYTHON"] = sys.executable + shim.write_text('@"%ARGUS_RELEASE_PYTHON%" %*\n', encoding="ascii") else: shim.symlink_to(sys.executable) env["PATH"] = os.pathsep.join((shim_dir, env.get("PATH", ""))) diff --git a/argus_skill/team/curator.py b/argus_skill/team/curator.py index c358a7618..f6dbc8d2a 100644 --- a/argus_skill/team/curator.py +++ b/argus_skill/team/curator.py @@ -40,10 +40,41 @@ log = logging.getLogger(__name__) +def _windows_process_command_line(pid: int) -> str: + script = ( + "$OutputEncoding=[Console]::OutputEncoding=[Text.UTF8Encoding]::new();" + f"$p=Get-CimInstance Win32_Process -Filter 'ProcessId = {int(pid)}';" + "if($null -ne $p){[Console]::Out.Write($p.CommandLine)}" + ) + try: + result = subprocess.run( + ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", script], + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=3.0, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + except (OSError, subprocess.SubprocessError): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _terminate_windows_tree(pid: int) -> None: + subprocess.run( + ["taskkill.exe", "/PID", str(int(pid)), "/T", "/F"], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + + def _pid_is_teammate(pid: int, member_id: str, root: Path | None = None) -> bool: """Verify an adopted PID against exact teammate command-line arguments.""" - if os.name == "nt": - return False + command_line = _windows_process_command_line(pid) if os.name == "nt" else "" try: argv = [ part.decode("utf-8", "replace") @@ -52,8 +83,7 @@ def _pid_is_teammate(pid: int, member_id: str, root: Path | None = None) -> bool ] except OSError: argv = [] - command_line = "" - if not argv: + if not argv and not command_line: ps = "/bin/ps" if Path("/bin/ps").is_file() else "/usr/bin/ps" try: result = subprocess.run( @@ -87,7 +117,7 @@ def option(name: str) -> str: rf"(?:^|\s){re.escape(name)}\s+(.+?)(?=\s+--[\w-]+(?:\s|$)|$)", command_line, ) - return match.group(1).strip() if match else "" + return match.group(1).strip().strip('"') if match else "" if option("--member-id") != member_id: return False @@ -125,6 +155,15 @@ def wait(self, timeout: float | None = None) -> int: time.sleep(0.1) return 0 + def terminate(self) -> None: + if os.name == "nt" and self.poll() is None: + _terminate_windows_tree(self.pid) + elif self.poll() is None: + os.kill(self.pid, signal.SIGTERM) + + def kill(self) -> None: + self.terminate() + class TrackedTeammate: """A teammate process the Curator owns by holding its ``Popen`` handle.""" @@ -348,11 +387,9 @@ def _terminate(self, tt: TrackedTeammate, *, grace: float = 2.0) -> None: if proc.poll() is not None: return if os.name == "nt": - proc.terminate() - try: - proc.wait(timeout=grace) - except subprocess.TimeoutExpired: - proc.kill() + _terminate_windows_tree(proc.pid) + with contextlib.suppress(subprocess.TimeoutExpired): + proc.wait(timeout=max(grace, 5.0)) return try: os.killpg(os.getpgid(proc.pid), signal.SIGTERM) diff --git a/argus_skill/team/task_board.py b/argus_skill/team/task_board.py index 748fb1421..dd8f4dc21 100644 --- a/argus_skill/team/task_board.py +++ b/argus_skill/team/task_board.py @@ -7,6 +7,8 @@ """ from __future__ import annotations +import hashlib +import os from pathlib import Path from typing import Any @@ -27,6 +29,20 @@ def _task_filename(task_id: str) -> str: invalid = not task_id or task_id in {".", ".."} or any(c in task_id for c in "/\\\0") if invalid: raise ValueError(f"invalid task_id for task board path: {task_id!r}") + if os.name == "nt": + stem = task_id.split(".", 1)[0].casefold() + windows_unsafe = ( + any(ord(char) < 32 or char in '<>:"|?*' for char in task_id) + or task_id.endswith((" ", ".")) + or stem in { + "con", "prn", "aux", "nul", + *(f"com{i}" for i in range(1, 10)), + *(f"lpt{i}" for i in range(1, 10)), + } + ) + if windows_unsafe: + digest = hashlib.sha256(task_id.encode("utf-8")).hexdigest() + return f"id-{digest}.json" return f"{task_id}.json" diff --git a/argus_skill/tools/ppt_master.py b/argus_skill/tools/ppt_master.py index 1c15e72d5..8557b36ad 100644 --- a/argus_skill/tools/ppt_master.py +++ b/argus_skill/tools/ppt_master.py @@ -6,6 +6,7 @@ import json import os import shutil +import stat import subprocess import sys import uuid @@ -179,6 +180,14 @@ def _prepare_checkout( return temporary +def _remove_tree(path: Path) -> None: + def remove_readonly(func, value, _exc_info) -> None: + os.chmod(value, stat.S_IWRITE) + func(value) + + shutil.rmtree(path, onerror=remove_readonly) + + def _copy_private_config(source: Path, destination: Path) -> None: for relative in (Path(".env"), Path("skills/ppt-master/.env")): source_path = source / relative @@ -200,7 +209,7 @@ def _replace_checkout(target: Path, prepared: Path) -> None: except BaseException: os.replace(backup, target) raise - shutil.rmtree(backup) + _remove_tree(backup) def _python_executable(explicit: str | None = None) -> str: @@ -289,7 +298,7 @@ def install_ppt_master( _replace_checkout(target, prepared) finally: if prepared.exists() and prepared != target: - shutil.rmtree(prepared) + _remove_tree(prepared) _validate_checkout(target, revision, git) if install_dependencies and current_revision == revision: diff --git a/argus_skill/tools/subagent/_experiment_preflight.py b/argus_skill/tools/subagent/_experiment_preflight.py index 2beb755f3..9f1fb41c0 100644 --- a/argus_skill/tools/subagent/_experiment_preflight.py +++ b/argus_skill/tools/subagent/_experiment_preflight.py @@ -189,8 +189,9 @@ def _claim_run_dir( claim_path = _claim_path(run_dir) key = (claim_owner, str(run_dir)) with _CLAIMS_LOCK: - if key in _HELD_CLAIMS: - return f"experiment run directory is already claimed by task {task_id}: {run_dir}" + for (owner, claimed_dir), _handle in _HELD_CLAIMS.items(): + if claimed_dir == str(run_dir): + return f"experiment run directory is already claimed by task {owner}: {run_dir}" claim_path.parent.mkdir(parents=True, exist_ok=True) handle = claim_path.open("a+", encoding="utf-8") try: diff --git a/argus_skill/tools/subagent/_registry.py b/argus_skill/tools/subagent/_registry.py index 8ab053104..fdaae5ae0 100644 --- a/argus_skill/tools/subagent/_registry.py +++ b/argus_skill/tools/subagent/_registry.py @@ -6,6 +6,7 @@ """ from __future__ import annotations +import hashlib import json import os import subprocess @@ -55,13 +56,24 @@ # Registry paths # --------------------------------------------------------------------------- +def _task_file_component(task_id: str) -> str: + text = str(task_id) + windows_unsafe = os.name == "nt" and ( + any(ord(char) < 32 or char in '<>:"|?*' for char in text) + or text.endswith((" ", ".")) + ) + if windows_unsafe or any(char in text for char in "/\\\0"): + return f"id-{hashlib.sha256(text.encode('utf-8')).hexdigest()}" + return text + + def _registry_path(task_id: str) -> Path: - return REGISTRY_DIR / f"{task_id}.json" + return REGISTRY_DIR / f"{_task_file_component(task_id)}.json" def _exit_status_path(task_id: str, run_id: str | None = None) -> Path: name = f"exit_code.{run_id}" if run_id else "exit_code" - return REGISTRY_DIR / f"{task_id}_logs" / name + return REGISTRY_DIR / f"{_task_file_component(task_id)}_logs" / name # --------------------------------------------------------------------------- diff --git a/argus_skill/webapi/routes/meta.py b/argus_skill/webapi/routes/meta.py index ea7936e57..f22e7956c 100644 --- a/argus_skill/webapi/routes/meta.py +++ b/argus_skill/webapi/routes/meta.py @@ -92,6 +92,34 @@ def _doctor(sid: str) -> dict[str, Any]: server_mod.get_doctor(sid, global_root=ctx.project_root_or_404(sid)), sid ) + @app.get("/api/system/doctor", dependencies=[Depends(ctx.require_auth)]) + def _system_doctor() -> dict[str, Any]: + """Read-only typed host/runtime inventory for Web and Desktop support.""" + import sys + from pathlib import Path + + from ...core.runtime_identity import source_root + from ...maintenance.doctor import DoctorContext, run_full_doctor + + root = server_mod._global_root(ctx.global_root) + source = source_root() + checkout = source if (source / "pyproject.toml").is_file() else None + report = run_full_doctor( + DoctorContext( + global_root=root, + project_root=root, + checkout=checkout, + python_executable=Path(sys.executable), + install_mode=( + "frozen" if getattr(sys, "frozen", False) + else "source" if checkout is not None + else "wheel" + ), + ), + include_backend=True, + ) + return report.to_jsonable() + @app.post("/api/projects/{sid}/config/set", dependencies=[Depends(ctx.require_auth)]) def _config_set(sid: str, body: ConfigSetIn) -> dict[str, Any]: project_state_dir = ctx.resolve_or_404(sid) diff --git a/desktop/src/renderer/index.html b/desktop/src/renderer/index.html index cf7c35a45..46553f830 100644 --- a/desktop/src/renderer/index.html +++ b/desktop/src/renderer/index.html @@ -77,6 +77,7 @@

Argus

重试 + diff --git a/desktop/src/renderer/main.ts b/desktop/src/renderer/main.ts index db5000c94..ffb0ae103 100644 --- a/desktop/src/renderer/main.ts +++ b/desktop/src/renderer/main.ts @@ -102,6 +102,7 @@ const detailEl = document.getElementById('detail') as HTMLParagraphElement; const barEl = document.getElementById('bar') as HTMLSpanElement; const retryEl = document.getElementById('retry') as HTMLButtonElement; const setupEl = document.getElementById('setup') as HTMLButtonElement; +const diagnosticsEl = document.getElementById('diagnostics') as HTMLButtonElement; const stepsEl = document.getElementById('steps') as HTMLOListElement; const wizardEl = document.getElementById('wizard') as HTMLElement; @@ -218,6 +219,7 @@ function render(status: DesktopStatus): void { if (status.detail) detailEl.textContent = status.detail; retryEl.hidden = status.state !== 'error'; setupEl.hidden = status.state !== 'error'; + diagnosticsEl.hidden = status.state !== 'error'; updateSteps(status); let width = 16; @@ -386,6 +388,20 @@ setupEl.addEventListener('click', () => { void reopenWizard(); }); +diagnosticsEl.addEventListener('click', () => { + diagnosticsEl.disabled = true; + void captureIpc(() => window.argusDesktop.exportDiagnostics()).then((result) => { + if (!result.ok) { + renderIpcFailure('无法导出诊断', result.detail); + return; + } + detailEl.hidden = false; + detailEl.textContent = `脱敏诊断已导出:${result.value}`; + }).finally(() => { + diagnosticsEl.disabled = false; + }); +}); + chooseRunnerEl.addEventListener('click', async () => { chooseRunnerEl.disabled = true; const result = await captureIpc(() => window.argusDesktop.chooseRunner(runnerKind)); @@ -463,6 +479,7 @@ wizardFinish.addEventListener('click', async () => { detailEl.hidden = true; retryEl.hidden = true; setupEl.hidden = true; + diagnosticsEl.hidden = true; barEl.style.width = '72%'; const invocation = await captureIpc(() => window.argusDesktop.completeSetup({ @@ -480,6 +497,7 @@ wizardFinish.addEventListener('click', async () => { detailEl.hidden = false; retryEl.hidden = false; setupEl.hidden = false; + diagnosticsEl.hidden = false; return; } applying = false; diff --git a/docs/doctor-repair-pipeline.md b/docs/doctor-repair-pipeline.md new file mode 100644 index 000000000..a6c51fa1a --- /dev/null +++ b/docs/doctor-repair-pipeline.md @@ -0,0 +1,117 @@ +# Argus Doctor and Repair Pipeline Specification + +- **Status:** Approved +- **Date:** 2026-08-14 +- **Scope:** Source, editable, wheel, frozen Desktop, CLI, Web, daemon, Windows, macOS, Linux +- **Compatibility:** Preserve `argus --doctor`; accept `argus doctor` and hidden legacy `argus -doctor` + +## 1. Context + +Argus spans Python, Node, multiple Agent CLIs, a persistent daemon, WebAPI, Ink TUI, and Electron Desktop. Failures often present in one surface while their root cause lives in another: an occupied port, stale PID sidecar, missing Electron binary, stale release artifact, wrong interpreter, unavailable backend, or a process that is alive but making no semantic progress. + +Doctor must turn those facts into deterministic findings. Repair must be a separate, typed, auditable phase. Different user machines require different actions, so successful and unsuccessful repair paths must be retained locally and exportable as a sanitized upstream report. No diagnostic text may be executed as a shell command. + +## 2. Functional Requirements + +- **FR-1 Read-only Doctor:** `argus doctor`, `argus --doctor`, and `argus -doctor` MUST perform no mutation. +- **FR-2 Bootstrap Doctor:** `argus-doctor` MUST run with the Python standard library when Argus Core cannot import. +- **FR-3 Cross-platform inventory:** Doctor MUST report OS, architecture, install mode, checkout, interpreter, venv, Git, Node, frontend assets, configured backend, Web endpoint, daemon identity, lock state, and known Desktop runtime paths. +- **FR-4 Stable findings:** Every finding MUST contain stable code, scope, severity, status, evidence, repair action IDs, and a human-safe recommendation. +- **FR-5 Blockage detection:** Doctor MUST distinguish stopped, starting, healthy, stalled, draining, owned port conflict, unowned port conflict, stale sidecar, missing dependency, and release mismatch. +- **FR-6 Repair plans:** `argus repair --plan` MUST persist a versioned plan with a unique ID, target fingerprint, preconditions, actions, risks, and verification checks. +- **FR-7 Registered actions only:** Repair MUST execute only actions registered in code. It MUST NOT execute arbitrary finding text. +- **FR-8 Authorization tiers:** SAFE actions MAY run under `argus repair --safe`; CONSENT actions require explicit `--apply --yes`; MANUAL actions are never executed. +- **FR-9 Revalidation:** Every action MUST revalidate its preconditions immediately before mutation and MUST skip when the target identity changed. +- **FR-10 Verification:** Repair MUST rerun Doctor and persist before/after findings and action outcomes. +- **FR-11 Path memory:** Repair MUST remember canonical checkout, interpreter, state root, Desktop user-data, Web endpoint, and successful repair provider paths under `ARGUS_SKILL_HOME/repairs/`. +- **FR-12 Audit history:** Plans and outcomes MUST be append-only/auditable and redact credentials and bearer tokens. +- **FR-13 Upstream report:** `argus repair --prepare-pr ` MUST create a sanitized Markdown report with reproduction, environment class, findings, actions, verification, and candidate changed paths. It MUST NOT publish. +- **FR-14 Authorized PR submission:** `--submit-pr` MAY invoke GitHub CLI only after explicit confirmation, only from a clean checkout on a non-main branch, and only for tracked source changes produced by a registered repository repair action. +- **FR-15 Existing runtime safety:** Doctor/Repair MUST NOT kill unknown processes, reset/stash/merge Git, change credentials, elevate with sudo/UAC, or spend money automatically. + +## 3. Non-functional Requirements + +- **NFR-1:** Default Doctor completes within 10 seconds without network probes. +- **NFR-2:** Deep probes are bounded individually to 15 seconds. +- **NFR-3:** JSON output remains valid UTF-8 under Windows CP936/PowerShell 5.1. +- **NFR-4:** Plan application is idempotent; reapplying a completed SAFE plan performs no duplicate mutation. +- **NFR-5:** Secrets, tokens, credential-bearing URLs, and home-directory user names are redacted from export bundles. +- **NFR-6:** A failed repair leaves an explicit failed outcome and does not claim success. + +## 4. Acceptance Criteria + +- **AC-1 (FR-1):** Given a file-system snapshot, when Doctor runs, then no file content, process, port, or Git state changes. +- **AC-2 (FR-2):** Given an unimportable Core, when standalone Doctor runs, then it returns structured bootstrap findings instead of crashing. +- **AC-3 (FR-5):** Given a live daemon with stale semantic progress, Doctor reports `stalled`, not `stopped`. +- **AC-4 (FR-5):** Given an occupied Web port, Doctor identifies whether the listener is owned, compatible, incompatible, or unknown. +- **AC-5 (FR-6/FR-10):** Given repairable findings, `repair --plan` persists a plan; apply records outcomes and post-repair verification. +- **AC-6 (FR-7):** Given a malicious recommendation string, Repair never executes it. +- **AC-7 (FR-8/FR-9):** Given a SAFE stale PID action whose PID becomes live before apply, Repair skips it. +- **AC-8 (FR-11):** Given a successful provider action, its canonical executable/path is available to the next Doctor run. +- **AC-9 (FR-13):** Given a completed plan, prepare-pr emits a credential-free report and does not call GitHub. +- **AC-10 (FR-14):** Given no explicit confirmation, dirty main, or missing `gh` auth, submit-pr refuses safely. +- **AC-11 (NFR-3):** Given a CP936 stream, Doctor and Repair emit valid readable output without `UnicodeEncodeError`. +- **AC-12 (NFR-4):** Given an already applied plan, a second apply is a no-op with `already_applied` status. + +## 5. Edge Cases + +- **EC-1:** Multiple Argus checkouts exist; report all, never delete or silently choose a dirty checkout. +- **EC-2:** PID is reused; require PID plus boot identity/lock proof. +- **EC-3:** Port listener changes during inspection; mark finding `changed_during_probe`. +- **EC-4:** State root is read-only; downgrade actions to MANUAL. +- **EC-5:** Core imports but optional Desktop/Web dependencies are absent. +- **EC-6:** GitHub Actions or GitHub billing blocks CI; classify as external service, not a test failure. +- **EC-7:** Repair process is interrupted; the next run reconciles `running` actions to `interrupted` before continuing. + +## 6. API Contracts + +```ts +interface DoctorFinding { + code: string; + scope: 'host'|'install'|'cli'|'web'|'desktop'|'backend'|'daemon'|'project'|'update'; + severity: 'info'|'warning'|'error'|'critical'; + ok: boolean; + status: string; + detail: string; + evidence: Record; + repair_action_ids: string[]; + recommendation: string; +} + +interface RepairAction { + id: string; + provider: string; + risk: 'safe'|'consent'|'manual'; + target: string; + precondition: Record; + verify_codes: string[]; +} + +interface RepairPlan { + schema_version: 1; + plan_id: string; + created_at: string; + target_fingerprint: string; + findings: DoctorFinding[]; + actions: RepairAction[]; + status: 'planned'|'running'|'completed'|'partial'|'failed'; +} +``` + +## 7. Data Models + +| Entity | Storage | Constraints | +|---|---|---| +| Repair plan | `repairs/plans/.json` | Immutable identity; atomic updates | +| Repair history | `repairs/history.jsonl` | Append-only; redacted | +| Path memory | `repairs/path-memory.json` | Canonical absolute paths; no secrets | +| PR report | `repairs/reports/.md` | Sanitized; no automatic publication | + +## 8. Out of Scope + +- Automatic credential creation, migration, deletion, or login. +- Automatic sudo/UAC/root elevation. +- Automatic package-manager installation outside the active Argus environment without consent. +- Automatic termination of unowned processes. +- Automatic Git reset, stash, merge, rebase, force-push, or main-branch commit. +- Fully autonomous PR publication without explicit operator authorization. diff --git a/frontend/core/src/release.generated.ts b/frontend/core/src/release.generated.ts index 6cf82848e..188996867 100644 --- a/frontend/core/src/release.generated.ts +++ b/frontend/core/src/release.generated.ts @@ -1,3 +1,3 @@ // Generated by argus_skill.release_tools.generate_manifest. Do not edit. -export const RELEASE_ID = "0.1.1+3fe127f899db9e23"; -export const RELEASE_SOURCE_DIGEST = "3fe127f899db9e23aa1cd36118ac3419edb3e74e83ac34771fc755df6cce36c1"; +export const RELEASE_ID = "0.1.1+a4de81c666ef26a3"; +export const RELEASE_SOURCE_DIGEST = "a4de81c666ef26a3645b67f679e18132546e5ec92003000d736e503810fa9700"; diff --git a/frontend/tui/bundle/argus.mjs b/frontend/tui/bundle/argus.mjs index 2bae676b7..66690e328 100644 --- a/frontend/tui/bundle/argus.mjs +++ b/frontend/tui/bundle/argus.mjs @@ -121,7 +121,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(r.setEncoding("utf8"),t){this.rawModeEnabledCount===0&&(r.ref(),r.setRawMode(!0),r.addListener("readable",this.handleReadable)),this.rawModeEnabledCount++;return}--this.rawModeEnabledCount===0&&(r.setRawMode(!1),r.removeListener("readable",this.handleReadable),r.unref())};handleReadable=()=>{let t;for(;(t=this.props.stdin.read())!==null;)this.handleInput(t),this.internal_eventEmitter.emit("input",t)};handleInput=t=>{t===""&&this.props.exitOnCtrlC&&this.handleExit(),t===MR&&this.state.activeFocusId&&this.setState({activeFocusId:void 0}),this.state.isFocusEnabled&&this.state.focusables.length>0&&(t===OR&&this.focusNext(),t===LR&&this.focusPrevious())};handleExit=t=>{this.isRawModeSupported()&&this.handleSetRawMode(!1),this.props.onExit(t)};enableFocus=()=>{this.setState({isFocusEnabled:!0})};disableFocus=()=>{this.setState({isFocusEnabled:!1})};focus=t=>{this.setState(r=>r.focusables.some(s=>s?.id===t)?{activeFocusId:t}:r)};focusNext=()=>{this.setState(t=>{let r=t.focusables.find(s=>s.isActive)?.id;return{activeFocusId:this.findNextFocusable(t)??r}})};focusPrevious=()=>{this.setState(t=>{let r=t.focusables.findLast(s=>s.isActive)?.id;return{activeFocusId:this.findPreviousFocusable(t)??r}})};addFocusable=(t,{autoFocus:r})=>{this.setState(i=>{let s=i.activeFocusId;return!s&&r&&(s=t),{activeFocusId:s,focusables:[...i.focusables,{id:t,isActive:!0}]}})};removeFocusable=t=>{this.setState(r=>({activeFocusId:r.activeFocusId===t?void 0:r.activeFocusId,focusables:r.focusables.filter(i=>i.id!==t)}))};activateFocusable=t=>{this.setState(r=>({focusables:r.focusables.map(i=>i.id!==t?i:{id:t,isActive:!0})}))};deactivateFocusable=t=>{this.setState(r=>({activeFocusId:r.activeFocusId===t?void 0:r.activeFocusId,focusables:r.focusables.map(i=>i.id!==t?i:{id:t,isActive:!1})}))};findNextFocusable=t=>{let r=t.focusables.findIndex(i=>i.id===t.activeFocusId);for(let i=r+1;i{let r=t.focusables.findIndex(i=>i.id===t.activeFocusId);for(let i=r-1;i>=0;i--){let s=t.focusables[i];if(s?.isActive)return s.id}}};var ty=()=>{},hf=class{options;log;throttledLog;isUnmounted;lastOutput;container;rootNode;fullStaticOutput;exitPromise;restoreConsole;unsubscribeResize;constructor(t){IE(this),this.options=t,this.rootNode=od("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.rootNode.onRender=t.debug?this.onRender:Pg(this.onRender,32,{leading:!0,trailing:!0}),this.rootNode.onImmediateRender=this.onRender,this.log=xD.create(t.stdout),this.throttledLog=t.debug?this.log:Pg(this.log,void 0,{leading:!0,trailing:!0}),this.isUnmounted=!1,this.lastOutput="",this.fullStaticOutput="",this.container=Ja.createContainer(this.rootNode,0,null,!1,null,"id",()=>{},null),this.unsubscribeExit=(0,ny.default)(this.unmount,{alwaysLast:!1}),PR.env.DEV==="true"&&Ja.injectIntoDevTools({bundleType:0,version:"16.13.1",rendererPackageName:"ink"}),t.patchConsole&&this.patchConsole(),Na||(t.stdout.on("resize",this.resized),this.unsubscribeResize=()=>{t.stdout.off("resize",this.resized)})}resized=()=>{this.calculateLayout(),this.onRender()};resolveExitPromise=()=>{};rejectExitPromise=()=>{};unsubscribeExit=()=>{};calculateLayout=()=>{let t=this.options.stdout.columns||80;this.rootNode.yogaNode.setWidth(t),this.rootNode.yogaNode.calculateLayout(void 0,void 0,it.DIRECTION_LTR)};onRender=()=>{if(this.isUnmounted)return;let{output:t,outputHeight:r,staticOutput:i}=yD(this.rootNode),s=i&&i!==` `;if(this.options.debug){s&&(this.fullStaticOutput+=i),this.options.stdout.write(this.fullStaticOutput+t);return}if(Na){s&&this.options.stdout.write(i),this.lastOutput=t;return}if(s&&(this.fullStaticOutput+=i),r>=this.options.stdout.rows){this.options.stdout.write(ko.clearTerminal+this.fullStaticOutput+t),this.lastOutput=t;return}s&&(this.log.clear(),this.options.stdout.write(i),this.log(t)),!s&&t!==this.lastOutput&&this.throttledLog(t),this.lastOutput=t};render(t){let r=ry.default.createElement(If,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount},t);Ja.updateContainer(r,this.container,null,ty)}writeToStdout(t){if(!this.isUnmounted){if(this.options.debug){this.options.stdout.write(t+this.fullStaticOutput+this.lastOutput);return}if(Na){this.options.stdout.write(t);return}this.log.clear(),this.options.stdout.write(t),this.log(this.lastOutput)}}writeToStderr(t){if(!this.isUnmounted){if(this.options.debug){this.options.stderr.write(t),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(Na){this.options.stderr.write(t);return}this.log.clear(),this.options.stderr.write(t),this.log(this.lastOutput)}}unmount(t){this.isUnmounted||(this.calculateLayout(),this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole=="function"&&this.restoreConsole(),typeof this.unsubscribeResize=="function"&&this.unsubscribeResize(),Na?this.options.stdout.write(this.lastOutput+` `):this.options.debug||this.log.done(),this.isUnmounted=!0,Ja.updateContainer(null,this.container,null,ty),wu.delete(this.options.stdout),t instanceof Error?this.rejectExitPromise(t):this.resolveExitPromise())}async waitUntilExit(){return this.exitPromise||=new Promise((t,r)=>{this.resolveExitPromise=t,this.rejectExitPromise=r}),this.exitPromise}clear(){!Na&&!this.options.debug&&this.log.clear()}patchConsole(){this.options.debug||(this.restoreConsole=Wh((t,r)=>{t==="stdout"&&this.writeToStdout(r),t==="stderr"&&(r.startsWith("The above error occurred")||this.writeToStderr(r))}))}};var GR=(e,t)=>{let r={stdout:Pd.stdout,stdin:Pd.stdin,stderr:Pd.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0,...HR(t)},i=WR(r.stdout,()=>new hf(r));return i.render(e),{rerender:i.render,unmount(){i.unmount()},waitUntilExit:i.waitUntilExit,cleanup:()=>wu.delete(r.stdout),clear:i.clear}},Um=GR,HR=(e={})=>e instanceof UR?{stdout:e,stdin:Pd.stdin}:e,WR=(e,t)=>{let r=wu.get(e);return r||(r=t(),wu.set(e,r)),r};var iA=Me(jt(),1);function Cf(e){let{items:t,children:r,style:i}=e,[s,a]=(0,iA.useState)(0),u=(0,iA.useMemo)(()=>t.slice(s),[t,s]);(0,iA.useLayoutEffect)(()=>{a(t.length)},[t.length]);let E=u.map((C,y)=>r(C,s+y)),I=(0,iA.useMemo)(()=>({position:"absolute",flexDirection:"column",...i}),[i]);return iA.default.createElement("ink-box",{internal_static:!0,style:I},E)}var KR=Me(jt(),1);var JR=Me(jt(),1);var jR=Me(jt(),1);var Gm=Me(jt(),1);import{Buffer as YR}from"node:buffer";var VR=/^(?:\x1b)([a-zA-Z0-9])$/,qR=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,oy={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},iy=[...Object.values(oy),"backspace"],zR=e=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(e),$R=e=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(e),XR=(e="")=>{let t;YR.isBuffer(e)?e[0]>127&&e[1]===void 0?(e[0]-=128,e="\x1B"+String(e)):e=String(e):e!==void 0&&typeof e!="string"?e=String(e):e||(e="");let r={name:"",ctrl:!1,meta:!1,shift:!1,option:!1,sequence:e,raw:e};if(r.sequence=r.sequence||e||r.name,e==="\r")r.raw=void 0,r.name="return";else if(e===` -`)r.name="enter";else if(e===" ")r.name="tab";else if(e==="\b"||e==="\x1B\b")r.name="backspace",r.meta=e.charAt(0)==="\x1B";else if(e==="\x7F"||e==="\x1B\x7F")r.name="delete",r.meta=e.charAt(0)==="\x1B";else if(e==="\x1B"||e==="\x1B\x1B")r.name="escape",r.meta=e.length===2;else if(e===" "||e==="\x1B ")r.name="space",r.meta=e.length===2;else if(e.length===1&&e<="")r.name=String.fromCharCode(e.charCodeAt(0)+97-1),r.ctrl=!0;else if(e.length===1&&e>="0"&&e<="9")r.name="number";else if(e.length===1&&e>="a"&&e<="z")r.name=e;else if(e.length===1&&e>="A"&&e<="Z")r.name=e.toLowerCase(),r.shift=!0;else if(t=VR.exec(e))r.meta=!0,r.shift=/^[A-Z]$/.test(t[1]);else if(t=qR.exec(e)){let i=[...e];i[0]==="\x1B"&&i[1]==="\x1B"&&(r.option=!0);let s=[t[1],t[2],t[4],t[6]].filter(Boolean).join(""),a=(t[3]||t[5]||1)-1;r.ctrl=!!(a&4),r.meta=!!(a&10),r.shift=!!(a&1),r.code=s,r.name=oy[s],r.shift=zR(s)||r.shift,r.ctrl=$R(s)||r.ctrl}return r},sy=XR;var Ay=Me(jt(),1);var ZR=()=>(0,Ay.useContext)(Nd),Ud=ZR;var eF=(e,t={})=>{let{stdin:r,setRawMode:i,internal_exitOnCtrlC:s,internal_eventEmitter:a}=Ud();(0,Gm.useEffect)(()=>{if(t.isActive!==!1)return i(!0),()=>{i(!1)}},[t.isActive,i]),(0,Gm.useEffect)(()=>{if(t.isActive===!1)return;let u=E=>{let I=sy(E),C={upArrow:I.name==="up",downArrow:I.name==="down",leftArrow:I.name==="left",rightArrow:I.name==="right",pageDown:I.name==="pagedown",pageUp:I.name==="pageup",return:I.name==="return",escape:I.name==="escape",ctrl:I.ctrl,shift:I.shift,tab:I.name==="tab",backspace:I.name==="backspace",delete:I.name==="delete",meta:I.meta||I.name==="escape"||I.option},y=I.ctrl?I.name:I.sequence;iy.includes(I.name)&&(y=""),y.startsWith("\x1B")&&(y=y.slice(1)),y.length===1&&typeof y[0]=="string"&&/[A-Z]/.test(y[0])&&(C.shift=!0),(!(y==="c"&&C.ctrl)||!s)&&Ja.batchedUpdates(()=>{e(y,C)})};return a?.on("input",u),()=>{a?.removeListener("input",u)}},[t.isActive,r,s,e])},rs=eF;var ay=Me(jt(),1);var tF=()=>(0,ay.useContext)(kd),sA=tF;var ly=Me(jt(),1);var rF=()=>(0,ly.useContext)(Td),AA=rF;var nF=Me(jt(),1);var Hm=Me(jt(),1);var oF=Me(jt(),1);mm();import{randomUUID as Wd}from"node:crypto";import{homedir as dF}from"node:os";import{posix as pF,win32 as Ym}from"node:path";var Wm=class extends Error{status;method;path;constructor(t,r,i,s){super(t),this.name="ApiError",this.status=r,this.method=i,this.path=s}};function iF(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"";try{let r=JSON.parse(e);for(let i of["detail","error","message"]){let s=r[i];if(typeof s=="string"&&s.trim())return s.trim();if(Array.isArray(s)){let a=s.map(u=>u&&typeof u=="object"?String(u.msg??""):"").filter(Boolean);if(a.length)return a.join("; ")}}}catch{}return t.startsWith("typeof D=="string"):[],u=Km(i?.major),E=Km(i?.minor);if(!r||!i||!s)return{compatible:!1,reason:"malformed /api/meta response"};if(typeof s.source_root!="string"||Km(s.pid)===null||typeof s.package_version!="string"||typeof s.release_id!="string")return{compatible:!1,reason:"malformed /api/meta runtime identity"};if(r.service!==AF)return{compatible:!1,reason:`unexpected service ${String(r.service||"unknown")}`};let I=e;if(i.name!==Su.name||u!==Su.major)return{compatible:!1,reason:`protocol ${String(i.name||"unknown")}/${String(u)} is incompatible with client ${Su.name}/${Su.major}`,meta:I};if(E===null||E!a.includes(D));if(C.length>0)return{compatible:!1,reason:`missing capabilities: ${C.join(", ")}`,meta:I};if(s.source_root_matches_config===!1)return{compatible:!1,reason:`backend loaded source ${String(s.source_root)} but ARGUS_SKILL_SOURCE_ROOT points to ${String(s.configured_source_root)}`,meta:I};if(s.release_id!==t.releaseId)return{compatible:!1,reason:`backend release ${String(s.release_id)} does not match client release ${t.releaseId}`,meta:I};if(t.sourceDigest){if(typeof s.runtime_source_digest!="string"||!s.runtime_source_digest)return{compatible:!1,reason:"backend process does not report the source digest required by this local checkout",meta:I};if(s.runtime_source_digest!==t.sourceDigest)return{compatible:!1,reason:`backend process source ${String(s.runtime_source_digest).slice(0,16)} does not match local source ${t.sourceDigest.slice(0,16)}`,meta:I}}return{compatible:!0,reason:"",warning:s.release_matches_source===!1?"backend source differs from its prebuilt release artifacts; pull a complete published revision and reinstall":void 0,meta:I}}function cy(e,t){let r=Jm(e);if(!r.compatible||!r.meta)throw new Error(`incompatible Argus API: ${r.reason}`);return r.warning&&t?.(r.warning),r.meta}function fy(e){let t=Bf(e),r=Bf(t?.daemon);if(!t||t.schema_version!==Hd)throw new Error(`incompatible snapshot schema: expected ${Hd}, got ${String(t?.schema_version??"missing")}`);if(!r)throw new Error("invalid snapshot: daemon section is missing");let s=["global_daily_cap_usd","read_status","read_error","protocol_compatible","protocol_error"].filter(E=>!Object.hasOwn(r,E));if(s.length>0)throw new Error(`invalid snapshot: daemon fields missing: ${s.join(", ")}`);let u=["spend_usd","spend_status","usage_summary","request_usage","cost_control","daemon_commands","observability","mission_view","partial","diagnostics"].filter(E=>!Object.hasOwn(t,E));if(u.length>0)throw new Error(`invalid snapshot: fields missing: ${u.join(", ")}`);if(!Array.isArray(t.diagnostics))throw new Error("invalid snapshot: diagnostics must be an array");return e}function jm(e){let t=typeof e=="string"||e instanceof URL?String(e):e.url;try{let r=new URL(t);return r.username="",r.password="",r.searchParams.has("token")&&r.searchParams.set("token","[redacted]"),r.toString()}catch{return t}}function ja(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}function lF(e){let t=ja(e,"cause"),r=new Set;for(;ja(t,"cause")&&!r.has(t);)r.add(t),t=ja(t,"cause");return t??e}function uF(e,t,r="GET"){let i=lF(e),s=String(ja(i,"code")??"").trim(),a=String(ja(i,"address")??"").trim(),u=String(ja(i,"port")??"").trim(),E=a&&u?`${a}:${u}`:a,I=i instanceof Error?i.message.trim():String(i??"").trim(),C=e instanceof Error?e.message.trim():String(e??"").trim(),y;return s==="ECONNREFUSED"?y=`connection refused${E?` by ${E}`:""}`:s==="ECONNRESET"?y="connection reset by the local service":s==="ETIMEDOUT"?y="connection timed out":s==="ENOTFOUND"?y="host name could not be resolved":I&&I!==C?y=I:y=C||"network request failed",`${r.toUpperCase()} ${jm(t)} failed: ${y}${s?` (${s})`:""}`}function gy(e){return e%1e3===0?`${e/1e3}s`:`${e}ms`}async function cF(e,t,r,i,s){let a=Number.isFinite(r)&&r>0?Math.max(1,Math.trunc(r)):1,u=new AbortController,E=t.signal,I=!1,C=!1,y=()=>u.abort(E?.reason);E?.aborted?y():E?.addEventListener("abort",y,{once:!0});let D=(async()=>{let G=await fetch(e,{...t,signal:u.signal});return C=!0,await s(G)})(),R,O=new Promise((G,ne)=>{R=setTimeout(()=>{I=!0;let oe=new Error(`request timed out after ${gy(a)}`);u.abort(oe),ne(oe)},a)});try{return await Promise.race([D,O])}catch(G){throw I?new Error(`${i.toUpperCase()} ${jm(e)} timed out after ${gy(a)}; the local Argus service did not respond`,{cause:G}):E?.aborted?E.reason instanceof Error?E.reason:new Error(`${i.toUpperCase()} ${jm(e)} was aborted`,{cause:G}):C&&ja(G,"cause")===void 0?G:new Error(uF(G,e,i),{cause:G})}finally{R&&clearTimeout(R),E?.removeEventListener("abort",y)}}function zA(e,t,r,i,s=t.method??"GET"){return cF(e,t,r,s,i)}function EF(e,t=dF()){let r=E=>E.includes("\\")||/^[A-Za-z]:[\\/]/.test(E),i=r(e)?Ym:pF,s=i.resolve(e),a=E=>i===Ym?E.toLowerCase():E,u=r(t)===(i===Ym)?a(i.resolve(t)):"";if(!(a(s)===u||a(s)===a(i.parse(s).root)))return s}function mF(e,t=""){let r=t.trim();return e===4401?{code:e,reason:r||"event stream authentication was rejected",retryable:!1}:e===4404?{code:e,reason:r||"the selected project no longer exists",retryable:!1}:{code:e,reason:r,retryable:!0}}function Vm(e){let t=e.item?.title||"new mission";return e.daemon?.admission_required?`\u2192 queued: choose one running session to park before starting ${t}`:e.daemon&&e.daemon.rc!==0?`\u2192 queued but not running: ${e.daemon.error||"background executor failed to start"}`:`\u2192 dispatched to the team: ${t}`}function dy(e){let t=[],r;for(;(r=e.indexOf(` +`)r.name="enter";else if(e===" ")r.name="tab";else if(e==="\b"||e==="\x1B\b")r.name="backspace",r.meta=e.charAt(0)==="\x1B";else if(e==="\x7F"||e==="\x1B\x7F")r.name="delete",r.meta=e.charAt(0)==="\x1B";else if(e==="\x1B"||e==="\x1B\x1B")r.name="escape",r.meta=e.length===2;else if(e===" "||e==="\x1B ")r.name="space",r.meta=e.length===2;else if(e.length===1&&e<="")r.name=String.fromCharCode(e.charCodeAt(0)+97-1),r.ctrl=!0;else if(e.length===1&&e>="0"&&e<="9")r.name="number";else if(e.length===1&&e>="a"&&e<="z")r.name=e;else if(e.length===1&&e>="A"&&e<="Z")r.name=e.toLowerCase(),r.shift=!0;else if(t=VR.exec(e))r.meta=!0,r.shift=/^[A-Z]$/.test(t[1]);else if(t=qR.exec(e)){let i=[...e];i[0]==="\x1B"&&i[1]==="\x1B"&&(r.option=!0);let s=[t[1],t[2],t[4],t[6]].filter(Boolean).join(""),a=(t[3]||t[5]||1)-1;r.ctrl=!!(a&4),r.meta=!!(a&10),r.shift=!!(a&1),r.code=s,r.name=oy[s],r.shift=zR(s)||r.shift,r.ctrl=$R(s)||r.ctrl}return r},sy=XR;var Ay=Me(jt(),1);var ZR=()=>(0,Ay.useContext)(Nd),Ud=ZR;var eF=(e,t={})=>{let{stdin:r,setRawMode:i,internal_exitOnCtrlC:s,internal_eventEmitter:a}=Ud();(0,Gm.useEffect)(()=>{if(t.isActive!==!1)return i(!0),()=>{i(!1)}},[t.isActive,i]),(0,Gm.useEffect)(()=>{if(t.isActive===!1)return;let u=E=>{let I=sy(E),C={upArrow:I.name==="up",downArrow:I.name==="down",leftArrow:I.name==="left",rightArrow:I.name==="right",pageDown:I.name==="pagedown",pageUp:I.name==="pageup",return:I.name==="return",escape:I.name==="escape",ctrl:I.ctrl,shift:I.shift,tab:I.name==="tab",backspace:I.name==="backspace",delete:I.name==="delete",meta:I.meta||I.name==="escape"||I.option},y=I.ctrl?I.name:I.sequence;iy.includes(I.name)&&(y=""),y.startsWith("\x1B")&&(y=y.slice(1)),y.length===1&&typeof y[0]=="string"&&/[A-Z]/.test(y[0])&&(C.shift=!0),(!(y==="c"&&C.ctrl)||!s)&&Ja.batchedUpdates(()=>{e(y,C)})};return a?.on("input",u),()=>{a?.removeListener("input",u)}},[t.isActive,r,s,e])},rs=eF;var ay=Me(jt(),1);var tF=()=>(0,ay.useContext)(kd),sA=tF;var ly=Me(jt(),1);var rF=()=>(0,ly.useContext)(Td),AA=rF;var nF=Me(jt(),1);var Hm=Me(jt(),1);var oF=Me(jt(),1);mm();import{randomUUID as Wd}from"node:crypto";import{homedir as dF}from"node:os";import{posix as pF,win32 as Ym}from"node:path";var Wm=class extends Error{status;method;path;constructor(t,r,i,s){super(t),this.name="ApiError",this.status=r,this.method=i,this.path=s}};function iF(e){let t=e.replace(/\s+/g," ").trim();if(!t)return"";try{let r=JSON.parse(e);for(let i of["detail","error","message"]){let s=r[i];if(typeof s=="string"&&s.trim())return s.trim();if(Array.isArray(s)){let a=s.map(u=>u&&typeof u=="object"?String(u.msg??""):"").filter(Boolean);if(a.length)return a.join("; ")}}}catch{}return t.startsWith("typeof D=="string"):[],u=Km(i?.major),E=Km(i?.minor);if(!r||!i||!s)return{compatible:!1,reason:"malformed /api/meta response"};if(typeof s.source_root!="string"||Km(s.pid)===null||typeof s.package_version!="string"||typeof s.release_id!="string")return{compatible:!1,reason:"malformed /api/meta runtime identity"};if(r.service!==AF)return{compatible:!1,reason:`unexpected service ${String(r.service||"unknown")}`};let I=e;if(i.name!==Su.name||u!==Su.major)return{compatible:!1,reason:`protocol ${String(i.name||"unknown")}/${String(u)} is incompatible with client ${Su.name}/${Su.major}`,meta:I};if(E===null||E!a.includes(D));if(C.length>0)return{compatible:!1,reason:`missing capabilities: ${C.join(", ")}`,meta:I};if(s.source_root_matches_config===!1)return{compatible:!1,reason:`backend loaded source ${String(s.source_root)} but ARGUS_SKILL_SOURCE_ROOT points to ${String(s.configured_source_root)}`,meta:I};if(s.release_id!==t.releaseId)return{compatible:!1,reason:`backend release ${String(s.release_id)} does not match client release ${t.releaseId}`,meta:I};if(t.sourceDigest){if(typeof s.runtime_source_digest!="string"||!s.runtime_source_digest)return{compatible:!1,reason:"backend process does not report the source digest required by this local checkout",meta:I};if(s.runtime_source_digest!==t.sourceDigest)return{compatible:!1,reason:`backend process source ${String(s.runtime_source_digest).slice(0,16)} does not match local source ${t.sourceDigest.slice(0,16)}`,meta:I}}return{compatible:!0,reason:"",warning:s.release_matches_source===!1?"backend source differs from its prebuilt release artifacts; pull a complete published revision and reinstall":void 0,meta:I}}function cy(e,t){let r=Jm(e);if(!r.compatible||!r.meta)throw new Error(`incompatible Argus API: ${r.reason}`);return r.warning&&t?.(r.warning),r.meta}function fy(e){let t=Bf(e),r=Bf(t?.daemon);if(!t||t.schema_version!==Hd)throw new Error(`incompatible snapshot schema: expected ${Hd}, got ${String(t?.schema_version??"missing")}`);if(!r)throw new Error("invalid snapshot: daemon section is missing");let s=["global_daily_cap_usd","read_status","read_error","protocol_compatible","protocol_error"].filter(E=>!Object.hasOwn(r,E));if(s.length>0)throw new Error(`invalid snapshot: daemon fields missing: ${s.join(", ")}`);let u=["spend_usd","spend_status","usage_summary","request_usage","cost_control","daemon_commands","observability","mission_view","partial","diagnostics"].filter(E=>!Object.hasOwn(t,E));if(u.length>0)throw new Error(`invalid snapshot: fields missing: ${u.join(", ")}`);if(!Array.isArray(t.diagnostics))throw new Error("invalid snapshot: diagnostics must be an array");return e}function jm(e){let t=typeof e=="string"||e instanceof URL?String(e):e.url;try{let r=new URL(t);return r.username="",r.password="",r.searchParams.has("token")&&r.searchParams.set("token","[redacted]"),r.toString()}catch{return t}}function ja(e,t){return typeof e=="object"&&e!==null?e[t]:void 0}function lF(e){let t=ja(e,"cause"),r=new Set;for(;ja(t,"cause")&&!r.has(t);)r.add(t),t=ja(t,"cause");return t??e}function uF(e,t,r="GET"){let i=lF(e),s=String(ja(i,"code")??"").trim(),a=String(ja(i,"address")??"").trim(),u=String(ja(i,"port")??"").trim(),E=a&&u?`${a}:${u}`:a,I=i instanceof Error?i.message.trim():String(i??"").trim(),C=e instanceof Error?e.message.trim():String(e??"").trim(),y;return s==="ECONNREFUSED"?y=`connection refused${E?` by ${E}`:""}`:s==="ECONNRESET"?y="connection reset by the local service":s==="ETIMEDOUT"?y="connection timed out":s==="ENOTFOUND"?y="host name could not be resolved":I&&I!==C?y=I:y=C||"network request failed",`${r.toUpperCase()} ${jm(t)} failed: ${y}${s?` (${s})`:""}`}function gy(e){return e%1e3===0?`${e/1e3}s`:`${e}ms`}async function cF(e,t,r,i,s){let a=Number.isFinite(r)&&r>0?Math.max(1,Math.trunc(r)):1,u=new AbortController,E=t.signal,I=!1,C=!1,y=()=>u.abort(E?.reason);E?.aborted?y():E?.addEventListener("abort",y,{once:!0});let D=(async()=>{let G=await fetch(e,{...t,signal:u.signal});return C=!0,await s(G)})(),R,O=new Promise((G,ne)=>{R=setTimeout(()=>{I=!0;let oe=new Error(`request timed out after ${gy(a)}`);u.abort(oe),ne(oe)},a)});try{return await Promise.race([D,O])}catch(G){throw I?new Error(`${i.toUpperCase()} ${jm(e)} timed out after ${gy(a)}; the local Argus service did not respond`,{cause:G}):E?.aborted?E.reason instanceof Error?E.reason:new Error(`${i.toUpperCase()} ${jm(e)} was aborted`,{cause:G}):C&&ja(G,"cause")===void 0?G:new Error(uF(G,e,i),{cause:G})}finally{R&&clearTimeout(R),E?.removeEventListener("abort",y)}}function zA(e,t,r,i,s=t.method??"GET"){return cF(e,t,r,s,i)}function EF(e,t=dF()){let r=E=>E.includes("\\")||/^[A-Za-z]:[\\/]/.test(E),i=r(e)?Ym:pF,s=i.resolve(e),a=E=>i===Ym?E.toLowerCase():E,u=r(t)===(i===Ym)?a(i.resolve(t)):"";if(!(a(s)===u||a(s)===a(i.parse(s).root)))return s}function mF(e,t=""){let r=t.trim();return e===4401?{code:e,reason:r||"event stream authentication was rejected",retryable:!1}:e===4404?{code:e,reason:r||"the selected project no longer exists",retryable:!1}:{code:e,reason:r,retryable:!0}}function Vm(e){let t=e.item?.title||"new mission";return e.daemon?.admission_required?`\u2192 queued: choose one running session to park before starting ${t}`:e.daemon&&e.daemon.rc!==0?`\u2192 queued but not running: ${e.daemon.error||"background executor failed to start"}`:`\u2192 dispatched to the team: ${t}`}function dy(e){let t=[],r;for(;(r=e.indexOf(` `))>=0;){let i=e.slice(0,r);e=e.slice(r+2);for(let s of i.split(` `)){let a=s.trim();if(a.startsWith("data:"))try{t.push(JSON.parse(a.slice(5).trim()))}catch{}}}return{frames:t,rest:e}}var ns=class{httpBase;wsBase;project;token;onCompatibilityWarning;metaTimeoutMs;readTimeoutMs;metaPromise;constructor(t){this.httpBase=`http://${t.host}:${t.port}`,this.wsBase=`ws://${t.host}:${t.port}`,this.project=t.project,this.token=t.token,this.onCompatibilityWarning=t.onCompatibilityWarning,this.metaTimeoutMs=t.metaTimeoutMs??8e3,this.readTimeoutMs=t.readTimeoutMs??12e3}authHeaders(){return this.token?{Authorization:`Bearer ${this.token}`}:{}}p(t){return`${this.httpBase}/api/projects/${encodeURIComponent(this.project)}${t}`}meta(){if(!this.metaPromise){let t="/api/meta",r=zA(`${this.httpBase}${t}`,{headers:this.authHeaders()},this.metaTimeoutMs,async i=>{if(i.status===404)throw new Error("incompatible Argus API: service does not expose /api/meta");return await co(i,"GET",t),cy(await i.json(),this.onCompatibilityWarning)});this.metaPromise=r,r.catch(()=>{this.metaPromise===r&&(this.metaPromise=void 0)})}return this.metaPromise}async listProjects(){return await this.meta(),zA(`${this.httpBase}/api/projects`,{headers:this.authHeaders()},this.readTimeoutMs,async t=>(await co(t,"GET","/api/projects"),(await t.json()).projects))}async createDaemon(t="",r="",i=process.cwd(),s,a=Wd()){let u="/api/daemons",E=EF(i),I={objective:t,name:r,launch_cwd:i,command_id:a,expected_revision:s};E&&(I.workdir=E);let C=JSON.stringify(I),y=()=>fetch(`${this.httpBase}${u}`,{method:"POST",headers:{"Content-Type":"application/json",Connection:"close",...this.authHeaders()},body:C}),D=await y();return D.status===400&&/Invalid HTTP request received/i.test(await D.clone().text())&&(D=await y()),await co(D,"POST",u),await D.json()}async replaceDaemon(t,r=!1,i,s=Wd()){return await this.post("/daemon/replace",{victim_sid:t,resume_continuous:r,command_id:s,expected_revision:i})}async scheduleDaemonUpgrade(t,r,i=Wd()){let s=`/api/projects/${encodeURIComponent(t)}/daemon/upgrade-schedule`,a=await fetch(`${this.httpBase}${s}`,{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({command_id:i,expected_revision:r})});return await co(a,"POST",s),await a.json()}stopDaemon(t=Wd()){let r="/daemon/stop";return zA(this.p(r),{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({force:!1,drain:!1,command_id:t})},this.readTimeoutMs,async i=>{await co(i,"POST",r);let s=await i.json(),a=Number(s.rc??0);if(!Number.isFinite(a)||![0,1].includes(a)){let u=String(s.error??s.message??`rc=${String(s.rc??"unknown")}`);throw new Error(`executor did not stop cleanly: ${u}`)}return s})}async setProjectLaunchCwd(t,r){let i=`/api/projects/${encodeURIComponent(t)}/launch-cwd`,s=await fetch(`${this.httpBase}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({launch_cwd:r})});await co(s,"POST",i)}async setProjectWorkdir(t,r){let i=`/api/projects/${encodeURIComponent(t)}/workdir`,s=await fetch(`${this.httpBase}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({workdir:r})});await co(s,"POST",i)}async renameProject(t){let r=this.p(""),i=await fetch(r,{method:"PATCH",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({name:t})});return await co(i,"PATCH",r),await i.json()}async snapshot(t=1,r){return await this.meta(),zA(this.p(`/snapshot?compact=true&events_limit=${t}`),{headers:this.authHeaders(),signal:r},this.readTimeoutMs,async i=>(await co(i,"GET","/snapshot"),fy(await i.json())))}async postTask(t){let r=await fetch(this.p("/tasks"),{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({text:t})});return await co(r,"POST","/tasks"),(await r.json()).item}async postNudge(t){let r=await fetch(this.p("/nudge"),{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({text:t})});await co(r,"POST","/nudge")}async message(t,r){let i=await fetch(this.p("/message"),{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({text:t}),signal:r});return await co(i,"POST","/message"),await i.json()}async messageStream(t,r,i){let s=await fetch(this.p("/message/stream"),{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({text:t}),signal:i});if(await co(s,"POST","/message/stream"),!s.body)throw new Error("Manager stream returned no response body");let a=C=>{if(!i?.aborted)if(C.type==="phase"){let y=Number(C.quiet_s??0);r.onPhase?.(String(C.label??""),String(C.role??"manager"),{heartbeat:C.heartbeat===!0,quietS:Number.isFinite(y)?y:0,kind:String(C.kind??""),detail:String(C.detail??"")})}else C.type==="delta"?r.onDelta?.(String(C.text??""),String(C.message_id??""),String(C.fragment_mode??"auto")):C.type==="done"?r.onDone?.(C.result??{}):C.type==="error"&&r.onError?.(new Error(String(C.error??"stream error")))},u=s.body.getReader(),E=new TextDecoder,I="";for(;;){let{done:C,value:y}=await u.read();if(C)break;I+=E.decode(y,{stream:!0});let D=dy(I);I=D.rest,D.frames.forEach(a)}i?.aborted||dy(I+` diff --git a/frontend/web/dist/assets/ResearchWorkbenchPanel-D4WnlzR6.js b/frontend/web/dist/assets/ResearchWorkbenchPanel-BOPEGTC6.js similarity index 99% rename from frontend/web/dist/assets/ResearchWorkbenchPanel-D4WnlzR6.js rename to frontend/web/dist/assets/ResearchWorkbenchPanel-BOPEGTC6.js index 28549896d..900910650 100644 --- a/frontend/web/dist/assets/ResearchWorkbenchPanel-D4WnlzR6.js +++ b/frontend/web/dist/assets/ResearchWorkbenchPanel-BOPEGTC6.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdf-BdyXXgZL.js","assets/index-7NNAUeAk.js","assets/rolldown-runtime-hePW80VL.js","assets/icons-BgG77X6K.js","assets/query-DOc9YWJi.js","assets/markdown-BdostSiP.js","assets/index-BsbGxZOe.css"])))=>i.map(i=>d[i]); -import{r as e}from"./rolldown-runtime-hePW80VL.js";import{D as t,E as n}from"./icons-BgG77X6K.js";import{i as r,n as i,t as a}from"./query-DOc9YWJi.js";import{n as o,t as s}from"./markdown-BdostSiP.js";import{a as c,i as l,n as u,o as d,r as f,t as p}from"./index-7NNAUeAk.js";var m=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),h=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),g={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},_=e(t()),v=(0,_.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,_.createElement)(`svg`,{ref:c,...g,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:h(`lucide`,i),...s},[...o.map(([e,t])=>(0,_.createElement)(e,t)),...Array.isArray(a)?a:[a]])),y=(e,t)=>{let n=(0,_.forwardRef)(({className:n,...r},i)=>(0,_.createElement)(v,{ref:i,iconNode:t,className:h(`lucide-${m(e)}`,n),...r}));return n.displayName=`${e}`,n},b=y(`Activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),x=y(`ArrowRight`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),S=y(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),C=y(`AudioLines`,[[`path`,{d:`M2 10v3`,key:`1fnikh`}],[`path`,{d:`M6 6v11`,key:`11sgs0`}],[`path`,{d:`M10 3v18`,key:`yhl04a`}],[`path`,{d:`M14 8v7`,key:`3a1oy3`}],[`path`,{d:`M18 5v13`,key:`123xd1`}],[`path`,{d:`M22 10v3`,key:`154ddg`}]]),w=y(`BookOpen`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z`,key:`ruj8y`}]]),T=y(`Calendar`,[[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`4`,rx:`2`,key:`1hopcy`}],[`path`,{d:`M3 10h18`,key:`8toen8`}]]),E=y(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),D=y(`ChevronDown`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),ee=y(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),O=y(`CircleCheck`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),k=y(`Circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),A=y(`Clock3`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`polyline`,{points:`12 6 12 12 16.5 12`,key:`1aq6pp`}]]),j=y(`CodeXml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),M=y(`Earth`,[[`path`,{d:`M21.54 15H17a2 2 0 0 0-2 2v4.54`,key:`1djwo0`}],[`path`,{d:`M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17`,key:`1tzkfa`}],[`path`,{d:`M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05`,key:`14pb5j`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),N=y(`ExternalLink`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),te=y(`FileCheck2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m3 15 2 2 4-4`,key:`1lhrkk`}]]),P=y(`FileCode2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m5 12-3 3 3 3`,key:`oke12k`}],[`path`,{d:`m9 18 3-3-3-3`,key:`112psh`}]]),ne=y(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),re=y(`FileJson`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),F=y(`FileSearch2`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`11.5`,cy:`14.5`,r:`2.5`,key:`1bq0ko`}],[`path`,{d:`M13.3 16.3 15 18`,key:`2quom7`}]]),ie=y(`FileSearch`,[[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3`,key:`ms7g94`}],[`path`,{d:`m9 18-1.5-1.5`,key:`1j6qii`}],[`circle`,{cx:`5`,cy:`14`,r:`3`,key:`ufru5t`}]]),I=y(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),L=y(`FileUp`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M12 12v6`,key:`3ahymv`}],[`path`,{d:`m15 15-3-3-3 3`,key:`15xj92`}]]),ae=y(`File`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}]]),oe=y(`Files`,[[`path`,{d:`M20 7h-3a2 2 0 0 1-2-2V2`,key:`x099mo`}],[`path`,{d:`M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z`,key:`18t6ie`}],[`path`,{d:`M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8`,key:`1nja0z`}]]),se=y(`FlaskConical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),ce=y(`FolderKanban`,[[`path`,{d:`M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z`,key:`1fr9dc`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M12 10v2`,key:`hh53o1`}],[`path`,{d:`M16 10v6`,key:`1d6xys`}]]),le=y(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),ue=y(`FolderSearch`,[[`path`,{d:`M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1`,key:`1bw5m7`}],[`path`,{d:`m21 21-1.9-1.9`,key:`1g2n9r`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}]]),de=y(`Folder`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),fe=y(`Gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),pe=y(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),me=y(`Github`,[[`path`,{d:`M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4`,key:`tonef`}],[`path`,{d:`M9 18c-4.51 2-5-2-7-2`,key:`9comsn`}]]),he=y(`History`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),ge=y(`Image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),_e=y(`Inbox`,[[`polyline`,{points:`22 12 16 12 14 15 10 15 8 12 2 12`,key:`o97t9d`}],[`path`,{d:`M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z`,key:`oot6mr`}]]),ve=y(`Lightbulb`,[[`path`,{d:`M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5`,key:`1gvzjb`}],[`path`,{d:`M9 18h6`,key:`x1upvd`}],[`path`,{d:`M10 22h4`,key:`ceow96`}]]),ye=y(`Link2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),be=y(`ListChecks`,[[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`m3 7 2 2 4-4`,key:`1obspn`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),xe=y(`ListFilter`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M7 12h10`,key:`b7w52i`}],[`path`,{d:`M10 18h4`,key:`1ulq68`}]]),Se=y(`LoaderCircle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),Ce=y(`LockKeyhole`,[[`circle`,{cx:`12`,cy:`16`,r:`1`,key:`1au0dj`}],[`rect`,{x:`3`,y:`10`,width:`18`,height:`12`,rx:`2`,key:`6s8ecr`}],[`path`,{d:`M7 10V7a5 5 0 0 1 10 0v3`,key:`1pqi11`}]]),we=y(`Megaphone`,[[`path`,{d:`m3 11 18-5v12L3 14v-3z`,key:`n962bs`}],[`path`,{d:`M11.6 16.8a3 3 0 1 1-5.8-1.6`,key:`1yl0tm`}]]),Te=y(`MessageSquareText`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M13 8H7`,key:`14i4kc`}],[`path`,{d:`M17 12H7`,key:`16if0g`}]]),Ee=y(`MessagesSquare`,[[`path`,{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`,key:`p1xzt8`}],[`path`,{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`,key:`1cx29u`}]]),De=y(`PackageCheck`,[[`path`,{d:`m16 16 2 2 4-4`,key:`gfu2re`}],[`path`,{d:`M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14`,key:`e7tb2h`}],[`path`,{d:`m7.5 4.27 9 5.15`,key:`1c824w`}],[`polyline`,{points:`3.29 7 12 12 20.71 7`,key:`ousv84`}],[`line`,{x1:`12`,x2:`12`,y1:`22`,y2:`12`,key:`a4e8g8`}]]),Oe=y(`Paperclip`,[[`path`,{d:`M13.234 20.252 21 12.3`,key:`1cbrk9`}],[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486`,key:`1pkts6`}]]),ke=y(`Pause`,[[`rect`,{x:`14`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`zuxfzm`}],[`rect`,{x:`6`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`1okwgv`}]]),Ae=y(`Play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),je=y(`Plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Me=y(`Presentation`,[[`path`,{d:`M2 3h20`,key:`91anmk`}],[`path`,{d:`M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3`,key:`2k9sn8`}],[`path`,{d:`m7 21 5-5 5 5`,key:`bip4we`}]]),Ne=y(`Radio`,[[`path`,{d:`M4.9 19.1C1 15.2 1 8.8 4.9 4.9`,key:`1vaf9d`}],[`path`,{d:`M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5`,key:`u1ii0m`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`path`,{d:`M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5`,key:`1j5fej`}],[`path`,{d:`M19.1 4.9C23 8.8 23 15.1 19.1 19`,key:`10b0cb`}]]),Pe=y(`RefreshCw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Fe=y(`RotateCcw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Ie=y(`Save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),Le=y(`Scale`,[[`path`,{d:`m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z`,key:`7g6ntu`}],[`path`,{d:`m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z`,key:`ijws7r`}],[`path`,{d:`M7 21h10`,key:`1b0cd5`}],[`path`,{d:`M12 3v18`,key:`108xh3`}],[`path`,{d:`M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2`,key:`3gwbw2`}]]),Re=y(`Search`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`path`,{d:`m21 21-4.3-4.3`,key:`1qie3q`}]]),ze=y(`Send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),Be=y(`Server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),R=y(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),z=y(`Sparkles`,[[`path`,{d:`M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z`,key:`4pj2yx`}],[`path`,{d:`M20 3v4`,key:`1olli1`}],[`path`,{d:`M22 5h-4`,key:`1gvqau`}],[`path`,{d:`M4 17v2`,key:`vumght`}],[`path`,{d:`M5 18H3`,key:`zchphs`}]]),Ve=y(`SquareTerminal`,[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]]),He=y(`Square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Ue=y(`Table2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),We=y(`Target`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Ge=y(`TimerReset`,[[`path`,{d:`M10 2h4`,key:`n1abiw`}],[`path`,{d:`M12 14v-4`,key:`1evpnu`}],[`path`,{d:`M4 13a8 8 0 0 1 8-7 8 8 0 1 1-5.3 14L4 17.6`,key:`1ts96g`}],[`path`,{d:`M9 17H4v5`,key:`8t5av`}]]),Ke=y(`Trash2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),qe=y(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Je=y(`Upload`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`17 8 12 3 7 8`,key:`t8dd8p`}],[`line`,{x1:`12`,x2:`12`,y1:`3`,y2:`15`,key:`widbto`}]]),Ye=y(`UserRound`,[[`circle`,{cx:`12`,cy:`8`,r:`5`,key:`1hypcn`}],[`path`,{d:`M20 21a8 8 0 0 0-16 0`,key:`rfgkzh`}]]),Xe=y(`WandSparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),Ze=y(`Watch`,[[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`polyline`,{points:`12 10 12 12 13 13`,key:`19dquz`}],[`path`,{d:`m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05`,key:`18k57s`}],[`path`,{d:`m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05`,key:`16ny36`}]]),Qe=y(`Workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),$e=y(`Wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z`,key:`cbrjhi`}]]),et=y(`X`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),tt=12e3;function nt(e=!1){let t={...f()};return e&&(t[`Content-Type`]=`application/json`),t}async function B(e,t={}){await c();let n={...t,headers:{...nt(!!t.body),...t.headers??{}},cache:`no-store`},r=String(t.method??`GET`).toUpperCase(),i=async n=>{if(!n.ok){let r=await n.text().catch(()=>``),i=r;try{i=JSON.parse(r).detail??r}catch{}throw Error(i||`${t.method??`GET`} ${e} failed (${n.status})`)}return await n.json()};return r===`GET`?d(e,n,tt,i):i(await fetch(e,n))}var V=(e,t=``)=>`/api/projects/${encodeURIComponent(e)}${t}`,rt=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`;function it(e){let t=e.replaceAll(`\r +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdf-Dzq_asqX.js","assets/index-DYvAJ_cb.js","assets/rolldown-runtime-hePW80VL.js","assets/icons-BgG77X6K.js","assets/query-DOc9YWJi.js","assets/markdown-BdostSiP.js","assets/index-BsbGxZOe.css"])))=>i.map(i=>d[i]); +import{r as e}from"./rolldown-runtime-hePW80VL.js";import{D as t,E as n}from"./icons-BgG77X6K.js";import{i as r,n as i,t as a}from"./query-DOc9YWJi.js";import{n as o,t as s}from"./markdown-BdostSiP.js";import{a as c,i as l,n as u,o as d,r as f,t as p}from"./index-DYvAJ_cb.js";var m=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),h=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),g={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},_=e(t()),v=(0,_.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,_.createElement)(`svg`,{ref:c,...g,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:h(`lucide`,i),...s},[...o.map(([e,t])=>(0,_.createElement)(e,t)),...Array.isArray(a)?a:[a]])),y=(e,t)=>{let n=(0,_.forwardRef)(({className:n,...r},i)=>(0,_.createElement)(v,{ref:i,iconNode:t,className:h(`lucide-${m(e)}`,n),...r}));return n.displayName=`${e}`,n},b=y(`Activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),x=y(`ArrowRight`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),S=y(`ArrowUp`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),C=y(`AudioLines`,[[`path`,{d:`M2 10v3`,key:`1fnikh`}],[`path`,{d:`M6 6v11`,key:`11sgs0`}],[`path`,{d:`M10 3v18`,key:`yhl04a`}],[`path`,{d:`M14 8v7`,key:`3a1oy3`}],[`path`,{d:`M18 5v13`,key:`123xd1`}],[`path`,{d:`M22 10v3`,key:`154ddg`}]]),w=y(`BookOpen`,[[`path`,{d:`M12 7v14`,key:`1akyts`}],[`path`,{d:`M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z`,key:`ruj8y`}]]),T=y(`Calendar`,[[`path`,{d:`M8 2v4`,key:`1cmpym`}],[`path`,{d:`M16 2v4`,key:`4m81vk`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`4`,rx:`2`,key:`1hopcy`}],[`path`,{d:`M3 10h18`,key:`8toen8`}]]),E=y(`Check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),D=y(`ChevronDown`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),ee=y(`ChevronRight`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),O=y(`CircleCheck`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),k=y(`Circle`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),A=y(`Clock3`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`polyline`,{points:`12 6 12 12 16.5 12`,key:`1aq6pp`}]]),j=y(`CodeXml`,[[`path`,{d:`m18 16 4-4-4-4`,key:`1inbqp`}],[`path`,{d:`m6 8-4 4 4 4`,key:`15zrgr`}],[`path`,{d:`m14.5 4-5 16`,key:`e7oirm`}]]),M=y(`Earth`,[[`path`,{d:`M21.54 15H17a2 2 0 0 0-2 2v4.54`,key:`1djwo0`}],[`path`,{d:`M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17`,key:`1tzkfa`}],[`path`,{d:`M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05`,key:`14pb5j`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]),N=y(`ExternalLink`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),te=y(`FileCheck2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m3 15 2 2 4-4`,key:`1lhrkk`}]]),P=y(`FileCode2`,[[`path`,{d:`M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4`,key:`1pf5j1`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`m5 12-3 3 3 3`,key:`oke12k`}],[`path`,{d:`m9 18 3-3-3-3`,key:`112psh`}]]),ne=y(`FileImage`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`10`,cy:`12`,r:`2`,key:`737tya`}],[`path`,{d:`m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22`,key:`wt3hpn`}]]),re=y(`FileJson`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1`,key:`1oajmo`}],[`path`,{d:`M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1`,key:`mpwhp6`}]]),F=y(`FileSearch2`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`circle`,{cx:`11.5`,cy:`14.5`,r:`2.5`,key:`1bq0ko`}],[`path`,{d:`M13.3 16.3 15 18`,key:`2quom7`}]]),ie=y(`FileSearch`,[[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3`,key:`ms7g94`}],[`path`,{d:`m9 18-1.5-1.5`,key:`1j6qii`}],[`circle`,{cx:`5`,cy:`14`,r:`3`,key:`ufru5t`}]]),I=y(`FileText`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]),L=y(`FileUp`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}],[`path`,{d:`M12 12v6`,key:`3ahymv`}],[`path`,{d:`m15 15-3-3-3 3`,key:`15xj92`}]]),ae=y(`File`,[[`path`,{d:`M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z`,key:`1rqfz7`}],[`path`,{d:`M14 2v4a2 2 0 0 0 2 2h4`,key:`tnqrlb`}]]),oe=y(`Files`,[[`path`,{d:`M20 7h-3a2 2 0 0 1-2-2V2`,key:`x099mo`}],[`path`,{d:`M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z`,key:`18t6ie`}],[`path`,{d:`M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8`,key:`1nja0z`}]]),se=y(`FlaskConical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),ce=y(`FolderKanban`,[[`path`,{d:`M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z`,key:`1fr9dc`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M12 10v2`,key:`hh53o1`}],[`path`,{d:`M16 10v6`,key:`1d6xys`}]]),le=y(`FolderOpen`,[[`path`,{d:`m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2`,key:`usdka0`}]]),ue=y(`FolderSearch`,[[`path`,{d:`M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1`,key:`1bw5m7`}],[`path`,{d:`m21 21-1.9-1.9`,key:`1g2n9r`}],[`circle`,{cx:`17`,cy:`17`,r:`3`,key:`18b49y`}]]),de=y(`Folder`,[[`path`,{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`,key:`1kt360`}]]),fe=y(`Gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),pe=y(`GitBranch`,[[`line`,{x1:`6`,x2:`6`,y1:`3`,y2:`15`,key:`17qcm7`}],[`circle`,{cx:`18`,cy:`6`,r:`3`,key:`1h7g24`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`path`,{d:`M18 9a9 9 0 0 1-9 9`,key:`n2h4wq`}]]),me=y(`Github`,[[`path`,{d:`M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4`,key:`tonef`}],[`path`,{d:`M9 18c-4.51 2-5-2-7-2`,key:`9comsn`}]]),he=y(`History`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),ge=y(`Image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),_e=y(`Inbox`,[[`polyline`,{points:`22 12 16 12 14 15 10 15 8 12 2 12`,key:`o97t9d`}],[`path`,{d:`M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z`,key:`oot6mr`}]]),ve=y(`Lightbulb`,[[`path`,{d:`M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5`,key:`1gvzjb`}],[`path`,{d:`M9 18h6`,key:`x1upvd`}],[`path`,{d:`M10 22h4`,key:`ceow96`}]]),ye=y(`Link2`,[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]),be=y(`ListChecks`,[[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`m3 7 2 2 4-4`,key:`1obspn`}],[`path`,{d:`M13 6h8`,key:`15sg57`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 18h8`,key:`oe0vm4`}]]),xe=y(`ListFilter`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M7 12h10`,key:`b7w52i`}],[`path`,{d:`M10 18h4`,key:`1ulq68`}]]),Se=y(`LoaderCircle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),Ce=y(`LockKeyhole`,[[`circle`,{cx:`12`,cy:`16`,r:`1`,key:`1au0dj`}],[`rect`,{x:`3`,y:`10`,width:`18`,height:`12`,rx:`2`,key:`6s8ecr`}],[`path`,{d:`M7 10V7a5 5 0 0 1 10 0v3`,key:`1pqi11`}]]),we=y(`Megaphone`,[[`path`,{d:`m3 11 18-5v12L3 14v-3z`,key:`n962bs`}],[`path`,{d:`M11.6 16.8a3 3 0 1 1-5.8-1.6`,key:`1yl0tm`}]]),Te=y(`MessageSquareText`,[[`path`,{d:`M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z`,key:`1lielz`}],[`path`,{d:`M13 8H7`,key:`14i4kc`}],[`path`,{d:`M17 12H7`,key:`16if0g`}]]),Ee=y(`MessagesSquare`,[[`path`,{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`,key:`p1xzt8`}],[`path`,{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`,key:`1cx29u`}]]),De=y(`PackageCheck`,[[`path`,{d:`m16 16 2 2 4-4`,key:`gfu2re`}],[`path`,{d:`M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14`,key:`e7tb2h`}],[`path`,{d:`m7.5 4.27 9 5.15`,key:`1c824w`}],[`polyline`,{points:`3.29 7 12 12 20.71 7`,key:`ousv84`}],[`line`,{x1:`12`,x2:`12`,y1:`22`,y2:`12`,key:`a4e8g8`}]]),Oe=y(`Paperclip`,[[`path`,{d:`M13.234 20.252 21 12.3`,key:`1cbrk9`}],[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486`,key:`1pkts6`}]]),ke=y(`Pause`,[[`rect`,{x:`14`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`zuxfzm`}],[`rect`,{x:`6`,y:`4`,width:`4`,height:`16`,rx:`1`,key:`1okwgv`}]]),Ae=y(`Play`,[[`polygon`,{points:`6 3 20 12 6 21 6 3`,key:`1oa8hb`}]]),je=y(`Plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Me=y(`Presentation`,[[`path`,{d:`M2 3h20`,key:`91anmk`}],[`path`,{d:`M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3`,key:`2k9sn8`}],[`path`,{d:`m7 21 5-5 5 5`,key:`bip4we`}]]),Ne=y(`Radio`,[[`path`,{d:`M4.9 19.1C1 15.2 1 8.8 4.9 4.9`,key:`1vaf9d`}],[`path`,{d:`M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5`,key:`u1ii0m`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`path`,{d:`M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5`,key:`1j5fej`}],[`path`,{d:`M19.1 4.9C23 8.8 23 15.1 19.1 19`,key:`10b0cb`}]]),Pe=y(`RefreshCw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Fe=y(`RotateCcw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Ie=y(`Save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),Le=y(`Scale`,[[`path`,{d:`m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z`,key:`7g6ntu`}],[`path`,{d:`m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z`,key:`ijws7r`}],[`path`,{d:`M7 21h10`,key:`1b0cd5`}],[`path`,{d:`M12 3v18`,key:`108xh3`}],[`path`,{d:`M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2`,key:`3gwbw2`}]]),Re=y(`Search`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`path`,{d:`m21 21-4.3-4.3`,key:`1qie3q`}]]),ze=y(`Send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),Be=y(`Server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),R=y(`ShieldCheck`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),z=y(`Sparkles`,[[`path`,{d:`M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z`,key:`4pj2yx`}],[`path`,{d:`M20 3v4`,key:`1olli1`}],[`path`,{d:`M22 5h-4`,key:`1gvqau`}],[`path`,{d:`M4 17v2`,key:`vumght`}],[`path`,{d:`M5 18H3`,key:`zchphs`}]]),Ve=y(`SquareTerminal`,[[`path`,{d:`m7 11 2-2-2-2`,key:`1lz0vl`}],[`path`,{d:`M11 13h4`,key:`1p7l4v`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}]]),He=y(`Square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Ue=y(`Table2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),We=y(`Target`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),Ge=y(`TimerReset`,[[`path`,{d:`M10 2h4`,key:`n1abiw`}],[`path`,{d:`M12 14v-4`,key:`1evpnu`}],[`path`,{d:`M4 13a8 8 0 0 1 8-7 8 8 0 1 1-5.3 14L4 17.6`,key:`1ts96g`}],[`path`,{d:`M9 17H4v5`,key:`8t5av`}]]),Ke=y(`Trash2`,[[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6`,key:`4alrt4`}],[`path`,{d:`M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2`,key:`v07s0e`}],[`line`,{x1:`10`,x2:`10`,y1:`11`,y2:`17`,key:`1uufr5`}],[`line`,{x1:`14`,x2:`14`,y1:`11`,y2:`17`,key:`xtxkd`}]]),qe=y(`TriangleAlert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),Je=y(`Upload`,[[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`polyline`,{points:`17 8 12 3 7 8`,key:`t8dd8p`}],[`line`,{x1:`12`,x2:`12`,y1:`3`,y2:`15`,key:`widbto`}]]),Ye=y(`UserRound`,[[`circle`,{cx:`12`,cy:`8`,r:`5`,key:`1hypcn`}],[`path`,{d:`M20 21a8 8 0 0 0-16 0`,key:`rfgkzh`}]]),Xe=y(`WandSparkles`,[[`path`,{d:`m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72`,key:`ul74o6`}],[`path`,{d:`m14 7 3 3`,key:`1r5n42`}],[`path`,{d:`M5 6v4`,key:`ilb8ba`}],[`path`,{d:`M19 14v4`,key:`blhpug`}],[`path`,{d:`M10 2v2`,key:`7u0qdc`}],[`path`,{d:`M7 8H3`,key:`zfb6yr`}],[`path`,{d:`M21 16h-4`,key:`1cnmox`}],[`path`,{d:`M11 3H9`,key:`1obp7u`}]]),Ze=y(`Watch`,[[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`polyline`,{points:`12 10 12 12 13 13`,key:`19dquz`}],[`path`,{d:`m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05`,key:`18k57s`}],[`path`,{d:`m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05`,key:`16ny36`}]]),Qe=y(`Workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),$e=y(`Wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z`,key:`cbrjhi`}]]),et=y(`X`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),tt=12e3;function nt(e=!1){let t={...f()};return e&&(t[`Content-Type`]=`application/json`),t}async function B(e,t={}){await c();let n={...t,headers:{...nt(!!t.body),...t.headers??{}},cache:`no-store`},r=String(t.method??`GET`).toUpperCase(),i=async n=>{if(!n.ok){let r=await n.text().catch(()=>``),i=r;try{i=JSON.parse(r).detail??r}catch{}throw Error(i||`${t.method??`GET`} ${e} failed (${n.status})`)}return await n.json()};return r===`GET`?d(e,n,tt,i):i(await fetch(e,n))}var V=(e,t=``)=>`/api/projects/${encodeURIComponent(e)}${t}`,rt=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`;function it(e){let t=e.replaceAll(`\r `,` `).split(` @@ -11,7 +11,7 @@ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{D as t,E as n}from"./i `):`Not configured`}),(0,J.jsx)(`i`,{className:x.remotes.length?`ok`:`missing`,children:x.remotes.length?(0,J.jsx)(E,{size:12}):(0,J.jsx)(et,{size:12})})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`dt`,{children:[(0,J.jsx)(pe,{size:13}),`Upstream`]}),(0,J.jsxs)(`dd`,{children:[x.upstream||`Not configured`,x.upstream?` · ahead ${x.ahead}, behind ${x.behind}`:``]}),(0,J.jsx)(`i`,{className:x.upstream?`ok`:`missing`,children:x.upstream?(0,J.jsx)(E,{size:12}):(0,J.jsx)(et,{size:12})})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`dt`,{children:[(0,J.jsx)(Ye,{size:13}),`Commit identity`]}),(0,J.jsx)(`dd`,{children:x.identity.name&&x.identity.email?`${x.identity.name} <${x.identity.email}>`:`Not configured`}),(0,J.jsx)(`i`,{className:x.identity.valid?`ok`:`missing`,children:x.identity.valid?(0,J.jsx)(E,{size:12}):(0,J.jsx)(et,{size:12})})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`dt`,{children:[(0,J.jsx)(me,{size:13}),`GitHub CLI`]}),(0,J.jsx)(`dd`,{children:x.github.authenticated?`${x.github.login} · ${x.github.protocol}`:`Not authenticated`}),(0,J.jsx)(`i`,{className:x.github.authenticated?`ok`:`missing`,children:x.github.authenticated?(0,J.jsx)(E,{size:12}):(0,J.jsx)(et,{size:12})})]})]}),(0,J.jsx)(`p`,{children:x.publish_ready?`Repository is ready for an explicitly approved push.`:`Configure the missing items before publishing. No credentials are shown in this UI.`})]}):(0,J.jsx)(X,{icon:pe,title:`Not a Git repository`})})]}),(0,J.jsxs)(`section`,{className:`vscode-terminal`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsx)(`strong`,{children:`ARGUS ACTIVITY`}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(Ve,{size:13}),`read-only`]})]}),(0,J.jsx)(`div`,{children:v.length?v.map((e,t)=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(`time`,{children:W(e.ts)}),(0,J.jsx)(`b`,{className:`terminal-role terminal-role--${ut(e)}`,children:ut(e)}),(0,J.jsx)(`span`,{children:`›`}),(0,J.jsx)(`code`,{children:q(e,800)||K(e)})]},`${e.ts}-${t}`)):(0,J.jsx)(`p`,{children:`$ waiting for Argus activity`})})]}),(0,J.jsxs)(`footer`,{className:`vscode-statusbar`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(pe,{size:12}),x?.branch||`no branch`]}),(0,J.jsx)(`span`,{children:m.isError?`Workspace error`:m.isFetching?`Workspace syncing`:m.data?.truncated?`Tree truncated`:`Workspace synced`}),(0,J.jsx)(`span`,{children:x?.github.authenticated?`GitHub: ${x.github.login}`:`GitHub: offline`}),(0,J.jsx)(`span`,{children:`UTF-8`}),(0,J.jsx)(`span`,{children:o.split(`.`).at(-1)?.toUpperCase()||`Plain Text`})]})]})]})}var Gt=2e5,Kt=5,qt=e=>`argus-v2-inbox:${e}`,Jt=e=>{try{let t=JSON.parse(localStorage.getItem(qt(e))??`[]`);return Array.isArray(t)?t:[]}catch{return[]}},Yt=(e,t)=>({id:crypto.randomUUID(),title:e,source:t,raw:``,prompt:``,changes:[],questions:[],createdAt:Date.now(),updatedAt:Date.now()});function Xt(e,t){let n=[...e.matchAll(/^#{1,3}\s+(.+)\n([\s\S]*?)(?=^#{1,3}\s+|$)/gm)],r=e=>/目标|objective|question/i.test(e)?We:/约束|constraint|boundary|non-goal/i.test(e)?be:/文献|evidence|source|paper/i.test(e)?ye:ve,i=n.map(e=>({title:e[1].trim(),body:e[2].trim(),icon:r(e[1])})).filter(e=>e.body);if(i.length)return i.slice(0,8);let a=e.split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean),o=[];a[0]&&o.push({title:`研究目标与背景`,body:a[0],icon:We});let s=e.split(` `).filter(e=>/不得|不要|必须|约束|only|must|do not|without/i.test(e)).join(` `);return s&&o.push({title:`约束与边界`,body:s,icon:be}),t.length&&o.push({title:`仍需确认`,body:t.map(e=>`- ${e}`).join(` -`),icon:ve}),o}function Zt(e){let{text:t}=Q(),[n,r]=(0,_.useState)(()=>Jt(e.sid)),[i,a]=(0,_.useState)(()=>Jt(e.sid)[0]?.id??``),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)([]),[u,d]=(0,_.useState)(0),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(`current`),[y,b]=(0,_.useState)(``),[x,S]=(0,_.useState)(``),w=_t(e.sid,e.refresh);(0,_.useEffect)(()=>{let t=Jt(e.sid);r(t),a(t[0]?.id??``),l([]),d(0)},[e.sid]),(0,_.useEffect)(()=>{try{localStorage.setItem(qt(e.sid),JSON.stringify(n)),h(``)}catch{h(`本机草稿存储空间不足;请缩短文本或删除旧草稿。`)}},[n,e.sid]);let T=n.find(e=>e.id===i)??null,D=(0,_.useMemo)(()=>Xt(T?.prompt??``,T?.questions??[]),[T?.prompt,T?.questions]),O=e=>T&&r(t=>t.map(t=>t.id===T.id?{...t,...e,updatedAt:Date.now()}:t)),k=()=>{let e=Yt(t(`新的科研输入`,`New research input`),t(`导师 / 组会 / 灵感`,`Advisor / meeting / idea`));r(t=>[e,...t]),a(e.id)},A=()=>{if(!T||!confirm(t(`删除“${T.title}”?`,`Delete “${T.title}”?`)))return;let e=n.filter(e=>e.id!==T.id);r(e),a(e[0]?.id??``)},j=T?`这是科研收信箱的预处理步骤,只分析输入并回复,不创建后台任务、不修改项目。请读取下面的零散内容和附件,提取知识点并生成第一版可直接交给 Argus 的研究 Prompt。必须保留事实来源和不确定性,不得虚构论文、实验或结论;使用以下 Markdown 结构:\n## 研究目标\n## 已知背景与知识点\n## 约束与非目标\n## 文献与证据线索\n## 建议任务与验收方式\n## 待确认问题\n\n标题:${T.title}\n来源:${T.source}\n\n原始内容:\n${T.raw}`:``,M=async e=>{let t=/\.(txt|md|markdown|json|csv|ya?ml|log|tex)$/i,n=/\.(pdf|png|jpe?g|webp|wav|mp3|m4a|ogg)$/i,r=e.filter(e=>!t.test(e.name)&&!n.test(e.name));if(r.length){p(`不支持的附件:${r.map(e=>e.name).join(`、`)}`);return}let i=e.find(e=>e.size>10485760);if(i){p(`${i.name} 超过单文件 10 MB 限制`);return}if(c.length+u+e.length>Kt){p(`每次分析最多导入 ${Kt} 个文件`);return}let a=e.filter(e=>t.test(e.name)),o=a.find(e=>e.size>1048576);if(o){p(`${o.name} 超过本机文本导入 1 MB 限制;请改为摘要或拆分文件`);return}let s=e.filter(e=>n.test(e.name)),f=[...c,...s];if(f.reduce((e,t)=>e+t.size,0)>26214400){p(`附件总大小超过 25 MB`);return}let m=await Promise.all(a.map(async e=>`\n\n--- 文件:${e.name} ---\n${await e.text()}`)),h=`${T?.raw??``}${m.join(``)}`.trim();if(h.length>Gt){p(`原始输入超过 ${Gt.toLocaleString()} 字符限制,请拆分或摘要`);return}m.length&&(O({raw:h}),d(e=>e+a.length)),l(f),p(``)},N=async()=>{if(!(!T||!T.raw.trim()&&!c.length)){s(!0),p(``);try{if(c.length){let e=await w.run(j,c),t=String(e?.reply||w.output||``).trim();if(!t)throw Error(`Argus 没有返回可用的知识提取结果`);O({prompt:t,changes:[`分析了 ${c.length} 个附件和原始输入`],questions:[]}),l([])}else{let t=await H.rewritePrompt(e.sid,j);if(t.error)throw Error(t.error);O({prompt:t.rewritten,changes:t.changes,questions:t.questions})}}catch(e){p(e instanceof Error?e.message:String(e))}finally{s(!1)}}},te=async()=>{if(T?.prompt.trim()){if(g===`new`){if(!y.trim()||!confirm(t(`确认用当前 Prompt 创建一个新的 Argus 项目?`,`Create a new Argus project with this prompt?`)))return;try{let e=await H.createDaemon(T.prompt,y,x);O({sentAt:Date.now()}),window.location.hash=`project/${e.sid}/overview`}catch(e){p(e instanceof Error?e.message:String(e))}return}confirm(t(`确认把这份第一版 Prompt 发送给当前 Argus 项目?`,`Send this first prompt to the current Argus project?`))&&await w.run(T.prompt)&&O({sentAt:Date.now()})}},P=T?.sentAt?4:T?.prompt?3:T?.raw||c.length?2:1;return(0,J.jsxs)(`div`,{className:`ros-page inbox-v2`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`RESEARCH INBOX`}),(0,J.jsx)(`h1`,{children:t(`从零散输入开始研究`,`Start research from rough input`)}),(0,J.jsx)(`p`,{children:t(`把消息、会议记录、文件或灵感交给 AI,提取知识点并形成第一版 Argus Prompt。`,`Give AI messages, meeting notes, files, or ideas to extract knowledge and create a first Argus prompt.`)})]}),(0,J.jsxs)(Y,{tone:`neutral`,children:[(0,J.jsx)(Ie,{size:12}),t(`本机自动保存`,`Saved locally`)]})]}),(0,J.jsx)(`div`,{className:`intake-steps`,children:[[t(`收集原始内容`,`Collect input`),Te],[t(`AI 提取知识`,`Extract knowledge`),Xe],[t(`形成 Argus Prompt`,`Build Argus prompt`),I],[t(`创建 / 发送项目`,`Create / send project`),ze]].map(([e,t],n)=>(0,J.jsxs)(`div`,{className:P>n?`is-done`:P===n+1?`is-active`:``,children:[(0,J.jsx)(`span`,{children:P>n+1?(0,J.jsx)(E,{size:14}):(0,J.jsx)(t,{size:15})}),(0,J.jsx)(`strong`,{children:String(e)}),n<3?(0,J.jsx)(ee,{size:14}):null]},String(e)))}),(0,J.jsxs)(`div`,{className:`inbox-v2__layout`,children:[(0,J.jsxs)(`aside`,{className:`ros-card inbox-sources`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`INBOX`}),(0,J.jsx)(`h2`,{children:t(`科研输入`,`Research input`)})]}),(0,J.jsx)(`button`,{className:`icon-button`,type:`button`,onClick:k,"aria-label":t(`新增输入`,`Add input`),children:(0,J.jsx)(je,{size:15})})]}),(0,J.jsx)(`div`,{children:n.length?n.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:T?.id===e.id?`is-active`:``,onClick:()=>a(e.id),children:[(0,J.jsx)(`span`,{className:`inbox-item-icon`,children:e.sentAt?(0,J.jsx)(E,{size:14}):e.prompt?(0,J.jsx)(z,{size:14}):(0,J.jsx)(_e,{size:14})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.title}),(0,J.jsxs)(`small`,{children:[e.source,` · `,ct(e.updatedAt/1e3)]})]})]},e.id)):(0,J.jsx)(X,{icon:_e,title:t(`暂无输入`,`No input yet`),description:t(`新增一条导师消息、组会笔记或研究灵感。`,`Add an advisor message, meeting note, or research idea.`)})})]}),(0,J.jsxs)(`main`,{className:`ros-card inbox-input`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`RAW MATERIAL`}),(0,J.jsx)(`h2`,{children:t(`原始内容与附件`,`Raw content and attachments`)})]}),T?(0,J.jsx)(`button`,{className:`icon-button`,type:`button`,onClick:A,"aria-label":t(`删除`,`Delete`),children:(0,J.jsx)(Ke,{size:14})}):null]}),T?(0,J.jsxs)(`div`,{className:`inbox-input__form`,children:[(0,J.jsxs)(`div`,{className:`form-grid`,children:[(0,J.jsxs)(`label`,{children:[(0,J.jsx)(`span`,{children:t(`标题`,`Title`)}),(0,J.jsx)(`input`,{value:T.title,onChange:e=>O({title:e.target.value})})]}),(0,J.jsxs)(`label`,{children:[(0,J.jsx)(`span`,{children:t(`来源`,`Source`)}),(0,J.jsx)(`input`,{value:T.source,onChange:e=>O({source:e.target.value})})]})]}),(0,J.jsxs)(`label`,{className:`field field--grow`,children:[(0,J.jsx)(`span`,{children:t(`零散消息、笔记或转写文本`,`Rough messages, notes, or transcripts`)}),(0,J.jsx)(`textarea`,{maxLength:Gt,value:T.raw,onChange:e=>O({raw:e.target.value}),placeholder:t(`不需要先整理,直接粘贴原始内容。AI 会区分目标、事实、约束、文献线索、待办和疑问…`,`Paste raw content directly. AI will separate goals, facts, constraints, evidence leads, tasks, and questions…`)})]}),c.length?(0,J.jsx)(`div`,{className:`inbox-attachment-list`,children:c.map((e,t)=>(0,J.jsxs)(`span`,{children:[e.type.startsWith(`audio/`)?(0,J.jsx)(C,{size:14}):e.type.startsWith(`image/`)?(0,J.jsx)(ge,{size:14}):(0,J.jsx)(I,{size:14}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsxs)(`small`,{children:[(e.size/1024/1024).toFixed(1),` MB · 仅在本次分析上传`]})]}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>l(e=>e.filter((e,n)=>n!==t)),children:(0,J.jsx)(et,{size:13})})]},`${e.name}-${t}`))}):null,(0,J.jsxs)(`div`,{className:`inbox-upload-types`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(I,{size:14}),`PDF / `,t(`文本`,`text`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(ge,{size:14}),t(`图片`,`images`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(C,{size:14}),t(`语音`,`audio`)]}),(0,J.jsx)(`p`,{children:t(`语音会交给 Argus 和已配置工具处理,不把“上传成功”冒充“已完成转写”。`,`Audio is handed to Argus and configured tools; an upload is never presented as a completed transcript.`)})]}),(0,J.jsxs)(`div`,{className:`inbox-input__actions`,children:[(0,J.jsxs)(`label`,{className:`button button--secondary file-button`,children:[(0,J.jsx)(Je,{size:14}),t(`添加文件`,`Add files`),(0,J.jsx)(`input`,{type:`file`,multiple:!0,accept:`.txt,.md,.markdown,.json,.csv,.yaml,.yml,.log,.tex,.pdf,.png,.jpg,.jpeg,.webp,.wav,.mp3,.m4a,.ogg`,onChange:e=>void M(Array.from(e.target.files??[]))})]}),(0,J.jsxs)(`button`,{className:`button button--primary`,type:`button`,disabled:!T.raw.trim()&&!c.length||o||w.busy,onClick:()=>void N(),children:[o||w.busy?(0,J.jsx)(z,{size:14}):(0,J.jsx)(Xe,{size:14}),o||w.busy?w.phase||t(`AI 正在分析`,`AI is analyzing`):t(`分析内容并生成 Prompt`,`Analyze and generate prompt`)]})]}),f?(0,J.jsx)(`div`,{className:`inline-error`,children:f}):null,m?(0,J.jsx)(`div`,{className:`inline-error`,children:m}):null]}):(0,J.jsx)(X,{icon:_e,title:t(`选择或新增一条科研输入`,`Select or add research input`)})]}),(0,J.jsxs)(`aside`,{className:`inbox-output`,children:[(0,J.jsxs)(`section`,{className:`ros-card knowledge-panel`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`KNOWLEDGE EXTRACTION`}),(0,J.jsx)(`h2`,{children:t(`AI 提取的知识点`,`AI-extracted knowledge`)})]}),D.length?(0,J.jsxs)(Y,{tone:`success`,children:[D.length,` `,t(`组`,`groups`)]}):null]}),D.length?(0,J.jsx)(`div`,{className:`knowledge-grid`,children:D.map(e=>{let t=e.icon;return(0,J.jsxs)(`article`,{children:[(0,J.jsx)(`span`,{children:(0,J.jsx)(t,{size:15})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.title}),(0,J.jsx)(Z,{children:e.body})]})]},e.title)})}):(0,J.jsx)(X,{icon:ve,title:t(`等待 AI 提取`,`Waiting for AI extraction`),description:t(`结果会明确区分目标、知识点、约束、证据线索和待确认问题。`,`The result separates goals, knowledge, constraints, evidence leads, and open questions.`)})]}),(0,J.jsxs)(`section`,{className:`ros-card first-prompt`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`FIRST ARGUS PROMPT`}),(0,J.jsx)(`h2`,{children:t(`第一版 Argus Prompt`,`First Argus prompt`)})]}),T?.prompt?(0,J.jsx)(Y,{tone:`info`,children:t(`可编辑`,`Editable`)}):null]}),T?.prompt?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`textarea`,{value:T.prompt,onChange:e=>O({prompt:e.target.value})}),(0,J.jsxs)(`div`,{className:`dispatch-mode`,children:[(0,J.jsx)(`button`,{type:`button`,className:g===`current`?`is-active`:``,onClick:()=>v(`current`),children:t(`发送当前项目`,`Send to current project`)}),(0,J.jsx)(`button`,{type:`button`,className:g===`new`?`is-active`:``,onClick:()=>v(`new`),children:t(`创建新项目`,`Create new project`)})]}),g===`new`?(0,J.jsxs)(`div`,{className:`new-project-fields`,children:[(0,J.jsx)(`input`,{value:y,onChange:e=>b(e.target.value),placeholder:t(`新项目名称`,`New project name`)}),(0,J.jsx)(`input`,{value:x,onChange:e=>S(e.target.value),placeholder:t(`工作目录(可选,留空自动创建)`,`Workdir (optional; blank creates one)`)})]}):null,(0,J.jsxs)(`button`,{className:`button button--primary button--full`,type:`button`,disabled:w.busy,onClick:()=>void te(),children:[(0,J.jsx)(ze,{size:14}),w.busy?w.phase||t(`正在发送`,`Sending`):g===`new`?t(`用此 Prompt 创建 Argus 项目`,`Create Argus project with this prompt`):t(`确认并发送给当前 Argus`,`Confirm and send to current Argus`)]}),w.output?(0,J.jsx)(`div`,{className:`manager-mini-result`,children:(0,J.jsx)(Z,{children:w.output})}):null]}):(0,J.jsx)(X,{icon:I,title:t(`尚未生成 Prompt`,`No prompt generated`),description:t(`AI 提取后会在这里生成第一版 Prompt,你可以先修改再发送。`,`The first prompt appears here after extraction and can be edited before sending.`)})]})]})]})]})}function Qt({paper:e,selected:t,onClick:n}){let{text:r}=Q();return(0,J.jsxs)(`button`,{type:`button`,className:`paper-card ${t?`is-selected`:``}`,onClick:n,children:[(0,J.jsxs)(`div`,{className:`paper-card__meta`,children:[(0,J.jsx)(Y,{tone:e.evidenceStatus===`verified_artifact`?`success`:e.evidenceStatus===`metadata`?`info`:`warn`,children:e.evidenceStatus===`verified_artifact`?r(`原文文件已验证`,`Source verified`):e.evidenceStatus===`metadata`?r(`仅元数据`,`Metadata only`):r(`待核验`,`Needs verification`)}),(0,J.jsxs)(`span`,{className:`paper-card__year`,children:[e.year||`—`,e.venue?` · ${e.venue}`:``]})]}),(0,J.jsx)(`h3`,{children:e.title}),e.authors.length?(0,J.jsxs)(`p`,{className:`paper-card__authors`,children:[e.authors.slice(0,4).join(`, `),e.authors.length>4?` et al.`:``]}):null,(0,J.jsx)(`p`,{className:`paper-card__summary`,children:e.relevance||e.abstract||r(`该记录尚未写入项目相关性摘要。`,`No project-relevance summary has been recorded.`)}),(0,J.jsxs)(`div`,{className:`paper-card__footer`,children:[(0,J.jsx)(`code`,{children:e.sourcePath}),(0,J.jsx)(`span`,{children:r(`查看详情`,`View details`)})]})]})}function $t(e){let{text:t}=Q(),n=Vt(e.sid,`literature`),r=n.active?.path||``,a=i({queryKey:[`workspace-literature`,e.sid,n.workspaceId],queryFn:({signal:t})=>$.literature(e.sid,n.workspaceId,t),enabled:!!n.workspaceId,refetchInterval:15e3}),[o,s]=(0,_.useState)(`all`),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(``),m=_t(e.sid,async()=>{await e.refresh(),await a.refetch()}),h=a.data?.papers??[],g=Math.max(0,...h.map(e=>e.year??0)),v=(0,_.useMemo)(()=>h.filter(e=>{if(o===`recent`&&(e.year??0)e.id===u)??v[0]??null,b=(0,_.useMemo)(()=>e.events.filter(e=>/paper|arxiv|doi|literature|search|citation|http/i.test(`${e.type} ${e.kind} ${q(e,2e3)}`)).slice(-30).reverse(),[e.events]),x=async()=>{f.trim()&&await m.run(`请为当前项目执行新的文献调研:${f}\n\n要求读取原始论文或官方仓库,把结构化记录追加到项目的 literature grounding/audit 文件中,包括标题、作者、年份、URL、与当前项目关系、最近工作威胁和仍待全文核验项。完成后文献中心应能从工作目录直接读取这些记录。`)};return(0,J.jsxs)(`div`,{className:`ros-page literature-v2`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`LITERATURE CENTER`}),(0,J.jsx)(`h1`,{children:t(`文献中心`,`Literature center`)}),(0,J.jsx)(`p`,{children:t(`直接读取 Argus 工作目录中的论文清单、文献审计和实时检索轨迹,不再依赖手工注册 artifacts。`,`Read paper inventories, literature audits, and live retrieval traces directly from the Argus workdir.`)})]}),(0,J.jsxs)(`div`,{className:`header-badges`,children:[(0,J.jsxs)(Y,{tone:`success`,children:[(0,J.jsx)(w,{size:12}),h.length,` `,t(`篇论文`,`papers`)]}),(0,J.jsxs)(Y,{tone:`neutral`,children:[a.data?.sourceFiles.length??0,` `,t(`个证据文件`,`evidence files`)]})]})]}),(0,J.jsxs)(`section`,{className:`literature-stats`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--blue`,children:(0,J.jsx)(w,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`论文记录`,`Paper records`),(0,J.jsx)(`strong`,{children:h.length})]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--green`,children:(0,J.jsx)(ie,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`原文文件已验证`,`Verified sources`),(0,J.jsx)(`strong`,{children:h.filter(e=>e.evidenceStatus===`verified_artifact`).length})]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--amber`,children:(0,J.jsx)(T,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`最近工作`,`Recent work`),(0,J.jsx)(`strong`,{children:h.filter(e=>(e.year??0)>=g-1).length})]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--violet`,children:(0,J.jsx)(ue,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`扫描项目文件`,`Scanned files`),(0,J.jsx)(`strong`,{children:a.data?.scannedFiles??0})]})]})]}),(0,J.jsxs)(`div`,{className:`literature-v2__layout`,children:[(0,J.jsxs)(`aside`,{className:`literature-v2__sidebar ros-card`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`LIBRARY`}),(0,J.jsx)(`h2`,{children:t(`项目文献库`,`Project library`)})]})}),(0,J.jsxs)(`label`,{className:`search-field search-field--block`,children:[(0,J.jsx)(Re,{size:14}),(0,J.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),placeholder:t(`搜索标题、作者、主题`,`Search title, author, or topic`)})]}),(0,J.jsx)(`nav`,{className:`library-tabs`,children:[[`all`,t(`全部论文`,`All papers`),h.length],[`recent`,t(`最近工作`,`Recent work`),h.filter(e=>(e.year??0)>=g-1).length],[`read`,t(`已验证原文`,`Verified sources`),h.filter(e=>e.evidenceStatus===`verified_artifact`).length],[`sources`,t(`证据文件`,`Evidence files`),a.data?.sourceFiles.length??0]].map(([e,t,n])=>(0,J.jsxs)(`button`,{type:`button`,className:o===e?`is-active`:``,onClick:()=>s(e),children:[(0,J.jsx)(`span`,{children:t}),(0,J.jsx)(`small`,{children:n})]},e))}),(0,J.jsxs)(`div`,{className:`literature-source-note`,children:[(0,J.jsx)(re,{size:15}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:t(`实时来源`,`Live source`)}),(0,J.jsx)(`p`,{title:r,children:r})]})]})]}),(0,J.jsxs)(`main`,{className:`literature-v2__main`,children:[(0,J.jsxs)(`div`,{className:`literature-list-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:o===`recent`?t(`最近工作`,`Recent work`):o===`read`?t(`已验证原文文件`,`Verified source files`):o===`sources`?t(`文献证据文件`,`Literature evidence files`):t(`全部论文`,`All papers`)}),(0,J.jsx)(`p`,{children:o===`recent`?t(`按项目中最新年份 ${g||`—`} 自动筛选`,`Filtered by the latest project year: ${g||`—`}`):t(`Argus 写入工作目录后约 5 秒内自动更新`,`Updates shortly after Argus writes to the workdir`)})]}),a.isError?(0,J.jsx)(Y,{tone:`danger`,children:t(`同步失败`,`Sync failed`)}):a.isFetching?(0,J.jsx)(Y,{tone:`live`,dot:!0,children:t(`同步中`,`Syncing`)}):(0,J.jsx)(Y,{tone:`success`,children:t(`已同步`,`Synced`)})]}),a.isError?(0,J.jsx)(`div`,{className:`inline-error`,children:a.error.message}):null,o===`sources`?(0,J.jsx)(`div`,{className:`source-file-grid`,children:a.data?.sourceFiles.map(e=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(re,{size:17}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]}),(0,J.jsx)(`time`,{children:ct(e.mtime)})]},e.path))}):v.length?(0,J.jsx)(`div`,{className:`paper-grid`,children:v.map(e=>(0,J.jsx)(Qt,{paper:e,selected:y?.id===e.id,onClick:()=>d(e.id)},e.id))}):(0,J.jsx)(X,{icon:w,title:t(`此筛选下暂无论文`,`No papers match this filter`),description:t(`Argus 完成检索并写入 LITERATURE_GROUNDING.json 后会自动出现。`,`Papers appear after Argus writes LITERATURE_GROUNDING.json.`)})]}),(0,J.jsxs)(`aside`,{className:`literature-v2__detail`,children:[(0,J.jsx)(`section`,{className:`ros-card paper-detail`,children:y?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`paper-detail__top`,children:[(0,J.jsx)(Y,{tone:y.evidenceStatus===`verified_artifact`?`success`:y.evidenceStatus===`metadata`?`info`:`warn`,children:y.evidenceStatus===`verified_artifact`?`verified artifact`:y.evidenceStatus}),(0,J.jsxs)(`span`,{children:[y.year||`—`,y.venue?` · ${y.venue}`:``]})]}),(0,J.jsx)(`h2`,{children:y.title}),y.authors.length?(0,J.jsx)(`p`,{className:`paper-detail__authors`,children:y.authors.join(`, `)}):null,(0,J.jsxs)(`div`,{className:`paper-detail__body`,children:[(0,J.jsx)(`h3`,{children:t(`与当前项目的关系`,`Relationship to this project`)}),(0,J.jsx)(Z,{children:y.relevance||y.abstract||t(`尚未写入摘要。`,`No summary recorded.`)}),y.abstract&&y.relevance?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{children:t(`摘要`,`Abstract`)}),(0,J.jsx)(`p`,{children:y.abstract})]}):null]}),(0,J.jsxs)(`div`,{className:`paper-detail__source`,children:[(0,J.jsx)(`span`,{children:t(`证据文件`,`Evidence file`)}),(0,J.jsx)(`code`,{children:y.sourcePath})]}),y.url?(0,J.jsxs)(`a`,{className:`button button--secondary button--full`,href:y.url,target:`_blank`,rel:`noreferrer`,children:[t(`打开原始来源`,`Open source`),` `,(0,J.jsx)(N,{size:14})]}):null]}):(0,J.jsx)(X,{icon:w,title:t(`选择一篇论文`,`Select a paper`)})}),(0,J.jsxs)(`section`,{className:`ros-card retrieval-panel`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`ARGUS RETRIEVAL`}),(0,J.jsx)(`h2`,{children:t(`最近检索`,`Recent retrieval`)})]}),(0,J.jsx)(Y,{tone:e.connected?`live`:`warn`,dot:!0,children:e.connected?`Live`:`Polling`})]}),(0,J.jsxs)(`div`,{children:[(a.data?.searchFiles??[]).slice(0,8).map(e=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(ie,{size:13}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]}),(0,J.jsx)(`time`,{children:W(e.mtime)})]},e.path)),!a.data?.searchFiles.length&&b.slice(0,8).map((e,t)=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(ie,{size:13}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:K(e)}),(0,J.jsx)(`code`,{children:q(e,100)})]}),(0,J.jsx)(`time`,{children:W(e.ts)})]},`${e.ts}-${t}`))]})]}),(0,J.jsxs)(`section`,{className:`ros-card literature-ask`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`NEW SEARCH`}),(0,J.jsx)(`h2`,{children:t(`让 Argus 调研新工作`,`Ask Argus to research new work`)})]})}),(0,J.jsx)(`textarea`,{rows:3,value:f,onChange:e=>p(e.target.value),placeholder:t(`例如:检索 2025–2026 年与当前方法最接近的直接竞争工作…`,`Example: find the closest competing work from 2025–2026…`)}),(0,J.jsxs)(`button`,{className:`button button--primary button--full`,type:`button`,disabled:!f.trim()||m.busy,onClick:()=>void x(),children:[(0,J.jsx)(z,{size:14}),m.busy?m.phase||t(`检索中`,`Researching`):t(`发起文献调研`,`Start literature research`)]}),m.output?(0,J.jsx)(`div`,{className:`manager-mini-result`,children:(0,J.jsx)(Z,{children:m.output})}):null]})]})]})]})}var en=`/assets/pdf.worker.min-CHFwMXne.mjs`;function tn(e){return[`.png`,`.jpg`,`.jpeg`,`.webp`,`.svg`].includes(e.extension)}function nn(e){return[`.csv`,`.tsv`].includes(e.extension)}function rn(e){return[`.tex`,`.md`].includes(e.extension)}function an({src:e,name:t}){let{text:n}=Q(),r=(0,_.useRef)(null),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(1),[c,l]=(0,_.useState)(1.25),[u,d]=(0,_.useState)(``),[f,m]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{let t=!0,n=null;a(null),s(1),d(``),m(!1);let r=localStorage.getItem(`argus_web_token`);return Promise.all([fetch(e,{headers:r?{Authorization:`Bearer ${r}`}:{}}).then(e=>{if(!e.ok)throw Error(`PDF request failed (${e.status})`);return e.arrayBuffer()}),p(()=>import(`./pdf-BdyXXgZL.js`),__vite__mapDeps([0,1,2,3,4,5,6]))]).then(([e,r])=>{if(t)return r.GlobalWorkerOptions.workerSrc=en,n=r.getDocument({data:e}),n.promise}).then(e=>{t&&e&&a(e)}).catch(e=>{t&&d(e instanceof Error?e.message:String(e))}),()=>{t=!1,n?.destroy()}},[e]),(0,_.useEffect)(()=>{if(!i||!r.current)return;m(!1);let e=!1,t=null;return i.getPage(o).then(n=>{if(e||!r.current)return;let i=n.getViewport({scale:c}),a=r.current,o=a.getContext(`2d`);if(!o)return;let s=Math.min(window.devicePixelRatio||1,2);return a.width=Math.floor(i.width*s),a.height=Math.floor(i.height*s),a.style.width=`${i.width}px`,a.style.height=`${i.height}px`,t=n.render({canvas:a,canvasContext:o,viewport:i,transform:s===1?void 0:[s,0,0,s,0,0]}),t.promise.then(()=>{e||m(!0)})}).catch(t=>{e||d(t instanceof Error?t.message:String(t))}),()=>{e=!0,t?.cancel()}},[i,o,c]),(0,J.jsxs)(`div`,{className:`pdf-canvas-viewer`,children:[(0,J.jsxs)(`div`,{className:`pdf-canvas-toolbar`,children:[(0,J.jsx)(`strong`,{children:t}),(0,J.jsxs)(`span`,{children:[n(`第`,`Page`),` `,o,` / `,i?.numPages??`…`]}),(0,J.jsx)(`button`,{type:`button`,disabled:o<=1,onClick:()=>s(e=>e-1),children:n(`上一页`,`Previous`)}),(0,J.jsx)(`button`,{type:`button`,disabled:!i||o>=i.numPages,onClick:()=>s(e=>e+1),children:n(`下一页`,`Next`)}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>l(e=>Math.max(.75,e-.15)),children:`−`}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>l(e=>Math.min(2,e+.15)),children:`+`})]}),u?(0,J.jsx)(`div`,{className:`inline-error`,children:u}):null,(0,J.jsx)(`div`,{className:`pdf-canvas-scroll`,children:(0,J.jsx)(`canvas`,{ref:r,"data-rendered":f?`true`:`false`})})]})}function on({sid:e,workspaceId:t,entry:n}){let{text:r}=Q(),a=i({queryKey:[`paper-source-file`,e,t,n?.path,n?.mtime],queryFn:({signal:r})=>$.file(e,t,n.path,r),enabled:!!(n&&t),refetchInterval:8e3});return n?a.isError?(0,J.jsx)(X,{icon:I,title:r(`源文件暂时无法读取`,`Source file unavailable`),description:a.error.message}):n.extension===`.md`&&a.data?(0,J.jsx)(`div`,{className:`paper-markdown-preview`,children:(0,J.jsx)(Z,{children:a.data.content})}):(0,J.jsxs)(`div`,{className:`latex-source`,children:[(0,J.jsx)(`div`,{className:`latex-line-numbers`,children:(a.data?.content??``).split(` +`),icon:ve}),o}function Zt(e){let{text:t}=Q(),[n,r]=(0,_.useState)(()=>Jt(e.sid)),[i,a]=(0,_.useState)(()=>Jt(e.sid)[0]?.id??``),[o,s]=(0,_.useState)(!1),[c,l]=(0,_.useState)([]),[u,d]=(0,_.useState)(0),[f,p]=(0,_.useState)(``),[m,h]=(0,_.useState)(``),[g,v]=(0,_.useState)(`current`),[y,b]=(0,_.useState)(``),[x,S]=(0,_.useState)(``),w=_t(e.sid,e.refresh);(0,_.useEffect)(()=>{let t=Jt(e.sid);r(t),a(t[0]?.id??``),l([]),d(0)},[e.sid]),(0,_.useEffect)(()=>{try{localStorage.setItem(qt(e.sid),JSON.stringify(n)),h(``)}catch{h(`本机草稿存储空间不足;请缩短文本或删除旧草稿。`)}},[n,e.sid]);let T=n.find(e=>e.id===i)??null,D=(0,_.useMemo)(()=>Xt(T?.prompt??``,T?.questions??[]),[T?.prompt,T?.questions]),O=e=>T&&r(t=>t.map(t=>t.id===T.id?{...t,...e,updatedAt:Date.now()}:t)),k=()=>{let e=Yt(t(`新的科研输入`,`New research input`),t(`导师 / 组会 / 灵感`,`Advisor / meeting / idea`));r(t=>[e,...t]),a(e.id)},A=()=>{if(!T||!confirm(t(`删除“${T.title}”?`,`Delete “${T.title}”?`)))return;let e=n.filter(e=>e.id!==T.id);r(e),a(e[0]?.id??``)},j=T?`这是科研收信箱的预处理步骤,只分析输入并回复,不创建后台任务、不修改项目。请读取下面的零散内容和附件,提取知识点并生成第一版可直接交给 Argus 的研究 Prompt。必须保留事实来源和不确定性,不得虚构论文、实验或结论;使用以下 Markdown 结构:\n## 研究目标\n## 已知背景与知识点\n## 约束与非目标\n## 文献与证据线索\n## 建议任务与验收方式\n## 待确认问题\n\n标题:${T.title}\n来源:${T.source}\n\n原始内容:\n${T.raw}`:``,M=async e=>{let t=/\.(txt|md|markdown|json|csv|ya?ml|log|tex)$/i,n=/\.(pdf|png|jpe?g|webp|wav|mp3|m4a|ogg)$/i,r=e.filter(e=>!t.test(e.name)&&!n.test(e.name));if(r.length){p(`不支持的附件:${r.map(e=>e.name).join(`、`)}`);return}let i=e.find(e=>e.size>10485760);if(i){p(`${i.name} 超过单文件 10 MB 限制`);return}if(c.length+u+e.length>Kt){p(`每次分析最多导入 ${Kt} 个文件`);return}let a=e.filter(e=>t.test(e.name)),o=a.find(e=>e.size>1048576);if(o){p(`${o.name} 超过本机文本导入 1 MB 限制;请改为摘要或拆分文件`);return}let s=e.filter(e=>n.test(e.name)),f=[...c,...s];if(f.reduce((e,t)=>e+t.size,0)>26214400){p(`附件总大小超过 25 MB`);return}let m=await Promise.all(a.map(async e=>`\n\n--- 文件:${e.name} ---\n${await e.text()}`)),h=`${T?.raw??``}${m.join(``)}`.trim();if(h.length>Gt){p(`原始输入超过 ${Gt.toLocaleString()} 字符限制,请拆分或摘要`);return}m.length&&(O({raw:h}),d(e=>e+a.length)),l(f),p(``)},N=async()=>{if(!(!T||!T.raw.trim()&&!c.length)){s(!0),p(``);try{if(c.length){let e=await w.run(j,c),t=String(e?.reply||w.output||``).trim();if(!t)throw Error(`Argus 没有返回可用的知识提取结果`);O({prompt:t,changes:[`分析了 ${c.length} 个附件和原始输入`],questions:[]}),l([])}else{let t=await H.rewritePrompt(e.sid,j);if(t.error)throw Error(t.error);O({prompt:t.rewritten,changes:t.changes,questions:t.questions})}}catch(e){p(e instanceof Error?e.message:String(e))}finally{s(!1)}}},te=async()=>{if(T?.prompt.trim()){if(g===`new`){if(!y.trim()||!confirm(t(`确认用当前 Prompt 创建一个新的 Argus 项目?`,`Create a new Argus project with this prompt?`)))return;try{let e=await H.createDaemon(T.prompt,y,x);O({sentAt:Date.now()}),window.location.hash=`project/${e.sid}/overview`}catch(e){p(e instanceof Error?e.message:String(e))}return}confirm(t(`确认把这份第一版 Prompt 发送给当前 Argus 项目?`,`Send this first prompt to the current Argus project?`))&&await w.run(T.prompt)&&O({sentAt:Date.now()})}},P=T?.sentAt?4:T?.prompt?3:T?.raw||c.length?2:1;return(0,J.jsxs)(`div`,{className:`ros-page inbox-v2`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`RESEARCH INBOX`}),(0,J.jsx)(`h1`,{children:t(`从零散输入开始研究`,`Start research from rough input`)}),(0,J.jsx)(`p`,{children:t(`把消息、会议记录、文件或灵感交给 AI,提取知识点并形成第一版 Argus Prompt。`,`Give AI messages, meeting notes, files, or ideas to extract knowledge and create a first Argus prompt.`)})]}),(0,J.jsxs)(Y,{tone:`neutral`,children:[(0,J.jsx)(Ie,{size:12}),t(`本机自动保存`,`Saved locally`)]})]}),(0,J.jsx)(`div`,{className:`intake-steps`,children:[[t(`收集原始内容`,`Collect input`),Te],[t(`AI 提取知识`,`Extract knowledge`),Xe],[t(`形成 Argus Prompt`,`Build Argus prompt`),I],[t(`创建 / 发送项目`,`Create / send project`),ze]].map(([e,t],n)=>(0,J.jsxs)(`div`,{className:P>n?`is-done`:P===n+1?`is-active`:``,children:[(0,J.jsx)(`span`,{children:P>n+1?(0,J.jsx)(E,{size:14}):(0,J.jsx)(t,{size:15})}),(0,J.jsx)(`strong`,{children:String(e)}),n<3?(0,J.jsx)(ee,{size:14}):null]},String(e)))}),(0,J.jsxs)(`div`,{className:`inbox-v2__layout`,children:[(0,J.jsxs)(`aside`,{className:`ros-card inbox-sources`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`INBOX`}),(0,J.jsx)(`h2`,{children:t(`科研输入`,`Research input`)})]}),(0,J.jsx)(`button`,{className:`icon-button`,type:`button`,onClick:k,"aria-label":t(`新增输入`,`Add input`),children:(0,J.jsx)(je,{size:15})})]}),(0,J.jsx)(`div`,{children:n.length?n.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:T?.id===e.id?`is-active`:``,onClick:()=>a(e.id),children:[(0,J.jsx)(`span`,{className:`inbox-item-icon`,children:e.sentAt?(0,J.jsx)(E,{size:14}):e.prompt?(0,J.jsx)(z,{size:14}):(0,J.jsx)(_e,{size:14})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.title}),(0,J.jsxs)(`small`,{children:[e.source,` · `,ct(e.updatedAt/1e3)]})]})]},e.id)):(0,J.jsx)(X,{icon:_e,title:t(`暂无输入`,`No input yet`),description:t(`新增一条导师消息、组会笔记或研究灵感。`,`Add an advisor message, meeting note, or research idea.`)})})]}),(0,J.jsxs)(`main`,{className:`ros-card inbox-input`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`RAW MATERIAL`}),(0,J.jsx)(`h2`,{children:t(`原始内容与附件`,`Raw content and attachments`)})]}),T?(0,J.jsx)(`button`,{className:`icon-button`,type:`button`,onClick:A,"aria-label":t(`删除`,`Delete`),children:(0,J.jsx)(Ke,{size:14})}):null]}),T?(0,J.jsxs)(`div`,{className:`inbox-input__form`,children:[(0,J.jsxs)(`div`,{className:`form-grid`,children:[(0,J.jsxs)(`label`,{children:[(0,J.jsx)(`span`,{children:t(`标题`,`Title`)}),(0,J.jsx)(`input`,{value:T.title,onChange:e=>O({title:e.target.value})})]}),(0,J.jsxs)(`label`,{children:[(0,J.jsx)(`span`,{children:t(`来源`,`Source`)}),(0,J.jsx)(`input`,{value:T.source,onChange:e=>O({source:e.target.value})})]})]}),(0,J.jsxs)(`label`,{className:`field field--grow`,children:[(0,J.jsx)(`span`,{children:t(`零散消息、笔记或转写文本`,`Rough messages, notes, or transcripts`)}),(0,J.jsx)(`textarea`,{maxLength:Gt,value:T.raw,onChange:e=>O({raw:e.target.value}),placeholder:t(`不需要先整理,直接粘贴原始内容。AI 会区分目标、事实、约束、文献线索、待办和疑问…`,`Paste raw content directly. AI will separate goals, facts, constraints, evidence leads, tasks, and questions…`)})]}),c.length?(0,J.jsx)(`div`,{className:`inbox-attachment-list`,children:c.map((e,t)=>(0,J.jsxs)(`span`,{children:[e.type.startsWith(`audio/`)?(0,J.jsx)(C,{size:14}):e.type.startsWith(`image/`)?(0,J.jsx)(ge,{size:14}):(0,J.jsx)(I,{size:14}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsxs)(`small`,{children:[(e.size/1024/1024).toFixed(1),` MB · 仅在本次分析上传`]})]}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>l(e=>e.filter((e,n)=>n!==t)),children:(0,J.jsx)(et,{size:13})})]},`${e.name}-${t}`))}):null,(0,J.jsxs)(`div`,{className:`inbox-upload-types`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(I,{size:14}),`PDF / `,t(`文本`,`text`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(ge,{size:14}),t(`图片`,`images`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(C,{size:14}),t(`语音`,`audio`)]}),(0,J.jsx)(`p`,{children:t(`语音会交给 Argus 和已配置工具处理,不把“上传成功”冒充“已完成转写”。`,`Audio is handed to Argus and configured tools; an upload is never presented as a completed transcript.`)})]}),(0,J.jsxs)(`div`,{className:`inbox-input__actions`,children:[(0,J.jsxs)(`label`,{className:`button button--secondary file-button`,children:[(0,J.jsx)(Je,{size:14}),t(`添加文件`,`Add files`),(0,J.jsx)(`input`,{type:`file`,multiple:!0,accept:`.txt,.md,.markdown,.json,.csv,.yaml,.yml,.log,.tex,.pdf,.png,.jpg,.jpeg,.webp,.wav,.mp3,.m4a,.ogg`,onChange:e=>void M(Array.from(e.target.files??[]))})]}),(0,J.jsxs)(`button`,{className:`button button--primary`,type:`button`,disabled:!T.raw.trim()&&!c.length||o||w.busy,onClick:()=>void N(),children:[o||w.busy?(0,J.jsx)(z,{size:14}):(0,J.jsx)(Xe,{size:14}),o||w.busy?w.phase||t(`AI 正在分析`,`AI is analyzing`):t(`分析内容并生成 Prompt`,`Analyze and generate prompt`)]})]}),f?(0,J.jsx)(`div`,{className:`inline-error`,children:f}):null,m?(0,J.jsx)(`div`,{className:`inline-error`,children:m}):null]}):(0,J.jsx)(X,{icon:_e,title:t(`选择或新增一条科研输入`,`Select or add research input`)})]}),(0,J.jsxs)(`aside`,{className:`inbox-output`,children:[(0,J.jsxs)(`section`,{className:`ros-card knowledge-panel`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`KNOWLEDGE EXTRACTION`}),(0,J.jsx)(`h2`,{children:t(`AI 提取的知识点`,`AI-extracted knowledge`)})]}),D.length?(0,J.jsxs)(Y,{tone:`success`,children:[D.length,` `,t(`组`,`groups`)]}):null]}),D.length?(0,J.jsx)(`div`,{className:`knowledge-grid`,children:D.map(e=>{let t=e.icon;return(0,J.jsxs)(`article`,{children:[(0,J.jsx)(`span`,{children:(0,J.jsx)(t,{size:15})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.title}),(0,J.jsx)(Z,{children:e.body})]})]},e.title)})}):(0,J.jsx)(X,{icon:ve,title:t(`等待 AI 提取`,`Waiting for AI extraction`),description:t(`结果会明确区分目标、知识点、约束、证据线索和待确认问题。`,`The result separates goals, knowledge, constraints, evidence leads, and open questions.`)})]}),(0,J.jsxs)(`section`,{className:`ros-card first-prompt`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`FIRST ARGUS PROMPT`}),(0,J.jsx)(`h2`,{children:t(`第一版 Argus Prompt`,`First Argus prompt`)})]}),T?.prompt?(0,J.jsx)(Y,{tone:`info`,children:t(`可编辑`,`Editable`)}):null]}),T?.prompt?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`textarea`,{value:T.prompt,onChange:e=>O({prompt:e.target.value})}),(0,J.jsxs)(`div`,{className:`dispatch-mode`,children:[(0,J.jsx)(`button`,{type:`button`,className:g===`current`?`is-active`:``,onClick:()=>v(`current`),children:t(`发送当前项目`,`Send to current project`)}),(0,J.jsx)(`button`,{type:`button`,className:g===`new`?`is-active`:``,onClick:()=>v(`new`),children:t(`创建新项目`,`Create new project`)})]}),g===`new`?(0,J.jsxs)(`div`,{className:`new-project-fields`,children:[(0,J.jsx)(`input`,{value:y,onChange:e=>b(e.target.value),placeholder:t(`新项目名称`,`New project name`)}),(0,J.jsx)(`input`,{value:x,onChange:e=>S(e.target.value),placeholder:t(`工作目录(可选,留空自动创建)`,`Workdir (optional; blank creates one)`)})]}):null,(0,J.jsxs)(`button`,{className:`button button--primary button--full`,type:`button`,disabled:w.busy,onClick:()=>void te(),children:[(0,J.jsx)(ze,{size:14}),w.busy?w.phase||t(`正在发送`,`Sending`):g===`new`?t(`用此 Prompt 创建 Argus 项目`,`Create Argus project with this prompt`):t(`确认并发送给当前 Argus`,`Confirm and send to current Argus`)]}),w.output?(0,J.jsx)(`div`,{className:`manager-mini-result`,children:(0,J.jsx)(Z,{children:w.output})}):null]}):(0,J.jsx)(X,{icon:I,title:t(`尚未生成 Prompt`,`No prompt generated`),description:t(`AI 提取后会在这里生成第一版 Prompt,你可以先修改再发送。`,`The first prompt appears here after extraction and can be edited before sending.`)})]})]})]})]})}function Qt({paper:e,selected:t,onClick:n}){let{text:r}=Q();return(0,J.jsxs)(`button`,{type:`button`,className:`paper-card ${t?`is-selected`:``}`,onClick:n,children:[(0,J.jsxs)(`div`,{className:`paper-card__meta`,children:[(0,J.jsx)(Y,{tone:e.evidenceStatus===`verified_artifact`?`success`:e.evidenceStatus===`metadata`?`info`:`warn`,children:e.evidenceStatus===`verified_artifact`?r(`原文文件已验证`,`Source verified`):e.evidenceStatus===`metadata`?r(`仅元数据`,`Metadata only`):r(`待核验`,`Needs verification`)}),(0,J.jsxs)(`span`,{className:`paper-card__year`,children:[e.year||`—`,e.venue?` · ${e.venue}`:``]})]}),(0,J.jsx)(`h3`,{children:e.title}),e.authors.length?(0,J.jsxs)(`p`,{className:`paper-card__authors`,children:[e.authors.slice(0,4).join(`, `),e.authors.length>4?` et al.`:``]}):null,(0,J.jsx)(`p`,{className:`paper-card__summary`,children:e.relevance||e.abstract||r(`该记录尚未写入项目相关性摘要。`,`No project-relevance summary has been recorded.`)}),(0,J.jsxs)(`div`,{className:`paper-card__footer`,children:[(0,J.jsx)(`code`,{children:e.sourcePath}),(0,J.jsx)(`span`,{children:r(`查看详情`,`View details`)})]})]})}function $t(e){let{text:t}=Q(),n=Vt(e.sid,`literature`),r=n.active?.path||``,a=i({queryKey:[`workspace-literature`,e.sid,n.workspaceId],queryFn:({signal:t})=>$.literature(e.sid,n.workspaceId,t),enabled:!!n.workspaceId,refetchInterval:15e3}),[o,s]=(0,_.useState)(`all`),[c,l]=(0,_.useState)(``),[u,d]=(0,_.useState)(``),[f,p]=(0,_.useState)(``),m=_t(e.sid,async()=>{await e.refresh(),await a.refetch()}),h=a.data?.papers??[],g=Math.max(0,...h.map(e=>e.year??0)),v=(0,_.useMemo)(()=>h.filter(e=>{if(o===`recent`&&(e.year??0)e.id===u)??v[0]??null,b=(0,_.useMemo)(()=>e.events.filter(e=>/paper|arxiv|doi|literature|search|citation|http/i.test(`${e.type} ${e.kind} ${q(e,2e3)}`)).slice(-30).reverse(),[e.events]),x=async()=>{f.trim()&&await m.run(`请为当前项目执行新的文献调研:${f}\n\n要求读取原始论文或官方仓库,把结构化记录追加到项目的 literature grounding/audit 文件中,包括标题、作者、年份、URL、与当前项目关系、最近工作威胁和仍待全文核验项。完成后文献中心应能从工作目录直接读取这些记录。`)};return(0,J.jsxs)(`div`,{className:`ros-page literature-v2`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`LITERATURE CENTER`}),(0,J.jsx)(`h1`,{children:t(`文献中心`,`Literature center`)}),(0,J.jsx)(`p`,{children:t(`直接读取 Argus 工作目录中的论文清单、文献审计和实时检索轨迹,不再依赖手工注册 artifacts。`,`Read paper inventories, literature audits, and live retrieval traces directly from the Argus workdir.`)})]}),(0,J.jsxs)(`div`,{className:`header-badges`,children:[(0,J.jsxs)(Y,{tone:`success`,children:[(0,J.jsx)(w,{size:12}),h.length,` `,t(`篇论文`,`papers`)]}),(0,J.jsxs)(Y,{tone:`neutral`,children:[a.data?.sourceFiles.length??0,` `,t(`个证据文件`,`evidence files`)]})]})]}),(0,J.jsxs)(`section`,{className:`literature-stats`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--blue`,children:(0,J.jsx)(w,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`论文记录`,`Paper records`),(0,J.jsx)(`strong`,{children:h.length})]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--green`,children:(0,J.jsx)(ie,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`原文文件已验证`,`Verified sources`),(0,J.jsx)(`strong`,{children:h.filter(e=>e.evidenceStatus===`verified_artifact`).length})]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--amber`,children:(0,J.jsx)(T,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`最近工作`,`Recent work`),(0,J.jsx)(`strong`,{children:h.filter(e=>(e.year??0)>=g-1).length})]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`stat-icon stat-icon--violet`,children:(0,J.jsx)(ue,{size:18})}),(0,J.jsxs)(`p`,{children:[t(`扫描项目文件`,`Scanned files`),(0,J.jsx)(`strong`,{children:a.data?.scannedFiles??0})]})]})]}),(0,J.jsxs)(`div`,{className:`literature-v2__layout`,children:[(0,J.jsxs)(`aside`,{className:`literature-v2__sidebar ros-card`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`LIBRARY`}),(0,J.jsx)(`h2`,{children:t(`项目文献库`,`Project library`)})]})}),(0,J.jsxs)(`label`,{className:`search-field search-field--block`,children:[(0,J.jsx)(Re,{size:14}),(0,J.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),placeholder:t(`搜索标题、作者、主题`,`Search title, author, or topic`)})]}),(0,J.jsx)(`nav`,{className:`library-tabs`,children:[[`all`,t(`全部论文`,`All papers`),h.length],[`recent`,t(`最近工作`,`Recent work`),h.filter(e=>(e.year??0)>=g-1).length],[`read`,t(`已验证原文`,`Verified sources`),h.filter(e=>e.evidenceStatus===`verified_artifact`).length],[`sources`,t(`证据文件`,`Evidence files`),a.data?.sourceFiles.length??0]].map(([e,t,n])=>(0,J.jsxs)(`button`,{type:`button`,className:o===e?`is-active`:``,onClick:()=>s(e),children:[(0,J.jsx)(`span`,{children:t}),(0,J.jsx)(`small`,{children:n})]},e))}),(0,J.jsxs)(`div`,{className:`literature-source-note`,children:[(0,J.jsx)(re,{size:15}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:t(`实时来源`,`Live source`)}),(0,J.jsx)(`p`,{title:r,children:r})]})]})]}),(0,J.jsxs)(`main`,{className:`literature-v2__main`,children:[(0,J.jsxs)(`div`,{className:`literature-list-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:o===`recent`?t(`最近工作`,`Recent work`):o===`read`?t(`已验证原文文件`,`Verified source files`):o===`sources`?t(`文献证据文件`,`Literature evidence files`):t(`全部论文`,`All papers`)}),(0,J.jsx)(`p`,{children:o===`recent`?t(`按项目中最新年份 ${g||`—`} 自动筛选`,`Filtered by the latest project year: ${g||`—`}`):t(`Argus 写入工作目录后约 5 秒内自动更新`,`Updates shortly after Argus writes to the workdir`)})]}),a.isError?(0,J.jsx)(Y,{tone:`danger`,children:t(`同步失败`,`Sync failed`)}):a.isFetching?(0,J.jsx)(Y,{tone:`live`,dot:!0,children:t(`同步中`,`Syncing`)}):(0,J.jsx)(Y,{tone:`success`,children:t(`已同步`,`Synced`)})]}),a.isError?(0,J.jsx)(`div`,{className:`inline-error`,children:a.error.message}):null,o===`sources`?(0,J.jsx)(`div`,{className:`source-file-grid`,children:a.data?.sourceFiles.map(e=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(re,{size:17}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]}),(0,J.jsx)(`time`,{children:ct(e.mtime)})]},e.path))}):v.length?(0,J.jsx)(`div`,{className:`paper-grid`,children:v.map(e=>(0,J.jsx)(Qt,{paper:e,selected:y?.id===e.id,onClick:()=>d(e.id)},e.id))}):(0,J.jsx)(X,{icon:w,title:t(`此筛选下暂无论文`,`No papers match this filter`),description:t(`Argus 完成检索并写入 LITERATURE_GROUNDING.json 后会自动出现。`,`Papers appear after Argus writes LITERATURE_GROUNDING.json.`)})]}),(0,J.jsxs)(`aside`,{className:`literature-v2__detail`,children:[(0,J.jsx)(`section`,{className:`ros-card paper-detail`,children:y?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`paper-detail__top`,children:[(0,J.jsx)(Y,{tone:y.evidenceStatus===`verified_artifact`?`success`:y.evidenceStatus===`metadata`?`info`:`warn`,children:y.evidenceStatus===`verified_artifact`?`verified artifact`:y.evidenceStatus}),(0,J.jsxs)(`span`,{children:[y.year||`—`,y.venue?` · ${y.venue}`:``]})]}),(0,J.jsx)(`h2`,{children:y.title}),y.authors.length?(0,J.jsx)(`p`,{className:`paper-detail__authors`,children:y.authors.join(`, `)}):null,(0,J.jsxs)(`div`,{className:`paper-detail__body`,children:[(0,J.jsx)(`h3`,{children:t(`与当前项目的关系`,`Relationship to this project`)}),(0,J.jsx)(Z,{children:y.relevance||y.abstract||t(`尚未写入摘要。`,`No summary recorded.`)}),y.abstract&&y.relevance?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{children:t(`摘要`,`Abstract`)}),(0,J.jsx)(`p`,{children:y.abstract})]}):null]}),(0,J.jsxs)(`div`,{className:`paper-detail__source`,children:[(0,J.jsx)(`span`,{children:t(`证据文件`,`Evidence file`)}),(0,J.jsx)(`code`,{children:y.sourcePath})]}),y.url?(0,J.jsxs)(`a`,{className:`button button--secondary button--full`,href:y.url,target:`_blank`,rel:`noreferrer`,children:[t(`打开原始来源`,`Open source`),` `,(0,J.jsx)(N,{size:14})]}):null]}):(0,J.jsx)(X,{icon:w,title:t(`选择一篇论文`,`Select a paper`)})}),(0,J.jsxs)(`section`,{className:`ros-card retrieval-panel`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`ARGUS RETRIEVAL`}),(0,J.jsx)(`h2`,{children:t(`最近检索`,`Recent retrieval`)})]}),(0,J.jsx)(Y,{tone:e.connected?`live`:`warn`,dot:!0,children:e.connected?`Live`:`Polling`})]}),(0,J.jsxs)(`div`,{children:[(a.data?.searchFiles??[]).slice(0,8).map(e=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(ie,{size:13}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]}),(0,J.jsx)(`time`,{children:W(e.mtime)})]},e.path)),!a.data?.searchFiles.length&&b.slice(0,8).map((e,t)=>(0,J.jsxs)(`article`,{children:[(0,J.jsx)(ie,{size:13}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:K(e)}),(0,J.jsx)(`code`,{children:q(e,100)})]}),(0,J.jsx)(`time`,{children:W(e.ts)})]},`${e.ts}-${t}`))]})]}),(0,J.jsxs)(`section`,{className:`ros-card literature-ask`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`NEW SEARCH`}),(0,J.jsx)(`h2`,{children:t(`让 Argus 调研新工作`,`Ask Argus to research new work`)})]})}),(0,J.jsx)(`textarea`,{rows:3,value:f,onChange:e=>p(e.target.value),placeholder:t(`例如:检索 2025–2026 年与当前方法最接近的直接竞争工作…`,`Example: find the closest competing work from 2025–2026…`)}),(0,J.jsxs)(`button`,{className:`button button--primary button--full`,type:`button`,disabled:!f.trim()||m.busy,onClick:()=>void x(),children:[(0,J.jsx)(z,{size:14}),m.busy?m.phase||t(`检索中`,`Researching`):t(`发起文献调研`,`Start literature research`)]}),m.output?(0,J.jsx)(`div`,{className:`manager-mini-result`,children:(0,J.jsx)(Z,{children:m.output})}):null]})]})]})]})}var en=`/assets/pdf.worker.min-CHFwMXne.mjs`;function tn(e){return[`.png`,`.jpg`,`.jpeg`,`.webp`,`.svg`].includes(e.extension)}function nn(e){return[`.csv`,`.tsv`].includes(e.extension)}function rn(e){return[`.tex`,`.md`].includes(e.extension)}function an({src:e,name:t}){let{text:n}=Q(),r=(0,_.useRef)(null),[i,a]=(0,_.useState)(null),[o,s]=(0,_.useState)(1),[c,l]=(0,_.useState)(1.25),[u,d]=(0,_.useState)(``),[f,m]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{let t=!0,n=null;a(null),s(1),d(``),m(!1);let r=localStorage.getItem(`argus_web_token`);return Promise.all([fetch(e,{headers:r?{Authorization:`Bearer ${r}`}:{}}).then(e=>{if(!e.ok)throw Error(`PDF request failed (${e.status})`);return e.arrayBuffer()}),p(()=>import(`./pdf-Dzq_asqX.js`),__vite__mapDeps([0,1,2,3,4,5,6]))]).then(([e,r])=>{if(t)return r.GlobalWorkerOptions.workerSrc=en,n=r.getDocument({data:e}),n.promise}).then(e=>{t&&e&&a(e)}).catch(e=>{t&&d(e instanceof Error?e.message:String(e))}),()=>{t=!1,n?.destroy()}},[e]),(0,_.useEffect)(()=>{if(!i||!r.current)return;m(!1);let e=!1,t=null;return i.getPage(o).then(n=>{if(e||!r.current)return;let i=n.getViewport({scale:c}),a=r.current,o=a.getContext(`2d`);if(!o)return;let s=Math.min(window.devicePixelRatio||1,2);return a.width=Math.floor(i.width*s),a.height=Math.floor(i.height*s),a.style.width=`${i.width}px`,a.style.height=`${i.height}px`,t=n.render({canvas:a,canvasContext:o,viewport:i,transform:s===1?void 0:[s,0,0,s,0,0]}),t.promise.then(()=>{e||m(!0)})}).catch(t=>{e||d(t instanceof Error?t.message:String(t))}),()=>{e=!0,t?.cancel()}},[i,o,c]),(0,J.jsxs)(`div`,{className:`pdf-canvas-viewer`,children:[(0,J.jsxs)(`div`,{className:`pdf-canvas-toolbar`,children:[(0,J.jsx)(`strong`,{children:t}),(0,J.jsxs)(`span`,{children:[n(`第`,`Page`),` `,o,` / `,i?.numPages??`…`]}),(0,J.jsx)(`button`,{type:`button`,disabled:o<=1,onClick:()=>s(e=>e-1),children:n(`上一页`,`Previous`)}),(0,J.jsx)(`button`,{type:`button`,disabled:!i||o>=i.numPages,onClick:()=>s(e=>e+1),children:n(`下一页`,`Next`)}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>l(e=>Math.max(.75,e-.15)),children:`−`}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>l(e=>Math.min(2,e+.15)),children:`+`})]}),u?(0,J.jsx)(`div`,{className:`inline-error`,children:u}):null,(0,J.jsx)(`div`,{className:`pdf-canvas-scroll`,children:(0,J.jsx)(`canvas`,{ref:r,"data-rendered":f?`true`:`false`})})]})}function on({sid:e,workspaceId:t,entry:n}){let{text:r}=Q(),a=i({queryKey:[`paper-source-file`,e,t,n?.path,n?.mtime],queryFn:({signal:r})=>$.file(e,t,n.path,r),enabled:!!(n&&t),refetchInterval:8e3});return n?a.isError?(0,J.jsx)(X,{icon:I,title:r(`源文件暂时无法读取`,`Source file unavailable`),description:a.error.message}):n.extension===`.md`&&a.data?(0,J.jsx)(`div`,{className:`paper-markdown-preview`,children:(0,J.jsx)(Z,{children:a.data.content})}):(0,J.jsxs)(`div`,{className:`latex-source`,children:[(0,J.jsx)(`div`,{className:`latex-line-numbers`,children:(a.data?.content??``).split(` `).map((e,t)=>(0,J.jsx)(`span`,{children:t+1},t))}),(0,J.jsx)(`pre`,{children:a.data?.content||`Loading…`})]}):(0,J.jsx)(X,{icon:I,title:r(`等待 Argus 写入论文源文件`,`Waiting for Argus to write a paper source`),description:r(`paper/ 或 technical_report/ 中出现 .tex / .md 后会自动加入。`,`.tex and .md files under paper/ or technical_report/ appear automatically.`)})}function sn({sid:e,workspaceId:t,entry:n}){let r=Bt(e,t,n.path);return(0,J.jsxs)(`figure`,{children:[r.url?(0,J.jsx)(`img`,{src:r.url,alt:n.name}):(0,J.jsx)(`div`,{className:`figure-loading`,children:r.error||`Loading…`}),(0,J.jsx)(`figcaption`,{children:n.name})]})}function cn(e){let{text:t}=Q(),n=Vt(e.sid,`paper`),r=n.workspaceId,a=n.active?.path||``,o=i({queryKey:[`paper-workspace-tree`,e.sid,r],queryFn:({signal:t})=>$.tree(e.sid,r,t),enabled:!!r,refetchInterval:1e4}),s=(0,_.useMemo)(()=>Rt(o.data?.entries??[]),[o.data?.entries]),c=s.filter(rn),l=s.filter(e=>e.extension===`.bib`),u=s.filter(e=>e.extension===`.pdf`),d=s.filter(e=>tn(e)||nn(e)),[f,p]=(0,_.useState)(``),m=[...c,...l].find(e=>e.path===f)??c[0]??l[0]??null,[h,g]=(0,_.useState)(`pdf`),[v,y]=(0,_.useState)(``),b=u.find(e=>/(?:^|\/)(?:argus-technical-report|main|paper|manuscript)\.pdf$/i.test(e.path))??u[0],x=u.find(e=>e.path===v)??b??null;return(0,J.jsxs)(`div`,{className:`ros-page paper-v3`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`PAPER WORKSPACE`}),(0,J.jsx)(`h1`,{children:t(`LaTeX 论文工作区`,`LaTeX paper workspace`)}),(0,J.jsx)(`p`,{children:t(`论文源文件、编译 PDF、图表和 BibTeX 与真实项目目录保持同步。`,`Keep paper sources, compiled PDFs, figures, and BibTeX synchronized with the real project directory.`)})]}),(0,J.jsxs)(`div`,{className:`header-badges`,children:[(0,J.jsxs)(Y,{tone:o.isError?`danger`:o.isFetching?`live`:`success`,dot:!0,children:[(0,J.jsx)(Ze,{size:12}),o.isError?t(`同步失败`,`Sync failed`):o.isFetching?t(`同步中`,`Syncing`):t(`自动同步`,`Auto sync`)]}),(0,J.jsxs)(Y,{tone:u.length?`success`:`neutral`,children:[u.length,` PDF`]}),(0,J.jsxs)(Y,{tone:`neutral`,children:[d.length,` `,t(`图表`,`figures`)]})]})]}),(0,J.jsxs)(`div`,{className:`paper-root-bar ros-card`,children:[(0,J.jsx)(le,{size:16}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`APPROVED PAPER WORKSPACE`}),(0,J.jsx)(`select`,{"aria-label":t(`选择论文工作区`,`Select paper workspace`),value:r,onChange:e=>{n.setWorkspaceId(e.target.value),p(``),y(``)},children:n.profiles.data?.profiles.map(e=>(0,J.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,J.jsx)(`code`,{children:a})]}),o.isError?(0,J.jsx)(Y,{tone:`danger`,children:`Error`}):o.isFetching?(0,J.jsx)(Y,{tone:`live`,dot:!0,children:`Scanning`}):(0,J.jsx)(Y,{tone:`success`,children:`Synced`}),(0,J.jsx)(`button`,{className:`icon-button`,type:`button`,onClick:()=>void o.refetch(),"aria-label":t(`刷新论文工作区`,`Refresh paper workspace`),children:(0,J.jsx)(Pe,{size:14})})]}),(0,J.jsxs)(`div`,{className:`paper-v3__shell`,children:[(0,J.jsxs)(`aside`,{className:`paper-v3__sources ros-card`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`LATEX PROJECT`}),(0,J.jsx)(`h2`,{children:t(`论文文件`,`Paper files`)})]}),(0,J.jsx)(Y,{tone:`neutral`,children:c.length+l.length})]}),(0,J.jsxs)(`div`,{className:`paper-source-group`,children:[(0,J.jsxs)(`h3`,{children:[(0,J.jsx)(I,{size:13}),`MANUSCRIPT`]}),c.length?c.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:m?.path===e.path?`is-active`:``,onClick:()=>p(e.path),children:[(0,J.jsx)(I,{size:14}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]}),(0,J.jsx)(`small`,{children:lt(e.size)})]},e.path)):(0,J.jsx)(`p`,{children:`等待 .tex / .md`})]}),(0,J.jsxs)(`div`,{className:`paper-source-group`,children:[(0,J.jsxs)(`h3`,{children:[(0,J.jsx)(w,{size:13}),`BIBTEX`]}),l.length?l.map(e=>(0,J.jsxs)(`button`,{type:`button`,onClick:()=>p(e.path),children:[(0,J.jsx)(w,{size:14}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]})]},e.path)):(0,J.jsx)(`p`,{children:t(`等待 references.bib`,`Waiting for references.bib`)})]}),(0,J.jsxs)(`footer`,{children:[(0,J.jsx)(`span`,{children:t(`监听`,`Watching`)}),(0,J.jsx)(`code`,{children:a})]})]}),(0,J.jsxs)(`main`,{className:`paper-v3__source ros-card`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:m?.name||t(`源文件编辑器`,`Source editor`)}),(0,J.jsx)(`code`,{children:m?.path||a})]}),m?(0,J.jsxs)(`span`,{children:[t(`更新于`,`Updated`),` `,ct(m.mtime)]}):null]}),(0,J.jsx)(`div`,{children:(0,J.jsx)(on,{sid:e.sid,workspaceId:r,entry:m})}),(0,J.jsxs)(`footer`,{children:[(0,J.jsx)(`span`,{children:m?.extension.replace(`.`,``).toUpperCase()||`WAITING`}),(0,J.jsx)(`span`,{children:m?lt(m.size):t(`Argus 写入后自动出现`,`Appears after Argus writes it`)})]})]}),(0,J.jsxs)(`aside`,{className:`paper-v3__outputs ros-card`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`BUILD OUTPUT`}),(0,J.jsx)(`h2`,{children:t(`可视化产出`,`Visual outputs`)})]}),o.isError?(0,J.jsx)(Y,{tone:`danger`,children:`Error`}):o.isFetching?(0,J.jsx)(Y,{tone:`live`,dot:!0,children:`Scanning`}):(0,J.jsx)(Y,{tone:`success`,children:`Synced`})]}),(0,J.jsxs)(`nav`,{children:[(0,J.jsxs)(`button`,{type:`button`,className:h===`pdf`?`is-active`:``,onClick:()=>g(`pdf`),children:[(0,J.jsx)(I,{size:14}),`PDF `,(0,J.jsx)(`small`,{children:u.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:h===`figures`?`is-active`:``,onClick:()=>g(`figures`),children:[(0,J.jsx)(ne,{size:14}),t(`图表`,`Figures`),` `,(0,J.jsx)(`small`,{children:d.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:h===`references`?`is-active`:``,onClick:()=>g(`references`),children:[(0,J.jsx)(w,{size:14}),t(`引用`,`References`),` `,(0,J.jsx)(`small`,{children:l.length})]})]}),(0,J.jsxs)(`div`,{className:`paper-output-surface`,children:[h===`pdf`?x?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`pdf-switcher`,children:u.map(e=>(0,J.jsx)(`button`,{type:`button`,className:x.path===e.path?`is-active`:``,onClick:()=>y(e.path),children:e.name},e.path))}),(0,J.jsx)(an,{src:$.rawUrl(e.sid,r,x.path),name:x.name})]}):(0,J.jsx)(X,{icon:I,title:t(`尚无编译 PDF`,`No compiled PDF`),description:t(`Argus 或 LaTeX 流程生成 PDF 后会直接在这里可视化。`,`PDFs generated by Argus or the LaTeX pipeline appear here.`)}):null,h===`figures`?d.length?(0,J.jsx)(`div`,{className:`paper-figure-grid`,children:d.map(t=>tn(t)?(0,J.jsx)(sn,{sid:e.sid,workspaceId:r,entry:t},t.path):(0,J.jsxs)(`article`,{children:[(0,J.jsx)(Ue,{size:22}),(0,J.jsx)(`strong`,{children:t.name}),(0,J.jsx)(`code`,{children:t.path})]},t.path))}):(0,J.jsx)(X,{icon:ne,title:t(`尚无图表产出`,`No figure outputs`)}):null,h===`references`?l.length?(0,J.jsx)(`div`,{className:`paper-reference-list`,children:l.map(e=>(0,J.jsxs)(`button`,{type:`button`,onClick:()=>{p(e.path)},children:[(0,J.jsx)(w,{size:15}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`code`,{children:e.path})]})]},e.path))}):(0,J.jsx)(X,{icon:w,title:t(`尚无 BibTeX`,`No BibTeX`)}):null]}),(0,J.jsxs)(`footer`,{children:[(0,J.jsx)(`span`,{children:u.length?`PDF build detected`:`Waiting for LaTeX build`}),(0,J.jsxs)(`span`,{children:[s.length,` tracked assets`]})]})]})]})]})}var ln=[{id:`experiments`,zh:`实验进程`,en:`Experiments`,zhDesc:`实时查看 Argus 运行位置、DAG、角色交接和停止原因。`,enDesc:`Track Argus execution, DAG progress, role handoffs, and stop reasons.`,icon:se,color:`blue`},{id:`copilot`,zh:`Research Copilot`,en:`Research Copilot`,zhDesc:`保留原版 Argus 对话、Prompt 优化和工具轨迹。`,enDesc:`Chat with Argus, refine prompts, and inspect tool activity.`,icon:Ee,color:`violet`},{id:`literature`,zh:`文献中心`,en:`Literature`,zhDesc:`汇总已读论文、最近工作、检索记录和文献证据。`,enDesc:`Review papers, related work, retrieval history, and evidence.`,icon:w,color:`indigo`},{id:`inbox`,zh:`科研收信箱`,en:`Research Inbox`,zhDesc:`从零散输入抽取知识点并形成第一版 Argus Prompt。`,enDesc:`Turn rough notes into structured knowledge and an Argus prompt.`,icon:_e,color:`rose`},{id:`ide`,zh:`AI IDE`,en:`AI IDE`,zhDesc:`连接真实服务器目录,查看代码、Git 和 Argus 活动。`,enDesc:`Browse server files, Git state, and Argus activity.`,icon:j,color:`emerald`},{id:`paper`,zh:`论文工作区`,en:`Paper Workspace`,zhDesc:`自动发现 Argus 新写入的文稿、BibTeX、图表和 PDF。`,enDesc:`Discover manuscripts, BibTeX, figures, and PDFs from the workspace.`,icon:I,color:`amber`},{id:`reviewer`,zh:`模拟审稿`,en:`Reviewer`,zhDesc:`区分每轮过程审稿与项目完成后的最终投稿前审稿。`,enDesc:`Separate round-level review from final pre-submission review.`,icon:R,color:`slate`},{id:`release`,zh:`成果发布`,en:`Release`,zhDesc:`规划 GitHub 仓库、学术海报和项目宣传页。`,enDesc:`Plan a GitHub repository, academic poster, and project page.`,icon:we,color:`rose`}];function un(e){let{text:t}=Q(),n=e.snapshot.mission_view,r=n?.active_role||e.status?.active_role||`idle`;return(0,J.jsxs)(`div`,{className:`overview-page`,children:[(0,J.jsxs)(`section`,{className:`overview-hero`,children:[(0,J.jsxs)(`div`,{className:`overview-hero__copy`,children:[(0,J.jsxs)(`div`,{className:`overview-hero__badges`,children:[(0,J.jsx)(Y,{tone:e.snapshot.daemon.alive?`live`:`neutral`,dot:!0,children:e.snapshot.daemon.alive?t(`Argus 正在运行`,`Argus running`):t(`Argus 已停止`,`Argus stopped`)}),(0,J.jsx)(Y,{tone:G(n?.stage.id),children:n?.stage.label||t(`未分阶段`,`Unstaged`)})]}),(0,J.jsx)(`h1`,{children:e.snapshot.session.display_name||e.project.label}),(0,J.jsx)(`p`,{children:n?.mission.objective||e.status?.continuous?.objective||e.project.objective||t(`尚未设置研究目标。`,`No research objective has been set.`)}),(0,J.jsx)(`code`,{children:e.snapshot.session.workdir||e.snapshot.session.launch_cwd})]}),(0,J.jsxs)(`div`,{className:`overview-hero__stats`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:t(`当前角色`,`Active role`)}),(0,J.jsx)(`strong`,{children:r}),(0,J.jsx)(`small`,{children:e.snapshot.roles.find(e=>e.active)?.label||`waiting`})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:t(`研究阶段`,`Research stage`)}),(0,J.jsx)(`strong`,{children:n?.stage.label||`—`}),(0,J.jsx)(`small`,{children:n?.mission.status||`idle`})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:t(`累计运行`,`Elapsed`)}),(0,J.jsx)(`strong`,{children:st(n?.mission.campaign_elapsed_seconds||e.snapshot.daemon.uptime_seconds)}),(0,J.jsx)(`small`,{children:n?.round.current?`Round ${n.round.current}/${n.round.max||`—`}`:t(`暂无轮次`,`No round`)})]})]})]}),(0,J.jsx)(`div`,{className:`overview-section-heading`,children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:t(`项目工作区`,`Project workspace`)}),(0,J.jsx)(`p`,{children:t(`所有模块共享同一个 Argus 项目、工作目录和实时事件流。`,`All modules share the same Argus project, workdir, and live event stream.`)})]})}),(0,J.jsx)(`section`,{className:`module-grid`,children:ln.map(n=>{let r=n.icon;return(0,J.jsxs)(`button`,{className:`module-card`,type:`button`,onClick:()=>e.navigate(n.id),children:[(0,J.jsx)(`span`,{className:`module-card__icon module-card__icon--${n.color}`,children:(0,J.jsx)(r,{size:20})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h3`,{children:t(n.zh,n.en)}),(0,J.jsx)(`p`,{children:t(n.zhDesc,n.enDesc)})]}),(0,J.jsx)(x,{size:16})]},n.id)})}),(0,J.jsxs)(`section`,{className:`overview-lower`,children:[(0,J.jsx)(ft,{eyebrow:`CURRENT MISSION`,title:t(`当前任务`,`Current mission`),children:(0,J.jsxs)(`div`,{className:`overview-mission`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(Ge,{size:18}),(0,J.jsx)(`span`,{children:n?.mission.status||`idle`})]}),(0,J.jsx)(`h3`,{children:n?.mission.title||e.project.current_task||t(`等待新任务`,`Waiting for a new task`)}),(0,J.jsx)(`p`,{children:n?.mission.summary||n?.frontier.summary||n?.review.reason||t(`Argus 的下一步和 Reviewer 边界会在这里同步。`,`Argus next steps and reviewer boundaries appear here.`)}),(0,J.jsxs)(`button`,{className:`button button--secondary`,type:`button`,onClick:()=>e.navigate(`experiments`),children:[t(`查看完整实验进程`,`View experiment progress`),` `,(0,J.jsx)(x,{size:14})]})]})}),(0,J.jsx)(ft,{eyebrow:`RECENT ACTIVITY`,title:t(`最近活动`,`Recent activity`),bodyClassName:`panel__body--flush`,children:(0,J.jsx)(mt,{events:e.events,limit:7,dense:!0})})]})]})}var dn=[`ICLR`,`NeurIPS`,`ICML`,`TMLR`,`ACL`,`EMNLP`,`NAACL`,`CVPR`,`ICCV`,`ECCV`,`AAAI`,`KDD`,`Nature Machine Intelligence`,`JMLR`,`IEEE TPAMI`,`__custom__`],fn=[`Novelty`,`Technical soundness`,`Experimental rigor`,`Baseline fairness`,`Statistical validity`,`Reproducibility`,`Writing clarity`,`Ethics / limitations`,`Artifact availability`],pn=`请特别检查 train/dev/test 泄漏、baseline 是否公平,以及 novelty claim 是否被现有直接工作覆盖。`,mn=`Pay special attention to train/dev/test leakage, baseline fairness, and whether direct prior work covers the novelty claim.`;function hn({mode:e,reviewerActive:t,hasReport:n}){let{text:r}=Q(),i=e===`process`?[[r(`Engineer 执行`,`Engineer execution`),r(`代码、实验与证据`,`Code, experiments, and evidence`),j],[r(`Reviewer 检查`,`Reviewer check`),r(`独立核验当前轮次`,`Independent round verification`),R],[r(`形成 Verdict`,`Produce verdict`),`done / continue / blocked`,Le],[r(`回流下一轮`,`Return to next round`),r(`修复任务进入 backlog`,`Repair tasks enter the backlog`),Fe]]:[[r(`选择最终稿`,`Select final draft`),r(`LaTeX / PDF 与证据包`,`LaTeX / PDF and evidence package`),I],[r(`独立最终审稿`,`Independent final review`),r(`按目标 venue 全面检查`,`Full target-venue review`),R],[r(`生成审稿报告`,`Generate review report`),r(`评分、问题与置信度`,`Scores, issues, and confidence`),F],[r(`修改清单`,`Revision checklist`),r(`投稿前人工确认`,`Human confirmation before submission`),be]];return(0,J.jsx)(`div`,{className:`review-flow`,children:i.map(([e,r,a],o)=>(0,J.jsxs)(`div`,{className:t&&o===1||n&&o>=2?`is-active`:o===0?`is-done`:``,children:[(0,J.jsx)(`span`,{children:o+1}),(0,J.jsx)(a,{size:17}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e}),(0,J.jsx)(`small`,{children:r})]}),o(o?.role_work??[]).filter(e=>e.role===`reviewer`).filter(e=>/review|verdict|decision|completion|handoff/i.test(`${e.kind} ${e.title}`)).sort((e,t)=>t.ts-e.ts),[o?.role_work]),c=(0,_.useMemo)(()=>e.events.filter(e=>/review/.test(String(e.type??``))||/review/.test(String(e.agent_layer??e.actor??``))),[e.events]),[l,u]=(0,_.useState)(``),d=s.find(e=>e.id===l)??s[0]??null,f=Vt(e.sid,`review`),p=i({queryKey:[`review-workspace-tree`,e.sid,f.workspaceId],queryFn:({signal:t})=>$.tree(e.sid,f.workspaceId,t),enabled:!!f.workspaceId,refetchInterval:12e3}),m=(p.data?.entries??[]).filter(e=>e.type===`file`&&!/final[_-]?review[_-]?request/i.test(e.path)&&/final[_-]?review|final[_-]?.*verdict|submission[_-]?review/i.test(e.path)).filter(e=>[`.md`,`.txt`,`.json`].includes(e.extension)).sort((e,t)=>t.mtime-e.mtime),h=(p.data?.entries??[]).filter(e=>e.type===`file`&&[`.tex`,`.md`,`.pdf`].includes(e.extension)&&/(?:^|\/)(paper|manuscript|technical_report)(?:\/|$)/i.test(e.path)).sort((e,t)=>t.mtime-e.mtime),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(``),x=m.find(e=>e.path===y)??m[0]??null,S=i({queryKey:[`final-review-file`,e.sid,f.workspaceId,x?.path,x?.mtime],queryFn:({signal:t})=>$.file(e.sid,f.workspaceId,x.path,t),enabled:!!(x&&f.workspaceId),refetchInterval:12e3}),[C,w]=(0,_.useState)(`ICLR`),[T,E]=(0,_.useState)(``),[D,ee]=(0,_.useState)(`conference`),[k,A]=(0,_.useState)(`strict`),[j,M]=(0,_.useState)([`Novelty`,`Technical soundness`,`Experimental rigor`,`Baseline fairness`,`Reproducibility`]),[N,te]=(0,_.useState)(()=>t===`zh-CN`?pn:mn),[P,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(``),[I,L]=(0,_.useState)(``),ae=o?.review,oe=o?.roles.find(e=>e.role===`reviewer`)||e.snapshot.roles.find(e=>e.role===`reviewer`);(0,_.useEffect)(()=>{te(e=>e===pn||e===mn?t===`zh-CN`?pn:mn:e)},[t]);let se=async()=>{let t=C===`__custom__`?T.trim():C;if(!(!t||!N.trim()||!confirm(n(`确认在项目完成后按 ${t} 标准发起独立最终审稿?`,`Start an independent final review using ${t} standards?`)))){ne(!0),ie(``),L(``);try{let r=await H.createFinalReview(e.sid,{venue:t,venue_type:D,strictness:k,manuscript_path:g,emphasis:j,scope:N});L(n(`最终审稿已进入 Argus 队列 · ${r.manifest_path}`,`Final review queued in Argus · ${r.manifest_path}`)),await Promise.all([e.refresh(),p.refetch()])}catch(e){ie(e instanceof Error?e.message:String(e))}finally{ne(!1)}}};return(0,J.jsxs)(`div`,{className:`ros-page reviewer-v2`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`REVIEWER ARENA`}),(0,J.jsx)(`h1`,{children:n(`模拟审稿`,`Reviewer arena`)}),(0,J.jsx)(`p`,{children:n(`过程审稿用于每轮 Engineer ⇄ Reviewer 纠偏;最终审稿用于论文完成后的投稿前独立检查。`,`Process review corrects each Engineer ⇄ Reviewer round; final review is an independent pre-submission check.`)})]}),(0,J.jsx)(Y,{tone:oe?.status?G(oe.status):`neutral`,dot:oe?.status===`active`,children:oe?.status||`waiting`})]}),(0,J.jsxs)(`div`,{className:`review-mode-tabs`,children:[(0,J.jsxs)(`button`,{type:`button`,className:r===`process`?`is-active`:``,onClick:()=>a(`process`),children:[(0,J.jsx)(he,{size:16}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:n(`过程审稿`,`Process review`)}),(0,J.jsx)(`small`,{children:n(`Argus 每轮执行中的 Reviewer 反馈`,`Reviewer feedback during each Argus round`)})]}),(0,J.jsx)(Y,{tone:`neutral`,children:s.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:r===`final`?`is-active`:``,onClick:()=>a(`final`),children:[(0,J.jsx)(Le,{size:16}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:n(`最终审稿`,`Final review`)}),(0,J.jsx)(`small`,{children:n(`项目完成后的独立投稿前审稿`,`Independent pre-submission review`)})]}),(0,J.jsx)(Y,{tone:`neutral`,children:m.length})]})]}),r===`process`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(hn,{mode:`process`,reviewerActive:oe?.status===`active`,hasReport:!!ae?.status}),(0,J.jsxs)(`div`,{className:`process-review-layout`,children:[(0,J.jsxs)(`aside`,{className:`ros-card review-rounds`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`ENGINEER ⇄ REVIEWER`}),(0,J.jsx)(`h2`,{children:n(`过程审稿轮次`,`Process review rounds`)})]})}),(0,J.jsx)(`div`,{children:s.length?s.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:d?.id===e.id?`is-active`:``,onClick:()=>u(e.id),children:[(0,J.jsx)(`span`,{className:`review-state review-state--${G(e.status)}`,children:(0,J.jsx)(R,{size:14})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.title}),(0,J.jsxs)(`small`,{children:[ct(e.ts),` · `,e.status||e.kind]})]})]},e.id)):(0,J.jsx)(X,{icon:R,title:n(`暂无过程审稿`,`No process reviews yet`)})})]}),(0,J.jsxs)(`main`,{className:`ros-card process-report`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`ROUND VERDICT`}),(0,J.jsx)(`h2`,{children:d?.title||n(`选择一轮 Reviewer 反馈`,`Select reviewer feedback`)})]}),d?(0,J.jsx)(Y,{tone:G(d.status),children:d.status}):null]}),d?(0,J.jsxs)(`article`,{children:[(0,J.jsxs)(`div`,{className:`process-report__meta`,children:[(0,J.jsxs)(`span`,{children:[`Round `,d.round_index??`—`]}),(0,J.jsx)(`time`,{children:ct(d.ts)})]}),(0,J.jsx)(Z,{children:d.detail||n(`该轮没有留下可展示报告。`,`This round has no displayable report.`)})]}):(0,J.jsx)(X,{icon:F,title:n(`选择左侧过程审稿`,`Select a process review`)})]}),(0,J.jsxs)(`aside`,{className:`ros-card review-live`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`LIVE REVIEW EVENTS`}),(0,J.jsx)(`h2`,{children:n(`Reviewer 实时轨迹`,`Live reviewer activity`)})]}),(0,J.jsx)(Y,{tone:e.connected?`live`:`warn`,dot:!0,children:e.connected?`Live`:`Polling`})]}),(0,J.jsx)(mt,{events:c,limit:24,dense:!0})]}),(0,J.jsxs)(`section`,{className:`process-verdict-card`,children:[(0,J.jsx)(`span`,{className:`process-verdict-card__icon process-verdict-card__icon--${G(ae?.status)}`,children:G(ae?.status)===`success`?(0,J.jsx)(O,{size:21}):(0,J.jsx)(qe,{size:21})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:n(`当前过程 Verdict`,`Current process verdict`)}),(0,J.jsx)(`strong`,{children:ae?.status||`Awaiting review`}),(0,J.jsx)(`p`,{children:ae?.reason||n(`Reviewer 完成下一轮后会写入判断和行动要求。`,`The Reviewer will record a decision and required actions after the next round.`)})]})]})]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(hn,{mode:`final`,reviewerActive:P,hasReport:!!(x||I)}),(0,J.jsxs)(`div`,{className:`final-review-layout`,children:[(0,J.jsxs)(`aside`,{className:`ros-card final-review-files`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`FINAL REPORTS`}),(0,J.jsx)(`h2`,{children:n(`最终审稿报告`,`Final review reports`)})]})}),(0,J.jsx)(`div`,{children:m.length?m.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:x?.path===e.path?`is-active`:``,onClick:()=>b(e.path),children:[(0,J.jsx)(F,{size:14}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:e.name}),(0,J.jsx)(`small`,{children:ct(e.mtime)})]})]},e.path)):(0,J.jsx)(X,{icon:F,title:n(`还没有最终审稿报告`,`No final review report yet`),description:n(`完成论文后可从右侧发起。`,`Start one from the form after the paper is complete.`)})})]}),(0,J.jsxs)(`main`,{className:`ros-card final-review-report`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`INDEPENDENT REVIEW`}),(0,J.jsx)(`h2`,{children:x?.name||n(`投稿前最终审稿`,`Pre-submission final review`)})]}),x?(0,J.jsx)(Y,{tone:`success`,children:`Saved report`}):null]}),S.data?(0,J.jsx)(`article`,{children:(0,J.jsx)(Z,{children:S.data.content})}):I?(0,J.jsxs)(`article`,{className:`final-review-receipt`,children:[(0,J.jsx)(Y,{tone:`success`,children:`Queued`}),(0,J.jsx)(`p`,{children:I}),(0,J.jsx)(`small`,{children:n(`Argus 将生成结构化最终审稿报告;可在过程事件和任务路线查看执行状态。`,`Argus will generate a structured final review report; execution remains visible in events and the task route.`)})]}):(0,J.jsx)(X,{icon:Le,title:n(`项目完成后再发起最终审稿`,`Start final review after project completion`),description:n(`最终 Reviewer 会读取完整稿件、实验、文献与过程审稿记录。`,`The final Reviewer reads the full manuscript, experiments, literature, and process-review history.`)})]}),(0,J.jsxs)(`aside`,{className:`ros-card final-review-form`,children:[(0,J.jsx)(`header`,{children:(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{children:`NEW FINAL REVIEW`}),(0,J.jsx)(`h2`,{children:n(`发起独立最终审稿`,`Start independent final review`)})]})}),(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`label`,{className:`field`,children:[(0,J.jsx)(`span`,{children:n(`选择最终稿`,`Select final manuscript`)}),(0,J.jsxs)(`select`,{value:g,onChange:e=>v(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:n(`自动选择最新稿件`,`Automatically select latest`)}),h.map(e=>(0,J.jsx)(`option`,{value:e.path,children:e.path},e.path))]})]}),(0,J.jsxs)(`div`,{className:`review-form-row`,children:[(0,J.jsxs)(`label`,{className:`field`,children:[(0,J.jsx)(`span`,{children:n(`Venue 类型`,`Venue type`)}),(0,J.jsxs)(`select`,{value:D,onChange:e=>ee(e.target.value),children:[(0,J.jsx)(`option`,{value:`conference`,children:`Conference`}),(0,J.jsx)(`option`,{value:`journal`,children:`Journal`}),(0,J.jsx)(`option`,{value:`workshop`,children:`Workshop`})]})]}),(0,J.jsxs)(`label`,{className:`field`,children:[(0,J.jsx)(`span`,{children:n(`审稿严格度`,`Review strictness`)}),(0,J.jsxs)(`select`,{value:k,onChange:e=>A(e.target.value),children:[(0,J.jsx)(`option`,{value:`preflight`,children:n(`快速预检`,`Quick preflight`)}),(0,J.jsx)(`option`,{value:`standard`,children:n(`标准审稿`,`Standard review`)}),(0,J.jsx)(`option`,{value:`strict`,children:n(`严格模拟审稿`,`Strict simulated review`)}),(0,J.jsx)(`option`,{value:`red-team`,children:`Red Team / Desk Reject`})]})]})]}),(0,J.jsxs)(`label`,{className:`field`,children:[(0,J.jsx)(`span`,{children:n(`目标会议 / 期刊`,`Target venue`)}),(0,J.jsx)(`select`,{value:C,onChange:e=>w(e.target.value),children:dn.map(e=>(0,J.jsx)(`option`,{value:e,children:e===`__custom__`?n(`其他 / 自定义…`,`Other / custom…`):e},e))})]}),C===`__custom__`?(0,J.jsxs)(`label`,{className:`field`,children:[(0,J.jsx)(`span`,{children:n(`自定义 Venue 名称`,`Custom venue name`)}),(0,J.jsx)(`input`,{value:T,onChange:e=>E(e.target.value),placeholder:n(`例如:Nature Machine Intelligence / CHI Workshop`,`Example: Nature Machine Intelligence / CHI Workshop`)})]}):null,(0,J.jsxs)(`fieldset`,{className:`review-emphasis`,children:[(0,J.jsx)(`legend`,{children:n(`重点审查维度`,`Review emphasis`)}),fn.map(e=>(0,J.jsxs)(`label`,{children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:j.includes(e),onChange:()=>M(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}),(0,J.jsx)(`span`,{children:e})]},e))]}),(0,J.jsxs)(`label`,{className:`field`,children:[(0,J.jsx)(`span`,{children:n(`特别强调`,`Special emphasis`)}),(0,J.jsx)(`textarea`,{rows:5,value:N,onChange:e=>te(e.target.value),placeholder:n(`写明你最希望 Reviewer 严格检查的问题…`,`Describe what the Reviewer should scrutinize most…`)})]}),(0,J.jsxs)(`div`,{className:`final-review-warning`,children:[(0,J.jsx)(qe,{size:15}),(0,J.jsx)(`p`,{children:n(`这是完成阶段的独立 Reviewer,不替代正式同行评审,也不会自动投稿。`,`This independent completion-stage Reviewer does not replace peer review and never submits automatically.`)})]}),(0,J.jsxs)(`button`,{className:`button button--primary button--full`,type:`button`,disabled:P||!N.trim()||C===`__custom__`&&!T.trim(),onClick:()=>void se(),children:[P?(0,J.jsx)(z,{size:14}):(0,J.jsx)(ze,{size:14}),P?n(`正在创建审稿任务`,`Creating review task`):n(`开始最终审稿`,`Start final review`)]}),re?(0,J.jsx)(`div`,{className:`inline-error`,children:re}):null]})]})]})]})]})}var _n=[{icon:me,title:`GitHub Repository`,zhDetail:`README、LICENSE、CITATION.cff、环境文件、Secret Scan 与人工确认后的仓库创建。`,enDetail:`Prepare README, LICENSE, CITATION.cff, environment files, secret scanning, and an approved repository.`,zhItems:[`选择账户与可见性`,`生成发布清单`,`预览 Git diff`,`人工批准后 push`],enItems:[`Choose account and visibility`,`Generate release manifest`,`Preview Git diff`,`Push after approval`]},{icon:Me,title:`Academic Poster`,zhDetail:`从最终稿、图表和结果中生成可审阅的学术海报。`,enDetail:`Generate a reviewable academic poster from the final paper, figures, and results.`,zhItems:[`A0/A1 与横竖版`,`机构 Logo 与主题`,`图表布局`,`PDF / PNG / SVG`],enItems:[`A0/A1 portrait or landscape`,`Institution logo and theme`,`Figure layout`,`PDF / PNG / SVG`]},{icon:M,title:`Project Page`,zhDetail:`生成论文项目宣传页和可部署的静态站点。`,enDetail:`Generate a paper project page and deployable static site.`,zhItems:[`方法与结果展示`,`交互式图表`,`Paper / Code / Model`,`预览后部署`],enItems:[`Methods and results`,`Interactive charts`,`Paper / Code / Model`,`Deploy after preview`]}];function vn(e){let{text:t}=Q();return(0,J.jsxs)(`div`,{className:`ros-page release-page`,children:[(0,J.jsxs)(`header`,{className:`ros-page-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`RESULTS RELEASE`}),(0,J.jsx)(`h1`,{children:t(`成果发布`,`Results release`)}),(0,J.jsx)(`p`,{children:t(`未来用于把研究工作整理成 GitHub 仓库、学术海报和项目宣传页。当前只展示规划,不执行发布。`,`Plan a GitHub repository, academic poster, and project page. This view does not publish anything yet.`)})]}),(0,J.jsx)(Y,{tone:`warn`,children:t(`敬请期待`,`Planned`)})]}),(0,J.jsxs)(`section`,{className:`release-hero`,children:[(0,J.jsx)(`span`,{children:(0,J.jsx)(z,{size:28})}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`eyebrow`,children:`PLANNED WORKSPACE`}),(0,J.jsx)(`h2`,{children:t(`从研究产物到可审核的公开成果`,`From research artifacts to reviewable public outputs`)}),(0,J.jsx)(`p`,{children:t(`后续将调用受审计的 AI Agent 基于真实工作区生成发布补丁和视觉资产,但任何外部创建、push 或部署都需要人工批准。`,`Audited agents will generate release patches and visual assets from the real workspace, while every external create, push, or deploy requires approval.`)})]})]}),(0,J.jsx)(`div`,{className:`release-module-grid`,children:_n.map(e=>{let n=e.icon,r=t(e.zhItems.join(` `),e.enItems.join(` `)).split(` diff --git a/frontend/web/dist/assets/index-7NNAUeAk.js b/frontend/web/dist/assets/index-DYvAJ_cb.js similarity index 99% rename from frontend/web/dist/assets/index-7NNAUeAk.js rename to frontend/web/dist/assets/index-DYvAJ_cb.js index 5ceade31b..a2b22d8bf 100644 --- a/frontend/web/dist/assets/index-7NNAUeAk.js +++ b/frontend/web/dist/assets/index-DYvAJ_cb.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/motion-sqs9Ax-g.js","assets/rolldown-runtime-hePW80VL.js","assets/ResearchWorkbenchPanel-D4WnlzR6.js","assets/icons-BgG77X6K.js","assets/query-DOc9YWJi.js","assets/markdown-BdostSiP.js","assets/ResearchWorkbenchPanel-Bxi8TjKE.css"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/motion-sqs9Ax-g.js","assets/rolldown-runtime-hePW80VL.js","assets/ResearchWorkbenchPanel-BOPEGTC6.js","assets/icons-BgG77X6K.js","assets/query-DOc9YWJi.js","assets/markdown-BdostSiP.js","assets/ResearchWorkbenchPanel-Bxi8TjKE.css"])))=>i.map(i=>d[i]); import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{C as n,D as r,E as i,S as a,T as o,_ as s,a as c,b as l,c as u,d,f,g as p,h as m,i as h,l as g,m as _,n as v,o as y,p as b,r as x,s as S,t as C,u as w,v as T,w as ee,x as te,y as E}from"./icons-BgG77X6K.js";import{_ as ne,a as re,c as ie,d as ae,f as D,g as O,h as oe,i as se,l as ce,m as k,n as le,o as A,p as ue,r as de,s as fe,t as j,u as pe,v as me,y as he}from"./query-DOc9YWJi.js";import{n as ge,t as _e}from"./markdown-BdostSiP.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var ve=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=typeof setTimeout==`function`?setTimeout:null,_=typeof clearTimeout==`function`?clearTimeout:null,v=typeof setImmediate<`u`?setImmediate:null;typeof navigator<`u`&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function y(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function b(e){if(h=!1,y(e),!m){if(n(c)!==null)m=!0,ae(x);else{var t=n(l);t!==null&&D(b,t.startTime-e)}}}function x(t,i){m=!1,h&&(h=!1,_(w),w=-1),p=!0;var a=f;try{for(y(i),d=n(c);d!==null&&(!(d.expirationTime>i)||t&&!te());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=i);i=e.unstable_now(),typeof s==`function`?d.callback=s:d===n(c)&&r(c),y(i)}else r(c);d=n(c)}if(d!==null)var u=!0;else{var g=n(l);g!==null&&D(b,g.startTime-i),u=!1}return u}finally{d=null,f=a,p=!1}}var S=!1,C=null,w=-1,T=5,ee=-1;function te(){return!(e.unstable_now()-eee||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(_(w),w=-1):h=!0,D(b,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,ae(x))),r},e.unstable_shouldYield=te,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ye=t(((e,t)=>{t.exports=ve()})),be=t((e=>{var t=r(),n=ye();function i(e){for(var t=`https://reactjs.org/docs/error-decoder.html?invariant=`+e,n=1;n`u`||window.document===void 0||window.document.createElement===void 0),u=Object.prototype.hasOwnProperty,d=/^[: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]*$/,f={},p={};function m(e){return u.call(p,e)?!0:u.call(f,e)?!1:d.test(e)?p[e]=!0:(f[e]=!0,!1)}function h(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case`function`:case`symbol`:return!0;case`boolean`:return r?!1:n===null?(e=e.toLowerCase().slice(0,5),e!==`data-`&&e!==`aria-`):!n.acceptsBooleans;default:return!1}}function g(e,t,n,r){if(t==null||h(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function _(e,t,n,r,i,a,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=o}var v={};`children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style`.split(` `).forEach(function(e){v[e]=new _(e,0,!1,e,null,!1,!1)}),[[`acceptCharset`,`accept-charset`],[`className`,`class`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`]].forEach(function(e){var t=e[0];v[t]=new _(t,1,!1,e[1],null,!1,!1)}),[`contentEditable`,`draggable`,`spellCheck`,`value`].forEach(function(e){v[e]=new _(e,2,!1,e.toLowerCase(),null,!1,!1)}),[`autoReverse`,`externalResourcesRequired`,`focusable`,`preserveAlpha`].forEach(function(e){v[e]=new _(e,2,!1,e,null,!1,!1)}),`allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope`.split(` `).forEach(function(e){v[e]=new _(e,3,!1,e.toLowerCase(),null,!1,!1)}),[`checked`,`multiple`,`muted`,`selected`].forEach(function(e){v[e]=new _(e,3,!0,e,null,!1,!1)}),[`capture`,`download`].forEach(function(e){v[e]=new _(e,4,!1,e,null,!1,!1)}),[`cols`,`rows`,`size`,`span`].forEach(function(e){v[e]=new _(e,6,!1,e,null,!1,!1)}),[`rowSpan`,`start`].forEach(function(e){v[e]=new _(e,5,!1,e.toLowerCase(),null,!1,!1)});var y=/[\-:]([a-z])/g;function b(e){return e[1].toUpperCase()}`accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height`.split(` `).forEach(function(e){var t=e.replace(y,b);v[t]=new _(t,1,!1,e,null,!1,!1)}),`xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type`.split(` `).forEach(function(e){var t=e.replace(y,b);v[t]=new _(t,1,!1,e,`http://www.w3.org/1999/xlink`,!1,!1)}),[`xml:base`,`xml:lang`,`xml:space`].forEach(function(e){var t=e.replace(y,b);v[t]=new _(t,1,!1,e,`http://www.w3.org/XML/1998/namespace`,!1,!1)}),[`tabIndex`,`crossOrigin`].forEach(function(e){v[e]=new _(e,1,!1,e.toLowerCase(),null,!1,!1)}),v.xlinkHref=new _(`xlinkHref`,1,!1,`xlink:href`,`http://www.w3.org/1999/xlink`,!0,!1),[`src`,`href`,`action`,`formAction`].forEach(function(e){v[e]=new _(e,1,!1,e.toLowerCase(),null,!0,!0)});function x(e,t,n,r){var i=v.hasOwnProperty(t)?v[t]:null;(i===null?r||!(2`)&&(c=c.replace(``,e.displayName)),c}while(1<=o&&0<=s);break}}}finally{ue=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:``)?A(e):``}function fe(e){switch(e.tag){case 5:return A(e.type);case 16:return A(`Lazy`);case 13:return A(`Suspense`);case 19:return A(`SuspenseList`);case 0:case 2:case 15:return e=de(e.type,!1),e;case 11:return e=de(e.type.render,!1),e;case 1:return e=de(e.type,!0),e;default:return``}}function j(e){if(e==null)return null;if(typeof e==`function`)return e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case T:return`Fragment`;case w:return`Portal`;case te:return`Profiler`;case ee:return`StrictMode`;case ie:return`Suspense`;case ae:return`SuspenseList`}if(typeof e==`object`)switch(e.$$typeof){case ne:return(e.displayName||`Context`)+`.Consumer`;case E:return(e._context.displayName||`Context`)+`.Provider`;case re:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case D:return t=e.displayName||null,t===null?j(e.type)||`Memo`:t;case O:t=e._payload,e=e._init;try{return j(e(t))}catch{}}return null}function pe(e){var t=e.type;switch(e.tag){case 24:return`Cache`;case 9:return(t.displayName||`Context`)+`.Consumer`;case 10:return(t._context.displayName||`Context`)+`.Provider`;case 18:return`DehydratedFragment`;case 11:return e=t.render,e=e.displayName||e.name||``,t.displayName||(e===``?`ForwardRef`:`ForwardRef(`+e+`)`);case 7:return`Fragment`;case 5:return t;case 4:return`Portal`;case 3:return`Root`;case 6:return`Text`;case 16:return j(t);case 8:return t===ee?`StrictMode`:`Mode`;case 22:return`Offscreen`;case 12:return`Profiler`;case 21:return`Scope`;case 13:return`Suspense`;case 19:return`SuspenseList`;case 25:return`TracingMarker`;case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t==`function`)return t.displayName||t.name||null;if(typeof t==`string`)return t}return null}function me(e){switch(typeof e){case`boolean`:case`number`:case`string`:case`undefined`:return e;case`object`:return e;default:return``}}function he(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()===`input`&&(t===`checkbox`||t===`radio`)}function ge(e){var t=he(e)?`checked`:`value`,n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=``+e[t];if(!e.hasOwnProperty(t)&&n!==void 0&&typeof n.get==`function`&&typeof n.set==`function`){var i=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(e){r=``+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=``+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function _e(e){e._valueTracker||=ge(e)}function ve(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r=``;return e&&(r=he(e)?e.checked?`true`:`false`:e.value),e=r,e!==n&&(t.setValue(e),!0)}function be(e){if(e||=typeof document<`u`?document:void 0,e===void 0)return null;try{return e.activeElement||e.body}catch{return e.body}}function xe(e,t){var n=t.checked;return k({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Se(e,t){var n=t.defaultValue==null?``:t.defaultValue,r=t.checked==null?t.defaultChecked:t.checked;n=me(t.value==null?n:t.value),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type===`checkbox`||t.type===`radio`?t.checked!=null:t.value!=null}}function Ce(e,t){t=t.checked,t!=null&&x(e,`checked`,t,!1)}function we(e,t){Ce(e,t);var n=me(t.value),r=t.type;if(n!=null)r===`number`?(n===0&&e.value===``||e.value!=n)&&(e.value=``+n):e.value!==``+n&&(e.value=``+n);else if(r===`submit`||r===`reset`){e.removeAttribute(`value`);return}t.hasOwnProperty(`value`)?Ee(e,t.type,n):t.hasOwnProperty(`defaultValue`)&&Ee(e,t.type,me(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Te(e,t,n){if(t.hasOwnProperty(`value`)||t.hasOwnProperty(`defaultValue`)){var r=t.type;if(!(r!==`submit`&&r!==`reset`||t.value!==void 0&&t.value!==null))return;t=``+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==``&&(e.name=``),e.defaultChecked=!!e._wrapperState.initialChecked,n!==``&&(e.name=n)}function Ee(e,t,n){(t!==`number`||be(e.ownerDocument)!==e)&&(n==null?e.defaultValue=``+e._wrapperState.initialValue:e.defaultValue!==``+n&&(e.defaultValue=``+n))}var M=Array.isArray;function De(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i`+t.valueOf().toString()+``,t=Pe.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ie(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Le={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Re=[`Webkit`,`ms`,`Moz`,`O`];Object.keys(Le).forEach(function(e){Re.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Le[t]=Le[e]})});function ze(e,t,n){return t==null||typeof t==`boolean`||t===``?``:n||typeof t!=`number`||t===0||Le.hasOwnProperty(e)&&Le[e]?(``+t).trim():t+`px`}function Be(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=n.indexOf(`--`)===0,i=ze(n,t[n],r);n===`float`&&(n=`cssFloat`),r?e.setProperty(n,i):e[n]=i}}var Ve=k({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function He(e,t){if(t){if(Ve[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(i(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(i(60));if(typeof t.dangerouslySetInnerHTML!=`object`||!(`__html`in t.dangerouslySetInnerHTML))throw Error(i(61))}if(t.style!=null&&typeof t.style!=`object`)throw Error(i(62))}}function Ue(e,t){if(e.indexOf(`-`)===-1)return typeof t.is==`string`;switch(e){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 We=null;function Ge(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ke=null,qe=null,N=null;function Je(e){if(e=Pi(e)){if(typeof Ke!=`function`)throw Error(i(280));var t=e.stateNode;t&&(t=Ii(t),Ke(e.stateNode,e.type,t))}}function Ye(e){qe?N?N.push(e):N=[e]:qe=e}function Xe(){if(qe){var e=qe,t=N;if(N=qe=null,Je(e),t)for(e=0;e>>=0,e===0?32:31-(Et(e)/Dt|0)|0}var kt=64,At=4194304;function jt(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64: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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Mt(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,a=e.pingedLanes,o=n&268435455;if(o!==0){var s=o&~i;s===0?(a&=o,a!==0&&(r=jt(a))):r=jt(s)}else o=n&~i,o===0?a!==0&&(r=jt(a)):r=jt(o);if(r===0)return 0;if(t!==0&&t!==r&&(t&i)===0&&(i=r&-r,a=t&-t,i>=a||i===16&&a&4194240))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Rt(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Tt(t),e[t]=n}function zt(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Zn),$n=` `,er=!1;function tr(e,t){switch(e){case`keyup`:return Xn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function nr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var rr=!1;function ir(e,t){switch(e){case`compositionend`:return nr(t);case`keypress`:return t.which===32?(er=!0,$n):null;case`textInput`:return e=t.data,e===$n&&er?null:e;default:return null}}function ar(e,t){if(rr)return e===`compositionend`||!W&&tr(e,t)?(e=xn(),bn=yn=U=null,rr=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Dr(n)}}function kr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?kr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ar(){for(var e=window,t=be();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=be(e.document)}return t}function jr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}function K(e){var t=Ar(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&kr(n.ownerDocument.documentElement,n)){if(r!==null&&jr(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),`selectionStart`in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,a=Math.min(r.start,i);r=r.end===void 0?a:Math.min(r.end,i),!e.extend&&a>r&&(i=r,r=a,a=i),i=Or(n,a);var o=Or(n,r);i&&o&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus==`function`&&n.focus(),n=0;n=document.documentMode,Nr=null,Pr=null,Fr=null,Ir=!1;function Lr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ir||Nr==null||Nr!==be(r)||(r=Nr,`selectionStart`in r&&jr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Fr&&Er(Fr,r)||(Fr=r,r=si(Pr,`onSelect`),0Ri||(e.current=Li[Ri],Li[Ri]=null,Ri--)}function X(e,t){Ri++,Li[Ri]=e.current,e.current=t}var Bi={},Vi=zi(Bi),Hi=zi(!1),Ui=Bi;function Wi(e,t){var n=e.type.contextTypes;if(!n)return Bi;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},a;for(a in n)i[a]=t[a];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Gi(e){return e=e.childContextTypes,e!=null}function Ki(){Y(Hi),Y(Vi)}function qi(e,t,n){if(Vi.current!==Bi)throw Error(i(168));X(Vi,t),X(Hi,n)}function Ji(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!=`function`)return n;for(var a in r=r.getChildContext(),r)if(!(a in t))throw Error(i(108,pe(e)||`Unknown`,a));return k({},n,r)}function Yi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Bi,Ui=Vi.current,X(Vi,e),X(Hi,Hi.current),!0}function Xi(e,t,n){var r=e.stateNode;if(!r)throw Error(i(169));n?(e=Ji(e,t,Ui),r.__reactInternalMemoizedMergedChildContext=e,Y(Hi),Y(Vi),X(Vi,e)):Y(Hi),X(Hi,n)}var Zi=null,Qi=!1,$i=!1;function ea(e){Zi===null?Zi=[e]:Zi.push(e)}function ta(e){Qi=!0,ea(e)}function na(){if(!$i&&Zi!==null){$i=!0;var e=0,t=V;try{var n=Zi;for(V=1;e>=o,i-=o,ua=1<<32-Tt(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Z&&fa(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Z&&fa(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Z&&fa(a,g),u}for(h=r(a,h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Z&&fa(a,g),u}function _(e,r,i,o){if(typeof i==`object`&&i&&i.type===T&&i.key===null&&(i=i.props.children),typeof i==`object`&&i){switch(i.$$typeof){case C:a:{for(var c=i.key,l=r;l!==null;){if(l.key===c){if(c=i.type,c===T){if(l.tag===7){n(e,l.sibling),r=a(l,i.props.children),r.return=e,e=r;break a}}else if(l.elementType===c||typeof c==`object`&&c&&c.$$typeof===O&&ja(c)===l.type){n(e,l.sibling),r=a(l,i.props),r.ref=ka(e,l,i),r.return=e,e=r;break a}n(e,l);break}t(e,l),l=l.sibling}i.type===T?(r=Zl(i.props.children,e.mode,o,i.key),r.return=e,e=r):(o=Xl(i.type,i.key,i.props,null,e.mode,o),o.ref=ka(e,r,i),o.return=e,e=o)}return s(e);case w:a:{for(l=i.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===i.containerInfo&&r.stateNode.implementation===i.implementation){n(e,r.sibling),r=a(r,i.children||[]),r.return=e,e=r;break a}n(e,r);break}t(e,r),r=r.sibling}r=eu(i,e.mode,o),r.return=e,e=r}return s(e);case O:return l=i._init,_(e,r,l(i._payload),o)}if(M(i))return h(e,r,i,o);if(ce(i))return g(e,r,i,o);Aa(e,i)}return typeof i==`string`&&i!==``||typeof i==`number`?(i=``+i,r!==null&&r.tag===6?(n(e,r.sibling),r=a(r,i),r.return=e,e=r):(n(e,r),r=$l(i,e.mode,o),r.return=e,e=r),s(e)):n(e,r)}return _}var Na=Ma(!0),Pa=Ma(!1),Fa=zi(null),Ia=null,La=null,Ra=null;function za(){Ra=La=Ia=null}function Ba(e){var t=Fa.current;Y(Fa),e._currentValue=t}function Va(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)===t?r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t):(e.childLanes|=t,r!==null&&(r.childLanes|=t)),e===n)break;e=e.return}}function Ha(e,t){Ia=e,Ra=La=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Ms=!0),e.firstContext=null)}function Ua(e){var t=e._currentValue;if(Ra!==e){if(e={context:e,memoizedValue:t,next:null},La===null){if(Ia===null)throw Error(i(308));La=e,Ia.dependencies={lanes:0,firstContext:e}}else La=La.next=e}return t}var Wa=null;function Ga(e){Wa===null?Wa=[e]:Wa.push(e)}function Ka(e,t,n,r){var i=t.interleaved;return i===null?(n.next=n,Ga(t)):(n.next=i.next,i.next=n),t.interleaved=n,qa(e,r)}function qa(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Ja=!1;function Ya(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Xa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Za(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Qa(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,$&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,qa(e,n)}return i=r.interleaved,i===null?(t.next=t,Ga(r)):(t.next=i.next,i.next=t),r.interleaved=t,qa(e,n)}function $a(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194240)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Bt(e,n)}}function eo(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function to(e,t,n,r){var i=e.updateQueue;Ja=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane,p=s.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});a:{var m=e,h=s;switch(f=t,p=n,h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(p,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(p,d,f):m,f==null)break a;d=k({},d,f);break a;case 2:Ja=!0}}s.callback!==null&&s.lane!==0&&(e.flags|=64,f=i.effects,f===null?i.effects=[s]:f.push(s))}else p={eventTime:p,lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;f=s,s=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(1);if(u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,t=i.shared.interleaved,t!==null){i=t;do o|=i.lane,i=i.next;while(i!==t)}else a===null&&(i.shared.lanes=0);Jc|=o,e.lanes=o,e.memoizedState=d}}function no(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=vo.transition;vo.transition={};try{e(!1),t()}finally{V=n,vo.transition=r}}function as(){return Mo().memoizedState}function os(e,t,n){var r=pl(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},cs(e))ls(t,n);else if(n=Ka(e,t,n,r),n!==null){var i=fl();ml(n,e,r,i),us(n,t,r)}}function ss(e,t,n){var r=pl(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(cs(e))ls(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Tr(s,o)){var c=t.interleaved;c===null?(i.next=i,Ga(t)):(i.next=c.next,c.next=i),t.interleaved=i;return}}catch{}n=Ka(e,t,i,r),n!==null&&(i=fl(),ml(n,e,r,i),us(n,t,r))}}function cs(e){var t=e.alternate;return e===bo||t!==null&&t===bo}function ls(e,t){wo=Co=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function us(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Bt(e,n)}}var ds={readContext:Ua,useCallback:Do,useContext:Do,useEffect:Do,useImperativeHandle:Do,useInsertionEffect:Do,useLayoutEffect:Do,useMemo:Do,useReducer:Do,useRef:Do,useState:Do,useDebugValue:Do,useDeferredValue:Do,useTransition:Do,useMutableSource:Do,useSyncExternalStore:Do,useId:Do,unstable_isNewReconciler:!1},fs={readContext:Ua,useCallback:function(e,t){return jo().memoizedState=[e,t===void 0?null:t],e},useContext:Ua,useEffect:Jo,useImperativeHandle:function(e,t,n){return n=n==null?null:n.concat([e]),Ko(4194308,4,Qo.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ko(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ko(4,2,e,t)},useMemo:function(e,t){var n=jo();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=jo();return t=n===void 0?t:n(t),r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=os.bind(null,bo,e),[r.memoizedState,e]},useRef:function(e){var t=jo();return e={current:e},t.memoizedState=e},useState:Uo,useDebugValue:es,useDeferredValue:function(e){return jo().memoizedState=e},useTransition:function(){var e=Uo(!1),t=e[0];return e=is.bind(null,e[1]),jo().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=bo,a=jo();if(Z){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Vc===null)throw Error(i(349));yo&30||Ro(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,Jo(Bo.bind(null,r,o,e),[e]),r.flags|=2048,Wo(9,zo.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=jo(),t=Vc.identifierPrefix;if(Z){var n=da,r=ua;n=(r&~(1<<32-Tt(r)-1)).toString(32)+n,t=`:`+t+`R`+n,n=To++,0<\/script>`,e=e.removeChild(e.firstChild)):typeof r.is==`string`?e=c.createElement(n,{is:r.is}):(e=c.createElement(n),n===`select`&&(c=e,r.multiple?c.multiple=!0:r.size&&(c.size=r.size))):e=c.createElementNS(e,n),e[Di]=t,e[Oi]=r,nc(e,t,!1,!1),t.stateNode=e;a:{switch(c=Ue(n,r),n){case`dialog`:J(`cancel`,e),J(`close`,e),a=r;break;case`iframe`:case`object`:case`embed`:J(`load`,e),a=r;break;case`video`:case`audio`:for(a=0;ael&&(t.flags|=128,r=!0,ac(s,!1),t.lanes=4194304)}}else{if(!r){if(e=mo(c),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),ac(s,!0),s.tail===null&&s.tailMode===`hidden`&&!c.alternate&&!Z)return oc(t),null}else 2*B()-s.renderingStartTime>el&&n!==1073741824&&(t.flags|=128,r=!0,ac(s,!1),t.lanes=4194304)}s.isBackwards?(c.sibling=t.child,t.child=c):(n=s.last,n===null?t.child=c:n.sibling=c,s.last=c)}return s.tail===null?(oc(t),null):(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=B(),t.sibling=null,n=po.current,X(po,r?n&1|2:n&1),t);case 22:case 23:return wl(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Wc&1073741824&&(oc(t),t.subtreeFlags&6&&(t.flags|=8192)):oc(t),null;case 24:return null;case 25:return null}throw Error(i(156,t.tag))}function cc(e,t){switch(ha(t),t.tag){case 1:return Gi(t.type)&&Ki(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return lo(),Y(Hi),Y(Vi),go(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return fo(t),null;case 13:if(Y(po),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ea()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Y(po),null;case 4:return lo(),null;case 10:return Ba(t.type._context),null;case 22:case 23:return wl(),null;case 24:return null;default:return null}}var lc=!1,uc=!1,dc=typeof WeakSet==`function`?WeakSet:Set,Q=null;function fc(e,t){var n=e.ref;if(n!==null){if(typeof n==`function`)try{n(null)}catch(n){Rl(e,t,n)}else n.current=null}}function pc(e,t,n){try{n()}catch(n){Rl(e,t,n)}}var mc=!1;function hc(e,t){if(hi=pn,e=Ar(),jr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(gi={focusedElem:e,selectionRange:n},pn=!1,Q=t;Q!==null;)if(t=Q,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,Q=e;else for(;Q!==null;){t=Q;try{var h=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var g=h.memoizedProps,_=h.memoizedState,v=t.stateNode;v.__reactInternalSnapshotBeforeUpdate=v.getSnapshotBeforeUpdate(t.elementType===t.type?g:hs(t.type,g),_)}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent=``:y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(i(163))}}catch(e){Rl(t,t.return,e)}if(e=t.sibling,e!==null){e.return=t.return,Q=e;break}Q=t.return}return h=mc,mc=!1,h}function gc(e,t,n){var r=t.updateQueue;if(r=r===null?null:r.lastEffect,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var a=i.destroy;i.destroy=void 0,a!==void 0&&pc(t,n,a)}i=i.next}while(i!==r)}}function _c(e,t){if(t=t.updateQueue,t=t===null?null:t.lastEffect,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function vc(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t==`function`?t(e):t.current=e}}function yc(e){var t=e.alternate;t!==null&&(e.alternate=null,yc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Di],delete t[Oi],delete t[Ai],delete t[ji],delete t[Mi])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function bc(e){return e.tag===5||e.tag===3||e.tag===4}function xc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||bc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Sc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mi));else if(r!==4&&(e=e.child,e!==null))for(Sc(e,t,n),e=e.sibling;e!==null;)Sc(e,t,n),e=e.sibling}function Cc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Cc(e,t,n),e=e.sibling;e!==null;)Cc(e,t,n),e=e.sibling}var wc=null,Tc=!1;function Ec(e,t,n){for(n=n.child;n!==null;)Dc(e,t,n),n=n.sibling}function Dc(e,t,n){if(Ct&&typeof Ct.onCommitFiberUnmount==`function`)try{Ct.onCommitFiberUnmount(St,n)}catch{}switch(n.tag){case 5:uc||fc(n,t);case 6:var r=wc,i=Tc;wc=null,Ec(e,t,n),wc=r,Tc=i,wc!==null&&(Tc?(e=wc,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):wc.removeChild(n.stateNode));break;case 18:wc!==null&&(Tc?(e=wc,n=n.stateNode,e.nodeType===8?Ci(e.parentNode,n):e.nodeType===1&&Ci(e,n),dn(e)):Ci(wc,n.stateNode));break;case 4:r=wc,i=Tc,wc=n.stateNode.containerInfo,Tc=!0,Ec(e,t,n),wc=r,Tc=i;break;case 0:case 11:case 14:case 15:if(!uc&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var a=i,o=a.destroy;a=a.tag,o!==void 0&&(a&2||a&4)&&pc(n,t,o),i=i.next}while(i!==r)}Ec(e,t,n);break;case 1:if(!uc&&(fc(n,t),r=n.stateNode,typeof r.componentWillUnmount==`function`))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(e){Rl(n,t,e)}Ec(e,t,n);break;case 21:Ec(e,t,n);break;case 22:n.mode&1?(uc=(r=uc)||n.memoizedState!==null,Ec(e,t,n),uc=r):Ec(e,t,n);break;default:Ec(e,t,n)}}function Oc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new dc),t.forEach(function(t){var r=Hl.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))})}}function kc(e,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=s),r&=~o}if(r=a,r=B()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Lc(r/1960))-r,10e?16:e,ol===null)var r=!1;else{if(e=ol,ol=null,sl=0,$&6)throw Error(i(331));var a=$;for($|=4,Q=e.current;Q!==null;){var o=Q,s=o.child;if(Q.flags&16){var c=o.deletions;if(c!==null){for(var l=0;lB()-$c?Tl(e,0):Xc|=n),hl(e,t)}function Bl(e,t){t===0&&(e.mode&1?(t=At,At<<=1,!(At&130023424)&&(At=4194304)):t=1);var n=fl();e=qa(e,t),e!==null&&(Rt(e,t,n),hl(e,n))}function Vl(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bl(e,n)}function Hl(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(i(314))}r!==null&&r.delete(t),Bl(e,n)}var Ul=function(e,t,n){if(e!==null){if(e.memoizedProps!==t.pendingProps||Hi.current)Ms=!0;else{if((e.lanes&n)===0&&!(t.flags&128))return Ms=!1,tc(e,t,n);Ms=!!(e.flags&131072)}}else Ms=!1,Z&&t.flags&1048576&&pa(t,oa,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;$s(e,t),e=t.pendingProps;var a=Wi(t,Vi.current);Ha(t,n),a=ko(null,t,r,e,a,n);var o=Ao();return t.flags|=1,typeof a==`object`&&a&&typeof a.render==`function`&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Gi(r)?(o=!0,Yi(t)):o=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Ya(t),a.updater=_s,t.stateNode=a,a._reactInternals=t,xs(t,r,e,n),t=Vs(null,t,r,!0,o,n)):(t.tag=0,Z&&o&&ma(t),Ns(null,t,a,n),t=t.child),t;case 16:r=t.elementType;a:{switch($s(e,t),e=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Jl(r),e=hs(r,e),a){case 0:t=zs(null,t,r,e,n);break a;case 1:t=Bs(null,t,r,e,n);break a;case 11:t=Ps(null,t,r,e,n);break a;case 14:t=Fs(null,t,r,hs(r.type,e),n);break a}throw Error(i(306,r,``))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),zs(e,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),Bs(e,t,r,a,n);case 3:a:{if(Hs(t),e===null)throw Error(i(387));r=t.pendingProps,o=t.memoizedState,a=o.element,Xa(e,t),to(t,r,null,n);var s=t.memoizedState;if(r=s.element,o.isDehydrated){if(o={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){a=Ss(Error(i(423)),t),t=Us(e,t,r,n,a);break a}if(r!==a){a=Ss(Error(i(424)),t),t=Us(e,t,r,n,a);break a}for(_a=wi(t.stateNode.containerInfo.firstChild),ga=t,Z=!0,va=null,n=Pa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(Ea(),r===a){t=ec(e,t,n);break a}Ns(e,t,r,n)}t=t.child}return t;case 5:return uo(t),e===null&&Sa(t),r=t.type,a=t.pendingProps,o=e===null?null:e.memoizedProps,s=a.children,_i(r,a)?s=null:o!==null&&_i(r,o)&&(t.flags|=32),Rs(e,t),Ns(e,t,s,n),t.child;case 6:return e===null&&Sa(t),null;case 13:return Ks(e,t,n);case 4:return co(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Na(t,null,r,n):Ns(e,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),Ps(e,t,r,a,n);case 7:return Ns(e,t,t.pendingProps,n),t.child;case 8:return Ns(e,t,t.pendingProps.children,n),t.child;case 12:return Ns(e,t,t.pendingProps.children,n),t.child;case 10:a:{if(r=t.type._context,a=t.pendingProps,o=t.memoizedProps,s=a.value,X(Fa,r._currentValue),r._currentValue=s,o!==null){if(Tr(o.value,s)){if(o.children===a.children&&!Hi.current){t=ec(e,t,n);break a}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var c=o.dependencies;if(c!==null){s=o.child;for(var l=c.firstContext;l!==null;){if(l.context===r){if(o.tag===1){l=Za(-1,n&-n),l.tag=2;var u=o.updateQueue;if(u!==null){u=u.shared;var d=u.pending;d===null?l.next=l:(l.next=d.next,d.next=l),u.pending=l}}o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Va(o.return,n,t),c.lanes|=n;break}l=l.next}}else if(o.tag===10)s=o.type===t.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(i(341));s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),Va(s,n,t),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===t){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}}Ns(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Ha(t,n),a=Ua(a),r=r(a),t.flags|=1,Ns(e,t,r,n),t.child;case 14:return r=t.type,a=hs(r,t.pendingProps),a=hs(r.type,a),Fs(e,t,r,a,n);case 15:return Is(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),$s(e,t),t.tag=1,Gi(r)?(e=!0,Yi(t)):e=!1,Ha(t,n),ys(t,r,a),xs(t,r,a,n),Vs(null,t,r,!0,e,n);case 19:return Qs(e,t,n);case 22:return Ls(e,t,n)}throw Error(i(156,t.tag))};function Wl(e,t){return ft(e,t)}function Gl(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Kl(e,t,n,r){return new Gl(e,t,n,r)}function ql(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Jl(e){if(typeof e==`function`)return+!!ql(e);if(e!=null){if(e=e.$$typeof,e===re)return 11;if(e===D)return 14}return 2}function Yl(e,t){var n=e.alternate;return n===null?(n=Kl(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Xl(e,t,n,r,a,o){var s=2;if(r=e,typeof e==`function`)ql(e)&&(s=1);else if(typeof e==`string`)s=5;else a:switch(e){case T:return Zl(n.children,a,o,t);case ee:s=8,a|=8;break;case te:return e=Kl(12,n,t,a|2),e.elementType=te,e.lanes=o,e;case ie:return e=Kl(13,n,t,a),e.elementType=ie,e.lanes=o,e;case ae:return e=Kl(19,n,t,a),e.elementType=ae,e.lanes=o,e;case oe:return Ql(n,a,o,t);default:if(typeof e==`object`&&e)switch(e.$$typeof){case E:s=10;break a;case ne:s=9;break a;case re:s=11;break a;case D:s=14;break a;case O:s=16,r=null;break a}throw Error(i(130,e==null?e:typeof e,``))}return t=Kl(s,n,t,a),t.elementType=e,t.type=r,t.lanes=o,t}function Zl(e,t,n,r){return e=Kl(7,e,r,t),e.lanes=n,e}function Ql(e,t,n,r){return e=Kl(22,e,r,t),e.elementType=oe,e.lanes=n,e.stateNode={isHidden:!1},e}function $l(e,t,n){return e=Kl(6,e,null,t),e.lanes=n,e}function eu(e,t,n){return t=Kl(4,e.children===null?[]:e.children,e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tu(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Lt(0),this.expirationTimes=Lt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Lt(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function nu(e,t,n,r,i,a,o,s,c){return e=new tu(e,t,n,s,c),t===1?(t=1,!0===a&&(t|=8)):t=0,a=Kl(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ya(a),e}function ru(e,t,n){var r=3{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=be()})),Se=t((e=>{var t=xe();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot})),Ce=class extends he{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new re({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=we(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=we(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=we(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=we(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){ie.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>D(t,e))}findAll(e={}){return this.getAll().filter(t=>D(e,t))}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return ie.batch(()=>Promise.all(e.map(e=>e.continue().catch(k))))}};function we(e){return e.options.scope?.id}var Te=class extends he{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??ae(r,t),a=this.get(i);return a||(a=new A({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){ie.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ue(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ue(e,t)):t}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ie.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ie.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ee=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Te,this.#t=e.mutationCache||new Ce,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=me.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(O(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=ce(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return ie.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;ie.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return ie.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=ie.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(k).catch(k)}invalidateQueries(e,t={}){return ie.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=ie.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(k)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(k)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(O(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(k).catch(k)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(k).catch(k)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return fe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(pe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{oe(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(pe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{oe(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=ae(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===ne&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},M=e(r(),1),De=e(Se(),1),Oe=class extends Error{status;method;path;constructor(e,t,n,r){super(e),this.name=`ApiError`,this.status=t,this.method=n,this.path=r}};function ke(e){let t=e.replace(/\s+/g,` `).trim();if(!t)return``;try{let t=JSON.parse(e);for(let e of[`detail`,`error`,`message`]){let n=t[e];if(typeof n==`string`&&n.trim())return n.trim();if(Array.isArray(n)){let e=n.map(e=>e&&typeof e==`object`?String(e.msg??``):``).filter(Boolean);if(e.length)return e.join(`; `)}}}catch{}return t.startsWith(`typeof e==`string`):[],o=Ie(r?.major),s=Ie(r?.minor);if(!n||!r||!i)return{compatible:!1,reason:`malformed /api/meta response`};if(typeof i.source_root!=`string`||Ie(i.pid)===null||typeof i.package_version!=`string`||typeof i.release_id!=`string`)return{compatible:!1,reason:`malformed /api/meta runtime identity`};if(n.service!==`argus-skill-webapi`)return{compatible:!1,reason:`unexpected service ${String(n.service||`unknown`)}`};let c=e;if(r.name!==Ne.name||o!==Ne.major)return{compatible:!1,reason:`protocol ${String(r.name||`unknown`)}/${String(o)} is incompatible with client ${Ne.name}/${Ne.major}`,meta:c};if(s===null||s!a.includes(e));if(l.length>0)return{compatible:!1,reason:`missing capabilities: ${l.join(`, `)}`,meta:c};if(i.source_root_matches_config===!1)return{compatible:!1,reason:`backend loaded source ${String(i.source_root)} but ARGUS_SKILL_SOURCE_ROOT points to ${String(i.configured_source_root)}`,meta:c};if(i.release_id!==t.releaseId)return{compatible:!1,reason:`backend release ${String(i.release_id)} does not match client release ${t.releaseId}`,meta:c};if(t.sourceDigest){if(typeof i.runtime_source_digest!=`string`||!i.runtime_source_digest)return{compatible:!1,reason:`backend process does not report the source digest required by this local checkout`,meta:c};if(i.runtime_source_digest!==t.sourceDigest)return{compatible:!1,reason:`backend process source ${String(i.runtime_source_digest).slice(0,16)} does not match local source ${t.sourceDigest.slice(0,16)}`,meta:c}}return{compatible:!0,reason:``,warning:i.release_matches_source===!1?`backend source differs from its prebuilt release artifacts; pull a complete published revision and reinstall`:void 0,meta:c}}function Re(e,t){let n=Le(e);if(!n.compatible||!n.meta)throw Error(`incompatible Argus API: ${n.reason}`);return n.warning&&t?.(n.warning),n.meta}function ze(e){let t=Fe(e),n=Fe(t?.daemon);if(!t||t.schema_version!==7)throw Error(`incompatible snapshot schema: expected 7, got ${String(t?.schema_version??`missing`)}`);if(!n)throw Error(`invalid snapshot: daemon section is missing`);let r=[`global_daily_cap_usd`,`read_status`,`read_error`,`protocol_compatible`,`protocol_error`].filter(e=>!Object.hasOwn(n,e));if(r.length>0)throw Error(`invalid snapshot: daemon fields missing: ${r.join(`, `)}`);let i=[`spend_usd`,`spend_status`,`usage_summary`,`request_usage`,`cost_control`,`daemon_commands`,`observability`,`mission_view`,`partial`,`diagnostics`].filter(e=>!Object.hasOwn(t,e));if(i.length>0)throw Error(`invalid snapshot: fields missing: ${i.join(`, `)}`);if(!Array.isArray(t.diagnostics))throw Error(`invalid snapshot: diagnostics must be an array`);return e}var Be=`argus_web_token`,Ve=null;function He(){let e;try{e=new URLSearchParams(window.location.search)}catch{return}let t=e.get(`token`);if(t){Ve=t;try{localStorage.setItem(Be,t)}catch{}try{e.delete(`token`);let t=e.toString();window.history.replaceState(null,``,`${window.location.pathname}${t?`?${t}`:``}${window.location.hash}`)}catch{}}}var Ue=()=>{if(Ve)return Ve;try{return new URLSearchParams(window.location.search).get(`token`)||localStorage.getItem(Be)}catch{return null}};function We(){let e=Ue();return e?{Authorization:`Bearer ${e}`}:{}}function Ge(){return Ue()??``}var Ke=8e3,qe=12e3,N=class extends Error{constructor(){super(`This browser is not paired with Argus. Reopen it from Argus Desktop or use a fresh pairing link.`),this.name=`PairingRequiredError`}},Je=class extends Error{method;path;constructor(e,t,n=`could not reach the local Argus service`){super(`${e.toUpperCase()} ${t} ${n}. Make sure Argus Desktop is running, then retry.`),this.name=`LocalArgusUnavailableError`,this.method=e.toUpperCase(),this.path=t}};function Ye(e){return e instanceof N||!!(e&&typeof e==`object`&&Number(e.status)===401)}function Xe(e){return Ye(e)||e instanceof Je}async function P(e,t){try{return await fetch(e,t)}catch(n){throw t.signal?.aborted?n:new Je(String(t.method??`GET`),e)}}async function Ze(e,t,n,r){let i=new AbortController,a=t.signal??void 0,o=!1,s=()=>{};if(a){let e=()=>i.abort(a.reason);a.aborted?e():(a.addEventListener(`abort`,e,{once:!0}),s=()=>a.removeEventListener(`abort`,e))}let c,l=(async()=>await r(await P(e,{...t,signal:i.signal})))(),u=new Promise((e,t)=>{c=setTimeout(()=>{o=!0;let e=Error(`request timed out after ${n}ms`);i.abort(e),t(e)},n)});try{return await Promise.race([l,u])}catch(r){if(o){let r=Math.round(n/1e3);throw new Je(String(t.method??`GET`),e,`timed out after ${r}s because the local Argus service did not respond`)}throw r}finally{c&&clearTimeout(c),s()}}async function Qe(e,t,n){return Ze(e,{headers:We(),signal:t},n??qe,async t=>(await je(t,`GET`,e),await t.json()))}async function F(e,t,n){let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,...We()},body:t===void 0?void 0:JSON.stringify(t),signal:n});return await je(r,`POST`,e),await r.json()}async function $e(e,t,n){let r=await fetch(e,{method:`POST`,headers:We(),body:t,signal:n});return await je(r,`POST`,e),await r.json()}function et(e){let t=e&&typeof e==`object`?e:{},n=String(t.command_status??``);if(Number(t.rc??0)!==0||n===`failed`||n===`rejected`)throw Error(String(t.error||`daemon command ${n||`failed`}`));return e}async function tt(e,t,n){let r=await fetch(t,{method:e,headers:{"Content-Type":`application/json`,...We()},body:n===void 0?void 0:JSON.stringify(n)});return await je(r,e,t),await r.json()}async function nt(e,t){let n=await fetch(e,{headers:We(),signal:t});return await je(n,`GET`,e),n.blob()}var I=(e,t=``)=>`/api/projects/${encodeURIComponent(e)}${t}`,L=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`,rt;function it(e){return!!(e&&typeof e==`object`&&`aborted`in e&&typeof e.aborted==`boolean`)}function at(e,t){return t?.length?{text:e,attachments:t}:{text:e}}function ot(){if(!rt){let e=(async()=>{let e=`/api/meta`,t=await Ze(e,{headers:We()},Ke,async t=>{if(t.status===404)throw Error(`incompatible Argus API: service does not expose /api/meta`);return await je(t,`GET`,e),Re(await t.json(),e=>console.warn(`Argus API compatibility warning: ${e}`))});if(t.authentication?.required&&!t.authentication.authenticated)throw new N;return t})();rt=e,e.catch(t=>{rt===e&&!(t instanceof N)&&(rt=void 0)})}return rt}function st(e){let t=[],n;for(;(n=e.indexOf(` +`+e.stack}return{value:e,source:t,stack:i,digest:null}}function Cs(e,t,n){return{value:e,source:null,stack:n??null,digest:t??null}}function ws(e,t){try{console.error(t.value)}catch(e){setTimeout(function(){throw e})}}var Ts=typeof WeakMap==`function`?WeakMap:Map;function Es(e,t,n){n=Za(-1,n),n.tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){nl||(nl=!0,rl=r),ws(e,t)},n}function Ds(e,t,n){n=Za(-1,n),n.tag=3;var r=e.type.getDerivedStateFromError;if(typeof r==`function`){var i=t.value;n.payload=function(){return r(i)},n.callback=function(){ws(e,t)}}var a=e.stateNode;return a!==null&&typeof a.componentDidCatch==`function`&&(n.callback=function(){ws(e,t),typeof r!=`function`&&(il===null?il=new Set([this]):il.add(this));var n=t.stack;this.componentDidCatch(t.value,{componentStack:n===null?``:n})}),n}function Os(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Ts;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(i.add(n),e=zl.bind(null,e,t,n),t.then(e,e))}function ks(e){do{var t;if((t=e.tag===13)&&(t=e.memoizedState,t=t===null||t.dehydrated!==null),t)return e;e=e.return}while(e!==null);return null}function As(e,t,n,r,i){return e.mode&1?(e.flags|=65536,e.lanes=i,e):(e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(t=Za(-1,1),t.tag=2,Qa(n,t,1))),n.lanes|=1),e)}var js=S.ReactCurrentOwner,Ms=!1;function Ns(e,t,n,r){t.child=e===null?Pa(t,null,n,r):Na(t,e.child,n,r)}function Ps(e,t,n,r,i){n=n.render;var a=t.ref;return Ha(t,i),r=ko(e,t,n,r,a,i),n=Ao(),e!==null&&!Ms?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,ec(e,t,i)):(Z&&n&&ma(t),t.flags|=1,Ns(e,t,r,i),t.child)}function Fs(e,t,n,r,i){if(e===null){var a=n.type;return typeof a==`function`&&!ql(a)&&a.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(t.tag=15,t.type=a,Is(e,t,a,r,i)):(e=Xl(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(a=e.child,(e.lanes&i)===0){var o=a.memoizedProps;if(n=n.compare,n=n===null?Er:n,n(o,r)&&e.ref===t.ref)return ec(e,t,i)}return t.flags|=1,e=Yl(a,r),e.ref=t.ref,e.return=t,t.child=e}function Is(e,t,n,r,i){if(e!==null){var a=e.memoizedProps;if(Er(a,r)&&e.ref===t.ref){if(Ms=!1,t.pendingProps=r=a,(e.lanes&i)!==0)e.flags&131072&&(Ms=!0);else return t.lanes=e.lanes,ec(e,t,i)}}return zs(e,t,n,r,i)}function Ls(e,t,n){var r=t.pendingProps,i=r.children,a=e===null?null:e.memoizedState;if(r.mode===`hidden`){if(!(t.mode&1))t.memoizedState={baseLanes:0,cachePool:null,transitions:null},X(Gc,Wc),Wc|=n;else{if(!(n&1073741824))return e=a===null?n:a.baseLanes|n,t.lanes=t.childLanes=1073741824,t.memoizedState={baseLanes:e,cachePool:null,transitions:null},t.updateQueue=null,X(Gc,Wc),Wc|=e,null;t.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=a===null?n:a.baseLanes,X(Gc,Wc),Wc|=r}}else a===null?r=n:(r=a.baseLanes|n,t.memoizedState=null),X(Gc,Wc),Wc|=r;return Ns(e,t,i,n),t.child}function Rs(e,t){var n=t.ref;(e===null&&n!==null||e!==null&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function zs(e,t,n,r,i){var a=Gi(n)?Ui:Vi.current;return a=Wi(t,a),Ha(t,i),n=ko(e,t,n,r,a,i),r=Ao(),e!==null&&!Ms?(t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i,ec(e,t,i)):(Z&&r&&ma(t),t.flags|=1,Ns(e,t,n,i),t.child)}function Bs(e,t,n,r,i){if(Gi(n)){var a=!0;Yi(t)}else a=!1;if(Ha(t,i),t.stateNode===null)$s(e,t),ys(t,n,r),xs(t,n,r,i),r=!0;else if(e===null){var o=t.stateNode,s=t.memoizedProps;o.props=s;var c=o.context,l=n.contextType;typeof l==`object`&&l?l=Ua(l):(l=Gi(n)?Ui:Vi.current,l=Wi(t,l));var u=n.getDerivedStateFromProps,d=typeof u==`function`||typeof o.getSnapshotBeforeUpdate==`function`;d||typeof o.UNSAFE_componentWillReceiveProps!=`function`&&typeof o.componentWillReceiveProps!=`function`||(s!==r||c!==l)&&bs(t,o,r,l),Ja=!1;var f=t.memoizedState;o.state=f,to(t,r,o,i),c=t.memoizedState,s!==r||f!==c||Hi.current||Ja?(typeof u==`function`&&(gs(t,n,u,r),c=t.memoizedState),(s=Ja||vs(t,n,s,r,f,c,l))?(d||typeof o.UNSAFE_componentWillMount!=`function`&&typeof o.componentWillMount!=`function`||(typeof o.componentWillMount==`function`&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount==`function`&&o.UNSAFE_componentWillMount()),typeof o.componentDidMount==`function`&&(t.flags|=4194308)):(typeof o.componentDidMount==`function`&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=c),o.props=r,o.state=c,o.context=l,r=s):(typeof o.componentDidMount==`function`&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,Xa(e,t),s=t.memoizedProps,l=t.type===t.elementType?s:hs(t.type,s),o.props=l,d=t.pendingProps,f=o.context,c=n.contextType,typeof c==`object`&&c?c=Ua(c):(c=Gi(n)?Ui:Vi.current,c=Wi(t,c));var p=n.getDerivedStateFromProps;(u=typeof p==`function`||typeof o.getSnapshotBeforeUpdate==`function`)||typeof o.UNSAFE_componentWillReceiveProps!=`function`&&typeof o.componentWillReceiveProps!=`function`||(s!==d||f!==c)&&bs(t,o,r,c),Ja=!1,f=t.memoizedState,o.state=f,to(t,r,o,i);var m=t.memoizedState;s!==d||f!==m||Hi.current||Ja?(typeof p==`function`&&(gs(t,n,p,r),m=t.memoizedState),(l=Ja||vs(t,n,l,r,f,m,c)||!1)?(u||typeof o.UNSAFE_componentWillUpdate!=`function`&&typeof o.componentWillUpdate!=`function`||(typeof o.componentWillUpdate==`function`&&o.componentWillUpdate(r,m,c),typeof o.UNSAFE_componentWillUpdate==`function`&&o.UNSAFE_componentWillUpdate(r,m,c)),typeof o.componentDidUpdate==`function`&&(t.flags|=4),typeof o.getSnapshotBeforeUpdate==`function`&&(t.flags|=1024)):(typeof o.componentDidUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=m),o.props=r,o.state=m,o.context=c,r=l):(typeof o.componentDidUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof o.getSnapshotBeforeUpdate!=`function`||s===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),r=!1)}return Vs(e,t,n,r,a,i)}function Vs(e,t,n,r,i,a){Rs(e,t);var o=!!(t.flags&128);if(!r&&!o)return i&&Xi(t,n,!1),ec(e,t,a);r=t.stateNode,js.current=t;var s=o&&typeof n.getDerivedStateFromError!=`function`?null:r.render();return t.flags|=1,e!==null&&o?(t.child=Na(t,e.child,null,a),t.child=Na(t,null,s,a)):Ns(e,t,s,a),t.memoizedState=r.state,i&&Xi(t,n,!0),t.child}function Hs(e){var t=e.stateNode;t.pendingContext?qi(e,t.pendingContext,t.pendingContext!==t.context):t.context&&qi(e,t.context,!1),co(e,t.containerInfo)}function Us(e,t,n,r,i){return Ea(),Da(i),t.flags|=256,Ns(e,t,n,r),t.child}var Ws={dehydrated:null,treeContext:null,retryLane:0};function Gs(e){return{baseLanes:e,cachePool:null,transitions:null}}function Ks(e,t,n){var r=t.pendingProps,i=po.current,a=!1,o=!!(t.flags&128),s;if((s=o)||(s=e!==null&&e.memoizedState===null?!1:!!(i&2)),s?(a=!0,t.flags&=-129):(e===null||e.memoizedState!==null)&&(i|=1),X(po,i&1),e===null)return Sa(t),e=t.memoizedState,e!==null&&(e=e.dehydrated,e!==null)?(t.lanes=t.mode&1?e.data===`$!`?8:1073741824:1,null):(o=r.children,e=r.fallback,a?(r=t.mode,a=t.child,o={mode:`hidden`,children:o},!(r&1)&&a!==null?(a.childLanes=0,a.pendingProps=o):a=Ql(o,r,0,null),e=Zl(e,r,n,null),a.return=t,e.return=t,a.sibling=e,t.child=a,t.child.memoizedState=Gs(n),t.memoizedState=Ws,e):qs(t,o));if(i=e.memoizedState,i!==null&&(s=i.dehydrated,s!==null))return Ys(e,t,o,r,s,i,n);if(a){a=r.fallback,o=t.mode,i=e.child,s=i.sibling;var c={mode:`hidden`,children:r.children};return!(o&1)&&t.child!==i?(r=t.child,r.childLanes=0,r.pendingProps=c,t.deletions=null):(r=Yl(i,c),r.subtreeFlags=i.subtreeFlags&14680064),s===null?(a=Zl(a,o,n,null),a.flags|=2):a=Yl(s,a),a.return=t,r.return=t,r.sibling=a,t.child=r,r=a,a=t.child,o=e.child.memoizedState,o=o===null?Gs(n):{baseLanes:o.baseLanes|n,cachePool:null,transitions:o.transitions},a.memoizedState=o,a.childLanes=e.childLanes&~n,t.memoizedState=Ws,r}return a=e.child,e=a.sibling,r=Yl(a,{mode:`visible`,children:r.children}),!(t.mode&1)&&(r.lanes=n),r.return=t,r.sibling=null,e!==null&&(n=t.deletions,n===null?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=r,t.memoizedState=null,r}function qs(e,t){return t=Ql({mode:`visible`,children:t},e.mode,0,null),t.return=e,e.child=t}function Js(e,t,n,r){return r!==null&&Da(r),Na(t,e.child,null,n),e=qs(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Ys(e,t,n,r,a,o,s){if(n)return t.flags&256?(t.flags&=-257,r=Cs(Error(i(422))),Js(e,t,s,r)):t.memoizedState===null?(o=r.fallback,a=t.mode,r=Ql({mode:`visible`,children:r.children},a,0,null),o=Zl(o,a,s,null),o.flags|=2,r.return=t,o.return=t,r.sibling=o,t.child=r,t.mode&1&&Na(t,e.child,null,s),t.child.memoizedState=Gs(s),t.memoizedState=Ws,o):(t.child=e.child,t.flags|=128,null);if(!(t.mode&1))return Js(e,t,s,null);if(a.data===`$!`){if(r=a.nextSibling&&a.nextSibling.dataset,r)var c=r.dgst;return r=c,o=Error(i(419)),r=Cs(o,r,void 0),Js(e,t,s,r)}if(c=(s&e.childLanes)!==0,Ms||c){if(r=Vc,r!==null){switch(s&-s){case 4:a=2;break;case 16:a=8;break;case 64: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:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:a=32;break;case 536870912:a=268435456;break;default:a=0}a=(a&(r.suspendedLanes|s))===0?a:0,a!==0&&a!==o.retryLane&&(o.retryLane=a,qa(e,a),ml(r,e,a,-1))}return Ol(),r=Cs(Error(i(421))),Js(e,t,s,r)}return a.data===`$?`?(t.flags|=128,t.child=e.child,t=Vl.bind(null,e),a._reactRetry=t,null):(e=o.treeContext,_a=wi(a.nextSibling),ga=t,Z=!0,va=null,e!==null&&(sa[ca++]=ua,sa[ca++]=da,sa[ca++]=la,ua=e.id,da=e.overflow,la=t),t=qs(t,r.children),t.flags|=4096,t)}function Xs(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),Va(e.return,t,n)}function Zs(e,t,n,r,i){var a=e.memoizedState;a===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=n,a.tailMode=i)}function Qs(e,t,n){var r=t.pendingProps,i=r.revealOrder,a=r.tail;if(Ns(e,t,r.children,n),r=po.current,r&2)r=r&1|2,t.flags|=128;else{if(e!==null&&e.flags&128)a:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Xs(e,n,t);else if(e.tag===19)Xs(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break a;for(;e.sibling===null;){if(e.return===null||e.return===t)break a;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(X(po,r),!(t.mode&1))t.memoizedState=null;else switch(i){case`forwards`:for(n=t.child,i=null;n!==null;)e=n.alternate,e!==null&&mo(e)===null&&(i=n),n=n.sibling;n=i,n===null?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),Zs(t,!1,i,n,a);break;case`backwards`:for(n=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&mo(e)===null){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}Zs(t,!0,n,null,a);break;case`together`:Zs(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function $s(e,t){!(t.mode&1)&&e!==null&&(e.alternate=null,t.alternate=null,t.flags|=2)}function ec(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Jc|=t.lanes,(n&t.childLanes)===0)return null;if(e!==null&&t.child!==e.child)throw Error(i(153));if(t.child!==null){for(e=t.child,n=Yl(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=Yl(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function tc(e,t,n){switch(t.tag){case 3:Hs(t),Ea();break;case 5:uo(t);break;case 1:Gi(t.type)&&Yi(t);break;case 4:co(t,t.stateNode.containerInfo);break;case 10:var r=t.type._context,i=t.memoizedProps.value;X(Fa,r._currentValue),r._currentValue=i;break;case 13:if(r=t.memoizedState,r!==null)return r.dehydrated===null?(n&t.child.childLanes)===0?(X(po,po.current&1),e=ec(e,t,n),e===null?null:e.sibling):Ks(e,t,n):(X(po,po.current&1),t.flags|=128,null);X(po,po.current&1);break;case 19:if(r=(n&t.childLanes)!==0,e.flags&128){if(r)return Qs(e,t,n);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),X(po,po.current),r)break;return null;case 22:case 23:return t.lanes=0,Ls(e,t,n)}return ec(e,t,n)}var nc=function(e,t){for(var n=t.child;n!==null;){if(n.tag===5||n.tag===6)e.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},rc=function(e,t,n,r){var i=e.memoizedProps;if(i!==r){e=t.stateNode,so(io.current);var a=null;switch(n){case`input`:i=xe(e,i),r=xe(e,r),a=[];break;case`select`:i=k({},i,{value:void 0}),r=k({},r,{value:void 0}),a=[];break;case`textarea`:i=Oe(e,i),r=Oe(e,r),a=[];break;default:typeof i.onClick!=`function`&&typeof r.onClick==`function`&&(e.onclick=mi)}He(n,r);var s;for(u in n=null,i)if(!r.hasOwnProperty(u)&&i.hasOwnProperty(u)&&i[u]!=null){if(u===`style`){var c=i[u];for(s in c)c.hasOwnProperty(s)&&(n||={},n[s]=``)}else u!==`dangerouslySetInnerHTML`&&u!==`children`&&u!==`suppressContentEditableWarning`&&u!==`suppressHydrationWarning`&&u!==`autoFocus`&&(o.hasOwnProperty(u)?a||=[]:(a||=[]).push(u,null))}for(u in r){var l=r[u];if(c=i?.[u],r.hasOwnProperty(u)&&l!==c&&(l!=null||c!=null)){if(u===`style`){if(c){for(s in c)!c.hasOwnProperty(s)||l&&l.hasOwnProperty(s)||(n||={},n[s]=``);for(s in l)l.hasOwnProperty(s)&&c[s]!==l[s]&&(n||={},n[s]=l[s])}else n||(a||=[],a.push(u,n)),n=l}else u===`dangerouslySetInnerHTML`?(l=l?l.__html:void 0,c=c?c.__html:void 0,l!=null&&c!==l&&(a||=[]).push(u,l)):u===`children`?typeof l!=`string`&&typeof l!=`number`||(a||=[]).push(u,``+l):u!==`suppressContentEditableWarning`&&u!==`suppressHydrationWarning`&&(o.hasOwnProperty(u)?(l!=null&&u===`onScroll`&&J(`scroll`,e),a||c===l||(a=[])):(a||=[]).push(u,l))}}n&&(a||=[]).push(`style`,n);var u=a;(t.updateQueue=u)&&(t.flags|=4)}},ic=function(e,t,n,r){n!==r&&(t.flags|=4)};function ac(e,t){if(!Z)switch(e.tailMode){case`hidden`:t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case`collapsed`:n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function oc(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function sc(e,t,n){var r=t.pendingProps;switch(ha(t),t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return oc(t),null;case 1:return Gi(t.type)&&Ki(),oc(t),null;case 3:return r=t.stateNode,lo(),Y(Hi),Y(Vi),go(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(e===null||e.child===null)&&(wa(t)?t.flags|=4:e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,va!==null&&(vl(va),va=null))),oc(t),null;case 5:fo(t);var a=so(oo.current);if(n=t.type,e!==null&&t.stateNode!=null)rc(e,t,n,r,a),e.ref!==t.ref&&(t.flags|=512,t.flags|=2097152);else{if(!r){if(t.stateNode===null)throw Error(i(166));return oc(t),null}if(e=so(io.current),wa(t)){r=t.stateNode,n=t.type;var s=t.memoizedProps;switch(r[Di]=t,r[Oi]=s,e=!!(t.mode&1),n){case`dialog`:J(`cancel`,r),J(`close`,r);break;case`iframe`:case`object`:case`embed`:J(`load`,r);break;case`video`:case`audio`:for(a=0;a<\/script>`,e=e.removeChild(e.firstChild)):typeof r.is==`string`?e=c.createElement(n,{is:r.is}):(e=c.createElement(n),n===`select`&&(c=e,r.multiple?c.multiple=!0:r.size&&(c.size=r.size))):e=c.createElementNS(e,n),e[Di]=t,e[Oi]=r,nc(e,t,!1,!1),t.stateNode=e;a:{switch(c=Ue(n,r),n){case`dialog`:J(`cancel`,e),J(`close`,e),a=r;break;case`iframe`:case`object`:case`embed`:J(`load`,e),a=r;break;case`video`:case`audio`:for(a=0;ael&&(t.flags|=128,r=!0,ac(s,!1),t.lanes=4194304)}}else{if(!r){if(e=mo(c),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),ac(s,!0),s.tail===null&&s.tailMode===`hidden`&&!c.alternate&&!Z)return oc(t),null}else 2*B()-s.renderingStartTime>el&&n!==1073741824&&(t.flags|=128,r=!0,ac(s,!1),t.lanes=4194304)}s.isBackwards?(c.sibling=t.child,t.child=c):(n=s.last,n===null?t.child=c:n.sibling=c,s.last=c)}return s.tail===null?(oc(t),null):(t=s.tail,s.rendering=t,s.tail=t.sibling,s.renderingStartTime=B(),t.sibling=null,n=po.current,X(po,r?n&1|2:n&1),t);case 22:case 23:return wl(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Wc&1073741824&&(oc(t),t.subtreeFlags&6&&(t.flags|=8192)):oc(t),null;case 24:return null;case 25:return null}throw Error(i(156,t.tag))}function cc(e,t){switch(ha(t),t.tag){case 1:return Gi(t.type)&&Ki(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return lo(),Y(Hi),Y(Vi),go(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return fo(t),null;case 13:if(Y(po),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ea()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Y(po),null;case 4:return lo(),null;case 10:return Ba(t.type._context),null;case 22:case 23:return wl(),null;case 24:return null;default:return null}}var lc=!1,uc=!1,dc=typeof WeakSet==`function`?WeakSet:Set,Q=null;function fc(e,t){var n=e.ref;if(n!==null){if(typeof n==`function`)try{n(null)}catch(n){Rl(e,t,n)}else n.current=null}}function pc(e,t,n){try{n()}catch(n){Rl(e,t,n)}}var mc=!1;function hc(e,t){if(hi=pn,e=Ar(),jr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(gi={focusedElem:e,selectionRange:n},pn=!1,Q=t;Q!==null;)if(t=Q,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,Q=e;else for(;Q!==null;){t=Q;try{var h=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(h!==null){var g=h.memoizedProps,_=h.memoizedState,v=t.stateNode;v.__reactInternalSnapshotBeforeUpdate=v.getSnapshotBeforeUpdate(t.elementType===t.type?g:hs(t.type,g),_)}break;case 3:var y=t.stateNode.containerInfo;y.nodeType===1?y.textContent=``:y.nodeType===9&&y.documentElement&&y.removeChild(y.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(i(163))}}catch(e){Rl(t,t.return,e)}if(e=t.sibling,e!==null){e.return=t.return,Q=e;break}Q=t.return}return h=mc,mc=!1,h}function gc(e,t,n){var r=t.updateQueue;if(r=r===null?null:r.lastEffect,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var a=i.destroy;i.destroy=void 0,a!==void 0&&pc(t,n,a)}i=i.next}while(i!==r)}}function _c(e,t){if(t=t.updateQueue,t=t===null?null:t.lastEffect,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function vc(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t==`function`?t(e):t.current=e}}function yc(e){var t=e.alternate;t!==null&&(e.alternate=null,yc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Di],delete t[Oi],delete t[Ai],delete t[ji],delete t[Mi])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function bc(e){return e.tag===5||e.tag===3||e.tag===4}function xc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||bc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Sc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mi));else if(r!==4&&(e=e.child,e!==null))for(Sc(e,t,n),e=e.sibling;e!==null;)Sc(e,t,n),e=e.sibling}function Cc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Cc(e,t,n),e=e.sibling;e!==null;)Cc(e,t,n),e=e.sibling}var wc=null,Tc=!1;function Ec(e,t,n){for(n=n.child;n!==null;)Dc(e,t,n),n=n.sibling}function Dc(e,t,n){if(Ct&&typeof Ct.onCommitFiberUnmount==`function`)try{Ct.onCommitFiberUnmount(St,n)}catch{}switch(n.tag){case 5:uc||fc(n,t);case 6:var r=wc,i=Tc;wc=null,Ec(e,t,n),wc=r,Tc=i,wc!==null&&(Tc?(e=wc,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):wc.removeChild(n.stateNode));break;case 18:wc!==null&&(Tc?(e=wc,n=n.stateNode,e.nodeType===8?Ci(e.parentNode,n):e.nodeType===1&&Ci(e,n),dn(e)):Ci(wc,n.stateNode));break;case 4:r=wc,i=Tc,wc=n.stateNode.containerInfo,Tc=!0,Ec(e,t,n),wc=r,Tc=i;break;case 0:case 11:case 14:case 15:if(!uc&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var a=i,o=a.destroy;a=a.tag,o!==void 0&&(a&2||a&4)&&pc(n,t,o),i=i.next}while(i!==r)}Ec(e,t,n);break;case 1:if(!uc&&(fc(n,t),r=n.stateNode,typeof r.componentWillUnmount==`function`))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(e){Rl(n,t,e)}Ec(e,t,n);break;case 21:Ec(e,t,n);break;case 22:n.mode&1?(uc=(r=uc)||n.memoizedState!==null,Ec(e,t,n),uc=r):Ec(e,t,n);break;default:Ec(e,t,n)}}function Oc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new dc),t.forEach(function(t){var r=Hl.bind(null,e,t);n.has(t)||(n.add(t),t.then(r,r))})}}function kc(e,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=s),r&=~o}if(r=a,r=B()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Lc(r/1960))-r,10e?16:e,ol===null)var r=!1;else{if(e=ol,ol=null,sl=0,$&6)throw Error(i(331));var a=$;for($|=4,Q=e.current;Q!==null;){var o=Q,s=o.child;if(Q.flags&16){var c=o.deletions;if(c!==null){for(var l=0;lB()-$c?Tl(e,0):Xc|=n),hl(e,t)}function Bl(e,t){t===0&&(e.mode&1?(t=At,At<<=1,!(At&130023424)&&(At=4194304)):t=1);var n=fl();e=qa(e,t),e!==null&&(Rt(e,t,n),hl(e,n))}function Vl(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bl(e,n)}function Hl(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(i(314))}r!==null&&r.delete(t),Bl(e,n)}var Ul=function(e,t,n){if(e!==null){if(e.memoizedProps!==t.pendingProps||Hi.current)Ms=!0;else{if((e.lanes&n)===0&&!(t.flags&128))return Ms=!1,tc(e,t,n);Ms=!!(e.flags&131072)}}else Ms=!1,Z&&t.flags&1048576&&pa(t,oa,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;$s(e,t),e=t.pendingProps;var a=Wi(t,Vi.current);Ha(t,n),a=ko(null,t,r,e,a,n);var o=Ao();return t.flags|=1,typeof a==`object`&&a&&typeof a.render==`function`&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Gi(r)?(o=!0,Yi(t)):o=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Ya(t),a.updater=_s,t.stateNode=a,a._reactInternals=t,xs(t,r,e,n),t=Vs(null,t,r,!0,o,n)):(t.tag=0,Z&&o&&ma(t),Ns(null,t,a,n),t=t.child),t;case 16:r=t.elementType;a:{switch($s(e,t),e=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Jl(r),e=hs(r,e),a){case 0:t=zs(null,t,r,e,n);break a;case 1:t=Bs(null,t,r,e,n);break a;case 11:t=Ps(null,t,r,e,n);break a;case 14:t=Fs(null,t,r,hs(r.type,e),n);break a}throw Error(i(306,r,``))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),zs(e,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),Bs(e,t,r,a,n);case 3:a:{if(Hs(t),e===null)throw Error(i(387));r=t.pendingProps,o=t.memoizedState,a=o.element,Xa(e,t),to(t,r,null,n);var s=t.memoizedState;if(r=s.element,o.isDehydrated){if(o={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){a=Ss(Error(i(423)),t),t=Us(e,t,r,n,a);break a}if(r!==a){a=Ss(Error(i(424)),t),t=Us(e,t,r,n,a);break a}for(_a=wi(t.stateNode.containerInfo.firstChild),ga=t,Z=!0,va=null,n=Pa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(Ea(),r===a){t=ec(e,t,n);break a}Ns(e,t,r,n)}t=t.child}return t;case 5:return uo(t),e===null&&Sa(t),r=t.type,a=t.pendingProps,o=e===null?null:e.memoizedProps,s=a.children,_i(r,a)?s=null:o!==null&&_i(r,o)&&(t.flags|=32),Rs(e,t),Ns(e,t,s,n),t.child;case 6:return e===null&&Sa(t),null;case 13:return Ks(e,t,n);case 4:return co(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Na(t,null,r,n):Ns(e,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),Ps(e,t,r,a,n);case 7:return Ns(e,t,t.pendingProps,n),t.child;case 8:return Ns(e,t,t.pendingProps.children,n),t.child;case 12:return Ns(e,t,t.pendingProps.children,n),t.child;case 10:a:{if(r=t.type._context,a=t.pendingProps,o=t.memoizedProps,s=a.value,X(Fa,r._currentValue),r._currentValue=s,o!==null){if(Tr(o.value,s)){if(o.children===a.children&&!Hi.current){t=ec(e,t,n);break a}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var c=o.dependencies;if(c!==null){s=o.child;for(var l=c.firstContext;l!==null;){if(l.context===r){if(o.tag===1){l=Za(-1,n&-n),l.tag=2;var u=o.updateQueue;if(u!==null){u=u.shared;var d=u.pending;d===null?l.next=l:(l.next=d.next,d.next=l),u.pending=l}}o.lanes|=n,l=o.alternate,l!==null&&(l.lanes|=n),Va(o.return,n,t),c.lanes|=n;break}l=l.next}}else if(o.tag===10)s=o.type===t.type?null:o.child;else if(o.tag===18){if(s=o.return,s===null)throw Error(i(341));s.lanes|=n,c=s.alternate,c!==null&&(c.lanes|=n),Va(s,n,t),s=o.sibling}else s=o.child;if(s!==null)s.return=o;else for(s=o;s!==null;){if(s===t){s=null;break}if(o=s.sibling,o!==null){o.return=s.return,s=o;break}s=s.return}o=s}}Ns(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Ha(t,n),a=Ua(a),r=r(a),t.flags|=1,Ns(e,t,r,n),t.child;case 14:return r=t.type,a=hs(r,t.pendingProps),a=hs(r.type,a),Fs(e,t,r,a,n);case 15:return Is(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:hs(r,a),$s(e,t),t.tag=1,Gi(r)?(e=!0,Yi(t)):e=!1,Ha(t,n),ys(t,r,a),xs(t,r,a,n),Vs(null,t,r,!0,e,n);case 19:return Qs(e,t,n);case 22:return Ls(e,t,n)}throw Error(i(156,t.tag))};function Wl(e,t){return ft(e,t)}function Gl(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Kl(e,t,n,r){return new Gl(e,t,n,r)}function ql(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Jl(e){if(typeof e==`function`)return+!!ql(e);if(e!=null){if(e=e.$$typeof,e===re)return 11;if(e===D)return 14}return 2}function Yl(e,t){var n=e.alternate;return n===null?(n=Kl(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Xl(e,t,n,r,a,o){var s=2;if(r=e,typeof e==`function`)ql(e)&&(s=1);else if(typeof e==`string`)s=5;else a:switch(e){case T:return Zl(n.children,a,o,t);case ee:s=8,a|=8;break;case te:return e=Kl(12,n,t,a|2),e.elementType=te,e.lanes=o,e;case ie:return e=Kl(13,n,t,a),e.elementType=ie,e.lanes=o,e;case ae:return e=Kl(19,n,t,a),e.elementType=ae,e.lanes=o,e;case oe:return Ql(n,a,o,t);default:if(typeof e==`object`&&e)switch(e.$$typeof){case E:s=10;break a;case ne:s=9;break a;case re:s=11;break a;case D:s=14;break a;case O:s=16,r=null;break a}throw Error(i(130,e==null?e:typeof e,``))}return t=Kl(s,n,t,a),t.elementType=e,t.type=r,t.lanes=o,t}function Zl(e,t,n,r){return e=Kl(7,e,r,t),e.lanes=n,e}function Ql(e,t,n,r){return e=Kl(22,e,r,t),e.elementType=oe,e.lanes=n,e.stateNode={isHidden:!1},e}function $l(e,t,n){return e=Kl(6,e,null,t),e.lanes=n,e}function eu(e,t,n){return t=Kl(4,e.children===null?[]:e.children,e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tu(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Lt(0),this.expirationTimes=Lt(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Lt(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function nu(e,t,n,r,i,a,o,s,c){return e=new tu(e,t,n,s,c),t===1?(t=1,!0===a&&(t|=8)):t=0,a=Kl(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ya(a),e}function ru(e,t,n){var r=3{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=be()})),Se=t((e=>{var t=xe();e.createRoot=t.createRoot,e.hydrateRoot=t.hydrateRoot})),Ce=class extends he{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new re({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=we(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=we(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=we(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=we(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){ie.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>D(t,e))}findAll(e={}){return this.getAll().filter(t=>D(e,t))}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return ie.batch(()=>Promise.all(e.map(e=>e.continue().catch(k))))}};function we(e){return e.options.scope?.id}var Te=class extends he{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??ae(r,t),a=this.get(i);return a||(a=new A({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){ie.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>ue(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>ue(e,t)):t}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ie.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ie.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ee=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Te,this.#t=e.mutationCache||new Ce,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=me.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=fe.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(O(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=ce(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return ie.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;ie.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return ie.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=ie.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(k).catch(k)}invalidateQueries(e,t={}){return ie.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=ie.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(k)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(k)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(O(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(k).catch(k)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(k).catch(k)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return fe.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(pe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{oe(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(pe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{oe(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=ae(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===ne&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},M=e(r(),1),De=e(Se(),1),Oe=class extends Error{status;method;path;constructor(e,t,n,r){super(e),this.name=`ApiError`,this.status=t,this.method=n,this.path=r}};function ke(e){let t=e.replace(/\s+/g,` `).trim();if(!t)return``;try{let t=JSON.parse(e);for(let e of[`detail`,`error`,`message`]){let n=t[e];if(typeof n==`string`&&n.trim())return n.trim();if(Array.isArray(n)){let e=n.map(e=>e&&typeof e==`object`?String(e.msg??``):``).filter(Boolean);if(e.length)return e.join(`; `)}}}catch{}return t.startsWith(`typeof e==`string`):[],o=Ie(r?.major),s=Ie(r?.minor);if(!n||!r||!i)return{compatible:!1,reason:`malformed /api/meta response`};if(typeof i.source_root!=`string`||Ie(i.pid)===null||typeof i.package_version!=`string`||typeof i.release_id!=`string`)return{compatible:!1,reason:`malformed /api/meta runtime identity`};if(n.service!==`argus-skill-webapi`)return{compatible:!1,reason:`unexpected service ${String(n.service||`unknown`)}`};let c=e;if(r.name!==Ne.name||o!==Ne.major)return{compatible:!1,reason:`protocol ${String(r.name||`unknown`)}/${String(o)} is incompatible with client ${Ne.name}/${Ne.major}`,meta:c};if(s===null||s!a.includes(e));if(l.length>0)return{compatible:!1,reason:`missing capabilities: ${l.join(`, `)}`,meta:c};if(i.source_root_matches_config===!1)return{compatible:!1,reason:`backend loaded source ${String(i.source_root)} but ARGUS_SKILL_SOURCE_ROOT points to ${String(i.configured_source_root)}`,meta:c};if(i.release_id!==t.releaseId)return{compatible:!1,reason:`backend release ${String(i.release_id)} does not match client release ${t.releaseId}`,meta:c};if(t.sourceDigest){if(typeof i.runtime_source_digest!=`string`||!i.runtime_source_digest)return{compatible:!1,reason:`backend process does not report the source digest required by this local checkout`,meta:c};if(i.runtime_source_digest!==t.sourceDigest)return{compatible:!1,reason:`backend process source ${String(i.runtime_source_digest).slice(0,16)} does not match local source ${t.sourceDigest.slice(0,16)}`,meta:c}}return{compatible:!0,reason:``,warning:i.release_matches_source===!1?`backend source differs from its prebuilt release artifacts; pull a complete published revision and reinstall`:void 0,meta:c}}function Re(e,t){let n=Le(e);if(!n.compatible||!n.meta)throw Error(`incompatible Argus API: ${n.reason}`);return n.warning&&t?.(n.warning),n.meta}function ze(e){let t=Fe(e),n=Fe(t?.daemon);if(!t||t.schema_version!==7)throw Error(`incompatible snapshot schema: expected 7, got ${String(t?.schema_version??`missing`)}`);if(!n)throw Error(`invalid snapshot: daemon section is missing`);let r=[`global_daily_cap_usd`,`read_status`,`read_error`,`protocol_compatible`,`protocol_error`].filter(e=>!Object.hasOwn(n,e));if(r.length>0)throw Error(`invalid snapshot: daemon fields missing: ${r.join(`, `)}`);let i=[`spend_usd`,`spend_status`,`usage_summary`,`request_usage`,`cost_control`,`daemon_commands`,`observability`,`mission_view`,`partial`,`diagnostics`].filter(e=>!Object.hasOwn(t,e));if(i.length>0)throw Error(`invalid snapshot: fields missing: ${i.join(`, `)}`);if(!Array.isArray(t.diagnostics))throw Error(`invalid snapshot: diagnostics must be an array`);return e}var Be=`argus_web_token`,Ve=null;function He(){let e;try{e=new URLSearchParams(window.location.search)}catch{return}let t=e.get(`token`);if(t){Ve=t;try{localStorage.setItem(Be,t)}catch{}try{e.delete(`token`);let t=e.toString();window.history.replaceState(null,``,`${window.location.pathname}${t?`?${t}`:``}${window.location.hash}`)}catch{}}}var Ue=()=>{if(Ve)return Ve;try{return new URLSearchParams(window.location.search).get(`token`)||localStorage.getItem(Be)}catch{return null}};function We(){let e=Ue();return e?{Authorization:`Bearer ${e}`}:{}}function Ge(){return Ue()??``}var Ke=8e3,qe=12e3,N=class extends Error{constructor(){super(`This browser is not paired with Argus. Reopen it from Argus Desktop or use a fresh pairing link.`),this.name=`PairingRequiredError`}},Je=class extends Error{method;path;constructor(e,t,n=`could not reach the local Argus service`){super(`${e.toUpperCase()} ${t} ${n}. Make sure Argus Desktop is running, then retry.`),this.name=`LocalArgusUnavailableError`,this.method=e.toUpperCase(),this.path=t}};function Ye(e){return e instanceof N||!!(e&&typeof e==`object`&&Number(e.status)===401)}function Xe(e){return Ye(e)||e instanceof Je}async function P(e,t){try{return await fetch(e,t)}catch(n){throw t.signal?.aborted?n:new Je(String(t.method??`GET`),e)}}async function Ze(e,t,n,r){let i=new AbortController,a=t.signal??void 0,o=!1,s=()=>{};if(a){let e=()=>i.abort(a.reason);a.aborted?e():(a.addEventListener(`abort`,e,{once:!0}),s=()=>a.removeEventListener(`abort`,e))}let c,l=(async()=>await r(await P(e,{...t,signal:i.signal})))(),u=new Promise((e,t)=>{c=setTimeout(()=>{o=!0;let e=Error(`request timed out after ${n}ms`);i.abort(e),t(e)},n)});try{return await Promise.race([l,u])}catch(r){if(o){let r=Math.round(n/1e3);throw new Je(String(t.method??`GET`),e,`timed out after ${r}s because the local Argus service did not respond`)}throw r}finally{c&&clearTimeout(c),s()}}async function Qe(e,t,n){return Ze(e,{headers:We(),signal:t},n??qe,async t=>(await je(t,`GET`,e),await t.json()))}async function F(e,t,n){let r=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`,...We()},body:t===void 0?void 0:JSON.stringify(t),signal:n});return await je(r,`POST`,e),await r.json()}async function $e(e,t,n){let r=await fetch(e,{method:`POST`,headers:We(),body:t,signal:n});return await je(r,`POST`,e),await r.json()}function et(e){let t=e&&typeof e==`object`?e:{},n=String(t.command_status??``);if(Number(t.rc??0)!==0||n===`failed`||n===`rejected`)throw Error(String(t.error||`daemon command ${n||`failed`}`));return e}async function tt(e,t,n){let r=await fetch(t,{method:e,headers:{"Content-Type":`application/json`,...We()},body:n===void 0?void 0:JSON.stringify(n)});return await je(r,e,t),await r.json()}async function nt(e,t){let n=await fetch(e,{headers:We(),signal:t});return await je(n,`GET`,e),n.blob()}var I=(e,t=``)=>`/api/projects/${encodeURIComponent(e)}${t}`,L=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random()}`,rt;function it(e){return!!(e&&typeof e==`object`&&`aborted`in e&&typeof e.aborted==`boolean`)}function at(e,t){return t?.length?{text:e,attachments:t}:{text:e}}function ot(){if(!rt){let e=(async()=>{let e=`/api/meta`,t=await Ze(e,{headers:We()},Ke,async t=>{if(t.status===404)throw Error(`incompatible Argus API: service does not expose /api/meta`);return await je(t,`GET`,e),Re(await t.json(),e=>console.warn(`Argus API compatibility warning: ${e}`))});if(t.authentication?.required&&!t.authentication.authenticated)throw new N;return t})();rt=e,e.catch(t=>{rt===e&&!(t instanceof N)&&(rt=void 0)})}return rt}function st(e){let t=[],n;for(;(n=e.indexOf(` `))>=0;){let r=e.slice(0,n);e=e.slice(n+2);for(let e of r.split(` `)){let n=e.trim();if(n.startsWith(`data:`))try{t.push(JSON.parse(n.slice(5).trim()))}catch{}}}return{frames:t,rest:e}}var R={meta:ot,projectIndex:async()=>(await ot(),Qe(`/api/projects`,void 0,qe)),listProjects:async()=>(await ot(),Qe(`/api/projects`,void 0,qe).then(e=>e.projects)),projectCosts:async e=>(await ot(),Qe(`/api/projects/costs`,e)),createDaemon:async(e,t=``,n=``,r)=>{let i=`/api/daemons`,a={objective:e,name:t,workdir:n,command_id:L(),expected_revision:r},o=()=>fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,...We()},body:JSON.stringify(a),cache:`no-store`}),s=await o();return s.status===400&&/Invalid HTTP request received/i.test(await s.clone().text())&&(s=await o()),await je(s,`POST`,i),et(await s.json())},updateProject:(e,t)=>tt(`PATCH`,I(e),{name:t}),deleteProject:e=>tt(`DELETE`,I(e)),snapshot:async(e,t)=>(await ot(),ze(await Qe(I(e,`/snapshot?compact=true&events_limit=1`),t,qe))),status:(e,t)=>Qe(I(e,`/status`),t),journal:(e,t=20,n)=>Qe(I(e,`/journal?n=${t}`),n).then(e=>e.journal),doctor:(e,t)=>Qe(I(e,`/doctor`),t),config:(e,t)=>Qe(I(e,`/config`),t),identity:(e,t)=>Qe(I(e,`/identity`),t).then(e=>e.identity),transcript:(e,t=30,n)=>Qe(I(e,`/transcript?n=${t}`),n).then(e=>e.turns),events:(e,t=80,n)=>Qe(I(e,`/events?limit=${t}&view=ui`),n).then(e=>e.events),backlogItem:(e,t,n)=>Qe(I(e,`/backlog/${encodeURIComponent(t)}`),n).then(e=>e.item),artifacts:(e,t)=>Qe(I(e,`/artifacts`),t).then(e=>e.artifacts),artifact:(e,t,n)=>Qe(I(e,`/artifact?${new URLSearchParams({path:t})}`),n),artifactBlob:(e,t,n=!1,r)=>{let i=new URLSearchParams({path:t});return n&&i.set(`download`,`true`),nt(I(e,`/artifact/raw?${i}`),r)},gitDiff:(e,t)=>Qe(I(e,`/git-diff`),t),metrics:e=>Qe(`/api/metrics`,e),trash:(e=``,t=100,n=0,r)=>Qe(`/api/trash?${new URLSearchParams({query:e,limit:String(t),offset:String(n)})}`,r),restoreTrash:e=>F(`/api/trash/${encodeURIComponent(e)}/restore`),addTask:(e,t)=>F(I(e,`/tasks`),{text:t}).then(e=>e.item),abortMission:(e,t)=>F(I(e,`/mission/abort`),{reason:t}),answerPending:(e,t,n)=>F(I(e,`/backlog/${encodeURIComponent(t)}/answer`),{text:n}),resolveDecision:(e,t,n,r)=>F(I(e,`/decisions/${encodeURIComponent(t)}/resolve`),{option_id:n,note:r}),uploadAttachments:async(e,t,n)=>{await ot();let r=new FormData;return t.forEach(e=>r.append(`files`,e,e.name)),$e(I(e,`/attachments`),r,n)},message:(e,t,n)=>{let r=it(n)?n:n?.signal,i=it(n)?void 0:n?.attachments;return F(I(e,`/message`),at(t,i),r)},messageStream:async(e,t,n,r)=>{let i=it(r)?r:r?.signal,a=it(r)?void 0:r?.attachments,o=await fetch(I(e,`/message/stream`),{method:`POST`,headers:{"Content-Type":`application/json`,...We()},body:JSON.stringify(at(t,a)),signal:i});if(await je(o,`POST`,I(e,`/message/stream`)),!o.body)throw Error(`Manager stream returned no response body`);let s=!1,c=e=>{if(!i?.aborted){if(e.type===`phase`){let t=Number(e.quiet_s??0);n.onPhase?.(String(e.label??``),String(e.role??`manager`),{heartbeat:e.heartbeat===!0,quietS:Number.isFinite(t)?t:0,kind:String(e.kind??``),detail:String(e.detail??``)})}else e.type===`delta`?n.onDelta?.(String(e.text??``),String(e.message_id??``),String(e.fragment_mode??`auto`)):e.type===`done`?(s=!0,n.onDone?.(e.result??{})):e.type===`error`&&(s=!0,n.onError?.(Error(String(e.error??`stream error`))))}},l=o.body.getReader(),u=new TextDecoder,d=``;for(;;){let{done:e,value:t}=await l.read();if(e)break;d+=u.decode(t,{stream:!0});let n=st(d);d=n.rest,n.frames.forEach(c)}if(!i?.aborted&&(st(d+` @@ -27,4 +27,4 @@ Error generating stack: `+e.message+` … content truncated`:``]}):(0,K.jsx)(`div`,{className:`mt-2 text-[10px] text-ink-faint`,children:r(`mission.skillUnavailable`)})]},String(e.id)))})]}):null,e.learned_wiki_pages.some(e=>e.status!==`retired`)?(0,K.jsxs)(`div`,{className:`mt-4 border-t border-line/50 pt-3`,children:[(0,K.jsx)(`div`,{className:`text-[10px] uppercase tracking-[0.12em] text-blue-sky`,children:r(`mission.knowledgeRetained`)}),(0,K.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:e.learned_wiki_pages.filter(e=>e.status!==`retired`).slice(-6).map(e=>(0,K.jsx)(`span`,{className:`rounded border border-blue/35 bg-blue/5 px-2 py-1 text-[10px] text-blue-sky`,children:String(e.title||e.id)},String(e.id)))})]}):null,e.storage.project_skill_dir||e.storage.global_skill_dir||e.storage.wiki_paths.length||e.storage.skill_history_compressed||e.storage.wiki_retired_compressed?(0,K.jsxs)(`div`,{className:`mt-4 border-t border-line/50 pt-3`,children:[(0,K.jsx)(`div`,{className:`text-[10px] uppercase tracking-[0.12em] text-ink-faint`,children:r(`mission.selfEvolution`)}),(0,K.jsxs)(`div`,{className:`mt-2 space-y-1 font-mono text-[10px] text-ink-dim`,children:[e.storage.project_skill_dir?(0,K.jsxs)(`div`,{className:`break-all`,children:[`project skills (`,e.storage.project_skill_count,`) · `,e.storage.project_skill_dir]}):null,e.storage.global_skill_dir?(0,K.jsxs)(`div`,{className:`break-all`,children:[`global skills (`,e.storage.global_skill_count,`) · `,e.storage.global_skill_dir]}):null,e.storage.wiki_paths.map(e=>(0,K.jsxs)(`div`,{className:`break-all`,children:[`project wiki · `,e]},e)),e.storage.skill_history_compressed||e.storage.wiki_retired_compressed?(0,K.jsxs)(`div`,{children:[`cold history · skill `,e.storage.skill_history_compressed,` · wiki `,e.storage.wiki_retired_compressed,` · `,ni(e.storage.skill_history_bytes_saved+e.storage.wiki_retired_bytes_saved),` saved`]}):null]})]}):null]})]}),(0,K.jsxs)(`section`,{className:`px-5 py-4`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,K.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-[0.16em] text-ink-faint`,children:r(`mission.replay`)}),e.timeline.length>1?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`input`,{type:`range`,min:0,max:e.timeline.length-1,value:l,onChange:e=>u(Number(e.target.value)),"aria-label":r(`mission.replayTimeline`),className:`h-1 min-w-32 flex-1 accent-blue`}),(0,K.jsxs)(`span`,{className:`font-mono text-[10px] text-ink-faint`,children:[l+1,`/`,e.timeline.length]})]}):null]}),(0,K.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[_.map(e=>(0,K.jsxs)(`div`,{className:`grid grid-cols-[44px_10px_minmax(0,1fr)] gap-2 text-xs`,children:[(0,K.jsx)(`time`,{className:`font-mono text-[10px] text-ink-faint`,children:new Date(e.ts*1e3).toISOString().slice(11,16)}),(0,K.jsx)(`span`,{className:`mt-1 h-2 w-2 rounded-full ${e.tone===`error`?`bg-err`:e.tone===`success`||e.tone===`metric`||e.tone===`skill`?`bg-ok`:`bg-blue`}`}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(`span`,{className:`font-medium text-ink`,children:e.title}),e.detail?(0,K.jsxs)(`span`,{className:`text-ink-dim`,children:[` · `,e.detail]}):null]})]},e.id)),e.timeline.length?null:(0,K.jsx)(`div`,{className:`py-10 text-center text-xs text-ink-faint`,children:r(`mission.waitingEvents`)})]}),e.artifacts.length?(0,K.jsx)(`div`,{className:`mt-5 flex flex-wrap gap-2 border-t border-line/50 pt-4`,children:e.artifacts.slice(-8).map(e=>{let n=String(e.path||``);return(0,K.jsx)(`button`,{type:`button`,disabled:!n||!t,onClick:()=>n&&t?.(n),className:`rounded border border-line px-2 py-1 font-mono text-[10px] text-blue-sky hover:border-blue-sky/50 disabled:text-ink-faint`,children:String(e.title||n)},String(e.id||n))})}):null,n?.available&&(n.status||n.diff)?(0,K.jsxs)(`details`,{className:`mt-5 border-t border-line/50 pt-4`,children:[(0,K.jsxs)(`summary`,{className:`cursor-pointer text-[10px] font-semibold uppercase tracking-[0.14em] text-ink-faint hover:text-ink`,children:[`Git changes`,n.branch?` · ${n.branch}`:``]}),n.stat?(0,K.jsx)(`pre`,{className:`mt-3 overflow-x-auto whitespace-pre-wrap font-mono text-[10px] leading-5 text-ink-dim`,children:n.stat}):null,n.diff?(0,K.jsxs)(`pre`,{className:`mt-3 max-h-80 overflow-auto whitespace-pre font-mono text-[10px] leading-5 text-ink-dim scroll-thin`,children:[n.diff,n.truncated?` … diff truncated`:``]}):null]}):null]})]})}var lo=e=>e instanceof Error?e.message:String(e||`Unknown error`);async function uo(e){let t=await e,n=t&&typeof t==`object`?t:{},r=String(n.command_status??``);if(Number(n.rc??0)!==0||r===`failed`||r===`rejected`)throw Error(String(n.error||`daemon command ${r||`failed`}`));return t}function fo({open:e,sid:t,snap:r,onClose:i,onChanged:a,onRestored:u}){let{t:f}=q(),[p,h]=(0,M.useState)(`task`),[g,_]=(0,M.useState)(``),[v,C]=(0,M.useState)(r.session.workdir??r.session.cwd??``),[w,ee]=(0,M.useState)(`ls`),[E,ne]=(0,M.useState)(``),[re,ie]=(0,M.useState)(``),[ae,D]=(0,M.useState)(null),[O,oe]=(0,M.useState)([]),[se,ce]=(0,M.useState)(0),[k,le]=(0,M.useState)(``),[A,ue]=(0,M.useState)(``),[de,fe]=(0,M.useState)(`work`);(0,M.useEffect)(()=>{e&&(C(r.session.workdir??r.session.cwd??``),Promise.all([R.metrics(),R.trash()]).then(([e,t])=>{D(e),oe(t.entries),ce(t.total)},e=>ne(lo(e))))},[e,r.session.cwd,r.session.workdir]);let j=async(e,t,n)=>{if(!A){ue(e),ne(``);try{let e=await t();n!==null&&ne(n||JSON.stringify(e,null,2)),a()}catch(e){ne(lo(e))}finally{ue(``)}}},pe=async()=>{let e=g.trim();if(e){if(p===`plan`){await j(`quick`,async()=>{let n=await R.previewPlan(t,e);return ne([...n.steps.map((e,t)=>`${t+1}. ${e.title}${e.detail?` — ${e.detail}`:``}`),...n.notes.map(e=>`Note: ${e}`),...n.error?[`Error: ${n.error}`]:[]].join(` `)),n},null);return}await j(`quick`,p===`task`?()=>R.addTask(t,e):p===`nudge`?()=>R.nudge(t,e):()=>R.note(t,e),`${p} submitted.`),_(``)}},me=async e=>{await j(`restore:${e.trash_id}`,async()=>{let t=await R.restoreTrash(e.trash_id);return oe(t=>t.filter(t=>t.trash_id!==e.trash_id)),ce(e=>Math.max(0,e-1)),await u(t.sid),t},`Restored ${e.label}.`)},he=r.daemon.alive&&r.daemon.protocol_compatible===!1,ge=r.daemon.alive&&r.daemon.control_available===!1,_e=r.daemon_admission?.running_daemons??[],ve=p===`task`?b:p===`nudge`?T:p===`note`?s:S,ye=async()=>{await j(`trash-search`,async()=>{let e=await R.trash(k);return oe(e.entries),ce(e.total),e},null)};return(0,K.jsxs)(ia,{open:e,onClose:()=>!A&&i(),label:f(`operations.title`),width:`max-w-5xl`,children:[(0,K.jsx)(aa,{title:f(`operations.title`),sub:r.session.display_name||t}),(0,K.jsx)(`div`,{className:`flex gap-1 border-b border-line bg-panel px-4 py-2`,children:[[`work`,f(`operations.work`),b],[`runtime`,f(`operations.runtime`),d],[`system`,f(`operations.system`),c],[`recovery`,f(`operations.recovery`),n]].map(([e,t,n])=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>{fe(e),ne(``)},title:t,"aria-label":t,className:`flex h-8 w-9 items-center justify-center rounded-md text-xs ${de===e?`bg-blue-deep text-white`:`text-ink-faint hover:bg-bg hover:text-ink`}`,children:(0,K.jsx)(o,{icon:n})},e))}),(0,K.jsxs)(`div`,{className:`grid max-h-[76vh] gap-3 overflow-y-auto bg-bg p-3 scroll-thin lg:grid-cols-2`,children:[de===`work`?(0,K.jsxs)(`section`,{className:`rounded-lg border border-line bg-panel p-4 lg:col-span-2`,children:[(0,K.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-ink-dim`,children:f(`operations.workInput`)}),(0,K.jsx)(`p`,{className:`mt-1 text-xs text-ink-faint`,children:f(`operations.workHint`)}),(0,K.jsx)(`div`,{className:`mt-3 flex gap-1`,children:[[`task`,b],[`nudge`,T],[`note`,s],[`plan`,S]].map(([e,t])=>(0,K.jsx)(`button`,{type:`button`,onClick:()=>h(e),title:e,"aria-label":e,className:`flex h-8 w-9 items-center justify-center rounded text-xs capitalize ${p===e?`bg-blue-deep text-white`:`bg-bg text-ink-dim`}`,children:(0,K.jsx)(o,{icon:t})},e))}),(0,K.jsx)(`textarea`,{value:g,onChange:e=>_(e.target.value),rows:5,placeholder:p===`plan`?f(`operations.planPlaceholder`):f(`operations.actionPlaceholder`,{action:p}),className:`mt-3 w-full resize-y rounded border border-line bg-bg p-3 text-sm text-ink outline-none focus:border-blue`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>void pe(),disabled:!!A||!g.trim(),title:p===`plan`?f(`operations.previewPlan`):f(`operations.submitAction`,{action:p}),"aria-label":p===`plan`?f(`operations.previewPlan`):f(`operations.submitAction`,{action:p}),className:`mt-2 flex h-9 w-9 items-center justify-center rounded bg-blue-deep text-xs font-medium text-white disabled:opacity-40`,children:A===`quick`?`…`:(0,K.jsx)(o,{icon:ve})})]}):null,de===`runtime`?(0,K.jsxs)(`section`,{className:`rounded-lg border border-line bg-panel p-4 lg:col-span-2`,children:[(0,K.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-ink-dim`,children:f(`operations.runtime`)}),(0,K.jsx)(`p`,{className:`mt-1 text-xs text-ink-faint`,children:f(`operations.runtimeHint`)}),(0,K.jsx)(`label`,{className:`mt-3 block text-[10px] uppercase tracking-wide text-ink-faint`,children:f(`operations.workdir`)}),(0,K.jsxs)(`div`,{className:`mt-1 flex gap-2`,children:[(0,K.jsx)(`input`,{value:v,onChange:e=>C(e.target.value),className:`h-9 min-w-0 flex-1 rounded border border-line bg-bg px-2 font-mono text-xs text-ink outline-none focus:border-blue`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>void j(`cwd`,()=>R.setWorkdir(t,v),f(`operations.workdirUpdated`)),disabled:!!A||!v.trim(),title:f(`operations.applyWorkdir`),"aria-label":f(`operations.applyWorkdir`),className:`flex h-9 w-9 items-center justify-center rounded border border-blue/50 text-xs text-blue disabled:opacity-40`,children:(0,K.jsx)(o,{icon:y})})]}),(0,K.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-2`,children:[(0,K.jsx)(`button`,{type:`button`,onClick:()=>void j(`reset`,()=>R.resetManager(t),`Manager context reset.`),disabled:!!A,title:f(`operations.resetManager`),"aria-label":f(`operations.resetManager`),className:`flex h-9 w-9 items-center justify-center rounded border border-line text-xs text-ink-dim disabled:opacity-40`,children:(0,K.jsx)(o,{icon:te})}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>void j(`upgrade`,()=>uo(R.upgradeDaemon(t,r.daemon_commands?.revision)),`Current-release daemon started after safely draining active work.`),disabled:!!A||ge,title:ge?`Externally supervised daemon cannot be restarted from this Web host`:he?`Upgrade incompatible daemon`:`Restart on current release`,"aria-label":ge?`Externally supervised daemon`:he?`Upgrade incompatible daemon`:`Restart on current release`,className:`flex h-9 w-9 items-center justify-center rounded border text-xs disabled:opacity-40 ${he?`border-err/60 bg-err/10 text-err`:`border-line text-ink-dim`}`,children:(0,K.jsx)(o,{icon:x})})]}),r.daemon.protocol_error?(0,K.jsx)(`p`,{className:`mt-2 text-xs text-err`,children:r.daemon.protocol_error}):null,_e.length?(0,K.jsxs)(`div`,{className:`mt-4`,children:[(0,K.jsx)(`div`,{className:`text-[10px] uppercase tracking-wide text-ink-faint`,children:f(`operations.replaceSlot`)}),(0,K.jsx)(`div`,{className:`mt-2 space-y-1`,children:_e.map(e=>(0,K.jsxs)(`button`,{type:`button`,disabled:!!A,onClick:()=>void j(`replace:${e.id}`,()=>uo(R.replaceDaemon(t,e.id,!!r.continuous?.enabled,r.daemon_commands?.revision)),`Parked ${e.label||e.id} and started this session.`),title:`Replace ${e.label||e.id}`,"aria-label":`Replace ${e.label||e.id}`,className:`flex w-full items-center justify-between rounded border border-line bg-bg px-2 py-1.5 text-left text-xs text-ink-dim disabled:opacity-40`,children:[(0,K.jsx)(`span`,{className:`truncate`,children:e.label||e.id}),(0,K.jsx)(o,{icon:x,className:`ml-2 text-warn`})]},e.id))})]}):null]}):null,de===`system`?(0,K.jsxs)(`section`,{className:`rounded-lg border border-line bg-panel p-4`,children:[(0,K.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-ink-dim`,children:f(`operations.skills`)}),(0,K.jsxs)(`div`,{className:`mt-3 flex gap-2`,children:[(0,K.jsx)(`input`,{value:w,onChange:e=>ee(e.target.value),className:`h-9 min-w-0 flex-1 rounded border border-line bg-bg px-2 font-mono text-xs text-ink outline-none focus:border-blue`,placeholder:`ls, stats, show NAME…`}),(0,K.jsx)(`button`,{type:`button`,disabled:!!A,onClick:()=>void j(`skills`,async()=>{let e=await R.skills(t,w);return ie(e),e},null),title:f(`operations.runSkill`),"aria-label":f(`operations.runSkill`),className:`flex h-9 w-9 items-center justify-center rounded border border-blue/50 text-xs text-blue disabled:opacity-40`,children:(0,K.jsx)(o,{icon:l})})]}),re?(0,K.jsx)(`pre`,{className:`mt-3 max-h-48 overflow-auto whitespace-pre-wrap rounded bg-bg p-3 font-mono text-xs text-ink-dim scroll-thin`,children:re}):null]}):null,de===`system`?(0,K.jsxs)(`section`,{className:`rounded-lg border border-line bg-panel p-4`,children:[(0,K.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-ink-dim`,children:f(`operations.metrics`)}),(0,K.jsxs)(`div`,{className:`mt-3 flex items-center gap-3`,children:[(0,K.jsx)(`span`,{className:`rounded px-2 py-1 text-xs font-semibold ${ae?.slo?.status===`healthy`?`bg-ok/10 text-ok`:`bg-warn/10 text-warn`}`,children:ae?.slo?.status??`loading`}),(0,K.jsxs)(`span`,{className:`text-xs text-ink-faint`,children:[`event validation failures: `,ae?.event_validation_failures??`—`]})]}),ae?(0,K.jsx)(`pre`,{className:`mt-3 max-h-48 overflow-auto whitespace-pre-wrap rounded bg-bg p-3 font-mono text-[10px] text-ink-dim scroll-thin`,children:JSON.stringify({web:ae.web,provider:ae.provider,cost_control:ae.cost_control},null,2)}):null]}):null,de===`recovery`?(0,K.jsxs)(`section`,{className:`rounded-lg border border-line bg-panel p-4 lg:col-span-2`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,K.jsxs)(`h3`,{className:`mr-auto text-xs font-semibold uppercase tracking-wide text-ink-dim`,children:[f(`operations.trash`),` · `,se]}),(0,K.jsx)(`input`,{value:k,onChange:e=>le(e.target.value),onKeyDown:e=>{!Pi(e)&&e.key===`Enter`&&ye()},placeholder:f(`operations.searchTrash`),className:`h-8 min-w-52 rounded border border-line bg-bg px-2 text-xs text-ink outline-none focus:border-blue`}),(0,K.jsx)(`button`,{type:`button`,disabled:!!A,onClick:()=>void ye(),title:f(`operations.searchTrash`),"aria-label":f(`operations.searchTrash`),className:`flex h-8 w-8 items-center justify-center rounded border border-blue/50 text-xs text-blue disabled:opacity-40`,children:(0,K.jsx)(o,{icon:m})})]}),O.length?(0,K.jsx)(`div`,{className:`mt-3 grid gap-2 sm:grid-cols-2`,children:O.map(e=>(0,K.jsxs)(`div`,{className:`flex items-center gap-3 rounded border border-line bg-bg p-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(`div`,{className:`truncate text-xs text-ink`,children:e.label}),(0,K.jsx)(`div`,{className:`truncate font-mono text-[10px] text-ink-faint`,children:e.trash_path})]}),(0,K.jsx)(`button`,{type:`button`,disabled:!!A,onClick:()=>void me(e),title:`Restore ${e.label}`,"aria-label":`Restore ${e.label}`,className:`flex h-8 w-8 items-center justify-center rounded border border-blue/50 text-xs text-blue disabled:opacity-40`,children:(0,K.jsx)(o,{icon:n})})]},e.trash_id))}):(0,K.jsx)(`p`,{className:`mt-3 text-xs text-ink-faint`,children:f(`operations.trashEmpty`)}),se>O.length?(0,K.jsxs)(`p`,{className:`mt-2 text-[10px] text-ink-faint`,children:[`Showing the newest `,O.length,` matches. Narrow the search to find older sessions.`]}):null]}):null,E?(0,K.jsx)(`pre`,{className:`rounded-lg border border-line bg-panel p-3 font-mono text-xs whitespace-pre-wrap text-ink-dim lg:col-span-2`,children:E}):null]})]})}var po=[`API`,`Protocol`,`Workspace`];function mo(){let{t:e}=q(),t=(0,M.useRef)(null);return Qr(t,(e,t)=>{if(t){e.set(`[data-handshake-line], [data-handshake-node]`,{opacity:1,scale:1,clearProps:`transform`});return}e.to(`[data-handshake-mark]`,{scale:1.055,duration:.75,ease:`sine.inOut`,repeat:-1,yoyo:!0,transformOrigin:`50% 50%`}),e.timeline({repeat:-1,repeatDelay:.25}).fromTo(`[data-handshake-line]`,{scaleX:0,opacity:.25,transformOrigin:`0% 50%`},{scaleX:1,opacity:.8,duration:.9,ease:`power2.inOut`}).fromTo(`[data-handshake-node]`,{autoAlpha:.25,scale:.72},{autoAlpha:1,scale:1,duration:.28,stagger:.16,ease:`back.out(1.8)`},.12).to(`[data-handshake-node]`,{autoAlpha:.35,duration:.3,stagger:.08},`+=0.35`)}),(0,K.jsxs)(`div`,{ref:t,role:`status`,"aria-label":e(`handshake.connecting`),className:`w-full max-w-xl px-6 text-center`,children:[(0,K.jsx)(`div`,{"data-handshake-mark":!0,className:`handshake-mark glass-card mx-auto flex h-16 w-16 items-center justify-center rounded-3xl text-blue shadow-glow sm:h-20 sm:w-20`,children:(0,K.jsx)(xi,{size:48,className:`text-blue`})}),(0,K.jsxs)(`div`,{className:`relative mx-auto mt-8 h-10 max-w-sm sm:max-w-md`,children:[(0,K.jsx)(`div`,{className:`absolute left-[10%] right-[10%] top-3 h-px bg-line/80`}),(0,K.jsx)(`div`,{"data-handshake-line":!0,className:`handshake-line absolute left-[10%] right-[10%] top-3 h-px`}),(0,K.jsx)(`div`,{className:`relative flex justify-between`,children:po.map(e=>(0,K.jsxs)(`div`,{className:`flex w-20 flex-col items-center gap-2.5`,children:[(0,K.jsx)(`span`,{"data-handshake-node":!0,className:`handshake-node h-6 w-6 rounded-full border ring-4 ring-bg`,children:(0,K.jsx)(`span`,{className:`m-auto mt-[7px] block h-2 w-2 rounded-full bg-blue`})}),(0,K.jsx)(`span`,{className:`text-xs font-medium text-ink-faint`,children:e})]},e))})]}),(0,K.jsx)(`p`,{className:`mt-9 text-base font-medium text-ink-dim`,children:`Connecting to Argus`}),(0,K.jsx)(`p`,{className:`mt-1.5 text-sm text-ink-faint`,children:`Negotiating protocol and restoring your workspace…`})]})}function ho({loading:e,hasProjects:t,error:n,onRetry:r,onNew:i,onChoose:a,canCreate:o}){let{t:s}=q();return(0,K.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-4 text-center`,children:[e?(0,K.jsx)(mo,{}):(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Ci,{size:32,tag:oi}),(0,K.jsx)(`p`,{className:`max-w-md text-sm leading-relaxed ${n?`text-err`:`text-ink-faint`}`,children:n||s(t?`landing.selectOrCreate`:`landing.noSessions`)})]}),!e&&(0,K.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[n?(0,K.jsx)(di,{onClick:r,variant:`danger`,children:s(`common.retry`)}):null,t?(0,K.jsx)(di,{onClick:a,children:s(`landing.select`)}):o?(0,K.jsx)(di,{onClick:i,variant:`primary`,children:s(`landing.new`)}):null]})]})}function go({active:e,onSelect:t,onOpenSessions:n}){let{t:r}=q(),i=[{id:`mission`,label:r(`mobile.mission`),icon:S},{id:`activity`,label:r(`mobile.activity`),icon:_},{id:`workbench`,label:r(`mobile.workbench`),icon:g},{id:`preview`,label:r(`mobile.preview`),icon:ee}];return(0,K.jsxs)(`nav`,{"aria-label":r(`mobile.views`),className:`mobile-tabbar glass-panel glass-panel--raised fixed inset-x-0 bottom-0 z-40 flex items-stretch border-t border-line/60 lg:hidden`,children:[n?(0,K.jsxs)(`button`,{type:`button`,onClick:n,"aria-label":r(`topbar.openSessions`),className:`flex min-h-[3.25rem] flex-1 flex-col items-center justify-center gap-0.5 text-ink-faint active:bg-panel-raised`,children:[(0,K.jsx)(o,{icon:h,className:`h-4 w-4`}),(0,K.jsx)(`span`,{className:`text-[10px] leading-none`,children:r(`mobile.sessions`)})]}):null,i.map(n=>{let r=n.id===e;return(0,K.jsxs)(`button`,{type:`button`,onClick:()=>t(n.id),"aria-current":r?`page`:void 0,className:`flex min-h-[3.25rem] flex-1 flex-col items-center justify-center gap-0.5 active:bg-panel-raised ${r?`text-blue`:`text-ink-faint`}`,children:[(0,K.jsx)(o,{icon:n.icon,className:`h-4 w-4`}),(0,K.jsx)(`span`,{className:`text-[10px] leading-none`,children:n.label})]},n.id)})]})}function _o(){(0,M.useEffect)(()=>{let e=window.visualViewport,t=document.documentElement;if(!e)return;let n=null,r=()=>{n!=null&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(()=>{let n=window.innerHeight-e.height-e.offsetTop,r=n>24?Math.round(n):0;t.style.setProperty(`--keyboard-inset`,`${r}px`)})};return r(),e.addEventListener(`resize`,r),e.addEventListener(`scroll`,r),()=>{n!=null&&window.cancelAnimationFrame(n),e.removeEventListener(`resize`,r),e.removeEventListener(`scroll`,r),t.style.removeProperty(`--keyboard-inset`)}},[])}async function vo(e,t){let n=V(e.trim());if(!n)return{kind:`not-command`};if(!n.cmd){let e=Vt(n.name);return{kind:`error`,message:e?`Unknown command ${n.name}. Did you mean ${e}?`:`Unknown command ${n.name}. Use /help for the full list.`}}if(n.cmd.id===`ask`)return{kind:`not-command`};if(Nt(n.cmd)&&!n.rest)return{kind:`error`,message:`Usage: ${n.cmd.name}${n.cmd.arg?` ${n.cmd.arg}`:``}`};try{await t[n.cmd.id](n.rest)}catch(e){return{kind:`error`,message:e instanceof Error?e.message:String(e??`Command failed`)}}return{kind:`handled`}}function yo({activeSid:e,activityEventsRef:t,notify:n,onClearEvents:r,onDispose:i,onOpenConfig:a,onOpenDoctor:o,onOpenHelp:s,onOpenIdentity:c,onOpenInspector:l,onOpenNewDaemon:u,onOpenOperations:d,onOpenSidebar:f,onReconnectEvents:p,onRenameProject:m,onRewriteDraft:h,onSelectProject:g,onSetArtifactPath:_,onSetEventFilter:v,onSetEventQuery:y,onSetTaskItemId:b,onSetWorkspaceView:x,onShowArtifacts:S,onStopIteration:C,onStopWaiting:w,refetchSnapshot:T}){return{status:async()=>l(),roles:async()=>d(),journal:async()=>l(),backlog:async()=>x(`mission`),item:async e=>{e&&b(e)},artifacts:async()=>S(),artifact:async e=>{e&&_(e)},events:async e=>{x(`activity`);let{filter:t,query:n}=Bt(e);v(t),y(n)},find:async e=>{x(`activity`),v(`all`),y(e)},run:async()=>x(`activity`),clear:async()=>{x(`activity`),v(`all`),y(``),r(t.current.length)},cancel:async()=>w(),task:async t=>{e&&(await R.addTask(e,t),T(),n(`success`,`Task queued.`))},rewrite:async e=>{let t=e.trim();if(!t){n(`info`,`Type your prompt in the composer and press Rewrite, or use /rewrite .`);return}h(t)},plan:async t=>{if(!e)return;let r=await R.previewPlan(e,t);r.error?n(`error`,r.error):n(`info`,r.steps.map(e=>e.title).join(` -`)||`Plan preview ready.`)},nudge:async t=>{e&&(await R.nudge(e,t),n(`success`,`Guidance injected.`))},abort:async t=>{e&&(await R.abortMission(e,t||`operator abort`),n(`info`,`Abort requested.`))},note:async t=>{e&&(await R.note(e,t),n(`success`,`Note appended to timeline.`))},done:async e=>{e&&i(e,`done`)},skip:async e=>{e&&i(e,`rm`)},stop:async e=>{e&&C(e)},new:async()=>u(),daemons:async()=>f(),resume:async e=>{e&&e!==`list`?g(e):f()},attach:async e=>{e&&g(e)},rename:async t=>{!e||!t||await m(t)},doctor:async()=>o(),backend:async t=>{if(!e||!t){a();return}await R.setConfig(e,`runner_backend`,t),n(`success`,`Backend set to ${t}.`)},config:async t=>{if(!e||!t){a();return}let r=t.indexOf(`=`);r>0?(await R.setConfig(e,t.slice(0,r).trim(),t.slice(r+1).trim()),n(`success`,`Config updated.`)):a()},identity:async()=>c(),reset:async()=>{e&&(await R.resetManager(e),n(`success`,`Manager context reset.`))},skills:async t=>{e&&n(`info`,(await R.skills(e,t||`ls`)).slice(0,400))},reconnect:async()=>p(),help:async()=>s(),quit:async()=>n(`info`,`Background work continues; close this browser tab when ready.`)}}function bo(e){return e.kind===`error`?(typeof e.reply==`string`?e.reply.trim():``)||`Manager could not handle this message.`:null}function xo(e,t){e.kind===`task`&&t.dispatchTask(e);let n=bo(e);n&&t.notifyError(n),t.refetchTranscript()}var So={skipFirst:0,reconnectKey:0};function Co(e,t){return t.kind===`clear`?{...e,skipFirst:Math.max(0,t.offset)}:t.kind===`reconnect`?{skipFirst:0,reconnectKey:e.reconnectKey+1}:{...e,skipFirst:0}}var wo=`local_request_id`;function To(e,t,n,r=Date.now()){return{type:`ui.operator`,agent_layer:`operator`,text:n,ts:r/1e3,event_id:`local-${e}-${t}-operator`,message_id:`local-${t}-operator`,[wo]:t}}function Eo(e,t,n,r,i,a=Date.now(),o=`auto`){let s=r.trim();if(!s)return e;let c=e.findIndex(e=>e.type===`ui.argus`&&Number(e[wo])===n),l=i.endsWith(`-argus`)?`${i.slice(0,-6)}-operator`:``,u=l?e.map(e=>e.type===`ui.operator`&&Number(e[wo])===n?{...e,message_id:l}:e):e,d=u.find(e=>e.type===`ui.operator`&&Number(e[wo])===n),f=d?Math.max(0,a-Number(d.ts??a/1e3)*1e3):0;if(c<0)return[...u,{type:`ui.argus`,agent_layer:`manager`,text:s,ts:a/1e3,event_id:`local-${t}-${n}-argus`,message_id:i||`local-${n}-argus`,fragment_mode:o,response_latency_ms:f,[wo]:n}];let p=u[c],m=[...u];return m[c]={...p,text:Dt(String(p.text??``),s,o),message_id:i||p.message_id,fragment_mode:o},m}function Do(e,t,n){let r=new Map;e.forEach(e=>{let t=String(e.type??``);if(t!==`ui.operator`&&t!==`ui.argus`)return;let n=`${t}\u0000${String(e.text??``)}`;r.set(n,(r.get(n)??0)+1)});let i=t.map(e=>({type:e.role===`operator`?`ui.operator`:`ui.argus`,agent_layer:e.role===`operator`?`operator`:`manager`,text:e.text,ts:e.ts,message_id:`transcript-${e.ts}-${e.role}`})),a=Array(i.length).fill(!0);for(let e=i.length-1;e>=0;--e){let t=i[e],n=`${String(t.type)}\u0000${String(t.text??``)}`,o=r.get(n)??0;o>0&&(a[e]=!1,r.set(n,o-1))}let o=[...i.filter((e,t)=>a[t]),...e],s=Array(o.length).fill(!0),c=new Set,l=n.filter(e=>{let t=String(e.message_id??``),n=t?o.findIndex((e,n)=>!c.has(n)&&String(e.message_id??``)===t):-1,r=Number(e.ts??0);return n<0&&(n=o.findIndex((t,n)=>{if(c.has(n)||t.type!==e.type||t.text!==e.text)return!1;let i=Number(t.ts??0);return Math.abs(i-r)<=5})),n>=0&&(c.add(n),s[n]=!1),!0});return[...o.filter((e,t)=>s[t]),...l].sort((e,t)=>Number(e.ts??0)-Number(t.ts??0))}function Oo(e,t){if(!t.length)return e;let n=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=n.get(e.id);return t?{...e,spend_usd:t.spend_usd,known_cost_usd:t.known_cost_usd,spend_status:t.spend_status,usage_calls:t.usage_calls,premium_requests:t.premium_requests,cost_updated_at:t.updated_at}:e})}async function ko(e,t,n,r=``){let i=await e.createDaemon(``,t,r),a=n.trim();return{created:i,startCampaign:a?()=>e.setContinuous(i.sid,!0,a):null}}var Ao=e=>e instanceof Error?e.message:String(e||`Unknown error`);function jo({localCwd:e,notify:t,onFocusComposer:n,queryClient:r,refetchProjects:i,selectProject:a}){let[o,s]=(0,M.useState)(!1),c=(0,M.useRef)(!1);return{createDaemon:async(o,l,u)=>{if(c.current)return!1;c.current=!0,s(!0);try{let{created:s,startCampaign:c}=await ko(R,o,l,u),d=String(s.workdir||u||``);return r.setQueryData([`projects`],t=>({local_cwd:t?.local_cwd??e,projects:[{id:s.sid,label:o||s.sid,display_name:o,objective:``,launch_cwd:d,workdir:d,last_active:Date.now()/1e3,daemon_alive:!1,daemon_pid:null,uptime_seconds:null},...(t?.projects??[]).filter(e=>e.id!==s.sid)]})),a(s.sid),i(),window.setTimeout(n,0),t(c?`info`:`success`,c?`Session created and selected. Campaign is starting in the background.`:`Session created and selected.`),c&&c().then(()=>{r.invalidateQueries({queryKey:[`snapshot`,s.sid]}),i(),t(`success`,`Campaign started.`)}).catch(e=>{t(`error`,`Session was created, but the campaign could not start: ${Ao(e)}`)}),!0}catch(e){return t(`error`,`Could not create session: ${Ao(e)}`),!1}finally{c.current=!1,s(!1)}},creatingDaemon:o}}var Mo=e=>e instanceof Error?e.message:String(e||`Unknown error`);function No({actions:e,activeSid:t,clearProjectSelection:n,continuous:r,currentSnapshotSid:i,notify:a,refetchProjects:o,selectProject:s,setDaemonManageOpen:c}){let[l,u]=(0,M.useState)(null),d=e.startDaemon.isPending||e.stopDaemon.isPending||e.updateProject.isPending||e.deleteProject.isPending,f=(0,M.useCallback)(e=>({onSuccess:()=>a(`success`,e),onError:e=>a(`error`,Mo(e))}),[a]),p=(0,M.useCallback)(()=>e.startDaemon.mutate(void 0,f(`Daemon start requested.`)),[f,e.startDaemon]),m=(0,M.useCallback)(()=>e.stopDaemon.mutate(!1,f(`Pause requested; the current operation is being interrupted.`)),[f,e.stopDaemon]),h=(0,M.useCallback)(async()=>{try{return await e.startDaemon.mutateAsync(),a(`success`,`Daemon resumed.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.startDaemon,a]),g=(0,M.useCallback)(async()=>{try{return await e.stopDaemon.mutateAsync(!1),a(`success`,`Daemon paused. Progress remains resumable.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.stopDaemon,a]),_=(0,M.useCallback)(async n=>{if(!t)return!1;try{return await e.updateProject.mutateAsync({sid:t,name:n}),a(`success`,`Session name updated.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.updateProject,t,a]),v=(0,M.useCallback)(async()=>{if(!t)return!1;try{let t=await e.deleteProject.mutateAsync();c(!1),n(`replace`);let r=Gt((await o()).data?.projects??[])[0];return r&&s(r.id,`replace`),a(`success`,t.workdir_preserved?`Session moved to recoverable trash. Files remain in ${t.workdir}.`:`Session moved to recoverable trash.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.deleteProject,t,n,a,o,s,c]),y=(0,M.useCallback)(e=>{if(c(!1),e===t&&i===e){u(null),c(!0);return}u(e),s(e)},[t,i,s,c]);return(0,M.useEffect)(()=>{!l||t!==l||i!==l||(u(null),c(!0))},[t,i,l,c]),{daemonBusy:d,manageDeleteProject:v,managePauseDaemon:g,manageRenameProject:_,manageStartDaemon:h,requestDispose:(0,M.useCallback)((t,n)=>e.disposeBacklog.mutate({id:t,op:n},{onSuccess:()=>a(`success`,n===`done`?`Work marked done.`:`Work removed.`),onError:e=>a(`error`,Mo(e))}),[e.disposeBacklog,a]),requestManageSession:y,requestStartDaemon:p,requestStopDaemon:m,requestStopIteration:(0,M.useCallback)(t=>e.stopBacklog.mutate(t,{onSuccess:()=>a(`success`,`Iteration stopped.`),onError:e=>a(`error`,Mo(e))}),[e.stopBacklog,a]),toggleContinuous:(0,M.useCallback)(()=>{if(!r)return;let t=!r.enabled;e.setContinuous.mutate({enabled:t,objective:r.objective},f(t?`Continuous campaign enabled.`:`Continuous campaign stopped.`))},[f,e.setContinuous,r])}}function Po({focusComposer:e,openHelp:t,toggleKiosk:n,togglePalette:r,toggleReasoning:i,toggleSidebarCollapse:a}){(0,M.useEffect)(()=>{let o=o=>{let s=o.target,c=s?.tagName===`INPUT`||s?.tagName===`TEXTAREA`,l=o.metaKey||o.ctrlKey;l&&o.key.toLowerCase()===`k`?(o.preventDefault(),r()):l&&o.key.toLowerCase()===`t`?(o.preventDefault(),i()):l&&o.key===`.`?(o.preventDefault(),n()):l&&o.key.toLowerCase()===`b`?(o.preventDefault(),a()):l&&o.key.toLowerCase()===`j`?(o.preventDefault(),e()):!c&&o.key===`?`?(o.preventDefault(),t()):!c&&o.key===`/`&&(o.preventDefault(),e())};return window.addEventListener(`keydown`,o),()=>window.removeEventListener(`keydown`,o)},[e,t,n,r,i,a])}var Fo=e=>e instanceof Error?e.message:String(e||`Unknown error`);function Io({activeSid:e,backlog:t,notify:n,pendingQuestions:r,refetchSnapshot:i}){let[a,o]=(0,M.useState)(!1),[s,c]=(0,M.useState)(!1),l=(0,M.useRef)(``),u=(0,M.useMemo)(()=>{let e=(t??[]).map(e=>({...e,operator_decision:e.operator_decision}));return ht(r??[],e)[0]??null},[t,r]);return(0,M.useEffect)(()=>{if(!u||!e){o(!1);return}let t=`${e}:${u.id}`;l.current!==t&&(l.current=t,o(!0))},[e,u]),{answerPendingReply:async(t,r)=>{if(!(!e||!u||s)){c(!0);try{let a=u.legacy?await R.answerPending(e,u.item_id,r):await R.resolveDecision(e,u.id,t,r);if(a.resolved===!1){n(`info`,String(a.reply||`Manager needs a more specific answer.`));return}o(!1),await i(),a.daemon&&Number(a.daemon.rc??0)!==0?n(`error`,`Answer queued, but the daemon did not start: ${a.daemon.error||`operator action required`}`):n(`success`,String(a.reply||`Manager delivered your answer to the team.`))}catch(e){await i(),n(`error`,`Could not send answer: ${Fo(e)}`)}finally{c(!1)}}},pendingReply:u,pendingReplyBusy:s,pendingReplyOpen:a,setPendingReplyOpen:o}}var Lo=`argus.browser.project.v1`;function Ro(){try{return window.sessionStorage.getItem(Lo)}catch{return null}}function zo(e){try{e?window.sessionStorage.setItem(Lo,e):window.sessionStorage.removeItem(Lo)}catch{}}function Bo(e,t){let n=new URL(window.location.href);e?n.searchParams.set(`project`,e):n.searchParams.delete(`project`);let r=t===`push`?`pushState`:`replaceState`;window.history[r](window.history.state,``,n.toString())}function Vo({cancelActiveMessage:e,notify:t,projects:n,projectsError:r,projectsReady:i,queryClient:a,setArtifactPath:o,setSidebarOpen:s,setTaskItemId:c}){let l=new URLSearchParams(window.location.search),[u,d]=(0,M.useState)(l.get(`project`)||Ro()),f=(0,M.useRef)(u),p=(0,M.useRef)(!1);f.current=u;let m=(0,M.useCallback)(t=>{t!==f.current&&(e(),o(null),c(null)),f.current=t,d(t),zo(t)},[e,o,c]),h=(0,M.useCallback)((e,t=`push`)=>{let n=new URLSearchParams(window.location.search).get(`project`);m(e),n!==e&&Bo(e,t)},[m]),g=(0,M.useCallback)((e=`replace`)=>{let t=new URLSearchParams(window.location.search).get(`project`);m(null),t!=null&&Bo(null,e)},[m]),_=(0,M.useCallback)(e=>{a.prefetchQuery({queryKey:[`snapshot`,e],queryFn:({signal:t})=>R.snapshot(e,t),staleTime:3e3})},[a]);return(0,M.useEffect)(()=>{if(!i)return;let e=p.current,r=Jt(n,f.current,e);if(!e&&(p.current=!0,r.id===f.current?zo(r.id):m(r.id),new URLSearchParams(window.location.search).get(`project`)!==r.id&&Bo(r.id,`replace`),r.recovered)){let e=n.find(e=>e.id===r.id);t(`info`,e?`Project “${r.requested}” was not found. Switched to ${e.label||e.id}.`:`Project “${r.requested}” was not found. Create a daemon to continue.`)}},[m,t,n,i]),(0,M.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`project`);if(s(!1),!e){m(null);return}if(!i){m(e);return}let r=qt(n,e);if(m(r.id),r.recovered){Bo(r.id,`replace`);let e=n.find(e=>e.id===r.id);t(`info`,e?`Project “${r.requested}” was not found. Switched to ${e.label||e.id}.`:`Project “${r.requested}” was not found. Create a daemon to continue.`)}};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[m,t,n,i,s]),{activateProject:m,activeSid:i?u&&n.some(e=>e.id===u)?u:null:r?u:null,clearProjectSelection:g,prefetchProject:_,selectProject:h,sid:u,sidRef:f}}function Ho(e,t){let n=localStorage.getItem(e);return n==null?t:n===`true`}function Uo(){let e=new URLSearchParams(window.location.search),[t,n]=(0,M.useState)(e.get(`kiosk`)===`1`),[r,i]=(0,M.useState)(()=>Ho(`argus.reasoning.visible.v1`,!1)),[a,o]=(0,M.useState)(()=>{let e=localStorage.getItem(`argus.workspace.view`);return e===`mission`||e===`workbench`?e:`activity`}),[s,c]=(0,M.useState)(`activity`),[l,u]=(0,M.useState)(()=>Ho(`argus.preview.expanded.v5`,!0)),[d,f]=(0,M.useState)(()=>{let e=Number(localStorage.getItem(`argus.sidebar.width.v2`)||256);return Number.isFinite(e)?Math.max(220,Math.min(400,e)):256}),[p,m]=(0,M.useState)(()=>{let e=Number(localStorage.getItem(`argus.preview.width.v2`)||440);return Number.isFinite(e)?Math.max(320,Math.min(600,e)):440}),[h,g]=(0,M.useState)(!1),[_,v]=(0,M.useState)(()=>Ho(`argus.sidebar.expanded.v4`,!0)),[y,b]=(0,M.useState)(()=>{let e=localStorage.getItem(`argus.theme`);return e===`light`||e===`dark`?e:null}),[x,S]=(0,M.useState)(()=>window.matchMedia(`(prefers-color-scheme: dark)`).matches),C=y??(x?`dark`:`light`),w=(0,M.useRef)(null),T=(0,M.useRef)(null);(0,M.useEffect)(()=>{localStorage.setItem(`argus.sidebar.expanded.v4`,String(_)),localStorage.setItem(`argus.preview.expanded.v5`,String(l)),localStorage.setItem(`argus.sidebar.width.v2`,String(d)),localStorage.setItem(`argus.preview.width.v2`,String(p))},[_,d,l,p]),(0,M.useEffect)(()=>{localStorage.setItem(`argus.workspace.view`,a)},[a]),(0,M.useEffect)(()=>{localStorage.setItem(`argus.reasoning.visible.v1`,String(r))},[r]),(0,M.useEffect)(()=>{let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=()=>S(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,M.useEffect)(()=>{document.documentElement.dataset.theme=C},[C]),(0,M.useEffect)(()=>{let e=()=>{document.documentElement.dataset.pageVisible=String(!document.hidden)};return e(),document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let ee=(0,M.useCallback)(()=>{let e=C===`light`?`dark`:`light`;b(e),localStorage.setItem(`argus.theme`,e)},[C]),te=(0,M.useCallback)((e,t)=>{let n=w.current;if(!n)return;t.preventDefault();let r=n.getBoundingClientRect();document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;let i=t=>{T.current!=null&&window.cancelAnimationFrame(T.current),T.current=window.requestAnimationFrame(()=>{if(e===`left`){let e=l?p+8:56,n=Math.max(220,Math.min(400,r.width-e-360-8));f(Math.max(220,Math.min(n,t.clientX-r.left)))}else{let e=_?d+8:56,n=Math.max(320,Math.min(600,r.width-e-360-8));m(Math.max(320,Math.min(n,r.right-t.clientX)))}})},a=()=>{T.current!=null&&window.cancelAnimationFrame(T.current),T.current=null,document.body.style.cursor=``,document.body.style.userSelect=``,window.removeEventListener(`pointermove`,i),window.removeEventListener(`pointerup`,a),window.removeEventListener(`pointercancel`,a)};window.addEventListener(`pointermove`,i),window.addEventListener(`pointerup`,a,{once:!0}),window.addEventListener(`pointercancel`,a,{once:!0})},[_,d,l,p]);return(0,M.useEffect)(()=>{let e=()=>{if(window.innerWidth<1024||!w.current)return;let e=w.current.clientWidth,t=_?d:56,n=l?p:56,r=(_?8:0)+(l?8:0),i=Math.max(540,e-360-r);if(t+n<=i)return;let a=l?Math.max(320,Math.min(p,i-t)):n,o=_?Math.max(220,Math.min(d,i-a)):t;o+a>i&&l&&(a=Math.max(320,i-o)),_&&f(o),l&&m(a)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[_,d,l,p]),{cycleTheme:ee,kiosk:t,leftPanelOpen:_,leftWidth:d,mobileView:s,resizeSidebar:te,rightPanelOpen:l,rightWidth:p,setKiosk:n,setLeftPanelOpen:v,setLeftWidth:f,setMobileView:c,setRightPanelOpen:u,setRightWidth:m,setShowReasoning:i,setSidebarOpen:g,setWorkspaceView:o,shellRef:w,showReasoning:r,sidebarOpen:h,themeMode:C,workspaceView:a}}function Wo({error:e,onRetry:t}){let{t:n}=q(),r=Ye(e),i=e instanceof Je;return!r&&!i?null:(0,K.jsxs)(`div`,{role:`alert`,className:`fixed left-1/2 top-3 z-[100] flex w-[min(92vw,42rem)] -translate-x-1/2 items-start gap-3 rounded-xl border border-err/50 bg-panel/95 px-4 py-3 text-left text-sm text-ink shadow-xl backdrop-blur`,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`,className:`mt-0.5 font-mono font-bold text-err`,children:`!`}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(`strong`,{className:`block text-err`,children:n(r?`connection.pairingTitle`:`connection.unreachableTitle`)}),(0,K.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-ink-dim`,children:n(r?`connection.pairingDetail`:`connection.unreachableDetail`)})]}),r?null:(0,K.jsx)(`button`,{type:`button`,onClick:t,className:`shrink-0 rounded-md border border-err/40 px-2.5 py-1 text-xs text-err hover:bg-err/10`,children:n(`common.retry`)})]})}var Go=0,Ko=(0,M.lazy)(async()=>({default:(await Jr(()=>import(`./ResearchWorkbenchPanel-D4WnlzR6.js`),__vite__mapDeps([2,1,3,4,5,6]))).ResearchWorkbenchPanel}));function qo(){let{locale:e,t}=q(),n=se(),r=fr(),i=pr(),a=(0,M.useMemo)(()=>Gt(Oo(r.data?.projects??[],i.data?.projects??[])),[i.data?.projects,r.data?.projects]),s=r.data?.local_cwd??``,c=[r.error,i.error].find(e=>Xe(e)),[l,u]=(0,M.useState)(`none`),{cycleTheme:d,kiosk:f,leftPanelOpen:p,leftWidth:m,mobileView:h,resizeSidebar:g,rightPanelOpen:_,rightWidth:v,setKiosk:y,setLeftPanelOpen:b,setLeftWidth:x,setMobileView:S,setRightPanelOpen:w,setRightWidth:T,setShowReasoning:ee,setSidebarOpen:te,setWorkspaceView:E,shellRef:ne,showReasoning:re,sidebarOpen:ie,themeMode:ae,workspaceView:D}=Uo(),[O,oe]=(0,M.useState)(()=>D===`mission`?`mission`:`activity`),[ce,k]=(0,M.useState)(D===`workbench`);(0,M.useEffect)(()=>{if(D===`workbench`){k(!0);return}oe(D)},[D]),_o();let[le,A]=(0,M.useState)(0),[ue,de]=(0,M.useState)(``),[fe,j]=(0,M.useState)(!1),[pe,me]=(0,M.useState)(0),[he,ge]=(0,M.useState)(!1),[_e,ve]=(0,M.useState)([]),[ye,be]=(0,M.useState)(``),[xe,Se]=(0,M.useState)(!1),[Ce,we]=(0,M.useState)(0),[Te,Ee]=(0,M.useState)([]),[De,Oe]=(0,M.useState)(0),[ke,Ae]=(0,M.useState)(null),[je,Me]=(0,M.useState)(null),[Ne,Pe]=(0,M.useState)(!1),[Fe,Ie]=(0,M.useState)(!1),Le=(0,M.useRef)(null),Re=(0,M.useRef)(0),[ze,Be]=(0,M.useState)(null),[Ve,He]=(0,M.useReducer)(Co,So),[Ue,We]=(0,M.useState)(`all`),[Ge,Ke]=(0,M.useState)(``),qe=(0,M.useCallback)(()=>Be(null),[]),N=(0,M.useCallback)((e,t)=>{Be({id:++Go,tone:e,message:t})},[]),Je=(0,M.useCallback)(()=>{let e=!!Le.current;return Re.current+=1,Le.current?.controller.abort(),Le.current=null,ge(!1),be(``),Se(!1),we(0),Ee([]),Oe(0),e},[]),Ye=(0,M.useCallback)(()=>{Je()&&N(`info`,`Stopped waiting for this reply. Server-side work may still finish in the project timeline.`)},[Je,N]),{activeSid:P,clearProjectSelection:Ze,prefetchProject:Qe,selectProject:F,sidRef:$e}=Vo({cancelActiveMessage:Je,notify:N,projects:a,projectsError:r.isError,projectsReady:r.isSuccess,queryClient:n,setArtifactPath:Ae,setSidebarOpen:te,setTaskItemId:Me});(0,M.useEffect)(()=>()=>{Re.current+=1,Le.current?.controller.abort(),Le.current=null},[]);let et=(0,M.useCallback)(e=>{let t=(e||``).trim(),n=$e.current;!t||!n||fe||(j(!0),R.rewritePrompt(n,t).then(e=>{if(j(!1),e.error||!e.rewritten.trim()){N(`error`,`Rewrite failed: ${e.error||`empty rewrite`} — your prompt is unchanged`);return}de(e.rewritten),A(e=>e+1);let t=e.questions.length?` Manager asks: ${e.questions.join(` · `)}`:``;N(`success`,`Prompt rewritten — review it, then send.${t}`)},e=>{j(!1),N(`error`,`Rewrite failed: ${ii(e)} — your prompt is unchanged`)}))},[N,fe,$e]),{createDaemon:tt,creatingDaemon:nt}=jo({localCwd:s,notify:N,onFocusComposer:()=>A(e=>e+1),queryClient:n,refetchProjects:r.refetch,selectProject:F}),I=mr(P),L=I.data,rt=L?.session.id===P?P:null,it=L?.continuous,at=br(rt,!0),ot=Sr(rt,O===`mission`),{events:st,connected:ct}=jr(rt,Ve.reconnectKey),lt=(0,M.useMemo)(()=>Or(st),[st]),z=(0,M.useMemo)(()=>Ar(st),[st]);(0,M.useEffect)(()=>{!rt||!lt||n.invalidateQueries({queryKey:[`artifacts`,rt],exact:!0})},[lt,rt,n]),(0,M.useEffect)(()=>{!rt||!z||n.invalidateQueries({queryKey:[`snapshot`,rt],exact:!0})},[rt,n,z]);let ut=(0,M.useMemo)(()=>Pn(st),[st]),dt=yr(rt,O===`activity`,120),ft=hr(P,20,l===`inspector`),{answerPendingReply:pt,pendingReply:mt,pendingReplyBusy:ht,pendingReplyOpen:B,setPendingReplyOpen:gt}=Io({activeSid:P,backlog:L?.backlog,notify:N,pendingQuestions:L?.pending_questions,refetchSnapshot:I.refetch}),_t=(0,M.useMemo)(()=>Do(st,dt.data??[],_e),[st,_e,dt.data]),vt=(0,M.useMemo)(()=>L?En(L,_t,at.data??[]):null,[_t,at.data,L]),yt=(0,M.useRef)(_t);yt.current=_t,(0,M.useEffect)(()=>{We(`all`),Ke(``),ve([]),He({kind:`reset`})},[rt]);let bt=wr(P,L?.daemon_commands?.revision),{daemonBusy:xt,manageDeleteProject:St,managePauseDaemon:Ct,manageRenameProject:wt,manageStartDaemon:Tt,requestDispose:Et,requestManageSession:Dt,requestStartDaemon:Ot,requestStopDaemon:kt,requestStopIteration:At,toggleContinuous:Mt}=No({actions:bt,activeSid:P,clearProjectSelection:Ze,continuous:it,currentSnapshotSid:L?.session.id,notify:N,refetchProjects:r.refetch,selectProject:F,setDaemonManageOpen:Ie}),Nt=(0,M.useCallback)(async e=>{if(!P)return;let t=await bt.updateProject.mutateAsync({sid:P,name:e});N(`success`,`Renamed to "${t.name}".`)},[bt.updateProject,P,N]),Pt=(0,M.useMemo)(()=>yo({activeSid:P,activityEventsRef:yt,notify:N,onClearEvents:e=>He({kind:`clear`,offset:e}),onDispose:Et,onOpenConfig:()=>u(`config`),onOpenDoctor:()=>u(`doctor`),onOpenHelp:()=>u(`help`),onOpenIdentity:()=>u(`identity`),onOpenInspector:()=>u(`inspector`),onOpenNewDaemon:()=>Pe(!0),onOpenOperations:()=>u(`operations`),onOpenSidebar:()=>te(!0),onReconnectEvents:()=>He({kind:`reconnect`}),onRenameProject:Nt,onRewriteDraft:et,onSelectProject:F,onSetArtifactPath:Ae,onSetEventFilter:We,onSetEventQuery:Ke,onSetTaskItemId:Me,onSetWorkspaceView:E,onShowArtifacts:()=>w(!0),onStopIteration:At,onStopWaiting:Ye,refetchSnapshot:I.refetch}),[P,N,Nt,Et,At,F,I.refetch,Ye,E]);Po({focusComposer:()=>A(e=>e+1),openHelp:()=>u(`help`),toggleKiosk:()=>y(e=>!e),togglePalette:()=>u(e=>e===`palette`?`none`:`palette`),toggleReasoning:()=>ee(e=>!e),toggleSidebarCollapse:()=>b(e=>!e)});let Ft=async(e,n=[])=>{let r=P;if(!r||Le.current)return!1;if(!n.length){let t=await vo(e,Pt);if(t.kind===`handled`)return!0;if(t.kind===`error`)return N(`error`,t.message),!1}let i=++Re.current,a=new AbortController;Le.current={id:i,sid:r,controller:a};let o=()=>{let e=Le.current;return!!(e&&e.id===i&&e.sid===r&&$e.current===r&&!a.signal.aborted)},s=()=>{Le.current?.id===i&&(Le.current=null,ge(!1),be(``),Se(!1),we(0),Oe(0),Ee([]))};ge(!0),be(n.length?t(`chat.uploadingAttachments`):``),Se(!1),we(0),Ee([]),Oe(Date.now());let c=[];if(n.length)try{let e=await R.uploadAttachments(r,n,a.signal);if(!o())return!1;c=e.attachments.map(e=>({attachment_id:e.attachment_id}))}catch(e){return o()&&(N(`error`,t(`chat.attachmentUploadFailed`,{error:ii(e)})),s()),!1}ve(t=>[...t,To(r,i,e)]);let l=(e,t=``,n=`auto`)=>{!o()||typeof e!=`string`||!e.trim()||ve(a=>Eo(a,r,i,e,t,Date.now(),n))},u=e=>{if(!o())return;let t=e.daemon&&typeof e.daemon==`object`?e.daemon:null,n=typeof e.reply==`string`?e.reply:null;t?.admission_required?N(`error`,n||`Task queued, but all daemon slots are busy: ${String(t.error||`operator action required`)}`):t&&Number(t.rc??0)!==0?N(`error`,n||`Task queued, but executor did not start: ${String(t.error||`unknown error`)}`):n&&N(`success`,n),I.refetch?.()},d=e=>{o()&&xo(e,{dispatchTask:u,notifyError:e=>N(`error`,e),refetchTranscript:()=>{dt.refetch()}})};return(async()=>{let t=!1,n=null,i=[];try{try{await R.messageStream(r,e,{onPhase:(e,t,n)=>{o()&&(be(e),Se(n.heartbeat),we(n.quietS),i=Gn(i,{label:e,role:t,kind:n.kind,detail:n.detail,heartbeat:n.heartbeat,quietS:n.quietS}),Ee(i))},onDelta:(e,n,r)=>{o()&&(t=!0,i=Kn(i),Ee(i),be(``),Se(!1),we(0),l(e,n,r===`append`||r===`snapshot`?r:`auto`))},onDone:e=>{o()&&(l(e.reply,``,`snapshot`),d(e))},onError:e=>{o()&&(n=e)}},{signal:a.signal,attachments:c})}catch(e){o()&&(n=e)}if(!o())return;n&&N(`error`,ai(n,t))}finally{s()}})(),!0},It=(0,M.useRef)(Ft);It.current=Ft;let Lt=(0,M.useMemo)(()=>{let n=oa(jt,e=>{It.current(e)},e=>{de(e),A(e=>e+1)},e),r=[...f?[]:[{id:`new`,label:t(`palette.newDaemon`),hint:`+`,group:t(`palette.view`),run:()=>Pe(!0)}],{id:`transcript`,label:t(`palette.openTranscript`),hint:`/transcript`,group:t(`palette.view`),run:()=>u(`transcript`)},{id:`inspector`,label:t(`palette.openProject`),hint:t(`palette.projectHint`),group:t(`palette.view`),run:()=>u(`inspector`)},{id:`operations`,label:t(`palette.openOperations`),hint:t(`palette.operationsHint`),group:t(`palette.view`),run:()=>u(`operations`)},{id:`help`,label:t(`help.title`),hint:`?`,group:t(`palette.view`),run:()=>u(`help`)},{id:`reasoning`,label:t(re?`palette.hideReasoning`:`palette.showReasoning`),hint:`⌘T`,group:t(`palette.view`),run:()=>ee(e=>!e)},{id:`kiosk`,label:t(f?`palette.exitKiosk`:`palette.enterKiosk`),hint:`⌘.`,group:t(`palette.view`),run:()=>y(e=>!e)}],i=f?[]:[{id:`message`,label:t(`palette.messageArgus`),hint:`/`,group:t(`palette.action`),run:()=>A(e=>e+1)},...he?[{id:`cancel-message`,label:t(`palette.stopWaiting`),hint:`Esc`,group:t(`palette.action`),run:Ye}]:[],...it?[{id:`continuous`,label:it.enabled?t(`palette.stopContinuous`):t(`palette.startContinuous`),group:t(`palette.action`),run:Mt}]:[],...L?.daemon.control_available===!1?[]:[L?.daemon.alive?{id:`stop`,label:t(`palette.stopDaemon`),group:t(`palette.action`),run:kt}:{id:`start`,label:t(`palette.startDaemon`),group:t(`palette.action`),run:Ot}]],o=a.map(e=>({id:`p-${e.id}`,label:e.label||e.id,hint:e.daemon_alive?`● ${t(`common.live`)}`:`○`,keywords:`${e.id} ${e.display_name??``} ${e.objective} ${e.daemon_alive?`live running`:`stopped idle`}`,group:t(`palette.project`),run:()=>F(e.id)}));return[...r,...i,...n,...o]},[a,L?.daemon.alive,f,re,it?.enabled,he,Ye,e,t]);return(0,K.jsxs)(`div`,{ref:ne,className:`workbench-shell ambient-canvas flex h-screen h-[100dvh] w-screen max-w-full overflow-hidden text-ink`,children:[(0,K.jsx)(Wo,{error:c,onRetry:()=>{r.refetch(),i.refetch()}}),!f&&ie?(0,K.jsx)(`button`,{type:`button`,"aria-label":t(`common.closeSessions`),onClick:()=>te(!1),className:`fixed inset-0 z-30 bg-black/40 lg:hidden`}):null,f?null:(0,K.jsx)(Ga,{projects:a,activeId:P,localCwd:s,onSelect:e=>{F(e),te(!1)},onPrefetch:Qe,onManage:Dt,onOpenPanel:e=>u(e),onNew:()=>Pe(!0),loading:r.isLoading,creating:nt,error:r.isError?ii(r.error):void 0,onRetry:()=>void r.refetch(),mobileOpen:ie,collapsed:!p,onToggleCollapse:()=>b(e=>!e),themeMode:ae,onCycleTheme:d,expandedWidth:m}),!f&&p?(0,K.jsx)(ro,{label:t(`common.resizeSessions`),value:m,min:220,max:400,onPointerDown:e=>g(`left`,e),onReset:()=>x(256),onNudge:e=>x(t=>Math.max(220,Math.min(400,t+e)))}):null,(0,K.jsx)(`main`,{className:`flex min-w-0 flex-1 overflow-x-hidden`,children:L?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`${h===`activity`?`flex`:`hidden`} glass-panel glass-panel--main h-full min-w-0 flex-1 flex-col lg:flex`,children:[(0,K.jsx)(Wr,{snap:L,streamOk:ct,onStart:Ot,onStop:kt,onManage:()=>Ie(!0),busy:xt,snapshotStale:I.isError,readOnly:f,missionView:vt}),(0,K.jsxs)(`div`,{className:`flex h-10 shrink-0 items-center gap-1 border-b border-line/60 px-3`,children:[(0,K.jsxs)(`div`,{className:`workspace-tabs`,"data-active":D,children:[(0,K.jsx)(`span`,{className:`workspace-tab-indicator`,"aria-hidden":`true`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(`mission`),className:`workspace-tab`,"data-selected":D===`mission`,children:t(`mobile.mission`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(`activity`),className:`workspace-tab`,"data-selected":D===`activity`,children:t(`mobile.activity`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(`workbench`),className:`workspace-tab`,"data-selected":D===`workbench`,children:t(`mobile.workbench`)})]}),D===`mission`?(0,K.jsx)(`span`,{className:`ml-auto hidden max-w-72 truncate text-[10px] text-ink-faint sm:block`,children:vt?.active_role?t(`mission.roleActive`,{role:vt.active_role}):t(`mission.overview`)}):(0,K.jsx)(`span`,{className:`ml-auto`}),f?null:(0,K.jsx)(`button`,{type:`button`,onClick:()=>u(`operations`),className:`rounded border border-line/60 px-2 py-1 text-[10px] text-ink-faint hover:border-blue/50 hover:text-blue`,children:t(`mission.operations`)})]}),(0,K.jsxs)(`div`,{className:`${D===`workbench`?`hidden`:`flex`} min-h-0 flex-1 flex-col`,children:[(0,K.jsx)(xa,{alert:ut}),O===`mission`&&vt?(0,K.jsx)(co,{view:vt,gitDiff:ot.data,onOpenArtifact:Ae}):(0,K.jsx)(Ni,{events:_t,connected:ct,showReasoning:re,onToggleReasoning:()=>ee(e=>!e),embedded:!0,filter:Ue,query:Ge,skipFirst:Ve.skipFirst}),f?null:(0,K.jsx)(`div`,{className:`composer-dock shrink-0 px-4 pt-3`,children:(0,K.jsxs)(`div`,{className:`mx-auto w-full max-w-full lg:max-w-[61.8vw]`,children:[(0,K.jsx)(ya,{questions:L.pending_questions??[],backlog:L.backlog,onAnswer:()=>gt(!0)}),(0,K.jsx)(ra,{value:ue,onChange:de,onSend:Ft,onCancel:Ye,disabled:!P,pending:he,focusSignal:le,embedded:!0,phase:ye,heartbeat:xe,quietS:Ce,steps:Te,startedAt:De,onRewrite:et,rewriting:fe,slashSelection:pe,onSlashSelectionChange:me},P||`no-session`)]})})]}),ce&&P?(0,K.jsx)(`div`,{className:`${D===`workbench`?`flex`:`hidden`} min-h-0 flex-1`,children:(0,K.jsx)(M.Suspense,{fallback:(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center text-xs text-ink-faint`,children:t(`common.loading`)}),children:(0,K.jsx)(Ko,{sid:P,active:D===`workbench`})})}):null]}),_?(0,K.jsx)(ro,{label:t(`common.resizePreview`),value:v,min:320,max:600,onPointerDown:e=>g(`right`,e),onReset:()=>T(440),onNudge:e=>T(t=>Math.max(320,Math.min(600,t-e)))}):null,(0,K.jsxs)(`aside`,{style:{"--preview-width":`${v}px`},className:`${h===`preview`?`flex`:`hidden`} relative min-w-0 flex-1 flex-col overflow-hidden border-l border-line/60 bg-panel transition-[width] duration-[250ms] ease-panel lg:flex lg:flex-none ${_?`lg:w-[var(--preview-width)]`:`lg:w-14`}`,children:[(0,K.jsx)(`div`,{className:`lg:hidden`,children:(0,K.jsx)(Wr,{snap:L,streamOk:ct,onStart:Ot,onStop:kt,onManage:()=>Ie(!0),busy:xt,snapshotStale:I.isError,readOnly:f,missionView:vt})}),(0,K.jsx)(Ba,{sid:rt,artifacts:at.data,error:at.isError,onExpand:Ae,className:`min-h-0 flex-1 mobile-scroll-region ${_?`lg:flex`:`lg:hidden`}`,embedded:!0,onCollapse:()=>w(!1),missionView:vt,activityEvents:_t}),_?null:(0,K.jsx)(`div`,{className:`hidden h-12 items-center justify-center border-b border-line/50 text-ink-faint lg:flex`,children:(0,K.jsx)(`button`,{type:`button`,onClick:()=>w(!0),"aria-label":t(`common.expandPreview`),title:t(`common.expandPreview`),className:`flex h-8 w-8 items-center justify-center rounded-md border border-line/50 bg-bg/40 hover:border-blue/50 hover:text-ink`,children:(0,K.jsx)(o,{icon:C,className:`h-3.5 w-3.5`})})})]})]}):(0,K.jsx)(ho,{loading:r.isLoading||!!(P&&I.isLoading),hasProjects:a.length>0,error:r.isError&&a.length===0?ii(r.error):I.isError&&!L?ii(I.error):void 0,onRetry:()=>{r.refetch(),P&&I.refetch()},onNew:()=>Pe(!0),onChoose:()=>te(!0),canCreate:!f})}),(0,K.jsx)(ca,{open:l===`palette`,onClose:()=>u(`none`),items:Lt}),(0,K.jsx)(ua,{open:l===`help`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(ga,{sid:P,open:l===`doctor`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(_a,{sid:P,open:l===`config`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(Z,{sid:P,open:l===`identity`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(va,{sid:P,open:l===`transcript`,onClose:()=>u(`none`)}),P&&L?(0,K.jsx)($a,{open:l===`inspector`,snap:L,journal:ft.data??[],busy:bt.disposeBacklog.isPending||bt.stopBacklog.isPending,onClose:()=>u(`none`),onDispose:Et,onStop:At,onInspect:Me}):null,P&&L?(0,K.jsx)(fo,{open:l===`operations`,sid:P,snap:L,onClose:()=>u(`none`),onChanged:()=>{I.refetch(),r.refetch()},onRestored:async e=>{await r.refetch(),F(e)}}):null,(0,K.jsx)(Da,{sid:P,path:ke,onClose:()=>Ae(null)}),(0,K.jsx)(no,{sid:P,itemId:je,onClose:()=>Me(null),onDone:e=>Et(e,`done`),onSkip:e=>Et(e,`rm`),onStop:At,busy:bt.disposeBacklog.isPending||bt.stopBacklog.isPending,readOnly:f}),(0,K.jsx)(Ha,{open:Ne,busy:nt,onClose:()=>Pe(!1),onCreate:tt}),(0,K.jsx)(ba,{reply:mt,open:B,busy:ht,onClose:()=>gt(!1),onSubmit:pt}),P&&L?(0,K.jsx)(Ua,{open:Fe,sid:P,name:L.session.display_name||``,alive:L.daemon.alive,controlAvailable:L.daemon.control_available!==!1,busy:xt,onClose:()=>Ie(!1),onRename:wt,onStart:Tt,onPause:Ct,onDelete:St}):null,(0,K.jsx)(Va,{notice:ze,onClose:qe}),L&&!f?(0,K.jsx)(go,{active:h===`preview`?`preview`:D,onSelect:e=>{if(e===`preview`){S(`preview`);return}S(`activity`),E(e)},onOpenSessions:()=>te(!0)}):null]})}function Jo({onDone:e}){let{t}=q(),n=(0,M.useRef)(!1),r=(0,M.useCallback)(()=>{n.current||(n.current=!0,e())},[e]);return(0,M.useEffect)(()=>{let e=window.setTimeout(r,330),t=()=>r();return window.addEventListener(`keydown`,t,{once:!0}),()=>{window.clearTimeout(e),window.removeEventListener(`keydown`,t)}},[r]),(0,K.jsxs)(`div`,{role:`status`,"aria-label":t(`splash.starting`),onClick:r,onAnimationEnd:e=>{e.currentTarget===e.target&&r()},className:`argus-web-splash`,children:[(0,K.jsx)(`div`,{className:`argus-web-splash-logo argus-web-splash-logo-full`,"aria-hidden":`true`,children:(0,K.jsx)(Ci,{size:72})}),(0,K.jsx)(`div`,{className:`argus-web-splash-logo argus-web-splash-logo-compact`,"aria-hidden":`true`,children:(0,K.jsx)(xi,{size:112})})]})}He();var Yo=new Ee({defaultOptions:{queries:{staleTime:3e3,retry:ur,refetchOnWindowFocus:!1}}});function Xo(){let[e,t]=(0,M.useState)(!0);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(qo,{}),e?(0,K.jsx)(Jo,{onDone:()=>t(!1)}):null]})}De.createRoot(document.getElementById(`root`)).render((0,K.jsx)(M.StrictMode,{children:(0,K.jsx)(de,{client:Yo,children:(0,K.jsx)(Vr,{children:(0,K.jsx)(Xo,{})})})}));export{ot as a,Ge as i,q as n,Ze as o,We as r,Jr as t}; \ No newline at end of file +`)||`Plan preview ready.`)},nudge:async t=>{e&&(await R.nudge(e,t),n(`success`,`Guidance injected.`))},abort:async t=>{e&&(await R.abortMission(e,t||`operator abort`),n(`info`,`Abort requested.`))},note:async t=>{e&&(await R.note(e,t),n(`success`,`Note appended to timeline.`))},done:async e=>{e&&i(e,`done`)},skip:async e=>{e&&i(e,`rm`)},stop:async e=>{e&&C(e)},new:async()=>u(),daemons:async()=>f(),resume:async e=>{e&&e!==`list`?g(e):f()},attach:async e=>{e&&g(e)},rename:async t=>{!e||!t||await m(t)},doctor:async()=>o(),backend:async t=>{if(!e||!t){a();return}await R.setConfig(e,`runner_backend`,t),n(`success`,`Backend set to ${t}.`)},config:async t=>{if(!e||!t){a();return}let r=t.indexOf(`=`);r>0?(await R.setConfig(e,t.slice(0,r).trim(),t.slice(r+1).trim()),n(`success`,`Config updated.`)):a()},identity:async()=>c(),reset:async()=>{e&&(await R.resetManager(e),n(`success`,`Manager context reset.`))},skills:async t=>{e&&n(`info`,(await R.skills(e,t||`ls`)).slice(0,400))},reconnect:async()=>p(),help:async()=>s(),quit:async()=>n(`info`,`Background work continues; close this browser tab when ready.`)}}function bo(e){return e.kind===`error`?(typeof e.reply==`string`?e.reply.trim():``)||`Manager could not handle this message.`:null}function xo(e,t){e.kind===`task`&&t.dispatchTask(e);let n=bo(e);n&&t.notifyError(n),t.refetchTranscript()}var So={skipFirst:0,reconnectKey:0};function Co(e,t){return t.kind===`clear`?{...e,skipFirst:Math.max(0,t.offset)}:t.kind===`reconnect`?{skipFirst:0,reconnectKey:e.reconnectKey+1}:{...e,skipFirst:0}}var wo=`local_request_id`;function To(e,t,n,r=Date.now()){return{type:`ui.operator`,agent_layer:`operator`,text:n,ts:r/1e3,event_id:`local-${e}-${t}-operator`,message_id:`local-${t}-operator`,[wo]:t}}function Eo(e,t,n,r,i,a=Date.now(),o=`auto`){let s=r.trim();if(!s)return e;let c=e.findIndex(e=>e.type===`ui.argus`&&Number(e[wo])===n),l=i.endsWith(`-argus`)?`${i.slice(0,-6)}-operator`:``,u=l?e.map(e=>e.type===`ui.operator`&&Number(e[wo])===n?{...e,message_id:l}:e):e,d=u.find(e=>e.type===`ui.operator`&&Number(e[wo])===n),f=d?Math.max(0,a-Number(d.ts??a/1e3)*1e3):0;if(c<0)return[...u,{type:`ui.argus`,agent_layer:`manager`,text:s,ts:a/1e3,event_id:`local-${t}-${n}-argus`,message_id:i||`local-${n}-argus`,fragment_mode:o,response_latency_ms:f,[wo]:n}];let p=u[c],m=[...u];return m[c]={...p,text:Dt(String(p.text??``),s,o),message_id:i||p.message_id,fragment_mode:o},m}function Do(e,t,n){let r=new Map;e.forEach(e=>{let t=String(e.type??``);if(t!==`ui.operator`&&t!==`ui.argus`)return;let n=`${t}\u0000${String(e.text??``)}`;r.set(n,(r.get(n)??0)+1)});let i=t.map(e=>({type:e.role===`operator`?`ui.operator`:`ui.argus`,agent_layer:e.role===`operator`?`operator`:`manager`,text:e.text,ts:e.ts,message_id:`transcript-${e.ts}-${e.role}`})),a=Array(i.length).fill(!0);for(let e=i.length-1;e>=0;--e){let t=i[e],n=`${String(t.type)}\u0000${String(t.text??``)}`,o=r.get(n)??0;o>0&&(a[e]=!1,r.set(n,o-1))}let o=[...i.filter((e,t)=>a[t]),...e],s=Array(o.length).fill(!0),c=new Set,l=n.filter(e=>{let t=String(e.message_id??``),n=t?o.findIndex((e,n)=>!c.has(n)&&String(e.message_id??``)===t):-1,r=Number(e.ts??0);return n<0&&(n=o.findIndex((t,n)=>{if(c.has(n)||t.type!==e.type||t.text!==e.text)return!1;let i=Number(t.ts??0);return Math.abs(i-r)<=5})),n>=0&&(c.add(n),s[n]=!1),!0});return[...o.filter((e,t)=>s[t]),...l].sort((e,t)=>Number(e.ts??0)-Number(t.ts??0))}function Oo(e,t){if(!t.length)return e;let n=new Map(t.map(e=>[e.id,e]));return e.map(e=>{let t=n.get(e.id);return t?{...e,spend_usd:t.spend_usd,known_cost_usd:t.known_cost_usd,spend_status:t.spend_status,usage_calls:t.usage_calls,premium_requests:t.premium_requests,cost_updated_at:t.updated_at}:e})}async function ko(e,t,n,r=``){let i=await e.createDaemon(``,t,r),a=n.trim();return{created:i,startCampaign:a?()=>e.setContinuous(i.sid,!0,a):null}}var Ao=e=>e instanceof Error?e.message:String(e||`Unknown error`);function jo({localCwd:e,notify:t,onFocusComposer:n,queryClient:r,refetchProjects:i,selectProject:a}){let[o,s]=(0,M.useState)(!1),c=(0,M.useRef)(!1);return{createDaemon:async(o,l,u)=>{if(c.current)return!1;c.current=!0,s(!0);try{let{created:s,startCampaign:c}=await ko(R,o,l,u),d=String(s.workdir||u||``);return r.setQueryData([`projects`],t=>({local_cwd:t?.local_cwd??e,projects:[{id:s.sid,label:o||s.sid,display_name:o,objective:``,launch_cwd:d,workdir:d,last_active:Date.now()/1e3,daemon_alive:!1,daemon_pid:null,uptime_seconds:null},...(t?.projects??[]).filter(e=>e.id!==s.sid)]})),a(s.sid),i(),window.setTimeout(n,0),t(c?`info`:`success`,c?`Session created and selected. Campaign is starting in the background.`:`Session created and selected.`),c&&c().then(()=>{r.invalidateQueries({queryKey:[`snapshot`,s.sid]}),i(),t(`success`,`Campaign started.`)}).catch(e=>{t(`error`,`Session was created, but the campaign could not start: ${Ao(e)}`)}),!0}catch(e){return t(`error`,`Could not create session: ${Ao(e)}`),!1}finally{c.current=!1,s(!1)}},creatingDaemon:o}}var Mo=e=>e instanceof Error?e.message:String(e||`Unknown error`);function No({actions:e,activeSid:t,clearProjectSelection:n,continuous:r,currentSnapshotSid:i,notify:a,refetchProjects:o,selectProject:s,setDaemonManageOpen:c}){let[l,u]=(0,M.useState)(null),d=e.startDaemon.isPending||e.stopDaemon.isPending||e.updateProject.isPending||e.deleteProject.isPending,f=(0,M.useCallback)(e=>({onSuccess:()=>a(`success`,e),onError:e=>a(`error`,Mo(e))}),[a]),p=(0,M.useCallback)(()=>e.startDaemon.mutate(void 0,f(`Daemon start requested.`)),[f,e.startDaemon]),m=(0,M.useCallback)(()=>e.stopDaemon.mutate(!1,f(`Pause requested; the current operation is being interrupted.`)),[f,e.stopDaemon]),h=(0,M.useCallback)(async()=>{try{return await e.startDaemon.mutateAsync(),a(`success`,`Daemon resumed.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.startDaemon,a]),g=(0,M.useCallback)(async()=>{try{return await e.stopDaemon.mutateAsync(!1),a(`success`,`Daemon paused. Progress remains resumable.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.stopDaemon,a]),_=(0,M.useCallback)(async n=>{if(!t)return!1;try{return await e.updateProject.mutateAsync({sid:t,name:n}),a(`success`,`Session name updated.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.updateProject,t,a]),v=(0,M.useCallback)(async()=>{if(!t)return!1;try{let t=await e.deleteProject.mutateAsync();c(!1),n(`replace`);let r=Gt((await o()).data?.projects??[])[0];return r&&s(r.id,`replace`),a(`success`,t.workdir_preserved?`Session moved to recoverable trash. Files remain in ${t.workdir}.`:`Session moved to recoverable trash.`),!0}catch(e){return a(`error`,Mo(e)),!1}},[e.deleteProject,t,n,a,o,s,c]),y=(0,M.useCallback)(e=>{if(c(!1),e===t&&i===e){u(null),c(!0);return}u(e),s(e)},[t,i,s,c]);return(0,M.useEffect)(()=>{!l||t!==l||i!==l||(u(null),c(!0))},[t,i,l,c]),{daemonBusy:d,manageDeleteProject:v,managePauseDaemon:g,manageRenameProject:_,manageStartDaemon:h,requestDispose:(0,M.useCallback)((t,n)=>e.disposeBacklog.mutate({id:t,op:n},{onSuccess:()=>a(`success`,n===`done`?`Work marked done.`:`Work removed.`),onError:e=>a(`error`,Mo(e))}),[e.disposeBacklog,a]),requestManageSession:y,requestStartDaemon:p,requestStopDaemon:m,requestStopIteration:(0,M.useCallback)(t=>e.stopBacklog.mutate(t,{onSuccess:()=>a(`success`,`Iteration stopped.`),onError:e=>a(`error`,Mo(e))}),[e.stopBacklog,a]),toggleContinuous:(0,M.useCallback)(()=>{if(!r)return;let t=!r.enabled;e.setContinuous.mutate({enabled:t,objective:r.objective},f(t?`Continuous campaign enabled.`:`Continuous campaign stopped.`))},[f,e.setContinuous,r])}}function Po({focusComposer:e,openHelp:t,toggleKiosk:n,togglePalette:r,toggleReasoning:i,toggleSidebarCollapse:a}){(0,M.useEffect)(()=>{let o=o=>{let s=o.target,c=s?.tagName===`INPUT`||s?.tagName===`TEXTAREA`,l=o.metaKey||o.ctrlKey;l&&o.key.toLowerCase()===`k`?(o.preventDefault(),r()):l&&o.key.toLowerCase()===`t`?(o.preventDefault(),i()):l&&o.key===`.`?(o.preventDefault(),n()):l&&o.key.toLowerCase()===`b`?(o.preventDefault(),a()):l&&o.key.toLowerCase()===`j`?(o.preventDefault(),e()):!c&&o.key===`?`?(o.preventDefault(),t()):!c&&o.key===`/`&&(o.preventDefault(),e())};return window.addEventListener(`keydown`,o),()=>window.removeEventListener(`keydown`,o)},[e,t,n,r,i,a])}var Fo=e=>e instanceof Error?e.message:String(e||`Unknown error`);function Io({activeSid:e,backlog:t,notify:n,pendingQuestions:r,refetchSnapshot:i}){let[a,o]=(0,M.useState)(!1),[s,c]=(0,M.useState)(!1),l=(0,M.useRef)(``),u=(0,M.useMemo)(()=>{let e=(t??[]).map(e=>({...e,operator_decision:e.operator_decision}));return ht(r??[],e)[0]??null},[t,r]);return(0,M.useEffect)(()=>{if(!u||!e){o(!1);return}let t=`${e}:${u.id}`;l.current!==t&&(l.current=t,o(!0))},[e,u]),{answerPendingReply:async(t,r)=>{if(!(!e||!u||s)){c(!0);try{let a=u.legacy?await R.answerPending(e,u.item_id,r):await R.resolveDecision(e,u.id,t,r);if(a.resolved===!1){n(`info`,String(a.reply||`Manager needs a more specific answer.`));return}o(!1),await i(),a.daemon&&Number(a.daemon.rc??0)!==0?n(`error`,`Answer queued, but the daemon did not start: ${a.daemon.error||`operator action required`}`):n(`success`,String(a.reply||`Manager delivered your answer to the team.`))}catch(e){await i(),n(`error`,`Could not send answer: ${Fo(e)}`)}finally{c(!1)}}},pendingReply:u,pendingReplyBusy:s,pendingReplyOpen:a,setPendingReplyOpen:o}}var Lo=`argus.browser.project.v1`;function Ro(){try{return window.sessionStorage.getItem(Lo)}catch{return null}}function zo(e){try{e?window.sessionStorage.setItem(Lo,e):window.sessionStorage.removeItem(Lo)}catch{}}function Bo(e,t){let n=new URL(window.location.href);e?n.searchParams.set(`project`,e):n.searchParams.delete(`project`);let r=t===`push`?`pushState`:`replaceState`;window.history[r](window.history.state,``,n.toString())}function Vo({cancelActiveMessage:e,notify:t,projects:n,projectsError:r,projectsReady:i,queryClient:a,setArtifactPath:o,setSidebarOpen:s,setTaskItemId:c}){let l=new URLSearchParams(window.location.search),[u,d]=(0,M.useState)(l.get(`project`)||Ro()),f=(0,M.useRef)(u),p=(0,M.useRef)(!1);f.current=u;let m=(0,M.useCallback)(t=>{t!==f.current&&(e(),o(null),c(null)),f.current=t,d(t),zo(t)},[e,o,c]),h=(0,M.useCallback)((e,t=`push`)=>{let n=new URLSearchParams(window.location.search).get(`project`);m(e),n!==e&&Bo(e,t)},[m]),g=(0,M.useCallback)((e=`replace`)=>{let t=new URLSearchParams(window.location.search).get(`project`);m(null),t!=null&&Bo(null,e)},[m]),_=(0,M.useCallback)(e=>{a.prefetchQuery({queryKey:[`snapshot`,e],queryFn:({signal:t})=>R.snapshot(e,t),staleTime:3e3})},[a]);return(0,M.useEffect)(()=>{if(!i)return;let e=p.current,r=Jt(n,f.current,e);if(!e&&(p.current=!0,r.id===f.current?zo(r.id):m(r.id),new URLSearchParams(window.location.search).get(`project`)!==r.id&&Bo(r.id,`replace`),r.recovered)){let e=n.find(e=>e.id===r.id);t(`info`,e?`Project “${r.requested}” was not found. Switched to ${e.label||e.id}.`:`Project “${r.requested}” was not found. Create a daemon to continue.`)}},[m,t,n,i]),(0,M.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get(`project`);if(s(!1),!e){m(null);return}if(!i){m(e);return}let r=qt(n,e);if(m(r.id),r.recovered){Bo(r.id,`replace`);let e=n.find(e=>e.id===r.id);t(`info`,e?`Project “${r.requested}” was not found. Switched to ${e.label||e.id}.`:`Project “${r.requested}” was not found. Create a daemon to continue.`)}};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[m,t,n,i,s]),{activateProject:m,activeSid:i?u&&n.some(e=>e.id===u)?u:null:r?u:null,clearProjectSelection:g,prefetchProject:_,selectProject:h,sid:u,sidRef:f}}function Ho(e,t){let n=localStorage.getItem(e);return n==null?t:n===`true`}function Uo(){let e=new URLSearchParams(window.location.search),[t,n]=(0,M.useState)(e.get(`kiosk`)===`1`),[r,i]=(0,M.useState)(()=>Ho(`argus.reasoning.visible.v1`,!1)),[a,o]=(0,M.useState)(()=>{let e=localStorage.getItem(`argus.workspace.view`);return e===`mission`||e===`workbench`?e:`activity`}),[s,c]=(0,M.useState)(`activity`),[l,u]=(0,M.useState)(()=>Ho(`argus.preview.expanded.v5`,!0)),[d,f]=(0,M.useState)(()=>{let e=Number(localStorage.getItem(`argus.sidebar.width.v2`)||256);return Number.isFinite(e)?Math.max(220,Math.min(400,e)):256}),[p,m]=(0,M.useState)(()=>{let e=Number(localStorage.getItem(`argus.preview.width.v2`)||440);return Number.isFinite(e)?Math.max(320,Math.min(600,e)):440}),[h,g]=(0,M.useState)(!1),[_,v]=(0,M.useState)(()=>Ho(`argus.sidebar.expanded.v4`,!0)),[y,b]=(0,M.useState)(()=>{let e=localStorage.getItem(`argus.theme`);return e===`light`||e===`dark`?e:null}),[x,S]=(0,M.useState)(()=>window.matchMedia(`(prefers-color-scheme: dark)`).matches),C=y??(x?`dark`:`light`),w=(0,M.useRef)(null),T=(0,M.useRef)(null);(0,M.useEffect)(()=>{localStorage.setItem(`argus.sidebar.expanded.v4`,String(_)),localStorage.setItem(`argus.preview.expanded.v5`,String(l)),localStorage.setItem(`argus.sidebar.width.v2`,String(d)),localStorage.setItem(`argus.preview.width.v2`,String(p))},[_,d,l,p]),(0,M.useEffect)(()=>{localStorage.setItem(`argus.workspace.view`,a)},[a]),(0,M.useEffect)(()=>{localStorage.setItem(`argus.reasoning.visible.v1`,String(r))},[r]),(0,M.useEffect)(()=>{let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=()=>S(e.matches);return t(),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),(0,M.useEffect)(()=>{document.documentElement.dataset.theme=C},[C]),(0,M.useEffect)(()=>{let e=()=>{document.documentElement.dataset.pageVisible=String(!document.hidden)};return e(),document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let ee=(0,M.useCallback)(()=>{let e=C===`light`?`dark`:`light`;b(e),localStorage.setItem(`argus.theme`,e)},[C]),te=(0,M.useCallback)((e,t)=>{let n=w.current;if(!n)return;t.preventDefault();let r=n.getBoundingClientRect();document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;let i=t=>{T.current!=null&&window.cancelAnimationFrame(T.current),T.current=window.requestAnimationFrame(()=>{if(e===`left`){let e=l?p+8:56,n=Math.max(220,Math.min(400,r.width-e-360-8));f(Math.max(220,Math.min(n,t.clientX-r.left)))}else{let e=_?d+8:56,n=Math.max(320,Math.min(600,r.width-e-360-8));m(Math.max(320,Math.min(n,r.right-t.clientX)))}})},a=()=>{T.current!=null&&window.cancelAnimationFrame(T.current),T.current=null,document.body.style.cursor=``,document.body.style.userSelect=``,window.removeEventListener(`pointermove`,i),window.removeEventListener(`pointerup`,a),window.removeEventListener(`pointercancel`,a)};window.addEventListener(`pointermove`,i),window.addEventListener(`pointerup`,a,{once:!0}),window.addEventListener(`pointercancel`,a,{once:!0})},[_,d,l,p]);return(0,M.useEffect)(()=>{let e=()=>{if(window.innerWidth<1024||!w.current)return;let e=w.current.clientWidth,t=_?d:56,n=l?p:56,r=(_?8:0)+(l?8:0),i=Math.max(540,e-360-r);if(t+n<=i)return;let a=l?Math.max(320,Math.min(p,i-t)):n,o=_?Math.max(220,Math.min(d,i-a)):t;o+a>i&&l&&(a=Math.max(320,i-o)),_&&f(o),l&&m(a)};return e(),window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[_,d,l,p]),{cycleTheme:ee,kiosk:t,leftPanelOpen:_,leftWidth:d,mobileView:s,resizeSidebar:te,rightPanelOpen:l,rightWidth:p,setKiosk:n,setLeftPanelOpen:v,setLeftWidth:f,setMobileView:c,setRightPanelOpen:u,setRightWidth:m,setShowReasoning:i,setSidebarOpen:g,setWorkspaceView:o,shellRef:w,showReasoning:r,sidebarOpen:h,themeMode:C,workspaceView:a}}function Wo({error:e,onRetry:t}){let{t:n}=q(),r=Ye(e),i=e instanceof Je;return!r&&!i?null:(0,K.jsxs)(`div`,{role:`alert`,className:`fixed left-1/2 top-3 z-[100] flex w-[min(92vw,42rem)] -translate-x-1/2 items-start gap-3 rounded-xl border border-err/50 bg-panel/95 px-4 py-3 text-left text-sm text-ink shadow-xl backdrop-blur`,children:[(0,K.jsx)(`span`,{"aria-hidden":`true`,className:`mt-0.5 font-mono font-bold text-err`,children:`!`}),(0,K.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,K.jsx)(`strong`,{className:`block text-err`,children:n(r?`connection.pairingTitle`:`connection.unreachableTitle`)}),(0,K.jsx)(`span`,{className:`mt-0.5 block text-xs leading-relaxed text-ink-dim`,children:n(r?`connection.pairingDetail`:`connection.unreachableDetail`)})]}),r?null:(0,K.jsx)(`button`,{type:`button`,onClick:t,className:`shrink-0 rounded-md border border-err/40 px-2.5 py-1 text-xs text-err hover:bg-err/10`,children:n(`common.retry`)})]})}var Go=0,Ko=(0,M.lazy)(async()=>({default:(await Jr(()=>import(`./ResearchWorkbenchPanel-BOPEGTC6.js`),__vite__mapDeps([2,1,3,4,5,6]))).ResearchWorkbenchPanel}));function qo(){let{locale:e,t}=q(),n=se(),r=fr(),i=pr(),a=(0,M.useMemo)(()=>Gt(Oo(r.data?.projects??[],i.data?.projects??[])),[i.data?.projects,r.data?.projects]),s=r.data?.local_cwd??``,c=[r.error,i.error].find(e=>Xe(e)),[l,u]=(0,M.useState)(`none`),{cycleTheme:d,kiosk:f,leftPanelOpen:p,leftWidth:m,mobileView:h,resizeSidebar:g,rightPanelOpen:_,rightWidth:v,setKiosk:y,setLeftPanelOpen:b,setLeftWidth:x,setMobileView:S,setRightPanelOpen:w,setRightWidth:T,setShowReasoning:ee,setSidebarOpen:te,setWorkspaceView:E,shellRef:ne,showReasoning:re,sidebarOpen:ie,themeMode:ae,workspaceView:D}=Uo(),[O,oe]=(0,M.useState)(()=>D===`mission`?`mission`:`activity`),[ce,k]=(0,M.useState)(D===`workbench`);(0,M.useEffect)(()=>{if(D===`workbench`){k(!0);return}oe(D)},[D]),_o();let[le,A]=(0,M.useState)(0),[ue,de]=(0,M.useState)(``),[fe,j]=(0,M.useState)(!1),[pe,me]=(0,M.useState)(0),[he,ge]=(0,M.useState)(!1),[_e,ve]=(0,M.useState)([]),[ye,be]=(0,M.useState)(``),[xe,Se]=(0,M.useState)(!1),[Ce,we]=(0,M.useState)(0),[Te,Ee]=(0,M.useState)([]),[De,Oe]=(0,M.useState)(0),[ke,Ae]=(0,M.useState)(null),[je,Me]=(0,M.useState)(null),[Ne,Pe]=(0,M.useState)(!1),[Fe,Ie]=(0,M.useState)(!1),Le=(0,M.useRef)(null),Re=(0,M.useRef)(0),[ze,Be]=(0,M.useState)(null),[Ve,He]=(0,M.useReducer)(Co,So),[Ue,We]=(0,M.useState)(`all`),[Ge,Ke]=(0,M.useState)(``),qe=(0,M.useCallback)(()=>Be(null),[]),N=(0,M.useCallback)((e,t)=>{Be({id:++Go,tone:e,message:t})},[]),Je=(0,M.useCallback)(()=>{let e=!!Le.current;return Re.current+=1,Le.current?.controller.abort(),Le.current=null,ge(!1),be(``),Se(!1),we(0),Ee([]),Oe(0),e},[]),Ye=(0,M.useCallback)(()=>{Je()&&N(`info`,`Stopped waiting for this reply. Server-side work may still finish in the project timeline.`)},[Je,N]),{activeSid:P,clearProjectSelection:Ze,prefetchProject:Qe,selectProject:F,sidRef:$e}=Vo({cancelActiveMessage:Je,notify:N,projects:a,projectsError:r.isError,projectsReady:r.isSuccess,queryClient:n,setArtifactPath:Ae,setSidebarOpen:te,setTaskItemId:Me});(0,M.useEffect)(()=>()=>{Re.current+=1,Le.current?.controller.abort(),Le.current=null},[]);let et=(0,M.useCallback)(e=>{let t=(e||``).trim(),n=$e.current;!t||!n||fe||(j(!0),R.rewritePrompt(n,t).then(e=>{if(j(!1),e.error||!e.rewritten.trim()){N(`error`,`Rewrite failed: ${e.error||`empty rewrite`} — your prompt is unchanged`);return}de(e.rewritten),A(e=>e+1);let t=e.questions.length?` Manager asks: ${e.questions.join(` · `)}`:``;N(`success`,`Prompt rewritten — review it, then send.${t}`)},e=>{j(!1),N(`error`,`Rewrite failed: ${ii(e)} — your prompt is unchanged`)}))},[N,fe,$e]),{createDaemon:tt,creatingDaemon:nt}=jo({localCwd:s,notify:N,onFocusComposer:()=>A(e=>e+1),queryClient:n,refetchProjects:r.refetch,selectProject:F}),I=mr(P),L=I.data,rt=L?.session.id===P?P:null,it=L?.continuous,at=br(rt,!0),ot=Sr(rt,O===`mission`),{events:st,connected:ct}=jr(rt,Ve.reconnectKey),lt=(0,M.useMemo)(()=>Or(st),[st]),z=(0,M.useMemo)(()=>Ar(st),[st]);(0,M.useEffect)(()=>{!rt||!lt||n.invalidateQueries({queryKey:[`artifacts`,rt],exact:!0})},[lt,rt,n]),(0,M.useEffect)(()=>{!rt||!z||n.invalidateQueries({queryKey:[`snapshot`,rt],exact:!0})},[rt,n,z]);let ut=(0,M.useMemo)(()=>Pn(st),[st]),dt=yr(rt,O===`activity`,120),ft=hr(P,20,l===`inspector`),{answerPendingReply:pt,pendingReply:mt,pendingReplyBusy:ht,pendingReplyOpen:B,setPendingReplyOpen:gt}=Io({activeSid:P,backlog:L?.backlog,notify:N,pendingQuestions:L?.pending_questions,refetchSnapshot:I.refetch}),_t=(0,M.useMemo)(()=>Do(st,dt.data??[],_e),[st,_e,dt.data]),vt=(0,M.useMemo)(()=>L?En(L,_t,at.data??[]):null,[_t,at.data,L]),yt=(0,M.useRef)(_t);yt.current=_t,(0,M.useEffect)(()=>{We(`all`),Ke(``),ve([]),He({kind:`reset`})},[rt]);let bt=wr(P,L?.daemon_commands?.revision),{daemonBusy:xt,manageDeleteProject:St,managePauseDaemon:Ct,manageRenameProject:wt,manageStartDaemon:Tt,requestDispose:Et,requestManageSession:Dt,requestStartDaemon:Ot,requestStopDaemon:kt,requestStopIteration:At,toggleContinuous:Mt}=No({actions:bt,activeSid:P,clearProjectSelection:Ze,continuous:it,currentSnapshotSid:L?.session.id,notify:N,refetchProjects:r.refetch,selectProject:F,setDaemonManageOpen:Ie}),Nt=(0,M.useCallback)(async e=>{if(!P)return;let t=await bt.updateProject.mutateAsync({sid:P,name:e});N(`success`,`Renamed to "${t.name}".`)},[bt.updateProject,P,N]),Pt=(0,M.useMemo)(()=>yo({activeSid:P,activityEventsRef:yt,notify:N,onClearEvents:e=>He({kind:`clear`,offset:e}),onDispose:Et,onOpenConfig:()=>u(`config`),onOpenDoctor:()=>u(`doctor`),onOpenHelp:()=>u(`help`),onOpenIdentity:()=>u(`identity`),onOpenInspector:()=>u(`inspector`),onOpenNewDaemon:()=>Pe(!0),onOpenOperations:()=>u(`operations`),onOpenSidebar:()=>te(!0),onReconnectEvents:()=>He({kind:`reconnect`}),onRenameProject:Nt,onRewriteDraft:et,onSelectProject:F,onSetArtifactPath:Ae,onSetEventFilter:We,onSetEventQuery:Ke,onSetTaskItemId:Me,onSetWorkspaceView:E,onShowArtifacts:()=>w(!0),onStopIteration:At,onStopWaiting:Ye,refetchSnapshot:I.refetch}),[P,N,Nt,Et,At,F,I.refetch,Ye,E]);Po({focusComposer:()=>A(e=>e+1),openHelp:()=>u(`help`),toggleKiosk:()=>y(e=>!e),togglePalette:()=>u(e=>e===`palette`?`none`:`palette`),toggleReasoning:()=>ee(e=>!e),toggleSidebarCollapse:()=>b(e=>!e)});let Ft=async(e,n=[])=>{let r=P;if(!r||Le.current)return!1;if(!n.length){let t=await vo(e,Pt);if(t.kind===`handled`)return!0;if(t.kind===`error`)return N(`error`,t.message),!1}let i=++Re.current,a=new AbortController;Le.current={id:i,sid:r,controller:a};let o=()=>{let e=Le.current;return!!(e&&e.id===i&&e.sid===r&&$e.current===r&&!a.signal.aborted)},s=()=>{Le.current?.id===i&&(Le.current=null,ge(!1),be(``),Se(!1),we(0),Oe(0),Ee([]))};ge(!0),be(n.length?t(`chat.uploadingAttachments`):``),Se(!1),we(0),Ee([]),Oe(Date.now());let c=[];if(n.length)try{let e=await R.uploadAttachments(r,n,a.signal);if(!o())return!1;c=e.attachments.map(e=>({attachment_id:e.attachment_id}))}catch(e){return o()&&(N(`error`,t(`chat.attachmentUploadFailed`,{error:ii(e)})),s()),!1}ve(t=>[...t,To(r,i,e)]);let l=(e,t=``,n=`auto`)=>{!o()||typeof e!=`string`||!e.trim()||ve(a=>Eo(a,r,i,e,t,Date.now(),n))},u=e=>{if(!o())return;let t=e.daemon&&typeof e.daemon==`object`?e.daemon:null,n=typeof e.reply==`string`?e.reply:null;t?.admission_required?N(`error`,n||`Task queued, but all daemon slots are busy: ${String(t.error||`operator action required`)}`):t&&Number(t.rc??0)!==0?N(`error`,n||`Task queued, but executor did not start: ${String(t.error||`unknown error`)}`):n&&N(`success`,n),I.refetch?.()},d=e=>{o()&&xo(e,{dispatchTask:u,notifyError:e=>N(`error`,e),refetchTranscript:()=>{dt.refetch()}})};return(async()=>{let t=!1,n=null,i=[];try{try{await R.messageStream(r,e,{onPhase:(e,t,n)=>{o()&&(be(e),Se(n.heartbeat),we(n.quietS),i=Gn(i,{label:e,role:t,kind:n.kind,detail:n.detail,heartbeat:n.heartbeat,quietS:n.quietS}),Ee(i))},onDelta:(e,n,r)=>{o()&&(t=!0,i=Kn(i),Ee(i),be(``),Se(!1),we(0),l(e,n,r===`append`||r===`snapshot`?r:`auto`))},onDone:e=>{o()&&(l(e.reply,``,`snapshot`),d(e))},onError:e=>{o()&&(n=e)}},{signal:a.signal,attachments:c})}catch(e){o()&&(n=e)}if(!o())return;n&&N(`error`,ai(n,t))}finally{s()}})(),!0},It=(0,M.useRef)(Ft);It.current=Ft;let Lt=(0,M.useMemo)(()=>{let n=oa(jt,e=>{It.current(e)},e=>{de(e),A(e=>e+1)},e),r=[...f?[]:[{id:`new`,label:t(`palette.newDaemon`),hint:`+`,group:t(`palette.view`),run:()=>Pe(!0)}],{id:`transcript`,label:t(`palette.openTranscript`),hint:`/transcript`,group:t(`palette.view`),run:()=>u(`transcript`)},{id:`inspector`,label:t(`palette.openProject`),hint:t(`palette.projectHint`),group:t(`palette.view`),run:()=>u(`inspector`)},{id:`operations`,label:t(`palette.openOperations`),hint:t(`palette.operationsHint`),group:t(`palette.view`),run:()=>u(`operations`)},{id:`help`,label:t(`help.title`),hint:`?`,group:t(`palette.view`),run:()=>u(`help`)},{id:`reasoning`,label:t(re?`palette.hideReasoning`:`palette.showReasoning`),hint:`⌘T`,group:t(`palette.view`),run:()=>ee(e=>!e)},{id:`kiosk`,label:t(f?`palette.exitKiosk`:`palette.enterKiosk`),hint:`⌘.`,group:t(`palette.view`),run:()=>y(e=>!e)}],i=f?[]:[{id:`message`,label:t(`palette.messageArgus`),hint:`/`,group:t(`palette.action`),run:()=>A(e=>e+1)},...he?[{id:`cancel-message`,label:t(`palette.stopWaiting`),hint:`Esc`,group:t(`palette.action`),run:Ye}]:[],...it?[{id:`continuous`,label:it.enabled?t(`palette.stopContinuous`):t(`palette.startContinuous`),group:t(`palette.action`),run:Mt}]:[],...L?.daemon.control_available===!1?[]:[L?.daemon.alive?{id:`stop`,label:t(`palette.stopDaemon`),group:t(`palette.action`),run:kt}:{id:`start`,label:t(`palette.startDaemon`),group:t(`palette.action`),run:Ot}]],o=a.map(e=>({id:`p-${e.id}`,label:e.label||e.id,hint:e.daemon_alive?`● ${t(`common.live`)}`:`○`,keywords:`${e.id} ${e.display_name??``} ${e.objective} ${e.daemon_alive?`live running`:`stopped idle`}`,group:t(`palette.project`),run:()=>F(e.id)}));return[...r,...i,...n,...o]},[a,L?.daemon.alive,f,re,it?.enabled,he,Ye,e,t]);return(0,K.jsxs)(`div`,{ref:ne,className:`workbench-shell ambient-canvas flex h-screen h-[100dvh] w-screen max-w-full overflow-hidden text-ink`,children:[(0,K.jsx)(Wo,{error:c,onRetry:()=>{r.refetch(),i.refetch()}}),!f&&ie?(0,K.jsx)(`button`,{type:`button`,"aria-label":t(`common.closeSessions`),onClick:()=>te(!1),className:`fixed inset-0 z-30 bg-black/40 lg:hidden`}):null,f?null:(0,K.jsx)(Ga,{projects:a,activeId:P,localCwd:s,onSelect:e=>{F(e),te(!1)},onPrefetch:Qe,onManage:Dt,onOpenPanel:e=>u(e),onNew:()=>Pe(!0),loading:r.isLoading,creating:nt,error:r.isError?ii(r.error):void 0,onRetry:()=>void r.refetch(),mobileOpen:ie,collapsed:!p,onToggleCollapse:()=>b(e=>!e),themeMode:ae,onCycleTheme:d,expandedWidth:m}),!f&&p?(0,K.jsx)(ro,{label:t(`common.resizeSessions`),value:m,min:220,max:400,onPointerDown:e=>g(`left`,e),onReset:()=>x(256),onNudge:e=>x(t=>Math.max(220,Math.min(400,t+e)))}):null,(0,K.jsx)(`main`,{className:`flex min-w-0 flex-1 overflow-x-hidden`,children:L?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`${h===`activity`?`flex`:`hidden`} glass-panel glass-panel--main h-full min-w-0 flex-1 flex-col lg:flex`,children:[(0,K.jsx)(Wr,{snap:L,streamOk:ct,onStart:Ot,onStop:kt,onManage:()=>Ie(!0),busy:xt,snapshotStale:I.isError,readOnly:f,missionView:vt}),(0,K.jsxs)(`div`,{className:`flex h-10 shrink-0 items-center gap-1 border-b border-line/60 px-3`,children:[(0,K.jsxs)(`div`,{className:`workspace-tabs`,"data-active":D,children:[(0,K.jsx)(`span`,{className:`workspace-tab-indicator`,"aria-hidden":`true`}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(`mission`),className:`workspace-tab`,"data-selected":D===`mission`,children:t(`mobile.mission`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(`activity`),className:`workspace-tab`,"data-selected":D===`activity`,children:t(`mobile.activity`)}),(0,K.jsx)(`button`,{type:`button`,onClick:()=>E(`workbench`),className:`workspace-tab`,"data-selected":D===`workbench`,children:t(`mobile.workbench`)})]}),D===`mission`?(0,K.jsx)(`span`,{className:`ml-auto hidden max-w-72 truncate text-[10px] text-ink-faint sm:block`,children:vt?.active_role?t(`mission.roleActive`,{role:vt.active_role}):t(`mission.overview`)}):(0,K.jsx)(`span`,{className:`ml-auto`}),f?null:(0,K.jsx)(`button`,{type:`button`,onClick:()=>u(`operations`),className:`rounded border border-line/60 px-2 py-1 text-[10px] text-ink-faint hover:border-blue/50 hover:text-blue`,children:t(`mission.operations`)})]}),(0,K.jsxs)(`div`,{className:`${D===`workbench`?`hidden`:`flex`} min-h-0 flex-1 flex-col`,children:[(0,K.jsx)(xa,{alert:ut}),O===`mission`&&vt?(0,K.jsx)(co,{view:vt,gitDiff:ot.data,onOpenArtifact:Ae}):(0,K.jsx)(Ni,{events:_t,connected:ct,showReasoning:re,onToggleReasoning:()=>ee(e=>!e),embedded:!0,filter:Ue,query:Ge,skipFirst:Ve.skipFirst}),f?null:(0,K.jsx)(`div`,{className:`composer-dock shrink-0 px-4 pt-3`,children:(0,K.jsxs)(`div`,{className:`mx-auto w-full max-w-full lg:max-w-[61.8vw]`,children:[(0,K.jsx)(ya,{questions:L.pending_questions??[],backlog:L.backlog,onAnswer:()=>gt(!0)}),(0,K.jsx)(ra,{value:ue,onChange:de,onSend:Ft,onCancel:Ye,disabled:!P,pending:he,focusSignal:le,embedded:!0,phase:ye,heartbeat:xe,quietS:Ce,steps:Te,startedAt:De,onRewrite:et,rewriting:fe,slashSelection:pe,onSlashSelectionChange:me},P||`no-session`)]})})]}),ce&&P?(0,K.jsx)(`div`,{className:`${D===`workbench`?`flex`:`hidden`} min-h-0 flex-1`,children:(0,K.jsx)(M.Suspense,{fallback:(0,K.jsx)(`div`,{className:`flex min-h-0 flex-1 items-center justify-center text-xs text-ink-faint`,children:t(`common.loading`)}),children:(0,K.jsx)(Ko,{sid:P,active:D===`workbench`})})}):null]}),_?(0,K.jsx)(ro,{label:t(`common.resizePreview`),value:v,min:320,max:600,onPointerDown:e=>g(`right`,e),onReset:()=>T(440),onNudge:e=>T(t=>Math.max(320,Math.min(600,t-e)))}):null,(0,K.jsxs)(`aside`,{style:{"--preview-width":`${v}px`},className:`${h===`preview`?`flex`:`hidden`} relative min-w-0 flex-1 flex-col overflow-hidden border-l border-line/60 bg-panel transition-[width] duration-[250ms] ease-panel lg:flex lg:flex-none ${_?`lg:w-[var(--preview-width)]`:`lg:w-14`}`,children:[(0,K.jsx)(`div`,{className:`lg:hidden`,children:(0,K.jsx)(Wr,{snap:L,streamOk:ct,onStart:Ot,onStop:kt,onManage:()=>Ie(!0),busy:xt,snapshotStale:I.isError,readOnly:f,missionView:vt})}),(0,K.jsx)(Ba,{sid:rt,artifacts:at.data,error:at.isError,onExpand:Ae,className:`min-h-0 flex-1 mobile-scroll-region ${_?`lg:flex`:`lg:hidden`}`,embedded:!0,onCollapse:()=>w(!1),missionView:vt,activityEvents:_t}),_?null:(0,K.jsx)(`div`,{className:`hidden h-12 items-center justify-center border-b border-line/50 text-ink-faint lg:flex`,children:(0,K.jsx)(`button`,{type:`button`,onClick:()=>w(!0),"aria-label":t(`common.expandPreview`),title:t(`common.expandPreview`),className:`flex h-8 w-8 items-center justify-center rounded-md border border-line/50 bg-bg/40 hover:border-blue/50 hover:text-ink`,children:(0,K.jsx)(o,{icon:C,className:`h-3.5 w-3.5`})})})]})]}):(0,K.jsx)(ho,{loading:r.isLoading||!!(P&&I.isLoading),hasProjects:a.length>0,error:r.isError&&a.length===0?ii(r.error):I.isError&&!L?ii(I.error):void 0,onRetry:()=>{r.refetch(),P&&I.refetch()},onNew:()=>Pe(!0),onChoose:()=>te(!0),canCreate:!f})}),(0,K.jsx)(ca,{open:l===`palette`,onClose:()=>u(`none`),items:Lt}),(0,K.jsx)(ua,{open:l===`help`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(ga,{sid:P,open:l===`doctor`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(_a,{sid:P,open:l===`config`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(Z,{sid:P,open:l===`identity`,onClose:()=>u(`none`)}),P&&(0,K.jsx)(va,{sid:P,open:l===`transcript`,onClose:()=>u(`none`)}),P&&L?(0,K.jsx)($a,{open:l===`inspector`,snap:L,journal:ft.data??[],busy:bt.disposeBacklog.isPending||bt.stopBacklog.isPending,onClose:()=>u(`none`),onDispose:Et,onStop:At,onInspect:Me}):null,P&&L?(0,K.jsx)(fo,{open:l===`operations`,sid:P,snap:L,onClose:()=>u(`none`),onChanged:()=>{I.refetch(),r.refetch()},onRestored:async e=>{await r.refetch(),F(e)}}):null,(0,K.jsx)(Da,{sid:P,path:ke,onClose:()=>Ae(null)}),(0,K.jsx)(no,{sid:P,itemId:je,onClose:()=>Me(null),onDone:e=>Et(e,`done`),onSkip:e=>Et(e,`rm`),onStop:At,busy:bt.disposeBacklog.isPending||bt.stopBacklog.isPending,readOnly:f}),(0,K.jsx)(Ha,{open:Ne,busy:nt,onClose:()=>Pe(!1),onCreate:tt}),(0,K.jsx)(ba,{reply:mt,open:B,busy:ht,onClose:()=>gt(!1),onSubmit:pt}),P&&L?(0,K.jsx)(Ua,{open:Fe,sid:P,name:L.session.display_name||``,alive:L.daemon.alive,controlAvailable:L.daemon.control_available!==!1,busy:xt,onClose:()=>Ie(!1),onRename:wt,onStart:Tt,onPause:Ct,onDelete:St}):null,(0,K.jsx)(Va,{notice:ze,onClose:qe}),L&&!f?(0,K.jsx)(go,{active:h===`preview`?`preview`:D,onSelect:e=>{if(e===`preview`){S(`preview`);return}S(`activity`),E(e)},onOpenSessions:()=>te(!0)}):null]})}function Jo({onDone:e}){let{t}=q(),n=(0,M.useRef)(!1),r=(0,M.useCallback)(()=>{n.current||(n.current=!0,e())},[e]);return(0,M.useEffect)(()=>{let e=window.setTimeout(r,330),t=()=>r();return window.addEventListener(`keydown`,t,{once:!0}),()=>{window.clearTimeout(e),window.removeEventListener(`keydown`,t)}},[r]),(0,K.jsxs)(`div`,{role:`status`,"aria-label":t(`splash.starting`),onClick:r,onAnimationEnd:e=>{e.currentTarget===e.target&&r()},className:`argus-web-splash`,children:[(0,K.jsx)(`div`,{className:`argus-web-splash-logo argus-web-splash-logo-full`,"aria-hidden":`true`,children:(0,K.jsx)(Ci,{size:72})}),(0,K.jsx)(`div`,{className:`argus-web-splash-logo argus-web-splash-logo-compact`,"aria-hidden":`true`,children:(0,K.jsx)(xi,{size:112})})]})}He();var Yo=new Ee({defaultOptions:{queries:{staleTime:3e3,retry:ur,refetchOnWindowFocus:!1}}});function Xo(){let[e,t]=(0,M.useState)(!0);return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(qo,{}),e?(0,K.jsx)(Jo,{onDone:()=>t(!1)}):null]})}De.createRoot(document.getElementById(`root`)).render((0,K.jsx)(M.StrictMode,{children:(0,K.jsx)(de,{client:Yo,children:(0,K.jsx)(Vr,{children:(0,K.jsx)(Xo,{})})})}));export{ot as a,Ge as i,q as n,Ze as o,We as r,Jr as t}; \ No newline at end of file diff --git a/frontend/web/dist/assets/pdf-BdyXXgZL.js b/frontend/web/dist/assets/pdf-Dzq_asqX.js similarity index 99% rename from frontend/web/dist/assets/pdf-BdyXXgZL.js rename to frontend/web/dist/assets/pdf-Dzq_asqX.js index 37edef433..f11e36dd0 100644 --- a/frontend/web/dist/assets/pdf-BdyXXgZL.js +++ b/frontend/web/dist/assets/pdf-Dzq_asqX.js @@ -1,4 +1,4 @@ -import{t as e}from"./index-7NNAUeAk.js";var t=typeof process==`object`&&process+``==`[object process]`&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!==`browser`),n=[1/0,1/0,-1/0,-1/0],r=new Float32Array(n),i=[.001,0,0,.001,0,0],a=`http://www.w3.org/2000/svg`,o={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},s={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},c=`pdfjs_internal_id_`,l=`pdfjs_internal_editor_`,u={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},d={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,INK_COLOR_AND_OPACITY:24,HIGHLIGHT_COLOR:31,HIGHLIGHT_THICKNESS:32,HIGHLIGHT_FREE:33,HIGHLIGHT_SHOW_ALL:34,DRAW_STEP:41},f={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},p={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},m={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},h={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26,RICHMEDIA:27},g={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},_={ERRORS:0,WARNINGS:1,INFOS:5},v={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93,rawFillPath:94},y={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},b={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},x=_.WARNINGS;function S(e){Number.isInteger(e)&&(x=e)}function C(){return x}function w(e){x>=_.INFOS&&console.info(`Info: ${e}`)}function T(e){x>=_.WARNINGS&&console.warn(`Warning: ${e}`)}function E(e){throw Error(e)}function D(e,t){e||E(t)}function O(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function k(e,t=null,n=null){if(!e)return null;if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=se(e)}catch{}let r=t?URL.parse(e,t):URL.parse(e);return O(r)?r:null}function A(e,t,n=!1){let r=URL.parse(e);return r?(r.hash=t,r.href):n&&k(e,`http://example.com`)?e.split(`#`,1)[0]+`${t?`#${t}`:``}`:``}function j(e){return e.substring(e.lastIndexOf(`/`)+1)}function M(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var N=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),ee=class extends N{constructor(e,t){super(e,`PasswordException`),this.code=t}},te=class extends N{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ne=class extends N{constructor(e){super(e,`InvalidPDFException`)}},re=class extends N{constructor(e,t,n){super(e,`ResponseException`),this.status=t,this.missing=n}},ie=class extends N{constructor(e){super(e,`FormatError`)}},P=class extends N{constructor(e){super(e,`AbortException`)}};function ae(e){(typeof e!=`object`||e?.length===void 0)&&E(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t`u`)return M(this,`isAlphaColorInputSupported`,!1);let e=document.createElement(`input`);return e.type=`color`,e.setAttribute(`alpha`,``),e.value=`#ff000080`,M(this,`isAlphaColorInputSupported`,e.value!==`#ff0000`)}static get isBackdropFilterSupported(){return M(this,`isBackdropFilterSupported`,typeof CSS<`u`&&CSS.supports(`backdrop-filter`,`blur(1px)`))}},I=class{static get hexNums(){return M(this,`hexNums`,Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,`0`)))}static makeHexColor(e,t,n){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[n]}`}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){let r=e[n],i=e[n+1];e[n]=r*t[0]+i*t[2]+t[4],e[n+1]=r*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5];for(let t=0;t<6;t+=2){let l=e[n+t],u=e[n+t+1];e[n+t]=l*r+u*a+s,e[n+t+1]=l*i+u*o+c}}static applyInverseTransform(e,t){let n=e[0],r=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-r*t[2]+t[2]*t[5]-t[4]*t[3])/i,e[1]=(-n*t[1]+r*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,n){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=e[0],u=e[1],d=e[2],f=e[3],p=r*l+s,m=p,h=r*d+s,g=h,_=o*u+c,v=_,y=o*f+c,b=y;if(i!==0||a!==0){let e=i*l,t=i*d,n=a*u,r=a*f;p+=n,g+=n,h+=r,m+=r,_+=e,b+=e,y+=t,v+=t}n[0]=Math.min(n[0],p,h,m,g),n[1]=Math.min(n[1],_,y,v,b),n[2]=Math.max(n[2],p,h,m,g),n[3]=Math.max(n[3],_,y,v,b)}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=n**2+r**2,s=n*i+r*a,c=i**2+a**2,l=(o+c)/2,u=Math.sqrt(l**2-(o*c-s**2));t[0]=Math.sqrt(l+u||1),t[1]=Math.sqrt(l-u||1)}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e),n[1]=Math.min(n[1],t),n[2]=Math.max(n[2],e),n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,r,i){i[0]=Math.min(i[0],e,n),i[1]=Math.min(i[1],t,r),i[2]=Math.max(i[2],e,n),i[3]=Math.max(i[3],t,r)}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s),this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c)}};function se(e){return decodeURIComponent(escape(e))}var ce=null,le=null;function ue(e){return ce||(ce=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,le=new Map([[`ſt`,`ſt`]])),e.replaceAll(ce,(e,t,n)=>t?t.normalize(`NFKC`):le.get(n))}function de(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),ae(e)}function fe(e,t,n){if(!Array.isArray(n)||n.length<2)return!1;let[r,i,...a]=n;if(!e(r)&&!Number.isInteger(r)||!t(i))return!1;let o=a.length,s=!0;switch(i.name){case`XYZ`:if(o<2||o>3)return!1;break;case`Fit`:case`FitB`:return o===0;case`FitH`:case`FitBH`:case`FitV`:case`FitBV`:if(o>1)return!1;break;case`FitR`:if(o!==4)return!1;s=!1;break;default:return!1}for(let e of a)if(!(typeof e==`number`||s&&e===null))return!1;return!0}var pe=()=>[],me=()=>new Map,he=()=>Object.create(null),ge=()=>new Set;typeof Iterator.prototype.join!=`function`&&(Iterator.prototype.join=function(e){return[...this].join(e)});function L(e,t,n){return Math.min(Math.max(e,t),n)}var _e=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let e=this.viewBox;return M(this,`rawDims`,{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){let n=[e,t];return I.applyTransform(n,this.transform),n}convertToPdfPoint(e,t){let n=[e,t];return I.applyInverseTransform(n,this.transform),n}},ve=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return e!==`textarea`&&e!==`input`&&e!==`option`&&e!==`select`}},ye=/url\(|image-set\(/i,be=/^on/i,xe=class{static get _allowedHtmlElements(){return M(this,`_allowedHtmlElements`,new Set([`a`,`b`,`br`,`button`,`div`,`i`,`img`,`input`,`label`,`li`,`ol`,`option`,`p`,`select`,`span`,`sub`,`sup`,`textarea`,`ul`]))}static get _allowedSvgElements(){return M(this,`_allowedSvgElements`,new Set([`ellipse`,`line`,`path`,`rect`,`svg`]))}static get _allowedRichTextElements(){return M(this,`_allowedRichTextElements`,new Set([`a`,`b`,`br`,`div`,`i`,`li`,`ol`,`p`,`span`,`sub`,`sup`,`ul`]))}static get _allowedRichTextAttributes(){return M(this,`_allowedRichTextAttributes`,new Set([`class`,`dir`,`style`]))}static get _allowedRichTextStyles(){return M(this,`_allowedRichTextStyles`,new Set(`color.font.fontFamily.fontSize.fontStretch.fontStyle.fontWeight.kerningMode.letterSpacing.lineHeight.margin.marginBottom.marginLeft.marginRight.marginTop.orphans.paddingLeft.paddingRight.breakAfter.breakBefore.breakInside.tabInterval.tabStop.textAlign.textDecoration.textIndent.transform.verticalAlign.widows`.split(`.`)))}static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:Object.hasOwn(e.attributes,`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})})}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null&&!be.test(t)&&!(r===`richText`&&!this._allowedRichTextAttributes.has(t)))switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:if(r===`richText`){let t=this._allowedRichTextStyles;for(let[r,i]of Object.entries(n))t.has(r)&&!ye.test(i)&&(e.style[r]=i)}else Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i?.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static#e(e,t,n){return n===`richText`?!t&&this._allowedRichTextElements.has(e)?document.createElement(e):null:t?t===a&&this._allowedSvgElements.has(e)?document.createElementNS(a,e):null:this._allowedHtmlElements.has(e)?document.createElement(e):null}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=this.#e(r.name,r.attributes?.xmlns,i)??document.createElement(`div`);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&ve.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=this.#e(u,s.attributes?.xmlns,i);if(d){if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&ve.shouldBuildText(u)&&c.push(e),d.append(e)}}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}static getPageViewport(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new _e({viewBox:[0,0,parseInt(r,10),parseInt(i,10)],userUnit:1,scale:t,rotation:n})}},Se=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ce(e,t=`text`){if(Ae(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`blob`:return n.blob();case`bytes`:return n.bytes();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!0),i.responseType=t===`bytes`?`arraybuffer`:t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case`bytes`:n(new Uint8Array(i.response));return;case`blob`:case`json`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var we=class extends N{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function Te(e){let t=e.length,n=0;for(;n{try{return new URL(e)}catch{}try{return new URL(decodeURIComponent(e))}catch{}try{return new URL(e,`https://foo.bar`)}catch{}try{return new URL(decodeURIComponent(e),`https://foo.bar`)}catch{}return null})(e);if(!n)return t;let r=e=>{try{let t=decodeURIComponent(e);return t.includes(`/`)&&(t=j(t),t.length===4&&i.test(t))?e:t}catch{return e}},i=/\.pdf$/i,a=j(n.pathname);if(i.test(a))return r(a);if(n.searchParams.size>0){let e=e=>[...e].findLast(e=>i.test(e)),t=e(n.searchParams.values())??e(n.searchParams.keys());if(t)return r(t)}if(n.hash){let e=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(n.hash);if(e)return r(e[0])}return t}var ke=class{#e=new Map;times=[];time(e){this.#e.has(e)&&T(`Timer is already running for ${e}`),this.#e.set(e,Date.now())}timeEnd(e){this.#e.has(e)||T(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.#e.get(e),end:Date.now()}),this.#e.delete(e)}toString(){let e=Math.max(...this.times.map(e=>e.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms\n`).join(``)}};function Ae(e,t){let n=t?URL.parse(e,t):URL.parse(e);return/https?:/.test(n?.protocol??``)}function R(e){e.preventDefault()}function z(e){e.preventDefault(),e.stopPropagation()}var je=class{static#e;static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Me(e){if(e.startsWith(`#`)){let t=e.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(e.startsWith(`rgb(`)){let[t,n,r]=e.slice(4,-1).split(`,`).map(e=>parseInt(e,10));return[t,n,r,1]}if(e.startsWith(`rgba(`)){let t=e.slice(5,-1).split(`,`);return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}let t=e.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return t?[Math.round(parseFloat(t[1])*255),Math.round(parseFloat(t[2])*255),Math.round(parseFloat(t[3])*255),t[4]!==void 0&&t[4]!==`none`?parseFloat(t[4]):1]:null}function Ne(e){let t=Me(e);return t?t.slice(0,3):(T(`Not a valid color format: "${e}"`),[0,0,0])}function Pe(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,t.style.colorScheme=`only light`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Ne(r))}t.remove()}function B(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function V(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Fe(e,t,n=!1,r=!0){if(t instanceof _e){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-x))`,s=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-y))`;!n||t.rotation%180==0?(a.width=o,a.height=s):(a.width=s,a.height=o)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Ie=class e{constructor(){let{pixelRatio:t}=e;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,n,r,i,a=-1){let o=1/0,s=1/0,c=1/0;r=e.capPixels(r,a),r>0&&(o=Math.sqrt(r/(t*n))),i!==-1&&(s=i/t,c=i/n);let l=Math.min(o,s,c);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){let n=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,n):n}return e}},Le=[`image/apng`,`image/avif`,`image/bmp`,`image/gif`,`image/jpeg`,`image/png`,`image/svg+xml`,`image/webp`,`image/x-icon`],Re=class{static get isDarkMode(){return M(this,`isDarkMode`,!!window?.matchMedia?.(`(prefers-color-scheme: dark)`).matches)}},ze=class{static get commentForegroundColor(){let e=document.createElement(`span`);e.classList.add(`comment`,`sidebar`);let{style:t}=e;t.width=t.height=`0`,t.display=`none`,t.color=`var(--comment-fg-color)`,document.body.append(e);let{color:n}=window.getComputedStyle(e);return e.remove(),M(this,`commentForegroundColor`,Ne(n))}};function Be(e,t){t=L(t??1,0,1);let n=255*(1-t);return e.map(e=>Math.round(e*t+n))}function Ve(e,t){let n=e[0]/255,r=e[1]/255,i=e[2]/255,a=Math.max(n,r,i),o=Math.min(n,r,i),s=(a+o)/2;if(a===o)t[0]=t[1]=0;else{let e=a-o;switch(t[1]=s<.5?e/(a+o):e/(2-a-o),a){case n:t[0]=((r-i)/e+(ri?(r+.05)/(i+.05):(i+.05)/(r+.05)}var Ge=new Map;function Ke(e,t){let n=e[0]+e[1]*256+e[2]*65536+t[0]*16777216+t[1]*4294967296+t[2]*1099511627776,r=Ge.get(n);if(r)return r;let i=new Float32Array(9),a=i.subarray(0,3),o=i.subarray(3,6);Ve(e,o);let s=i.subarray(6,9);Ve(t,s);let c=s[2]<.5,l=c?12:4.5;if(o[2]=c?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),We(o,s,a).005;){let n=o[2]=(e+t)/2;c===We(o,s,a){n.delete()},{signal:n._signal}),this.#r.append(r)}get#p(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#f(t),this.#r.append(t,this.#p),this.#i=e}addComment(e,t=null){if(this.#a)return;let n=e.renderForToolbar();if(!n)return;this.#f(n);let r=this.#o=this.#p;t?(this.#r.insertBefore(n,t),this.#r.insertBefore(r,t)):this.#r.append(n,r),this.#a=e,e.toolbar=this}addColorPicker(e){if(this.#t)return;this.#t=e;let t=e.renderButton();this.#f(t),this.#r.append(t,this.#p)}async addEditSignatureButton(e){let t=this.#s=await e.renderEditButton(this.#n);this.#f(t),this.#r.append(t,this.#p)}removeButton(e){e===`comment`&&(this.#a?.removeToolbarCommentButton(),this.#a=null,this.#o?.remove(),this.#o=null)}async addButton(e,t){switch(e){case`colorPicker`:t&&this.addColorPicker(t);break;case`altText`:t&&await this.addAltText(t);break;case`editSignature`:t&&await this.addEditSignatureButton(t);break;case`delete`:this.addDeleteButton();break;case`comment`:t&&this.addComment(t)}}async addButtonBefore(e,t,n){if(!t&&e===`comment`)return;let r=this.#r.querySelector(n);r&&e===`comment`&&this.addComment(t,r)}updateEditSignatureButton(e){this.#s&&(this.#s.title=e)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},Xe=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`);let t=this.#n._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener(`contextmenu`,R,{signal:t});let n=this.#e=document.createElement(`div`);return n.className=`buttons`,e.append(n),this.#n.hasCommentManager()&&this.#a(`commentButton`,`pdfjs-comment-floating-button`,`pdfjs-comment-floating-button-label`,()=>{this.#n.commentSelection(`floating_button`)}),this.#a(`highlightButton`,`pdfjs-highlight-floating-button1`,`pdfjs-highlight-floating-button-label`,()=>{this.#n.highlightSelection(`floating_button`)}),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(en){r=a,n=e;continue}t?a>r&&(r=a):a=1}static clearPointerType(){e.#r=null}static clearPointerIds(){e.#e=NaN,e.#t=null}static clearTimeStamp(){e.#n=NaN}},$e=class{#e=0;get id(){return`${l}${this.#e++}`}},et=class e{#e=de();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=`data:image/svg+xml;charset=UTF-8,`,t=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),n=new Image;n.src=e;let r=n.decode().then(()=>(t.drawImage(n,0,0,1,1,0,0,1,3),new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]===0));return M(this,`_isSVGFittingCanvas`,r)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ce(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){T(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},tt=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},nt=class e{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;let{isMac:n}=F.platform;for(let[r,i,a={}]of t){let t=r.some(e=>e.startsWith(`mac+`));for(let o of r){let r=o;if(t){let e=o.startsWith(`mac+`);if(n!==e)continue;e&&(r=o.slice(4))}let[s,c]=e.#e(r);s!==null&&this.callbacks.getOrInsertComputed(s,pe).push({callback:i,options:a,modifiers:c})}}}static#e(t){let n=null,r=0;for(let i of t.split(`+`)){if(i=i.trim(),!i)continue;let a=i.toUpperCase(),o=e[a];if(o){r|=o;continue}if(n!==null){T(`KeyboardManager: multiple keys in shortcut "${t}"`);break}n=a===`SPACE`?` `:i}return n===null&&T(`KeyboardManager: no key found in shortcut "${t}"`),[n,r]}static#t(e){let t=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(e);return t?t[1]?.toLowerCase()??t[2]:null}exec(t,n){let r=this.callbacks.get(n.key);if(!r){if(/^[a-z]$/i.test(n.key))return;let t=e.#t(n.code);if(t===null||t===n.key||(r=this.callbacks.get(t),!r))return}let i=(n.altKey?e.ALT:0)|(n.ctrlKey?e.CTRL:0)|(n.metaKey?e.META:0)|(n.shiftKey?e.SHIFT:0),a=r.find(e=>e.modifiers===i);if(!a)return;let{callback:o,options:{bubbles:s=!1,args:c=[],checker:l=null}}=a;l&&!l(t,n)||(o.bind(t,...c,n)(),s||z(n))}},rt=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Pe(e),M(this,`_colors`,e)}convert(t){let n=Ne(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?I.makeHexColor(...t):e}},it=class e{#e=new AbortController;#t=null;#n=null;#r=new Map;#i=new Map;#a=null;#o=null;#s=null;#c=null;#l=new tt;#u=null;#d=null;#f=null;#p=0;#m=new Set;#h=null;#g=null;#_=new Set;_editorUndoBar=null;#v=!1;#y=!1;#b=!1;#x=null;#S=null;#C=null;#w=null;#T=!1;#E=null;#D=new $e;#O=!1;#k=!1;#A=!1;#j=null;#M=null;#N=null;#P=null;#F=null;#I=u.NONE;#L=new Set;#R=null;#z=null;#B=null;#V=null;#H=null;#U={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#W=[0,0];#G=null;#K=null;#q=null;#J=null;#Y=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#K.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return M(this,`_keyboardManager`,new nt([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`Backspace`,`alt+Backspace`,`ctrl+Backspace`,`shift+Backspace`,`mac+Backspace`,`mac+alt+Backspace`,`mac+ctrl+Backspace`,`Delete`,`ctrl+Delete`,`shift+Delete`,`mac+Delete`],t.delete,{checker:r}],[[`Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#K.contains(t)&&!e.isEnterHandled}],[[`Space`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#K.contains(document.activeElement)}],[[`Escape`],t.unselectAll],[[`ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this._signal=this.#e.signal;this.#K=e,this.#q=t,this.#J=n,this.#o=r,this.#u=i,this.#z=a,this.#H=s,this._eventBus=o;let _={signal:g,...Ze};o.on(`editingaction`,this.onEditingAction.bind(this),_),o.on(`pagechanging`,this.onPageChanging.bind(this),_),o.on(`scalechanging`,this.onScaleChanging.bind(this),_),o.on(`rotationchanging`,this.onRotationChanging.bind(this),_),o.on(`setpreference`,this.onSetPreference.bind(this),_),o.on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),_),window.addEventListener(`pointerdown`,()=>{this.#k=!0},{capture:!0,signal:g}),window.addEventListener(`pointerup`,()=>{this.#k=!1},{capture:!0,signal:g}),window.addEventListener(`beforeunload`,this.endCurrentEditing.bind(this),{capture:!0,signal:g}),this.#te(),this.#ce(),this.#ie(),this.#s=s.annotationStorage,this.#x=s.filterFactory,this.#B=c,this.#w=l||null,this.#v=u,this.#y=d,this.#b=f,this.#F=p||null,this.viewParameters={realScale:Se.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=m||null,this._supportsPinchToZoom=h!==!1,i?.setSidebarUiManager(this)}destroy(){this.#Y?.resolve(),this.#Y=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#i.values())e.destroy();this.#i.clear(),this.#r.clear(),this.#_.clear(),this.#P?.clear(),this.#t=null,this.#L.clear(),this.#l.destroy(),this.#o?.destroy(),this.#u?.destroy(),this.#z?.destroy(),this.#E?.hide(),this.#E=null,this.#N?.destroy(),this.#N=null,this.#n=null,this.#S&&=(clearTimeout(this.#S),null),this.#G&&=(clearTimeout(this.#G),null),this._editorUndoBar?.destroy(),this.#H=null}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#F}get useNewAltTextFlow(){return this.#y}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return M(this,`hcmFilter`,this.#B?this.#x.addHCMFilter(this.#B.foreground,this.#B.background):`none`)}get direction(){return M(this,`direction`,getComputedStyle(this.#K).direction)}get _highlightColors(){return M(this,`_highlightColors`,this.#w?new Map(this.#w.split(`,`).map(e=>(e=e.split(`=`).map(e=>e.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){let{_highlightColors:e}=this;if(!e)return M(this,`highlightColors`,null);let t=new Map,n=!!this.#B;for(let[r,i]of e){let e=r.endsWith(`_HCM`);if(n&&e){t.set(r.replace(`_HCM`,``),i);continue}!n&&!e&&t.set(r,i)}return M(this,`highlightColors`,t)}get highlightColorNames(){return M(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;let t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#f=e}setMainHighlightColorPicker(e){this.#N=e}editAltText(e,t=!1){this.#o?.editAltText(this,e,t)}hasCommentManager(){return!!this.#u}editComment(e,t,n,r){this.#u?.showDialog(this,e,t,n,r)}selectComment(e,t){(this.#i.get(e)?.getEditorByUID(t))?.toggleComment(!0,!0)}updateComment(e){this.#u?.updateComment(e.getData())}updatePopupColor(e){this.#u?.updatePopupColor(e)}removeComment(e){this.#u?.removeComments([e.uid])}deleteComment(e,t){let n=()=>{e.comment=t};this.addCommands({cmd:()=>{this._editorUndoBar?.show(n,`comment`),this.toggleComment(null),e.comment=null},undo:n,mustExec:!0})}toggleComment(e,t,n=void 0){this.#u?.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){return e&&this.#u?.makeCommentColor(e,t)||null}getCommentDialogElement(){return this.#u?.dialogElement||null}async waitForEditorsRendered(e){if(this.#i.has(e-1))return;let{resolve:t,promise:n}=Promise.withResolvers(),r=n=>{n.pageNumber===e&&(this._eventBus.off(`editorsrendered`,r),t())};this._eventBus.on(`editorsrendered`,r,Ze),await n}getSignature(e){this.#z?.getSignature({uiManager:this,editor:e})}get signatureManager(){return this.#z}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal,...Ze}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){e===`enableNewAltTextWhenAddingImage`&&(this.#b=t)}onPageChanging({pageNumber:e}){this.#p=e-1}deletePage(e){for(let t of this.getEditors(e))t.remove();this.#i.delete(e),this.#p===e&&(this.#p=0)}focusMainContainer(){this.#K.focus()}findParent(e,t){for(let n of this.#i.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#q.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#_.add(e)}removeShouldRescale(e){this.#_.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Se.PDF_TO_CSS_UNITS;for(let e of this.#_)e.onScaleChanging();this.#f?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#X({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#Z(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#i.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``,t=!1){let n=document.getSelection();if(!n||n.isCollapsed)return;let{anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o}=n,s=n.toString(),c=this.#X(n).closest(`.textLayer`),l=this.getSelectionBoxes(c);if(!l)return;n.empty();let d=this.#Z(c),f=this.#I===u.NONE,p=()=>{let n=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:l,anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o,text:s});f&&this.showAllEditors(`highlight`,!0,!0),t&&n?.editComment()};if(f){this.switchToMode(u.HIGHLIGHT,p);return}p()}commentSelection(e=``){this.highlightSelection(e,!0)}endCurrentEditing(){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Q(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#X(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#E||=new Xe(this),this.#E.show(t,n,this.direction===`ltr`))}getAndRemoveDataFromAnnotationStorage(e){if(!this.#s)return null;let t=`${l}${e}`,n=this.#s.getRawValue(t);return n&&this.#s.remove(t),n}addToAnnotationStorage(e){!e.isEmpty()&&this.#s&&!this.#s.has(e.id)&&this.#s.setValue(e.id,e)}a11yAlert(e,t=null){let n=this.#J;n&&(n.setAttribute(`data-l10n-id`,e),t?n.setAttribute(`data-l10n-args`,JSON.stringify(t)):n.removeAttribute(`data-l10n-args`))}#$(){let e=document.getSelection();if(!e||e.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#le({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#R)return;let n=this.#X(e).closest(`.textLayer`);if(!n){this.#R&&(this.#E?.hide(),this.#R=null,this.#le({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=t,this.#le({hasSelectedText:!0}),(this.#I===u.HIGHLIGHT||this.#I===u.NONE)&&(this.#I===u.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#T=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#I===u.HIGHLIGHT?this.#Z(n):null;if(e?.toggleDrawing(),this.#k){let t=new AbortController,n=this.combinedSignal(t),r=n=>{(n.type!==`pointerup`||n.button===0)&&(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#ee(`main_toolbar`))};window.addEventListener(`pointerup`,r,{signal:n}),window.addEventListener(`blur`,r,{signal:n})}else e?.toggleDrawing(!0),this.#ee(`main_toolbar`)}}#ee(e=``){this.#I===u.HIGHLIGHT?this.highlightSelection(e):this.#v&&this.#Q()}#te(){document.addEventListener(`selectionchange`,this.#$.bind(this),{signal:this._signal})}#ne(){if(this.#C)return;this.#C=new AbortController;let e=this.combinedSignal(this.#C);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#re(){this.#C?.abort(),this.#C=null}blur(){if(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#ee(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#L)if(t.div.contains(e)){this.#M=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#M)return;let[e,t]=this.#M;this.#M=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#ie(){if(this.#j)return;this.#j=new AbortController;let e=this.combinedSignal(this.#j);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#ae(){this.#j?.abort(),this.#j=null}#oe(){if(this.#d)return;this.#d=new AbortController;let e=this.combinedSignal(this.#d);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#se(){this.#d?.abort(),this.#d=null}#ce(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#ie(),this.setEditingState(!0)}removeEditListeners(){this.#ae(),this.setEditingState(!1)}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#g)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#g)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#L){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#g)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){T(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#pe(t);this.#ge(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){T(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#I!==u.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#ee(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`);break;case`commentSelection`:this.commentSelection(`context_menu`)}}updatePageIndex(e,t){for(let n of this.getEditors(e))n.pageIndex=t;let n=this.#a.get(e);n&&(n.pageIndex=t,this.#i.set(t,n),this.#O?n.enable():n.disable())}startUpdatePages(){this.#a=new Map(this.#i),this.#i.clear()}endUpdatePages(){this.#a=null}clonePage(e,t){for(let n of this.getEditors(e)){let e=n.serialize(n.mode!==u.HIGHLIGHT);e&&(e.pageIndex=t,e.id=this.getId(),e.isClone=!0,delete e.popupRef,this.#s.setValue(e.id,e))}}findClonesForPage(e){let t=[],{pageIndex:n}=e;for(let[r,i]of this.#s)i.pageIndex===n&&i.isClone&&(this.#s.remove(r),t.push(e.deserialize(i).then(t=>{t&&(t.isClone=!0,e.addOrRebuild(t))})));return Promise.all(t)}#le(e){Object.entries(e).some(([e,t])=>this.#U[e]!==t)&&(this._eventBus.dispatch(`editingstateschanged`,{source:this,details:Object.assign(this.#U,e)}),this.#I===u.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#ue([[d.HIGHLIGHT_FREE,!0]]))}#ue(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#ne(),this.#oe(),this.#le({isEditing:this.#I!==u.NONE,isEmpty:this.#he(),hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:this.#l.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#re(),this.#se(),this.#le({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#g){this.#g=e;for(let e of this.#g)this.#ue(e.defaultPropertiesToUpdate)}}getId(){return this.#D.id}get currentLayer(){return this.#i.get(this.#p)}getLayer(e){return this.#i.get(e)}get currentPageIndex(){return this.#p}addLayer(e){this.#i.set(e.pageIndex,e),this.#O?e.enable():e.disable()}removeLayer(e){this.#i.delete(e.pageIndex)}async updateMode(e,t=null,n=!1,r=!1,i=!1,a=!1){if(this.#I!==e&&!(this.#Y&&(await this.#Y.promise,!this.#Y))){if(this.#Y=Promise.withResolvers(),this.#f?.commitOrRemove(),this.#I===u.POPUP&&this.#u?.hideSidebar(),this.#u?.destroyPopup(),this.#I=e,e===u.NONE){this.setEditingState(!1),this.#fe();for(let e of this.#r.values())e.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#Y.resolve();return}for(let e of this.#r.values())e.addStandaloneCommentButton();e===u.SIGNATURE&&await this.#z?.loadSignatures(),n&&H.clearPointerType(),this.setEditingState(!0),await this.#de(),this.unselectAll();for(let t of this.#i.values())t.updateMode(e);if(e===u.POPUP){this.#n||=await this.#H.getAnnotationsByType(new Set(this.#g.map(e=>e._editorType)));let e=new Set,t=[];for(let n of this.#r.values()){let{annotationElementId:r,hasComment:i,deleted:a}=n;r&&e.add(r),i&&!a&&t.push(n.getData())}for(let n of this.#n){let{id:r,popupRef:i,contentsObj:a}=n;i&&a?.str&&!e.has(r)&&!this.#m.has(r)&&t.push(n)}this.#u?.showSidebar(t)}if(!t){r&&this.addNewEditorFromKeyboard(),this.#Y.resolve();return}for(let e of this.#r.values())e.uid===t?(this.setSelected(e),a?e.editComment():i?e.enterInEditMode():e.focus()):e.unselect();this.#Y.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==this.#I&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,...e})}updateParams(e,t){if(this.#g){switch(e){case d.CREATE:this.currentLayer.addNewEditor(t);return;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#V||=new Map).set(e,t),this.showAllEditors(`highlight`,t)}if(this.hasSelection)for(let n of this.#L)n.updateParams(e,t);else for(let n of this.#g)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#r.values())n.editorType===e&&n.show(t);(this.#V?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#ue([[d.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#A!==e){this.#A=e;for(let t of this.#i.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#de(){if(!this.#O){this.#O=!0;let e=[];for(let t of this.#i.values())e.push(t.enable());await Promise.all(e);for(let e of this.#r.values())e.enable()}}#fe(){if(this.unselectAll(),this.#O){this.#O=!1;for(let e of this.#i.values())e.disable();for(let e of this.#r.values())e.disable()}}*getEditors(e){for(let t of this.#r.values())t.pageIndex===e&&(yield t)}getEditor(e){return this.#r.get(e)}addEditor(e){this.#r.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#S&&clearTimeout(this.#S),this.#S=setTimeout(()=>{this.focusMainContainer(),this.#S=null},0)),this.#r.delete(e.id),e.annotationElementId&&this.#P?.delete(e.annotationElementId),this.unselect(e),(!e.annotationElementId||!this.#m.has(e.annotationElementId))&&this.#s?.remove(e.id)}addDeletedAnnotationElement(e){this.#m.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#m.has(e)}removeDeletedAnnotationElement(e){this.#m.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#pe(e){let t=this.#i.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#ue(e.propertiesToUpdate))}get#me(){let e=null;for(e of this.#L);return e}updateUI(e){this.#me===e&&this.#ue(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#ue(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#L.has(e)){this.#L.delete(e),e.unselect(),this.#le({hasSelectedEditor:this.hasSelection});return}this.#L.add(e),e.select(),this.#ue(e.propertiesToUpdate),this.#le({hasSelectedEditor:!0})}setSelected(e){this.updateToolbar({mode:e.mode,editId:e.uid}),this.#f?.commitOrRemove();for(let t of this.#L)t!==e&&t.unselect();this.#u?.destroyPopup(),this.#L.clear(),this.#L.add(e),e.select(),this.#ue(e.propertiesToUpdate),this.#le({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#L.values().next().value}unselect(e){e.unselect(),this.#L.delete(e),this.#le({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#L.size!==0}get isEnterHandled(){return this.#L.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#l.undo(),this.#le({hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#he()}),this._editorUndoBar?.hide()}redo(){this.#l.redo(),this.#le({hasSomethingToUndo:!0,hasSomethingToRedo:this.#l.hasSomethingToRedo(),isEmpty:this.#he()})}addCommands(e){this.#l.add(e),this.#le({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#he()})}cleanUndoStack(e){this.#l.cleanType(e)}#he(){if(this.#r.size===0)return!0;if(this.#r.size===1)for(let e of this.#r.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#L],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#pe(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ge(e){for(let e of this.#L)e.unselect();this.#L.clear();for(let t of e)t.isEmpty()||(this.#L.add(t),t.select());this.#le({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#L)e.commit();this.#ge(this.#r.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#I!==u.NONE))&&!this.#f?.commitOrRemove()&&(this.#u?.destroyPopup(),this.hasSelection)){for(let e of this.#L)e.unselect();this.#L.clear(),this.#le({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#W[0]+=e,this.#W[1]+=t;let[r,i]=this.#W,a=[...this.#L];this.#G&&clearTimeout(this.#G),this.#G=setTimeout(()=>{this.#G=null,this.#W[0]=this.#W[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(r,i),e.translationDone())},undo:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(-r,-i),e.translationDone())},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t),n.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#h=new Map;for(let e of this.#L)this.#h.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#h)return!1;this.disableUserSelect(!1);let e=this.#h;this.#h=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#r.has(e.id)){let i=this.#i.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#h)for(let n of this.#h.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#L.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#I}isEditingMode(){return this.#I!==u.NONE}get imageManager(){return M(this,`imageManager`,new et)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a})}let s=[];for(let e=0,n=t.rangeCount;ee.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),(this.#e!==e||this.#t!==t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getElementForAltText()?.setAttribute(`aria-describedby`,n.id)}},ot=class{#e=null;#t=null;#n=!1;#r=null;#i=null;#a=null;#o=null;#s=null;#c=!1;#l=null;constructor(e){this.#r=e}renderForToolbar(){let e=this.#t=document.createElement(`button`);return e.className=`comment`,this.#u(e,!1)}renderForStandalone(){let e=this.#e=document.createElement(`button`);e.className=`annotationCommentButton`;let t=this.#r.commentButtonPosition;if(t){let{style:n}=e;n.insetInlineEnd=`calc(${100*(this.#r._uiManager.direction===`ltr`?1-t[0]:t[0])}% - var(--comment-button-dim))`,n.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;let r=this.#r.commentButtonColor;r&&(n.backgroundColor=r)}return this.#u(e,!0)}focusButton(){setTimeout(()=>{(this.#e??this.#t)?.focus()},0)}onUpdatedColor(){if(!this.#e)return;let e=this.#r.commentButtonColor;e&&(this.#e.style.backgroundColor=e),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#e?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#l)return this.#l;if(!this.#e)return null;let{x:e,y:t,height:n}=this.#e.getBoundingClientRect(),{x:r,y:i,width:a,height:o}=this.#r.parent.boundingClientRect;return[(e-r)/a,(t+n-i)/o]}set commentPopupPositionInLayer(e){this.#l=e}hasDefaultPopupPosition(){return this.#l===null}removeStandaloneCommentButton(){this.#e?.remove(),this.#e=null}removeToolbarCommentButton(){this.#t?.remove(),this.#t=null}setCommentButtonStates({selected:e,hasPopup:t}){this.#e&&(this.#e.classList.toggle(`selected`,e),this.#e.ariaExpanded=t)}#u(e,t){if(!this.#r._uiManager.hasCommentManager())return null;e.tabIndex=`0`,e.ariaHasPopup=`dialog`,t?(e.ariaControls=`commentPopup`,e.setAttribute(`data-l10n-id`,`pdfjs-show-comment-button`)):(e.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],e.setAttribute(`data-l10n-id`,`pdfjs-editor-add-comment-button`));let n=this.#r._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;e.addEventListener(`contextmenu`,R,{signal:n}),t&&(e.addEventListener(`focusin`,e=>{this.#r._focusEventsAllowed=!1,z(e)},{capture:!0,signal:n}),e.addEventListener(`focusout`,e=>{this.#r._focusEventsAllowed=!0,z(e)},{capture:!0,signal:n})),e.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:n});let r=t=>{t.preventDefault(),e===this.#t?this.edit():this.#r.toggleComment(!0)};return e.addEventListener(`click`,r,{capture:!0,signal:n}),e.addEventListener(`keydown`,t=>{t.target===e&&t.key===`Enter`&&(this.#n=!0,r(t))},{signal:n}),e.addEventListener(`pointerenter`,()=>{this.#r.toggleComment(!1,!0)},{signal:n}),e.addEventListener(`pointerleave`,()=>{this.#r.toggleComment(!1,!1)},{signal:n}),e}edit(e){let t=this.commentPopupPositionInLayer,n,r;if(t)[n,r]=t;else{[n,r]=this.#r.commentButtonPosition;let{width:e,height:t,x:i,y:a}=this.#r;n=i+n*e,r=a+r*t}let i=this.#r.parent.boundingClientRect,{x:a,y:o,width:s,height:c}=i;this.#r._uiManager.editComment(this.#r,a+n*s,o+r*c,{...e,parentDimensions:i})}finish(){this.#t&&(this.#t.focus({focusVisible:this.#n}),this.#n=!1)}isDeleted(){return this.#c||this.#o===``}isEmpty(){return this.#o===null}hasBeenEdited(){return this.isDeleted()||this.#o!==this.#i}serialize(){return this.data}get data(){return{text:this.#o,richText:this.#a,date:this.#s,deleted:this.isDeleted()}}set data(e){if(e!==this.#o&&(this.#a=null),e===null){this.#o=``,this.#c=!0;return}this.#o=e,this.#s=new Date,this.#c=!1}restoreData({text:e,richText:t,date:n}){this.#o=e,this.#a=t,this.#s=n,this.#c=!1}setInitialText(e,t=null){this.#i=e,this.data=e,this.#s=null,this.#a=t}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#e?.remove(),this.#e=null,this.#o=``,this.#a=null,this.#s=null,this.#r=null,this.#n=!1,this.#c=!1}},st=class e{#e;#t=!1;#n=null;#r;#i;#a;#o;#s=null;#c;#l=null;#u;#d=null;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,signal:o}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#u=new AbortController,this.#c=AbortSignal.any([o,this.#u.signal]),e.addEventListener(`touchstart`,this.#f.bind(this),{passive:!1,signal:this.#c})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Ie.pixelRatio}#f(e){if(this.#r?.())return;if(e.touches.length===1){if(this.#s)return;let e=this.#s=new AbortController,t=AbortSignal.any([this.#c,e.signal]),n=this.#e,r={capture:!0,signal:t,passive:!1},i=e=>{e.pointerType===`touch`&&(this.#s?.abort(),this.#s=null)};n.addEventListener(`pointerdown`,e=>{e.pointerType===`touch`&&(z(e),i(e))},r),n.addEventListener(`pointerup`,i,r),n.addEventListener(`pointercancel`,i,r);return}if(!this.#d){this.#d=new AbortController;let e=AbortSignal.any([this.#c,this.#d.signal]),t=this.#e,n={signal:e,capture:!1,passive:!1};t.addEventListener(`touchmove`,this.#p.bind(this),n);let r=this.#m.bind(this);t.addEventListener(`touchend`,r,n),t.addEventListener(`touchcancel`,r,n),n.capture=!0,t.addEventListener(`pointerdown`,z,n),t.addEventListener(`pointermove`,z,n),t.addEventListener(`pointercancel`,z,n),t.addEventListener(`pointerup`,z,n),this.#i?.()}if(z(e),e.touches.length!==2||this.#n?.()){this.#l=null;return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),this.#l={touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY}}#p(t){if(!this.#l||t.touches.length!==2)return;z(t);let[n,r]=t.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:a}=n,{screenX:o,screenY:s}=r,c=this.#l,{touch0X:l,touch0Y:u,touch1X:d,touch1Y:f}=c,p=d-l,m=f-u,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=Math.hypot(p,m)||1;if(!this.#t&&Math.abs(v-_)<=e.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=a,c.touch1X=o,c.touch1Y=s,!this.#t){this.#t=!0;return}let y=[(i+o)/2,(a+s)/2];this.#a?.(y,v,_)}#m(e){e.touches.length>=2||(this.#d&&(this.#d.abort(),this.#d=null,this.#o?.()),this.#l&&(z(e),this.#l=null,this.#t=!1))}destroy(){this.#u?.abort(),this.#u=null,this.#s?.abort(),this.#s=null}},U=class e{#e=null;#t=null;#n=null;#r=null;#i=null;#a=!1;#o=null;#s=``;#c=null;#l=null;#u=null;#d=null;#f=null;#p=``;#m=!1;#h=null;#g=!1;#_=!1;#v=!1;#y=null;#b=0;#x=0;#S=null;#C=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#w=!1;#T=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new rt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=it.TRANSLATE_SMALL,r=it.TRANSLATE_BIG;return M(this,`_resizerKeyboardManager`,new nt([[[`ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return M(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new ct({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._l10nAlert??=Object.freeze({highlight:`pdfjs-editor-highlight-added-alert`,freetext:`pdfjs-editor-freetext-added-alert`,ink:`pdfjs-editor-ink-added-alert`,stamp:`pdfjs-editor-stamp-added-alert`,signature:`pdfjs-editor-signature-added-alert`}),e._l10nResizer??=Object.freeze({topLeft:`pdfjs-editor-resizer-top-left`,topMiddle:`pdfjs-editor-resizer-top-middle`,topRight:`pdfjs-editor-resizer-top-right`,middleRight:`pdfjs-editor-resizer-middle-right`,bottomRight:`pdfjs-editor-resizer-bottom-right`,bottomMiddle:`pdfjs-editor-resizer-bottom-middle`,bottomLeft:`pdfjs-editor-resizer-bottom-left`,middleLeft:`pdfjs-editor-resizer-middle-left`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){E(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(e){this.#w=e,this.div?.classList.toggle(`draggable`,e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#T}setParent(e){e===null?(this.#W(),this.#d?.remove(),this.#d=null):(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#m?this.#m=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r),this._onTranslated()}#E([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#E(this.parentDimensions,e,t)}translateInPage(e,t){this.#h||=[this.x,this.y,this.width,this.height],this.#E(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){this.#h||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o),n.scrollIntoView({block:`nearest`})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#h&&(this.#h[0]!==this.x||this.#h[1]!==this.y)}get _hasBeenResized(){return!!this.#h&&(this.#h[2]!==this.width||this.#h[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=L(i,0,n-o),a=L(a,0,r-s);break;case 90:i=L(i,0,n-s),a=L(a,o,r);break;case 180:i=L(i,o,n),a=L(a,s,r);break;case 270:i=L(i,s,n),a=L(a,0,r-o)}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#D(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#D(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#D(t,n,360-this.parentRotation)}#O(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(){let{div:{style:e},width:t,height:n}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*n).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#k(){if(this.#c)return;this.#c=document.createElement(`div`),this.#c.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#c.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#A.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,R,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#c)}#A(e,t){t.preventDefault();let{isMac:n}=F.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#l=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#N.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,z,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,R,{signal:a}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#M()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#j(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#M(){if(!this.#u)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#u;this.#u=null;let i=this.x,a=this.y,o=this.width,s=this.height;(i!==e||a!==t||o!==n||s!==r)&&this.addCommands({cmd:this.#j.bind(this,i,a,o,s),undo:this.#j.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#N(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#O(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#O(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2]}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#l;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#l[0]=e,this.#l[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=L(Math.abs(b[0]-y[0]-E),l,1)/s:T=L(Math.abs(b[1]-y[1]-D),u,1)/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#h||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#_)return this._editToolbar;this._editToolbar=new Ye(this),this.div.append(this._editToolbar.render());let{toolbarButtons:e}=this;if(e)for(let[t,n]of e)await this._editToolbar.addButton(t,n);return this.hasComment||this._editToolbar.addButton(`comment`,this.addCommentButton()),this._editToolbar.addButton(`delete`),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore(`comment`,this.addCommentButton(),`.deleteButton`)}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton(`comment`)}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#n?.destroy()}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#n||(at.initialize(e._l10n),this.#n=new at(this),this.#e&&=(this.#n.data=this.#e,null)),this.#n}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}focusCommentButton(){this.#r?.focusButton()}addCommentButton(){return this.canAddComment?this.#r||=new ot(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(this.#i){this._uiManager.isEditingMode()&&this.#i.classList.remove(`hidden`);return}this.hasComment&&(this.#i=this.#r.renderForStandalone(),this.div.append(this.#i))}}removeStandaloneCommentButton(){this.#r.removeStandaloneCommentButton(),this.#i=null}hideStandaloneCommentButton(){this.#i?.classList.add(`hidden`)}get comment(){if(!this.#r)return null;let{data:{richText:e,text:t,date:n,deleted:r}}=this.#r;return{text:t,richText:e,date:n,deleted:r,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){this.#r||=new ot(this),typeof e==`object`&&e?this.#r.restoreData(e):this.#r.data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:n}){if(!t||(this.#r||=new ot(this),this.#r.setInitialText(e,n),!this.annotationElementId))return;let r=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);r&&this.updateFromAnnotationLayer(r)}get hasEditedComment(){return this.#r?.hasBeenEdited()}get hasDeletedComment(){return this.#r?.isDeleted()}get hasComment(){return!!this.#r&&!this.#r.isEmpty()&&!this.#r.isDeleted()}async editComment(e){this.#r||=new ot(this),this.#r.edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){this.#r.setSelectedButton(e)}addComment(e){if(this.hasEditedComment){let[,,,t]=e.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,i=r+n+1,a=t-100,o=i+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[i,a,o,t]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){this.#r.data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let e=this.div=document.createElement(`div`);e.setAttribute(`data-editor-rotation`,(360-this.rotation)%360),e.className=this.name,e.setAttribute(`id`,this.id),e.tabIndex=this.#a?-1:0,e.setAttribute(`role`,`application`),this.defaultL10nId&&e.setAttribute(`data-l10n-id`,this.defaultL10nId),this._isVisible||e.classList.add(`hidden`),this.setInForeground(),this.#z();let[t,n]=this.parentDimensions;this.parentRotation%180!=0&&(e.style.maxWidth=`${(100*n/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/n).toFixed(2)}%`);let[r,i]=this.getInitialTranslation();return this.translate(r,i),Qe(this,e,[`keydown`,`pointerdown`,`dblclick`]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#C||=new st({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#P.bind(this),onPinching:this.#F.bind(this),onPinchEnd:this.#I.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),e}#P(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#F(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#O(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#h||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#I(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#M()}pointerdown(e){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#m=!0,this._isDraggable){this.#R(e);return}this.#L(e)}#L(e){let{isMac:t}=F.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#R(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#o=null,this.#m=!1,this._uiManager.endDragSession()||this.#L(e),n&&this._onStopDragging()};t&&(this.#b=e.clientX,this.#x=e.clientY,this.#o=e.pointerId,this.#s=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#o){z(e);return}let[a,o]=this.screenToPageTranslation(t-this.#b,r-this.#x);this.#b=t,this.#x=r,this._uiManager.dragSelectedEditors(a,o)},a),window.addEventListener(`touchmove`,z,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#s&&(this.#C||e.isPrimary)&&o(e),z(e)},a));let s=e=>{if(!this.#o||this.#o===e.pointerId){o(e);return}z(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.#y=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&e._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#r?.onUpdatedColor()}getData(){let{comment:{text:e,color:t,date:n,opacity:r,deleted:i,richText:a},uid:o,pageIndex:s,creationDate:c,modificationDate:l}=this;return{id:o,pageIndex:s,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:n||l,popupRef:!i,color:t,opacity:r}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#_=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#_=!1,!0):!1}isInEditMode(){return this.#_}shouldGetKeyboardEvents(){return this.#v}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t0&&e0}#z(){if(this.#f||!this.div)return;this.#f=new AbortController;let e=this._uiManager.combinedSignal(this.#f);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}rebuild(){this.#z()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||``}}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:n.getId(),uiManager:n,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});r.rotation=e.rotation,r.#e=e.accessibilityData,r._isCopy=e.isCopy||!1;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#f?.abort(),this.#f=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#y&&=(clearTimeout(this.#y),null),this.#W(),this.removeEditToolbar(),this.#S){for(let e of this.#S.values())clearTimeout(e);this.#S=null}this.parent=null,this.#C?.destroy(),this.#C=null,this.#d?.remove(),this.#d=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#k(),this.#c.classList.remove(`hidden`))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction===`ltr`?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[t,n]}=this,[r,i,a,o]=this.getPDFRect();return[e._round(r+(a-r)*t),e._round(i+(o-i)*(1-n))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#r.commentPopupPositionInLayer}set commentPopupPosition(e){this.#r.commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return this.#r.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#r.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){this.#r?.setCommentButtonStates(e)}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!==`Enter`)return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#c.children;if(!this.#t){this.#t=Array.from(n);let t=this.#B.bind(this),r=this.#V.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#H.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(ai)for(let e=0;e{this.div?.classList.contains(`selectedEditor`)&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#c?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!==`BUTTON`&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(e){this.#g=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#S||=new Map;let{action:n}=t,r=this.#S.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#S.delete(n),this.#S.size===0&&(this.#S=null)},e._telemetryTimeout),this.#S.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#a=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#a=!0}updateFakeAnnotationElement(e){if(!this.#d&&!this.deleted){this.#d=e.addFakeAnnotation(this);return}if(this.deleted){this.#d.remove(),this.#d=null;return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#d.updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstElementChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},ct=class extends U{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},lt=3285377520,W=4294901760,ut=65535,dt=class{constructor(e){this.h1=e?e&4294967295:lt,this.h2=e?e&4294967295:lt}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e>>17,o=o*d&W|o*p&ut,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&W|s*f&ut,s=s<<15|s>>>17,s=s*d&W|s*p&ut,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&W|o*f&ut,o=o<<15|o>>>17,o=o*d&W|o*p&ut,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&W|e*36045&ut,t=t*4283543511&W|((t<<16|e>>>16)*2950163797&W)>>>16,e^=t>>>1,e=e*444984403&W|e*60499&ut,t=t*3301882366&W|((t<<16|e>>>16)*3120437893&W)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},ft=Object.freeze({map:null,hash:``,transfer:void 0}),pt=class{#e=!1;#t=null;#n=null;#r=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(e,t){let n=this.#r.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#r.get(e)}remove(e){let t=this.#r.get(e);t!==void 0&&(t instanceof U&&this.#n.delete(t.annotationElementId),this.#r.delete(e),this.#r.size===0&&this.resetModified(),!this.#r.values().some(e=>e instanceof U)&&this.onAnnotationEditor?.(null))}setValue(e,t){let n=this.#r.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#r.set(e,t);r&&this.#i(),t instanceof U&&((this.#n||=new Map).set(t.annotationElementId,t),this.onAnnotationEditor?.(t.constructor._type))}has(e){return this.#r.has(e)}get size(){return this.#r.size}#i(){this.#e||(this.#e=!0,this.onSetModified?.())}resetModified(){this.#e&&(this.#e=!1,this.onResetModified?.())}get print(){return new mt(this)}get serializable(){if(this.#r.size===0)return ft;let e=new Map,t=new dt,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#r){let o=a instanceof U?a.serialize(!1,r):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:ft}get editorStats(){let e=null,t=new Map,n=0,r=0;for(let i of this.#r.values()){if(!(i instanceof U)){i.popup&&(i.popup.deleted?r+=1:n+=1);continue}i.isCommentDeleted?r+=1:i.hasEditedComment&&(n+=1);let a=i.telemetryFinalData;if(!a)continue;let{type:o}=a;t.getOrInsertComputed(o,()=>Object.getPrototypeOf(i).constructor),e||=Object.create(null);let s=e[o]||=new Map;for(let[e,t]of Object.entries(a)){if(e===`type`)continue;let n=s.getOrInsertComputed(e,me);n.set(t,(n.get(t)??0)+1)}}if((r>0||n>0)&&(e||=Object.create(null),e.comments={deleted:r,edited:n}),!e)return null;for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}updateEditor(e,t){let n=this.#n?.get(e);return n?(n.updateFromAnnotationLayer(t),!0):!1}getEditor(e){return this.#n?.get(e)||null}get modifiedIds(){if(this.#t)return this.#t;let e=[];if(this.#n)for(let t of this.#n.values())t.serialize()&&e.push(t.annotationElementId);let t=``;if(e.length){let n=new dt;n.update(e.join(`,`)),t=n.hexdigest()}return this.#t={ids:new Set(e),hash:t}}[Symbol.iterator](){return this.#r.entries()}},mt=class extends pt{#e=ft;constructor(e){super();let{serializable:t}=e;if(t===ft)return;let{map:n,hash:r,transfer:i}=t,a=structuredClone(n,i?{transfer:i}:null);this.#e={map:a,hash:r,transfer:[]}}get print(){E(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return M(this,`modifiedIds`,{ids:new Set,hash:``})}},ht=`__forcedDependency`,{floor:gt,ceil:_t}=Math;function vt(e,t,n,r,i,a){e[t*4+0]=Math.min(e[t*4+0],n),e[t*4+1]=Math.min(e[t*4+1],r),e[t*4+2]=Math.max(e[t*4+2],i),e[t*4+3]=Math.max(e[t*4+3],a)}function yt(e,t,n,r,i){let a;e?(e<0&&(a=i[0],i[0]=i[2],i[2]=a),i[0]*=e,i[2]*=e,t<0&&(a=i[1],i[1]=i[3],i[3]=a),i[1]*=t,i[3]*=t):i.fill(0),i[0]+=n,i[1]+=r,i[2]+=n,i[3]+=r}var bt=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0],xt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get length(){return this.#e.length}isEmpty(e){return this.#e[e]===bt}minX(e){return this.#t[e*4+0]/256}minY(e){return this.#t[e*4+1]/256}maxX(e){return(this.#t[e*4+2]+1)/256}maxY(e){return(this.#t[e*4+3]+1)/256}},St=(e,t)=>e?.getOrInsertComputed(t,()=>({dependencies:new Set,isRenderingOperation:!1})),Ct=class{#e=[[1,0,0,1,0,0]];#t=[-1/0,-1/0,1/0,1/0];#n=new Float64Array(n);_pendingBBoxIdx=-1;#r;#i;#a;#o;_savesStack=[];_markedContentStack=[];constructor(e,t){this.#r=e.width,this.#i=e.height,this.#s(t)}growOperationsCount(e){e>=this.#o.length&&this.#s(e,this.#o)}#s(e,t){let n=new ArrayBuffer(e*4);this.#a=new Uint8ClampedArray(n),this.#o=new Uint32Array(n),t&&t.length>0?(this.#o.set(t),this.#o.fill(bt,t.length)):this.#o.fill(bt)}get clipBox(){return this.#t}save(e){return this.#t={__proto__:this.#t},this._savesStack.push(e),this}restore(e,t){let n=Object.getPrototypeOf(this.#t);if(n===null)return this;this.#t=n;let r=this._savesStack.pop();return r!==void 0&&(t?.(r,e),this.#o[e]=this.#o[r]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){let n=this._savesStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){let n=this._markedContentStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}pushBaseTransform(e){return this.#e.push(I.multiplyByDOMMatrix(this.#e.at(-1),e.getTransform())),this}popBaseTransform(){return this.#e.length>1&&this.#e.pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,this.#n.set(n,0)),this}recordClipBox(e,t,r,i,a,o){let s=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform()),c=n.slice();I.axialAlignedBoundingBox([r,a,i,o],s,c);let l=I.intersect(this.#t,c);return l?(this.#t[0]=l[0],this.#t[1]=l[1],this.#t[2]=l[2],this.#t[3]=l[3]):(this.#t[0]=this.#t[1]=1/0,this.#t[2]=this.#t[3]=-1/0),this}recordBBox(e,t,r,i,a,o){let s=this.#t;if(s[0]===1/0)return this;let c=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform());if(s[0]===-1/0)return I.axialAlignedBoundingBox([r,a,i,o],c,this.#n),this;let l=n.slice();return I.axialAlignedBoundingBox([r,a,i,o],c,l),this.#n[0]=L(l[0],s[0],this.#n[0]),this.#n[1]=L(l[1],s[1],this.#n[1]),this.#n[2]=L(l[2],this.#n[2],s[2]),this.#n[3]=L(l[3],this.#n[3],s[3]),this}recordFullPageBBox(e){return this.#n[0]=Math.max(0,this.#t[0]),this.#n[1]=Math.max(0,this.#t[1]),this.#n[2]=Math.min(this.#r,this.#t[2]),this.#n[3]=Math.min(this.#i,this.#t[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;let r=gt(this.#n[0]*256/this.#r),i=gt(this.#n[1]*256/this.#i),a=_t(this.#n[2]*256/this.#r),o=_t(this.#n[3]*256/this.#i);if(vt(this.#a,e,r,i,a,o),n)for(let t of n)for(let n of t)n!==e&&vt(this.#a,n,r,i,a,o);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,this.#t[0]=Math.max(this.#t[0],this.#n[0]),this.#t[1]=Math.max(this.#t[1],this.#n[1]),this.#t[2]=Math.min(this.#t[2],this.#n[2]),this.#t[3]=Math.min(this.#t[3],this.#n[3])),this}take(){return new xt(this.#o,this.#a)}takeDebugMetadata(){throw Error(`Unreachable`)}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}},wt=class{#e={__proto__:null};#t={__proto__:null,transform:[],moveText:[],sameLineText:[],[ht]:[]};#n=new Map;#r=new Set;#i=new Map;#a;#o;#s;constructor(e,t=!1){this.#s=e,t&&(this.#a=new Map,this.#o=(e,t)=>{St(this.#a,t).dependencies.add(e)})}get clipBox(){return this.#s.clipBox}growOperationsCount(e){this.#s.growOperationsCount(e)}save(e){return this.#e={__proto__:this.#e},this.#t={__proto__:this.#t,transform:{__proto__:this.#t.transform},moveText:{__proto__:this.#t.moveText},sameLineText:{__proto__:this.#t.sameLineText},[ht]:{__proto__:this.#t[ht]}},this.#s.save(e),this}restore(e){this.#s.restore(e,this.#o);let t=Object.getPrototypeOf(this.#e);return t===null?this:(this.#e=t,this.#t=Object.getPrototypeOf(this.#t),this)}recordOpenMarker(e){return this.#s.recordOpenMarker(e,this.#o),this}getOpenMarker(){return this.#s.getOpenMarker()}recordCloseMarker(e){return this.#s.recordCloseMarker(e,this.#o),this}beginMarkedContent(e){return this.#s.beginMarkedContent(e),this}endMarkedContent(e){return this.#s.endMarkedContent(e,this.#o),this}pushBaseTransform(e){return this.#s.pushBaseTransform(e),this}popBaseTransform(){return this.#s.popBaseTransform(),this}recordSimpleData(e,t){return this.#e[e]=t,this}recordIncrementalData(e,t){return this.#t[e].push(t),this}resetIncrementalData(e,t){return this.#t[e].length=0,this}recordNamedData(e,t){return this.#n.set(e,t),this}recordSimpleDataFromNamed(e,t,n){this.#e[e]=this.#n.get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(ht,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(let t of e)t in this.#e&&this.recordFutureForcedDependency(t,this.#e[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let e of this.#r)this.recordFutureForcedDependency(ht,e);return this}resetBBox(e){return this.#s.resetBBox(e),this}recordClipBox(e,t,n,r,i,a){return this.#s.recordClipBox(e,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#s.recordBBox(e,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){let s=n.bbox,c,l;if(s&&(c=s[2]!==s[0]&&s[3]!==s[1]&&this.#i.get(n),c!==!1&&(l=[0,0,0,0],I.axialAlignedBoundingBox(s,n.fontMatrix,l),(r!==1||i!==0||a!==0)&&yt(r,-r,i,a,l),c)))return this.recordBBox(e,t,l[0],l[2],l[1],l[3]);if(!o)return this.recordFullPageBBox(e);let u=o();return s&&l&&c===void 0&&(c=l[0]<=i-u.actualBoundingBoxLeft&&l[2]>=i+u.actualBoundingBoxRight&&l[1]<=a-u.actualBoundingBoxAscent&&l[3]>=a+u.actualBoundingBoxDescent,this.#i.set(n,c),c)?this.recordBBox(e,t,l[0],l[2],l[1],l[3]):this.recordBBox(e,t,i-u.actualBoundingBoxLeft,i+u.actualBoundingBoxRight,a-u.actualBoundingBoxAscent,a+u.actualBoundingBoxDescent)}recordFullPageBBox(e){return this.#s.recordFullPageBBox(e),this}getSimpleIndex(e){return this.#e[e]}recordDependencies(e,t){let n=this.#r,r=this.#e,i=this.#t;for(let e of t)e in this.#e?n.add(r[e]):e in i&&i[e].forEach(n.add,n);return this}recordNamedDependency(e,t){return this.#n.has(t)&&this.#r.add(this.#n.get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[ht]),this.#a){let t=St(this.#a,e),{dependencies:n}=t;this.#r.forEach(n.add,n),this.#s._savesStack.forEach(n.add,n),this.#s._markedContentStack.forEach(n.add,n),n.delete(e),t.isRenderingOperation=!0}let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.recordOperation(e,t,[this.#r,this.#s._savesStack,this.#s._markedContentStack]),n&&this.#r.clear(),this}recordShowTextOperation(e,t=!1){let n=Array.from(this.#r);this.recordOperation(e,t),this.recordIncrementalData(`sameLineText`,e);for(let e of n)this.recordIncrementalData(`sameLineText`,e);return this}bboxToClipBoxDropOperation(e,t=!1){let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.bboxToClipBoxDropOperation(e),n&&this.#r.clear(),this}take(){return this.#i.clear(),this.#s.take()}takeDebugMetadata(){return this.#a}},Tt=class e{#e;#t;#n;#r=0;#i=0;constructor(t,n,r){if(t instanceof e&&t.#n===!!r)return t;this.#e=t,this.#t=n,this.#n=!!r}get clipBox(){return this.#e.clipBox}growOperationsCount(){throw Error(`Unreachable`)}save(e){return this.#i++,this.#e.save(this.#t),this}restore(e){return this.#i>0&&(this.#e.restore(this.#t),this.#i--),this}recordOpenMarker(e){return this.#r++,this}getOpenMarker(){return this.#r>0?this.#t:this.#e.getOpenMarker()}recordCloseMarker(e){return this.#r--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return this.#e.pushBaseTransform(e),this}popBaseTransform(){return this.#e.popBaseTransform(),this}recordSimpleData(e,t){return this.#e.recordSimpleData(e,this.#t),this}recordIncrementalData(e,t){return this.#e.recordIncrementalData(e,this.#t),this}resetIncrementalData(e,t){return this.#e.resetIncrementalData(e,this.#t),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this.#e.recordSimpleDataFromNamed(e,t,this.#t),this}recordFutureForcedDependency(e,t){return this.#e.recordFutureForcedDependency(e,this.#t),this}inheritSimpleDataAsFutureForcedDependencies(e){return this.#e.inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#e.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return this.#n||this.#e.resetBBox(this.#t),this}recordClipBox(e,t,n,r,i,a){return this.#n||this.#e.recordClipBox(this.#t,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#n||this.#e.recordBBox(this.#t,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r,i,a,o){return this.#n||this.#e.recordCharacterBBox(this.#t,t,n,r,i,a,o),this}recordFullPageBBox(e){return this.#n||this.#e.recordFullPageBBox(this.#t),this}getSimpleIndex(e){return this.#e.getSimpleIndex(e)}recordDependencies(e,t){return this.#e.recordDependencies(this.#t,t),this}recordNamedDependency(e,t){return this.#e.recordNamedDependency(this.#t,t),this}recordOperation(e){return this.#e.recordOperation(this.#t,!0),this}recordShowTextOperation(e){return this.#e.recordShowTextOperation(this.#t,!0),this}bboxToClipBoxDropOperation(e){return this.#n||this.#e.bboxToClipBoxDropOperation(this.#t,!0),this}take(){throw Error(`Unreachable`)}takeDebugMetadata(){throw Error(`Unreachable`)}},G={stroke:[`path`,`transform`,`filter`,`strokeColor`,`strokeAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`dash`],fill:[`path`,`transform`,`filter`,`fillColor`,`fillAlpha`,`globalCompositeOperation`,`SMask`],imageXObject:[`transform`,`SMask`,`filter`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`],rawFillPath:[`filter`,`fillColor`,`fillAlpha`],showText:[`transform`,`leading`,`charSpacing`,`wordSpacing`,`hScale`,`textRise`,`moveText`,`textMatrix`,`font`,`fontObj`,`filter`,`fillColor`,`textRenderingMode`,`SMask`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`,`sameLineText`],transform:[`transform`],transformAndFill:[`transform`,`fillColor`]},Et=class e{#e;#t;#n=4;#r=0;#i=new e.#a(this.#n*6);static#a=F.isFloat16ArraySupported?Float16Array:Float32Array;constructor(e){this.#e=e.width,this.#t=e.height}record(t,r,i,a){if(this.#r===this.#n){this.#n*=2;let t=new e.#a(this.#n*6);t.set(this.#i),this.#i=t}let o=B(t),s;if(a[0]!==1/0){let e=n.slice();I.axialAlignedBoundingBox([0,-i,r,0],o,e);let t=I.intersect(a,e);if(!t)return;let[c,l,u,d]=t;if(c!==e[0]||l!==e[1]||u!==e[2]||d!==e[3]){let e=Math.atan2(o[1],o[0]),t=Math.abs(Math.sin(e)),n=Math.abs(Math.cos(e));if(t<1e-6||n<1e-6||Math.abs(t-n)<1e-6)s=[c,l,c,d,u,l];else{let e=u-c,r=d-l,i=t*t,a=n*n,o=n*t,f=a-i,p=(r*a-e*o)/f;s=[c+(r*o-e*i)/f,l,c,l+p,u,d-p]}}}s||(s=[0,-i,0,0,r,-i],I.applyTransform(s,o,0),I.applyTransform(s,o,2),I.applyTransform(s,o,4)),s[0]/=this.#e,s[1]/=this.#t,s[2]/=this.#e,s[3]/=this.#t,s[4]/=this.#e,s[5]/=this.#t,this.#i.set(s,this.#r*6),this.#r++}take(){return this.#i.subarray(0,this.#r*6)}},Dt=class{#e=new Set;#t=null;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){let t=this.#n();t.insertRule(e,t.cssRules.length)}#n(){if(this.#t)return this.#t;let e=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&e){let{adoptedStyleSheets:t}=this._document;if(t){let n=new e;return t.push(n),this.#t=n}}return this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement)),this.#t=this.styleElement.sheet}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);if(this.nativeFontFaces.clear(),this.#e.clear(),this.#t){let{adoptedStyleSheets:e}=this._document;e?.includes(this.#t)&&(this._document.adoptedStyleSheets=e.filter(e=>e!==this.#t)),this.#t=null}this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!(!e||this.#e.has(e.loadedName))){if(D(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:t,src:r,style:i}=e,a=new FontFace(t,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(t),n?.(e)}catch{T(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}E(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw T(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return M(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){return M(this,`isSyncFontLoadingSupported`,t||F.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(D(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return M(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function i(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let a,o,s=this._document.createElement(`canvas`);s.width=1,s.height=1;let c=s.getContext(`2d`),l=0;function u(e,t){if(++l>30){T(`Load test font never loaded.`),t();return}if(c.font=`30px `+e,c.fillText(`.`,0,20),c.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(u.bind(null,e,t))}let d=`lt${Date.now()}${this.loadTestFontId++}`,f=this._loadTestFont;f=i(f,976,d.length,d);let p=1482184792,m=n(f,16);for(a=0,o=d.length-3;a{g.remove(),t.complete()})}},Ot=class{compiledGlyphs=Object.create(null);#e;constructor(e,t=null,n,r){this.#e=e,this._inspectFont=t,n&&(this.charProcOperatorList=n),r&&Object.assign(this,r)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){T(`getPathGenerator - ignoring character: "${e}".`)}let i=Je(r?.path);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}get black(){return this.#e.black}get bold(){return this.#e.bold}get disableFontFace(){return this.#e.disableFontFace}set disableFontFace(e){M(this,`disableFontFace`,!!e)}get fontExtraProperties(){return this.#e.fontExtraProperties}get isInvalidPDFjsFont(){return this.#e.isInvalidPDFjsFont}get isType3Font(){return this.#e.isType3Font}get italic(){return this.#e.italic}get missingFile(){return this.#e.missingFile}get remeasure(){return this.#e.remeasure}get vertical(){return this.#e.vertical}get ascent(){return this.#e.ascent}get defaultWidth(){return this.#e.defaultWidth}get descent(){return this.#e.descent}get bbox(){return this.#e.bbox}get fontMatrix(){return this.#e.fontMatrix}get fallbackName(){return this.#e.fallbackName}get loadedName(){return this.#e.loadedName}get mimetype(){return this.#e.mimetype}get name(){return this.#e.name}get data(){return this.#e.data}clearData(){this.#e.clearData()}get cssFontInfo(){return this.#e.cssFontInfo}get systemFontInfo(){return this.#e.systemFontInfo}get defaultVMetrics(){return this.#e.defaultVMetrics}},kt=class{static strings=[`fontFamily`,`fontWeight`,`italicAngle`]},At=class{static strings=[`css`,`loadedName`,`baseFontName`,`src`]},K=class{static bools=[`black`,`bold`,`disableFontFace`,`fontExtraProperties`,`isInvalidPDFjsFont`,`isType3Font`,`italic`,`missingFile`,`remeasure`,`vertical`];static numbers=[`ascent`,`defaultWidth`,`descent`];static strings=[`fallbackName`,`loadedName`,`mimetype`,`name`];static OFFSET_NUMBERS=Math.ceil(this.bools.length*2/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+this.numbers.length*8;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6},jt=class{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16},Mt=class{#e;#t=new TextDecoder;#n;constructor(e){this.#e=e,this.#n=new DataView(e)}#r(e){D(e>n&3;return r===0?void 0:r===2}get black(){return this.#r(0)}get bold(){return this.#r(1)}get disableFontFace(){return this.#r(2)}get fontExtraProperties(){return this.#r(3)}get isInvalidPDFjsFont(){return this.#r(4)}get isType3Font(){return this.#r(5)}get italic(){return this.#r(6)}get missingFile(){return this.#r(7)}get remeasure(){return this.#r(8)}get vertical(){return this.#r(9)}#i(e){return D(e0){t=n.slice();for(let e=0,n=l.length;etypeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0,Vt=fe.bind(null,Bt,e=>typeof e==`object`&&typeof e?.name==`string`),Ht=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){T("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},Ut={DATA:1,ERROR:2},q={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Wt(){}function J(e){if(e instanceof P||e instanceof ne||e instanceof ee||e instanceof re||e instanceof te)return e;switch(e instanceof Error||typeof e==`object`&&e||E(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new P(e.message);case`InvalidPDFException`:return new ne(e.message);case`PasswordException`:return new ee(e.message,e.code);case`ResponseException`:return new re(e.message,e.status,e.missing);case`UnknownErrorException`:return new te(e.message,e.details)}return new te(e.message,e.toString())}var Gt=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===Ut.DATA)n.resolve(e.data);else if(e.callback===Ut.ERROR)n.reject(J(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:Ut.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:Ut.ERROR,callbackId:e.callbackId,reason:J(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:q.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{D(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:q.CANCEL,streamId:i,reason:J(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:q.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){D(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.ERROR,streamId:t,reason:J(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,reason:J(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case q.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(J(e.reason));break;case q.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(J(e.reason));break;case q.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||Wt).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,reason:J(e)})});break;case q.ENQUEUE:if(D(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case q.CLOSE:if(D(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case q.ERROR:D(a,`error should have stream controller`),a.controller.error(J(e.reason)),this.#i(a,t);break;case q.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(J(e.reason)),this.#i(a,t);break;case q.CANCEL:if(!o)break;let s=J(e.reason);Promise.try(o.onCancel||Wt,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,reason:J(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},Kt=class{#e=Object.freeze({cMapUrl:`CMap`,standardFontDataUrl:`font`,wasmUrl:`wasm`});constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=n}async fetch({kind:e,filename:t}){switch(e){case`cMapUrl`:case`standardFontDataUrl`:case`wasmUrl`:break;default:E(`Not implemented: ${e}`)}let n=this[e];if(!n)throw Error(`Ensure that the \`${e}\` API parameter is provided.`);let r=`${n}${t}`;return this._fetch(r,e).catch(t=>{throw Error(`Unable to load ${this.#e[e]} data at: ${r}`)})}async _fetch(e,t){E("Abstract method `_fetch` called.")}},qt=class extends Kt{async _fetch(e,t){let n=await Ce(e,t===`cMapUrl`&&!e.endsWith(`.bcmap`)?`text`:`bytes`);return n instanceof Uint8Array?n:oe(n)}},Jt=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.width=t,e.height=n}destroy(e){let{canvas:t}=e;if(!t)throw Error(`Canvas is not specified`);t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){E("Abstract method `_createCanvas` called.")}},Yt=class extends Jt{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},Xt=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addKnockoutFilter(e=0){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}addSelectionHCMFilter(e,t){return`none`}addSelectionFilter(){return`none`}createSelectionStyle(e=null){return null}destroy(e=!1){}},Zt=class extends Xt{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.colorScheme=`only light`,t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(a,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(a,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(Te(e)?T(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=A(e,``))}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=I.makeHexColor(...a);let o=this.#v(t);if(t=I.makeHexColor(...o),this.#b(),e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array(256);for(let e=0;e<=255;e++){let t=e/255;s[e]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}let c=s.join(`,`),l=`g_${this.#r}_hcm_filter`,u=i.filter=this.#m(l);this.#g(c,c,c,u),this.#p(u);let d=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(d(0,5),d(1,5),d(2,5),u),i.url=this.#d(l),i.url}addSelectionHCMFilter(e,t){return this.addHighlightHCMFilter(`selection`,e,t,`HighlightText`,`Highlight`)}addSelectionFilter(){return this.addHighlightHCMFilter(`selection_default`,`black`,`white`,`HighlightText`,`Highlight`)}createSelectionStyle(e=null){let t=e?this.addSelectionHCMFilter(e.foreground,e.background):this.addSelectionFilter();return t===`none`||!F.platform.isFirefox?null:{"backdrop-filter":t,"background-color":`transparent`}}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addKnockoutFilter(e=0){let t=e>0?Math.min(1/e,1e6):1e6,n=`knockout_${t}`,r=this.#s.get(n);if(r)return r;let i=`g_${this.#r}_knockout_filter_${this.#o++}`,o=this.#d(i);this.#s.set(n,o);let s=this.#m(i),c=this.#i.createElementNS(a,`feComponentTransfer`);s.append(c);let l=this.#i.createElementNS(a,`feFuncA`);return l.setAttribute(`type`,`linear`),l.setAttribute(`slope`,`${t}`),l.setAttribute(`intercept`,`0`),c.append(l),o}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#x.bind(this));u{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0`),e.append(t)}#p(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0`),e.append(t)}#m(e){let t=this.#i.createElementNS(a,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(a,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(a,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(a,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Ne(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#y(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Me(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#b(){this.#l.style.color=``,this.#l.style.backgroundColor=``}#x(e){let[t,n,r,i]=this.#y(e);if(i===1)return[t,n,r];let[a,o,s]=this.#v(`Canvas`);return[Qt(t,a,i),Qt(n,o,i),Qt(r,s,i)]}};function Qt(e,t,n){return Math.round(n*e+(1-n)*t)}t&&T("Please use the `legacy` build in Node.js environments.");async function $t(e){let t=await process.getBuiltinModule(`fs/promises`).readFile(e);return new Uint8Array(t)}var en=class extends Xt{},tn=class extends Jt{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@napi-rs/canvas`).createCanvas(e,t)}},nn=class extends Kt{async _fetch(e,t){return $t(e)}};function rn({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=F.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=c^l,p=e.length;n=new Uint32Array(n.buffer);let m=0;for(let r=0;r>7&1)&f,n[m+1]=c^-(r>>6&1)&f,n[m+2]=c^-(r>>5&1)&f,n[m+3]=c^-(r>>4&1)&f,n[m+4]=c^-(r>>3&1)&f,n[m+5]=c^-(r>>2&1)&f,n[m+6]=c^-(r>>1&1)&f,n[m+7]=c^-(r&1)&f}if(d===0)continue;let r=t>7-e&1)&f}return{srcPos:t,destPos:m}}function an({src:e,srcPos:t=0,dest:n,destPos:r=0,width:i,height:a}){let o=0,s=i*a*3,c=s>>2,l=new Uint32Array(e.buffer,t,c),u=F.isLittleEndian?4278190080:255;if(F.isLittleEndian){for(;o>>24|t<<8|u,n[r+2]=t>>>16|i<<16|u,n[r+3]=i>>>8|u}for(let i=o*4,a=t+s;i>>8|u,n[r+2]=t<<16|i>>>16|u,n[r+3]=i<<8|u}for(let i=o*4,a=t+s;i=_.INFOS&&console.info(`Info: ${e}`)}function T(e){x>=_.WARNINGS&&console.warn(`Warning: ${e}`)}function E(e){throw Error(e)}function D(e,t){e||E(t)}function O(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function k(e,t=null,n=null){if(!e)return null;if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=se(e)}catch{}let r=t?URL.parse(e,t):URL.parse(e);return O(r)?r:null}function A(e,t,n=!1){let r=URL.parse(e);return r?(r.hash=t,r.href):n&&k(e,`http://example.com`)?e.split(`#`,1)[0]+`${t?`#${t}`:``}`:``}function j(e){return e.substring(e.lastIndexOf(`/`)+1)}function M(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var N=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),ee=class extends N{constructor(e,t){super(e,`PasswordException`),this.code=t}},te=class extends N{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ne=class extends N{constructor(e){super(e,`InvalidPDFException`)}},re=class extends N{constructor(e,t,n){super(e,`ResponseException`),this.status=t,this.missing=n}},ie=class extends N{constructor(e){super(e,`FormatError`)}},P=class extends N{constructor(e){super(e,`AbortException`)}};function ae(e){(typeof e!=`object`||e?.length===void 0)&&E(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t`u`)return M(this,`isAlphaColorInputSupported`,!1);let e=document.createElement(`input`);return e.type=`color`,e.setAttribute(`alpha`,``),e.value=`#ff000080`,M(this,`isAlphaColorInputSupported`,e.value!==`#ff0000`)}static get isBackdropFilterSupported(){return M(this,`isBackdropFilterSupported`,typeof CSS<`u`&&CSS.supports(`backdrop-filter`,`blur(1px)`))}},I=class{static get hexNums(){return M(this,`hexNums`,Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,`0`)))}static makeHexColor(e,t,n){return`#${this.hexNums[e]}${this.hexNums[t]}${this.hexNums[n]}`}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,n=0){let r=e[n],i=e[n+1];e[n]=r*t[0]+i*t[2]+t[4],e[n+1]=r*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,n=0){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5];for(let t=0;t<6;t+=2){let l=e[n+t],u=e[n+t+1];e[n+t]=l*r+u*a+s,e[n+t+1]=l*i+u*o+c}}static applyInverseTransform(e,t){let n=e[0],r=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(n*t[3]-r*t[2]+t[2]*t[5]-t[4]*t[3])/i,e[1]=(-n*t[1]+r*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,n){let r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=e[0],u=e[1],d=e[2],f=e[3],p=r*l+s,m=p,h=r*d+s,g=h,_=o*u+c,v=_,y=o*f+c,b=y;if(i!==0||a!==0){let e=i*l,t=i*d,n=a*u,r=a*f;p+=n,g+=n,h+=r,m+=r,_+=e,b+=e,y+=t,v+=t}n[0]=Math.min(n[0],p,h,m,g),n[1]=Math.min(n[1],_,y,v,b),n[2]=Math.max(n[2],p,h,m,g),n[3]=Math.max(n[3],_,y,v,b)}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){let n=e[0],r=e[1],i=e[2],a=e[3],o=n**2+r**2,s=n*i+r*a,c=i**2+a**2,l=(o+c)/2,u=Math.sqrt(l**2-(o*c-s**2));t[0]=Math.sqrt(l+u||1),t[1]=Math.sqrt(l-u||1)}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static pointBoundingBox(e,t,n){n[0]=Math.min(n[0],e),n[1]=Math.min(n[1],t),n[2]=Math.max(n[2],e),n[3]=Math.max(n[3],t)}static rectBoundingBox(e,t,n,r,i){i[0]=Math.min(i[0],e,n),i[1]=Math.min(i[1],t,r),i[2]=Math.max(i[2],e,n),i[3]=Math.max(i[3],t,r)}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s),this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c)}};function se(e){return decodeURIComponent(escape(e))}var ce=null,le=null;function ue(e){return ce||(ce=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,le=new Map([[`ſt`,`ſt`]])),e.replaceAll(ce,(e,t,n)=>t?t.normalize(`NFKC`):le.get(n))}function de(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),ae(e)}function fe(e,t,n){if(!Array.isArray(n)||n.length<2)return!1;let[r,i,...a]=n;if(!e(r)&&!Number.isInteger(r)||!t(i))return!1;let o=a.length,s=!0;switch(i.name){case`XYZ`:if(o<2||o>3)return!1;break;case`Fit`:case`FitB`:return o===0;case`FitH`:case`FitBH`:case`FitV`:case`FitBV`:if(o>1)return!1;break;case`FitR`:if(o!==4)return!1;s=!1;break;default:return!1}for(let e of a)if(!(typeof e==`number`||s&&e===null))return!1;return!0}var pe=()=>[],me=()=>new Map,he=()=>Object.create(null),ge=()=>new Set;typeof Iterator.prototype.join!=`function`&&(Iterator.prototype.join=function(e){return[...this].join(e)});function L(e,t,n){return Math.min(Math.max(e,t),n)}var _e=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let e=this.viewBox;return M(this,`rawDims`,{pageWidth:e[2]-e[0],pageHeight:e[3]-e[1],pageX:e[0],pageY:e[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){let n=[e,t];return I.applyTransform(n,this.transform),n}convertToPdfPoint(e,t){let n=[e,t];return I.applyInverseTransform(n,this.transform),n}},ve=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return e!==`textarea`&&e!==`input`&&e!==`option`&&e!==`select`}},ye=/url\(|image-set\(/i,be=/^on/i,xe=class{static get _allowedHtmlElements(){return M(this,`_allowedHtmlElements`,new Set([`a`,`b`,`br`,`button`,`div`,`i`,`img`,`input`,`label`,`li`,`ol`,`option`,`p`,`select`,`span`,`sub`,`sup`,`textarea`,`ul`]))}static get _allowedSvgElements(){return M(this,`_allowedSvgElements`,new Set([`ellipse`,`line`,`path`,`rect`,`svg`]))}static get _allowedRichTextElements(){return M(this,`_allowedRichTextElements`,new Set([`a`,`b`,`br`,`div`,`i`,`li`,`ol`,`p`,`span`,`sub`,`sup`,`ul`]))}static get _allowedRichTextAttributes(){return M(this,`_allowedRichTextAttributes`,new Set([`class`,`dir`,`style`]))}static get _allowedRichTextStyles(){return M(this,`_allowedRichTextStyles`,new Set(`color.font.fontFamily.fontSize.fontStretch.fontStyle.fontWeight.kerningMode.letterSpacing.lineHeight.margin.marginBottom.marginLeft.marginRight.marginTop.orphans.paddingLeft.paddingRight.breakAfter.breakBefore.breakInside.tabInterval.tabStop.textAlign.textDecoration.textIndent.transform.verticalAlign.widows`.split(`.`)))}static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:Object.hasOwn(e.attributes,`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})})}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null&&!be.test(t)&&!(r===`richText`&&!this._allowedRichTextAttributes.has(t)))switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:if(r===`richText`){let t=this._allowedRichTextStyles;for(let[r,i]of Object.entries(n))t.has(r)&&!ye.test(i)&&(e.style[r]=i)}else Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i?.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static#e(e,t,n){return n===`richText`?!t&&this._allowedRichTextElements.has(e)?document.createElement(e):null:t?t===a&&this._allowedSvgElements.has(e)?document.createElementNS(a,e):null:this._allowedHtmlElements.has(e)?document.createElement(e):null}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=this.#e(r.name,r.attributes?.xmlns,i)??document.createElement(`div`);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&ve.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=this.#e(u,s.attributes?.xmlns,i);if(d){if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&ve.shouldBuildText(u)&&c.push(e),d.append(e)}}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}static getPageViewport(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new _e({viewBox:[0,0,parseInt(r,10),parseInt(i,10)],userUnit:1,scale:t,rotation:n})}},Se=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ce(e,t=`text`){if(Ae(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`blob`:return n.blob();case`bytes`:return n.bytes();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!0),i.responseType=t===`bytes`?`arraybuffer`:t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case`bytes`:n(new Uint8Array(i.response));return;case`blob`:case`json`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var we=class extends N{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function Te(e){let t=e.length,n=0;for(;n{try{return new URL(e)}catch{}try{return new URL(decodeURIComponent(e))}catch{}try{return new URL(e,`https://foo.bar`)}catch{}try{return new URL(decodeURIComponent(e),`https://foo.bar`)}catch{}return null})(e);if(!n)return t;let r=e=>{try{let t=decodeURIComponent(e);return t.includes(`/`)&&(t=j(t),t.length===4&&i.test(t))?e:t}catch{return e}},i=/\.pdf$/i,a=j(n.pathname);if(i.test(a))return r(a);if(n.searchParams.size>0){let e=e=>[...e].findLast(e=>i.test(e)),t=e(n.searchParams.values())??e(n.searchParams.keys());if(t)return r(t)}if(n.hash){let e=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i.exec(n.hash);if(e)return r(e[0])}return t}var ke=class{#e=new Map;times=[];time(e){this.#e.has(e)&&T(`Timer is already running for ${e}`),this.#e.set(e,Date.now())}timeEnd(e){this.#e.has(e)||T(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.#e.get(e),end:Date.now()}),this.#e.delete(e)}toString(){let e=Math.max(...this.times.map(e=>e.name.length));return this.times.map(t=>`${t.name.padEnd(e)} ${t.end-t.start}ms\n`).join(``)}};function Ae(e,t){let n=t?URL.parse(e,t):URL.parse(e);return/https?:/.test(n?.protocol??``)}function R(e){e.preventDefault()}function z(e){e.preventDefault(),e.stopPropagation()}var je=class{static#e;static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Me(e){if(e.startsWith(`#`)){let t=e.slice(1);return[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),t.length>=8?parseInt(t.slice(6,8),16)/255:1]}if(e.startsWith(`rgb(`)){let[t,n,r]=e.slice(4,-1).split(`,`).map(e=>parseInt(e,10));return[t,n,r,1]}if(e.startsWith(`rgba(`)){let t=e.slice(5,-1).split(`,`);return[parseInt(t[0],10),parseInt(t[1],10),parseInt(t[2],10),parseFloat(t[3])]}let t=e.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+|none))?\)$/);return t?[Math.round(parseFloat(t[1])*255),Math.round(parseFloat(t[2])*255),Math.round(parseFloat(t[3])*255),t[4]!==void 0&&t[4]!==`none`?parseFloat(t[4]):1]:null}function Ne(e){let t=Me(e);return t?t.slice(0,3):(T(`Not a valid color format: "${e}"`),[0,0,0])}function Pe(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,t.style.colorScheme=`only light`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Ne(r))}t.remove()}function B(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function V(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Fe(e,t,n=!1,r=!0){if(t instanceof _e){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=`round(down, var(--total-scale-factor) * ${r}px, var(--scale-round-x))`,s=`round(down, var(--total-scale-factor) * ${i}px, var(--scale-round-y))`;!n||t.rotation%180==0?(a.width=o,a.height=s):(a.width=s,a.height=o)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Ie=class e{constructor(){let{pixelRatio:t}=e;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}limitCanvas(t,n,r,i,a=-1){let o=1/0,s=1/0,c=1/0;r=e.capPixels(r,a),r>0&&(o=Math.sqrt(r/(t*n))),i!==-1&&(s=i/t,c=i/n);let l=Math.min(o,s,c);return this.sx>l||this.sy>l?(this.sx=l,this.sy=l,!0):!1}static get pixelRatio(){return globalThis.devicePixelRatio||1}static capPixels(e,t){if(t>=0){let n=Math.ceil(window.screen.availWidth*window.screen.availHeight*this.pixelRatio**2*(1+t/100));return e>0?Math.min(e,n):n}return e}},Le=[`image/apng`,`image/avif`,`image/bmp`,`image/gif`,`image/jpeg`,`image/png`,`image/svg+xml`,`image/webp`,`image/x-icon`],Re=class{static get isDarkMode(){return M(this,`isDarkMode`,!!window?.matchMedia?.(`(prefers-color-scheme: dark)`).matches)}},ze=class{static get commentForegroundColor(){let e=document.createElement(`span`);e.classList.add(`comment`,`sidebar`);let{style:t}=e;t.width=t.height=`0`,t.display=`none`,t.color=`var(--comment-fg-color)`,document.body.append(e);let{color:n}=window.getComputedStyle(e);return e.remove(),M(this,`commentForegroundColor`,Ne(n))}};function Be(e,t){t=L(t??1,0,1);let n=255*(1-t);return e.map(e=>Math.round(e*t+n))}function Ve(e,t){let n=e[0]/255,r=e[1]/255,i=e[2]/255,a=Math.max(n,r,i),o=Math.min(n,r,i),s=(a+o)/2;if(a===o)t[0]=t[1]=0;else{let e=a-o;switch(t[1]=s<.5?e/(a+o):e/(2-a-o),a){case n:t[0]=((r-i)/e+(ri?(r+.05)/(i+.05):(i+.05)/(r+.05)}var Ge=new Map;function Ke(e,t){let n=e[0]+e[1]*256+e[2]*65536+t[0]*16777216+t[1]*4294967296+t[2]*1099511627776,r=Ge.get(n);if(r)return r;let i=new Float32Array(9),a=i.subarray(0,3),o=i.subarray(3,6);Ve(e,o);let s=i.subarray(6,9);Ve(t,s);let c=s[2]<.5,l=c?12:4.5;if(o[2]=c?Math.sqrt(o[2]):1-Math.sqrt(1-o[2]),We(o,s,a).005;){let n=o[2]=(e+t)/2;c===We(o,s,a){n.delete()},{signal:n._signal}),this.#r.append(r)}get#p(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#f(t),this.#r.append(t,this.#p),this.#i=e}addComment(e,t=null){if(this.#a)return;let n=e.renderForToolbar();if(!n)return;this.#f(n);let r=this.#o=this.#p;t?(this.#r.insertBefore(n,t),this.#r.insertBefore(r,t)):this.#r.append(n,r),this.#a=e,e.toolbar=this}addColorPicker(e){if(this.#t)return;this.#t=e;let t=e.renderButton();this.#f(t),this.#r.append(t,this.#p)}async addEditSignatureButton(e){let t=this.#s=await e.renderEditButton(this.#n);this.#f(t),this.#r.append(t,this.#p)}removeButton(e){e===`comment`&&(this.#a?.removeToolbarCommentButton(),this.#a=null,this.#o?.remove(),this.#o=null)}async addButton(e,t){switch(e){case`colorPicker`:t&&this.addColorPicker(t);break;case`altText`:t&&await this.addAltText(t);break;case`editSignature`:t&&await this.addEditSignatureButton(t);break;case`delete`:this.addDeleteButton();break;case`comment`:t&&this.addComment(t)}}async addButtonBefore(e,t,n){if(!t&&e===`comment`)return;let r=this.#r.querySelector(n);r&&e===`comment`&&this.addComment(t,r)}updateEditSignatureButton(e){this.#s&&(this.#s.title=e)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},Xe=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`);let t=this.#n._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener(`contextmenu`,R,{signal:t});let n=this.#e=document.createElement(`div`);return n.className=`buttons`,e.append(n),this.#n.hasCommentManager()&&this.#a(`commentButton`,`pdfjs-comment-floating-button`,`pdfjs-comment-floating-button-label`,()=>{this.#n.commentSelection(`floating_button`)}),this.#a(`highlightButton`,`pdfjs-highlight-floating-button1`,`pdfjs-highlight-floating-button-label`,()=>{this.#n.highlightSelection(`floating_button`)}),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(en){r=a,n=e;continue}t?a>r&&(r=a):a=1}static clearPointerType(){e.#r=null}static clearPointerIds(){e.#e=NaN,e.#t=null}static clearTimeStamp(){e.#n=NaN}},$e=class{#e=0;get id(){return`${l}${this.#e++}`}},et=class e{#e=de();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=`data:image/svg+xml;charset=UTF-8,`,t=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),n=new Image;n.src=e;let r=n.decode().then(()=>(t.drawImage(n,0,0,1,1,0,0,1,3),new Uint32Array(t.getImageData(0,0,1,1).data.buffer)[0]===0));return M(this,`_isSVGFittingCanvas`,r)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ce(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){T(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},tt=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},nt=class e{static ALT=1;static CTRL=2;static META=4;static SHIFT=8;constructor(t){this.callbacks=new Map;let{isMac:n}=F.platform;for(let[r,i,a={}]of t){let t=r.some(e=>e.startsWith(`mac+`));for(let o of r){let r=o;if(t){let e=o.startsWith(`mac+`);if(n!==e)continue;e&&(r=o.slice(4))}let[s,c]=e.#e(r);s!==null&&this.callbacks.getOrInsertComputed(s,pe).push({callback:i,options:a,modifiers:c})}}}static#e(t){let n=null,r=0;for(let i of t.split(`+`)){if(i=i.trim(),!i)continue;let a=i.toUpperCase(),o=e[a];if(o){r|=o;continue}if(n!==null){T(`KeyboardManager: multiple keys in shortcut "${t}"`);break}n=a===`SPACE`?` `:i}return n===null&&T(`KeyboardManager: no key found in shortcut "${t}"`),[n,r]}static#t(e){let t=/^(?:Key([A-Z])|(?:Digit|Numpad)(\d))$/.exec(e);return t?t[1]?.toLowerCase()??t[2]:null}exec(t,n){let r=this.callbacks.get(n.key);if(!r){if(/^[a-z]$/i.test(n.key))return;let t=e.#t(n.code);if(t===null||t===n.key||(r=this.callbacks.get(t),!r))return}let i=(n.altKey?e.ALT:0)|(n.ctrlKey?e.CTRL:0)|(n.metaKey?e.META:0)|(n.shiftKey?e.SHIFT:0),a=r.find(e=>e.modifiers===i);if(!a)return;let{callback:o,options:{bubbles:s=!1,args:c=[],checker:l=null}}=a;l&&!l(t,n)||(o.bind(t,...c,n)(),s||z(n))}},rt=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Pe(e),M(this,`_colors`,e)}convert(t){let n=Ne(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?I.makeHexColor(...t):e}},it=class e{#e=new AbortController;#t=null;#n=null;#r=new Map;#i=new Map;#a=null;#o=null;#s=null;#c=null;#l=new tt;#u=null;#d=null;#f=null;#p=0;#m=new Set;#h=null;#g=null;#_=new Set;_editorUndoBar=null;#v=!1;#y=!1;#b=!1;#x=null;#S=null;#C=null;#w=null;#T=!1;#E=null;#D=new $e;#O=!1;#k=!1;#A=!1;#j=null;#M=null;#N=null;#P=null;#F=null;#I=u.NONE;#L=new Set;#R=null;#z=null;#B=null;#V=null;#H=null;#U={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#W=[0,0];#G=null;#K=null;#q=null;#J=null;#Y=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#K.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return M(this,`_keyboardManager`,new nt([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`Backspace`,`alt+Backspace`,`ctrl+Backspace`,`shift+Backspace`,`mac+Backspace`,`mac+alt+Backspace`,`mac+ctrl+Backspace`,`Delete`,`ctrl+Delete`,`shift+Delete`,`mac+Delete`],t.delete,{checker:r}],[[`Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#K.contains(t)&&!e.isEnterHandled}],[[`Space`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#K.contains(document.activeElement)}],[[`Escape`],t.unselectAll],[[`ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){let g=this._signal=this.#e.signal;this.#K=e,this.#q=t,this.#J=n,this.#o=r,this.#u=i,this.#z=a,this.#H=s,this._eventBus=o;let _={signal:g,...Ze};o.on(`editingaction`,this.onEditingAction.bind(this),_),o.on(`pagechanging`,this.onPageChanging.bind(this),_),o.on(`scalechanging`,this.onScaleChanging.bind(this),_),o.on(`rotationchanging`,this.onRotationChanging.bind(this),_),o.on(`setpreference`,this.onSetPreference.bind(this),_),o.on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),_),window.addEventListener(`pointerdown`,()=>{this.#k=!0},{capture:!0,signal:g}),window.addEventListener(`pointerup`,()=>{this.#k=!1},{capture:!0,signal:g}),window.addEventListener(`beforeunload`,this.endCurrentEditing.bind(this),{capture:!0,signal:g}),this.#te(),this.#ce(),this.#ie(),this.#s=s.annotationStorage,this.#x=s.filterFactory,this.#B=c,this.#w=l||null,this.#v=u,this.#y=d,this.#b=f,this.#F=p||null,this.viewParameters={realScale:Se.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=m||null,this._supportsPinchToZoom=h!==!1,i?.setSidebarUiManager(this)}destroy(){this.#Y?.resolve(),this.#Y=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#i.values())e.destroy();this.#i.clear(),this.#r.clear(),this.#_.clear(),this.#P?.clear(),this.#t=null,this.#L.clear(),this.#l.destroy(),this.#o?.destroy(),this.#u?.destroy(),this.#z?.destroy(),this.#E?.hide(),this.#E=null,this.#N?.destroy(),this.#N=null,this.#n=null,this.#S&&=(clearTimeout(this.#S),null),this.#G&&=(clearTimeout(this.#G),null),this._editorUndoBar?.destroy(),this.#H=null}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#F}get useNewAltTextFlow(){return this.#y}get useNewAltTextWhenAddingImage(){return this.#b}get hcmFilter(){return M(this,`hcmFilter`,this.#B?this.#x.addHCMFilter(this.#B.foreground,this.#B.background):`none`)}get direction(){return M(this,`direction`,getComputedStyle(this.#K).direction)}get _highlightColors(){return M(this,`_highlightColors`,this.#w?new Map(this.#w.split(`,`).map(e=>(e=e.split(`=`).map(e=>e.trim()),e[1]=e[1].toUpperCase(),e))):null)}get highlightColors(){let{_highlightColors:e}=this;if(!e)return M(this,`highlightColors`,null);let t=new Map,n=!!this.#B;for(let[r,i]of e){let e=r.endsWith(`_HCM`);if(n&&e){t.set(r.replace(`_HCM`,``),i);continue}!n&&!e&&t.set(r,i)}return M(this,`highlightColors`,t)}get highlightColorNames(){return M(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}getNonHCMColor(e){if(!this._highlightColors)return e;let t=this.highlightColorNames.get(e);return this._highlightColors.get(t)||e}getNonHCMColorName(e){return this.highlightColorNames.get(e)||e}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#f=e}setMainHighlightColorPicker(e){this.#N=e}editAltText(e,t=!1){this.#o?.editAltText(this,e,t)}hasCommentManager(){return!!this.#u}editComment(e,t,n,r){this.#u?.showDialog(this,e,t,n,r)}selectComment(e,t){(this.#i.get(e)?.getEditorByUID(t))?.toggleComment(!0,!0)}updateComment(e){this.#u?.updateComment(e.getData())}updatePopupColor(e){this.#u?.updatePopupColor(e)}removeComment(e){this.#u?.removeComments([e.uid])}deleteComment(e,t){let n=()=>{e.comment=t};this.addCommands({cmd:()=>{this._editorUndoBar?.show(n,`comment`),this.toggleComment(null),e.comment=null},undo:n,mustExec:!0})}toggleComment(e,t,n=void 0){this.#u?.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){return e&&this.#u?.makeCommentColor(e,t)||null}getCommentDialogElement(){return this.#u?.dialogElement||null}async waitForEditorsRendered(e){if(this.#i.has(e-1))return;let{resolve:t,promise:n}=Promise.withResolvers(),r=n=>{n.pageNumber===e&&(this._eventBus.off(`editorsrendered`,r),t())};this._eventBus.on(`editorsrendered`,r,Ze),await n}getSignature(e){this.#z?.getSignature({uiManager:this,editor:e})}get signatureManager(){return this.#z}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal,...Ze}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){e===`enableNewAltTextWhenAddingImage`&&(this.#b=t)}onPageChanging({pageNumber:e}){this.#p=e-1}deletePage(e){for(let t of this.getEditors(e))t.remove();this.#i.delete(e),this.#p===e&&(this.#p=0)}focusMainContainer(){this.#K.focus()}findParent(e,t){for(let n of this.#i.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#q.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#_.add(e)}removeShouldRescale(e){this.#_.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Se.PDF_TO_CSS_UNITS;for(let e of this.#_)e.onScaleChanging();this.#f?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#X({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#Z(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#i.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``,t=!1){let n=document.getSelection();if(!n||n.isCollapsed)return;let{anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o}=n,s=n.toString(),c=this.#X(n).closest(`.textLayer`),l=this.getSelectionBoxes(c);if(!l)return;n.empty();let d=this.#Z(c),f=this.#I===u.NONE,p=()=>{let n=d?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:l,anchorNode:r,anchorOffset:i,focusNode:a,focusOffset:o,text:s});f&&this.showAllEditors(`highlight`,!0,!0),t&&n?.editComment()};if(f){this.switchToMode(u.HIGHLIGHT,p);return}p()}commentSelection(e=``){this.highlightSelection(e,!0)}endCurrentEditing(){this.commitOrRemove(),this.currentLayer?.endDrawingSession(!1)}#Q(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#X(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#E||=new Xe(this),this.#E.show(t,n,this.direction===`ltr`))}getAndRemoveDataFromAnnotationStorage(e){if(!this.#s)return null;let t=`${l}${e}`,n=this.#s.getRawValue(t);return n&&this.#s.remove(t),n}addToAnnotationStorage(e){!e.isEmpty()&&this.#s&&!this.#s.has(e.id)&&this.#s.setValue(e.id,e)}a11yAlert(e,t=null){let n=this.#J;n&&(n.setAttribute(`data-l10n-id`,e),t?n.setAttribute(`data-l10n-args`,JSON.stringify(t)):n.removeAttribute(`data-l10n-args`))}#$(){let e=document.getSelection();if(!e||e.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#le({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#R)return;let n=this.#X(e).closest(`.textLayer`);if(!n){this.#R&&(this.#E?.hide(),this.#R=null,this.#le({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=t,this.#le({hasSelectedText:!0}),(this.#I===u.HIGHLIGHT||this.#I===u.NONE)&&(this.#I===u.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#T=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#I===u.HIGHLIGHT?this.#Z(n):null;if(e?.toggleDrawing(),this.#k){let t=new AbortController,n=this.combinedSignal(t),r=n=>{(n.type!==`pointerup`||n.button===0)&&(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#ee(`main_toolbar`))};window.addEventListener(`pointerup`,r,{signal:n}),window.addEventListener(`blur`,r,{signal:n})}else e?.toggleDrawing(!0),this.#ee(`main_toolbar`)}}#ee(e=``){this.#I===u.HIGHLIGHT?this.highlightSelection(e):this.#v&&this.#Q()}#te(){document.addEventListener(`selectionchange`,this.#$.bind(this),{signal:this._signal})}#ne(){if(this.#C)return;this.#C=new AbortController;let e=this.combinedSignal(this.#C);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#re(){this.#C?.abort(),this.#C=null}blur(){if(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#ee(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#L)if(t.div.contains(e)){this.#M=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#M)return;let[e,t]=this.#M;this.#M=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#ie(){if(this.#j)return;this.#j=new AbortController;let e=this.combinedSignal(this.#j);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#ae(){this.#j?.abort(),this.#j=null}#oe(){if(this.#d)return;this.#d=new AbortController;let e=this.combinedSignal(this.#d);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#se(){this.#d?.abort(),this.#d=null}#ce(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#ie(),this.setEditingState(!0)}removeEditListeners(){this.#ae(),this.setEditingState(!1)}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#g)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#g)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#L){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#g)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){T(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#pe(t);this.#ge(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){T(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#I!==u.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#T&&(this.#T=!1,this.#ee(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`);break;case`commentSelection`:this.commentSelection(`context_menu`)}}updatePageIndex(e,t){for(let n of this.getEditors(e))n.pageIndex=t;let n=this.#a.get(e);n&&(n.pageIndex=t,this.#i.set(t,n),this.#O?n.enable():n.disable())}startUpdatePages(){this.#a=new Map(this.#i),this.#i.clear()}endUpdatePages(){this.#a=null}clonePage(e,t){for(let n of this.getEditors(e)){let e=n.serialize(n.mode!==u.HIGHLIGHT);e&&(e.pageIndex=t,e.id=this.getId(),e.isClone=!0,delete e.popupRef,this.#s.setValue(e.id,e))}}findClonesForPage(e){let t=[],{pageIndex:n}=e;for(let[r,i]of this.#s)i.pageIndex===n&&i.isClone&&(this.#s.remove(r),t.push(e.deserialize(i).then(t=>{t&&(t.isClone=!0,e.addOrRebuild(t))})));return Promise.all(t)}#le(e){Object.entries(e).some(([e,t])=>this.#U[e]!==t)&&(this._eventBus.dispatch(`editingstateschanged`,{source:this,details:Object.assign(this.#U,e)}),this.#I===u.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#ue([[d.HIGHLIGHT_FREE,!0]]))}#ue(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#ne(),this.#oe(),this.#le({isEditing:this.#I!==u.NONE,isEmpty:this.#he(),hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:this.#l.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#re(),this.#se(),this.#le({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#g){this.#g=e;for(let e of this.#g)this.#ue(e.defaultPropertiesToUpdate)}}getId(){return this.#D.id}get currentLayer(){return this.#i.get(this.#p)}getLayer(e){return this.#i.get(e)}get currentPageIndex(){return this.#p}addLayer(e){this.#i.set(e.pageIndex,e),this.#O?e.enable():e.disable()}removeLayer(e){this.#i.delete(e.pageIndex)}async updateMode(e,t=null,n=!1,r=!1,i=!1,a=!1){if(this.#I!==e&&!(this.#Y&&(await this.#Y.promise,!this.#Y))){if(this.#Y=Promise.withResolvers(),this.#f?.commitOrRemove(),this.#I===u.POPUP&&this.#u?.hideSidebar(),this.#u?.destroyPopup(),this.#I=e,e===u.NONE){this.setEditingState(!1),this.#fe();for(let e of this.#r.values())e.hideStandaloneCommentButton();this._editorUndoBar?.hide(),this.toggleComment(null),this.#Y.resolve();return}for(let e of this.#r.values())e.addStandaloneCommentButton();e===u.SIGNATURE&&await this.#z?.loadSignatures(),n&&H.clearPointerType(),this.setEditingState(!0),await this.#de(),this.unselectAll();for(let t of this.#i.values())t.updateMode(e);if(e===u.POPUP){this.#n||=await this.#H.getAnnotationsByType(new Set(this.#g.map(e=>e._editorType)));let e=new Set,t=[];for(let n of this.#r.values()){let{annotationElementId:r,hasComment:i,deleted:a}=n;r&&e.add(r),i&&!a&&t.push(n.getData())}for(let n of this.#n){let{id:r,popupRef:i,contentsObj:a}=n;i&&a?.str&&!e.has(r)&&!this.#m.has(r)&&t.push(n)}this.#u?.showSidebar(t)}if(!t){r&&this.addNewEditorFromKeyboard(),this.#Y.resolve();return}for(let e of this.#r.values())e.uid===t?(this.setSelected(e),a?e.editComment():i?e.enterInEditMode():e.focus()):e.unselect();this.#Y.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==this.#I&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,...e})}updateParams(e,t){if(this.#g){switch(e){case d.CREATE:this.currentLayer.addNewEditor(t);return;case d.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#V||=new Map).set(e,t),this.showAllEditors(`highlight`,t)}if(this.hasSelection)for(let n of this.#L)n.updateParams(e,t);else for(let n of this.#g)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#r.values())n.editorType===e&&n.show(t);(this.#V?.get(d.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#ue([[d.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#A!==e){this.#A=e;for(let t of this.#i.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#de(){if(!this.#O){this.#O=!0;let e=[];for(let t of this.#i.values())e.push(t.enable());await Promise.all(e);for(let e of this.#r.values())e.enable()}}#fe(){if(this.unselectAll(),this.#O){this.#O=!1;for(let e of this.#i.values())e.disable();for(let e of this.#r.values())e.disable()}}*getEditors(e){for(let t of this.#r.values())t.pageIndex===e&&(yield t)}getEditor(e){return this.#r.get(e)}addEditor(e){this.#r.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#S&&clearTimeout(this.#S),this.#S=setTimeout(()=>{this.focusMainContainer(),this.#S=null},0)),this.#r.delete(e.id),e.annotationElementId&&this.#P?.delete(e.annotationElementId),this.unselect(e),(!e.annotationElementId||!this.#m.has(e.annotationElementId))&&this.#s?.remove(e.id)}addDeletedAnnotationElement(e){this.#m.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#m.has(e)}removeDeletedAnnotationElement(e){this.#m.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#pe(e){let t=this.#i.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#ue(e.propertiesToUpdate))}get#me(){let e=null;for(e of this.#L);return e}updateUI(e){this.#me===e&&this.#ue(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#ue(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#L.has(e)){this.#L.delete(e),e.unselect(),this.#le({hasSelectedEditor:this.hasSelection});return}this.#L.add(e),e.select(),this.#ue(e.propertiesToUpdate),this.#le({hasSelectedEditor:!0})}setSelected(e){this.updateToolbar({mode:e.mode,editId:e.uid}),this.#f?.commitOrRemove();for(let t of this.#L)t!==e&&t.unselect();this.#u?.destroyPopup(),this.#L.clear(),this.#L.add(e),e.select(),this.#ue(e.propertiesToUpdate),this.#le({hasSelectedEditor:!0})}get firstSelectedEditor(){return this.#L.values().next().value}unselect(e){e.unselect(),this.#L.delete(e),this.#le({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#L.size!==0}get isEnterHandled(){return this.#L.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#l.undo(),this.#le({hasSomethingToUndo:this.#l.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#he()}),this._editorUndoBar?.hide()}redo(){this.#l.redo(),this.#le({hasSomethingToUndo:!0,hasSomethingToRedo:this.#l.hasSomethingToRedo(),isEmpty:this.#he()})}addCommands(e){this.#l.add(e),this.#le({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#he()})}cleanUndoStack(e){this.#l.cleanType(e)}#he(){if(this.#r.size===0)return!0;if(this.#r.size===1)for(let e of this.#r.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#L],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#pe(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ge(e){for(let e of this.#L)e.unselect();this.#L.clear();for(let t of e)t.isEmpty()||(this.#L.add(t),t.select());this.#le({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#L)e.commit();this.#ge(this.#r.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#I!==u.NONE))&&!this.#f?.commitOrRemove()&&(this.#u?.destroyPopup(),this.hasSelection)){for(let e of this.#L)e.unselect();this.#L.clear(),this.#le({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#W[0]+=e,this.#W[1]+=t;let[r,i]=this.#W,a=[...this.#L];this.#G&&clearTimeout(this.#G),this.#G=setTimeout(()=>{this.#G=null,this.#W[0]=this.#W[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(r,i),e.translationDone())},undo:()=>{for(let e of a)this.#r.has(e.id)&&(e.translateInPage(-r,-i),e.translationDone())},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t),n.translationDone()}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#h=new Map;for(let e of this.#L)this.#h.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#h)return!1;this.disableUserSelect(!1);let e=this.#h;this.#h=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#r.has(e.id)){let i=this.#i.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#h)for(let n of this.#h.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#L.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#I}isEditingMode(){return this.#I!==u.NONE}get imageManager(){return M(this,`imageManager`,new et)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a})}let s=[];for(let e=0,n=t.rangeCount;ee.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),(this.#e!==e||this.#t!==t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getElementForAltText()?.setAttribute(`aria-describedby`,n.id)}},ot=class{#e=null;#t=null;#n=!1;#r=null;#i=null;#a=null;#o=null;#s=null;#c=!1;#l=null;constructor(e){this.#r=e}renderForToolbar(){let e=this.#t=document.createElement(`button`);return e.className=`comment`,this.#u(e,!1)}renderForStandalone(){let e=this.#e=document.createElement(`button`);e.className=`annotationCommentButton`;let t=this.#r.commentButtonPosition;if(t){let{style:n}=e;n.insetInlineEnd=`calc(${100*(this.#r._uiManager.direction===`ltr`?1-t[0]:t[0])}% - var(--comment-button-dim))`,n.top=`calc(${100*t[1]}% - var(--comment-button-dim))`;let r=this.#r.commentButtonColor;r&&(n.backgroundColor=r)}return this.#u(e,!0)}focusButton(){setTimeout(()=>{(this.#e??this.#t)?.focus()},0)}onUpdatedColor(){if(!this.#e)return;let e=this.#r.commentButtonColor;e&&(this.#e.style.backgroundColor=e),this.#r._uiManager.updatePopupColor(this.#r)}get commentButtonWidth(){return(this.#e?.getBoundingClientRect().width??0)/this.#r.parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(this.#l)return this.#l;if(!this.#e)return null;let{x:e,y:t,height:n}=this.#e.getBoundingClientRect(),{x:r,y:i,width:a,height:o}=this.#r.parent.boundingClientRect;return[(e-r)/a,(t+n-i)/o]}set commentPopupPositionInLayer(e){this.#l=e}hasDefaultPopupPosition(){return this.#l===null}removeStandaloneCommentButton(){this.#e?.remove(),this.#e=null}removeToolbarCommentButton(){this.#t?.remove(),this.#t=null}setCommentButtonStates({selected:e,hasPopup:t}){this.#e&&(this.#e.classList.toggle(`selected`,e),this.#e.ariaExpanded=t)}#u(e,t){if(!this.#r._uiManager.hasCommentManager())return null;e.tabIndex=`0`,e.ariaHasPopup=`dialog`,t?(e.ariaControls=`commentPopup`,e.setAttribute(`data-l10n-id`,`pdfjs-show-comment-button`)):(e.ariaControlsElements=[this.#r._uiManager.getCommentDialogElement()],e.setAttribute(`data-l10n-id`,`pdfjs-editor-add-comment-button`));let n=this.#r._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;e.addEventListener(`contextmenu`,R,{signal:n}),t&&(e.addEventListener(`focusin`,e=>{this.#r._focusEventsAllowed=!1,z(e)},{capture:!0,signal:n}),e.addEventListener(`focusout`,e=>{this.#r._focusEventsAllowed=!0,z(e)},{capture:!0,signal:n})),e.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:n});let r=t=>{t.preventDefault(),e===this.#t?this.edit():this.#r.toggleComment(!0)};return e.addEventListener(`click`,r,{capture:!0,signal:n}),e.addEventListener(`keydown`,t=>{t.target===e&&t.key===`Enter`&&(this.#n=!0,r(t))},{signal:n}),e.addEventListener(`pointerenter`,()=>{this.#r.toggleComment(!1,!0)},{signal:n}),e.addEventListener(`pointerleave`,()=>{this.#r.toggleComment(!1,!1)},{signal:n}),e}edit(e){let t=this.commentPopupPositionInLayer,n,r;if(t)[n,r]=t;else{[n,r]=this.#r.commentButtonPosition;let{width:e,height:t,x:i,y:a}=this.#r;n=i+n*e,r=a+r*t}let i=this.#r.parent.boundingClientRect,{x:a,y:o,width:s,height:c}=i;this.#r._uiManager.editComment(this.#r,a+n*s,o+r*c,{...e,parentDimensions:i})}finish(){this.#t&&(this.#t.focus({focusVisible:this.#n}),this.#n=!1)}isDeleted(){return this.#c||this.#o===``}isEmpty(){return this.#o===null}hasBeenEdited(){return this.isDeleted()||this.#o!==this.#i}serialize(){return this.data}get data(){return{text:this.#o,richText:this.#a,date:this.#s,deleted:this.isDeleted()}}set data(e){if(e!==this.#o&&(this.#a=null),e===null){this.#o=``,this.#c=!0;return}this.#o=e,this.#s=new Date,this.#c=!1}restoreData({text:e,richText:t,date:n}){this.#o=e,this.#a=t,this.#s=n,this.#c=!1}setInitialText(e,t=null){this.#i=e,this.data=e,this.#s=null,this.#a=t}shown(){}destroy(){this.#t?.remove(),this.#t=null,this.#e?.remove(),this.#e=null,this.#o=``,this.#a=null,this.#s=null,this.#r=null,this.#n=!1,this.#c=!1}},st=class e{#e;#t=!1;#n=null;#r;#i;#a;#o;#s=null;#c;#l=null;#u;#d=null;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,signal:o}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#u=new AbortController,this.#c=AbortSignal.any([o,this.#u.signal]),e.addEventListener(`touchstart`,this.#f.bind(this),{passive:!1,signal:this.#c})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/Ie.pixelRatio}#f(e){if(this.#r?.())return;if(e.touches.length===1){if(this.#s)return;let e=this.#s=new AbortController,t=AbortSignal.any([this.#c,e.signal]),n=this.#e,r={capture:!0,signal:t,passive:!1},i=e=>{e.pointerType===`touch`&&(this.#s?.abort(),this.#s=null)};n.addEventListener(`pointerdown`,e=>{e.pointerType===`touch`&&(z(e),i(e))},r),n.addEventListener(`pointerup`,i,r),n.addEventListener(`pointercancel`,i,r);return}if(!this.#d){this.#d=new AbortController;let e=AbortSignal.any([this.#c,this.#d.signal]),t=this.#e,n={signal:e,capture:!1,passive:!1};t.addEventListener(`touchmove`,this.#p.bind(this),n);let r=this.#m.bind(this);t.addEventListener(`touchend`,r,n),t.addEventListener(`touchcancel`,r,n),n.capture=!0,t.addEventListener(`pointerdown`,z,n),t.addEventListener(`pointermove`,z,n),t.addEventListener(`pointercancel`,z,n),t.addEventListener(`pointerup`,z,n),this.#i?.()}if(z(e),e.touches.length!==2||this.#n?.()){this.#l=null;return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),this.#l={touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY}}#p(t){if(!this.#l||t.touches.length!==2)return;z(t);let[n,r]=t.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:a}=n,{screenX:o,screenY:s}=r,c=this.#l,{touch0X:l,touch0Y:u,touch1X:d,touch1Y:f}=c,p=d-l,m=f-u,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=Math.hypot(p,m)||1;if(!this.#t&&Math.abs(v-_)<=e.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=a,c.touch1X=o,c.touch1Y=s,!this.#t){this.#t=!0;return}let y=[(i+o)/2,(a+s)/2];this.#a?.(y,v,_)}#m(e){e.touches.length>=2||(this.#d&&(this.#d.abort(),this.#d=null,this.#o?.()),this.#l&&(z(e),this.#l=null,this.#t=!1))}destroy(){this.#u?.abort(),this.#u=null,this.#s?.abort(),this.#s=null}},U=class e{#e=null;#t=null;#n=null;#r=null;#i=null;#a=!1;#o=null;#s=``;#c=null;#l=null;#u=null;#d=null;#f=null;#p=``;#m=!1;#h=null;#g=!1;#_=!1;#v=!1;#y=null;#b=0;#x=0;#S=null;#C=null;isSelected=!1;_isCopy=!1;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nAlert=null;static _l10nResizer=null;#w=!1;#T=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new rt;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=it.TRANSLATE_SMALL,r=it.TRANSLATE_BIG;return M(this,`_resizerKeyboardManager`,new nt([[[`ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null,this.annotationElementId=e.annotationElementId||null,this.creationDate=e.creationDate||new Date,this.modificationDate=e.modificationDate||null,this.canAddComment=!0;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}updatePageIndex(e){this.pageIndex=e}get editorType(){return Object.getPrototypeOf(this).constructor._type}get mode(){return Object.getPrototypeOf(this).constructor._editorType}static get isDrawer(){return!1}static get _defaultLineColor(){return M(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new ct({id:e._uiManager.getId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._l10nAlert??=Object.freeze({highlight:`pdfjs-editor-highlight-added-alert`,freetext:`pdfjs-editor-freetext-added-alert`,ink:`pdfjs-editor-ink-added-alert`,stamp:`pdfjs-editor-stamp-added-alert`,signature:`pdfjs-editor-signature-added-alert`}),e._l10nResizer??=Object.freeze({topLeft:`pdfjs-editor-resizer-top-left`,topMiddle:`pdfjs-editor-resizer-top-middle`,topRight:`pdfjs-editor-resizer-top-right`,middleRight:`pdfjs-editor-resizer-middle-right`,bottomRight:`pdfjs-editor-resizer-bottom-right`,bottomMiddle:`pdfjs-editor-resizer-bottom-middle`,bottomLeft:`pdfjs-editor-resizer-bottom-left`,middleLeft:`pdfjs-editor-resizer-middle-left`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){E(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#w}set _isDraggable(e){this.#w=e,this.div?.classList.toggle(`draggable`,e)}get uid(){return this.annotationElementId||this.id}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#T}setParent(e){e===null?(this.#W(),this.#d?.remove(),this.#d=null):(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#m?this.#m=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.isInEditMode()&&this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}_moveAfterPaste(e,t){if(this.isClone){delete this.isClone;return}let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r),this._onTranslated()}#E([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#E(this.parentDimensions,e,t)}translateInPage(e,t){this.#h||=[this.x,this.y,this.width,this.height],this.#E(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){this.#h||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o),n.scrollIntoView({block:`nearest`})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#h&&(this.#h[0]!==this.x||this.#h[1]!==this.y)}get _hasBeenResized(){return!!this.#h&&(this.#h[2]!==this.width||this.#h[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=L(i,0,n-o),a=L(a,0,r-s);break;case 90:i=L(i,0,n-s),a=L(a,o,r);break;case 180:i=L(i,o,n),a=L(a,s,r);break;case 270:i=L(i,s,n),a=L(a,0,r-o)}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#D(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#D(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#D(t,n,360-this.parentRotation)}#O(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(){let{div:{style:e},width:t,height:n}=this;e.width=`${(100*t).toFixed(2)}%`,e.height=`${(100*n).toFixed(2)}%`}getInitialTranslation(){return[0,0]}#k(){if(this.#c)return;this.#c=document.createElement(`div`),this.#c.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#c.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#A.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,R,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#c)}#A(e,t){t.preventDefault();let{isMac:n}=F.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#l=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#N.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,z,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,R,{signal:a}),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#M()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#j(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()}_onResized(){}#M(){if(!this.#u)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#u;this.#u=null;let i=this.x,a=this.y,o=this.width,s=this.height;(i!==e||a!==t||o!==n||s!==r)&&this.addCommands({cmd:this.#j.bind(this,i,a,o,s),undo:this.#j.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#N(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#O(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#O(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2]}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#l;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#l[0]=e,this.#l[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=L(Math.abs(b[0]-y[0]-E),l,1)/s:T=L(Math.abs(b[1]-y[1]-D),u,1)/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#h||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||this.#_)return this._editToolbar;this._editToolbar=new Ye(this),this.div.append(this._editToolbar.render());let{toolbarButtons:e}=this;if(e)for(let[t,n]of e)await this._editToolbar.addButton(t,n);return this.hasComment||this._editToolbar.addButton(`comment`,this.addCommentButton()),this._editToolbar.addButton(`delete`),this._editToolbar}addCommentButtonInToolbar(){this._editToolbar?.addButtonBefore(`comment`,this.addCommentButton(),`.deleteButton`)}removeCommentButtonFromToolbar(){this._editToolbar?.removeButton(`comment`)}removeEditToolbar(){this._editToolbar?.remove(),this._editToolbar=null,this.#n?.destroy()}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}createAltText(){return this.#n||(at.initialize(e._l10n),this.#n=new at(this),this.#e&&=(this.#n.data=this.#e,null)),this.#n}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}focusCommentButton(){this.#r?.focusButton()}addCommentButton(){return this.canAddComment?this.#r||=new ot(this):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(this.#i){this._uiManager.isEditingMode()&&this.#i.classList.remove(`hidden`);return}this.hasComment&&(this.#i=this.#r.renderForStandalone(),this.div.append(this.#i))}}removeStandaloneCommentButton(){this.#r.removeStandaloneCommentButton(),this.#i=null}hideStandaloneCommentButton(){this.#i?.classList.add(`hidden`)}get comment(){if(!this.#r)return null;let{data:{richText:e,text:t,date:n,deleted:r}}=this.#r;return{text:t,richText:e,date:n,deleted:r,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){this.#r||=new ot(this),typeof e==`object`&&e?this.#r.restoreData(e):this.#r.data=e,this.hasComment?(this.removeCommentButtonFromToolbar(),this.addStandaloneCommentButton(),this._uiManager.updateComment(this)):(this.addCommentButtonInToolbar(),this.removeStandaloneCommentButton(),this._uiManager.removeComment(this))}setCommentData({comment:e,popupRef:t,richText:n}){if(!t||(this.#r||=new ot(this),this.#r.setInitialText(e,n),!this.annotationElementId))return;let r=this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId);r&&this.updateFromAnnotationLayer(r)}get hasEditedComment(){return this.#r?.hasBeenEdited()}get hasDeletedComment(){return this.#r?.isDeleted()}get hasComment(){return!!this.#r&&!this.#r.isEmpty()&&!this.#r.isDeleted()}async editComment(e){this.#r||=new ot(this),this.#r.edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){this.#r.setSelectedButton(e)}addComment(e){if(this.hasEditedComment){let[,,,t]=e.rect,[n]=this.pageDimensions,[r]=this.pageTranslation,i=r+n+1,a=t-100,o=i+180;e.popup={contents:this.comment.text,deleted:this.comment.deleted,rect:[i,a,o,t]}}}updateFromAnnotationLayer({popup:{contents:e,deleted:t}}){this.#r.data=t?null:e}get parentBoundingClientRect(){return this.parent.boundingClientRect}render(){let e=this.div=document.createElement(`div`);e.setAttribute(`data-editor-rotation`,(360-this.rotation)%360),e.className=this.name,e.setAttribute(`id`,this.id),e.tabIndex=this.#a?-1:0,e.setAttribute(`role`,`application`),this.defaultL10nId&&e.setAttribute(`data-l10n-id`,this.defaultL10nId),this._isVisible||e.classList.add(`hidden`),this.setInForeground(),this.#z();let[t,n]=this.parentDimensions;this.parentRotation%180!=0&&(e.style.maxWidth=`${(100*n/t).toFixed(2)}%`,e.style.maxHeight=`${(100*t/n).toFixed(2)}%`);let[r,i]=this.getInitialTranslation();return this.translate(r,i),Qe(this,e,[`keydown`,`pointerdown`,`dblclick`]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#C||=new st({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#P.bind(this),onPinching:this.#F.bind(this),onPinchEnd:this.#I.bind(this),signal:this._uiManager._signal})),this.addStandaloneCommentButton(),this._uiManager._editorUndoBar?.hide(),e}#P(){this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#F(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#O(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#h||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(),this.fixAndSetPosition(),this._onResizing()}#I(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#M()}pointerdown(e){let{isMac:t}=F.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#m=!0,this._isDraggable){this.#R(e);return}this.#L(e)}#L(e){let{isMac:t}=F.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#R(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#o=null,this.#m=!1,this._uiManager.endDragSession()||this.#L(e),n&&this._onStopDragging()};t&&(this.#b=e.clientX,this.#x=e.clientY,this.#o=e.pointerId,this.#s=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#o){z(e);return}let[a,o]=this.screenToPageTranslation(t-this.#b,r-this.#x);this.#b=t,this.#x=r,this._uiManager.dragSelectedEditors(a,o)},a),window.addEventListener(`touchmove`,z,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#s&&(this.#C||e.isPrimary)&&o(e),z(e)},a));let s=e=>{if(!this.#o||this.#o===e.pointerId){o(e);return}z(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.#y=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}getPDFRect(){return this.getRect(0,0)}getNonHCMColor(){return this.color&&e._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){this.#r?.onUpdatedColor()}getData(){let{comment:{text:e,color:t,date:n,opacity:r,deleted:i,richText:a},uid:o,pageIndex:s,creationDate:c,modificationDate:l}=this;return{id:o,pageIndex:s,rect:this.getPDFRect(),richText:a,contentsObj:{str:e},creationDate:c,modificationDate:n||l,popupRef:!i,color:t,opacity:r}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){return!this.isInEditMode()&&(this.parent.setEditingState(!1),this.#_=!0,!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),this.#_=!1,!0):!1}isInEditMode(){return this.#_}shouldGetKeyboardEvents(){return this.#v}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t0&&e0}#z(){if(this.#f||!this.div)return;this.#f=new AbortController;let e=this._uiManager.combinedSignal(this.#f);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}rebuild(){this.#z()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){return{annotationType:this.mode,pageIndex:this.pageIndex,rect:this.getPDFRect(),rotation:this.rotation,structTreeParentId:this._structTreeParentId,popupRef:this._initialData?.popupRef||``}}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:n.getId(),uiManager:n,annotationElementId:e.annotationElementId,creationDate:e.creationDate,modificationDate:e.modificationDate});r.rotation=e.rotation,r.#e=e.accessibilityData,r._isCopy=e.isCopy||!1;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#f?.abort(),this.#f=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),this.#y&&=(clearTimeout(this.#y),null),this.#W(),this.removeEditToolbar(),this.#S){for(let e of this.#S.values())clearTimeout(e);this.#S=null}this.parent=null,this.#C?.destroy(),this.#C=null,this.#d?.remove(),this.#d=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#k(),this.#c.classList.remove(`hidden`))}get toolbarPosition(){return null}get commentButtonPosition(){return this._uiManager.direction===`ltr`?[1,0]:[0,0]}get commentButtonPositionInPage(){let{commentButtonPosition:[t,n]}=this,[r,i,a,o]=this.getPDFRect();return[e._round(r+(a-r)*t),e._round(i+(o-i)*(1-n))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return this.#r.commentPopupPositionInLayer}set commentPopupPosition(e){this.#r.commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return this.#r.hasDefaultPopupPosition()}get commentButtonWidth(){return this.#r.commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){this.#r?.setCommentButtonStates(e)}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!==`Enter`)return;this._uiManager.setSelected(this),this.#u={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#c.children;if(!this.#t){this.#t=Array.from(n);let t=this.#B.bind(this),r=this.#V.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#H.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(ai)for(let e=0;e{this.div?.classList.contains(`selectedEditor`)&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}focus(){this.div&&!this.div.contains(document.activeElement)&&setTimeout(()=>this.div?.focus({preventScroll:!0}),0)}unselect(){this.isSelected&&(this.isSelected=!1,this.#c?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0),this.hideCommentPopup())}hideCommentPopup(){this.hasComment&&this._uiManager.toggleComment(null)}updateParams(e,t){}disableEditing(){}enableEditing(){}get canChangeContent(){return!1}enterInEditMode(){this.canChangeContent&&(this.enableEditMode(),this.div.focus())}dblclick(e){e.target.nodeName!==`BUTTON`&&(this.enterInEditMode(),this.parent.updateToolbar({mode:this.constructor._editorType,editId:this.uid}))}getElementForAltText(){return this.div}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(e){this.#g=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#S||=new Map;let{action:n}=t,r=this.#S.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#S.delete(n),this.#S.size===0&&(this.#S=null)},e._telemetryTimeout),this.#S.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#a=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#a=!0}updateFakeAnnotationElement(e){if(!this.#d&&!this.deleted){this.#d=e.addFakeAnnotation(this);return}if(this.deleted){this.#d.remove(),this.#d=null;return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&this.#d.updateEdited({rect:this.getPDFRect(),popup:this.comment})}renderAnnotationElement(e){if(this.deleted)return e.hide(),null;let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstElementChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},ct=class extends U{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},lt=3285377520,W=4294901760,ut=65535,dt=class{constructor(e){this.h1=e?e&4294967295:lt,this.h2=e?e&4294967295:lt}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e>>17,o=o*d&W|o*p&ut,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&W|s*f&ut,s=s<<15|s>>>17,s=s*d&W|s*p&ut,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&W|o*f&ut,o=o<<15|o>>>17,o=o*d&W|o*p&ut,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&W|e*36045&ut,t=t*4283543511&W|((t<<16|e>>>16)*2950163797&W)>>>16,e^=t>>>1,e=e*444984403&W|e*60499&ut,t=t*3301882366&W|((t<<16|e>>>16)*3120437893&W)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},ft=Object.freeze({map:null,hash:``,transfer:void 0}),pt=class{#e=!1;#t=null;#n=null;#r=new Map;onSetModified=null;onResetModified=null;onAnnotationEditor=null;getValue(e,t){let n=this.#r.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#r.get(e)}remove(e){let t=this.#r.get(e);t!==void 0&&(t instanceof U&&this.#n.delete(t.annotationElementId),this.#r.delete(e),this.#r.size===0&&this.resetModified(),!this.#r.values().some(e=>e instanceof U)&&this.onAnnotationEditor?.(null))}setValue(e,t){let n=this.#r.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#r.set(e,t);r&&this.#i(),t instanceof U&&((this.#n||=new Map).set(t.annotationElementId,t),this.onAnnotationEditor?.(t.constructor._type))}has(e){return this.#r.has(e)}get size(){return this.#r.size}#i(){this.#e||(this.#e=!0,this.onSetModified?.())}resetModified(){this.#e&&(this.#e=!1,this.onResetModified?.())}get print(){return new mt(this)}get serializable(){if(this.#r.size===0)return ft;let e=new Map,t=new dt,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#r){let o=a instanceof U?a.serialize(!1,r):a;a.page&&(a.pageIndex=a.page._pageIndex,delete a.page),o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:ft}get editorStats(){let e=null,t=new Map,n=0,r=0;for(let i of this.#r.values()){if(!(i instanceof U)){i.popup&&(i.popup.deleted?r+=1:n+=1);continue}i.isCommentDeleted?r+=1:i.hasEditedComment&&(n+=1);let a=i.telemetryFinalData;if(!a)continue;let{type:o}=a;t.getOrInsertComputed(o,()=>Object.getPrototypeOf(i).constructor),e||=Object.create(null);let s=e[o]||=new Map;for(let[e,t]of Object.entries(a)){if(e===`type`)continue;let n=s.getOrInsertComputed(e,me);n.set(t,(n.get(t)??0)+1)}}if((r>0||n>0)&&(e||=Object.create(null),e.comments={deleted:r,edited:n}),!e)return null;for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}updateEditor(e,t){let n=this.#n?.get(e);return n?(n.updateFromAnnotationLayer(t),!0):!1}getEditor(e){return this.#n?.get(e)||null}get modifiedIds(){if(this.#t)return this.#t;let e=[];if(this.#n)for(let t of this.#n.values())t.serialize()&&e.push(t.annotationElementId);let t=``;if(e.length){let n=new dt;n.update(e.join(`,`)),t=n.hexdigest()}return this.#t={ids:new Set(e),hash:t}}[Symbol.iterator](){return this.#r.entries()}},mt=class extends pt{#e=ft;constructor(e){super();let{serializable:t}=e;if(t===ft)return;let{map:n,hash:r,transfer:i}=t,a=structuredClone(n,i?{transfer:i}:null);this.#e={map:a,hash:r,transfer:[]}}get print(){E(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return M(this,`modifiedIds`,{ids:new Set,hash:``})}},ht=`__forcedDependency`,{floor:gt,ceil:_t}=Math;function vt(e,t,n,r,i,a){e[t*4+0]=Math.min(e[t*4+0],n),e[t*4+1]=Math.min(e[t*4+1],r),e[t*4+2]=Math.max(e[t*4+2],i),e[t*4+3]=Math.max(e[t*4+3],a)}function yt(e,t,n,r,i){let a;e?(e<0&&(a=i[0],i[0]=i[2],i[2]=a),i[0]*=e,i[2]*=e,t<0&&(a=i[1],i[1]=i[3],i[3]=a),i[1]*=t,i[3]*=t):i.fill(0),i[0]+=n,i[1]+=r,i[2]+=n,i[3]+=r}var bt=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0],xt=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get length(){return this.#e.length}isEmpty(e){return this.#e[e]===bt}minX(e){return this.#t[e*4+0]/256}minY(e){return this.#t[e*4+1]/256}maxX(e){return(this.#t[e*4+2]+1)/256}maxY(e){return(this.#t[e*4+3]+1)/256}},St=(e,t)=>e?.getOrInsertComputed(t,()=>({dependencies:new Set,isRenderingOperation:!1})),Ct=class{#e=[[1,0,0,1,0,0]];#t=[-1/0,-1/0,1/0,1/0];#n=new Float64Array(n);_pendingBBoxIdx=-1;#r;#i;#a;#o;_savesStack=[];_markedContentStack=[];constructor(e,t){this.#r=e.width,this.#i=e.height,this.#s(t)}growOperationsCount(e){e>=this.#o.length&&this.#s(e,this.#o)}#s(e,t){let n=new ArrayBuffer(e*4);this.#a=new Uint8ClampedArray(n),this.#o=new Uint32Array(n),t&&t.length>0?(this.#o.set(t),this.#o.fill(bt,t.length)):this.#o.fill(bt)}get clipBox(){return this.#t}save(e){return this.#t={__proto__:this.#t},this._savesStack.push(e),this}restore(e,t){let n=Object.getPrototypeOf(this.#t);if(n===null)return this;this.#t=n;let r=this._savesStack.pop();return r!==void 0&&(t?.(r,e),this.#o[e]=this.#o[r]),this}recordOpenMarker(e){return this._savesStack.push(e),this}getOpenMarker(){return this._savesStack.length===0?null:this._savesStack.at(-1)}recordCloseMarker(e,t){let n=this._savesStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}beginMarkedContent(e){return this._markedContentStack.push(e),this}endMarkedContent(e,t){let n=this._markedContentStack.pop();return n!==void 0&&(t?.(n,e),this.#o[e]=this.#o[n]),this}pushBaseTransform(e){return this.#e.push(I.multiplyByDOMMatrix(this.#e.at(-1),e.getTransform())),this}popBaseTransform(){return this.#e.length>1&&this.#e.pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,this.#n.set(n,0)),this}recordClipBox(e,t,r,i,a,o){let s=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform()),c=n.slice();I.axialAlignedBoundingBox([r,a,i,o],s,c);let l=I.intersect(this.#t,c);return l?(this.#t[0]=l[0],this.#t[1]=l[1],this.#t[2]=l[2],this.#t[3]=l[3]):(this.#t[0]=this.#t[1]=1/0,this.#t[2]=this.#t[3]=-1/0),this}recordBBox(e,t,r,i,a,o){let s=this.#t;if(s[0]===1/0)return this;let c=I.multiplyByDOMMatrix(this.#e.at(-1),t.getTransform());if(s[0]===-1/0)return I.axialAlignedBoundingBox([r,a,i,o],c,this.#n),this;let l=n.slice();return I.axialAlignedBoundingBox([r,a,i,o],c,l),this.#n[0]=L(l[0],s[0],this.#n[0]),this.#n[1]=L(l[1],s[1],this.#n[1]),this.#n[2]=L(l[2],this.#n[2],s[2]),this.#n[3]=L(l[3],this.#n[3],s[3]),this}recordFullPageBBox(e){return this.#n[0]=Math.max(0,this.#t[0]),this.#n[1]=Math.max(0,this.#t[1]),this.#n[2]=Math.min(this.#r,this.#t[2]),this.#n[3]=Math.min(this.#i,this.#t[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;let r=gt(this.#n[0]*256/this.#r),i=gt(this.#n[1]*256/this.#i),a=_t(this.#n[2]*256/this.#r),o=_t(this.#n[3]*256/this.#i);if(vt(this.#a,e,r,i,a,o),n)for(let t of n)for(let n of t)n!==e&&vt(this.#a,n,r,i,a,o);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,this.#t[0]=Math.max(this.#t[0],this.#n[0]),this.#t[1]=Math.max(this.#t[1],this.#n[1]),this.#t[2]=Math.min(this.#t[2],this.#n[2]),this.#t[3]=Math.min(this.#t[3],this.#n[3])),this}take(){return new xt(this.#o,this.#a)}takeDebugMetadata(){throw Error(`Unreachable`)}recordSimpleData(e,t){return this}recordIncrementalData(e,t){return this}resetIncrementalData(e,t){return this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this}recordFutureForcedDependency(e,t){return this}inheritSimpleDataAsFutureForcedDependencies(e){return this}inheritPendingDependenciesAsFutureForcedDependencies(){return this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){return this}getSimpleIndex(e){}recordDependencies(e,t){return this}recordNamedDependency(e,t){return this}recordShowTextOperation(e,t=!1){return this}},wt=class{#e={__proto__:null};#t={__proto__:null,transform:[],moveText:[],sameLineText:[],[ht]:[]};#n=new Map;#r=new Set;#i=new Map;#a;#o;#s;constructor(e,t=!1){this.#s=e,t&&(this.#a=new Map,this.#o=(e,t)=>{St(this.#a,t).dependencies.add(e)})}get clipBox(){return this.#s.clipBox}growOperationsCount(e){this.#s.growOperationsCount(e)}save(e){return this.#e={__proto__:this.#e},this.#t={__proto__:this.#t,transform:{__proto__:this.#t.transform},moveText:{__proto__:this.#t.moveText},sameLineText:{__proto__:this.#t.sameLineText},[ht]:{__proto__:this.#t[ht]}},this.#s.save(e),this}restore(e){this.#s.restore(e,this.#o);let t=Object.getPrototypeOf(this.#e);return t===null?this:(this.#e=t,this.#t=Object.getPrototypeOf(this.#t),this)}recordOpenMarker(e){return this.#s.recordOpenMarker(e,this.#o),this}getOpenMarker(){return this.#s.getOpenMarker()}recordCloseMarker(e){return this.#s.recordCloseMarker(e,this.#o),this}beginMarkedContent(e){return this.#s.beginMarkedContent(e),this}endMarkedContent(e){return this.#s.endMarkedContent(e,this.#o),this}pushBaseTransform(e){return this.#s.pushBaseTransform(e),this}popBaseTransform(){return this.#s.popBaseTransform(),this}recordSimpleData(e,t){return this.#e[e]=t,this}recordIncrementalData(e,t){return this.#t[e].push(t),this}resetIncrementalData(e,t){return this.#t[e].length=0,this}recordNamedData(e,t){return this.#n.set(e,t),this}recordSimpleDataFromNamed(e,t,n){this.#e[e]=this.#n.get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(ht,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(let t of e)t in this.#e&&this.recordFutureForcedDependency(t,this.#e[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(let e of this.#r)this.recordFutureForcedDependency(ht,e);return this}resetBBox(e){return this.#s.resetBBox(e),this}recordClipBox(e,t,n,r,i,a){return this.#s.recordClipBox(e,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#s.recordBBox(e,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r=1,i=0,a=0,o){let s=n.bbox,c,l;if(s&&(c=s[2]!==s[0]&&s[3]!==s[1]&&this.#i.get(n),c!==!1&&(l=[0,0,0,0],I.axialAlignedBoundingBox(s,n.fontMatrix,l),(r!==1||i!==0||a!==0)&&yt(r,-r,i,a,l),c)))return this.recordBBox(e,t,l[0],l[2],l[1],l[3]);if(!o)return this.recordFullPageBBox(e);let u=o();return s&&l&&c===void 0&&(c=l[0]<=i-u.actualBoundingBoxLeft&&l[2]>=i+u.actualBoundingBoxRight&&l[1]<=a-u.actualBoundingBoxAscent&&l[3]>=a+u.actualBoundingBoxDescent,this.#i.set(n,c),c)?this.recordBBox(e,t,l[0],l[2],l[1],l[3]):this.recordBBox(e,t,i-u.actualBoundingBoxLeft,i+u.actualBoundingBoxRight,a-u.actualBoundingBoxAscent,a+u.actualBoundingBoxDescent)}recordFullPageBBox(e){return this.#s.recordFullPageBBox(e),this}getSimpleIndex(e){return this.#e[e]}recordDependencies(e,t){let n=this.#r,r=this.#e,i=this.#t;for(let e of t)e in this.#e?n.add(r[e]):e in i&&i[e].forEach(n.add,n);return this}recordNamedDependency(e,t){return this.#n.has(t)&&this.#r.add(this.#n.get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[ht]),this.#a){let t=St(this.#a,e),{dependencies:n}=t;this.#r.forEach(n.add,n),this.#s._savesStack.forEach(n.add,n),this.#s._markedContentStack.forEach(n.add,n),n.delete(e),t.isRenderingOperation=!0}let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.recordOperation(e,t,[this.#r,this.#s._savesStack,this.#s._markedContentStack]),n&&this.#r.clear(),this}recordShowTextOperation(e,t=!1){let n=Array.from(this.#r);this.recordOperation(e,t),this.recordIncrementalData(`sameLineText`,e);for(let e of n)this.recordIncrementalData(`sameLineText`,e);return this}bboxToClipBoxDropOperation(e,t=!1){let n=!t&&e===this.#s._pendingBBoxIdx;return this.#s.bboxToClipBoxDropOperation(e),n&&this.#r.clear(),this}take(){return this.#i.clear(),this.#s.take()}takeDebugMetadata(){return this.#a}},Tt=class e{#e;#t;#n;#r=0;#i=0;constructor(t,n,r){if(t instanceof e&&t.#n===!!r)return t;this.#e=t,this.#t=n,this.#n=!!r}get clipBox(){return this.#e.clipBox}growOperationsCount(){throw Error(`Unreachable`)}save(e){return this.#i++,this.#e.save(this.#t),this}restore(e){return this.#i>0&&(this.#e.restore(this.#t),this.#i--),this}recordOpenMarker(e){return this.#r++,this}getOpenMarker(){return this.#r>0?this.#t:this.#e.getOpenMarker()}recordCloseMarker(e){return this.#r--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return this.#e.pushBaseTransform(e),this}popBaseTransform(){return this.#e.popBaseTransform(),this}recordSimpleData(e,t){return this.#e.recordSimpleData(e,this.#t),this}recordIncrementalData(e,t){return this.#e.recordIncrementalData(e,this.#t),this}resetIncrementalData(e,t){return this.#e.resetIncrementalData(e,this.#t),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return this.#e.recordSimpleDataFromNamed(e,t,this.#t),this}recordFutureForcedDependency(e,t){return this.#e.recordFutureForcedDependency(e,this.#t),this}inheritSimpleDataAsFutureForcedDependencies(e){return this.#e.inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return this.#e.inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return this.#n||this.#e.resetBBox(this.#t),this}recordClipBox(e,t,n,r,i,a){return this.#n||this.#e.recordClipBox(this.#t,t,n,r,i,a),this}recordBBox(e,t,n,r,i,a){return this.#n||this.#e.recordBBox(this.#t,t,n,r,i,a),this}recordCharacterBBox(e,t,n,r,i,a,o){return this.#n||this.#e.recordCharacterBBox(this.#t,t,n,r,i,a,o),this}recordFullPageBBox(e){return this.#n||this.#e.recordFullPageBBox(this.#t),this}getSimpleIndex(e){return this.#e.getSimpleIndex(e)}recordDependencies(e,t){return this.#e.recordDependencies(this.#t,t),this}recordNamedDependency(e,t){return this.#e.recordNamedDependency(this.#t,t),this}recordOperation(e){return this.#e.recordOperation(this.#t,!0),this}recordShowTextOperation(e){return this.#e.recordShowTextOperation(this.#t,!0),this}bboxToClipBoxDropOperation(e){return this.#n||this.#e.bboxToClipBoxDropOperation(this.#t,!0),this}take(){throw Error(`Unreachable`)}takeDebugMetadata(){throw Error(`Unreachable`)}},G={stroke:[`path`,`transform`,`filter`,`strokeColor`,`strokeAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`dash`],fill:[`path`,`transform`,`filter`,`fillColor`,`fillAlpha`,`globalCompositeOperation`,`SMask`],imageXObject:[`transform`,`SMask`,`filter`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`],rawFillPath:[`filter`,`fillColor`,`fillAlpha`],showText:[`transform`,`leading`,`charSpacing`,`wordSpacing`,`hScale`,`textRise`,`moveText`,`textMatrix`,`font`,`fontObj`,`filter`,`fillColor`,`textRenderingMode`,`SMask`,`fillAlpha`,`strokeAlpha`,`globalCompositeOperation`,`sameLineText`],transform:[`transform`],transformAndFill:[`transform`,`fillColor`]},Et=class e{#e;#t;#n=4;#r=0;#i=new e.#a(this.#n*6);static#a=F.isFloat16ArraySupported?Float16Array:Float32Array;constructor(e){this.#e=e.width,this.#t=e.height}record(t,r,i,a){if(this.#r===this.#n){this.#n*=2;let t=new e.#a(this.#n*6);t.set(this.#i),this.#i=t}let o=B(t),s;if(a[0]!==1/0){let e=n.slice();I.axialAlignedBoundingBox([0,-i,r,0],o,e);let t=I.intersect(a,e);if(!t)return;let[c,l,u,d]=t;if(c!==e[0]||l!==e[1]||u!==e[2]||d!==e[3]){let e=Math.atan2(o[1],o[0]),t=Math.abs(Math.sin(e)),n=Math.abs(Math.cos(e));if(t<1e-6||n<1e-6||Math.abs(t-n)<1e-6)s=[c,l,c,d,u,l];else{let e=u-c,r=d-l,i=t*t,a=n*n,o=n*t,f=a-i,p=(r*a-e*o)/f;s=[c+(r*o-e*i)/f,l,c,l+p,u,d-p]}}}s||(s=[0,-i,0,0,r,-i],I.applyTransform(s,o,0),I.applyTransform(s,o,2),I.applyTransform(s,o,4)),s[0]/=this.#e,s[1]/=this.#t,s[2]/=this.#e,s[3]/=this.#t,s[4]/=this.#e,s[5]/=this.#t,this.#i.set(s,this.#r*6),this.#r++}take(){return this.#i.subarray(0,this.#r*6)}},Dt=class{#e=new Set;#t=null;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){let t=this.#n();t.insertRule(e,t.cssRules.length)}#n(){if(this.#t)return this.#t;let e=this._document.defaultView?.CSSStyleSheet||globalThis.CSSStyleSheet;if(!this.styleElement&&e){let{adoptedStyleSheets:t}=this._document;if(t){let n=new e;return t.push(n),this.#t=n}}return this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement)),this.#t=this.styleElement.sheet}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);if(this.nativeFontFaces.clear(),this.#e.clear(),this.#t){let{adoptedStyleSheets:e}=this._document;e?.includes(this.#t)&&(this._document.adoptedStyleSheets=e.filter(e=>e!==this.#t)),this.#t=null}this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!(!e||this.#e.has(e.loadedName))){if(D(!t,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:t,src:r,style:i}=e,a=new FontFace(t,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(t),n?.(e)}catch{T(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}E(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw T(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return M(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){return M(this,`isSyncFontLoadingSupported`,t||F.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(D(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return M(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function i(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let a,o,s=this._document.createElement(`canvas`);s.width=1,s.height=1;let c=s.getContext(`2d`),l=0;function u(e,t){if(++l>30){T(`Load test font never loaded.`),t();return}if(c.font=`30px `+e,c.fillText(`.`,0,20),c.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(u.bind(null,e,t))}let d=`lt${Date.now()}${this.loadTestFontId++}`,f=this._loadTestFont;f=i(f,976,d.length,d);let p=1482184792,m=n(f,16);for(a=0,o=d.length-3;a{g.remove(),t.complete()})}},Ot=class{compiledGlyphs=Object.create(null);#e;constructor(e,t=null,n,r){this.#e=e,this._inspectFont=t,n&&(this.charProcOperatorList=n),r&&Object.assign(this,r)}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${this.data.toBase64()});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){T(`getPathGenerator - ignoring character: "${e}".`)}let i=Je(r?.path);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}get black(){return this.#e.black}get bold(){return this.#e.bold}get disableFontFace(){return this.#e.disableFontFace}set disableFontFace(e){M(this,`disableFontFace`,!!e)}get fontExtraProperties(){return this.#e.fontExtraProperties}get isInvalidPDFjsFont(){return this.#e.isInvalidPDFjsFont}get isType3Font(){return this.#e.isType3Font}get italic(){return this.#e.italic}get missingFile(){return this.#e.missingFile}get remeasure(){return this.#e.remeasure}get vertical(){return this.#e.vertical}get ascent(){return this.#e.ascent}get defaultWidth(){return this.#e.defaultWidth}get descent(){return this.#e.descent}get bbox(){return this.#e.bbox}get fontMatrix(){return this.#e.fontMatrix}get fallbackName(){return this.#e.fallbackName}get loadedName(){return this.#e.loadedName}get mimetype(){return this.#e.mimetype}get name(){return this.#e.name}get data(){return this.#e.data}clearData(){this.#e.clearData()}get cssFontInfo(){return this.#e.cssFontInfo}get systemFontInfo(){return this.#e.systemFontInfo}get defaultVMetrics(){return this.#e.defaultVMetrics}},kt=class{static strings=[`fontFamily`,`fontWeight`,`italicAngle`]},At=class{static strings=[`css`,`loadedName`,`baseFontName`,`src`]},K=class{static bools=[`black`,`bold`,`disableFontFace`,`fontExtraProperties`,`isInvalidPDFjsFont`,`isType3Font`,`italic`,`missingFile`,`remeasure`,`vertical`];static numbers=[`ascent`,`defaultWidth`,`descent`];static strings=[`fallbackName`,`loadedName`,`mimetype`,`name`];static OFFSET_NUMBERS=Math.ceil(this.bools.length*2/8);static OFFSET_BBOX=this.OFFSET_NUMBERS+this.numbers.length*8;static OFFSET_FONT_MATRIX=this.OFFSET_BBOX+1+8;static OFFSET_DEFAULT_VMETRICS=this.OFFSET_FONT_MATRIX+1+48;static OFFSET_STRINGS=this.OFFSET_DEFAULT_VMETRICS+1+6},jt=class{static KIND=0;static HAS_BBOX=1;static HAS_BACKGROUND=2;static SHADING_TYPE=3;static N_COORD=4;static N_COLOR=8;static N_STOP=12;static N_FIGURES=16},Mt=class{#e;#t=new TextDecoder;#n;constructor(e){this.#e=e,this.#n=new DataView(e)}#r(e){D(e>n&3;return r===0?void 0:r===2}get black(){return this.#r(0)}get bold(){return this.#r(1)}get disableFontFace(){return this.#r(2)}get fontExtraProperties(){return this.#r(3)}get isInvalidPDFjsFont(){return this.#r(4)}get isType3Font(){return this.#r(5)}get italic(){return this.#r(6)}get missingFile(){return this.#r(7)}get remeasure(){return this.#r(8)}get vertical(){return this.#r(9)}#i(e){return D(e0){t=n.slice();for(let e=0,n=l.length;etypeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0,Vt=fe.bind(null,Bt,e=>typeof e==`object`&&typeof e?.name==`string`),Ht=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){T("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},Ut={DATA:1,ERROR:2},q={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Wt(){}function J(e){if(e instanceof P||e instanceof ne||e instanceof ee||e instanceof re||e instanceof te)return e;switch(e instanceof Error||typeof e==`object`&&e||E(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new P(e.message);case`InvalidPDFException`:return new ne(e.message);case`PasswordException`:return new ee(e.message,e.code);case`ResponseException`:return new re(e.message,e.status,e.missing);case`UnknownErrorException`:return new te(e.message,e.details)}return new te(e.message,e.toString())}var Gt=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===Ut.DATA)n.resolve(e.data);else if(e.callback===Ut.ERROR)n.reject(J(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:Ut.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:Ut.ERROR,callbackId:e.callbackId,reason:J(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:q.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{D(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:q.CANCEL,streamId:i,reason:J(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:q.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){D(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:q.ERROR,streamId:t,reason:J(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.START_COMPLETE,streamId:t,reason:J(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case q.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(J(e.reason));break;case q.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(J(e.reason));break;case q.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||Wt).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.PULL_COMPLETE,streamId:t,reason:J(e)})});break;case q.ENQUEUE:if(D(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case q.CLOSE:if(D(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case q.ERROR:D(a,`error should have stream controller`),a.controller.error(J(e.reason)),this.#i(a,t);break;case q.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(J(e.reason)),this.#i(a,t);break;case q.CANCEL:if(!o)break;let s=J(e.reason);Promise.try(o.onCancel||Wt,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:q.CANCEL_COMPLETE,streamId:t,reason:J(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},Kt=class{#e=Object.freeze({cMapUrl:`CMap`,standardFontDataUrl:`font`,wasmUrl:`wasm`});constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){this.cMapUrl=e,this.standardFontDataUrl=t,this.wasmUrl=n}async fetch({kind:e,filename:t}){switch(e){case`cMapUrl`:case`standardFontDataUrl`:case`wasmUrl`:break;default:E(`Not implemented: ${e}`)}let n=this[e];if(!n)throw Error(`Ensure that the \`${e}\` API parameter is provided.`);let r=`${n}${t}`;return this._fetch(r,e).catch(t=>{throw Error(`Unable to load ${this.#e[e]} data at: ${r}`)})}async _fetch(e,t){E("Abstract method `_fetch` called.")}},qt=class extends Kt{async _fetch(e,t){let n=await Ce(e,t===`cMapUrl`&&!e.endsWith(`.bcmap`)?`text`:`bytes`);return n instanceof Uint8Array?n:oe(n)}},Jt=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.width=t,e.height=n}destroy(e){let{canvas:t}=e;if(!t)throw Error(`Canvas is not specified`);t.width=t.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){E("Abstract method `_createCanvas` called.")}},Yt=class extends Jt{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},Xt=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addKnockoutFilter(e=0){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}addSelectionHCMFilter(e,t){return`none`}addSelectionFilter(){return`none`}createSelectionStyle(e=null){return null}destroy(e=!1){}},Zt=class extends Xt{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.colorScheme=`only light`,t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(a,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(a,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(Te(e)?T(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=A(e,``))}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=I.makeHexColor(...a);let o=this.#v(t);if(t=I.makeHexColor(...o),this.#b(),e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array(256);for(let e=0;e<=255;e++){let t=e/255;s[e]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}let c=s.join(`,`),l=`g_${this.#r}_hcm_filter`,u=i.filter=this.#m(l);this.#g(c,c,c,u),this.#p(u);let d=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(d(0,5),d(1,5),d(2,5),u),i.url=this.#d(l),i.url}addSelectionHCMFilter(e,t){return this.addHighlightHCMFilter(`selection`,e,t,`HighlightText`,`Highlight`)}addSelectionFilter(){return this.addHighlightHCMFilter(`selection_default`,`black`,`white`,`HighlightText`,`Highlight`)}createSelectionStyle(e=null){let t=e?this.addSelectionHCMFilter(e.foreground,e.background):this.addSelectionFilter();return t===`none`||!F.platform.isFirefox?null:{"backdrop-filter":t,"background-color":`transparent`}}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addKnockoutFilter(e=0){let t=e>0?Math.min(1/e,1e6):1e6,n=`knockout_${t}`,r=this.#s.get(n);if(r)return r;let i=`g_${this.#r}_knockout_filter_${this.#o++}`,o=this.#d(i);this.#s.set(n,o);let s=this.#m(i),c=this.#i.createElementNS(a,`feComponentTransfer`);s.append(c);let l=this.#i.createElementNS(a,`feFuncA`);return l.setAttribute(`type`,`linear`),l.setAttribute(`slope`,`${t}`),l.setAttribute(`intercept`,`0`),c.append(l),o}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#x.bind(this));u{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0`),e.append(t)}#p(e){let t=this.#i.createElementNS(a,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0`),e.append(t)}#m(e){let t=this.#i.createElementNS(a,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(a,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(a,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(a,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Ne(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#y(e){return this.#l.style.color=`CanvasText`,this.#l.style.backgroundColor=e,Me(getComputedStyle(this.#l).getPropertyValue(`background-color`))}#b(){this.#l.style.color=``,this.#l.style.backgroundColor=``}#x(e){let[t,n,r,i]=this.#y(e);if(i===1)return[t,n,r];let[a,o,s]=this.#v(`Canvas`);return[Qt(t,a,i),Qt(n,o,i),Qt(r,s,i)]}};function Qt(e,t,n){return Math.round(n*e+(1-n)*t)}t&&T("Please use the `legacy` build in Node.js environments.");async function $t(e){let t=await process.getBuiltinModule(`fs/promises`).readFile(e);return new Uint8Array(t)}var en=class extends Xt{},tn=class extends Jt{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire(import.meta.url)(`@napi-rs/canvas`).createCanvas(e,t)}},nn=class extends Kt{async _fetch(e,t){return $t(e)}};function rn({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=F.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=c^l,p=e.length;n=new Uint32Array(n.buffer);let m=0;for(let r=0;r>7&1)&f,n[m+1]=c^-(r>>6&1)&f,n[m+2]=c^-(r>>5&1)&f,n[m+3]=c^-(r>>4&1)&f,n[m+4]=c^-(r>>3&1)&f,n[m+5]=c^-(r>>2&1)&f,n[m+6]=c^-(r>>1&1)&f,n[m+7]=c^-(r&1)&f}if(d===0)continue;let r=t>7-e&1)&f}return{srcPos:t,destPos:m}}function an({src:e,srcPos:t=0,dest:n,destPos:r=0,width:i,height:a}){let o=0,s=i*a*3,c=s>>2,l=new Uint32Array(e.buffer,t,c),u=F.isLittleEndian?4278190080:255;if(F.isLittleEndian){for(;o>>24|t<<8|u,n[r+2]=t>>>16|i<<16|u,n[r+3]=i>>>8|u}for(let i=o*4,a=t+s;i>>8|u,n[r+2]=t<<16|i>>>16|u,n[r+3]=i<<8|u}for(let i=o*4,a=t+s;i - + diff --git a/pyproject.toml b/pyproject.toml index b9f7079a2..a444c9518 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -114,6 +114,7 @@ dev = [ [project.scripts] argus = "argus_skill.apps.tui_launcher:main" +argus-doctor = "argus_doctor:main" argus-skill = "argus_skill.__main__:main" argus-plugin-server = "argus_skill.plugin.mcp_server:main" @@ -126,6 +127,7 @@ packages = ["argus_skill"] # Package Markdown and JSON files are runtime Skill data. [tool.hatch.build.targets.wheel.force-include] +"argus_doctor.py" = "argus_doctor.py" "frontend/tui/bundle/argus.mjs" = "argus_skill/_frontend/tui/bundle/argus.mjs" "frontend/web/dist" = "argus_skill/_frontend/web/dist" diff --git a/tests/agent_cli/test_copilot_acp.py b/tests/agent_cli/test_copilot_acp.py index 32e895769..3d4be2ccb 100644 --- a/tests/agent_cli/test_copilot_acp.py +++ b/tests/agent_cli/test_copilot_acp.py @@ -686,7 +686,9 @@ def _later() -> None: ) + "\n" ) - time.sleep(0.035) + # Leave enough post-tool quiet time for two 20ms watchdog samples + # even on Windows' coarser thread scheduler. + time.sleep(0.08) proc._q.put( json.dumps( { @@ -735,7 +737,7 @@ def _later() -> None: assert result.turn_completed assert len(snapshots) >= 2 # once before and once after the real tool event - assert all(snapshot.idle_seconds < 0.05 for snapshot in snapshots) + assert all(snapshot.idle_seconds < 0.1 for snapshot in snapshots) count_at_completion = len(snapshots) time.sleep(0.04) assert len(snapshots) == count_at_completion # completion stops heartbeats diff --git a/tests/apps/test_cli_parser.py b/tests/apps/test_cli_parser.py index 0e60449c5..864dd0107 100644 --- a/tests/apps/test_cli_parser.py +++ b/tests/apps/test_cli_parser.py @@ -23,7 +23,8 @@ def test_public_help_distinguishes_human_and_automation_surfaces() -> None: assert "supervised foreground worker" in help_text assert "argus --daemon" in help_text assert "persistent unattended background worker" in help_text - assert "argus --doctor" in help_text + assert "argus doctor" in help_text + assert "argus repair --plan" in help_text assert "argus update" in help_text assert "--status" not in help_text assert "dashboard" not in help_text.lower() @@ -46,6 +47,47 @@ def test_debug_help_still_exposes_internal_flags(monkeypatch: pytest.MonkeyPatch assert "wiki" in help_text +def test_parser_exposes_doctor_and_repair_subcommands() -> None: + doctor = build_parser().parse_args(["doctor", "--json", "--deep"]) + assert doctor.command == "doctor" + assert doctor.json is True + assert doctor.deep is True + + repair = build_parser().parse_args(["repair", "--safe", "--json"]) + assert repair.command == "repair" + assert repair.safe is True + assert repair.json is True + + +def test_parser_accepts_doctor_safe_fix_and_repair_lifecycle() -> None: + doctor = build_parser().parse_args(["doctor", "--fix-safe", "--json"]) + legacy = build_parser().parse_args(["-doctor", "--fix-safe", "--json"]) + apply = build_parser().parse_args(["repair", "--apply", "rp-20260814T000000Z-abc12345", "--yes"]) + prepare = build_parser().parse_args(["repair", "--prepare-pr", "rp-20260814T000000Z-abc12345"]) + submit = build_parser().parse_args(["repair", "--submit-pr", "rp-20260814T000000Z-abc12345", "--yes"]) + + assert doctor.command == "doctor" and doctor.fix_safe is True + assert legacy.doctor is True and legacy.fix_safe is True and legacy.json is True + assert apply.apply == "rp-20260814T000000Z-abc12345" and apply.yes is True + assert prepare.prepare_pr == "rp-20260814T000000Z-abc12345" + assert submit.submit_pr == "rp-20260814T000000Z-abc12345" and submit.yes is True + + +def test_missing_repair_plan_fails_without_traceback( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], +) -> None: + rc = main([ + "--life-dir", str(tmp_path), + "repair", "--apply", "rp-20260814T000000Z-deadbeef", "--yes", + ]) + + captured = capsys.readouterr() + assert rc == 3 + assert "repair refused" in captured.err + assert "Traceback" not in captured.err + + def test_parser_exposes_update_subcommand(): args = build_parser().parse_args(["update"]) assert args.command == "update" @@ -119,6 +161,11 @@ def test_parser_exposes_cli_doctor() -> None: assert args.backend == "copilot" +def test_parser_accepts_hidden_single_dash_doctor_alias() -> None: + args = build_parser().parse_args(["-doctor"]) + assert args.doctor is True + + def test_parser_accepts_wiki_ingest_subcommand(tmp_path: Path): p = build_parser() wiki = tmp_path / ".autors" / "demo" / "wiki" diff --git a/tests/core/test_runtime_env.py b/tests/core/test_runtime_env.py index 4ddc6d653..d73242433 100644 --- a/tests/core/test_runtime_env.py +++ b/tests/core/test_runtime_env.py @@ -1,10 +1,14 @@ from __future__ import annotations import os +from pathlib import Path import pytest -from argus_skill.core.runtime_env import load_backend_runtime_env +from argus_skill.core.runtime_env import ( + configure_framework_python_env, + load_backend_runtime_env, +) def test_load_backend_runtime_env_is_allowlisted_and_non_overriding(tmp_path) -> None: @@ -41,3 +45,63 @@ def test_load_backend_runtime_env_rejects_writable_file(tmp_path) -> None: assert load_backend_runtime_env(env, root=tmp_path) == {} assert env == {} + + +def test_configure_framework_python_env_prepends_current_interpreter(tmp_path) -> None: + interpreter = tmp_path / "framework-venv" / ("Scripts" if os.name == "nt" else "bin") / "python" + system_bin = tmp_path / "system-bin" + env = {"PATH": str(system_bin)} + + configured = configure_framework_python_env(env, executable=interpreter) + + assert configured is env + assert env["ARGUS_SKILL_PYTHON"] == str(interpreter) + assert env["PATH"].split(os.pathsep) == [str(interpreter.parent), str(system_bin)] + if os.name == "nt": + assert env["PYTHONUTF8"] == "1" + assert env["PYTHONIOENCODING"] == "utf-8" + + +def test_configure_framework_python_env_preserves_explicit_runtime_and_deduplicates_path( + tmp_path, +) -> None: + explicit = tmp_path / "explicit-venv" / ("Scripts" if os.name == "nt" else "bin") / "python" + fallback = tmp_path / "fallback-venv" / ("Scripts" if os.name == "nt" else "bin") / "python" + runtime_bin = tmp_path / "runtime-bin" + system_bin = tmp_path / "system-bin" + env = { + "ARGUS_SKILL_PYTHON": str(explicit), + "ARGUS_SKILL_RUNTIME_BIN": str(runtime_bin), + "PATH": os.pathsep.join( + [str(system_bin), str(explicit.parent), str(runtime_bin), str(explicit.parent)] + ), + } + + configure_framework_python_env(env, executable=fallback) + + assert env["ARGUS_SKILL_PYTHON"] == str(explicit) + assert env["PATH"].split(os.pathsep) == [ + str(runtime_bin), + str(explicit.parent), + str(system_bin), + ] + + +def test_cli_entrypoint_normalizes_framework_python_before_argument_handling( + tmp_path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from argus_skill.apps.cli._core import main + + monkeypatch.delenv("ARGUS_SKILL_PYTHON", raising=False) + monkeypatch.delenv("ARGUS_SKILL_RUNTIME_BIN", raising=False) + monkeypatch.setenv("PATH", str(tmp_path / "unrelated-python")) + + with pytest.raises(SystemExit) as exit_info: + main(["--help"]) + + assert exit_info.value.code == 0 + framework_python = os.environ["ARGUS_SKILL_PYTHON"] + assert os.environ["PATH"].split(os.pathsep)[0] == str( + Path(framework_python).resolve().parent + ) diff --git a/tests/life/test_final_submission_cert_persists.py b/tests/life/test_final_submission_cert_persists.py index e9cf97258..8184c526d 100644 --- a/tests/life/test_final_submission_cert_persists.py +++ b/tests/life/test_final_submission_cert_persists.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import subprocess import time from pathlib import Path @@ -78,6 +79,7 @@ def test_legacy_cert_is_valid_only_while_project_is_unchanged(tmp_path: Path): source.parent.mkdir() source.write_text("legacy certified\n", encoding="utf-8") certified_at = time.time() + os.utime(source, (certified_at - 1, certified_at - 1)) events = tmp_path / "life" / "events.jsonl" events.write_text(json.dumps({ "type": "life.mission.completed", @@ -89,6 +91,7 @@ def test_legacy_cert_is_valid_only_while_project_is_unchanged(tmp_path: Path): assert sup._journal_has_final_certification() is True source.write_text("changed\n", encoding="utf-8") + os.utime(source, (certified_at + 1, certified_at + 1)) assert sup._journal_has_final_certification() is False diff --git a/tests/life/test_state_machine_guards.py b/tests/life/test_state_machine_guards.py index f2e61c6f6..8e06892ca 100644 --- a/tests/life/test_state_machine_guards.py +++ b/tests/life/test_state_machine_guards.py @@ -11,6 +11,7 @@ """ from __future__ import annotations +import os from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -126,7 +127,8 @@ def test_concurrent_claims_are_unique_and_finish_without_deadlock( with ThreadPoolExecutor(max_workers=8) as pool: futures = [pool.submit(mem.backlog.claim_next) for _ in range(40)] - claimed = [future.result(timeout=5) for future in futures] + timeout = 15 if os.name == "nt" else 5 + claimed = [future.result(timeout=timeout) for future in futures] ids = [item.id for item in claimed if item is not None] assert len(ids) == 32 diff --git a/tests/maintenance/test_repair_pipeline.py b/tests/maintenance/test_repair_pipeline.py new file mode 100644 index 000000000..6f4da06bb --- /dev/null +++ b/tests/maintenance/test_repair_pipeline.py @@ -0,0 +1,384 @@ +from __future__ import annotations + +import json +import os +import socket +from dataclasses import replace +from pathlib import Path + +import pytest + +from argus_skill.maintenance.doctor import DoctorContext, run_full_doctor +from argus_skill.maintenance.models import DoctorFinding, RepairAction +from argus_skill.maintenance.repair import ( + apply_plan, + create_plan, + prepare_pr_report, + read_path_memory, + submit_pr, + write_path_memory, +) + + +def _context(tmp_path: Path) -> DoctorContext: + checkout = tmp_path / "Argus" + checkout.mkdir() + (checkout / "pyproject.toml").write_text("[project]\nname='argus-skill'\n", encoding="utf-8") + (checkout / "argus_skill").mkdir() + return DoctorContext( + global_root=tmp_path / "state", + project_root=tmp_path / "state" / "projects" / "s-test", + checkout=checkout, + python_executable=Path(os.sys.executable), + web_host="127.0.0.1", + web_port=8799, + ) + + +def test_full_doctor_returns_typed_cross_platform_inventory(tmp_path: Path) -> None: + report = run_full_doctor(_context(tmp_path), include_backend=False) + + assert report.schema_version == 1 + assert report.target_fingerprint + assert {finding.scope for finding in report.findings} >= { + "host", "install", "cli", "web", "desktop", "daemon", + } + assert all(finding.code and finding.status for finding in report.findings) + + +def test_doctor_accepts_wheel_and_frozen_install_modes_without_checkout( + tmp_path: Path, +) -> None: + base = _context(tmp_path) + for mode in ("wheel", "frozen"): + context = replace(base, checkout=None, install_mode=mode) + report = run_full_doctor(context, include_backend=False) + finding = next(item for item in report.findings if item.code == "ARGUS-INSTALL-001") + assert finding.ok is True + assert finding.status == f"{mode}_install" + + +def test_doctor_distinguishes_an_occupied_non_http_port(tmp_path: Path) -> None: + context = _context(tmp_path) + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + listener.listen() + try: + report = run_full_doctor( + replace(context, web_port=listener.getsockname()[1]), + include_backend=False, + ) + finally: + listener.close() + + finding = next(item for item in report.findings if item.code == "ARGUS-WEB-001") + assert finding.status == "occupied_unresponsive" + assert finding.ok is False + + +def test_doctor_is_read_only(tmp_path: Path) -> None: + context = _context(tmp_path) + before = sorted(str(path.relative_to(tmp_path)) for path in tmp_path.rglob("*")) + + run_full_doctor(context, include_backend=False) + + after = sorted(str(path.relative_to(tmp_path)) for path in tmp_path.rglob("*")) + assert after == before + + +def test_doctor_classifies_missing_desktop_runtime_as_repairable(tmp_path: Path) -> None: + context = _context(tmp_path) + desktop = context.checkout / "desktop" + desktop.mkdir() + (desktop / "package.json").write_text("{}", encoding="utf-8") + + report = run_full_doctor(context, include_backend=False) + finding = next(item for item in report.findings if item.code == "ARGUS-DESKTOP-001") + + assert finding.status == "electron_binary_missing" + assert finding.repair_action_ids == ("install_electron_binary",) + + +def test_doctor_surfaces_unresolved_desktop_startup_error(tmp_path: Path) -> None: + base = _context(tmp_path) + user_data = tmp_path / "desktop-user-data" + log = user_data / "logs" / "desktop.log" + log.parent.mkdir(parents=True) + log.write_text( + "backend ready: Argus Desktop ready\nbackend failed to start: Electron uninstall\n", + encoding="utf-8", + ) + + report = run_full_doctor( + replace(base, desktop_user_data=user_data), include_backend=False + ) + finding = next(item for item in report.findings if item.code == "ARGUS-DESKTOP-LOG-001") + + assert finding.status == "recent_startup_error" + assert finding.ok is False + + +def test_doctor_reports_stalled_daemon_separately_from_stopped( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from types import SimpleNamespace + + context = _context(tmp_path) + context.project_root.mkdir(parents=True) + monkeypatch.setattr( + "argus_skill.daemon.state.read_daemon_status", + lambda _path: SimpleNamespace( + alive=True, + pid=123, + health_state="stalled", + stalled=True, + started_at_iso="2026-08-14T00:00:00+00:00", + seconds_since_progress=3600.0, + ), + ) + + report = run_full_doctor(context, include_backend=False) + finding = next(item for item in report.findings if item.code == "ARGUS-DAEMON-001") + + assert finding.status == "stalled" + assert finding.ok is False + + +def test_doctor_plans_identity_bound_repair_for_stuck_drain( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from types import SimpleNamespace + + context = _context(tmp_path) + context.project_root.mkdir(parents=True) + (context.project_root / "daemon.drain-request.json").write_text( + json.dumps({"pid": 123, "requested_at": 1.0}), encoding="utf-8" + ) + monkeypatch.setattr( + "argus_skill.daemon.state.read_daemon_status", + lambda _path: SimpleNamespace( + alive=True, + pid=123, + health_state="active", + stalled=False, + started_at_iso="2026-08-14T00:00:00+00:00", + seconds_since_progress=10.0, + ), + ) + + report = run_full_doctor(context, include_backend=False) + finding = next(item for item in report.findings if item.code == "ARGUS-DAEMON-001") + plan = create_plan(context, [finding]) + action = next(item for item in plan.actions if item.id == "stop_owned_stuck_daemon") + + assert finding.status == "drain_stuck" + assert action.risk == "consent" + assert action.precondition["pid"] == 123 + assert action.precondition["started_at_iso"] == "2026-08-14T00:00:00+00:00" + + +def test_plan_persists_registered_actions_and_never_shell_text(tmp_path: Path) -> None: + context = _context(tmp_path) + finding = DoctorFinding( + code="ARGUS-STATE-001", + scope="daemon", + severity="error", + ok=False, + status="stale_pid", + detail="stale pid; rm -rf should remain inert text", + recommendation="rm -rf /must-not-run", + repair_action_ids=("remove_verified_stale_daemon_pid",), + ) + + plan = create_plan(context, [finding]) + payload = json.loads(plan.path.read_text(encoding="utf-8")) + + assert payload["plan_id"] == plan.plan_id + assert payload["actions"][0]["id"] == "remove_verified_stale_daemon_pid" + assert "command" not in payload["actions"][0] + assert not (tmp_path / "must-not-run").exists() + + +def test_safe_apply_removes_only_verified_stale_pid_and_records_history( + tmp_path: Path, +) -> None: + context = _context(tmp_path) + context.project_root.mkdir(parents=True) + pid_path = context.project_root / "daemon.pid" + pid_path.write_text("2000000000\n", encoding="ascii") + finding = DoctorFinding( + code="ARGUS-STATE-001", + scope="daemon", + severity="error", + ok=False, + status="stale_pid", + detail="dead pid", + repair_action_ids=("remove_verified_stale_daemon_pid",), + ) + plan = create_plan(context, [finding]) + + result = apply_plan(context, plan.plan_id, safe_only=True) + + assert result.status == "completed" + assert not pid_path.exists() + assert result.actions[0]["status"] == "applied" + assert (context.global_root / "repairs" / "history.jsonl").exists() + memory = read_path_memory(context.global_root) + assert memory["checkout"] == str(context.checkout.resolve()) + assert memory["python_executable"] == str(context.python_executable.resolve()) + + +def test_apply_refuses_when_target_fingerprint_changed(tmp_path: Path) -> None: + context = _context(tmp_path) + finding = DoctorFinding( + code="ARGUS-PATH-001", + scope="install", + severity="warning", + ok=False, + status="path_memory_missing", + detail="missing", + repair_action_ids=("refresh_path_memory",), + ) + plan = create_plan(context, [finding]) + changed = DoctorContext(**{**context.__dict__, "web_port": 8800}) + + with pytest.raises(RuntimeError, match="target fingerprint changed"): + apply_plan(changed, plan.plan_id, safe_only=True) + + +def test_interrupted_plan_reconciles_without_repeating_applied_actions( + tmp_path: Path, +) -> None: + context = _context(tmp_path) + finding = DoctorFinding( + code="ARGUS-PATH-001", + scope="install", + severity="warning", + ok=False, + status="path_memory_missing", + detail="missing", + repair_action_ids=("refresh_path_memory",), + ) + plan = create_plan(context, [finding]) + write_path_memory(context) + payload = json.loads(plan.path.read_text(encoding="utf-8")) + payload["status"] = "running" + payload["outcomes"] = [{"id": "refresh_path_memory", "status": "applied"}] + plan.path.write_text(json.dumps(payload), encoding="utf-8") + + result = apply_plan(context, plan.plan_id, safe_only=True) + + assert result.status == "completed" + assert result.actions == ({"id": "refresh_path_memory", "status": "already_applied"},) + history = (context.global_root / "repairs" / "history.jsonl").read_text(encoding="utf-8") + assert "repair.plan.reconciled" in history + + +def test_apply_fails_when_registered_verification_does_not_clear( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + context = _context(tmp_path) + finding = DoctorFinding( + code="ARGUS-PATH-001", + scope="install", + severity="warning", + ok=False, + status="path_memory_missing", + detail="missing", + repair_action_ids=("refresh_path_memory",), + ) + plan = create_plan(context, [finding]) + monkeypatch.setattr( + "argus_skill.maintenance.repair.write_path_memory", + lambda _context: context.global_root / "repairs" / "path-memory.json", + ) + + result = apply_plan(context, plan.plan_id, safe_only=True) + + assert result.status == "failed" + payload = json.loads(plan.path.read_text(encoding="utf-8")) + assert payload["verification_failures"] == ["ARGUS-PATH-001"] + + +def test_completed_plan_is_idempotent(tmp_path: Path) -> None: + context = _context(tmp_path) + finding = DoctorFinding( + code="ARGUS-PATH-001", + scope="install", + severity="warning", + ok=False, + status="path_memory_missing", + detail="missing", + repair_action_ids=("refresh_path_memory",), + ) + plan = create_plan(context, [finding]) + + first = apply_plan(context, plan.plan_id, safe_only=True) + second = apply_plan(context, plan.plan_id, safe_only=True) + + assert first.status == "completed" + assert second.status == "already_applied" + + +def test_prepare_pr_report_is_sanitized_and_does_not_publish( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + context = _context(tmp_path) + secret = "ghp_NOT_A_REAL_TOKEN" + finding = DoctorFinding( + code="ARGUS-INSTALL-001", + scope="install", + severity="error", + ok=False, + status="broken_install", + detail=f"token={secret} under {Path.home()}", + repair_action_ids=("install_editable",), + ) + plan = create_plan(context, [finding]) + called = False + + def forbidden(*_args, **_kwargs): + nonlocal called + called = True + raise AssertionError("prepare-pr must not publish") + + monkeypatch.setattr("subprocess.run", forbidden) + report = prepare_pr_report(context, plan.plan_id) + text = report.read_text(encoding="utf-8") + + assert secret not in plan.path.read_text(encoding="utf-8") + assert secret not in text + assert str(Path.home()) not in text + assert "ARGUS-INSTALL-001" in text + assert called is False + + +def test_submit_pr_requires_explicit_authorization(tmp_path: Path) -> None: + context = _context(tmp_path) + finding = DoctorFinding( + code="ARGUS-ASSET-001", + scope="install", + severity="error", + ok=False, + status="assets_missing", + detail="missing", + repair_action_ids=("rebuild_release_assets",), + ) + plan = create_plan(context, [finding]) + + with pytest.raises(PermissionError, match="--yes"): + submit_pr(context, plan.plan_id, confirmed=False) + + +def test_repair_action_model_has_no_arbitrary_command_field() -> None: + action = RepairAction( + id="refresh_path_memory", + provider="core", + risk="safe", + target="paths", + ) + assert not hasattr(action, "command") diff --git a/tests/release_tools/test_build_release.py b/tests/release_tools/test_build_release.py index 3857d386d..a5a08487a 100644 --- a/tests/release_tools/test_build_release.py +++ b/tests/release_tools/test_build_release.py @@ -13,8 +13,13 @@ def test_release_uses_the_platform_npm_launcher() -> None: def test_release_subprocesses_use_current_python_bin(monkeypatch) -> None: captured = {} - monkeypatch.setattr(build_release.sys, "executable", "/opt/argus-venv/bin/python") - monkeypatch.setenv("PATH", "/usr/bin:/bin") + interpreter = ( + r"G:\workspace\测试\argus-venv\Scripts\python.exe" + if os.name == "nt" + else "/opt/argus-venv/bin/python" + ) + monkeypatch.setattr(build_release.sys, "executable", interpreter) + monkeypatch.setenv("PATH", os.pathsep.join(("/usr/bin", "/bin"))) def fake_run(argv, **kwargs): captured["argv"] = argv @@ -33,5 +38,10 @@ def fake_run(argv, **kwargs): assert captured["argv"] == ("npm", "run", "build") assert captured["check"] is True - assert "/opt/argus-venv/bin/python" in captured["python_target"] + if os.name == "nt": + assert captured["python_target"] == '@"%ARGUS_RELEASE_PYTHON%" %*\n' + assert captured["env"]["ARGUS_RELEASE_PYTHON"] == interpreter + captured["python_target"].encode("ascii") + else: + assert captured["python_target"] == interpreter assert captured["env"]["PYTHONPATH"].split(os.pathsep)[0] == str(build_release.ROOT) diff --git a/tests/skills/test_research_visualization_router.py b/tests/skills/test_research_visualization_router.py index b9e999932..9e53186b8 100644 --- a/tests/skills/test_research_visualization_router.py +++ b/tests/skills/test_research_visualization_router.py @@ -62,6 +62,6 @@ def test_agents_receive_visual_library_paths_without_matcher(tmp_path: Path) -> seed_vertical_skills(project_dir, "research", overwrite=True) store = LayeredSkillStore(project_dir=project_dir, global_dir=global_dir) - paths = store.list_paths() + paths = [path.replace("\\", "/") for path in store.list_paths()] assert any(path.endswith("engineer/research-visualization-router.md") for path in paths) assert any(path.endswith("engineer/presentation-master.md") for path in paths) diff --git a/tests/team/test_curator.py b/tests/team/test_curator.py index 64a88834a..46d6ec127 100644 --- a/tests/team/test_curator.py +++ b/tests/team/test_curator.py @@ -11,8 +11,17 @@ def _sleeping_proc(*_args, **_kwargs): import subprocess + import sys - return subprocess.Popen(["sleep", "60"], start_new_session=True) + return subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(60)"], + start_new_session=os.name != "nt", + creationflags=( + getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + if os.name == "nt" + else 0 + ), + ) # --- restart durability: adopt orphans the prior daemon left running -------- @@ -137,8 +146,9 @@ def test_spawn_tracked_records_real_child_and_roster_then_stop_reaps(tmp_path: P tt = next(iter(c._children.values())) assert tt.member_id == "w1" and tt.task_id == "t::a" assert tt.proc.poll() is None # alive - # own session (own process group) so per-child killpg can't hit the daemon - assert os.getpgid(pid) == pid + # POSIX uses an owned session; Windows uses CREATE_NEW_PROCESS_GROUP. + if os.name != "nt": + assert os.getpgid(pid) == pid # projected onto the roster (no heartbeat field) m = next(m for m in roster.members(root) if m["id"] == "w1") assert m["pid"] == pid and m["cwd"] == str(tmp_path) @@ -337,8 +347,11 @@ def test_reap_hard_timeout_killpg_and_fails_task(tmp_path: Path, monkeypatch) -> root = tmp_path / "team" task_board.form(root, [{"task_id": "t::a", "objective": "x"}]) killed: list = [] - monkeypatch.setattr(cur.os, "killpg", lambda pgid, sig: killed.append((pgid, sig))) - monkeypatch.setattr(cur.os, "getpgid", lambda pid: pid) + if os.name == "nt": + monkeypatch.setattr(cur, "_terminate_windows_tree", lambda pid: killed.append((pid, "force"))) + else: + monkeypatch.setattr(cur.os, "killpg", lambda pgid, sig: killed.append((pgid, sig))) + monkeypatch.setattr(cur.os, "getpgid", lambda pid: pid) c = cur.Curator(project_root=tmp_path, make_proc=lambda *a, **k: FakeProc(), teammate_timeout_s=10.0, hard_grace_s=5.0) c._refill(root, width=1, cwd=tmp_path, now=100.0) diff --git a/tests/team/test_task_board.py b/tests/team/test_task_board.py index e2561a62d..1254131b4 100644 --- a/tests/team/test_task_board.py +++ b/tests/team/test_task_board.py @@ -66,6 +66,14 @@ def test_task_ids_cannot_escape_task_storage(tmp_path: Path, task_id: str) -> No assert not any((tmp_path / "tasks").glob("*.json")) +def test_windows_unsafe_logical_id_round_trips_without_unsafe_filename(tmp_path: Path) -> None: + tb.form(tmp_path, [{"task_id": "team::task", "objective": "portable"}]) + + assert [task["task_id"] for task in tb.snapshot(tmp_path)] == ["team::task"] + if __import__("os").name == "nt": + assert all(":" not in path.name for path in (tmp_path / "tasks").iterdir()) + + def test_form_stores_priority(tmp_path: Path) -> None: tb.form(tmp_path, [ {"task_id": "a", "objective": "x", "owns_paths": ["a/**"]}, diff --git a/tests/test_aris_adapted_skills.py b/tests/test_aris_adapted_skills.py index 70b1670d1..dde1b921c 100644 --- a/tests/test_aris_adapted_skills.py +++ b/tests/test_aris_adapted_skills.py @@ -90,7 +90,7 @@ def test_figure_renderer_script_is_present_and_importable() -> None: proc = subprocess.run( [sys.executable, "-c", f"import importlib.util, sys; " - f"spec = importlib.util.spec_from_file_location('fr', '{renderer}'); " + f"spec = importlib.util.spec_from_file_location('fr', {str(renderer)!r}); " f"mod = importlib.util.module_from_spec(spec); " f"spec.loader.exec_module(mod); " f"print('OK')"], @@ -173,9 +173,10 @@ def test_seed_builtin_skills_copies_bundled_scripts(tmp_path: Path) -> None: "figure_renderer.py was NOT seeded into the workspace — the " "bundled-script copy path is broken" ) - # Sanity: the seeded copy is byte-identical to the in-tree source + # Sanity: the seeded copy has identical source content. Git may check out + # the source with CRLF on Windows while importlib.resources yields LF. in_tree = BUILTIN_ROOT / "engineer" / "figure_spec_scripts" / "figure_renderer.py" - assert renderer.read_bytes() == in_tree.read_bytes() + assert renderer.read_text(encoding="utf-8") == in_tree.read_text(encoding="utf-8") def test_plan_review_skill_has_rl_config_sanity_section() -> None: diff --git a/tests/test_bootstrap_doctor.py b/tests/test_bootstrap_doctor.py new file mode 100644 index 000000000..5e2ec7b36 --- /dev/null +++ b/tests/test_bootstrap_doctor.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +import argus_doctor + +ROOT = Path(__file__).resolve().parents[1] + + +def test_bootstrap_doctor_runs_without_importing_argus_core() -> None: + result = subprocess.run( + [sys.executable, "-I", str(ROOT / "argus_doctor.py"), "--root", str(ROOT), "--json"], + check=False, + capture_output=True, + text=True, + encoding="utf-8", + ) + + assert result.returncode == 0, result.stderr + report = json.loads(result.stdout) + assert report["schema_version"] == 1 + assert report["mode"] == "bootstrap" + assert report["ok"] is True + assert {item["code"] for item in report["findings"]} >= { + "ARGUS-HOST-001", + "ARGUS-INSTALL-001", + "ARGUS-PYTHON-003", + "ARGUS-WEB-001", + } + + +def test_bootstrap_accepts_current_editable_python_without_checkout_venv( + tmp_path: Path, +) -> None: + root = tmp_path / "Argus" + (root / "argus_skill").mkdir(parents=True) + (root / "pyproject.toml").write_text("[project]\nname='argus-skill'\n", encoding="utf-8") + + report = argus_doctor.run_bootstrap_doctor(root) + python = next( + item for item in report["findings"] if item["code"] == "ARGUS-PYTHON-002" + ) + core = next( + item for item in report["findings"] if item["code"] == "ARGUS-PYTHON-003" + ) + + assert python["ok"] is True + assert "without checkout .venv" in python["detail"] + assert core["ok"] is True + + +def test_bootstrap_repair_requires_explicit_yes(capsys) -> None: + rc = argus_doctor.main(["--repair-install"]) + + assert rc == 3 + assert "requires --yes" in capsys.readouterr().err + + +def test_bootstrap_install_uses_only_registered_venv_command( + tmp_path: Path, + monkeypatch, +) -> None: + root = tmp_path / "Argus" + (root / "argus_skill").mkdir(parents=True) + (root / "pyproject.toml").write_text("[project]\nname='argus-skill'\n", encoding="utf-8") + runtime = root / (".venv/Scripts/python.exe" if sys.platform == "win32" else ".venv/bin/python") + runtime.parent.mkdir(parents=True) + runtime.write_text("", encoding="utf-8") + calls = [] + monkeypatch.setattr( + argus_doctor, + "_run_repair_command", + lambda command, **kwargs: calls.append((command, kwargs)) or {"status": "applied"}, + ) + + actions = argus_doctor.run_bootstrap_repair(root, install=True) + + assert actions[0]["id"] == "install_editable" + assert calls == [ + ([runtime, "-m", "pip", "install", "-e", str(root.resolve())], { + "cwd": root.resolve(), + "timeout": 600, + }) + ] + + +def test_bootstrap_doctor_reports_missing_checkout_without_crashing(tmp_path: Path) -> None: + report = argus_doctor.run_bootstrap_doctor(tmp_path / "missing") + + assert report["ok"] is False + install = next(item for item in report["findings"] if item["code"] == "ARGUS-INSTALL-001") + assert install["ok"] is False + assert "--root" in install["fix"] diff --git a/tests/test_copilot_home_isolation.py b/tests/test_copilot_home_isolation.py index ffd08b785..9468d9a19 100644 --- a/tests/test_copilot_home_isolation.py +++ b/tests/test_copilot_home_isolation.py @@ -111,7 +111,8 @@ def test_auth_fields_refresh_without_overwriting_argus_state(tmp_path: Path) -> assert config["loggedInUsers"] == [{"login": "operator"}] assert config["lastLoggedInUser"] == {"login": "operator"} assert "trustedFolders" not in config - assert (home / "config.json").stat().st_mode & 0o777 == 0o600 + if os.name != "nt": + assert (home / "config.json").stat().st_mode & 0o777 == 0o600 def test_operator_logout_removes_stale_isolated_auth(tmp_path: Path) -> None: diff --git a/tests/test_doctor.py b/tests/test_doctor.py index 3e5ede612..997bbf9f7 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -8,9 +8,13 @@ """ from __future__ import annotations +import json import os import shutil import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace from argus_skill.webapi.diagnostics import Check, render_report, run_diagnostics @@ -61,6 +65,48 @@ def test_render_report_all_green_has_no_recommendation(): assert "→ recommended:" not in report +def test_doctor_json_uses_stable_codes() -> None: + from argus_skill.apps.cli._core import _doctor_payload + + payload = _doctor_payload([Check("lock sanity", False, "stale", "repair")]) + + assert payload["schema_version"] == 1 + assert payload["ok"] is False + assert payload["checks"][0]["code"] == "ARGUS-STATE-001" + + +def test_safe_repair_removes_only_a_verified_stale_daemon_pid( + tmp_path, + monkeypatch, + capsys, +) -> None: + from argus_skill.apps.cli import _core + from argus_skill.maintenance.doctor import DoctorContext + + pid_path = tmp_path / "daemon.pid" + pid_path.write_text("2000000000\n", encoding="ascii") + context = DoctorContext( + global_root=tmp_path / "state", + project_root=tmp_path, + checkout=Path(__file__).resolve().parents[1], + python_executable=Path(sys.executable), + ) + monkeypatch.setattr(_core, "_maintenance_context", lambda _args: context) + + rc = _core._cmd_repair( + SimpleNamespace(safe=True, plan=False, json=True) + ) + payload = json.loads(capsys.readouterr().out) + + assert rc in {0, 3} # consent/manual findings may remain after SAFE actions + assert not pid_path.exists() + stale = next( + item for item in payload["actions"] + if item["id"] == "remove_verified_stale_daemon_pid" + ) + assert stale["status"] == "applied" + + def test_render_report_with_theme_is_failsoft(): # A theme-shaped object whose methods raise must not break rendering. class BrokenTheme: diff --git a/tests/test_grok_backend.py b/tests/test_grok_backend.py index 1fd8c5c79..06993aca2 100644 --- a/tests/test_grok_backend.py +++ b/tests/test_grok_backend.py @@ -1,5 +1,7 @@ from __future__ import annotations +import os +import sys from pathlib import Path import pytest @@ -74,7 +76,8 @@ def test_grok_prompt_uses_private_temporary_file() -> None: assert prepared[-2:] == ["--prompt-file", str(cleanup_path)] assert prompt not in prepared assert cleanup_path.read_text(encoding="utf-8") == prompt - assert cleanup_path.stat().st_mode & 0o077 == 0 + if os.name != "nt": + assert cleanup_path.stat().st_mode & 0o077 == 0 finally: if cleanup_path is not None: cleanup_path.unlink(missing_ok=True) @@ -201,11 +204,13 @@ def test_grok_result_usage_is_accounted() -> None: assert usage.provider_cost_usd == pytest.approx(0.03) -def test_grok_run_exec_removes_prompt_file(tmp_path: Path) -> None: - executable = tmp_path / "grok" - executable.write_text( - """#!/usr/bin/env python3 -import json +def test_grok_run_exec_removes_prompt_file( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + script = tmp_path / "grok.py" + script.write_text( + """import json import pathlib import sys @@ -221,7 +226,20 @@ def test_grok_run_exec_removes_prompt_file(tmp_path: Path) -> None: """, encoding="utf-8", ) - executable.chmod(0o755) + if os.name == "nt": + executable = tmp_path / "grok.cmd" + monkeypatch.setenv("ARGUS_TEST_PYTHON", sys.executable) + executable.write_text( + '@"%ARGUS_TEST_PYTHON%" "%~dp0grok.py" %*\n', + encoding="ascii", + ) + else: + executable = tmp_path / "grok" + executable.write_text( + f"#!/bin/sh\nexec {sys.executable!r} {str(script)!r} \"$@\"\n", + encoding="utf-8", + ) + executable.chmod(0o755) result = _runner(str(executable)).run_exec( prompt="hello from Argus", diff --git a/tests/test_harbor_integration.py b/tests/test_harbor_integration.py index 0430fcb19..2dc6611fa 100644 --- a/tests/test_harbor_integration.py +++ b/tests/test_harbor_integration.py @@ -4,6 +4,7 @@ import importlib.util import json import logging +import os import subprocess import sys import types @@ -24,6 +25,17 @@ ) +def _assert_bash_syntax(command: str) -> None: + # Harbor executes inside a Linux container. On native Windows, `bash` may + # be a WSL relay without an installed distribution, so syntax validation is + # covered by Linux CI rather than producing a host-environment false alarm. + if os.name == "nt": + return + assert subprocess.run( + ["bash", "-n"], input=command, text=True, check=False, + ).returncode == 0 + + def test_latest_project_root_selects_latest_completed_state(tmp_path: Path) -> None: older = tmp_path / "projects" / "older" newer = tmp_path / "projects" / "newer" @@ -249,40 +261,16 @@ def test_harbor_directly_installs_and_invokes_argus( for command in commands if "pip install" in command and "packages.test/argus.whl" in command ) - assert ( - subprocess.run( - ["bash", "-n"], - input=install_command, - text=True, - check=False, - ).returncode - == 0 - ) + _assert_bash_syntax(install_command) auth_command = next(command for command in commands if "OPENAI_API_KEY" in command) assert "sk-test-sensitive-value" not in auth_command - assert ( - subprocess.run( - ["bash", "-n"], - input=auth_command, - text=True, - check=False, - ).returncode - == 0 - ) + _assert_bash_syntax(auth_command) runtime = next(command for command in commands if "--daemon-fg" in command) assert "--continuous --bounded --new" in runtime assert "--objective-file /logs/agent/argus-objective.txt" in runtime assert "--life-dir /logs/agent/argus-state" in runtime assert "Fix the task" not in runtime - assert ( - subprocess.run( - ["bash", "-n"], - input=runtime, - text=True, - check=False, - ).returncode - == 0 - ) + _assert_bash_syntax(runtime) runtime_call = next(entry for entry in environment.commands if entry["command"] == runtime) assert runtime_call["timeout_sec"] == 900 assert runtime_call["env"]["ARGUS_SKILL_RUNNER_BACKEND"] == "codex" diff --git a/tests/test_pi_backend.py b/tests/test_pi_backend.py index 439051610..d2b872b54 100644 --- a/tests/test_pi_backend.py +++ b/tests/test_pi_backend.py @@ -30,7 +30,7 @@ def test_pi_command_uses_json_stdin_and_exact_session( ), ) - assert Path(command[0]).name == "pi" + assert Path(command[0]).stem.casefold() == "pi" assert command[1:] == [ "--mode", "json", diff --git a/tests/test_runner_binary_resolution.py b/tests/test_runner_binary_resolution.py index c81a26bd7..a59786cec 100644 --- a/tests/test_runner_binary_resolution.py +++ b/tests/test_runner_binary_resolution.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os from pathlib import Path from argus_skill.agent_cli.agent_cli_runner import AgentCliRunner @@ -15,49 +16,58 @@ ) +def _same_path(actual: str | None, expected: Path) -> bool: + return bool(actual) and os.path.normcase(str(Path(actual).resolve())) == os.path.normcase( + str(expected.resolve()) + ) + + +def _fake_executable(path: Path, *, exit_code: int = 0) -> Path: + if os.name == "nt": + path = path.with_suffix(".cmd") + path.write_text(f"@exit /b {exit_code}\n", encoding="ascii") + else: + path.write_text(f"#!/bin/sh\nexit {exit_code}\n", encoding="utf-8") + path.chmod(0o755) + return path + + def test_runner_resolves_user_local_bin_when_service_path_omits_it( tmp_path: Path, monkeypatch, ) -> None: executable = tmp_path / ".local" / "bin" / "copilot" executable.parent.mkdir(parents=True) - executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - executable.chmod(0o755) - monkeypatch.setenv("HOME", str(tmp_path)) + executable = _fake_executable(executable) + monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path)) monkeypatch.setenv("PATH", str(tmp_path / "service-bin")) - assert resolve_runner_bin(BACKEND_COPILOT) == str(executable) - assert AgentCliRunner(backend=BACKEND_COPILOT).agent_bin == str(executable) + assert _same_path(resolve_runner_bin(BACKEND_COPILOT), executable) + assert _same_path(AgentCliRunner(backend=BACKEND_COPILOT).agent_bin, executable) def test_opencode_runner_uses_opencode_binary(tmp_path: Path, monkeypatch) -> None: - executable = tmp_path / "opencode" - executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - executable.chmod(0o755) + executable = _fake_executable(tmp_path / "opencode") monkeypatch.setenv("PATH", str(tmp_path)) - assert resolve_runner_bin(BACKEND_OPENCODE) == str(executable) - assert AgentCliRunner(backend=BACKEND_OPENCODE).agent_bin == str(executable) + assert _same_path(resolve_runner_bin(BACKEND_OPENCODE), executable) + assert _same_path(AgentCliRunner(backend=BACKEND_OPENCODE).agent_bin, executable) def test_pi_runner_uses_pi_binary(tmp_path: Path, monkeypatch) -> None: - executable = tmp_path / "pi" - executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - executable.chmod(0o755) + executable = _fake_executable(tmp_path / "pi") monkeypatch.setenv("PATH", str(tmp_path)) - assert resolve_runner_bin(BACKEND_PI) == str(executable) - assert AgentCliRunner(backend=BACKEND_PI).agent_bin == str(executable) + assert _same_path(resolve_runner_bin(BACKEND_PI), executable) + assert _same_path(AgentCliRunner(backend=BACKEND_PI).agent_bin, executable) def test_grok_runner_uses_grok_binary(tmp_path: Path, monkeypatch) -> None: - executable = tmp_path / "grok" - executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - executable.chmod(0o755) + executable = _fake_executable(tmp_path / "grok") monkeypatch.setenv("PATH", str(tmp_path)) - assert resolve_runner_bin(BACKEND_GROK) == str(executable) - assert AgentCliRunner(backend=BACKEND_GROK).agent_bin == str(executable) + assert _same_path(resolve_runner_bin(BACKEND_GROK), executable) + assert _same_path(AgentCliRunner(backend=BACKEND_GROK).agent_bin, executable) def test_qoder_runner_uses_qodercli_binary(tmp_path: Path, monkeypatch) -> None: @@ -76,13 +86,12 @@ def test_opencode_runner_resolves_standard_install_directory( ) -> None: executable = tmp_path / ".opencode" / "bin" / "opencode" executable.parent.mkdir(parents=True) - executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - executable.chmod(0o755) - monkeypatch.setenv("HOME", str(tmp_path)) + executable = _fake_executable(executable) + monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path)) monkeypatch.setenv("PATH", str(tmp_path / "service-bin")) - assert resolve_runner_bin(BACKEND_OPENCODE) == str(executable) - assert AgentCliRunner(backend=BACKEND_OPENCODE).agent_bin == str(executable) + assert _same_path(resolve_runner_bin(BACKEND_OPENCODE), executable) + assert _same_path(AgentCliRunner(backend=BACKEND_OPENCODE).agent_bin, executable) def test_missing_codex_falls_back_to_available_copilot( @@ -91,15 +100,13 @@ def test_missing_codex_falls_back_to_available_copilot( ) -> None: copilot = tmp_path / "bin" / "copilot" copilot.parent.mkdir() - copilot.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - copilot.chmod(0o755) + copilot = _fake_executable(copilot) monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("PATH", str(copilot.parent)) - assert resolve_available_runner(BACKEND_CODEX) == ( - BACKEND_COPILOT, - str(copilot), - ) + backend, resolved = resolve_available_runner(BACKEND_CODEX) + assert backend == BACKEND_COPILOT + assert _same_path(resolved, copilot) def test_existing_codex_never_falls_back_on_runtime_failure( @@ -108,28 +115,21 @@ def test_existing_codex_never_falls_back_on_runtime_failure( ) -> None: bindir = tmp_path / "bin" bindir.mkdir() - codex = bindir / "codex" - codex.write_text("#!/bin/sh\nexit 1\n", encoding="utf-8") - codex.chmod(0o755) - copilot = bindir / "copilot" - copilot.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - copilot.chmod(0o755) + codex = _fake_executable(bindir / "codex", exit_code=1) + _fake_executable(bindir / "copilot") monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("PATH", str(bindir)) - assert resolve_available_runner(BACKEND_CODEX) == ( - BACKEND_CODEX, - str(codex), - ) + backend, resolved = resolve_available_runner(BACKEND_CODEX) + assert backend == BACKEND_CODEX + assert _same_path(resolved, codex) def test_unknown_backend_typo_does_not_fall_back( tmp_path: Path, monkeypatch, ) -> None: - copilot = tmp_path / "copilot" - copilot.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") - copilot.chmod(0o755) + _fake_executable(tmp_path / "copilot") monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("PATH", str(tmp_path)) diff --git a/tests/tools/test_capability_vault.py b/tests/tools/test_capability_vault.py index 653852f4d..eee4955c5 100644 --- a/tests/tools/test_capability_vault.py +++ b/tests/tools/test_capability_vault.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import stat from pathlib import Path @@ -108,7 +109,8 @@ def test_save_and_load_model_api_grant_uses_private_vault(tmp_path: Path) -> Non assert loaded.api_key == "dummy-key" assert loaded.base_url == "https://example.invalid/openai/v1/" assert loaded.image_model == "gpt-image-2" - assert stat.S_IMODE(saved.stat().st_mode) == 0o600 + if os.name != "nt": + assert stat.S_IMODE(saved.stat().st_mode) == 0o600 def test_load_model_api_grant_honors_codex_model_provider(tmp_path: Path) -> None: diff --git a/tests/tools/test_gpu_keepalive_setup.py b/tests/tools/test_gpu_keepalive_setup.py index 9100c0bbe..9bb327787 100644 --- a/tests/tools/test_gpu_keepalive_setup.py +++ b/tests/tools/test_gpu_keepalive_setup.py @@ -1,6 +1,7 @@ """Tests for the setup wizard's GPU keep-alive (anti-reclaim) integration.""" from __future__ import annotations +import os from pathlib import Path import pytest @@ -45,7 +46,8 @@ def test_save_keepalive_is_readable_by_gpu_lease(tmp_path: Path, monkeypatch) -> ) path = _wizard._save_gpu_keepalive(cfg) assert path.exists() - assert (path.stat().st_mode & 0o777) == 0o600 + if os.name != "nt": + assert (path.stat().st_mode & 0o777) == 0o600 loaded = gpu_lease.load_config() assert loaded["match"] == _wizard._KEEPALIVE_TOKEN assert loaded["command"][1].endswith("gpu_load.py") @@ -60,9 +62,9 @@ def test_special_prompt_passes_trust_check(tmp_path: Path, monkeypatch) -> None: body = _wizard._render_gpu_keepalive_prompt("0,1") path = _wizard._write_special_prompt("20-gpu-keepalive.md", body) assert path.exists() - assert (path.stat().st_mode & 0o777) == 0o644 - # not group/world-writable -> accepted by the trust check - assert (path.stat().st_mode & 0o022) == 0 + if os.name != "nt": + assert (path.stat().st_mode & 0o777) == 0o644 + assert (path.stat().st_mode & 0o022) == 0 loaded = dict(special_prompts.load_special_prompts()) assert "20-gpu-keepalive" in loaded @@ -76,7 +78,8 @@ def test_setup_creates_trusted_default_house_rules(tmp_path: Path, monkeypatch) assert path == sp_dir / "10-house-rules.md" assert path is not None - assert (path.stat().st_mode & 0o777) == 0o644 + if os.name != "nt": + assert (path.stat().st_mode & 0o777) == 0o644 assert "unrelated jobs" in path.read_text(encoding="utf-8") assert special_prompts.describe_special_prompt_gate() == (True, "") @@ -107,10 +110,13 @@ def test_setup_does_not_overwrite_untrusted_house_rules( generated = _wizard._ensure_default_house_rules_prompt() - assert generated is not None - assert generated == sp_dir / "10-house-rules-setup-1.md" + if os.name == "nt": + assert generated is None + else: + assert generated == sp_dir / "10-house-rules-setup-1.md" + assert generated is not None + assert (generated.stat().st_mode & 0o022) == 0 assert existing.read_text(encoding="utf-8") == "Operator draft; do not overwrite.\n" - assert (generated.stat().st_mode & 0o022) == 0 from argus_skill.life import special_prompts assert special_prompts.describe_special_prompt_gate() == (True, "") @@ -132,7 +138,8 @@ def test_save_and_load_author_roundtrip(tmp_path: Path, monkeypatch) -> None: monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path)) path = _wizard._save_author("Example User", "author@example.invalid") assert path.exists() - assert (path.stat().st_mode & 0o777) == 0o600 + if os.name != "nt": + assert (path.stat().st_mode & 0o777) == 0o600 loaded = _wizard._load_existing_author() assert loaded == {"name": "Example User", "email": "author@example.invalid"} @@ -293,7 +300,8 @@ def test_configure_experiment_api_writes_prompt(tmp_path: Path, monkeypatch) -> assert ok is True path = sp_dir / "30-experiment-api.md" assert path.exists() - assert (path.stat().st_mode & 0o022) == 0 # not group/world-writable + if os.name != "nt": + assert (path.stat().st_mode & 0o022) == 0 assert "30-experiment-api" in dict(special_prompts.load_special_prompts()) diff --git a/tests/tools/test_lean_check.py b/tests/tools/test_lean_check.py index 13b08cfe0..d3bc157e0 100644 --- a/tests/tools/test_lean_check.py +++ b/tests/tools/test_lean_check.py @@ -51,9 +51,10 @@ def _fake_lean(tmp_path: Path, behavior: str) -> Path: script = path.with_suffix(".py") script.write_text(body, encoding="utf-8") launcher = path.with_suffix(".cmd") + os.environ["ARGUS_TEST_PYTHON"] = sys.executable launcher.write_text( - f'@echo off\r\n"{sys.executable}" "{script}" %*\r\n', - encoding="utf-8", + '@echo off\n"%ARGUS_TEST_PYTHON%" "%~dp0' + script.name + '" %*\n', + encoding="ascii", ) return launcher path.write_text("#!/usr/bin/env python3\n" + body, encoding="utf-8") @@ -82,9 +83,10 @@ def _fake_lake_with_versions(tmp_path: Path) -> Path: script = path.with_suffix(".py") script.write_text(body, encoding="utf-8") launcher = path.with_suffix(".cmd") + os.environ["ARGUS_TEST_PYTHON"] = sys.executable launcher.write_text( - f'@echo off\r\n"{sys.executable}" "{script}" %*\r\n', - encoding="utf-8", + '@echo off\n"%ARGUS_TEST_PYTHON%" "%~dp0' + script.name + '" %*\n', + encoding="ascii", ) return launcher path.write_text("#!/usr/bin/env python3\n" + body, encoding="utf-8") diff --git a/tests/tools/test_setup_codex_config.py b/tests/tools/test_setup_codex_config.py index 5193679a6..dde7fbd22 100644 --- a/tests/tools/test_setup_codex_config.py +++ b/tests/tools/test_setup_codex_config.py @@ -2,6 +2,7 @@ from __future__ import annotations import json +import os from pathlib import Path from argus_skill.tools import setup as _wizard @@ -46,9 +47,10 @@ def test_seed_codex_config_writes_files(tmp_path: Path, monkeypatch) -> None: assert "gpt-engineer" in cfg.read_text() auth_data = json.loads(auth.read_text()) assert auth_data["OPENAI_API_KEY"] == "sk-test-1234" - # auth.json should be 0600 - mode = auth.stat().st_mode & 0o777 - assert mode == 0o600, f"auth.json mode should be 0600, got {oct(mode)}" + # POSIX exposes mode bits; Windows protects the file through its user ACL. + if os.name != "nt": + mode = auth.stat().st_mode & 0o777 + assert mode == 0o600, f"auth.json mode should be 0600, got {oct(mode)}" def test_seed_codex_config_requires_inputs(tmp_path: Path, monkeypatch) -> None: diff --git a/tests/tools/test_subagent_supervisor.py b/tests/tools/test_subagent_supervisor.py index b35f3a5c0..a9d4b24f5 100644 --- a/tests/tools/test_subagent_supervisor.py +++ b/tests/tools/test_subagent_supervisor.py @@ -2,6 +2,7 @@ import argparse import json +import os import subprocess import time import types @@ -40,6 +41,11 @@ cmd_reply, ) +requires_fork = pytest.mark.skipif( + not hasattr(os, "fork"), + reason="subagent daemonization uses POSIX fork", +) + _ORIGINAL_RUN_BACKEND_TURN = _sub._llm._run_backend_turn @@ -1002,6 +1008,7 @@ def _submit_args(**kw) -> argparse.Namespace: return argparse.Namespace(**base) +@requires_fork def test_cmd_submit_blocks_on_open_discussion(monkeypatch, tmp_path, capsys) -> None: monkeypatch.chdir(tmp_path) me = __import__("os").getpid() @@ -1017,6 +1024,7 @@ def test_cmd_submit_blocks_on_open_discussion(monkeypatch, tmp_path, capsys) -> assert "truncation" in out["supervisor_concern"] +@requires_fork def test_cmd_submit_rejects_same_id_while_discussion_worker_lives( monkeypatch, tmp_path, @@ -1052,6 +1060,7 @@ def test_cmd_submit_rejects_same_id_while_discussion_worker_lives( assert "already discussing" in out["error"] +@requires_fork def test_cmd_submit_rejects_terminal_record_while_report_worker_lives( monkeypatch, tmp_path, @@ -1082,6 +1091,7 @@ def test_cmd_submit_rejects_terminal_record_while_report_worker_lives( assert "already done" in out["error"] +@requires_fork def test_cmd_submit_override_records_and_proceeds(monkeypatch, tmp_path, capsys) -> None: monkeypatch.chdir(tmp_path) me = __import__("os").getpid() @@ -1096,6 +1106,7 @@ def test_cmd_submit_override_records_and_proceeds(monkeypatch, tmp_path, capsys) assert "I checked, proceed" in ledger +@requires_fork def test_cmd_submit_refuses_poisoned_stop(monkeypatch, tmp_path, capsys) -> None: monkeypatch.chdir(tmp_path) rd = tmp_path / "runs" / "r1" @@ -1112,6 +1123,7 @@ def test_cmd_submit_refuses_poisoned_stop(monkeypatch, tmp_path, capsys) -> None assert not (rd / "STOP").exists() +@requires_fork def test_cmd_submit_rejects_insufficient_cpus_before_artifacts( monkeypatch, tmp_path, capsys ) -> None: @@ -1138,6 +1150,7 @@ def test_cmd_submit_rejects_insufficient_cpus_before_artifacts( assert not run_dir.exists() +@requires_fork def test_cmd_submit_rejects_cpu_conflict_before_new_task_record( monkeypatch, tmp_path, capsys ) -> None: @@ -1169,6 +1182,7 @@ def test_cmd_submit_rejects_cpu_conflict_before_new_task_record( assert not _sub._registry_path("new").exists() +@requires_fork def test_cmd_submit_reserves_disjoint_cpus_before_fork( monkeypatch, tmp_path, capsys ) -> None: @@ -1199,6 +1213,7 @@ def test_cmd_submit_reserves_disjoint_cpus_before_fork( assert record["cpu_count"] == 2 +@requires_fork def test_cmd_submit_normalizes_relative_cwd_and_run_dir( monkeypatch, tmp_path, diff --git a/tests/webapi/test_server_m0.py b/tests/webapi/test_server_m0.py index 5c2a6f3a0..5dfcdf15f 100644 --- a/tests/webapi/test_server_m0.py +++ b/tests/webapi/test_server_m0.py @@ -942,6 +942,27 @@ def test_get_meta_is_public_versioned_and_uncached( ) +def test_system_doctor_requires_auth_and_returns_typed_read_only_report( + tmp_path: Path, +) -> None: + app = server.create_app(global_root=tmp_path, auth_token="secret") + with TestClient(app) as doctor_client: + rejected = doctor_client.get("/api/system/doctor") + response = doctor_client.get( + "/api/system/doctor", + headers={"Authorization": "Bearer secret"}, + ) + + assert rejected.status_code == 401 + assert response.status_code == 200 + payload = response.json() + assert payload["schema_version"] == 1 + assert payload["target_fingerprint"] + assert {item["scope"] for item in payload["findings"]} >= { + "host", "install", "cli", "web", "desktop", "daemon", + } + + def test_metrics_endpoints_expose_json_slo_and_prometheus(client: TestClient) -> None: payload = client.get("/api/metrics") assert payload.status_code == 200